Skip to content

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

Rust

isolate prime agent production config from cli profile switches (#2251)

ktdf6c709a06d8
diff --git a/packages/coding-agent/.changes/eng-6058-production-config.md b/packages/coding-agent/.changes/eng-6058-production-config.md
new file mode 100644
index 0000000000..926bc58985
--- /dev/null
+++ b/packages/coding-agent/.changes/eng-6058-production-config.md
@@ -0,0 +1,2 @@
+- Fixed Prime Agent production credentials and team selection to stay independent of Prime CLI configuration, with validated CLI credential reuse only during explicit login.
+- Fixed explicit Prime CLI credential import for the default SDK services factory.
diff --git a/packages/coding-agent/README.md b/packages/coding-agent/README.md
index bfb3ce55bf..a0f8f7e4e7 100644
--- a/packages/coding-agent/README.md
+++ b/packages/coding-agent/README.md
@@ -113,6 +113,8 @@ Select the xAI subscription entry in `/login` to sign in. Model access depends o
- Xiaomi MiMo Token Plan (Amsterdam)
- Xiaomi MiMo Token Plan (Singapore)
+Prime Inference credentials and teams belong to Agent's `~/.prime/agent/auth.json`. Normal use ignores Prime CLI's `~/.prime/config.json`. If you previously relied on CLI credentials, run `/login` once: Agent can import a production-compatible CLI key after production validation, without changing CLI config. `PRIME_API_KEY` still overrides the saved Agent key.
+
See [docs/providers.md](docs/providers.md) for detailed setup instructions.
**Custom providers & models:** Add providers via `~/.prime/agent/models.json` if they speak a supported API (OpenAI, Anthropic, Google). For custom APIs or OAuth, use extensions. See [docs/models.md](docs/models.md) and [docs/custom-provider.md](docs/custom-provider.md).
@@ -172,6 +174,8 @@ Type `/` in the editor to trigger commands. [Extensions](#extensions) can regist
| `/changelog` | Display version history |
| `/quit` | Quit Prime Agent |
+Trace uploads use environment or Agent-owned credentials, not live Prime CLI credentials. `/traces login` can reuse a CLI key only after production URL and scope validation. See [trace sharing credentials](docs/providers.md#trace-sharing-credentials).
+
### Keyboard Shortcuts
See `/hotkeys` for the full list. Customize via `~/.prime/agent/keybindings.json`. See [docs/keybindings.md](docs/keybindings.md).
@@ -683,6 +687,9 @@ prime-agent --thinking high "Solve this complex problem"
| `PRIME_AGENT_DOWNLOAD_BASE_URL` | Override the Prime Agent release manifest and tarball base URL |
| `PI_CACHE_RETENTION` | Set to `long` for extended prompt cache (Anthropic: 1h, OpenAI: 24h) |
| `PRIME_API_KEY` | Prime Inference API key; also used for trace sharing if it has `agent_traces` scope |
+| `PRIME_TEAM_ID` | Override the Prime Inference team request header without changing the saved Agent team |
+| `PRIME_AGENT_INFERENCE_API_BASE_URL` | Override Agent authentication and team API URLs, not model inference URLs; defaults to production |
+| `PRIME_AGENT_INFERENCE_FRONTEND_URL` | Override the Agent login browser frontend; defaults to production |
| `PRIME_AGENT_TRACES_API_KEY` | Prime API key used only for opt-in trace sharing |
| `PRIME_AGENT_TRACES_BASE_URL` | Override the Prime Agent trace upload API base URL |
| `PRIME_AGENT_KERNEL_PYTHON` | Use an existing Python environment with `prime-agent-runtime` instead of auto-bootstrapping `~/.prime/agent/kernel-venv` |
diff --git a/packages/coding-agent/docs/providers.md b/packages/coding-agent/docs/providers.md
index c5d704d8d0..9de7b26704 100644
--- a/packages/coding-agent/docs/providers.md
+++ b/packages/coding-agent/docs/providers.md
@@ -110,7 +110,7 @@ Store credentials in `~/.prime/agent/auth.json`:
}
```
-The file is created with `0600` permissions (user read/write only). Auth file credentials take priority over environment variables.
+The file is created with `0600` permissions (user read/write only). Auth file credentials take priority over environment variables, except for Prime Inference, where `PRIME_API_KEY` takes priority.
### Key Resolution
@@ -134,7 +134,19 @@ OAuth credentials are also stored here after `/login` and managed automatically.
### Prime Inference
-Prime Inference uses the OpenAI-compatible endpoint at `https://api.pinference.ai/api/v1`. Set `PRIME_API_KEY` or store an API key for `prime-inference` via `/login`.
+Prime Inference uses the production OpenAI-compatible endpoint at `https://api.pinference.ai/api/v1`. Set `PRIME_API_KEY` or use `/login` to save a key for `prime-inference` in `~/.prime/agent/auth.json`.
+
+Normal startup, model discovery, inference, credential status, and team selection do not read Prime CLI credentials or URLs from `~/.prime/config.json`. If you previously relied on CLI credentials, run `/login` once. During this explicit login, Agent can reuse a CLI key only when every configured CLI URL is a canonical production URL (or absent), the resolved Agent login destinations are production, and production `/whoami` validates the key. Local or development CLI configuration falls back to the browser login flow, which defaults to production.
+
+An imported key and its CLI-file team selection are saved as an Agent-owned snapshot. Later CLI login, logout, URL, or team changes do not affect Agent. Agent login, team changes, and logout never write the CLI config. Saving a different key clears the previous Agent team to personal billing unless the login supplies a new team snapshot; saving the same key preserves the saved team.
+
+`PRIME_TEAM_ID` overrides the request's `X-Prime-Team-ID` header but is never saved as the imported team. Runtime and `PRIME_API_KEY` credentials do not inherit a saved Agent team; set `PRIME_TEAM_ID` explicitly when using those credentials with team billing.
+
+For deliberate development or test use, `PRIME_AGENT_INFERENCE_API_BASE_URL` overrides the Agent authentication and team API (default `https://api.primeintellect.ai/api/v1`). `PRIME_AGENT_INFERENCE_FRONTEND_URL` overrides the login browser frontend (default `https://app.primeintellect.ai`). These Agent-specific settings apply to browser login, manual-key validation, and team lookup. They do not change model inference URLs. CLI credential reuse is disabled when either resolved login destination is nonproduction. Legacy `PRIME_API_BASE_URL` and CLI-file URLs do not control Agent authentication.
+
+### Trace sharing credentials
+
+Trace sharing remains opt-in. Normal uploads use explicit environment or Agent-owned credentials, never a live CLI credential fallback. `/traces login` can reuse a CLI key only after the same production URL checks and production validation, including the required `agent_traces` scope. The trace API defaults to `https://api.primeintellect.ai`; only the trace-specific `PRIME_AGENT_TRACES_BASE_URL` overrides that default, not CLI URLs or `PRIME_API_BASE_URL`. Explicit trace login does not reuse CLI credentials when its resolved trace API destination is nonproduction.
## Cloud Providers
@@ -252,7 +264,16 @@ Or set `GOOGLE_APPLICATION_CREDENTIALS` to a service account key file.
## Resolution Order
-When resolving credentials for a provider:
+For Prime Inference:
+
+1. CLI `--api-key` flag (runtime override)
+2. `PRIME_API_KEY`
+3. Agent `auth.json` entry
+4. Custom provider keys from `models.json`
+
+Prime CLI config is not part of normal credential resolution.
+
+For other providers:
1. CLI `--api-key` flag
2. `auth.json` entry (API key or OAuth token)
diff --git a/packages/coding-agent/docs/usage.md b/packages/coding-agent/docs/usage.md
index e9eb8b97a4..299fc3512c 100644
--- a/packages/coding-agent/docs/usage.md
+++ b/packages/coding-agent/docs/usage.md
@@ -62,6 +62,12 @@ Type `/` in the editor to open command completion. Extensions can register custo
| `/changelog` | Display version history |
| `/quit` | Quit Prime Agent |
+### Prime credentials and trace sharing
+
+Prime Inference uses Agent-owned credentials in `~/.prime/agent/auth.json`, with `--api-key` and `PRIME_API_KEY` taking priority. Normal use ignores Prime CLI credentials, URLs, and teams in `~/.prime/config.json`. Run `/login` once if you previously relied on CLI credentials. Explicit login can import a production-compatible CLI key and its file team snapshot after production validation. Agent login, team changes, and logout never modify CLI config.
+
+Trace uploads also ignore live CLI credentials. Use `/traces login` to save a trace credential, or set `PRIME_AGENT_TRACES_API_KEY`. Explicit trace login can reuse a CLI key only after production URL and scope validation. Trace sharing is opt-in; `/traces off` disables automatic sharing. See [Providers](providers.md#prime-inference) for credential precedence, team overrides, and production endpoint details.
+
## Message Queue
You can submit messages while the agent is still working:
@@ -362,6 +368,9 @@ prime-agent --tools ipython -p "Review the code"
| `PRIME_AGENT_DOWNLOAD_BASE_URL` | Override the Prime Agent release manifest and tarball base URL |
| `PI_CACHE_RETENTION` | Set to `long` for extended prompt cache where supported |
| `PRIME_API_KEY` | Prime Inference API key; also used for trace sharing when it has `agent_traces` scope |
+| `PRIME_TEAM_ID` | Override the Prime Inference team request header without changing the saved Agent team |
+| `PRIME_AGENT_INFERENCE_API_BASE_URL` | Override Agent authentication and team API URLs, not model inference URLs; defaults to production |
+| `PRIME_AGENT_INFERENCE_FRONTEND_URL` | Override the Agent login browser frontend; defaults to production |
| `PRIME_AGENT_TRACES_API_KEY` | Prime API key used only for opt-in trace sharing |
| `PRIME_AGENT_TRACES_BASE_URL` | Override the Prime Agent trace upload API base URL |
| `PRIME_AGENT_KERNEL_PYTHON` | Use an existing Python environment with `prime-agent-runtime` instead of bootstrapping `~/.prime/agent/kernel-venv` |
diff --git a/packages/coding-agent/src/core/agent-session-services.ts b/packages/coding-agent/src/core/agent-session-services.ts
index 249ffc0773..8da9b04bc0 100644
--- a/packages/coding-agent/src/core/agent-session-services.ts
+++ b/packages/coding-agent/src/core/agent-session-services.ts
@@ -145,7 +145,9 @@ export async function createAgentSessionServices(
): Promise<AgentSessionServices> {
const cwd = options.cwd;
const agentDir = options.agentDir ?? getAgentDir();
- const authStorage = options.authStorage ?? AuthStorage.create(join(agentDir, "auth.json"));
+ const authStorage =
+ options.authStorage ??
+ AuthStorage.create(options.agentDir === undefined ? undefined : join(agentDir, "auth.json"));
const settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);
const modelRegistry = options.modelRegistry ?? ModelRegistry.create(authStorage, join(agentDir, "models.json"));
diff --git a/packages/coding-agent/src/core/agent-traces.ts b/packages/coding-agent/src/core/agent-traces.ts
index f51aaab062..0cf28666eb 100644
--- a/packages/coding-agent/src/core/agent-traces.ts
+++ b/packages/coding-agent/src/core/agent-traces.ts
@@ -7,7 +7,6 @@ import { appendRotatingLog, getAgentDir, getAgentTracesLogPath, getSessionsDir,
import { readFirstLineSync } from "../utils/file-lines.js";
import type { AuthStorage } from "./auth-storage.js";
import {
- loadPrimeCliConfig,
PRIME_AGENT_TRACES_PROVIDER_ID,
PRIME_INFERENCE_PROVIDER_ID,
resolvePrimeAgentTracesBaseUrl,
@@ -64,7 +63,6 @@ export interface AgentTraceUploadOptions {
/** Require the global automatic-sharing opt-in. Set false only for an explicit one-shot upload command. */
requireEnabled?: boolean;
baseUrl?: string;
- configPath?: string;
fetchFn?: typeof fetch;
reloadConfig?: boolean;
requestTimeoutMs?: number;
@@ -79,7 +77,6 @@ export interface AgentTraceUploadInstallOptions {
authStorage: AuthStorage;
settingsManager: SettingsManager;
baseUrl?: string;
- configPath?: string;
fetchFn?: typeof fetch;
requestTimeoutMs?: number;
/** The session's semantic-edge ledger; registered with the outbox as its own delivery kind. */
@@ -838,7 +835,7 @@ export async function catchUpAgentTraceUploads(
export async function getPrimeAgentTraceCredential(
authStorage: AuthStorage,
- options: { reloadAuth?: boolean; configPath?: string } = {},
+ options: { reloadAuth?: boolean } = {},
): Promise<AgentTraceCredential | undefined> {
const traceEnvKey = stringEnv("PRIME_AGENT_TRACES_API_KEY");
if (traceEnvKey) {
@@ -867,11 +864,6 @@ export async function getPrimeAgentTraceCredential(
}
}
- const primeCliKey = loadPrimeCliConfig(options.configPath).apiKey;
- if (primeCliKey) {
- return { apiKey: primeCliKey, source: "prime-cli", label: "Prime CLI credential" };
- }
-
return undefined;
}
@@ -962,7 +954,6 @@ async function performAgentTraceUpload(
}
const credential = await getPrimeAgentTraceCredential(options.authStorage, {
- configPath: options.configPath,
reloadAuth: options.reloadConfig !== false,
});
if (!credential) {
diff --git a/packages/coding-agent/src/core/auth-storage.ts b/packages/coding-agent/src/core/auth-storage.ts
index 5f2acb9089..c6fd7a9797 100644
--- a/packages/coding-agent/src/core/auth-storage.ts
+++ b/packages/coding-agent/src/core/auth-storage.ts
@@ -20,16 +20,7 @@ import { dirname, join } from "path";
import lockfile from "proper-lockfile";
import { getAgentDir } from "../config.js";
import { realpathIfPresentSync, writeFileAtomicSync } from "../utils/atomic-file.js";
-import {
- clearPrimeCliCredentials,
- getPrimeCliConfigPath,
- loadPrimeCliConfig,
- PRIME_INFERENCE_PROVIDER_ID,
- type PrimeCliConfig,
- type PrimeTeam,
- savePrimeCliApiKey,
- savePrimeCliTeamSelection,
-} from "./prime-inference-auth.js";
+import { getPrimeCliConfigPath, PRIME_INFERENCE_PROVIDER_ID, type PrimeTeam } from "./prime-inference-auth.js";
import { resolveConfigValue, resolveConfigValueUncached } from "./resolve-config-value.js";
export type PrimeTeamCredential = {
@@ -402,22 +393,6 @@ export class AuthStorage {
};
}
- private getPrimeCliAuthCandidate(provider: string): AuthSourceCandidate | undefined {
- const apiKey = this.getPrimeCliApiKey(provider);
- if (!apiKey) {
- return undefined;
- }
- return {
- label: "Prime CLI",
- ...this.createAuthSourceCandidate({
- configured: false,
- source: "prime_cli",
- identityMaterial: provider,
- valueMaterial: apiKey,
- }),
- };
- }
-
private getStoredAuthCandidate(
provider: string,
options?: { resolveCommandValue?: boolean; resolvedCommandValue?: string },
@@ -515,7 +490,6 @@ export class AuthStorage {
? [
this.getRuntimeAuthCandidate(provider),
this.getEnvironmentAuthCandidate(provider),
- this.getPrimeCliAuthCandidate(provider),
this.getStoredAuthCandidate(provider),
fallbackCandidate,
]
@@ -651,7 +625,11 @@ export class AuthStorage {
if (!content) {
return {};
}
- return JSON.parse(content) as AuthStorageData;
+ const data: unknown = JSON.parse(content);
+ if (typeof data !== "object" || data === null || Array.isArray(data)) {
+ throw new Error("Invalid auth storage: expected a JSON object");
+ }
+ return data as AuthStorageData;
}
/**
@@ -796,14 +774,9 @@ export class AuthStorage {
* Logout from a provider.
*/
logout(provider: string): void {
- if (provider === PRIME_INFERENCE_PROVIDER_ID && this.isPrimeCliConfigEnabled()) {
- try {
- clearPrimeCliCredentials(this.getEnabledPrimeCliConfigPath());
- this.clearStaleAuthSource(provider, "prime_cli");
- } catch (error) {
- this.recordError(error);
- throw error;
- }
+ if (provider === PRIME_INFERENCE_PROVIDER_ID) {
+ this.removeVerified(provider);
+ return;
}
this.remove(provider);
}
@@ -862,7 +835,7 @@ export class AuthStorage {
* Get API key for a provider.
* Priority:
* 1. Runtime override (CLI --api-key)
- * 2. Prime Inference: environment variable, Prime CLI config, auth.json
+ * 2. Prime Inference: environment variable, auth.json
* 3. Other providers: auth.json, environment variable
* 4. Fallback resolver (models.json custom providers)
*/
@@ -894,17 +867,6 @@ export class AuthStorage {
};
}
- if (providerId === PRIME_INFERENCE_PROVIDER_ID) {
- const primeCliCandidate = this.getPrimeCliAuthCandidate(providerId);
- const primeCliKey = this.getPrimeCliApiKey(providerId);
- if (primeCliKey && primeCliCandidate && !this.isAuthSourceStale(providerId, primeCliCandidate)) {
- return {
- apiKey: primeCliKey,
- sourceToken: this.getAuthSourceTokenForCandidate(providerId, primeCliCandidate),
- };
- }
- }
-
const cred = this.data[providerId];
if (cred?.type === "api_key") {
@@ -1018,114 +980,60 @@ export class AuthStorage {
return getOAuthProviders();
}
- 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;
+ private updatePrimeInferenceCredential(
+ update: (credential: AuthCredential | undefined) => ApiKeyCredential | undefined,
+ ): void {
+ try {
+ const data = this.storage.withLock((current) => {
+ const data = this.parseStorageData(current);
+ const credential = update(data[PRIME_INFERENCE_PROVIDER_ID]);
+ if (!credential) return { result: data };
+ data[PRIME_INFERENCE_PROVIDER_ID] = credential;
+ return { result: data, next: JSON.stringify(data, null, 2) };
+ });
+ this.data = data;
+ this.loadError = null;
+ } catch (error) {
+ this.recordError(error);
+ throw error;
}
- this.set(PRIME_INFERENCE_PROVIDER_ID, {
- ...credential,
- primeTeam: team ? this.toPrimeTeamCredential(team) : null,
- });
}
- 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);
- }
- this.clearStaleAuthSource(PRIME_INFERENCE_PROVIDER_ID, "prime_cli");
- } catch (error) {
- this.recordError(error);
- throw error;
- }
- if (this.data[PRIME_INFERENCE_PROVIDER_ID]) {
- this.remove(PRIME_INFERENCE_PROVIDER_ID);
- }
- return;
- }
+ setPrimeInferenceTeamSelection(team: PrimeTeam | null, expectedApiKey?: string): void {
+ this.updatePrimeInferenceCredential((credential) =>
+ credential?.type === "api_key" && (expectedApiKey === undefined || credential.key === expectedApiKey)
+ ? { ...credential, primeTeam: team ? this.toPrimeTeamCredential(team) : null }
+ : undefined,
+ );
+ }
- const existingCredential = this.data[PRIME_INFERENCE_PROVIDER_ID];
- const existingPrimeTeam = existingCredential?.type === "api_key" ? existingCredential.primeTeam : undefined;
- this.set(PRIME_INFERENCE_PROVIDER_ID, {
+ setPrimeInferenceApiKey(apiKey: string, team?: PrimeTeam | null): void {
+ this.updatePrimeInferenceCredential((existing) => ({
type: "api_key",
key: apiKey,
- ...(existingPrimeTeam !== undefined ? { primeTeam: existingPrimeTeam } : {}),
- });
+ primeTeam:
+ team !== undefined
+ ? team
+ ? this.toPrimeTeamCredential(team)
+ : null
+ : existing?.type === "api_key" && existing.key === apiKey
+ ? (existing.primeTeam ?? null)
+ : null,
+ }));
+ this.clearStaleAuthSource(PRIME_INFERENCE_PROVIDER_ID, "stored");
}
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 (process.env.PRIME_TEAM_ID?.trim()) return undefined;
const authSource = this.getAuthStatus(PRIME_INFERENCE_PROVIDER_ID).source;
- if (authSource === "runtime" || authSource === "environment") {
- return undefined;
- }
- // A stale CLI key must not erase the selected team used to validate cached model access.
- if (authSource === "prime_cli" || (authSource === "stale" && 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;
- }
- if (credential?.type === "api_key" && credential.primeTeam !== undefined) {
- return credential.primeTeam;
- }
- if (!config?.apiKey && config?.teamId) {
- return this.toPrimeTeamCredential({
- teamId: config.teamId,
- name: config.teamName ?? "Prime CLI team",
- ...(config.teamRole ? { role: config.teamRole } : {}),
- });
- }
- return undefined;
+ if (authSource === "runtime" || authSource === "environment") return undefined;
+ const credential = this.data[PRIME_INFERENCE_PROVIDER_ID];
+ return credential?.type === "api_key" ? credential.primeTeam : undefined;
}
getProviderHeaders(providerId: string): Record<string, string> | undefined {
- if (providerId !== PRIME_INFERENCE_PROVIDER_ID) {
- return undefined;
- }
-
- const primeCliConfig = this.getPrimeCliConfig(providerId);
- if (primeCliConfig?.teamIdFromEnv) {
- return primeCliConfig.teamId ? { "X-Prime-Team-ID": primeCliConfig.teamId } : undefined;
- }
-
- const teamId = this.getPrimeInferenceTeamSelection()?.teamId;
+ if (providerId !== PRIME_INFERENCE_PROVIDER_ID) return undefined;
+ const teamId = process.env.PRIME_TEAM_ID?.trim() || this.getPrimeInferenceTeamSelection()?.teamId;
return teamId ? { "X-Prime-Team-ID": teamId } : undefined;
}
@@ -1153,28 +1061,6 @@ export class AuthStorage {
return credential;
}
- private getPrimeCliConfig(providerId: string): PrimeCliConfig | undefined {
- if (providerId !== PRIME_INFERENCE_PROVIDER_ID) {
- return undefined;
- }
- if (!this.isPrimeCliConfigEnabled()) {
- return undefined;
- }
- 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 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 3331ae3605..a4911ed165 100644
--- a/packages/coding-agent/src/core/prime-inference-auth.ts
+++ b/packages/coding-agent/src/core/prime-inference-auth.ts
@@ -1,18 +1,8 @@
import { Buffer } from "node:buffer";
import { constants, generateKeyPairSync, privateDecrypt } from "node:crypto";
-import {
- chmodSync,
- closeSync,
- existsSync,
- mkdirSync,
- openSync,
- readFileSync,
- renameSync,
- rmSync,
- writeFileSync,
-} from "node:fs";
+import { existsSync, readFileSync } from "node:fs";
import { homedir } from "node:os";
-import { basename, dirname, join } from "node:path";
+import { join } from "node:path";
import type { OAuthAuthInfo } from "@earendil-works/pi-ai";
export const PRIME_INFERENCE_PROVIDER_ID = "prime-inference";
@@ -31,18 +21,14 @@ export type PrimeInferenceAuthSource = "prime-cli" | "browser";
export type PrimeInferenceLoginResult = {
apiKey: string;
source: PrimeInferenceAuthSource;
+ primeTeam?: PrimeTeam | null;
};
-export type PrimeCliConfig = {
+type PrimeCliConfig = {
apiKey?: string;
- baseUrl: string;
- frontendUrl: string;
- inferenceUrl: string;
- path: string;
teamId?: string;
teamName?: string;
teamRole?: string;
- teamIdFromEnv: boolean;
};
export type PrimeInferenceLoginCallbacks = {
@@ -53,6 +39,7 @@ export type PrimeInferenceLoginCallbacks = {
export type PrimeInferenceLoginOptions = {
configPath?: string;
+ usePrimeCliConfig?: boolean;
fetchFn?: typeof fetch;
pollIntervalMs?: number;
requestTimeoutMs?: number;
@@ -136,115 +123,54 @@ 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 loadProductionPrimeCliConfig(configPath?: string): PrimeCliConfig | undefined {
+ const path = getPrimeCliConfigPath(configPath);
+ const data = readPrimeCliConfigData(path);
+ const urls = [
+ ["base_url", DEFAULT_PRIME_API_BASE_URL],
+ ["frontend_url", DEFAULT_PRIME_FRONTEND_URL],
+ ["inference_url", DEFAULT_PRIME_INFERENCE_URL],
+ ] as const;
+ for (const [field, expected] of urls) {
+ if (data[field] === undefined) continue;
+ const value = stringField(data, field);
+ if (!value) return undefined;
+ const normalized = field === "base_url" ? normalizeBaseUrl(value) : normalizeUrl(value, expected);
+ if (normalized !== expected) return undefined;
}
+ return {
+ apiKey: stringField(data, "api_key"),
+ teamId: stringField(data, "team_id"),
+ teamName: stringField(data, "team_name"),
+ teamRole: stringField(data, "team_role"),
+ };
}
-function clearPrimeTeamFields(data: Record<string, unknown>): void {
- delete data.team_id;
- delete data.team_name;
- delete data.team_role;
+function importedPrimeTeam(config: PrimeCliConfig): PrimeTeam | null {
+ return config.teamId
+ ? {
+ teamId: config.teamId,
+ name: config.teamName ?? "Prime team",
+ ...(config.teamRole ? { role: config.teamRole } : {}),
+ }
+ : null;
}
-export function loadPrimeCliConfig(configPath: string = defaultPrimeCliConfigPath()): PrimeCliConfig {
- const data = readPrimeCliConfigData(configPath);
- const teamIdFromEnv = stringEnv("PRIME_TEAM_ID");
- const teamId = teamIdFromEnv ?? stringField(data, "team_id");
-
- const config: PrimeCliConfig = {
- baseUrl: normalizeBaseUrl(stringField(data, "base_url")),
- frontendUrl: normalizeUrl(stringField(data, "frontend_url"), DEFAULT_PRIME_FRONTEND_URL),
- inferenceUrl: normalizeUrl(stringField(data, "inference_url"), DEFAULT_PRIME_INFERENCE_URL),
- path: configPath,
- teamIdFromEnv: teamIdFromEnv !== undefined,
+export function resolvePrimeInferenceAuthConfig(): PrimeChallengeConfig {
+ return {
+ baseUrl: normalizeBaseUrl(stringEnv("PRIME_AGENT_INFERENCE_API_BASE_URL")),
+ frontendUrl: normalizeUrl(stringEnv("PRIME_AGENT_INFERENCE_FRONTEND_URL"), DEFAULT_PRIME_FRONTEND_URL),
};
- const apiKey = stringField(data, "api_key");
- if (apiKey) {
- config.apiKey = apiKey;
- }
- if (teamId) {
- config.teamId = teamId;
- }
- if (!teamIdFromEnv) {
- const teamName = stringField(data, "team_name");
- const teamRole = stringField(data, "team_role");
- if (teamName) {
- config.teamName = teamName;
- }
- if (teamRole) {
- config.teamRole = teamRole;
- }
- }
- 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"));
}
-function resolvePrimeAgentTracesChallengeConfig(config: PrimeCliConfig): PrimeChallengeConfig {
+function resolvePrimeAgentTracesChallengeConfig(): PrimeChallengeConfig {
return {
baseUrl: resolvePrimeAgentTracesBaseUrl(),
- frontendUrl: stringEnv("PRIME_AGENT_TRACES_BASE_URL") ? config.frontendUrl : DEFAULT_PRIME_FRONTEND_URL,
+ frontendUrl: DEFAULT_PRIME_FRONTEND_URL,
};
}
@@ -645,27 +571,33 @@ export async function loginPrimeInference(
callbacks: PrimeInferenceLoginCallbacks,
options: PrimeInferenceLoginOptions = {},
): Promise<PrimeInferenceLoginResult> {
- const config = loadPrimeCliConfig(options.configPath);
+ const config = resolvePrimeInferenceAuthConfig();
+ const candidate =
+ options.usePrimeCliConfig !== false &&
+ config.baseUrl === DEFAULT_PRIME_API_BASE_URL &&
+ config.frontendUrl === DEFAULT_PRIME_FRONTEND_URL
+ ? loadProductionPrimeCliConfig(options.configPath)
+ : undefined;
const fetchFn = options.fetchFn ?? fetch;
const requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
- if (config.apiKey) {
+ if (candidate?.apiKey) {
callbacks.onProgress?.("Checking existing Prime CLI credentials...");
- const access = await checkPrimeInferenceAccess(config.apiKey, config.baseUrl, {
+ const access = await checkPrimeInferenceAccess(candidate.apiKey, config.baseUrl, {
fetchFn,
requestTimeoutMs,
signal: callbacks.signal,
});
if (access.ok) {
throwIfCancelled(callbacks.signal);
- return { apiKey: config.apiKey, source: "prime-cli" };
+ return { apiKey: candidate.apiKey, source: "prime-cli", primeTeam: importedPrimeTeam(candidate) };
}
callbacks.onProgress?.(
`Existing Prime CLI key cannot access Prime Inference (${formatAccessFailure(access)}). Starting browser login...`,
);
} else {
- callbacks.onProgress?.("No Prime CLI API key found. Starting browser login...");
+ callbacks.onProgress?.("No eligible production Prime CLI API key found. Starting browser login...");
}
const apiKey = await runPrimeBrowserLogin(config, callbacks, fetchFn, requestTimeoutMs, pollIntervalMs);
@@ -688,15 +620,18 @@ export async function loginPrimeAgentTraces(
callbacks: PrimeInferenceLoginCallbacks,
options: PrimeInferenceLoginOptions = {},
): Promise<PrimeInferenceLoginResult> {
- const config = loadPrimeCliConfig(options.configPath);
- const traceConfig = resolvePrimeAgentTracesChallengeConfig(config);
+ const traceConfig = resolvePrimeAgentTracesChallengeConfig();
+ const config =
+ options.usePrimeCliConfig !== false && traceConfig.baseUrl === DEFAULT_PRIME_API_BASE_URL
+ ? loadProductionPrimeCliConfig(options.configPath)
+ : undefined;
const fetchFn = options.fetchFn ?? fetch;
const requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
- if (config.apiKey) {
+ if (config?.apiKey) {
callbacks.onProgress?.("Checking existing Prime CLI credentials...");
- const access = await checkPrimeAgentTracesAccess(config.apiKey, traceConfig.baseUrl, {
+ const access = await checkPrimeAgentTracesAccess(config.apiKey, DEFAULT_PRIME_API_BASE_URL, {
fetchFn,
requestTimeoutMs,
signal: callbacks.signal,
diff --git a/packages/coding-agent/src/modes/interactive/auth-flows.ts b/packages/coding-agent/src/modes/interactive/auth-flows.ts
index 80e7b2378e..6e7e7e76ae 100644
--- a/packages/coding-agent/src/modes/interactive/auth-flows.ts
+++ b/packages/coding-agent/src/modes/interactive/auth-flows.ts
@@ -7,7 +7,6 @@ import {
checkPrimeAgentTracesAccess,
checkPrimeInferenceAccess,
fetchPrimeTeams,
- loadPrimeCliConfig,
loginPrimeAgentTraces,
loginPrimeInference,
PRIME_AGENT_TRACES_PROVIDER_ID,
@@ -16,6 +15,7 @@ import {
PRIME_INFERENCE_PROVIDER_NAME,
type PrimeTeam,
resolvePrimeAgentTracesBaseUrl,
+ resolvePrimeInferenceAuthConfig,
} from "../../core/prime-inference-auth.js";
import { BUILT_IN_PROVIDER_DISPLAY_NAMES } from "../../core/provider-display-names.js";
import { SERPER_CREDENTIAL_ID, SERPER_CREDENTIAL_NAME } from "../../core/websearch-credential.js";
@@ -293,17 +293,6 @@ 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));
}
@@ -412,24 +401,7 @@ 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.";
- }
- }
+ if (process.env.PRIME_TEAM_ID?.trim()) return "Using team from PRIME_TEAM_ID.";
const storedTeam = this.host.modelRegistry.authStorage.getPrimeInferenceTeamSelection();
if (storedTeam) {
return `Using team "${storedTeam.name}".`;
@@ -442,27 +414,28 @@ export class ProviderAuthFlows {
private async selectPrimeInferenceTeam(apiKey: string, dialog: LoginDialogComponent): Promise<string | undefined> {
try {
- const config = loadPrimeCliConfig(this.host.modelRegistry.authStorage.getPrimeCliConfigPath());
- if (config.teamIdFromEnv) {
+ if (process.env.PRIME_TEAM_ID?.trim()) {
this.host.modelRegistry.authStorage.reload();
return "Using team from PRIME_TEAM_ID.";
}
dialog.showProgress("Loading Prime teams...");
- const teams = await fetchPrimeTeams(apiKey, config.baseUrl, { signal: dialog.signal });
+ const teams = await fetchPrimeTeams(apiKey, resolvePrimeInferenceAuthConfig().baseUrl, {
+ signal: dialog.signal,
+ });
if (dialog.signal.aborted) {
return this.getPrimeInferenceDefaultTeamStatus();
}
if (teams.length === 0) {
- this.host.modelRegistry.authStorage.setPrimeInferenceTeamSelection(null);
+ this.host.modelRegistry.authStorage.setPrimeInferenceTeamSelection(null, apiKey);
return "Using personal account.";
}
const storedTeam = this.host.modelRegistry.authStorage.getPrimeInferenceTeamSelection();
- const currentTeamId = storedTeam === null ? undefined : (storedTeam?.teamId ?? config.teamId);
+ const currentTeamId = storedTeam === null ? undefined : storedTeam?.teamId;
const selectedTeam = await this.showPrimeTeamSelector(teams, currentTeamId);
if (selectedTeam !== undefined) {
- this.host.modelRegistry.authStorage.setPrimeInferenceTeamSelection(selectedTeam);
+ this.host.modelRegistry.authStorage.setPrimeInferenceTeamSelection(selectedTeam, apiKey);
}
return selectedTeam
? `Using team "${selectedTeam.name}".`
@@ -479,8 +452,9 @@ export class ProviderAuthFlows {
apiKey: string,
dialog: LoginDialogComponent,
closeDialog: () => void,
+ primeTeam?: PrimeTeam | null,
): Promise<AuthenticationResult> {
- this.host.modelRegistry.authStorage.setPrimeInferenceApiKey(apiKey);
+ this.host.modelRegistry.authStorage.setPrimeInferenceApiKey(apiKey, primeTeam);
const teamStatus = await this.selectPrimeInferenceTeam(apiKey, dialog);
closeDialog();
@@ -490,7 +464,6 @@ export class ProviderAuthFlows {
"api_key",
teamStatus,
"provider",
- this.host.modelRegistry.authStorage.getPrimeCliConfigPath() ?? getAuthPath(),
);
}
@@ -564,6 +537,7 @@ export class ProviderAuthFlows {
},
{
configPath: this.host.modelRegistry.authStorage.getPrimeCliConfigPath(),
+ usePrimeCliConfig: this.host.modelRegistry.authStorage.getPrimeCliConfigPath() !== undefined,
},
);
// When the browser challenge cannot start or breaks down, keep the dialog
@@ -599,8 +573,9 @@ export class ProviderAuthFlows {
if (result.source === "manual") {
browserAbort.abort();
dialog.showProgress("Checking Prime Inference access...");
- const config = loadPrimeCliConfig(this.host.modelRegistry.authStorage.getPrimeCliConfigPath());
- const access = await checkPrimeInferenceAccess(result.apiKey, config.baseUrl, { signal: dialog.signal });
+ const access = await checkPrimeInferenceAccess(result.apiKey, resolvePrimeInferenceAuthConfig().baseUrl, {
+ signal: dialog.signal,
+ });
if (dialog.signal.aborted) {
closeDialog();
return { status: "cancelled" };
@@ -611,7 +586,12 @@ export class ProviderAuthFlows {
}
}
- return await this.completePrimeInferenceLogin(result.apiKey, dialog, closeDialog);
+ return await this.completePrimeInferenceLogin(
+ result.apiKey,
+ dialog,
+ closeDialog,
+ "primeTeam" in result ? result.primeTeam : undefined,
+ );
} catch (error: unknown) {
closeDialog();
const errorMsg = error instanceof Error ? error.message : String(error);
@@ -666,16 +646,22 @@ export class ProviderAuthFlows {
};
try {
- const browserLogin = loginPrimeAgentTraces({
- onAuth: (info) => {
- dialog.showAuth(info.url, info.instructions);
- armManualInput("Complete the sign-in in your browser, or paste a Prime API key below:");
+ const browserLogin = loginPrimeAgentTraces(
+ {
+ onAuth: (info) => {
+ dialog.showAuth(info.url, info.instructions);
+ armManualInput("Complete the sign-in in your browser, or paste a Prime API key below:");
+ },
+ onProgress: (message) => {
+ dialog.showProgress(message);
+ },
+ signal: browserAbort.signal,
},
- onProgress: (message) => {
- dialog.showProgress(message);
+ {
+ configPath: this.host.modelRegistry.authStorage.getPrimeCliConfigPath(),
+ usePrimeCliConfig: this.host.modelRegistry.authStorage.getPrimeCliConfigPath() !== undefined,
},
- signal: browserAbort.signal,
- });
+ );
const browserLoginOrFallback = browserLogin.catch((error: unknown) => {
if (browserAbort.signal.aborted) {
throw error;
diff --git a/packages/coding-agent/test/agent-session-services.test.ts b/packages/coding-agent/test/agent-session-services.test.ts
index ca25424d6d..b9958a67be 100644
--- a/packages/coding-agent/test/agent-session-services.test.ts
+++ b/packages/coding-agent/test/agent-session-services.test.ts
@@ -3,6 +3,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { registerFauxProvider } from "@earendil-works/pi-ai";
import { afterEach, describe, expect, it, vi } from "vitest";
+import { ENV_AGENT_DIR } from "../src/config.js";
import { AGENT_MESSAGE_SKILL_NAME, type AgentSessionMessageController } from "../src/core/agent-messages.js";
import { AGENT_OBSERVE_SKILL_NAME, type AgentObserveController } from "../src/core/agent-observe.js";
import { createAgentSessionFromServices, createAgentSessionServices } from "../src/core/agent-session-services.js";
@@ -28,6 +29,34 @@ describe("createAgentSessionFromServices", () => {
}
});
+ it("enables CLI login reuse only for default services storage", async () => {
+ const tempDir = join(tmpdir(), `pi-default-services-auth-${Date.now()}`);
+ mkdirSync(tempDir, { recursive: true });
+ cleanupPaths.push(tempDir);
+ vi.stubEnv("HOME", tempDir);
+ vi.stubEnv(ENV_AGENT_DIR, "");
+ const injected = AuthStorage.inMemory();
+ for (const options of [{}, { agentDir: join(tempDir, "custom") }, { authStorage: injected }]) {
+ const services = await createAgentSessionServices({
+ cwd: tempDir,
+ ...options,
+ telemetryDisabled: true,
+ resourceLoaderOptions: {
+ noExtensions: true,
+ noSkills: true,
+ noPromptTemplates: true,
+ noThemes: true,
+ noContextFiles: true,
+ },
+ });
+ expect(services.modelRegistry.authStorage).toBe(services.authStorage);
+ expect(services.authStorage.getPrimeCliConfigPath()).toBe(
+ "agentDir" in options || "authStorage" in options ? undefined : join(tempDir, ".prime", "config.json"),
+ );
+ if ("authStorage" in options) expect(services.authStorage).toBe(injected);
+ }
+ });
+
it("shows the telemetry disclosure independently of the Herdr reporter", async () => {
vi.stubEnv("DO_NOT_TRACK", "0");
vi.stubEnv("PRIME_AGENT_TELEMETRY", "1");
diff --git a/packages/coding-agent/test/agent-traces.test.ts b/packages/coding-agent/test/agent-traces.test.ts
index 311a3d45ab..4b3426f4df 100644
--- a/packages/coding-agent/test/agent-traces.test.ts
+++ b/packages/coding-agent/test/agent-traces.test.ts
@@ -318,11 +318,13 @@ describe("agent trace upload", () => {
const calls: FetchCall[] = [];
const result = await uploadAgentTraceFile({
sessionFile: sessionManager.getSessionFile(),
- authStorage: AuthStorage.inMemory({
- [PRIME_AGENT_TRACES_PROVIDER_ID]: { type: "api_key", key: "trace-key" },
- }),
+ authStorage: AuthStorage.inMemory(
+ {
+ [PRIME_AGENT_TRACES_PROVIDER_ID]: { type: "api_key", key: "trace-key" },
+ },
+ { primeCliConfigPath: configPath, usePrimeCliConfig: true },
+ ),
settingsManager: SettingsManager.inMemory({ agentTraces: { enabled: true } }),
- configPath,
fetchFn: createFetchRecorder(calls),
reloadConfig: false,
});
@@ -1583,26 +1585,50 @@ describe("agent trace upload", () => {
expect(calls).toHaveLength(0);
});
- it("prefers the prime-inference credential over the prime-cli config key", async () => {
+ it.each([false, true])("does not fall back to CLI credentials for trace upload (stale: %s)", async (stale) => {
+ const session = writeSession(tempDir, join(tempDir, "sessions"), "cli-fallback-session");
+ const calls: FetchCall[] = [];
+ const configPath = join(tempDir, "prime-config.json");
+ writeFileSync(configPath, JSON.stringify({ api_key: "cli-key", base_url: "https://api.primeintellect.ai" }));
+ const authStorage = AuthStorage.inMemory({}, { primeCliConfigPath: configPath });
+ if (stale) {
+ authStorage.setPrimeInferenceApiKey("agent-key");
+ expect(authStorage.markAuthStale(PRIME_INFERENCE_PROVIDER_ID)).toBe(true);
+ writeFileSync(configPath, JSON.stringify({ api_key: "changed-cli-key" }));
+ }
+ const result = await uploadAgentTraceFile({
+ sessionFile: session.getSessionFile(),
+ authStorage,
+ settingsManager: SettingsManager.inMemory({ agentTraces: { enabled: true } }),
+ fetchFn: createFetchRecorder(calls),
+ reloadConfig: false,
+ });
+ expect(result).toEqual({ status: "missing_credentials" });
+ expect(calls).toHaveLength(0);
+ });
+
+ it("uses Agent inference credentials at production despite local CLI credentials and URLs", async () => {
const session = writeSession(tempDir, join(tempDir, "sessions"), "credential-order-session");
const calls: FetchCall[] = [];
const configPath = join(tempDir, "prime-config.json");
- writeFileSync(configPath, JSON.stringify({ api_key: "cli-fallback-key" }));
+ writeFileSync(configPath, JSON.stringify({ api_key: "cli-fallback-key", base_url: "http://localhost:8000" }));
const result = await uploadAgentTraceFile({
sessionFile: session.getSessionFile(),
- authStorage: AuthStorage.inMemory({
- [PRIME_INFERENCE_PROVIDER_ID]: { type: "api_key", key: "inference-key" },
- }),
+ authStorage: AuthStorage.inMemory(
+ {
+ [PRIME_INFERENCE_PROVIDER_ID]: { type: "api_key", key: "inference-key" },
+ },
+ { primeCliConfigPath: configPath, usePrimeCliConfig: true },
+ ),
settingsManager: SettingsManager.inMemory({ agentTraces: { enabled: true } }),
- baseUrl: "https://api.example.test",
- configPath,
fetchFn: createFetchRecorder(calls),
reloadConfig: false,
});
expect(result.status).toBe("uploaded");
expect(calls).toHaveLength(1);
+ expect(calls[0]?.url).toBe("https://api.primeintellect.ai/api/v1/agent-traces/sessions/credential-order-session");
expect(calls[0]?.init.headers).toMatchObject({ Authorization: "Bearer inference-key" });
});
});
diff --git a/packages/coding-agent/test/auth-flows.test.ts b/packages/coding-agent/test/auth-flows.test.ts
index 6c6fff6746..08853cc830 100644
--- a/packages/coding-agent/test/auth-flows.test.ts
+++ b/packages/coding-agent/test/auth-flows.test.ts
@@ -3,10 +3,14 @@ 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 { afterEach, beforeAll, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";
+import { ENV_AGENT_DIR } from "../src/config.js";
+import { createAgentSessionServices } from "../src/core/agent-session-services.js";
import { AuthStorage } from "../src/core/auth-storage.js";
import { ModelRegistry } from "../src/core/model-registry.js";
import { PRIME_INFERENCE_PROVIDER_ID } from "../src/core/prime-inference-auth.js";
+import { createAgentSession } from "../src/core/sdk.js";
+import { SessionManager } from "../src/core/session-manager.js";
import { ProviderAuthFlows, type ProviderAuthFlowsHost } from "../src/modes/interactive/auth-flows.js";
import { initTheme } from "../src/modes/interactive/theme/theme.js";
@@ -84,6 +88,8 @@ describe("ProviderAuthFlows", () => {
});
beforeEach(() => {
+ vi.stubEnv("PRIME_AGENT_INFERENCE_API_BASE_URL", "");
+ vi.stubEnv("PRIME_AGENT_INFERENCE_FRONTEND_URL", "");
tempDir = join(tmpdir(), `pi-auth-flows-${Date.now()}-${Math.random().toString(36).slice(2)}`);
mkdirSync(tempDir, { recursive: true });
authJsonPath = join(tempDir, "auth.json");
@@ -108,9 +114,16 @@ describe("ProviderAuthFlows", () => {
rmSync(tempDir, { recursive: true });
}
vi.restoreAllMocks();
+ vi.unstubAllEnvs();
});
- it("preserves the Prime CLI team when login reuses the existing Prime CLI key", async () => {
+ it.each(["services", "sdk"])("imports CLI credentials through default %s", async (factory) => {
+ process.env.HOME = tempDir;
+ vi.stubEnv(ENV_AGENT_DIR, "");
+ vi.stubEnv("PI_OFFLINE", "1");
+ authJsonPath = join(tempDir, ".prime", "agent", "auth.json");
+ primeConfigPath = join(tempDir, ".prime", "config.json");
+ mkdirSync(join(tempDir, ".prime", "agent"), { recursive: true });
process.env.PRIME_TEAM_ID = "env-team";
writeFileSync(
primeConfigPath,
@@ -130,10 +143,23 @@ describe("ProviderAuthFlows", () => {
},
}),
);
- const authStorage = AuthStorage.create(authJsonPath, {
- primeCliConfigPath: primeConfigPath,
- usePrimeCliConfig: true,
+ const services = await createAgentSessionServices({
+ cwd: tempDir,
+ resourceLoaderOptions: { noExtensions: true },
});
+ let modelRegistry = services.modelRegistry;
+ if (factory === "sdk") {
+ const { session } = await createAgentSession({
+ cwd: tempDir,
+ resourceLoader: services.resourceLoader,
+ sessionManager: SessionManager.inMemory(tempDir),
+ noTools: "all",
+ });
+ onTestFinished(() => session.dispose());
+ modelRegistry = session.modelRegistry;
+ }
+ const authStorage = modelRegistry.authStorage;
+ expect(authStorage.getPrimeCliConfigPath()).toBe(primeConfigPath);
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(
jsonResponse({
data: { scope: { inference: { write: true } } },
@@ -141,7 +167,7 @@ describe("ProviderAuthFlows", () => {
);
const { host, statusMessages, errorMessages } = createHost(authStorage);
- const result = await new ProviderAuthFlows(host).runPrimeInferenceLogin();
+ const result = await new ProviderAuthFlows({ ...host, modelRegistry }).runPrimeInferenceLogin();
expect(errorMessages).toEqual([]);
expect(result.status).toBe("success");
@@ -153,60 +179,87 @@ describe("ProviderAuthFlows", () => {
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);
+ expect(AuthStorage.create(authJsonPath).get(PRIME_INFERENCE_PROVIDER_ID)).toEqual({
+ type: "api_key",
+ key: "prime-cli-key",
+ primeTeam: { teamId: "cli-team", name: "CLI Research", role: "admin" },
+ });
+ expect(statusMessages.join("\n")).not.toContain(primeConfigPath);
});
- it("stores a reused Prime CLI key when Prime CLI config sync is disabled", async () => {
+ it("does not import default CLI credentials when CLI reuse 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",
- });
+ const fetchMock = vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("offline"));
+ const { host, overlays } = createHost(authStorage);
+ const result = new ProviderAuthFlows(host).runPrimeInferenceLogin();
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledOnce());
+ expect(String(fetchMock.mock.calls[0]?.[0])).toBe("https://api.primeintellect.ai/api/v1/auth_challenge/generate");
+ overlays[0]?.handleInput?.("\x1b");
+ await expect(result).resolves.toEqual({ status: "cancelled" });
+ expect(authStorage.has(PRIME_INFERENCE_PROVIDER_ID)).toBe(false);
});
- it("offers Prime Inference logout when auth comes from the Prime CLI config", async () => {
+ it("does not offer logout for credentials owned only by the Prime CLI", async () => {
writeFileSync(primeConfigPath, JSON.stringify({ api_key: "prime-cli-key" }));
- const authStorage = AuthStorage.create(authJsonPath, {
- primeCliConfigPath: primeConfigPath,
- usePrimeCliConfig: true,
- });
+ const authStorage = AuthStorage.create(authJsonPath, { primeCliConfigPath: primeConfigPath });
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();
+ await expect(new ProviderAuthFlows(host).runLogout()).resolves.toBeNull();
+ expect(overlays).toHaveLength(0);
+ expect(JSON.parse(readFileSync(primeConfigPath, "utf-8"))).toEqual({ api_key: "prime-cli-key" });
});
+ it.each([undefined, "https://agent-api.example/api/v1/"])(
+ "uses the Agent auth target for manual validation and teams (%s)",
+ async (override) => {
+ delete process.env.PRIME_TEAM_ID;
+ if (override) vi.stubEnv("PRIME_AGENT_INFERENCE_API_BASE_URL", override);
+ const baseUrl = override ? "https://agent-api.example" : "https://api.primeintellect.ai";
+ const original = JSON.stringify({
+ api_key: "dev-secret",
+ base_url: "https://dev-api.example",
+ team_id: "dev-team",
+ });
+ writeFileSync(primeConfigPath, original);
+ const authStorage = AuthStorage.create(authJsonPath, { primeCliConfigPath: primeConfigPath });
+ const urls: string[] = [];
+ vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {
+ const url = String(input);
+ urls.push(url);
+ if (url === `${baseUrl}/api/v1/auth_challenge/generate`) throw new Error("browser unavailable");
+ expect(new Headers(init?.headers).get("Authorization")).toBe("Bearer manual-key");
+ if (url === `${baseUrl}/api/v1/user/whoami`)
+ return jsonResponse({ data: { scope: { inference: { write: true } } } });
+ if (url === `${baseUrl}/api/v1/user/teams?offset=0&limit=100`)
+ return jsonResponse({ data: [], total_count: 0 });
+ throw new Error(`Unexpected URL: ${url}`);
+ });
+ const { host, overlays, errorMessages } = createHost(authStorage);
+ const result = new ProviderAuthFlows(host).runPrimeInferenceLogin();
+ await vi.waitFor(() =>
+ expect(stripAnsi(overlays[0]?.render(80).join("\n") ?? "")).toContain("Paste a Prime API key below:"),
+ );
+ overlays[0]?.handleInput?.("manual-key");
+ overlays[0]?.handleInput?.("\r");
+ await expect(result).resolves.toMatchObject({ status: "success" });
+ expect(errorMessages).toEqual([]);
+ expect(urls).toEqual([
+ `${baseUrl}/api/v1/auth_challenge/generate`,
+ `${baseUrl}/api/v1/user/whoami`,
+ `${baseUrl}/api/v1/user/teams?offset=0&limit=100`,
+ ]);
+ expect(authStorage.get(PRIME_INFERENCE_PROVIDER_ID)).toEqual({
+ type: "api_key",
+ key: "manual-key",
+ primeTeam: null,
+ });
+ expect(readFileSync(primeConfigPath, "utf8")).toBe(original);
+ },
+ );
+
it("includes xAI subscription and API-key entries from the provider registry", () => {
const { host } = createHost(AuthStorage.inMemory());
const flows = new ProviderAuthFlows({
diff --git a/packages/coding-agent/test/auth-storage.test.ts b/packages/coding-agent/test/auth-storage.test.ts
index 663419cdd6..3b62009a35 100644
--- a/packages/coding-agent/test/auth-storage.test.ts
+++ b/packages/coding-agent/test/auth-storage.test.ts
@@ -222,105 +222,6 @@ describe("AuthStorage", () => {
expect(apiKey).toBe("literal_api_key_value");
});
- test("prime inference falls back to Prime CLI config when enabled", async () => {
- 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.hasAuth("prime-inference")).toBe(true);
- expect(authStorage.getAuthStatus("prime-inference")).toEqual({
- configured: false,
- source: "prime_cli",
- label: "Prime CLI",
- });
- });
-
- 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({});
-
- authStorage = AuthStorage.create(authJsonPath, {
- primeCliConfigPath: primeConfigPath,
- usePrimeCliConfig: true,
- });
-
- 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 marks current Prime CLI auth stale", async () => {
- 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,
- });
-
- expect(authStorage.markAuthStale("prime-inference")).toBe(true);
-
- expect(authStorage.hasAuth("prime-inference")).toBe(false);
- await expect(authStorage.getApiKey("prime-inference")).resolves.toBeUndefined();
- expect(authStorage.getAuthStatus("prime-inference")).toEqual({
- configured: false,
- source: "stale",
- label: "expired",
- });
- });
-
- test("changed Prime CLI key no longer matches stale auth marker", async () => {
- 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.markAuthStale("prime-inference");
-
- writeFileSync(primeConfigPath, JSON.stringify({ api_key: "changed-prime-key" }));
-
- expect(authStorage.hasAuth("prime-inference")).toBe(true);
- await expect(authStorage.getApiKey("prime-inference")).resolves.toBe("changed-prime-key");
- expect(authStorage.getAuthStatus("prime-inference")).toEqual({
- configured: false,
- source: "prime_cli",
- label: "Prime CLI",
- });
- });
-
- test("setPrimeInferenceApiKey clears stale Prime CLI auth marker", async () => {
- 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.markAuthStale("prime-inference");
-
- authStorage.setPrimeInferenceApiKey("new-prime-key");
-
- expect(authStorage.hasAuth("prime-inference")).toBe(true);
- await expect(authStorage.getApiKey("prime-inference")).resolves.toBe("new-prime-key");
- expect(authStorage.getAuthStatus("prime-inference")).toEqual({
- configured: false,
- source: "prime_cli",
- label: "Prime CLI",
- });
- });
-
test("stored credential updates do not revive stale runtime auth", async () => {
authStorage = AuthStorage.inMemory();
authStorage.setRuntimeApiKey("anthropic", "runtime-key");
@@ -362,454 +263,294 @@ describe("AuthStorage", () => {
expect(authStorage.getAuthStatus("anthropic")).toEqual({ configured: true, source: "stored" });
});
- test("prime inference uses Prime CLI auth over stored 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",
- },
- });
+ describe("Prime Inference isolation", () => {
+ let primeConfigPath: string;
+ const team = { teamId: "agent-team", name: "Agent Research", role: "admin" };
- 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",
- });
- });
-
- test("prime inference uses environment auth over Prime CLI and stored auth", async () => {
- const originalPrimeApiKey = process.env.PRIME_API_KEY;
- const originalPrimeTeamId = process.env.PRIME_TEAM_ID;
- process.env.PRIME_API_KEY = "env-prime-key";
- delete process.env.PRIME_TEAM_ID;
- try {
- const primeConfigPath = join(tempDir, "prime-config.json");
+ beforeEach(() => {
+ vi.stubEnv("PRIME_API_KEY", undefined);
+ vi.stubEnv("PRIME_TEAM_ID", undefined);
+ primeConfigPath = join(tempDir, "prime-config.json");
writeFileSync(
primeConfigPath,
- JSON.stringify({ api_key: "prime-cli-key", team_id: "cli-team", team_name: "CLI Research" }),
+ JSON.stringify({ api_key: "cli-key", team_id: "cli-team", base_url: "http://localhost:8000" }),
);
- writeAuthJson({
- "prime-inference": {
- type: "api_key",
- key: "agent-key",
- primeTeam: { teamId: "stored-team", name: "Stored Research" },
- },
- });
+ });
- authStorage = AuthStorage.create(authJsonPath, {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ function createStorage() {
+ return AuthStorage.create(authJsonPath, {
primeCliConfigPath: primeConfigPath,
usePrimeCliConfig: true,
});
+ }
- await expect(authStorage.getApiKey("prime-inference")).resolves.toBe("env-prime-key");
- expect(authStorage.getAuthStatus("prime-inference")).toEqual({
- configured: false,
- source: "environment",
- label: "PRIME_API_KEY",
- });
+ test("CLI-only credentials never count as Agent auth", async () => {
+ authStorage = createStorage();
+ await expect(authStorage.getApiKey("prime-inference")).resolves.toBeUndefined();
+ expect(authStorage.hasAuth("prime-inference")).toBe(false);
+ expect(authStorage.getAuthStatus("prime-inference")).toEqual({ configured: false });
+ expect(authStorage.getCurrentAuthSourceToken("prime-inference")).toBeUndefined();
+ expect(authStorage.markAuthStale("prime-inference")).toBe(false);
expect(authStorage.getProviderHeaders("prime-inference")).toBeUndefined();
expect(authStorage.getPrimeInferenceTeamSelection()).toBeUndefined();
- } finally {
- if (originalPrimeApiKey === undefined) {
- delete process.env.PRIME_API_KEY;
- } else {
- process.env.PRIME_API_KEY = originalPrimeApiKey;
- }
- if (originalPrimeTeamId === undefined) {
- delete process.env.PRIME_TEAM_ID;
- } else {
- process.env.PRIME_TEAM_ID = originalPrimeTeamId;
- }
- }
- });
-
- 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",
- team_name: "CLI Research",
- team_role: "admin",
- }),
- );
- 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,
- });
-
- expect(authStorage.getProviderHeaders("prime-inference")).toEqual({ "X-Prime-Team-ID": "cli-team" });
- expect(authStorage.getPrimeInferenceTeamSelection()).toEqual({
- teamId: "cli-team",
- name: "CLI Research",
- role: "admin",
- });
- });
-
- 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({
- "prime-inference": {
- type: "api_key",
- key: "agent-key",
- primeTeam: null,
- },
- });
-
- authStorage = AuthStorage.create(authJsonPath, {
- primeCliConfigPath: primeConfigPath,
- usePrimeCliConfig: true,
+ test("stored auth and team survive CLI edits, corruption, removal, and Agent reload", async () => {
+ writeAuthJson({ "prime-inference": { type: "api_key", key: "agent-key", primeTeam: team } });
+ authStorage = createStorage();
+
+ for (const config of [
+ JSON.stringify({ api_key: "new-cli-key", team_id: "new-cli-team" }),
+ "{invalid-json",
+ undefined,
+ ]) {
+ if (config === undefined) rmSync(primeConfigPath);
+ else writeFileSync(primeConfigPath, config);
+ authStorage.reload();
+ await expect(authStorage.getApiKey("prime-inference")).resolves.toBe("agent-key");
+ expect(authStorage.getAuthStatus("prime-inference")).toEqual({ configured: true, source: "stored" });
+ expect(authStorage.getPrimeInferenceTeamSelection()).toEqual(team);
+ expect(authStorage.getProviderHeaders("prime-inference")).toEqual({ "X-Prime-Team-ID": team.teamId });
+ expect(authStorage.drainErrors()).toEqual([]);
+ }
});
- 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,
- },
- });
+ test("runtime, environment, stored, and models fallback resolve in order without CLI", async () => {
+ writeAuthJson({ "prime-inference": { type: "api_key", key: "agent-key", primeTeam: team } });
+ authStorage = createStorage();
+ authStorage.setFallbackResolver(() => "models-key");
+ vi.stubEnv("PRIME_API_KEY", "env-key");
+ authStorage.setRuntimeApiKey("prime-inference", "runtime-key");
- authStorage = AuthStorage.create(authJsonPath, {
- primeCliConfigPath: primeConfigPath,
- usePrimeCliConfig: true,
+ await expect(authStorage.getApiKey("prime-inference")).resolves.toBe("runtime-key");
+ expect(authStorage.getAuthStatus("prime-inference").source).toBe("runtime");
+ expect(authStorage.getPrimeInferenceTeamSelection()).toBeUndefined();
+ expect(authStorage.getProviderHeaders("prime-inference")).toBeUndefined();
+ authStorage.removeRuntimeApiKey("prime-inference");
+ await expect(authStorage.getApiKey("prime-inference")).resolves.toBe("env-key");
+ expect(authStorage.getAuthStatus("prime-inference")).toEqual({
+ configured: false,
+ source: "environment",
+ label: "PRIME_API_KEY",
});
+ expect(authStorage.getPrimeInferenceTeamSelection()).toBeUndefined();
+ expect(authStorage.getProviderHeaders("prime-inference")).toBeUndefined();
+ vi.stubEnv("PRIME_API_KEY", undefined);
+ await expect(authStorage.getApiKey("prime-inference")).resolves.toBe("agent-key");
+ expect(authStorage.getAuthStatus("prime-inference").source).toBe("stored");
+ authStorage.remove("prime-inference");
+ await expect(authStorage.getApiKey("prime-inference")).resolves.toBe("models-key");
+ expect(authStorage.getAuthStatus("prime-inference").source).toBe("fallback");
+ await expect(authStorage.getApiKey("prime-inference", { includeFallback: false })).resolves.toBeUndefined();
+ });
+
+ test.each([undefined, null])("missing or personal Agent team never inherits CLI team (%j)", (primeTeam) => {
+ writeAuthJson({ "prime-inference": { type: "api_key", key: "agent-key", primeTeam } });
+ authStorage = createStorage();
+ expect(authStorage.getPrimeInferenceTeamSelection()).toBe(primeTeam);
+ expect(authStorage.getProviderHeaders("prime-inference")).toBeUndefined();
+ });
+ test("PRIME_TEAM_ID overrides headers without changing the stored selection", () => {
+ writeAuthJson({ "prime-inference": { type: "api_key", key: "agent-key", primeTeam: team } });
+ authStorage = createStorage();
+ vi.stubEnv("PRIME_TEAM_ID", "env-team");
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", () => {
- const primeConfigPath = join(tempDir, "prime-config.json");
- writeFileSync(primeConfigPath, JSON.stringify({ api_key: "prime-cli-key", team_id: "cli-team" }));
- writeAuthJson({
- "prime-inference": {
+ vi.stubEnv("PRIME_TEAM_ID", undefined);
+ expect(authStorage.getPrimeInferenceTeamSelection()).toEqual(team);
+ expect(authStorage.get("prime-inference")).toMatchObject({ primeTeam: team });
+ });
+
+ test("CLI edits cannot revive stale Agent auth or replace its cached team", async () => {
+ writeAuthJson({ "prime-inference": { type: "api_key", key: "agent-key", primeTeam: team } });
+ authStorage = createStorage();
+ expect(authStorage.markAuthStale("prime-inference")).toBe(true);
+ writeFileSync(primeConfigPath, JSON.stringify({ api_key: "fresh-cli-key", team_id: "new-cli-team" }));
+ expect(authStorage.hasAuth("prime-inference")).toBe(false);
+ await expect(authStorage.getApiKey("prime-inference")).resolves.toBeUndefined();
+ expect(authStorage.getAuthStatus("prime-inference")).toEqual({
+ configured: false,
+ source: "stale",
+ label: "expired",
+ });
+ expect(authStorage.getPrimeInferenceTeamSelection()).toEqual(team);
+ authStorage.setPrimeInferenceTeamSelection(null);
+ await expect(authStorage.getApiKey("prime-inference")).resolves.toBeUndefined();
+ expect(authStorage.getAuthStatus("prime-inference").source).toBe("stale");
+ expect(createStorage().getPrimeInferenceTeamSelection()).toBeNull();
+ authStorage.setPrimeInferenceApiKey("fresh-agent-key");
+ await expect(authStorage.getApiKey("prime-inference")).resolves.toBe("fresh-agent-key");
+ expect(authStorage.getAuthStatus("prime-inference")).toEqual({ configured: true, source: "stored" });
+ });
+
+ test("saving an Agent key does not revive stale runtime or environment credentials", async () => {
+ authStorage = createStorage();
+ vi.stubEnv("PRIME_API_KEY", "env-key");
+ authStorage.setRuntimeApiKey("prime-inference", "runtime-key");
+ expect(authStorage.markAuthStale("prime-inference")).toBe(true);
+ expect(authStorage.markAuthStale("prime-inference")).toBe(true);
+ authStorage.setPrimeInferenceApiKey("agent-key");
+ await expect(authStorage.getApiKey("prime-inference")).resolves.toBe("agent-key");
+ authStorage.remove("prime-inference");
+ await expect(authStorage.getApiKey("prime-inference")).resolves.toBeUndefined();
+ vi.stubEnv("PRIME_API_KEY", "fresh-env-key");
+ await expect(authStorage.getApiKey("prime-inference")).resolves.toBe("fresh-env-key");
+ });
+
+ test("login preserves, clears, or replaces team according to key and explicit selection", () => {
+ writeAuthJson({ "prime-inference": { type: "api_key", key: "agent-key", primeTeam: team } });
+ authStorage = createStorage();
+ authStorage.setPrimeInferenceApiKey("agent-key");
+ expect(createStorage().getPrimeInferenceTeamSelection()).toEqual(team);
+ authStorage.setPrimeInferenceApiKey("different-key");
+ expect(createStorage().get("prime-inference")).toEqual({
type: "api_key",
- key: "agent-key",
+ key: "different-key",
+ primeTeam: null,
+ });
+ authStorage.setPrimeInferenceApiKey("imported-key", team);
+ expect(createStorage().getPrimeInferenceTeamSelection()).toEqual(team);
+ authStorage.setPrimeInferenceApiKey("imported-key", null);
+ expect(createStorage().getPrimeInferenceTeamSelection()).toBeNull();
+ });
+
+ test.each(["existing", "missing", "directory"])(
+ "Agent login, team, and logout leave %s CLI config unchanged",
+ async (state) => {
+ if (state !== "existing") rmSync(primeConfigPath);
+ if (state === "directory") mkdirSync(primeConfigPath);
+ const cliState = () => {
+ if (!existsSync(primeConfigPath)) return undefined;
+ return statSync(primeConfigPath).isDirectory() ? "directory" : readFileSync(primeConfigPath, "utf8");
+ };
+ const cliBefore = cliState();
+ authStorage = createStorage();
+ authStorage.setPrimeInferenceApiKey("agent-key", team);
+ expect(cliState()).toBe(cliBefore);
+ expect(statSync(authJsonPath).mode & 0o777).toBe(0o600);
+ const reopened = createStorage();
+ await expect(reopened.getApiKey("prime-inference")).resolves.toBe("agent-key");
+ expect(reopened.getPrimeInferenceTeamSelection()).toEqual(team);
+ authStorage.setPrimeInferenceTeamSelection({ teamId: "new-team", name: "New Team" });
+ expect(createStorage().getPrimeInferenceTeamSelection()?.teamId).toBe("new-team");
+ expect(cliState()).toBe(cliBefore);
+ authStorage.setPrimeInferenceTeamSelection(null);
+ expect(createStorage().getPrimeInferenceTeamSelection()).toBeNull();
+ expect(cliState()).toBe(cliBefore);
+ authStorage.logout("prime-inference");
+ expect(createStorage().has("prime-inference")).toBe(false);
+ await expect(authStorage.getApiKey("prime-inference")).resolves.toBeUndefined();
+ expect(cliState()).toBe(cliBefore);
+ expect(authStorage.drainErrors()).toEqual([]);
},
- });
-
- authStorage = AuthStorage.create(authJsonPath, {
- primeCliConfigPath: primeConfigPath,
- usePrimeCliConfig: true,
- });
-
- expect(authStorage.getProviderHeaders("prime-inference")).toEqual({ "X-Prime-Team-ID": "cli-team" });
- });
-
- 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({});
-
- authStorage = AuthStorage.create(authJsonPath, {
- primeCliConfigPath: primeConfigPath,
- usePrimeCliConfig: true,
- });
-
- 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": {
+ test("key and team changes merge the current disk credential, not a stale instance", () => {
+ writeAuthJson({ "prime-inference": { type: "api_key", key: "agent-key", primeTeam: team } });
+ authStorage = createStorage();
+ const peer = createStorage();
+ const peerTeam = { teamId: "peer-team", name: "Peer Team" };
+ peer.setPrimeInferenceTeamSelection(peerTeam);
+ authStorage.setPrimeInferenceApiKey("agent-key");
+ expect(createStorage().getPrimeInferenceTeamSelection()).toEqual(peerTeam);
+ peer.setPrimeInferenceApiKey("peer-key", team);
+ authStorage.setPrimeInferenceTeamSelection(peerTeam);
+ expect(createStorage().get("prime-inference")).toEqual({
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,
+ key: "peer-key",
+ primeTeam: peerTeam,
+ });
});
- authStorage.setPrimeInferenceApiKey("prime-cli-key");
+ test.each(["rotation", "logout"])("stale team picker cannot overwrite credentials after peer %s", (change) => {
+ writeAuthJson({ "prime-inference": { type: "api_key", key: "old-key", primeTeam: team } });
+ authStorage = createStorage();
+ const peer = createStorage();
+ const newTeam = { teamId: "new-team", name: "New Team" };
+ if (change === "rotation") peer.setPrimeInferenceApiKey("new-key", newTeam);
+ else peer.logout("prime-inference");
- 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" });
- });
-
- 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,
+ for (const selection of [{ teamId: "stale-team", name: "Stale Team" }, null]) {
+ authStorage.setPrimeInferenceTeamSelection(selection, "old-key");
+ expect(createStorage().get("prime-inference")).toEqual(
+ change === "rotation" ? { type: "api_key", key: "new-key", primeTeam: newTeam } : undefined,
+ );
+ }
});
- 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" },
+ test.each(["login", "team", "logout"])(
+ "failed %s leaves disk, memory, stale state, and CLI unchanged",
+ async (operation) => {
+ const credential = { type: "api_key", key: "agent-key", primeTeam: team };
+ writeAuthJson({ "prime-inference": credential });
+ authStorage = createStorage();
+ const beforeAuth = readFileSync(authJsonPath, "utf8");
+ const beforeCli = readFileSync(primeConfigPath, "utf8");
+ expect(authStorage.markAuthStale("prime-inference")).toBe(true);
+ renameFault.error = new Error("disk full");
+ try {
+ expect(() => {
+ if (operation === "login") authStorage.setPrimeInferenceApiKey("new-key");
+ else if (operation === "team") authStorage.setPrimeInferenceTeamSelection(null);
+ else authStorage.logout("prime-inference");
+ }).toThrow("disk full");
+ } finally {
+ renameFault.error = undefined;
+ }
+ expect(authStorage.get("prime-inference")).toEqual(credential);
+ expect(readFileSync(authJsonPath, "utf8")).toBe(beforeAuth);
+ expect(readFileSync(primeConfigPath, "utf8")).toBe(beforeCli);
+ await expect(authStorage.getApiKey("prime-inference")).resolves.toBeUndefined();
+ expect(authStorage.getAuthStatus("prime-inference").source).toBe("stale");
},
- });
-
- 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" },
+ test.each(["[]", "null", '"fake-secret"', "1", "true", "{"])(
+ "invalid Agent auth rejects startup and verified login without changing disk: %s",
+ (content) => {
+ writeFileSync(authJsonPath, content);
+ authStorage = createStorage();
+ expect(authStorage.drainErrors()).toHaveLength(1);
+ expect(authStorage.list()).toEqual([]);
+ expect(() => authStorage.setPrimeInferenceApiKey("replacement")).toThrow();
+ expect(readFileSync(authJsonPath, "utf8")).toBe(content);
+ expect(authStorage.list()).toEqual([]);
},
- });
-
- 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,
+ test("late invalid auth preserves stale identity through failed changes and permits repaired-file retry", () => {
+ const credential = { type: "api_key", key: "agent-key", primeTeam: team };
+ writeAuthJson({ "prime-inference": credential });
+ authStorage = createStorage();
+ expect(authStorage.markAuthStale("prime-inference")).toBe(true);
+ writeFileSync(authJsonPath, "[]");
+ for (const change of [
+ () => authStorage.setPrimeInferenceApiKey("replacement"),
+ () => authStorage.setPrimeInferenceTeamSelection(null, "agent-key"),
+ () => authStorage.logout("prime-inference"),
+ ]) {
+ expect(change).toThrow();
+ expect(readFileSync(authJsonPath, "utf8")).toBe("[]");
+ expect(authStorage.get("prime-inference")).toEqual(credential);
+ expect(authStorage.getAuthStatus("prime-inference").source).toBe("stale");
+ }
+ authStorage.reload();
+ expect(authStorage.get("prime-inference")).toEqual(credential);
+ expect(authStorage.getAuthStatus("prime-inference").source).toBe("stale");
+ writeAuthJson({});
+ authStorage.setPrimeInferenceApiKey("repaired-key");
+ expect(authStorage.getAuthStatus("prime-inference")).toEqual({ configured: true, source: "stored" });
+ expect(createStorage().get("prime-inference")).toEqual({
+ type: "api_key",
+ key: "repaired-key",
+ primeTeam: null,
+ });
});
-
- 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/model-registry.test.ts b/packages/coding-agent/test/model-registry.test.ts
index b8b4f84f7a..d4ee7be4c4 100644
--- a/packages/coding-agent/test/model-registry.test.ts
+++ b/packages/coding-agent/test/model-registry.test.ts
@@ -1626,14 +1626,26 @@ describe("ModelRegistry", () => {
"missing credentials",
"active credentials",
"rotated credentials",
- ] as const)("recovers stale Prime CLI private-model access but invalidates it after %s", async (change) => {
+ ] as const)("recovers stale Prime Agent private-model access but invalidates it after %s", async (change) => {
vi.stubEnv("PRIME_API_KEY", "");
vi.stubEnv("PRIME_TEAM_ID", "");
vi.stubEnv("PI_OFFLINE", "0");
const configPath = join(tempDir, "prime-config.json");
- writeFileSync(configPath, JSON.stringify({ api_key: "prime-test-key", team_id: "team-a" }));
- const cliAuth = AuthStorage.inMemory({}, { primeCliConfigPath: configPath });
- const registry = ModelRegistry.create(cliAuth, modelsJsonPath);
+ writeFileSync(
+ configPath,
+ JSON.stringify({ api_key: "dev-key", team_id: "dev-team", base_url: "http://localhost:8000" }),
+ );
+ const agentAuth = AuthStorage.inMemory(
+ {
+ "prime-inference": {
+ type: "api_key",
+ key: "prime-test-key",
+ primeTeam: { teamId: "team-a", name: "Research" },
+ },
+ },
+ { primeCliConfigPath: configPath, usePrimeCliConfig: true },
+ );
+ const registry = ModelRegistry.create(agentAuth, modelsJsonPath);
const modelId = "internal/live-private-model";
const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(
async () =>
@@ -1658,6 +1670,19 @@ describe("ModelRegistry", () => {
registry.registerProvider("unrelated-extension", { baseUrl: "https://unused.invalid" });
const model = (await registry.refreshAvailableModels()).find((candidate) => candidate.id === modelId)!;
expect(model).toBeDefined();
+ const request = fetchSpy.mock.calls.find(([, init]) => new Headers(init?.headers).has("Authorization"));
+ expect(String(request?.[0])).toBe("https://api.pinference.ai/api/v1/models");
+ expect(new Headers(request?.[1]?.headers).get("Authorization")).toBe("Bearer prime-test-key");
+ writeFileSync(
+ configPath,
+ JSON.stringify({
+ api_key: "changed-dev-key",
+ team_id: "changed-dev-team",
+ base_url: "http://localhost:9000",
+ }),
+ );
+ await expect(agentAuth.getApiKey("prime-inference")).resolves.toBe("prime-test-key");
+ expect(agentAuth.getProviderHeaders("prime-inference")).toEqual({ "X-Prime-Team-ID": "team-a" });
expect(
fetchSpy.mock.calls.filter(([, init]) => new Headers(init?.headers).has("Authorization")),
).toHaveLength(1);
@@ -1668,33 +1693,33 @@ describe("ModelRegistry", () => {
await Promise.all([registry.refreshAvailableModels(), registry.refreshAvailableModels()]);
expect(registry.find("prime-inference", modelId)).toEqual(model);
- expect(cliAuth.getProviderHeaders("prime-inference")).toEqual({ "X-Prime-Team-ID": "team-a" });
+ expect(agentAuth.getProviderHeaders("prime-inference")).toEqual({ "X-Prime-Team-ID": "team-a" });
expect(registry.hasConfiguredAuth(model)).toBe(false);
- await expect(cliAuth.getApiKey("prime-inference")).resolves.toBeUndefined();
+ await expect(agentAuth.getApiKey("prime-inference")).resolves.toBeUndefined();
await expect(registry.canUseModel(model, { assumeAuthConfigured: true })).resolves.toBe(true);
registry.clearProviderAuthStale("prime-inference");
await expect(registry.canUseModel(model)).resolves.toBe(true);
- await expect(cliAuth.getApiKey("prime-inference")).resolves.toBe("prime-test-key");
+ await expect(agentAuth.getApiKey("prime-inference")).resolves.toBe("prime-test-key");
expect(registry.markProviderAuthStale("prime-inference")).toBe(true);
switch (change) {
case "team change":
- cliAuth.setPrimeInferenceTeamSelection({ teamId: "team-b", name: "Other team" });
+ agentAuth.setPrimeInferenceTeamSelection({ teamId: "team-b", name: "Other team" });
break;
case "logout":
- cliAuth.logout("prime-inference");
+ agentAuth.logout("prime-inference");
break;
case "missing team":
- cliAuth.setPrimeInferenceTeamSelection(null);
+ agentAuth.setPrimeInferenceTeamSelection(null);
break;
case "missing credentials":
- writeFileSync(configPath, JSON.stringify({ team_id: "team-a" }));
+ agentAuth.remove("prime-inference");
break;
case "active credentials":
registry.clearProviderAuthStale("prime-inference");
break;
case "rotated credentials":
- writeFileSync(configPath, JSON.stringify({ api_key: "rotated-key", team_id: "team-a" }));
+ agentAuth.setPrimeInferenceApiKey("rotated-key", { teamId: "team-a", name: "Research" });
break;
}
registry.refresh();
diff --git a/packages/coding-agent/test/prime-inference-auth.test.ts b/packages/coding-agent/test/prime-inference-auth.test.ts
index e63024e462..797376ee91 100644
--- a/packages/coding-agent/test/prime-inference-auth.test.ts
+++ b/packages/coding-agent/test/prime-inference-auth.test.ts
@@ -1,6 +1,6 @@
import { Buffer } from "node:buffer";
import { constants, publicEncrypt } from "node:crypto";
-import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -8,9 +8,9 @@ import {
checkPrimeAgentTracesAccess,
checkPrimeInferenceAccess,
fetchPrimeTeams,
- loadPrimeCliConfig,
loginPrimeAgentTraces,
loginPrimeInference,
+ resolvePrimeInferenceAuthConfig,
} from "../src/core/prime-inference-auth.js";
function jsonResponse(body: unknown, status: number = 200): Response {
@@ -68,6 +68,8 @@ describe("Prime Inference auth", () => {
let originalTraceBaseUrl: string | undefined;
beforeEach(() => {
+ vi.stubEnv("PRIME_AGENT_INFERENCE_API_BASE_URL", "");
+ vi.stubEnv("PRIME_AGENT_INFERENCE_FRONTEND_URL", "");
tempDir = join(tmpdir(), `pi-prime-auth-${Date.now()}-${Math.random().toString(36).slice(2)}`);
mkdirSync(tempDir, { recursive: true });
configPath = join(tempDir, "config.json");
@@ -76,6 +78,7 @@ describe("Prime Inference auth", () => {
});
afterEach(() => {
+ vi.unstubAllEnvs();
if (originalTraceBaseUrl === undefined) {
delete process.env.PRIME_AGENT_TRACES_BASE_URL;
} else {
@@ -87,71 +90,33 @@ describe("Prime Inference auth", () => {
vi.restoreAllMocks();
});
- it("loads Prime CLI config with defaults", () => {
- writeFileSync(
- configPath,
- JSON.stringify({
- api_key: "prime-key",
- base_url: "https://prime-api.example/api/v1",
- frontend_url: "https://prime-app.example/",
- }),
- );
-
- expect(loadPrimeCliConfig(configPath)).toEqual({
- apiKey: "prime-key",
- baseUrl: "https://prime-api.example",
- frontendUrl: "https://prime-app.example",
- inferenceUrl: "https://api.pinference.ai/api/v1",
- path: configPath,
- teamIdFromEnv: false,
+ it("imports the production CLI file team without changing it or applying PRIME_TEAM_ID", async () => {
+ vi.stubEnv("PRIME_TEAM_ID", "env-team");
+ const original = JSON.stringify({
+ api_key: "prime-key",
+ base_url: "https://api.primeintellect.ai/api/v1/",
+ frontend_url: "https://app.primeintellect.ai/",
+ inference_url: "https://api.pinference.ai/api/v1/",
+ team_id: "file-team",
+ team_name: "Research",
+ team_role: "admin",
});
- });
-
- it("loads Prime CLI team selection", () => {
- writeFileSync(
- configPath,
- JSON.stringify({
- api_key: "prime-key",
- team_id: "team-1",
- team_name: "Research",
- team_role: "admin",
- }),
- );
+ writeFileSync(configPath, original);
+ const fetchMock = vi.fn(async (input: string | URL | Request, init?: RequestInit): Promise<Response> => {
+ expect(getUrl(input)).toBe("https://api.primeintellect.ai/api/v1/user/whoami");
+ expect(getAuthorization(init)).toBe("Bearer prime-key");
+ return jsonResponse({ data: { scope: { inference: { write: true } } } });
+ });
+ const onAuth = vi.fn();
- expect(loadPrimeCliConfig(configPath)).toMatchObject({
+ await expect(loginPrimeInference({ onAuth }, { configPath, fetchFn: fetchMock })).resolves.toEqual({
apiKey: "prime-key",
- teamId: "team-1",
- teamName: "Research",
- teamRole: "admin",
- teamIdFromEnv: false,
+ source: "prime-cli",
+ primeTeam: { teamId: "file-team", name: "Research", role: "admin" },
});
- });
-
- it("lets PRIME_TEAM_ID override Prime CLI team selection", () => {
- const originalTeamId = process.env.PRIME_TEAM_ID;
- process.env.PRIME_TEAM_ID = "env-team";
- writeFileSync(
- configPath,
- JSON.stringify({
- team_id: "file-team",
- team_name: "Research",
- team_role: "admin",
- }),
- );
-
- try {
- expect(loadPrimeCliConfig(configPath)).toMatchObject({
- teamId: "env-team",
- teamIdFromEnv: true,
- });
- expect(loadPrimeCliConfig(configPath).teamName).toBeUndefined();
- } finally {
- if (originalTeamId === undefined) {
- delete process.env.PRIME_TEAM_ID;
- } else {
- process.env.PRIME_TEAM_ID = originalTeamId;
- }
- }
+ expect(onAuth).not.toHaveBeenCalled();
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(readFileSync(configPath, "utf8")).toBe(original);
});
it("fetches Prime teams across paginated responses", async () => {
@@ -216,7 +181,7 @@ describe("Prime Inference auth", () => {
configPath,
JSON.stringify({
api_key: "prime-cli-key",
- base_url: "https://dev-api.example/api/v1",
+ base_url: "https://api.primeintellect.ai/api/v1",
}),
);
const fetchMock = vi.fn(async (input: string | URL | Request, init?: RequestInit): Promise<Response> => {
@@ -236,30 +201,74 @@ describe("Prime Inference auth", () => {
expect(fetchMock).toHaveBeenCalledOnce();
});
- it("validates imported Prime CLI trace credentials against PRIME_AGENT_TRACES_BASE_URL", async () => {
- process.env.PRIME_AGENT_TRACES_BASE_URL = "https://trace-api.example/api/v1";
- writeFileSync(
- configPath,
- JSON.stringify({
- api_key: "prime-cli-key",
- base_url: "https://dev-api.example/api/v1",
- }),
- );
+ it.each([
+ [
+ "PRIME_AGENT_INFERENCE_API_BASE_URL",
+ "https://custom.example/api/v1/",
+ loginPrimeInference,
+ "https://custom.example",
+ ],
+ [
+ "PRIME_AGENT_INFERENCE_FRONTEND_URL",
+ "https://custom.example/",
+ loginPrimeInference,
+ "https://api.primeintellect.ai",
+ ],
+ [
+ "PRIME_AGENT_TRACES_BASE_URL",
+ "https://custom.example/api/v1/",
+ loginPrimeAgentTraces,
+ "https://custom.example",
+ ],
+ ] as const)("does not import CLI credentials with %s", async (env, value, login, baseUrl) => {
+ vi.stubEnv(env, value);
+ writeFileSync(configPath, JSON.stringify({ api_key: "prime-cli-key" }));
const fetchMock = vi.fn(async (input: string | URL | Request, init?: RequestInit): Promise<Response> => {
- expect(getUrl(input)).toBe("https://trace-api.example/api/v1/user/whoami");
- expect(getAuthorization(init)).toBe("Bearer prime-cli-key");
- return jsonResponse({ data: { scope: { agent_traces: { write: true } } } });
+ expect(getUrl(input)).toBe(`${baseUrl}/api/v1/auth_challenge/generate`);
+ expect(getAuthorization(init)).toBeUndefined();
+ throw new Error("stop before browser");
});
- const onAuth = vi.fn();
-
- const result = await loginPrimeAgentTraces(
- { onAuth },
- { configPath, fetchFn: fetchMock, requestTimeoutMs: 1000 },
+ await expect(login({ onAuth: vi.fn() }, { configPath, fetchFn: fetchMock })).rejects.toThrow(
+ "stop before browser",
);
+ expect(fetchMock).toHaveBeenCalledOnce();
+ });
- expect(result).toEqual({ apiKey: "prime-cli-key", source: "prime-cli" });
- expect(onAuth).not.toHaveBeenCalled();
+ it.each([
+ { base_url: "https://dev.example" },
+ { frontend_url: "https://dev.example" },
+ { inference_url: "https://dev.example" },
+ { base_url: null },
+ ])("rejects ineligible CLI URLs %j without sending its key", async (urls) => {
+ const original = JSON.stringify({ api_key: "dev-key", ...urls });
+ writeFileSync(configPath, original);
+ const fetchMock = vi.fn(async (input: string | URL | Request, init?: RequestInit): Promise<Response> => {
+ expect(getUrl(input)).toBe("https://api.primeintellect.ai/api/v1/auth_challenge/generate");
+ expect(getAuthorization(init)).toBeUndefined();
+ throw new Error("stop before browser");
+ });
+ await expect(loginPrimeInference({ onAuth: vi.fn() }, { configPath, fetchFn: fetchMock })).rejects.toThrow(
+ "stop before browser",
+ );
expect(fetchMock).toHaveBeenCalledOnce();
+ expect(readFileSync(configPath, "utf8")).toBe(original);
+ });
+
+ it("normalizes Agent-only auth endpoints independently of unrelated settings", () => {
+ vi.stubEnv("PRIME_AGENT_INFERENCE_API_BASE_URL", " ");
+ vi.stubEnv("PRIME_AGENT_INFERENCE_FRONTEND_URL", " ");
+ vi.stubEnv("PRIME_API_BASE_URL", "https://unrelated.example");
+ vi.stubEnv("PRIME_AGENT_TRACES_BASE_URL", "https://traces.example");
+ expect(resolvePrimeInferenceAuthConfig()).toEqual({
+ baseUrl: "https://api.primeintellect.ai",
+ frontendUrl: "https://app.primeintellect.ai",
+ });
+ vi.stubEnv("PRIME_AGENT_INFERENCE_API_BASE_URL", " https://custom.example/api/v1/ ");
+ vi.stubEnv("PRIME_AGENT_INFERENCE_FRONTEND_URL", " https://app.example/ ");
+ expect(resolvePrimeInferenceAuthConfig()).toEqual({
+ baseUrl: "https://custom.example",
+ frontendUrl: "https://app.example",
+ });
});
it("throws contextual errors for invalid Prime whoami JSON", async () => {
@@ -286,7 +295,7 @@ describe("Prime Inference auth", () => {
const result = await loginPrimeInference({ onAuth }, { configPath, fetchFn: fetchMock, requestTimeoutMs: 1000 });
- expect(result).toEqual({ apiKey: "prime-cli-key", source: "prime-cli" });
+ expect(result).toEqual({ apiKey: "prime-cli-key", source: "prime-cli", primeTeam: null });
expect(onAuth).not.toHaveBeenCalled();
expect(fetchMock).toHaveBeenCalledOnce();
});
@@ -319,15 +328,15 @@ describe("Prime Inference auth", () => {
configPath,
JSON.stringify({
api_key: "old-key",
- base_url: "https://prime-api.example",
- frontend_url: "https://prime-app.example",
- inference_url: "https://pinference.example/api/v1",
+ base_url: "https://api.primeintellect.ai",
+ frontend_url: "https://app.primeintellect.ai",
+ inference_url: "https://api.pinference.ai/api/v1",
}),
);
let challengePublicKey = "";
const fetchMock = vi.fn(async (input: string | URL | Request, init?: RequestInit): Promise<Response> => {
const url = getUrl(input);
- if (url === "https://prime-api.example/api/v1/user/whoami") {
+ if (url === "https://api.primeintellect.ai/api/v1/user/whoami") {
const auth = getAuthorization(init);
if (auth === "Bearer old-key") {
return jsonResponse({ data: { scope: { inference: { read: true, write: false } } } });
@@ -336,11 +345,11 @@ describe("Prime Inference auth", () => {
return jsonResponse({ data: { scope: { inference: { read: true, write: true } } } });
}
}
- if (url === "https://prime-api.example/api/v1/auth_challenge/generate") {
+ if (url === "https://api.primeintellect.ai/api/v1/auth_challenge/generate") {
challengePublicKey = String(getJsonBody(init).encryptionPublicKey);
return jsonResponse({ challenge: "challenge-code", status_auth_token: "status-token" });
}
- if (url.startsWith("https://prime-api.example/api/v1/auth_challenge/status")) {
+ if (url.startsWith("https://api.primeintellect.ai/api/v1/auth_challenge/status")) {
expect(getAuthorization(init)).toBe("Bearer status-token");
return jsonResponse({ result: encryptChallengeResult(challengePublicKey, "browser-key") });
}
@@ -359,7 +368,7 @@ describe("Prime Inference auth", () => {
expect(result).toEqual({ apiKey: "browser-key", source: "browser" });
expect(onAuth).toHaveBeenCalledWith({
- url: "https://prime-app.example/dashboard/tokens/challenge?code=challenge-code",
+ url: "https://app.primeintellect.ai/dashboard/tokens/challenge?code=challenge-code",
instructions: "Code: challenge-code",
});
expect(progress.join("\n")).toContain("Existing Prime CLI key cannot access Prime Inference");
@@ -402,19 +411,19 @@ describe("Prime Inference auth", () => {
expect(result).toEqual({ apiKey: "trace-key", source: "browser" });
expect(onAuth).toHaveBeenCalledWith({
- url: "https://prime-app.example/dashboard/tokens/challenge?code=challenge-code&scope=agent_traces",
+ url: "https://app.primeintellect.ai/dashboard/tokens/challenge?code=challenge-code&scope=agent_traces",
instructions: "Code: challenge-code",
});
});
it("rejects an expired browser challenge", async () => {
- writeFileSync(configPath, JSON.stringify({ base_url: "https://prime-api.example" }));
+ writeFileSync(configPath, JSON.stringify({ base_url: "https://api.primeintellect.ai" }));
const fetchMock = vi.fn(async (input: string | URL | Request): Promise<Response> => {
const url = getUrl(input);
- if (url === "https://prime-api.example/api/v1/auth_challenge/generate") {
+ if (url === "https://api.primeintellect.ai/api/v1/auth_challenge/generate") {
return jsonResponse({ challenge: "challenge-code", status_auth_token: "status-token" });
}
- if (url.startsWith("https://prime-api.example/api/v1/auth_challenge/status")) {
+ if (url.startsWith("https://api.primeintellect.ai/api/v1/auth_challenge/status")) {
return new Response("expired", { status: 404 });
}
throw new Error(`Unexpected fetch URL: ${url}`);
diff --git a/packages/coding-agent/test/suite/agent-session-runtime.test.ts b/packages/coding-agent/test/suite/agent-session-runtime.test.ts
index cfe1b5f162..5e8194b6d8 100644
--- a/packages/coding-agent/test/suite/agent-session-runtime.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-runtime.test.ts
@@ -457,6 +457,10 @@ describe("AgentSessionRuntime characterization", () => {
it("keeps semantic spawn lineage through the production runtime factory", async () => {
const tempDir = join(tmpdir(), `pi-runtime-factory-${Date.now()}-${Math.random().toString(36).slice(2)}`);
+ vi.stubEnv("HOME", tempDir);
+ cleanups.push(() => {
+ vi.unstubAllEnvs();
+ });
mkdirSync(tempDir, { recursive: true });
cleanups.push(() => rmSync(tempDir, { recursive: true, force: true }));
const faux = registerFauxProvider({ models: [{ id: "faux-1", reasoning: false }] });
@@ -517,6 +521,8 @@ describe("AgentSessionRuntime characterization", () => {
},
});
cleanups.push(() => created.session.dispose());
+ expect(created.services.modelRegistry.authStorage).toBe(created.services.authStorage);
+ expect(created.services.authStorage.getPrimeCliConfigPath()).toBe(join(tempDir, ".prime", "config.json"));
await created.session.bindExtensions({});
const ledgerPath = join(childSessionDir, SEMANTIC_EDGES_LEDGER_FILENAME);