read_snapshot_models(); $custom = $this->is_custom_model( $provider, $model ); $rate = $this->lookup_in_snapshot( $snapshot, $provider, $model, $custom ); if ( null === $rate ) { $rate = $custom ? array( 0.0, 0.0 ) : $this->lookup_in_baseline( $provider, $model, max( 0, $input_tokens ) ); } /** * Filter the resolved [input_per_million, output_per_million] pair. * * Existing sites that hooked into `aipt_api_pricing` to override prices * continue to work — the filter is applied after the snapshot lookup * so overrides always win. * * @since 2.6.0 * @param array{0: float, 1: float} $rate Current per-1M USD tuple. * @param string $provider Plugin provider id. * @param string $model Model identifier. */ $rate = apply_filters( 'aipt_pricing_resolved_rate', $rate, $provider, $model ); $rate = $this->apply_legacy_filter( $rate, $provider, $model ); if ( ! is_array( $rate ) || count( $rate ) < 2 ) { return array( 0.0, 0.0 ); } return array( max( 0.0, (float) $rate[0] ), max( 0.0, (float) $rate[1] ) ); } /** * Trigger an HTTP refresh of the remote snapshot. * * @param bool $force When true, ignores the in-progress lock (used by * manual admin button after a stuck cron). * @return array{ok: bool, status: string, message: string, model_count: int} */ public function refresh( bool $force = false ): array { if ( ! $this->has_opted_in() ) { return array( 'ok' => false, 'status' => 'not_opted_in', 'message' => 'Pricing updates are paused until the plugin setup is completed.', 'model_count' => $this->get_model_count(), ); } if ( ! $force && get_transient( self::LOCK_TRANSIENT ) ) { return array( 'ok' => false, 'status' => 'locked', 'message' => 'A refresh is already in progress; try again shortly.', 'model_count' => $this->get_model_count(), ); } set_transient( self::LOCK_TRANSIENT, 1, 5 * MINUTE_IN_SECONDS ); try { $url = $this->get_feed_url(); $response = wp_remote_get( $url, array( 'timeout' => self::FETCH_TIMEOUT, 'headers' => array( 'accept' => 'application/json', 'user-agent' => 'AIPT/' . AIPT_VERSION . '; ' . home_url( '/' ), ), ) ); if ( $response instanceof \WP_Error ) { $message = $response->get_error_message(); $this->record_failure( $message ); return array( 'ok' => false, 'status' => 'error', 'message' => $message, 'model_count' => $this->get_model_count(), ); } $code = (int) wp_remote_retrieve_response_code( $response ); if ( $code < 200 || $code >= 300 ) { $message = sprintf( 'HTTP %d from pricing feed', $code ); $this->record_failure( $message ); return array( 'ok' => false, 'status' => 'error', 'message' => $message, 'model_count' => $this->get_model_count(), ); } $body = (string) wp_remote_retrieve_body( $response ); $decoded = json_decode( $body, true ); if ( ! is_array( $decoded ) || empty( $decoded['models'] ) || ! is_array( $decoded['models'] ) ) { $this->record_failure( 'Malformed response: missing models map.' ); return array( 'ok' => false, 'status' => 'error', 'message' => 'Pricing feed returned a malformed payload.', 'model_count' => $this->get_model_count(), ); } $models = $decoded['models']; $source = isset( $decoded['source'] ) ? sanitize_key( (string) $decoded['source'] ) : 'unknown'; $upstream_ts = isset( $decoded['updated_at'] ) ? sanitize_text_field( (string) $decoded['updated_at'] ) : ''; update_option( self::OPTION_SNAPSHOT, $models, false ); update_option( self::OPTION_META, array( 'updated_at' => time(), 'upstream_at' => $upstream_ts, 'source' => $source, 'status' => 'fresh', 'model_count' => count( $models ), 'failures' => 0, 'last_error' => '', 'feed_url' => $url, ), false ); return array( 'ok' => true, 'status' => 'fresh', 'message' => sprintf( 'Pricing snapshot refreshed (%d models).', count( $models ) ), 'model_count' => count( $models ), ); } finally { delete_transient( self::LOCK_TRANSIENT ); } } /** * Snapshot metadata for the dashboard UI. * * @return array{ * updated_at:int|null, * upstream_at:string, * source:string, * status:string, * model_count:int, * failures:int, * last_error:string, * feed_url:string * } */ public function get_snapshot_meta(): array { $meta = get_option( self::OPTION_META, array() ); if ( ! is_array( $meta ) ) { $meta = array(); } $updated_at = isset( $meta['updated_at'] ) ? (int) $meta['updated_at'] : 0; $status = isset( $meta['status'] ) ? (string) $meta['status'] : 'never'; if ( 'fresh' === $status && $updated_at > 0 ) { if ( ( time() - $updated_at ) > self::STALE_AFTER_DAYS * DAY_IN_SECONDS ) { $status = 'stale'; } } return array( 'updated_at' => $updated_at > 0 ? $updated_at : null, 'upstream_at' => isset( $meta['upstream_at'] ) ? (string) $meta['upstream_at'] : '', 'source' => isset( $meta['source'] ) ? (string) $meta['source'] : '', 'status' => $status, 'model_count' => isset( $meta['model_count'] ) ? (int) $meta['model_count'] : 0, 'failures' => isset( $meta['failures'] ) ? (int) $meta['failures'] : 0, 'last_error' => isset( $meta['last_error'] ) ? (string) $meta['last_error'] : '', 'feed_url' => isset( $meta['feed_url'] ) ? (string) $meta['feed_url'] : $this->get_feed_url(), ); } /** * Cron entry point — wraps refresh() so a thrown exception never bubbles * into the cron runner. * * @return void */ public static function cron_callback(): void { try { self::instance()->refresh( false ); } catch ( \Throwable $e ) { Logger::error( 'cron', 'Pricing refresh threw', array( 'error' => $e->getMessage() ) ); } } /** * Whether the user completed the Freemius opt-in (wp.org guideline #7). * * Before the opt-in dialog is answered — and for installs that skipped * it — the site must not contact the remote feed. `is_registered()` is * true only once the user connected, so pending and skipped installs * stay offline here. * * @return bool */ private function has_opted_in(): bool { return FsManager::getInstance()->is_registered(); } /** * @return array */ private function read_snapshot_models(): array { $snapshot = get_option( self::OPTION_SNAPSHOT, array() ); return is_array( $snapshot ) ? $snapshot : array(); } private function get_model_count(): int { $meta = $this->get_snapshot_meta(); return (int) $meta['model_count']; } /** * The feed's prompt cache write and read rates for a model as ratios of * its input rate, each null when the feed lists no positive rate. * * @param string $provider Plugin provider id. * @param string $model Model identifier as sent to the provider. * @return array{0: float|null, 1: float|null} [write ratio, read ratio]. */ public function cache_rate_ratios( string $provider, string $model ): array { $entry = $this->find_snapshot_entry( $this->read_snapshot_models(), $provider, $model, $this->is_custom_model( $provider, $model ) ); $input = null !== $entry ? (float) $entry['in'] : 0.0; if ( $input <= 0.0 ) { return array( null, null ); } return array( self::rate_ratio( $entry['cache_write'] ?? null, $input ), self::rate_ratio( $entry['cache_read'] ?? null, $input ), ); } /** * A feed rate as a ratio of the input rate. A missing, non-numeric or * zero rate is unknown, not free, so it answers null. * * @param mixed $rate Rate the feed lists, USD per million tokens. * @param float $input Positive input rate of the same model. * @return float|null */ private static function rate_ratio( $rate, float $input ): ?float { if ( ! is_numeric( $rate ) || (float) $rate <= 0.0 ) { return null; } return (float) $rate / $input; } /** * Whether the id is one the site owner stored for a direct provider and * the catalog does not list. A catalog id or OpenRouter route answers false * without reading the store. */ private function is_custom_model( string $provider, string $model ): bool { return ModelCatalog::is_custom_model( $provider, $model ); } /** * @param array $snapshot * @param bool $exact_only Skip the family-prefix match. * @return array{0: float, 1: float}|null */ private function lookup_in_snapshot( array $snapshot, string $provider, string $model, bool $exact_only = false ): ?array { $entry = $this->find_snapshot_entry( $snapshot, $provider, $model, $exact_only ); return null !== $entry ? array( (float) $entry['in'], (float) $entry['out'] ) : null; } /** * The snapshot entry that prices a model: its exact key, else the longest * dash-bounded family prefix unless $exact_only is set. Only entries with * both rates count. * * @param array $snapshot * @param bool $exact_only Skip the family-prefix match. * @return array|null */ private function find_snapshot_entry( array $snapshot, string $provider, string $model, bool $exact_only = false ): ?array { if ( empty( $snapshot ) || '' === $model ) { return null; } $candidates = $this->build_lookup_keys( $provider, $model ); foreach ( $candidates as $key ) { if ( isset( $snapshot[ $key ]['in'], $snapshot[ $key ]['out'] ) ) { return $snapshot[ $key ]; } } if ( $exact_only ) { return null; } $primary = sprintf( '%s/%s', $provider, $model ); $best = null; $best_len = 0; foreach ( $snapshot as $key => $value ) { if ( ! is_string( $key ) || ! isset( $value['in'], $value['out'] ) ) { continue; } if ( strlen( $key ) >= strlen( $primary ) ) { continue; } if ( 0 !== strpos( $primary, $key . '-' ) ) { continue; } if ( strlen( $key ) > $best_len ) { $best = $value; $best_len = strlen( $key ); } } return $best; } /** * Whether a published rate exists for this exact model, as opposed to the * provider-level default `resolve()` falls back to. Cost estimates shown * to the merchant use this so an unlisted model never gets an invented * price. A stored custom id counts only through an exact snapshot key or * an exact legacy filter row. * * @param string $provider Plugin provider id. * @param string $model Model identifier as sent to the provider. * @return bool */ public function has_known_rate( string $provider, string $model ): bool { $custom = $this->is_custom_model( $provider, $model ); if ( null !== $this->lookup_in_snapshot( $this->read_snapshot_models(), $provider, $model, $custom ) ) { return true; } if ( $custom ) { return $this->has_legacy_filter_rate( $provider, $model ); } if ( null !== $this->lookup_in_baseline_table( $provider, $model, 0 ) ) { return true; } return $this->has_legacy_filter_rate( $provider, $model ); } /** * Whether the legacy `aipt_api_pricing` filter supplies a row for this * exact model that differs from the baseline table's own row. The * baseline row left as it was is no override, as in apply_legacy_filter(): * a stored custom id the baseline happens to list stays unpriced. */ private function has_legacy_filter_rate( string $provider, string $model ): bool { $baseline_table = ApiPricing::get_baseline_table(); $legacy_table = apply_filters( 'aipt_api_pricing', $baseline_table ); if ( ! is_array( $legacy_table ) ) { return false; } $key = sprintf( '%s/%s', strtolower( $provider ), strtolower( $model ) ); $row = $legacy_table[ $key ] ?? null; if ( ! is_array( $row ) || ! isset( $row[0], $row[1] ) || ! is_numeric( $row[0] ) || ! is_numeric( $row[1] ) ) { return false; } return ! self::is_baseline_row( $baseline_table, $key, array( (float) $row[0], (float) $row[1] ) ); } /** * Whether a rate from the legacy filter is the baseline table's own row * for this key. Rates compare as floats, so the row returned as ints or * numeric strings is still the baseline row. * * @param array $baseline_table ApiPricing::get_baseline_table(). * @param array{0: float, 1: float} $legacy_rate The filter's rate for the key. */ private static function is_baseline_row( array $baseline_table, string $key, array $legacy_rate ): bool { $baseline_rate = $baseline_table[ $key ] ?? null; return is_array( $baseline_rate ) && (float) ( $baseline_rate[0] ?? 0 ) === $legacy_rate[0] && (float) ( $baseline_rate[1] ?? 0 ) === $legacy_rate[1]; } /** * @return array{0: float, 1: float} */ private function lookup_in_baseline( string $provider, string $model, int $input_tokens ): array { return $this->lookup_in_baseline_table( $provider, $model, $input_tokens ) ?? ApiPricing::get_provider_fallback( $provider ); } /** * Baseline table lookup (exact key, then family prefix) without the * provider-level fallback. * * @return array{0: float, 1: float}|null */ private function lookup_in_baseline_table( string $provider, string $model, int $input_tokens ): ?array { $baseline_rate = ApiPricing::get_baseline_rate( $provider, $model, $input_tokens ); if ( null !== $baseline_rate ) { return $baseline_rate; } $baseline = ApiPricing::get_baseline_table(); $key = sprintf( '%s/%s', strtolower( $provider ), strtolower( $model ) ); if ( isset( $baseline[ $key ] ) && is_array( $baseline[ $key ] ) ) { return array( (float) ( $baseline[ $key ][0] ?? 0 ), (float) ( $baseline[ $key ][1] ?? 0 ), ); } $best = null; $best_len = 0; foreach ( $baseline as $candidate_key => $rate ) { if ( ! is_array( $rate ) ) { continue; } if ( strlen( $candidate_key ) >= strlen( $key ) ) { continue; } if ( 0 !== strpos( $key, $candidate_key . '-' ) ) { continue; } if ( strlen( $candidate_key ) > $best_len ) { $best = $rate; $best_len = strlen( $candidate_key ); } } if ( $best ) { return array( (float) ( $best[0] ?? 0 ), (float) ( $best[1] ?? 0 ) ); } return null; } /** * @return string[] */ private function build_lookup_keys( string $provider, string $model ): array { $provider = strtolower( trim( $provider ) ); $model = strtolower( trim( $model ) ); if ( '' === $provider || '' === $model ) { return array(); } $keys = array( sprintf( '%s/%s', $provider, $model ) ); if ( 'openrouter' === $provider && false === strpos( $model, '/' ) ) { $keys[] = sprintf( 'openrouter/%s', $model ); } return $keys; } /** * Apply the legacy `aipt_api_pricing` filter to preserve overrides set * by sites that wired into the old ApiPricing::PRICING shape. * * @param array{0: float, 1: float} $rate * @return array{0: float, 1: float} */ private function apply_legacy_filter( array $rate, string $provider, string $model ): array { $baseline_table = ApiPricing::get_baseline_table(); $legacy_table = apply_filters( 'aipt_api_pricing', $baseline_table ); if ( ! is_array( $legacy_table ) ) { return $rate; } $key = sprintf( '%s/%s', strtolower( $provider ), strtolower( $model ) ); if ( isset( $legacy_table[ $key ] ) && is_array( $legacy_table[ $key ] ) ) { $legacy_rate = array( (float) ( $legacy_table[ $key ][0] ?? $rate[0] ), (float) ( $legacy_table[ $key ][1] ?? $rate[1] ), ); if ( self::is_baseline_row( $baseline_table, $key, $legacy_rate ) ) { return $rate; } return $legacy_rate; } return $rate; } private function get_feed_url(): string { /** * Filter the upstream pricing feed URL. * * Defaults to api.aiforwoo.com — override for self-hosted backends or * test fixtures. * * @since 2.6.0 * @param string $url Default feed URL. */ $url = apply_filters( 'aipt_pricing_feed_url', self::DEFAULT_FEED_URL ); if ( ! is_string( $url ) || '' === trim( $url ) ) { return self::DEFAULT_FEED_URL; } return esc_url_raw( $url ); } private function record_failure( string $reason ): void { $meta = get_option( self::OPTION_META, array() ); if ( ! is_array( $meta ) ) { $meta = array(); } $meta['failures'] = isset( $meta['failures'] ) ? (int) $meta['failures'] + 1 : 1; $meta['status'] = 'error'; $meta['last_error'] = substr( $reason, 0, 500 ); update_option( self::OPTION_META, $meta, false ); } }