/** * Google Cloud Monitoring integration for AI Universe * Exports singleton instance for shared monitoring across all services * @packageDocumentation */ /** * Metric types supported by the monitoring service */ export type MetricType = 'tool_call_latency' | 'tool_call_count' | 'tool_call_errors' | 'http_request_latency' | 'http_request_count' | 'http_request_errors' | 'http_request_size_bytes' | 'http_response_size_bytes' | 'active_requests' | 'token_usage' | 'streaming_chunks' | 'auth_attempts' | 'rate_limit_hits'; /** * Labels for metrics to enable filtering and grouping */ export interface MetricLabels { tool_name?: string; model_name?: string; operation?: string; domain?: string; status_code?: string; status?: string; error_type?: string; user_id?: string; endpoint?: string; [key: string]: string | undefined; } /** * Logger interface for monitoring service */ export interface MonitoringLogger { info: (message: string, meta?: any) => void; warn: (message: string, meta?: any) => void; error: (message: string, meta?: any) => void; debug: (message: string, meta?: any) => void; } /** * Configuration for monitoring service */ export interface MonitoringConfig { projectId: string; enabled: boolean; writeInterval?: number; maxBatchSize?: number; logger?: MonitoringLogger; metricPrefix?: string; maxRetries?: number; retryDelay?: number; maxClockSkewMs?: number; minSamplingPeriodMs?: number; } /** * Google Cloud Monitoring service * * Provides centralized monitoring for: * - Tool call latency and success/failure rates * - HTTP request latency and error rates * - Token usage tracking * - Rate limiting and authentication metrics * - Active request gauges */ export declare class MonitoringService { private client; private config; private initialized; private initializationAttempts; private pendingMetrics; private writeIntervalHandle; private readonly logger; private readonly metricPrefix; constructor(config?: Partial); /** * Detect if Application Default Credentials are available * Supports: * - GOOGLE_APPLICATION_CREDENTIALS (local dev with service account) * - Cloud Run Workload Identity (GOOGLE_CLOUD_PROJECT or K_SERVICE) * - GCP Compute Engine / GKE metadata server * * Disables monitoring in CI environments where GCP env vars are set * for configuration but no actual credentials are available. */ private detectApplicationDefaultCredentials; /** * Initialize the monitoring service with retry logic */ private ensureInitialized; /** * Start batch writing of metrics */ private startBatchWriting; /** * Record a metric value */ recordMetric(type: MetricType, value: number, labels?: MetricLabels): Promise; /** * Record latency for an operation */ recordLatency(type: MetricType, durationMs: number, labels?: MetricLabels): Promise; /** * Increment a counter metric */ incrementCounter(type: MetricType, labels?: MetricLabels): Promise; /** * Record a gauge value (e.g., active requests) */ recordGauge(type: MetricType, value: number, labels?: MetricLabels): Promise; /** * Round timestamp to the nearest sampling period bucket * This prevents Google Cloud Monitoring INVALID_ARGUMENT errors for duplicate timestamps */ private roundTimestampToBucket; /** * Flush pending metrics to Google Cloud Monitoring */ flushMetrics(): Promise; /** * Create exponential buckets for distribution metrics (latency) * Buckets: 0-10ms, 10-100ms, 100ms-1s, 1s-10s, 10s-100s */ private createExponentialBuckets; /** * Create a distribution value for latency metrics */ private createDistributionValue; /** * Adjust timestamp to prevent clock skew issues with GCP Monitoring * GCP rejects timestamps >5min in the future, so we cap all future timestamps to "now" * * @param timestamp Original timestamp * @returns Adjusted timestamp (capped to current time if in future) */ private adjustTimestampForClockSkew; /** * Create a time series object for Google Cloud Monitoring */ private createTimeSeries; /** * Check if a metric type should use DISTRIBUTION (latency, size histograms) */ private isLatencyMetric; /** * Get the metric kind for a metric type */ private getMetricKind; /** * Helper: Measure and record execution time of an async function */ measureAsync(metricType: MetricType, labels: MetricLabels, fn: () => Promise): Promise; /** * Helper: Measure and record execution time of a sync function */ measure(metricType: MetricType, labels: MetricLabels, fn: () => T): T; /** * Shutdown the monitoring service gracefully */ shutdown(): Promise; /** * Get monitoring statistics (for debugging/health checks) */ getStats(): { enabled: boolean; pendingMetrics: number; projectId: string; }; } export declare const monitoringService: MonitoringService; /** * Helper function for measuring tool calls * Uses the singleton monitoringService instance to avoid memory leaks */ export interface ToolMonitoringOptions { labels?: MetricLabels; logger?: MonitoringLogger; } export declare function withToolMonitoring(toolName: string, operation: string, fn: () => Promise, options?: ToolMonitoringOptions): Promise; /** * Helper function for measuring HTTP calls * Uses the singleton monitoringService instance to avoid memory leaks */ export declare function withHttpMonitoring(domain: string, operation: string, fn: () => Promise, getStatusCode?: () => string | undefined, logger?: MonitoringLogger): Promise; //# sourceMappingURL=MonitoringService.d.ts.map