Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
88.24% covered (warning)
88.24%
180 / 204
69.57% covered (warning)
69.57%
16 / 23
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_AI_Sidebar
88.67% covered (warning)
88.67%
180 / 203
69.57% covered (warning)
69.57%
16 / 23
114.54
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
 maybe_enqueue_abilities_script
92.31% covered (success)
92.31%
24 / 26
0.00% covered (danger)
0.00%
0 / 1
7.02
 get_asset_data_from_file
30.00% covered (danger)
30.00%
3 / 10
0.00% covered (danger)
0.00%
0 / 1
13.57
 get_asset_data_from_remote
27.27% covered (danger)
27.27%
3 / 11
0.00% covered (danger)
0.00%
0 / 1
25.85
 register_provider
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
5.03
 get_ai_sidebar_asset_data
78.57% covered (warning)
78.57%
11 / 14
0.00% covered (danger)
0.00%
0 / 1
7.48
 is_seo_suggestions_enabled
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 is_draft_assist_enabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_jetpack_ai_sidebar_preview_enabled
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
6
 has_enabled_sidebar_features
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 should_expose_provider
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 is_agents_manager_disconnected
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 get_jetpack_ai_sidebar_preview_config
100.00% covered (success)
100.00%
29 / 29
100.00% covered (success)
100.00%
1 / 1
14
 is_toolbar_button_enabled
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 register_toolbar_button_extension
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 add_agents_manager_data
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
4
 get_agents_manager_data_fields
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 enable_agents_manager_on_provider_surfaces
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 maybe_patch_jetpack_ai_sidebar_preview_data
95.65% covered (success)
95.65%
22 / 23
0.00% covered (danger)
0.00%
0 / 1
8
 get_agent_provider_upsert_script
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 is_block_editor
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
3.14
 is_supported_provider_surface
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
6
 has_ai_features
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2/**
3 * Jetpack AI Sidebar — Agents Manager integration and provider registration.
4 *
5 * Initializes the jetpack-agents-manager package so it loads the Agents
6 * Manager bundle and emits its `agentsManagerData` payload, registers Jetpack
7 * AI as an Agents Manager provider, and loads the Jetpack AI provider bundle
8 * that exposes Jetpack AI abilities in the block editor.
9 *
10 * @package automattic/jetpack
11 */
12
13namespace Automattic\Jetpack\Extensions\AiAssistantPlugin;
14
15use Automattic\Jetpack\Agents_Manager\Agents_Manager;
16use Automattic\Jetpack\Connection\Manager as Connection_Manager;
17use Automattic\Jetpack\SEO\Ai_Seo;
18use Automattic\Jetpack\Status;
19use Automattic\Jetpack\Status\Host;
20
21// Required directly rather than relying on the plugin bootstrap: on
22// WordPress.com Simple the extension files load through wpcom's own loader
23// and load-jetpack.php never runs.
24require_once __DIR__ . '/../../../../_inc/lib/class-jetpack-ai-settings.php';
25
26const AM_ASSET_BASE_PATH                  = 'widgets.wp.com/agents-manager/';
27const AI_SIDEBAR_ASSET_TRANSIENT          = 'jetpack_ai_sidebar_asset';
28const AI_SIDEBAR_JS_URL                   = 'https://' . AM_ASSET_BASE_PATH . 'jetpack-ai-sidebar.min.js';
29const AI_SIDEBAR_CSS_URL                  = 'https://' . AM_ASSET_BASE_PATH . 'jetpack-ai-sidebar.css';
30const AI_SIDEBAR_RTL_CSS_URL              = 'https://' . AM_ASSET_BASE_PATH . 'jetpack-ai-sidebar.rtl.css';
31const AI_SIDEBAR_PROVIDER_URL             = 'https://' . AM_ASSET_BASE_PATH . 'jetpack-ai-sidebar.provider.mjs';
32const AI_SIDEBAR_AGENT_ID                 = 'wp-orchestrator';
33const AI_SIDEBAR_TOOLBAR_BUTTON_EXTENSION = 'ai-sidebar-toolbar-button';
34
35/**
36 * Initializes the Agents Manager package and registers the Jetpack AI
37 * provider in the block editor.
38 */
39class Jetpack_AI_Sidebar {
40
41    /**
42     * Initialize hooks.
43     *
44     * @return void
45     */
46    public static function init(): void {
47        // Gate the whole sidebar entrypoint on the preview surface, which is
48        // itself overridable via the jetpack_ai_sidebar_enabled filter.
49        if ( ! self::is_jetpack_ai_sidebar_preview_enabled() ) {
50            return;
51        }
52
53        // Initialize the Agents Manager package so it owns loading the Agents
54        // Manager bundle and emitting the `agentsManagerData` payload. The call
55        // is idempotent: on WordPress.com and Atomic, jetpack-mu-wpcom may have
56        // already initialized it, in which case this is a no-op.
57        Agents_Manager::init();
58
59        // Register as Agents Manager provider. The filter fires inside
60        // Agents_Manager::enqueue_scripts(). Priority 20 so Jetpack loads
61        // AFTER Image Studio (priority 10).
62        add_filter( 'agents_manager_agent_providers', array( __CLASS__, 'register_provider' ), 20 );
63
64        add_filter( 'jetpack_ai_sidebar_agents_manager_data', array( __CLASS__, 'add_agents_manager_data' ), 10, 1 );
65
66        // Ask the Agents Manager package to mount on Jetpack AI provider surfaces.
67        add_filter( 'agents_manager_enabled_in_block_editor', array( __CLASS__, 'enable_agents_manager_on_provider_surfaces' ) );
68
69        // Enqueue the IIFE bundle on supported editor surfaces — it registers
70        // Jetpack AI abilities via @wordpress/abilities, which Big Sky or the
71        // Agents Manager can discover regardless of which provider system is active.
72        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'maybe_enqueue_abilities_script' ), 201 );
73
74        // Patch Jetpack AI Sidebar Preview data into agentsManagerData when the
75        // Agents Manager bundle was enqueued by an external host (Big Sky on
76        // Atomic, etc.) and the jetpack_ai_sidebar_agents_manager_data filter
77        // never fired. Priority 250 runs after both jetpack-mu-wpcom and the
78        // Agents Manager package enqueue (priority 101).
79        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'maybe_patch_jetpack_ai_sidebar_preview_data' ), 250 );
80
81        // Let editor JS know when the Jetpack AI Sidebar toolbar button replaces the legacy AI toolbar.
82        add_action( 'jetpack_register_gutenberg_extensions', array( __CLASS__, 'register_toolbar_button_extension' ), 99 );
83    }
84
85    // ──────────────────────────────────────────────────
86    // Jetpack AI provider bundle
87    // ──────────────────────────────────────────────────
88
89    /**
90     * Enqueue the IIFE bundle that registers Jetpack AI abilities.
91     *
92     * This runs independently of AM/provider registration so preview abilities
93     * are available even when Big Sky standalone is the active UI.
94     *
95     * @return void
96     */
97    public static function maybe_enqueue_abilities_script(): void {
98        if ( ! self::should_expose_provider() ) {
99            return;
100        }
101
102        // CIAB (next-admin) has its own AM setup — don't enqueue alongside it.
103        if ( did_action( 'next_admin_init' ) ) {
104            return;
105        }
106
107        if ( self::is_agents_manager_disconnected() ) {
108            return;
109        }
110
111        // Guard against double-enqueue (e.g. hooked multiple times).
112        if ( wp_script_is( 'jetpack-ai-provider' ) ) {
113            return;
114        }
115
116        $asset_data = self::get_ai_sidebar_asset_data();
117        if ( ! $asset_data ) {
118            return;
119        }
120
121        $version      = $asset_data['version'] ?? false;
122        $dependencies = $asset_data['dependencies'] ?? array();
123
124        wp_enqueue_script(
125            'jetpack-ai-provider',
126            AI_SIDEBAR_JS_URL,
127            $dependencies,
128            $version,
129            true
130        );
131
132        wp_enqueue_style(
133            'jetpack-ai-provider',
134            is_rtl() ? AI_SIDEBAR_RTL_CSS_URL : AI_SIDEBAR_CSS_URL,
135            array(),
136            $version
137        );
138    }
139
140    // ──────────────────────────────────────────────────
141    // Asset manifest (Image Studio pattern)
142    // ──────────────────────────────────────────────────
143
144    /**
145     * Try to read the asset manifest from the local filesystem.
146     *
147     * On WordPress.com, widgets.wp.com assets are available at ABSPATH.
148     *
149     * @param string $relative_path The relative path to the JSON file.
150     * @return array|false The decoded asset data, or false if not available locally.
151     */
152    private static function get_asset_data_from_file( string $relative_path ) {
153        $local_path = ABSPATH . $relative_path;
154        if ( ! file_exists( $local_path ) ) {
155            return false;
156        }
157
158        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Reading a local file, not a remote URL.
159        $contents = file_get_contents( $local_path );
160        if ( false === $contents ) {
161            return false;
162        }
163
164        $data = json_decode( $contents, true );
165        if ( json_last_error() !== JSON_ERROR_NONE || ! is_array( $data ) ) {
166            return false;
167        }
168
169        return $data;
170    }
171
172    /**
173     * Fetch the asset manifest via HTTP.
174     *
175     * @param string $url The URL to fetch.
176     * @return array|false The decoded asset data, or false on failure.
177     */
178    private static function get_asset_data_from_remote( string $url ) {
179        $response = wp_safe_remote_get( $url );
180        if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
181            return false;
182        }
183
184        $content_type = wp_remote_retrieve_header( $response, 'content-type' );
185        if ( is_string( $content_type ) && false === stripos( $content_type, 'json' ) ) {
186            return false;
187        }
188
189        $body = wp_remote_retrieve_body( $response );
190        $data = json_decode( $body, true );
191        if ( json_last_error() !== JSON_ERROR_NONE || ! is_array( $data ) ) {
192            return false;
193        }
194
195        return $data;
196    }
197
198    // ──────────────────────────────────────────────────
199    // Provider registration
200    // ──────────────────────────────────────────────────
201
202    /**
203     * Register Jetpack AI as an Agents Manager provider.
204     *
205     * Appends the CDN-hosted ESM wrapper URL to the providers list so AM
206     * can dynamically import it. Asset enqueueing is handled separately by
207     * maybe_enqueue_abilities_script.
208     *
209     * @param array $providers Existing provider URLs.
210     * @return array Updated providers.
211     */
212    public static function register_provider( array $providers ): array {
213        // CIAB (next-admin) has AM natively — skip to avoid duplicate agents.
214        if ( did_action( 'next_admin_init' ) ) {
215            return $providers;
216        }
217
218        // The provider IIFE is enqueued on the same surfaces where the ESM
219        // wrapper is registered. Avoid registering the wrapper when AM may
220        // import it before window.__JetpackAIProvider exists.
221        if ( ! self::should_expose_provider() ) {
222            return $providers;
223        }
224
225        // The providers filter still runs for disconnected variants.
226        if ( self::is_agents_manager_disconnected() ) {
227            return $providers;
228        }
229
230        // Don't register if the IIFE bundle cannot be loaded. The ESM wrapper
231        // re-exports from window.__JetpackAIProvider at import time; if the
232        // IIFE never ran, toolProvider is still a truthy Proxy and AM would
233        // call getAbilities() on it and get undefined, breaking the merge.
234        if ( ! self::get_ai_sidebar_asset_data() ) {
235            return $providers;
236        }
237
238        // Register as AM provider via CDN-hosted ESM wrapper.
239        // AM dynamically imports this module to merge tools, suggestions, and components.
240        // No ?ver= needed — the wrapper re-exports from window.__JetpackAIProvider
241        // at import time, so its behavior always matches the loaded IIFE bundle.
242        $providers[] = AI_SIDEBAR_PROVIDER_URL;
243
244        return $providers;
245    }
246
247    /**
248     * Fetch and cache the CDN asset manifest for the AI sidebar bundle.
249     *
250     * @return array|false The decoded asset data, or false on failure.
251     */
252    private static function get_ai_sidebar_asset_data() {
253        $skip_cache = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG;
254
255        if ( ! $skip_cache ) {
256            $cached = get_transient( AI_SIDEBAR_ASSET_TRANSIENT );
257            if ( false !== $cached ) {
258                return $cached;
259            }
260        }
261
262        $json_path = AM_ASSET_BASE_PATH . 'jetpack-ai-sidebar.asset.json';
263
264        // Try local file first (available on WordPress.com).
265        $data = self::get_asset_data_from_file( $json_path );
266
267        // Fallback to remote fetch.
268        if ( false === $data ) {
269            $data = self::get_asset_data_from_remote( 'https://' . $json_path );
270        }
271
272        if ( false === $data ) {
273            // The manifest is unavailable from both the local file and the CDN
274            // — for example when the server cannot reach widgets.wp.com. Skip
275            // rather than enqueue a provider whose bundle the browser may also
276            // be unable to load, which would break the Agents Manager merge.
277            return false;
278        }
279
280        if ( ! $skip_cache ) {
281            set_transient( AI_SIDEBAR_ASSET_TRANSIENT, $data, HOUR_IN_SECONDS );
282        }
283
284        return $data;
285    }
286
287    // ──────────────────────────────────────────────────
288    // Helper methods
289    // ──────────────────────────────────────────────────
290
291    /**
292     * UI feature flag for the SEO suggestions (SEO title and meta description).
293     *
294     * Two halves: the site can offer AI SEO at all — the package's shared gate,
295     * the same one the AI settings row uses, so the control and the surface it
296     * governs cannot drift — and the feature's own toggle is on. Kept independent
297     * of the Optimize Title suggestion: SEO suggestions target the SEO meta
298     * fields, not the visible post title.
299     *
300     * The SEO *feature* option is consulted, not the automatic-generation one:
301     * a switched-off feature must not offer suggestions, even user-initiated
302     * ones, while automatic generation governs only automatic runs.
303     *
304     * Guarded with class_exists: the autoloader can pick an older jetpack-seo
305     * copy from another plugin, predating the shared gate. Suggestions stay off
306     * without it.
307     *
308     * @return bool
309     */
310    private static function is_seo_suggestions_enabled(): bool {
311        return class_exists( Ai_Seo::class )
312            && Ai_Seo::is_available()
313            && \Jetpack_AI_Settings::is_ai_seo_enabled();
314    }
315
316    /**
317     * UI feature flag for Draft Assist: turning an empty new post or page into a first draft.
318     *
319     * Exposed only in internal testing environments while the feature is in development.
320     * Governs both halves of the feature: the sidebar suggestion offered on an empty post
321     * and the client-side ability that writes the generated draft into the open post.
322     * No plan gate: the draft is written into a post the user can already edit.
323     *
324     * @return bool
325     */
326    private static function is_draft_assist_enabled(): bool {
327        return jetpack_is_internal_testing_environment();
328    }
329
330    /**
331     * UI feature flag for the public Jetpack AI Sidebar Preview surface.
332     *
333     * Defaults to enabled only on WordPress.com platform sites (Simple or WoA)
334     * that have the Big Sky plugin present and enabled. Big Sky defaults on for
335     * Simple sites and off on WoA/Atomic. The jetpack_ai_sidebar_enabled filter
336     * is a host-level override of that default, respected by init() and every
337     * sidebar surface that gates on this method. Independently of the filter,
338     * the sidebar requires at least one of its features (writing assistant or
339     * SEO enhancer) to be enabled.
340     *
341     * @return bool
342     */
343    private static function is_jetpack_ai_sidebar_preview_enabled(): bool {
344        $host = new Host();
345
346        $enabled = false;
347        if ( $host->is_wpcom_platform() && class_exists( 'Big_Sky' ) ) {
348            $default = $host->is_wpcom_simple() ? '1' : '0';
349            $enabled = (bool) get_option( 'big_sky_enable', $default );
350        }
351
352        /**
353         * Filter to enable or disable the Jetpack AI sidebar feature.
354         *
355         * Defaults to true only on WordPress.com platform sites with Big Sky
356         * present and enabled. Acts as a host-level override that can force the
357         * sidebar on (e.g. for local development) or off, and is respected by
358         * init() and every sidebar surface. The override cannot force the
359         * sidebar on while the writing-assistant and SEO enhancer features are
360         * both off — a featureless sidebar never loads.
361         *
362         * @param bool $enabled Whether the Jetpack AI sidebar is enabled.
363         */
364        $enabled = (bool) apply_filters( 'jetpack_ai_sidebar_enabled', $enabled );
365
366        // Re-asserted after the filter so a later filter cannot surface a
367        // sidebar whose features are all off, or one blocked by the host or
368        // master gates — the gates are final, as with is_ai_enabled().
369        return $enabled
370            && \Jetpack_AI_Settings::apply_master_gates( true )
371            && self::has_enabled_sidebar_features();
372    }
373
374    /**
375     * Whether any feature the sidebar surfaces is effectively enabled; with
376     * nothing to offer it must not load. Caveat: init() runs before seo-tools
377     * registers jetpack_disable_seo_tools, so that term reads its default here.
378     *
379     * @return bool
380     */
381    private static function has_enabled_sidebar_features(): bool {
382        return \Jetpack_AI_Settings::is_feature_enabled( 'writing_assistant' )
383            || self::is_seo_suggestions_enabled();
384    }
385
386    /**
387     * Whether the Jetpack AI provider bundle should be exposed for this request.
388     *
389     * This is scoped to the supported editor surfaces: post editor, page editor,
390     * and site editor. Each surface remains subject to the preview and AI feature
391     * gates.
392     *
393     * @return bool
394     */
395    private static function should_expose_provider(): bool {
396        return self::is_jetpack_ai_sidebar_preview_enabled()
397            && self::is_supported_provider_surface()
398            && self::has_ai_features();
399    }
400
401    /**
402     * Whether the Agents Manager is loading a disconnected build, which it does
403     * when the current user has no linked WordPress.com account.
404     *
405     * @return bool
406     */
407    private static function is_agents_manager_disconnected(): bool {
408        $variant = Agents_Manager::get_active_variant();
409
410        // Null means the Agents Manager is not loading at all, which is not a disconnection.
411        return is_string( $variant ) && str_contains( $variant, 'disconnected' );
412    }
413
414    /**
415     * Preview configuration consumed by the Agents Manager and Jetpack AI provider bundles.
416     *
417     * @return array Preview mode and feature availability.
418     */
419    private static function get_jetpack_ai_sidebar_preview_config(): array {
420        // Ability permission callbacks enforce server-side access for these
421        // features. The writing suggestions additionally follow the writing
422        // assistant toggle on the AI settings page — a switched-off feature
423        // must not surface suggestions even when an external host (Big Sky,
424        // Woo) draws the sidebar — and SEO requires the site-side gates below.
425        $writing_on = \Jetpack_AI_Settings::is_feature_enabled( 'writing_assistant' );
426
427        $features = array(
428            'aiEditorialReview'       => (bool) apply_filters( 'jetpack_ai_editorial_review_enabled', true ) && $writing_on,
429            'generateFeedback'        => $writing_on,
430            'proofreadContent'        => $writing_on,
431            'blockTransformations'    => $writing_on,
432            'blockToolbarButton'      => $writing_on,
433            'optimizeTitleSuggestion' => $writing_on,
434            'seoSuggestions'          => self::is_seo_suggestions_enabled(),
435            'excerptSuggestion'       => $writing_on,
436            'draftAssist'             => self::is_draft_assist_enabled() && $writing_on,
437            'chatHistory'             => false,
438            'supportGuides'           => false,
439        );
440
441        /**
442         * Filter the feature set exposed in Jetpack AI Sidebar Preview.
443         *
444         * @param array $features Associative array of preview feature flags.
445         */
446        $filtered_features = apply_filters( 'jetpack_ai_sidebar_preview_features', $features );
447        $features          = is_array( $filtered_features ) ? array_merge( $features, $filtered_features ) : $features;
448
449        // Normalize the flags released here while leaving host-added values
450        // untouched. Keep the AI settings page toggles and SEO's site-side
451        // requirements final.
452        $features['aiEditorialReview']       = (bool) $features['aiEditorialReview'] && $writing_on;
453        $features['generateFeedback']        = (bool) $features['generateFeedback'] && $writing_on;
454        $features['proofreadContent']        = (bool) $features['proofreadContent'] && $writing_on;
455        $features['blockToolbarButton']      = (bool) $features['blockToolbarButton'] && $writing_on;
456        $features['optimizeTitleSuggestion'] = (bool) $features['optimizeTitleSuggestion'] && $writing_on;
457        $features['seoSuggestions']          = (bool) $features['seoSuggestions'] && self::is_seo_suggestions_enabled();
458        $features['excerptSuggestion']       = (bool) $features['excerptSuggestion'] && $writing_on;
459        $features['draftAssist']             = (bool) $features['draftAssist'] && self::is_draft_assist_enabled() && $writing_on;
460        // Block transformations (Translate, Change Tone, etc.) are writing features
461        // and follow the writing assistant toggle.
462        $features['blockTransformations'] = (bool) $features['blockTransformations'] && $writing_on;
463
464        return array(
465            'enabled'  => self::is_jetpack_ai_sidebar_preview_enabled(),
466            'features' => $features,
467        );
468    }
469
470    /**
471     * Whether the Jetpack AI Sidebar toolbar button replaces the legacy AI toolbar.
472     *
473     * The button is a writing entry point, so it follows the writing assistant
474     * toggle. Switching it off cannot bring the legacy toolbar back in its place:
475     * the editor renders that toolbar only while this feature is unavailable AND
476     * the AI Assistant block and its ai-assistant-support extension are
477     * registered, and both of those are themselves gated on the writing assistant.
478     *
479     * @return bool
480     */
481    public static function is_toolbar_button_enabled(): bool {
482        $preview_config = self::get_jetpack_ai_sidebar_preview_config();
483
484        return self::should_expose_provider()
485            && ! self::is_agents_manager_disconnected()
486            && true === ( $preview_config['features']['blockToolbarButton'] ?? false );
487    }
488
489    /**
490     * Register the Jetpack AI Sidebar toolbar button feature.
491     *
492     * @return void
493     */
494    public static function register_toolbar_button_extension(): void {
495        if ( ! self::is_toolbar_button_enabled() ) {
496            \Jetpack_Gutenberg::set_extension_unavailable(
497                AI_SIDEBAR_TOOLBAR_BUTTON_EXTENSION,
498                'jetpack_ai_sidebar_feature_disabled'
499            );
500            return;
501        }
502
503        \Jetpack_Gutenberg::set_extension_available( AI_SIDEBAR_TOOLBAR_BUTTON_EXTENSION );
504    }
505
506    /**
507     * Add Jetpack AI Sidebar-specific data to externally emitted Agents Manager payloads.
508     *
509     * @param mixed $data Data encoded into `agentsManagerData`.
510     * @return mixed Filtered data.
511     */
512    public static function add_agents_manager_data( $data ) {
513        if ( ! is_array( $data ) ) {
514            return $data;
515        }
516
517        $fields = self::get_agents_manager_data_fields( $data );
518        if ( ! $fields ) {
519            return $data;
520        }
521
522        // Set our fields in place, leaving the rest of $data (including agentProviders)
523        // untouched so the client-side gate can drop Jetpack AI Sidebar while keeping
524        // fallbacks such as the Big Sky provider. Hosts that need intentional overrides
525        // should use the sidebar and preview feature filters.
526        foreach ( $fields as $key => $value ) {
527            $data[ $key ] = $value;
528        }
529        return $data;
530    }
531
532    /**
533     * Fields Jetpack should add to `agentsManagerData` for the current screen.
534     *
535     * @param array $data Existing Agents Manager data.
536     * @return array
537     */
538    private static function get_agents_manager_data_fields( array $data = array() ): array {
539        if ( ! self::should_expose_provider() ) {
540            return array();
541        }
542
543        $fields = array();
544        if ( empty( $data['agentId'] ) ) {
545            $fields['agentId'] = AI_SIDEBAR_AGENT_ID;
546        }
547        $fields['jetpackAiSidebar'] = self::get_jetpack_ai_sidebar_preview_config();
548
549        return $fields;
550    }
551
552    /**
553     * Enable Agents Manager when the Jetpack AI provider can be exposed.
554     *
555     * @param mixed $enabled Existing Agents Manager block-editor gate value.
556     * @return bool
557     */
558    public static function enable_agents_manager_on_provider_surfaces( $enabled ): bool {
559        if ( $enabled ) {
560            return true;
561        }
562
563        return self::should_expose_provider();
564    }
565
566    /**
567     * Inject Jetpack AI Sidebar Preview data into an externally enqueued AM bundle.
568     *
569     * The design-intended hook is jetpack_ai_sidebar_agents_manager_data, applied
570     * by jetpack-agents-manager Agents_Manager::enqueue_scripts(). On Atomic the bundled
571     * mu-wpcom (via wpcomsh) lags this PR, so the filter never fires and the
572     * client gets agentsManagerData without our fields. This `before` script runs
573     * after the upstream `before` that declares the const (added earlier) but
574     * before the AM bundle reads it, so the field is set when AM initialises.
575     * Gives Atomic parity with Jurassic Ninja without depending on a wpcomsh
576     * redeploy.
577     *
578     * Skipped on WordPress.com Simple — wpcom's data extension owns the predicate
579     * there, including any WordPress.com-specific kill-switch override.
580     *
581     * @return void
582     */
583    public static function maybe_patch_jetpack_ai_sidebar_preview_data(): void {
584        if ( ( new Host() )->is_wpcom_simple() ) {
585            return;
586        }
587
588        // 'registered' rather than 'enqueued': wp_add_inline_script attaches to any
589        // registered handle and serializes correctly regardless of when the
590        // enqueue lands in the dependency graph.
591        if ( ! wp_script_is( 'agents-manager', 'registered' ) ) {
592            return;
593        }
594
595        // The fields getter carries the provider exposure gate.
596        $fields = self::get_agents_manager_data_fields();
597        if ( ! $fields ) {
598            return;
599        }
600
601        // The second path the provider URL can reach agentsManagerData by.
602        if ( self::is_agents_manager_disconnected() ) {
603            return;
604        }
605
606        // Build the assignments from the same field source as the data filter so the
607        // two emit paths cannot drift. agentId is guarded client-side because the
608        // externally emitted payload may already define the active agent.
609        $assignments = '';
610        foreach ( $fields as $key => $value ) {
611            $assignment_value = wp_json_encode( $value, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP );
612
613            if ( 'agentId' === $key ) {
614                $assignments .= ' if ( ! agentsManagerData.agentId ) { agentsManagerData.agentId = ' . $assignment_value . '; }';
615                continue;
616            }
617
618            $assignments .= ' agentsManagerData.' . $key . ' = ' . $assignment_value . ';';
619        }
620
621        if ( self::get_ai_sidebar_asset_data() ) {
622            $assignments .= self::get_agent_provider_upsert_script();
623        }
624
625        wp_add_inline_script(
626            'agents-manager',
627            'if ( typeof agentsManagerData === "object" && agentsManagerData !== null ) {' . $assignments . ' }',
628            'before'
629        );
630    }
631
632    /**
633     * Build the inline script that upserts Jetpack AI Sidebar into agentProviders.
634     *
635     * @return string Inline JavaScript.
636     */
637    private static function get_agent_provider_upsert_script(): string {
638        $provider_url = wp_json_encode( AI_SIDEBAR_PROVIDER_URL, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP );
639
640        return ' agentsManagerData.agentProviders = Array.isArray( agentsManagerData.agentProviders ) ? agentsManagerData.agentProviders : [];'
641            . ' if ( agentsManagerData.agentProviders.indexOf( ' . $provider_url . ' ) === -1 ) { agentsManagerData.agentProviders.push( ' . $provider_url . ' ); }';
642    }
643
644    /**
645     * Check if the current screen is a block editor.
646     *
647     * @return bool
648     */
649    private static function is_block_editor(): bool {
650        if ( ! function_exists( 'get_current_screen' ) ) {
651            return false;
652        }
653
654        $screen = get_current_screen();
655        return $screen && $screen->is_block_editor();
656    }
657
658    /**
659     * Check if the current screen can consume the Jetpack AI provider bundle.
660     *
661     * @return bool
662     */
663    private static function is_supported_provider_surface(): bool {
664        $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
665        if ( ! $screen instanceof \WP_Screen ) {
666            return false;
667        }
668
669        if ( 'site-editor' === $screen->base ) {
670            return true;
671        }
672
673        return self::is_block_editor()
674            && 'post' === $screen->base
675            && in_array( $screen->post_type, array( 'post', 'page' ), true );
676    }
677
678    /**
679     * Check whether AI features are available.
680     *
681     * - wpcom simple: available when Jetpack AI is enabled.
682     * - Atomic/self-hosted: requires Jetpack AI enabled, a connected owner, and non-offline mode.
683     *
684     * @return bool
685     */
686    private static function has_ai_features(): bool {
687        if ( ! \Jetpack_AI_Settings::is_ai_enabled() ) {
688            return false;
689        }
690
691        $host = new Host();
692
693        if ( $host->is_wpcom_simple() ) {
694            return true;
695        }
696
697        return ( new Connection_Manager( 'jetpack' ) )->has_connected_owner()
698            && ! ( new Status() )->is_offline_mode();
699    }
700}