UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

307 lines • 18.7 kB
import { type AnyModel, type Api, type AssistantImages, type AssistantMessage, type AssistantMessageEventStream, type AuthCheck, type AuthInteraction, type AuthOperationOptions, type AuthResult, type AuthType, type ClassifierApi, type ClassifierContext, type ClassifierModel, type ClassifierResult, type Context, type Credential, type CredentialInfo, type CredentialStore, type DeferredHandle, type ImageApi, type ImageModel, type ImagesContext, type LoginOptions, type LogoutOptions, type OAuthRevocationResult, type Message, type Model, type Models, type ModelsApiStreamOptions, type ModelsClassifierOptions, type ModelsDeferredCancelOptions, type ModelsDeferredFetchOptions, type ModelsImagesOptions, type ModelsRefreshOptions, type ModelsRefreshResult, type ModelsRequestTransforms, type ModelsSimpleStreamOptions, type ModelsStore, type ModelThinkingLevel, type ModelType, type ModelTypeMap, type Provider, type ProviderHeaders, type SimpleStreamOptions, type StreamOptions } from "@earendil-works/pi-ai"; import { AuthStorage as DefaultAuthStorage } from "./auth-storage.ts"; import { type AuthStatus, type CompatibilityRequestConfig, type ProviderConfigInput } from "./provider-composer.ts"; import { type ProviderOrigin } from "./provider-origin.ts"; import type { SettingsManager } from "./settings-manager.ts"; import { type ModelRoute, type ModelRouteReason, type VirtualModelDefinition } from "./virtual-models.ts"; export interface ProviderRegistrationOptions { refresh?: boolean; /** The registering extension, reported as the provider's origin (senpi#4328). */ extensionPath?: string | undefined; } export interface CreateModelRuntimeOptions { settingsManager?: SettingsManager; /** Credential storage. Defaults to the file at authPath. */ credentials?: CredentialStore; authPath?: string; agentDir?: string; modelsPath?: string | null; modelsStore?: ModelsStore; modelsStorePath?: string; /** Allow create() to refresh model catalogs over the network. Defaults to false. */ allowModelNetwork?: boolean; /** Timeout for the create-time network model refresh. */ modelRefreshTimeoutMs?: number; catalogBaseUrl?: string; /** Optional caller cancellation for initial cache restoration and availability checks. */ signal?: AbortSignal; /** Skip initial catalog and availability refresh. Static models remain available. */ refreshOnCreate?: boolean; } export interface ModelRuntimeAuthOverrides extends AuthOperationOptions { apiKey?: string; env?: Record<string, string>; /** Require this much remaining OAuth-token validity; defaults to five minutes. */ minOAuthValidityMs?: number; /** Resolve against one named slot of a pooled credential instead of the flat projection. */ slotName?: string; /** An OAuth access token the provider just refused; a stored credential still carrying it is re-exchanged. */ rejectedAccess?: string; } /** * Stream options plus the coding-agent-only affinity key. It is declared here * rather than widening the engine's `StreamOptions`: a stable key (the session * id) keeps one conversation on one credential slot, and its absence simply * distributes requests instead of concentrating them. */ export type CredentialRotationStreamOptions = StreamOptions & ModelsRequestTransforms & { affinityKey?: string; }; export type CredentialSynchronizationOperation = "login" | "logout" | "setRuntimeApiKey" | "removeRuntimeApiKey"; /** Credentials changed successfully, but the local model/auth snapshot could not be synchronized. */ export declare class CredentialSynchronizationError extends Error { readonly providerId: string; readonly operation: CredentialSynchronizationOperation; readonly credential: Credential | undefined; constructor(providerId: string, operation: CredentialSynchronizationOperation, credential: Credential | undefined, options: ErrorOptions); } /** Configured pi-ai Models collection used by coding-agent and SDK consumers. */ export declare class ModelRuntime implements Models { private settingsManager; private unsubscribeProviderSettings; private readonly providerSemaphores; setSettingsManager(settingsManager: SettingsManager): void; private readonly models; private readonly credentials; private readonly defaultBuiltins; private readonly builtins; private readonly nativeExtensionProviders; private readonly extensionProviders; /** The extension behind each registration that named one (senpi#4328). */ private readonly providerExtensionPaths; /** Virtual models by provider id, then model id. */ private readonly virtualModels; private readonly compositionErrors; private readonly modelsPath; private readonly modelNetworkEnabled; private readonly modelRefreshTimeoutMs; private config; private snapshot; private availabilityInitialized; private availabilityRefreshSeq; private availabilityErrorSeq; private readonly providerAvailabilitySeq; private busyAvailabilityRetries; private busyAvailabilityRetryTimer; private availabilityError; private readonly credentialOperations; private readonly servedCredentials; /** * Actual stored-slot attempts, scoped to the session rather than a predicted list winner. Bounded by recency: * sessions are never released to the runtime, and an evicted session is re-recorded on its next request. */ private readonly activeCredentialAccounts; getActiveCredentialAccount(providerId: string, sessionId: string): string | undefined; /** * The credential pool is loaded lazily for pooled providers and ChatGPT * registrations whose health must be tracked even alone. Importing it eagerly would pull the pool's schema * validator - and its module-level global registry - into every consumer of * ModelRuntime, which the import-graph guard forbids. */ private readonly poolStatePath; /** Providers whose stale generic-pool health was already retired in this process (senpi#2081). */ private readonly outerSlotStateRetired; private credentialPoolModules; private constructor(); /** * The AuthStorage this runtime's providers register into, when it was built on one. A session * built on a shared runtime must read this same store, or extension OAuth providers are never * listed (senpi#3434). */ get authStorage(): DefaultAuthStorage | undefined; static create(options?: CreateModelRuntimeOptions): Promise<ModelRuntime>; /** Synchronous compatibility constructor for legacy ModelRegistry callers. */ static createSync(options?: CreateModelRuntimeOptions): ModelRuntime; private providerIds; /** Returns the provider without virtual models, or undefined when only virtual models define it. */ private recomposeProvider; /** The provider without virtual models, or undefined when nothing defines it. */ private composeProvider; private rebuildProviders; private updateModelSnapshot; private runAvailabilityRefresh; private queueAvailabilityRefresh; private refreshProviderAvailability; /** * A pass whose credential reads hit a locked store saw the cached snapshot (empty in a * fresh process), not the store. Such a pass must not publish availability or mark it * initialized; it records the contention so the next refresh re-reads the store. */ private answeredFromBusyStore; /** * Re-read availability after a busy store, so a lock held during startup does not leave * every provider unconfigured until some later caller happens to refresh. Bounded: at most * {@link BUSY_AVAILABILITY_RETRY_LIMIT} attempts with doubling delays, reset by a published * pass; the timer never keeps the process alive. */ private scheduleBusyAvailabilityRetry; getProviders(): readonly Provider[]; getProvider(providerId: string): Provider | undefined; getModels(providerId?: string): readonly Model<Api>[]; getModel(providerId: string, modelId: string): Model<Api> | undefined; getModelsOfType<TType extends ModelType>(type: TType, providerId?: string): readonly ModelTypeMap[TType][]; getModelOfType<TType extends ModelType>(type: TType, providerId: string, modelId: string): ModelTypeMap[TType] | undefined; getAllModels(providerId?: string): readonly AnyModel[]; getAvailableOfType<TType extends ModelType>(type: TType, providerId?: string, options?: AuthOperationOptions): Promise<readonly ModelTypeMap[TType][]>; getAllAvailable(providerId?: string, options?: AuthOperationOptions): Promise<readonly AnyModel[]>; checkAuth(providerId: string, options?: AuthOperationOptions): Promise<AuthCheck | undefined>; getAvailable(providerId?: string, options?: AuthOperationOptions): Promise<readonly Model<Api>[]>; getAvailableSnapshot(): readonly Model<Api>[]; /** True only when the most recent availability refresh completed without error. */ hasFreshAvailabilitySnapshot(): boolean; hasAvailabilitySnapshot(): boolean; /** Non-fatal models.json notices (e.g. renamed provider ids), rendered as warnings. */ getWarnings(): readonly string[]; getError(): string | undefined; getRegisteredProviderConfig(providerId: string): ProviderConfigInput | undefined; getRegisteredProviderIds(): readonly string[]; getRegisteredNativeProvider(providerId: string): Provider | undefined; getProviderOrigin(providerId: string): ProviderOrigin | undefined; private noteExtensionPath; /** @internal Compatibility fallback for ModelRegistry when provider auth is unconfigured. */ getCompatibilityRequestConfig(model: Model<Api>): CompatibilityRequestConfig; /** @internal Configured headers for a request the provider could not authenticate. */ getCompatibilityRequestHeaders(model: Model<Api>, env?: Record<string, string>): Promise<ProviderHeaders | undefined>; isUsingOAuth(providerId: string): boolean; isUsingSubscription(providerId: string): boolean; hasConfiguredAuth(providerId: string): boolean; /** * Deterministic fallback-expansion gate declared by the provider's own * registration. Only a definitive `false` excludes; providers without the * hook, and hooks that throw, stay eligible so expansion never shrinks on * uncertainty. */ isFallbackEligible(providerId: string): boolean; getAuth(providerId: string, overrides?: ModelRuntimeAuthOverrides): Promise<AuthResult | undefined>; getAuth(model: AnyModel, overrides?: ModelRuntimeAuthOverrides): Promise<AuthResult | undefined>; /** * Auth for a request a session sends outside the rotation stream (compaction, /btw, look-at, * cache keepalive). The key must belong to the account the session's own turns use, so a pooled * provider resolves the slot the stream would pick for this session; without a pool, or when * the stream would not rotate either, it is `getAuth(model)`. */ getSessionAuth(model: Model<Api>, sessionId: string): Promise<AuthResult | undefined>; private sessionSlotAuth; private enqueueCredentialOperation; private synchronizeCredentialState; setRuntimeApiKey(providerId: string, apiKey: string, options?: AuthOperationOptions): Promise<void>; removeRuntimeApiKey(providerId: string, options?: AuthOperationOptions): Promise<void>; listCredentials(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]>; getProviderAuthStatus(providerId: string): AuthStatus; /** Whether the provider's only credential is a configured header: no configured key, and no key of its own. */ providerAuthIsHeaderOnly(providerId: string): boolean; /** * The provider's auth status plus whether it is a non-stored sign-in (#3537). `signIn` is set * only by the last branch, the provider's own check resolving `type: "oauth"`, so a runtime key, * a stored credential or a configured models.json/extension key always wins first. */ resolveProviderAuth(providerId: string): { status: AuthStatus; signIn: boolean; }; private prepareRequest; /** * Rotation engages only for a provider that actually holds more than one * credential slot and only when nothing pins the request to one credential * (a runtime key or an explicit per-request apiKey). Every single-credential * user therefore keeps byte-identical request behavior. */ private loadCredentialPool; /** * Fully synchronous admission check. A provider that cannot possibly hold a * pool must not even reach the async rotation path: awaiting an async method * costs a microtask hop, which would reorder an ordinary request's provider * call relative to the untouched `streamSimple` path. */ private couldRotateCredentials; private ownsAccountSelection; /** * Health the generic pool recorded for a provider before its lane became the only owner of account * selection is retired before that provider's first request in this process. Older builds pinned the * lane's verdicts on these slots and left them blocked; an upgrade must heal them with no re-login * (senpi#2081). A busy state file is retried on the next request. */ private retireOuterSlotState; private credentialRotationSources; stream<TApi extends Api>(model: Model<TApi>, context: Context, options?: ModelsApiStreamOptions<TApi>): AssistantMessageEventStream; /** * One provider request with the #2297 recovery: a stored OAuth token the provider * refuses before any output is re-exchanged once and the request re-sent. */ private attemptWithTokenRecovery; complete<TApi extends Api>(model: Model<TApi>, context: Context, options?: ModelsApiStreamOptions<TApi>): Promise<AssistantMessage>; streamSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): AssistantMessageEventStream; /** * Resolve auth, headers, `extraBody`, env, and the upstream model id exactly as a * single-credential `streamSimple` request does, without sending it. The session-start * prompt-cache prewarm (senpi#2096) builds its request from this so its prefix matches * the first turn's. */ prepareSimpleRequest(model: Model<Api>, options?: ModelsSimpleStreamOptions): Promise<{ model: Model<Api>; options: SimpleStreamOptions; }>; completeSimple(model: Model<Api>, context: Context, options?: ModelsSimpleStreamOptions): Promise<AssistantMessage>; streamDeferred(model: Model<Api>, handle: DeferredHandle, options?: ModelsDeferredFetchOptions): AssistantMessageEventStream; fetchDeferred(model: Model<Api>, handle: DeferredHandle, options?: ModelsDeferredFetchOptions): Promise<AssistantMessage>; cancelDeferred(model: Model<Api>, handle: DeferredHandle, options?: ModelsDeferredCancelOptions): Promise<void>; generateImages(model: ImageModel<ImageApi>, context: ImagesContext, options?: ModelsImagesOptions): Promise<AssistantImages>; classify(model: ClassifierModel<ClassifierApi>, context: ClassifierContext, options?: ModelsClassifierOptions): Promise<ClassifierResult>; login(providerId: string, type: AuthType, interaction: AuthInteraction, options?: LoginOptions): Promise<Credential>; logout(providerId: string, options?: LogoutOptions): Promise<OAuthRevocationResult | void>; /** * {@link logout}, answering what the user should know: an Anthropic Subscription `claude-cli` account is signed out * of the Claude CLI's own store before the credential is deleted (senpi#4436), and `notices` names any account that * could not be signed out cleanly. `revocation` reports a ChatGPT OAuth remote revocation; `slotId` signs out one * stored account and keeps its registration and signed-in siblings. */ logoutProvider(providerId: string, options?: LogoutOptions): Promise<{ readonly notices: readonly string[]; readonly revocation?: OAuthRevocationResult; }>; reloadConfig(): Promise<void>; refresh(options?: ModelsRefreshOptions): Promise<ModelsRefreshResult>; /** * Providers registered after startup missed the create() refresh. Load their catalogs * under the runtime network policy, bounded like startup, so newly registered models are * usable without a manual refresh. Offline policy restores from the store only and never * touches the network. */ private shouldSkipRegistrationRefresh; private refreshAfterRegistration; registerNativeProvider(provider: Provider, options?: ProviderRegistrationOptions): Promise<ModelsRefreshResult>; /** * Mark a newly registered provider as configured when it has a stored credential or a configured * API key. Availability checks run asynchronously, and callers such as initial model selection * read the snapshot before they finish. The next availability pass replaces this entry. */ private markProvisionallyConfigured; registerProvider(providerId: string, config: ProviderConfigInput, options?: ProviderRegistrationOptions): Promise<ModelsRefreshResult>; unregisterProvider(providerId: string): void; /** * Register a virtual model under `definition.provider`, which may also list physical models or * several virtual models. Re-registering the same provider and id replaces the virtual model. * Throws when the id belongs to a physical model of that provider. */ registerVirtualModel(definition: VirtualModelDefinition): void; unregisterVirtualModel(providerId: string, id: string): void; /** * Ask a virtual model's router for the model and thinking level of one request. The router must * return a physical catalog model whose provider has credentials; the thinking level is clamped * to that model. Throws when routing fails. * * `previous` reports the latest successful response in `messages`. A retry passes the failed * response as `options.failed`; `messages` no longer contains it. `options.state` is the router * state stored by the caller, which also stores the returned state. */ resolveModel(model: Model<Api>, messages: readonly Message[], options: { reason: ModelRouteReason; thinkingLevel: ModelThinkingLevel; signal?: AbortSignal; failed?: AssistantMessage; state?: unknown; }): Promise<ModelRoute>; /** A catalog chat model that is not virtual. */ getPhysicalModel(providerId: string, modelId: string): Model<Api> | undefined; } //# sourceMappingURL=model-runtime.d.ts.map