@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
1,090 lines • 48.5 kB
JavaScript
/**
* CredentialStore implementation backed by auth.json.
* Provider auth orchestration belongs to ModelRuntime and pi-ai Models.
*/
import { findEnvKeys, getEnvApiKey, readByProviderId, refreshOAuthCredential } from "@earendil-works/pi-ai";
import { slotKind, unusedSlotKinds } from "@earendil-works/pi-ai/auth/pool/kinds";
import { stampLogin } from "@earendil-works/pi-ai/auth/pool/login-id";
import { appendLoginSlot, listSlots, projectSlot, removeSlot, repairManagedSentinelSlots, upsertSlot, } from "@earendil-works/pi-ai/auth/pool/slots";
import { builtinProviders } from "@earendil-works/pi-ai/providers/all";
import { readFile } from "fs/promises";
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "fs";
import { createHash } from "node:crypto";
import { dirname, join } from "path";
import lockfile from "proper-lockfile";
import { getAgentDir } from "../config.js";
import { raceWithAbortSignal } from "../utils/abort.js";
import { getFileContentRevision, normalizePath } from "../utils/paths.js";
import { stripBom } from "../utils/text.js";
import { signOutLegacyClaudeLogins } from "./anthropic-legacy-sign-out.js";
import { resolveReadOnlyCredential, resolveStoredCredential, resolveStoredSlot, validateReadOnlyAuthData, } from "./auth-credential-values.js";
import { migrateLegacyProviderKeys } from "./auth-provider-key-migration.js";
import { describeAuthStoreLoadFailure, failureAfterRead, parseAuthDocument, } from "./auth-store-load-error.js";
import { ANTHROPIC_SUBSCRIPTION_PROVIDER_ID } from "./extensions/builtin/anthropic-subscription/provider-id.js";
import { signInRequiredAccounts, signInRequiredMessage, } from "./extensions/builtin/anthropic-subscription/sign-in-again.js";
import { lockWithLossHandling } from "./file-lock.js";
import { CredentialStoreBusyError, FILE_STORAGE_LOCK_OPTIONS, FILE_STORAGE_LOCK_RETRY_BUDGET_MS, FILE_STORAGE_LOCK_RETRY_MAX_DELAY_MS, FILE_STORAGE_LOCK_RETRY_MIN_DELAY_MS, FILE_STORAGE_SYNC_LOCK_BUDGET_MS, isLockError, } from "./lockfile-policy.js";
/**
* Heals pools poisoned by a shipped build that stored a provider-owned pool's
* flat sentinel as a generated `login-N` slot. Such a slot resolves to sentinel
* material, fails the provider's auth `check`, and hard-errors every request
* whose affinity picks it - deterministically, for the lifetime of the entry -
* so it is dropped the moment auth.json is read and the repair is written back
* once by the mutable store.
*/
function repairPoisonedPoolSlots(data) {
let repaired;
for (const [providerId, credential] of Object.entries(data)) {
if (typeof credential !== "object" || credential === null)
continue;
const healed = repairManagedSentinelSlots(providerId, credential);
if (!healed)
continue;
repaired ??= { ...data };
repaired[providerId] = healed;
}
return repaired ? { data: repaired, repaired: true } : { data, repaired: false };
}
const KIND_LABEL = { oauth: "OAuth login", api_key: "API key" };
/**
* One notice per provider whose stored credential holds slots its type cannot use (senpi#3448).
* Nothing is changed: which credential pays stays the user's choice, so the notice names the
* unused login, where it still is, and the action that switches to it.
*/
function unusedLoginNotices(data) {
const notices = [];
for (const [provider, credential] of Object.entries(data)) {
if (typeof credential !== "object" || credential === null)
continue;
for (const kind of unusedSlotKinds(credential)) {
const slots = listSlots(credential).filter((slot) => slotKind(slot) === kind);
const inUse = KIND_LABEL[credential.type];
const names = slots.map((slot) => slot.name);
notices.push({
// Slot names, never key material: a new unused login gets a new id and is shown again.
id: `${provider}:${kind}:${names.join(",")}`,
provider,
message: `${provider}: an ${KIND_LABEL[kind]} saved earlier is stored next to your ${inUse} but is never used; the ${inUse} stays in use. It is still in auth.json (${slots.map((slot) => slot.name).join(", ")}); to switch to it, save it again with /login (the ${inUse} is backed up first).`,
});
}
}
return notices;
}
/**
* One notice, at every start, while Claude subscription accounts from the retired sign-in still need a sign-in again
* (senpi#4436); it repeats until they are signed in again or removed, so it is never marked seen.
*/
function signInRequiredNotices(data) {
const subscription = data[ANTHROPIC_SUBSCRIPTION_PROVIDER_ID];
const accounts = Array.isArray(subscription?.accounts) ? subscription.accounts : [];
const required = signInRequiredAccounts(accounts);
const names = required.map((entry) => entry.name);
if (names.length === 0)
return [];
return [
{
id: `${ANTHROPIC_SUBSCRIPTION_PROVIDER_ID}:sign-in-required:${names.join(",")}`,
provider: ANTHROPIC_SUBSCRIPTION_PROVIDER_ID,
message: signInRequiredMessage(required),
repeats: true,
},
];
}
/** What a login that replaced a credential of the other kind tells the user (senpi#3448, #3486). */
export function describeCredentialReplacement(provider, replacement) {
const where = replacement.backupPath ? ` It is saved in ${replacement.backupPath}` : " It was not backed up";
return `Your ${KIND_LABEL[replacement.replaced]} for ${provider} was replaced by this login.${where}; to switch back, log in with it again.`;
}
// Every write stages a fresh 0o600 file and renames it over the store, so the
// credential file is never briefly world-readable and never half-written; the
// restrictive mode also wins over any wider mode an earlier direct write left.
const AUTH_FILE_WRITE_OPTIONS = { encoding: "utf-8", mode: 0o600 };
let sharedAuthFileReadState;
export class FileAuthStorageBackend {
constructor(authPath = join(getAgentDir(), "auth.json")) {
this.authPath = normalizePath(authPath);
}
ensureParentDir() {
const dir = dirname(this.authPath);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true, mode: 0o700 });
}
}
ensureFileExists() {
if (!existsSync(this.authPath)) {
writeFileSync(this.authPath, "{}", AUTH_FILE_WRITE_OPTIONS);
}
}
/**
* Atomic credential write: stage a 0o600 temp file beside the store and
* rename it over the target. An existing store may carry an
* administrator-set mode; it is copied onto the temp before the rename, so
* preservation matches the previous in-place write (whose mode applied only
* on creation) and the staged bytes are never wider than the file already
* was. Cross-process writers are serialized by the proper-lockfile lock the
* caller already holds, so the pid-suffixed temp cannot collide; a crashed
* write leaves at worst a 0o600 temp behind.
*/
writeAuthFile(content) {
const temporary = `${this.authPath}.${process.pid}.tmp`;
try {
writeFileSync(temporary, content, AUTH_FILE_WRITE_OPTIONS);
if (existsSync(this.authPath)) {
chmodSync(temporary, statSync(this.authPath).mode & 0o777);
}
renameSync(temporary, this.authPath);
}
catch (error) {
try {
rmSync(temporary, { force: true });
}
catch {
// Best effort; a stale temp is already 0o600.
}
throw error;
}
}
acquireLockSyncWithRetry(path) {
const startedAt = Date.now();
let attempt = 0;
while (true) {
try {
return lockfile.lockSync(path, { ...FILE_STORAGE_LOCK_OPTIONS, retries: 0 });
}
catch (error) {
if (!isLockError(error))
throw error;
const waitedMs = Date.now() - startedAt;
if (waitedMs >= FILE_STORAGE_SYNC_LOCK_BUDGET_MS) {
throw new CredentialStoreBusyError(path, waitedMs, error);
}
const delayMs = Math.min(FILE_STORAGE_LOCK_RETRY_MIN_DELAY_MS * 2 ** attempt, FILE_STORAGE_LOCK_RETRY_MAX_DELAY_MS, FILE_STORAGE_SYNC_LOCK_BUDGET_MS - waitedMs);
attempt++;
const sleeper = new Int32Array(new SharedArrayBuffer(4));
Atomics.wait(sleeper, 0, 0, delayMs);
}
}
}
withLock(fn) {
this.ensureParentDir();
this.ensureFileExists();
let release;
try {
release = this.acquireLockSyncWithRetry(this.authPath);
const current = existsSync(this.authPath) ? readFileSync(this.authPath, "utf-8") : undefined;
const { result, next } = fn(current);
if (next !== undefined) {
this.writeAuthFile(next);
}
return result;
}
finally {
if (release) {
release();
}
}
}
async acquireLockAsync(signal, onCompromised, path = this.authPath, budgetMs = FILE_STORAGE_LOCK_RETRY_BUDGET_MS) {
signal?.throwIfAborted();
const startedAt = Date.now();
let attempt = 0;
// The retry loop stays here rather than delegating to proper-lockfile's own
// `retries`, so an abort is observed between attempts instead of after the
// whole budget, and `onCompromised` is rebound per attempt.
while (true) {
try {
const { release } = await lockWithLossHandling(path, {
...FILE_STORAGE_LOCK_OPTIONS,
retries: 0,
onLost: onCompromised,
});
if (signal?.aborted) {
await release();
signal.throwIfAborted();
}
return release;
}
catch (error) {
signal?.throwIfAborted();
if (!isLockError(error))
throw error;
const waitedMs = Date.now() - startedAt;
if (waitedMs >= budgetMs) {
throw new CredentialStoreBusyError(path, waitedMs, error);
}
const delayMs = Math.min(FILE_STORAGE_LOCK_RETRY_MIN_DELAY_MS * 2 ** attempt, FILE_STORAGE_LOCK_RETRY_MAX_DELAY_MS, budgetMs - waitedMs);
attempt++;
await raceWithAbortSignal(new Promise((resolve) => setTimeout(resolve, delayMs)), signal);
}
}
}
async withRefreshLock(providerId, slotName, fn, options) {
this.ensureParentDir();
const identity = createHash("sha256")
.update(JSON.stringify([providerId, slotName]))
.digest("hex");
const path = `${this.authPath}.refresh-${identity}`;
const lost = new AbortController();
const signal = options?.signal ? AbortSignal.any([options.signal, lost.signal]) : lost.signal;
// The normal 5.5s write-lock budget is shorter than a token exchange.
// This independent lock may wait for the full 15s exchange plus persistence.
const release = await this.acquireLockAsync(signal, (error) => lost.abort(error), path, 30_000);
try {
signal.throwIfAborted();
const result = await fn(signal);
lost.signal.throwIfAborted();
return result;
}
finally {
await release();
}
}
/**
* `writeAuthFile` for an async writer: on Windows a rename over a file another process holds open
* fails with EPERM, EACCES or EBUSY until that handle closes, so wait it out between attempts,
* within the async lock budget (#6849 review L4). Other errors, and every error elsewhere, throw.
*/
async writeAuthFileWhenFree(content, checkLock, signal) {
const startedAt = Date.now();
for (let attempt = 0;; attempt++) {
// Every attempt is made under the lock: one lost during a wait writes nothing (#6849 review L5).
checkLock();
try {
this.writeAuthFile(content);
return;
}
catch (error) {
const code = error.code;
const held = process.platform === "win32" && (code === "EPERM" || code === "EACCES" || code === "EBUSY");
const waitedMs = Date.now() - startedAt;
if (!held || waitedMs >= FILE_STORAGE_LOCK_RETRY_BUDGET_MS)
throw error;
signal?.throwIfAborted();
const delayMs = Math.min(FILE_STORAGE_LOCK_RETRY_MIN_DELAY_MS * 2 ** attempt, FILE_STORAGE_LOCK_RETRY_MAX_DELAY_MS, FILE_STORAGE_LOCK_RETRY_BUDGET_MS - waitedMs);
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
}
}
async withLockAsync(fn, options) {
options?.signal?.throwIfAborted();
this.ensureParentDir();
this.ensureFileExists();
let release;
let lockCompromised = false;
let lockCompromisedError;
const throwIfCompromised = () => {
if (lockCompromised) {
throw lockCompromisedError ?? new Error("Auth storage lock was compromised");
}
};
try {
release = await this.acquireLockAsync(options?.signal, (error) => {
lockCompromised = true;
lockCompromisedError = error;
});
throwIfCompromised();
options?.signal?.throwIfAborted();
const current = existsSync(this.authPath) ? readFileSync(this.authPath, "utf-8") : undefined;
const { result, next } = await fn(current);
throwIfCompromised();
options?.signal?.throwIfAborted();
if (next !== undefined) {
await this.writeAuthFileWhenFree(next, throwIfCompromised, options?.signal);
}
throwIfCompromised();
return result;
}
finally {
if (release) {
try {
await release();
}
catch {
// Ignore unlock errors when lock is compromised.
}
}
}
}
}
export class ReadOnlyAuthStorage {
constructor(authPath = join(getAgentDir(), "auth.json")) {
this.authPath = normalizePath(authPath);
}
load() {
if (this.data)
return this.data;
let parsed;
try {
parsed = JSON.parse(stripBom(readFileSync(this.authPath, "utf-8")));
}
catch (error) {
if (error.code === "ENOENT") {
this.data = {};
return this.data;
}
throw new Error(`Failed to read auth.json: ${error instanceof Error ? error.message : String(error)}`);
}
validateReadOnlyAuthData(parsed);
this.data = repairPoisonedPoolSlots(parsed).data;
return this.data;
}
async read(providerId, options) {
options?.signal?.throwIfAborted();
// Read boundary (senpi#1989): an auth.json written by an earlier version is
// keyed by the legacy provider id. Try the canonical key first, then the
// legacy spelling, so a credential is never reported missing after the
// rename. Nothing is rewritten here.
const credential = readByProviderId(this.load(), providerId);
options?.signal?.throwIfAborted();
return resolveReadOnlyCredential(credential, providerId, this.authPath);
}
async readSlot(providerId, slotName, options) {
options?.signal?.throwIfAborted();
const credential = readByProviderId(this.load(), providerId);
options?.signal?.throwIfAborted();
return resolveStoredSlot(credential, { providerId, slotName, authPath: this.authPath }, (flat) => resolveReadOnlyCredential(flat, providerId, this.authPath));
}
async list(options) {
options?.signal?.throwIfAborted();
const credentials = Object.entries(this.load()).map(([providerId, credential]) => ({
providerId,
type: credential.type,
}));
options?.signal?.throwIfAborted();
return credentials;
}
async modify(_providerId, _fn, _options) {
throw new Error("Read-only credential storage cannot modify auth.json");
}
async delete(_providerId, _options) {
throw new Error("Read-only credential storage cannot modify auth.json");
}
}
export class InMemoryAuthStorageBackend {
constructor() {
this.asyncChain = Promise.resolve();
}
withLock(fn) {
const { result, next } = fn(this.value);
if (next !== undefined) {
this.value = next;
}
return result;
}
withLockAsync(fn, options) {
const previous = this.asyncChain;
const operation = (async () => {
await previous.catch(() => { });
options?.signal?.throwIfAborted();
const { result, next } = await fn(this.value);
options?.signal?.throwIfAborted();
if (next !== undefined) {
this.value = next;
}
return result;
})();
this.asyncChain = operation.catch(() => { });
return raceWithAbortSignal(operation, options?.signal);
}
}
/**
* Credential storage backed by a JSON file.
*/
export class AuthStorage {
constructor(storage, authPath) {
this.data = {};
this.runtimeOverrides = new Map();
this.extensionOAuthProviders = new Map();
this.errors = [];
this.reportedMigrationSkips = new Set();
this.notices = [];
this.seenInMemory = new Set();
this.takenNotices = new Set();
this.replacements = new Map();
this.busyReads = 0;
this.dataLoaded = false;
this.dataFromBusyRead = false;
this.storage = storage;
this.authPath = authPath;
const refreshLock = storage.withRefreshLock?.bind(storage);
if (refreshLock) {
this.withRefreshLock = (providerId, slotName, fn, options) => refreshLock(providerId, slotName, async (signal) => {
// A best-effort cached read is not safe after a rotating-token
// waiter acquires its lock: reload strictly or fail before exchange.
await this.reloadFromStorageAsync({ signal });
return fn(signal);
}, options);
}
this.readState =
authPath && sharedAuthFileReadState?.authPath === authPath ? sharedAuthFileReadState.readState : { data: {} };
if (authPath && !sharedAuthFileReadState) {
sharedAuthFileReadState = { authPath, readState: this.readState };
}
if (authPath && this.readState.loaded) {
// Another instance already loaded this store: start from its credentials, not an
// empty snapshot, so a busy read below keeps them. A repaired or migrated load
// leaves the revision unset, so only an exact revision match skips the re-read.
this.data = this.readState.data;
this.dataLoaded = true;
const revision = getFileContentRevision(authPath);
if (revision !== undefined && revision === this.readState.revision)
return;
}
this.reload();
}
static create(authPath = join(getAgentDir(), "auth.json")) {
const normalizedAuthPath = normalizePath(authPath);
return new AuthStorage(new FileAuthStorageBackend(normalizedAuthPath), normalizedAuthPath);
}
getStoragePath() {
return this.authPath;
}
static fromStorage(storage) {
return new AuthStorage(storage);
}
static inMemory(data = {}) {
const storage = new InMemoryAuthStorageBackend();
storage.withLock(() => ({ result: undefined, next: JSON.stringify(data, null, 2) }));
return AuthStorage.fromStorage(storage);
}
parseStorageData(content) {
if (!content)
return {};
// Mutation paths keep the stored keys as-is: the key migration (and its
// pre-write backup) belongs to the load seam, so a write can never drop a
// legacy entry without the backup that preserves it.
return repairPoisonedPoolSlots(parseAuthDocument(content)).data;
}
/**
* Reports whether the parse healed poisoned pool slots or moved legacy
* provider keys, so a load can write the result back exactly once. Repair
* runs FIRST, while the entry still sits under its legacy key, so poisoned
* sentinel slots heal with old-key derivation semantics; the sentinel
* matcher accepts legacy materials too, so a later load of an already
* migrated credential heals the same way.
*/
parseStorageContent(content) {
if (!content) {
return { data: {}, repaired: false, migrated: false };
}
const repaired = repairPoisonedPoolSlots(parseAuthDocument(content));
const migrated = migrateLegacyProviderKeys(repaired.data);
const moved = signOutLegacyClaudeLogins(migrated.data);
if (moved.skipped && !this.reportedMigrationSkips.has(moved.skipped)) {
this.reportedMigrationSkips.add(moved.skipped);
this.recordError(new Error(`A Claude login in auth.json was left unchanged because ${moved.skipped}. Claude logins from the old sign-in are no longer used; sign in again with Claude: run /login anthropic-subscription.`));
}
this.notices = [...unusedLoginNotices(moved.data), ...signInRequiredNotices(moved.data)];
return {
data: moved.data,
repaired: repaired.repaired,
migrated: migrated.migrated || moved.migrated,
};
}
recordError(error) {
this.errors.push(error instanceof Error ? error : new Error(String(error)));
}
/**
* Timestamped 0o600 copy of the pre-migration bytes, written inside the
* held store lock before the migrated document replaces them. A migration
* re-run after a crash between backup and rewrite writes another backup;
* the loop suffix keeps same-millisecond names from overwriting each other.
*/
backupAuthFile(content) {
if (!this.authPath || content === undefined)
return undefined;
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
let backupPath = `${this.authPath}.backup-${stamp}`;
for (let attempt = 1; existsSync(backupPath); attempt++) {
backupPath = `${this.authPath}.backup-${stamp}-${attempt}`;
}
writeFileSync(backupPath, content, AUTH_FILE_WRITE_OPTIONS);
return backupPath;
}
updateReadState(data, revision) {
this.data = data;
this.dataLoaded = true;
this.dataFromBusyRead = false;
this.loadError = undefined;
this.readState.data = data;
this.readState.loaded = true;
this.readState.revision = revision;
}
/** The shared read state holds the store's current contents: this instance answers from it again. */
adoptReadState(data) {
this.data = data;
this.dataLoaded = true;
this.dataFromBusyRead = false;
this.loadError = undefined;
return data;
}
/** A sync write that parsed and saved the locked store proves it loads again. */
writeLocked(fn) {
const result = this.storage.withLock(fn);
this.loadError = undefined;
return result;
}
/**
* Reload credentials from storage.
*/
reload() {
let data = {};
let revision;
const load = { parsed: false, writeBack: false };
try {
this.storage.withLock((current) => {
const parsed = this.parseStorageContent(current);
load.parsed = true;
load.writeBack = parsed.repaired || parsed.migrated;
data = parsed.data;
// A written repair or migration invalidates the revision read before
// it; leaving it unset makes the next reader re-read instead of
// trusting a stale stamp.
revision =
parsed.repaired || parsed.migrated || !this.authPath ? undefined : getFileContentRevision(this.authPath);
if (parsed.migrated)
this.backupAuthFile(current);
return parsed.repaired || parsed.migrated
? { result: undefined, next: JSON.stringify(parsed.data, null, 2) }
: { result: undefined };
});
this.updateReadState(data, revision);
return "loaded";
}
catch (rawError) {
const error = failureAfterRead(rawError, load);
const recorded = this.noteLoadFailure(error);
// auth.json parsed and only a later step failed (a write-back or a lost lock): its parsed
// credentials stand, as on the async path. A failure before the parse keeps the last snapshot.
if (load.parsed) {
this.updateReadState(data, revision);
this.loadError = describeAuthStoreLoadFailure(error);
}
if (!recorded)
return "failed";
if (!(error instanceof CredentialStoreBusyError))
return "failed";
if (!this.dataLoaded) {
this.busyReads++;
this.dataFromBusyRead = true;
}
return "busy";
}
}
/**
* True while the store has never loaded because every read found it locked, so the
* in-memory credentials are not the store's: empty, or auth.json as `readWhileBusy()` read it
* without the lock; `reload()` retries. A readable empty store, or a busy read after a
* successful load, is not busy.
*/
isCredentialStoreBusy() {
return this.dataFromBusyRead;
}
/**
* Why the store could not be loaded on its last read, or undefined once any read or write of this
* instance finds it good again (senpi#4413). While set, the in-memory credentials are not the store's
* contents; a store that cannot be read or parsed also refuses every write.
*/
getLoadError() {
return this.loadError;
}
/**
* Records a failed read; returns false when it repeats the load error already reported, so a store
* that stays broken is not re-recorded on every status read that retries it.
*/
noteLoadFailure(error) {
const loadError = describeAuthStoreLoadFailure(error);
const repeated = loadError !== undefined &&
this.loadError?.kind === loadError.kind &&
this.loadError.reason === loadError.reason;
if (loadError)
this.loadError = loadError;
if (repeated)
return false;
this.recordError(error);
return true;
}
/**
* Monotonic count of reads (sync or async) that found the store locked before it ever
* loaded and answered from credentials that are not the store's (empty, or read without the
* lock). A change across an operation means its credentials may not reflect the store.
*/
getBusyReadCount() {
return this.busyReads;
}
/**
* While another process holds auth.json's lock and this store has never loaded, fills its credentials
* from the file read without the lock, asynchronously and within the sync lock budget (#6841). Writes
* replace the file by rename, so this sees a whole old or new store; it is never written back, and the
* store stays busy, so the next read still takes the lock. A file that cannot be read in time, or does
* not parse, leaves the credentials as they were. Like a locked read, the parse also refreshes the
* store's notices and records a migration it had to skip.
*/
async readWhileBusy() {
if (!this.dataFromBusyRead || this.dataLoaded || !this.authPath)
return;
try {
const content = await readFile(this.authPath, {
encoding: "utf8",
signal: AbortSignal.timeout(FILE_STORAGE_SYNC_LOCK_BUDGET_MS),
});
if (this.dataFromBusyRead && !this.dataLoaded)
this.data = this.parseStorageContent(content).data;
}
catch {
// Unreadable, too slow or unparsable: keep what the store had.
}
}
noteBusyFallback(error) {
if (error instanceof CredentialStoreBusyError && !this.readState.loaded)
this.busyReads++;
}
/** Set a non-persistent API key used ahead of stored credentials. */
setRuntimeApiKey(provider, apiKey) {
this.runtimeOverrides.set(provider, apiKey);
}
removeRuntimeApiKey(provider) {
this.runtimeOverrides.delete(provider);
}
get(provider) {
return readByProviderId(this.data, provider);
}
getProviderEnv(provider) {
const credential = readByProviderId(this.data, provider);
return credential?.type === "api_key" && credential.env ? { ...credential.env } : undefined;
}
/**
* Stores a login. A login of the other kind replaces the provider's credential (senpi#3448); the
* previous bytes are backed up first, and the replacement is returned and kept for
* `takeReplacement`, so no credential disappears without the user being told where it went.
*/
set(provider, credential) {
return this.writeLocked((content) => {
const currentData = this.parseStorageData(content);
const replacement = this.noteReplacement(provider, currentData[provider], credential, content);
const next = stampLogin(appendLoginSlot(currentData[provider], credential, undefined, {
accountIdentity: this.oauthAuth(provider)?.accountIdentity,
}));
const nextData = { ...currentData, [provider]: next };
this.data = nextData;
return { result: replacement, next: JSON.stringify(nextData, null, 2) };
});
}
/** The last replacement a login made for this provider, once; the caller shows it to the user. */
takeReplacement(provider) {
const replacement = this.replacements.get(provider);
this.replacements.delete(provider);
return replacement;
}
/** Credential notices not yet marked seen; a changed problem gets a new id and shows again. */
pendingNotices() {
const seen = this.seenNoticeIds();
return this.notices.filter((notice) => notice.repeats === true || !seen.has(notice.id));
}
/**
* Hands out each pending notice once per process, so a run that reports auth problems at several
* points shows it once (senpi#3486). With `persistSeen`, the notices are also recorded as seen, so
* the next launch stays quiet until the problem changes; a run nobody reads (RPC) leaves them pending.
*/
takePendingNotices(options) {
const taken = this.pendingNotices().filter((notice) => !this.takenNotices.has(notice.id));
for (const notice of taken)
this.takenNotices.add(notice.id);
if (options.persistSeen)
this.markNoticesSeen(taken.map((notice) => notice.id));
return taken;
}
/**
* Records notices as shown, so the next launch stays quiet until the problem changes. Ids of
* problems that no longer exist are dropped. A failed write never aborts startup: it is reported,
* and the notice may be shown once more.
*/
markNoticesSeen(ids) {
if (ids.length === 0)
return;
const path = this.seenNoticesPath();
if (!path) {
for (const id of ids)
this.seenInMemory.add(id);
return;
}
const current = new Set(this.notices.map((notice) => notice.id));
const seen = [...new Set([...this.seenNoticeIds(), ...ids])].filter((id) => current.has(id));
try {
writeFileSync(path, JSON.stringify(seen, null, 2), AUTH_FILE_WRITE_OPTIONS);
}
catch (error) {
const reason = error instanceof Error ? error.message : String(error);
this.recordError(new Error(`Could not record which credential notices were shown (${path}): ${reason}. They may be shown again on the next start; check that the file is writable.`));
}
}
seenNoticesPath() {
return this.authPath ? join(dirname(this.authPath), "auth-notices-seen.json") : undefined;
}
seenNoticeIds() {
const path = this.seenNoticesPath();
if (!path)
return new Set(this.seenInMemory);
try {
const parsed = JSON.parse(readFileSync(path, "utf-8"));
return new Set(Array.isArray(parsed) ? parsed.filter((id) => typeof id === "string") : []);
}
catch {
return new Set();
}
}
noteReplacement(provider, previous, next, content) {
if (previous === undefined || previous.type === next.type)
return undefined;
const backupPath = this.backupAuthFile(content);
const replacement = backupPath
? { replaced: previous.type, backupPath }
: { replaced: previous.type };
this.replacements.set(provider, replacement);
return replacement;
}
remove(provider) {
this.writeLocked((content) => {
const nextData = { ...this.parseStorageData(content) };
delete nextData[provider];
this.data = nextData;
return { result: undefined, next: JSON.stringify(nextData, null, 2) };
});
}
listSlots(provider) {
return listSlots(readByProviderId(this.data, provider));
}
/** Adding a new slot is a sign-in and stamps a fresh `loginId`; updating an existing slot keeps it (senpi#4099). */
setSlot(provider, slot) {
this.writeLocked((content) => {
const currentData = this.parseStorageData(content);
const current = currentData[provider];
const upserted = upsertSlot(current, slot);
const adds = !listSlots(current).some((existing) => existing.name === slot.name);
const next = adds ? stampLogin(upserted) : upserted;
const nextData = { ...currentData, [provider]: next };
this.data = nextData;
return { result: undefined, next: JSON.stringify(nextData, null, 2) };
});
}
removeSlot(provider, name) {
this.writeLocked((content) => {
const currentData = this.parseStorageData(content);
const next = removeSlot(currentData[provider], name);
const nextData = { ...currentData };
if (next === undefined)
delete nextData[provider];
else
nextData[provider] = next;
this.data = nextData;
return { result: undefined, next: JSON.stringify(nextData, null, 2) };
});
}
has(provider) {
return provider in this.data;
}
hasAuth(provider) {
return this.runtimeOverrides.has(provider) || this.has(provider) || getEnvApiKey(provider) !== undefined;
}
getAuthStatus(provider) {
if (this.has(provider))
return { configured: true, source: "stored" };
if (this.runtimeOverrides.has(provider))
return { configured: true, source: "runtime", label: "--api-key" };
const envName = findEnvKeys(provider)?.[0];
if (envName && process.env[envName])
return { configured: true, source: "environment", label: envName };
return { configured: false };
}
getAll() {
return { ...this.data };
}
drainErrors() {
const errors = this.errors;
this.errors = [];
return errors;
}
async reloadFromStorageAsync(options) {
try {
return await this.reloadLockedAsync(options);
}
catch (error) {
if (!options?.signal?.aborted)
this.loadError = describeAuthStoreLoadFailure(error) ?? this.loadError;
throw error;
}
}
async reloadLockedAsync(options) {
const load = { parsed: false, writeBack: false };
try {
return await this.storage.withLockAsync(async (content) => {
const parsed = this.parseStorageContent(content);
load.parsed = true;
load.writeBack = parsed.repaired || parsed.migrated;
const revision = parsed.repaired || parsed.migrated || !this.authPath ? undefined : getFileContentRevision(this.authPath);
this.updateReadState(parsed.data, revision);
if (parsed.migrated)
this.backupAuthFile(content);
return parsed.repaired || parsed.migrated
? { result: parsed.data, next: JSON.stringify(parsed.data, null, 2) }
: { result: parsed.data };
}, options);
}
catch (error) {
throw failureAfterRead(error, load);
}
}
async readLatestData(options) {
options?.signal?.throwIfAborted();
if (!this.authPath) {
try {
return await this.reloadFromStorageAsync(options);
}
catch (error) {
options?.signal?.throwIfAborted();
this.recordError(error);
this.noteBusyFallback(error);
return this.readState.data;
}
}
const revision = getFileContentRevision(this.authPath);
if (revision !== undefined && revision === this.readState.revision)
return this.adoptReadState(this.readState.data);
if (!this.readState.reload) {
const controller = new AbortController();
const reload = {
controller,
promise: this.reloadFromStorageAsync({ signal: controller.signal }),
readers: 0,
};
this.readState.reload = reload;
void reload.promise.then(() => {
if (this.readState.reload === reload)
this.readState.reload = undefined;
}, (error) => {
if (!controller.signal.aborted)
this.recordError(error);
if (this.readState.reload === reload)
this.readState.reload = undefined;
});
}
const reload = this.readState.reload;
reload.readers++;
try {
try {
return this.adoptReadState(await raceWithAbortSignal(reload.promise, options?.signal));
}
catch (error) {
options?.signal?.throwIfAborted();
this.loadError = describeAuthStoreLoadFailure(error) ?? this.loadError;
this.noteBusyFallback(error);
return this.readState.data;
}
}
finally {
reload.readers--;
if (reload.readers === 0 && this.readState.reload === reload) {
this.readState.reload = undefined;
reload.controller.abort();
}
}
}
async read(provider, options) {
options?.signal?.throwIfAborted();
const runtimeKey = this.runtimeOverrides.get(provider);
if (runtimeKey)
return { type: "api_key", key: runtimeKey };
const credential = (await this.readLatestData(options))[provider];
options?.signal?.throwIfAborted();
return resolveStoredCredential(credential, provider, this.authPath);
}
async readSlot(provider, slotName, options) {
options?.signal?.throwIfAborted();
const runtimeKey = this.runtimeOverrides.get(provider);
if (runtimeKey)
return projectSlot({ type: "api_key", key: runtimeKey }, slotName);
const credential = (await this.readLatestData(options))[provider];
options?.signal?.throwIfAborted();
return resolveStoredSlot(credential, { providerId: provider, slotName, authPath: this.authPath }, (flat) => resolveStoredCredential(flat, provider, this.authPath));
}
async modify(provider, fn, options) {
let latestData = this.readState.data;
let revision;
const result = await this.storage.withLockAsync(async (content) => {
const currentData = this.parseStorageData(content);
const next = await fn(currentData[provider]);
if (next === undefined) {
latestData = currentData;
revision = this.authPath ? getFileContentRevision(this.authPath) : undefined;
return { result: currentData[provider] };
}
this.noteReplacement(provider, currentData[provider], next, content);
const merged = { ...currentData, [provider]: next };
latestData = merged;
return { result: next, next: JSON.stringify(merged, null, 2) };
}, options);
this.updateReadState(latestData, revision);
return result;
}
async delete(provider, options) {
options?.signal?.throwIfAborted();
this.runtimeOverrides.delete(provider);
let latestData = this.readState.data;
await this.storage.withLockAsync(async (content) => {
const currentData = this.parseStorageData(content);
delete currentData[provider];
latestData = currentData;
return { result: undefined, next: JSON.stringify(currentData, null, 2) };
}, options);
this.updateReadState(latestData);
}
/** List credential metadata without resolving configured key values. */
async list(options) {
const entries = new Map(Object.entries(await this.readLatestData(options)).map(([providerId, credential]) => [
providerId,
{ providerId, type: credential.type },
]));
options?.signal?.throwIfAborted();
for (const providerId of this.runtimeOverrides.keys()) {
entries.set(providerId, { providerId, type: "api_key" });
}
return [...entries.values()];
}
async getApiKey(providerId, options = {}) {
const runtimeKey = this.runtimeOverrides.get(providerId);
if (runtimeKey)
return runtimeKey;
const credential = await this.read(providerId);
if (credential?.type === "api_key")
return credential.key;
if (credential?.type === "oauth") {
const oauth = builtinProviders().find((provider) => provider.id === providerId)?.auth.oauth;
if (!oauth)
return undefined;
let current = credential;
if (Date.now() >= current.expires) {
const refreshed = await this.refreshOAuthCredential(providerId, oauth);
if (refreshed === undefined)
return undefined;
current = refreshed;
}
return (await oauth.toAuth(current)).apiKey;
}
if (options.includeFallback === false)
return undefined;
return getEnvApiKey(providerId);
}
/**
* Refreshes the stored OAuth credential when it has expired. It delegates to pi-ai's `refreshOAuthCredential`,
* the path request-time resolution uses: the exchange runs under this store's per-account refresh lock and the
* expiry is checked again once that lock is held, so callers in any process share one token exchange.
*/
async refreshOAuthCredential(providerId, oauth, signal = new AbortController().signal) {
const stored = await this.read(providerId, { signal });
if (stored?.type !== "oauth")
return undefined;
const isStale = (credential) => Date.now() >= credential.expires;
if (!isStale(stored))
return stored;
const refreshed = await refreshOAuthCredential({
credentials: this,
providerId,
oauth,
stale: stored,
isStale,
signal,
owning: true,
});
return refreshed?.type === "oauth" ? refreshed : undefined;
}
registerOAuthProvider(providerId, oauth) {
this.extensionOAuthProviders.set(providerId, oauth);
}
unregisterOAuthProvider(providerId) {
this.extensionOAuthProviders.delete(providerId);
}
getOAuthProviders() {
const dynamic = [...this.extensionOAuthProviders.entries()].map(([id, oauth]) => ({
id,
name: oauth.name,
}));
const builtin = builtinProviders().flatMap((provider) => provider.auth.oauth && !this.extensionOAuthProviders.has(provider.id)
? [{ id: provider.id, name: provider.auth.oauth.name }]
: []);
return [...dynamic, ...builtin];
}
oauthAuth(providerId) {
return (this.extensionOAuthProviders.get(providerId) ??
builtinProviders().find((provider) => provider.id === providerId)?.auth.oauth);
}
async login(providerId, callbacks) {
const oauth = this.oauthAuth(providerId);
if (!oauth)
throw new Error(`Unknown OAuth provider: ${providerId}`);
const signal = callbacks.signal ?? new AbortController().signal;
const interaction = {
signal,
prompt: (prompt) => this.handleLegacyPrompt(prompt, callbacks),
notify: (event) => this.handleLegacyEvent(event, callbacks),
};
const before = this.get(providerId);
const credential = await oauth.login(interaction);
this.set(providerId, credential);
if (this.authPath === undefined)
return;
// Lazy like ModelRuntime.loadCredentialPool: the pool store pulls zod, which must stay out of the
// model-runtime import graph that every auth-storage importer shares.
const { retireLoginSlotHealth } = await import("./credential-pool/login-health.js");
await retireLoginSlotHealth(join(dirname(this.authPath), "credential-pool-state.json"), providerId, before, this.get(providerId));
}
logout(provider) {
this.removeRuntimeApiKey(provider);
this.remove(provider);
}
handleLegacyPrompt(prompt, callbacks) {
switch (prompt.type) {
case "manual_code":
return callbacks.onManualCodeInput?.() ?? callbacks.onPrompt(prompt);
case "select":
return callbacks.onSelect(prompt).then((value) => {
if (value === undefined)
throw new Error("Login cancelled");
return value;
});
case "secret":
case "text":
return callbacks.onPrompt(prompt);
}
}
handleLegacyEvent(event, callbacks) {
switch (event.type) {
case "auth_url":
callbacks.onAuth(event);
break;
case "device_code":
callbacks.onDeviceCode(event);
break;
case "info":
callbacks.onProgress?.(event.message);
break;
case "progress":
callbacks.onProgress?.(event.message);
break;
}
}
}
/**
* One-off synchronous read of a stored credential from an auth.json file,
* without instantiating a store or resolving configured key values.
*/
export function readStoredCredential(providerId, authPath = join(getAgentDir(), "auth.json")) {
try {
const data = JSON.parse(stripBom(readFileSync(normalizePath(authPath), "utf-8")));
// Read boundary (senpi#1989): try canonical, then the legacy spelling.
return readByProviderId(data, providerId);
}
catch {
return undefined;
}
}
//# sourceMappingURL=auth-storage.js.map