@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
227 lines • 10.1 kB
JavaScript
import { join } from "node:path";
import { getAgentDir } from "../config.js";
import { AuthStorage } from "./auth-storage.js";
import { ModelRuntime as DefaultModelRuntime } from "./model-runtime.js";
import { BUILT_IN_PROVIDER_DISPLAY_NAMES } from "./provider-display-names.js";
export { clearApiKeyCache } from "./provider-composer.js";
/**
* Synchronous compatibility facade exposed to extensions.
* Coding-agent internals use ModelRuntime directly.
*/
export class ModelRegistry {
constructor(runtime, authStorage = AuthStorage.inMemory()) {
this.busyRetriedThisTurn = false;
this.runtime = runtime;
this.authStorage = authStorage;
}
static create(authStorage, modelsJsonPath = join(getAgentDir(), "models.json")) {
return new ModelRegistry(DefaultModelRuntime.createSync({ credentials: authStorage, modelsPath: modelsJsonPath }), authStorage);
}
static inMemory(authStorage) {
return new ModelRegistry(DefaultModelRuntime.createSync({ credentials: authStorage, modelsPath: null }), authStorage);
}
get modelRuntime() {
return this.runtime;
}
/** Reload models.json asynchronously. Await before making synchronous registry reads. */
refresh(options) {
return this.runtime.refresh(options);
}
getError() {
return this.runtime.getError();
}
getAll() {
return [...this.runtime.getModels()];
}
getAvailable() {
if (this.runtime.hasAvailabilitySnapshot()) {
return [...this.runtime.getAvailableSnapshot()];
}
this.retryBusyCredentialRead();
return this.runtime.getProviders().flatMap((provider) => {
if (!this.authStorage.hasAuth(provider.id) && !this.runtime.getProviderAuthStatus(provider.id).configured) {
return [];
}
const models = this.runtime.getModels(provider.id);
return [...(provider.filterModels?.(models, this.authStorage.get(provider.id)) ?? models)];
});
}
find(provider, modelId) {
return this.runtime.getModel(provider, modelId);
}
/** Find a model of a non-chat type, e.g. `findOfType("classifier", "typesafe", "jev-latest")`. */
findOfType(type, provider, modelId) {
return this.runtime.getModelOfType(type, provider, modelId);
}
hasConfiguredAuth(model) {
this.retryBusyCredentialRead();
return this.authStorage.hasAuth(model.provider) || this.runtime.getProviderAuthStatus(model.provider).configured;
}
/**
* The live auth check reads the in-memory credentials. When the last read found the store
* locked they were never loaded, so re-read now (bounded by the sync lock budget) instead
* of answering from the empty fallback for the rest of the process. A store that could not be
* loaded is re-read the same way, so a repaired auth.json is seen without a restart (#4413).
*/
retryBusyCredentialRead() {
if (!this.authStorage.isCredentialStoreBusy() && !this.authStorage.getLoadError())
return;
// A re-read of a store another process holds blocks for the sync lock budget, and a provider list
// re-reads once per row in one synchronous pass: wait once per pass, not once per row (#6841).
if (this.busyRetriedThisTurn)
return;
if (this.authStorage.reload() !== "busy")
return;
this.busyRetriedThisTurn = true;
queueMicrotask(() => {
this.busyRetriedThisTurn = false;
});
}
getUpstreamModelId(model) {
return this.runtime.getCompatibilityRequestConfig(model).upstreamModelId;
}
getServiceTier(model) {
return this.runtime.getCompatibilityRequestConfig(model).serviceTier;
}
/**
* Request auth for a direct provider call. A caller acting for a session passes its id so the
* key belongs to the account that session's turns use; without it the stored credential is
* resolved as for session-less callers.
*/
async getApiKeyAndHeaders(model, options = {}) {
try {
const resolution = options.sessionId === undefined
? await this.runtime.getAuth(model)
: await this.runtime.getSessionAuth(model, options.sessionId);
const compatibility = this.runtime.getCompatibilityRequestConfig(model);
if (!resolution) {
if (compatibility.authHeader) {
return { ok: false, error: `No API key found for "${model.provider}"` };
}
const headers = await this.runtime.getCompatibilityRequestHeaders(model);
return { ok: true, headers, extraBody: compatibility.extraBody };
}
return {
ok: true,
apiKey: resolution.auth.apiKey,
headers: resolution.auth.headers,
extraBody: compatibility.extraBody,
baseUrl: resolution.auth.baseUrl,
upstreamModelId: compatibility.upstreamModelId,
serviceTier: compatibility.serviceTier,
env: resolution.env,
...(resolution.ambient ? { ambient: true } : {}),
};
}
catch (error) {
const cause = error instanceof Error ? error.cause : undefined;
const message = cause instanceof Error ? cause.message : error instanceof Error ? error.message : String(error);
return {
ok: false,
error: message === "authHeader requires a resolved API key"
? `No API key found for "${model.provider}"`
: message,
};
}
}
getProviderAuthStatus(provider) {
return this.resolveProviderAuth(provider).status;
}
providerAuthIsHeaderOnly(provider) {
return this.runtime.providerAuthIsHeaderOnly(provider);
}
/** `getProviderAuthStatus` plus whether it is a non-stored sign-in, from one resolution (#3537). */
resolveProviderAuth(provider) {
this.retryBusyCredentialRead();
const resolved = this.runtime.resolveProviderAuth(provider);
if (resolved.status.configured || this.runtime.hasAvailabilitySnapshot())
return resolved;
// Until an availability pass succeeds the runtime's stored-provider set is empty, so answer
// from the live store, as getAvailable() does through hasAuth(); otherwise a store that was
// locked on its first read keeps reporting "not configured" while its models are usable
// (#2249). getAuthStatus() labels the source (stored, --api-key, environment) correctly.
const live = this.authStorage.getAuthStatus(provider);
return live.configured ? { status: live, signIn: false } : resolved;
}
getProvider(provider) {
return this.runtime.getProvider(provider);
}
/** Stream through the configured provider with request-time authentication. */
stream(model, context, options) {
return this.runtime.stream(model, context, options);
}
/** Stream with provider-neutral options and request-time authentication. */
streamSimple(model, context, options) {
return this.runtime.streamSimple(model, context, options);
}
complete(model, context, options) {
return this.runtime.complete(model, context, options);
}
/** Every known model of a type (chat, image, classifier), optionally for one provider. */
getModelsOfType(type, provider) {
return this.runtime.getModelsOfType(type, provider);
}
/** Models of a type whose provider has working credentials. */
getAvailableOfType(type, provider, options) {
return this.runtime.getAvailableOfType(type, provider, options);
}
getModelOfType(type, provider, modelId) {
return this.runtime.getModelOfType(type, provider, modelId);
}
/** Classify structured state with request-time authentication. Never rejects. */
classify(model, context, options) {
return this.runtime.classify(model, context, options);
}
getProviderDisplayName(provider) {
return this.runtime.getProvider(provider)?.name ?? BUILT_IN_PROVIDER_DISPLAY_NAMES[provider] ?? provider;
}
getProviderAuth(provider) {
return this.runtime.getAuth(provider);
}
async getApiKeyForProvider(provider) {
try {
return (await this.runtime.getAuth(provider))?.auth.apiKey;
}
catch {
return undefined;
}
}
isUsingOAuth(model) {
return this.authStorage.get(model.provider)?.type === "oauth" || this.runtime.isUsingOAuth(model.provider);
}
/** Fallback-expansion gate: `false` only when the provider's registration declares the lane unusable. */
isFallbackEligible(model) {
return this.runtime.isFallbackEligible(model.provider);
}
registerProvider(providerOrName, config) {
if (typeof providerOrName === "string") {
if (!config)
throw new Error("Provider config is required when registering by name");
this.runtime.registerProvider(providerOrName, config);
return;
}
this.runtime.registerNativeProvider(providerOrName);
}
unregisterProvider(providerName) {
this.runtime.unregisterProvider(providerName);
}
registerVirtualModel(definition) {
this.runtime.registerVirtualModel(definition);
}
unregisterVirtualModel(providerName, id) {
this.runtime.unregisterVirtualModel(providerName, id);
}
getRegisteredProviderConfig(providerName) {
return this.runtime.getRegisteredProviderConfig(providerName);
}
getRegisteredNativeProvider(providerName) {
return this.runtime.getRegisteredNativeProvider(providerName);
}
getRegisteredProviderIds() {
return this.runtime.getRegisteredProviderIds();
}
getProviderOrigin(providerName) {
return this.runtime.getProviderOrigin(providerName);
}
}
//# sourceMappingURL=model-registry.js.map