feat(backend): let pi self-authenticate providers from its own auth store

The backend injects a single managed model key (THT_MODEL_API_KEY[_FILE]) as
the selected provider's env var, but that key belongs to one provider — so
selecting a second cloud provider (e.g. DeepSeek while the managed key is zai's)
forced the wrong key onto it and failed auth. This is why the model could not be
switched to DeepSeek.

When the selected provider is present in pi's own auth store
(~/.pi/agent/auth.json), skip injection and let pi resolve that provider's key
itself. Deployments without an auth store (containers) yield an empty set, so the
managed-key injection stays authoritative and fail-fast there. authProviders is
injectable into PiProcessManager for deterministic tests.

Verified live: GLM 5.2, DeepSeek V4 Flash, and aritmolab Qwen3.6 all operate through the ThothII model selector.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-17 18:26:18 +02:00
co-authored by Claude Opus 4.8
parent bd7fa6d2c1
commit c5fd03ed84
5 changed files with 120 additions and 2 deletions
+32
View File
@@ -0,0 +1,32 @@
import { readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
/**
* Providers pi can authenticate on its own from `~/.pi/agent/auth.json`.
*
* The backend injects a single managed model key (`THT_MODEL_API_KEY[_FILE]`),
* which belongs to exactly one provider. Forcing that one key onto a different
* provider's credential variable breaks its auth. So when the selected provider
* is present in pi's own auth store, the backend skips injection and lets pi
* resolve that provider's key itself. An absent/malformed store (e.g. a
* containerized deployment that ships no auth.json) yields an empty set, which
* keeps the managed-key path authoritative there.
*/
export function loadPiAuthProviders(
opts: { agentDir?: string; read?: (path: string) => string } = {},
): Set<string> {
const agentDir = opts.agentDir ?? join(homedir(), ".pi", "agent");
const read = opts.read ?? ((path: string) => readFileSync(path, "utf8"));
try {
const raw: unknown = JSON.parse(read(join(agentDir, "auth.json")));
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return new Set();
return new Set(
Object.keys(raw as Record<string, unknown>)
.map((key) => key.trim().toLowerCase())
.filter((key) => key.length > 0),
);
} catch {
return new Set();
}
}
+8 -1
View File
@@ -4,6 +4,7 @@ import { RpcClient } from "../rpc/rpc-client.js";
import { SessionBridge } from "../bridge/session-bridge.js";
import type { ThtRunner } from "../tht/tht-runner.js";
import { buildPiChildEnv, canonicalPiProvider } from "./provider-credentials.js";
import { loadPiAuthProviders } from "./auth-providers.js";
import { secretValue } from "../config/secret-bundle.js";
import { clearPrincipalEnvironment, principalEnvironment, type PrincipalContext } from "../auth/principal.js";
@@ -35,8 +36,13 @@ export class PiProcessManager {
private spawnFn: (
sessionId: string, author: string, provider: string | undefined, principal?: PrincipalContext,
) => ChildProcessWithoutNullStreams;
private loadAuthProviders: () => ReadonlySet<string>;
constructor(private cfg: AppConfig, opts?: { spawnFn?: SpawnFn }) {
constructor(
private cfg: AppConfig,
opts?: { spawnFn?: SpawnFn; authProviders?: () => ReadonlySet<string> },
) {
this.loadAuthProviders = opts?.authProviders ?? (() => loadPiAuthProviders());
if (opts?.spawnFn) {
this.spawnFn = (sessionId, author, provider, principal) =>
this.spawnPi(opts.spawnFn!, sessionId, author, provider, principal);
@@ -51,6 +57,7 @@ export class PiProcessManager {
): ChildProcessWithoutNullStreams {
const env = buildPiChildEnv({
provider,
authProviders: this.loadAuthProviders(),
credentialValue: secretValue(this.cfg, "THT_MODEL_API_KEY"),
credentialFile: this.cfg.modelApiKeyFile,
additions: { THT_SESSION: sessionId, THT_AUTHOR: author },
+10
View File
@@ -105,6 +105,13 @@ export function buildPiChildEnv(opts: {
additions?: NodeJS.ProcessEnv;
credentialValue?: string;
fsOps?: CredentialFsOps;
/**
* Providers pi can authenticate from its own auth store. For these, the single
* managed key is NOT injected (it belongs to one provider and would misauth the
* others); pi resolves the key itself. Empty/absent in deployments without a pi
* auth store, keeping the managed-key path authoritative there.
*/
authProviders?: ReadonlySet<string>;
}): NodeJS.ProcessEnv {
const env = { ...(opts.ambient ?? process.env), ...opts.additions };
delete env.PI_PROVIDER_API_KEY;
@@ -145,6 +152,9 @@ export function buildPiChildEnv(opts: {
);
}
if (provider && !LOCAL_PROVIDERS.has(provider)) {
// pi self-authenticates this provider from its own auth store; injecting the
// single managed key here would force one provider's key onto another.
if (opts.authProviders?.has(provider)) return env;
const envName = PROVIDER_KEY_ENV[provider];
if (!envName || (!opts.credentialFile && opts.credentialValue === undefined)) {
throw new Error("model provider credential is unavailable");