import type { AxiosRequestConfig } from 'axios'; import type { ISecurityManager } from '../security/types'; import type { Logger } from '../utils/logger'; export interface OpenRouterPlugin { init(client: import('../client').OpenRouterClient): Promise | void; destroy?: () => Promise | void; } export interface MiddlewareContext { request: { options: OpenRouterRequestOptions; }; response?: { result?: ChatCompletionResult; rawResponse?: any; error?: any; }; metadata?: Record; } export type MiddlewareFunction = (ctx: MiddlewareContext, next: () => Promise) => Promise; export interface ApiCallMetadata { callId: string; modelUsed: string; usage: UsageInfo | null; cost: number | null; timestamp: number; finishReason: string | null; requestMessagesCount?: number; } export interface HistoryEntry { message: Message; apiCallMetadata?: ApiCallMetadata | null; } export interface IHistoryStorage { load(key: string): Promise; save(key: string, entries: HistoryEntry[]): Promise; delete(key: string): Promise; listKeys(): Promise; destroy?: () => Promise | void; } export type Role = 'user' | 'assistant' | 'system' | 'tool'; export interface Message { role: Role; content: string | null; timestamp?: string; name?: string; tool_call_id?: string; tool_calls?: ToolCall[]; reasoning?: string | null; annotations?: UrlCitationAnnotation[]; } export interface ToolCall { id: string; type: 'function'; function: { name: string; arguments: string; }; } export interface ToolContext { userInfo?: UserAuthInfo; securityManager?: ISecurityManager; logger?: Logger; includeToolResultInReport?: boolean; } export interface Tool { type: 'function'; function: { name: string; description?: string; parameters?: Record; }; execute: (args: any, context?: ToolContext) => Promise | any; security?: ToolSecurity; name?: string; } export type ToolCallStatus = 'success' | 'error_parsing' | 'error_validation' | 'error_security' | 'error_execution' | 'error_unknown' | 'error_not_found'; export interface ToolCallDetail { toolCallId: string; toolName: string; requestArgsString: string; parsedArgs?: any | null; status: ToolCallStatus; result?: any | null; error?: { type: string; message: string; details?: any; } | null; resultString: string; durationMs?: number; } export interface ToolCallOutcome { message: Message; details: ToolCallDetail; } export interface RateLimit { limit: number; period: 'second' | 'minute' | 'hour' | 'day'; } export interface DangerousArgumentsConfig { globalPatterns?: Array; toolSpecificPatterns?: Record>; blockedValues?: string[]; } export interface ToolSecurity { requiredRole?: string | string[]; requiredScopes?: string | string[]; rateLimit?: RateLimit; } export interface UserAuthConfig { type?: 'jwt' | 'api-key' | 'custom'; jwtSecret?: string; customAuthenticator?: (token: string) => Promise | UserAuthInfo | null; } export interface UserAuthInfo { userId: string; role?: string; scopes?: string[]; expiresAt?: number; apiKey?: string; [key: string]: any; } export interface ToolAccessConfig { allow?: boolean; roles?: string | string[]; scopes?: string | string[]; rateLimit?: RateLimit; allowedApiKeys?: string[]; } export interface RoleConfig { allowedTools?: string | string[] | '*'; rateLimits?: Record; } export interface RolesConfig { roles?: Record; } export interface SecurityConfig { defaultPolicy?: 'allow-all' | 'deny-all'; userAuthentication?: UserAuthConfig; toolAccess?: Record; roles?: RolesConfig; requireAuthentication?: boolean; } export interface ToolCallEvent { toolName: string; userId: string; args: any; result: any; success: boolean; error?: Error; timestamp: number; } /** @deprecated Use IHistoryStorage interface instead */ export type HistoryStorageType = 'memory' | 'disk'; export interface ResponseFormat { type: 'json_object' | 'json_schema'; json_schema?: { name: string; strict?: boolean; schema: Record; description?: string; }; } export interface ProviderRoutingConfig { order?: string[]; allow_fallbacks?: boolean; require_parameters?: boolean; data_collection?: 'allow' | 'deny'; ignore?: string[]; quantizations?: string[]; sort?: 'price' | 'throughput' | 'latency'; } export interface PluginConfig { id: string; max_results?: number; search_prompt?: string; [key: string]: any; } export interface ReasoningConfig { effort?: 'low' | 'medium' | 'high'; max_tokens?: number; exclude?: boolean; } export interface ModelPricingInfo { id: string; name?: string; promptCostPerMillion: number; completionCostPerMillion: number; context_length?: number; } export interface UrlCitationAnnotation { type: 'url_citation'; url_citation: { url: string; title: string; content?: string; start_index: number; end_index: number; }; } export interface OpenRouterConfig { apiKey: string; apiEndpoint?: string; apiBaseUrl?: string; model?: string; debug?: boolean; proxy?: string | { host: string; port: number | string; user?: string; pass?: string; } | null; referer?: string; title?: string; axiosConfig?: AxiosRequestConfig; historyAdapter?: IHistoryStorage; historyTtl?: number; historyCleanupInterval?: number; /** @deprecated Use historyAdapter */ historyStorage?: HistoryStorageType; /** @deprecated Configure path in DiskHistoryStorage adapter */ chatsFolder?: string; /** @deprecated Limit handling depends on history adapter/manager */ maxHistoryEntries?: number; /** @deprecated Auto-saving depends on history adapter */ historyAutoSave?: boolean; defaultProviderRouting?: ProviderRoutingConfig; modelFallbacks?: string[]; responseFormat?: ResponseFormat | null; maxToolCalls?: number; strictJsonParsing?: boolean; security?: SecurityConfig; enableCostTracking?: boolean; priceRefreshIntervalMs?: number; initialModelPrices?: Record; enableReasoning?: boolean; webSearch?: boolean; } export interface OpenRouterRequestOptions { prompt?: string; customMessages?: Message[] | null; user?: string; group?: string | null; systemPrompt?: string | null; accessToken?: string | null; model?: string; temperature?: number; maxTokens?: number | null; topP?: number | null; presencePenalty?: number | null; frequencyPenalty?: number | null; stop?: string | string[] | null; seed?: number | null; logitBias?: Record | null; tools?: Tool[] | null; toolChoice?: "none" | "auto" | { type: "function"; function: { name: string; }; } | null; parallelToolCalls?: boolean; maxToolCalls?: number; maxToolIterations?: number; includeToolResultInReport?: boolean; responseFormat?: ResponseFormat | null; strictJsonParsing?: boolean; route?: string; transforms?: string[]; provider?: ProviderRoutingConfig; models?: string[]; plugins?: PluginConfig[]; reasoning?: ReasoningConfig; stream?: boolean; streamCallbacks?: StreamCallbacks; } export interface UsageInfo { prompt_tokens: number; completion_tokens: number; total_tokens: number; [key: string]: any; } export interface OpenRouterResponse { id: string; object: string; created: number; model: string; choices: Array<{ index: number; message: Message; finish_reason: 'stop' | 'length' | 'tool_calls' | 'content_filter' | null; logprobs?: any | null; }>; usage?: UsageInfo; system_fingerprint?: string; error?: { message?: string; type?: string; code?: string; [key: string]: any; } | string; } export interface ChatCompletionResult { content: any; usage: UsageInfo | null; model: string; toolCallsCount: number; toolCalls?: ToolCallDetail[]; finishReason: string | null; durationMs: number; id?: string; cost?: number | null; reasoning?: string | null; annotations?: UrlCitationAnnotation[]; } export interface CreditBalance { total_credits: number; total_usage: number; } export interface ApiKeyInfo { data: { limit: number; usage: number; is_free_tier: boolean; rate_limit: { requests: number; interval: string; }; }; } export interface StreamChunk { id: string; object: string; created: number; model: string; choices: Array<{ index: number; delta: { role?: Role; content?: string | null; tool_calls?: Array<{ index?: number; id?: string; type?: 'function'; function?: { name?: string; arguments?: string; }; }>; reasoning?: string | null; }; finish_reason?: 'stop' | 'length' | 'tool_calls' | 'content_filter' | null; logprobs?: any | null; }>; usage?: UsageInfo; } export interface StreamCallbacks { onChunk?: (chunk: StreamChunk) => void; onContent?: (content: string) => void; onToolCallExecuting?: (toolName: string, args: any) => void; onToolCallResult?: (toolName: string, result: any) => void; onComplete?: (fullContent: string, usage?: UsageInfo, toolCalls?: ToolCall[]) => void; onError?: (error: Error) => void; } export interface ChatStreamResult { content: string; usage?: UsageInfo | null; model?: string; finishReason?: string | null; id?: string; toolCalls?: ToolCall[]; reasoning?: string; annotations?: UrlCitationAnnotation[]; cost?: number | null; durationMs?: number; }