session = Context::load_json( self::SESSION_FILE ) ?: []; } /** Save current session data. */ private function save_session(): void { Context::save_json( self::SESSION_FILE, $this->session ); } /** Prepare headers for streaming AJAX responses. */ private function stream_setup(): void { $prev = ini_get( 'zlib.output_compression' ); if ( function_exists( 'apache_setenv' ) ) { @apache_setenv( 'no-gzip', '1' ); } while ( ob_get_level() ) { @ob_end_flush(); } header( 'Content-Type: text/plain; charset=utf-8' ); $this->session['prev_zlib'] = $prev; } /* ===== Public entry point ======================================= */ /** * Execute full post generation pipeline and return the created post ID. * * @return int Generated post ID. */ public function generate_post(): int { list( $allowed, $msg ) = Limits::can_generate(); if ( ! $allowed ) { throw new \RuntimeException( esc_html( $msg ) ); } $this->run_stage( fn() => $this->generate_draft(), 'draft' ); $this->run_stage( fn() => $this->run_qa_stage(), 'qa' ); $this->run_stage( fn() => $this->finalize_post(), 'final' ); return $this->run_stage( fn() => $this->generate_image(), 'image' ); } /** * Manual trigger for post generation, used by REST endpoints or AJAX. * * @return int Generated post ID. */ public static function manual_run(): int { $generator = new self(); return $generator->generate_post(); } /** * Generate list of topics suggestions. * * @return array{thread_id:string,vector_id:string,topics:array} */ public static function suggest_topics(): array { $generator = new self(); return $generator->with_retry( fn() => $generator->generate_topic_suggestions() ); } /** * Launch topic suggestion generation asynchronously. * * @return string Job identifier for polling. */ public static function start_async_topic_job(): string { $job_id = wp_generate_uuid4(); $session = [ 'job_id' => $job_id, 'job_status' => 'queued', 'progress' => '', 'retries' => 0, 'last_update'=> time(), ]; Context::save_json( self::TOPIC_SESSION_FILE, $session ); if ( ! wp_next_scheduled( 'aipub_process_topic_job', [ $job_id ] ) ) { wp_schedule_single_event( time(), 'aipub_process_topic_job', [ $job_id ] ); } if ( ! wp_doing_cron() ) { function_exists( 'spawn_cron' ) ? spawn_cron() : wp_cron(); } return $job_id; } /** * Generate a post based on a selected topic. * * @param string $thread_id Existing thread ID from suggest_topics(). * @param string $vector_id Existing vector store ID from suggest_topics(). * @param string $topic Chosen topic text. * @param string[] $keywords Associated keywords. * @return int Generated post ID. */ public static function manual_run_with_topic( string $thread_id, string $vector_id, string $topic, array $keywords ): int { $generator = new self(); return $generator->generate_post_with_topic( $thread_id, $vector_id, $topic, $keywords ); } /** * Launch post generation asynchronously via WP-Cron. * * Stores the job ID and optional topic info in session.json and * schedules the cron event that will execute the generation. * * @param string $thread_id Optional thread ID for selected topic. * @param string $vector_id Optional vector store ID for selected topic. * @param string $topic Optional topic text. * @param string[] $keywords Optional keywords. * @return string Generated job ID used for polling. */ public static function start_async_generation( string $thread_id = '', string $vector_id = '', string $topic = '', array $keywords = [] ): string { list( $allowed, $msg ) = Limits::can_generate(); if ( ! $allowed ) { throw new \RuntimeException( esc_html( $msg ) ); } $job_id = wp_generate_uuid4(); $session = [ 'job_id' => $job_id, 'job_status' => 'queued', 'progress' => '', ]; if ( $topic ) { $session['topic_text'] = $topic; $session['topic_keys'] = $keywords; } if ( $thread_id && $vector_id ) { $session['topic_thread'] = $thread_id; $session['topic_vector'] = $vector_id; } Context::save_json( self::SESSION_FILE, $session ); if ( ! wp_next_scheduled( 'aipub_process_post_job', [ $job_id ] ) ) { wp_schedule_single_event( time(), 'aipub_process_post_job', [ $job_id ] ); } if ( ! wp_doing_cron() ) { function_exists( 'spawn_cron' ) ? spawn_cron() : wp_cron(); } return $job_id; } /** * Cron callback to process an async post generation job. * * @param string $job_id Job identifier from start_async_generation(). * @return void */ public static function process_async_job( string $job_id ): void { ignore_user_abort( true ); aipub_with_time_limit( Brand_Strategy::TIMEOUT_SECS, function () use ( $job_id ) { $gen = new self(); $gen->load_session(); if ( ( $gen->session['job_id'] ?? '' ) !== $job_id ) { return; // Unknown job. } list( $allowed, $msg ) = Limits::can_generate(); if ( ! $allowed ) { $gen->session['job_status'] = 'error'; $gen->session['error'] = $msg; $gen->save_session(); return; } $gen->session['job_status'] = 'running'; $gen->session['progress'] = 'draft'; $gen->save_session(); $attempts = $gen->session['retries'] ?? 0; try { if ( isset( $gen->session['topic_thread'], $gen->session['topic_vector'], $gen->session['topic_text'] ) ) { $post_id = $gen->generate_post_with_topic( $gen->session['topic_thread'], $gen->session['topic_vector'], $gen->session['topic_text'], $gen->session['topic_keys'] ?? [] ); } elseif ( isset( $gen->session['topic_text'] ) ) { $post_id = $gen->generate_post_from_topic_text( $gen->session['topic_text'], $gen->session['topic_keys'] ?? [] ); } else { $gen->generate_draft(); $gen->session['progress'] = 'qa'; $gen->save_session(); $gen->run_qa_stage(); $gen->session['progress'] = 'final'; $gen->save_session(); $gen->finalize_post(); $gen->session['progress'] = 'image'; $gen->save_session(); $post_id = $gen->generate_image(); } Cron::maybe_reschedule(); $gen->session['job_status'] = 'done'; $gen->session['progress'] = 'done'; $gen->session['result'] = [ 'post_id' => $post_id, 'post_edit' => admin_url( 'post.php?post=' . $post_id . '&action=edit' ), 'post_view' => get_permalink( $post_id ), ]; $gen->save_session(); } catch ( \Throwable $e ) { $attempts++; if ( $attempts < self::MAX_RETRIES ) { $gen->session['retries'] = $attempts; $gen->session['job_status'] = 'running'; $gen->save_session(); if ( ! wp_next_scheduled( 'aipub_process_post_job', [ $job_id ] ) ) { wp_schedule_single_event( time() + 30, 'aipub_process_post_job', [ $job_id ] ); } return; } $gen->session['job_status'] = 'error'; $gen->session['error'] = $e->getMessage(); $gen->save_session(); $gen->cleanup_openai( [], $gen->session['vector_id'] ?? '', $gen->session['thread_id'] ?? '' ); } } ); } /** * Cron callback to process async topic suggestion job. * * @param string $job_id Job identifier from start_async_topic_job(). * @return void */ public static function process_async_topic_job( string $job_id ): void { ignore_user_abort( true ); aipub_with_time_limit( Brand_Strategy::TIMEOUT_SECS, function () use ( $job_id ) { $session = Context::load_json( self::TOPIC_SESSION_FILE ) ?: []; if ( ( $session['job_id'] ?? '' ) !== $job_id ) { return; } $session['job_status'] = 'running'; $session['last_update'] = time(); Context::save_json( self::TOPIC_SESSION_FILE, $session ); $attempts = $session['retries'] ?? 0; try { $gen = new self(); $data = $gen->generate_topic_suggestions(); $session['job_status'] = 'done'; $session['progress'] = 'done'; $session['result'] = $data; $session['last_update'] = time(); Context::save_json( self::TOPIC_SESSION_FILE, $session ); } catch ( \Throwable $e ) { $attempts++; if ( $attempts < self::MAX_RETRIES ) { $session['retries'] = $attempts; $session['job_status'] = 'running'; $session['error'] = $e->getMessage(); $session['last_update'] = time(); Context::save_json( self::TOPIC_SESSION_FILE, $session ); if ( ! wp_next_scheduled( 'aipub_process_topic_job', [ $job_id ] ) ) { wp_schedule_single_event( time() + 30, 'aipub_process_topic_job', [ $job_id ] ); } return; } $session['job_status'] = 'error'; $session['error'] = $e->getMessage(); $session['last_update'] = time(); Context::save_json( self::TOPIC_SESSION_FILE, $session ); } } ); } /** Generate the draft stage and persist context. */ public function generate_draft( bool $stream = false ): void { $this->assert_setup_complete(); $this->load_session(); if ( $stream ) { $this->stream_setup(); echo wp_json_encode( [ 'msg' => 'drafting' ] ) . "\n"; @flush(); } $thread_id = $this->create_thread(); $ctx_files = $this->collect_all_context_files(); $vector_store_id = $this->create_vector_store( $ctx_files ); $publisher_id = $this->create_publisher_assistant( $vector_store_id ); $this->with_retry( fn() => $this->draft_post( $thread_id, $publisher_id ) ); $this->add_files_to_vector_store( $vector_store_id, [ Context::dir() . 'draft-post.json' ] ); $this->session = array_merge( $this->session, [ 'thread_id' => $thread_id, 'vector_id' => $vector_store_id, 'publisher_id' => $publisher_id, ] ); $this->save_session(); if ( $stream ) { echo wp_json_encode( [ 'success' => true ] ) . "\n"; if ( function_exists( 'ini_set' ) && isset( $old_zlib ) ) { // phpcs:ignore WordPress.PHP.DiscouragedFunctions.Discouraged,Squiz.PHP.DiscouragedFunctions.Discouraged -- restore previous compression setting @ini_set( 'zlib.output_compression', $old_zlib ); unset( $old_zlib ); } } } /** Run QA against the draft post. */ public function run_qa_stage( bool $stream = false ): void { $this->load_session(); if ( empty( $this->session['thread_id'] ) || empty( $this->session['vector_id'] ) ) { throw new \RuntimeException( 'Session not initialized.' ); } if ( $stream ) { $old_zlib = ini_get( 'zlib.output_compression' ); if ( function_exists( 'ini_set' ) ) { // phpcs:ignore WordPress.PHP.DiscouragedFunctions.Discouraged,Squiz.PHP.DiscouragedFunctions.Discouraged -- disable compression for this stream @ini_set( 'zlib.output_compression', 'Off' ); } if ( function_exists( 'apache_setenv' ) ) { @apache_setenv( 'no-gzip', '1' ); } while ( ob_get_level() ) { @ob_end_flush(); } header( 'Content-Type: text/plain; charset=utf-8' ); $this->session['prev_zlib'] = $old_zlib; echo wp_json_encode( [ 'msg' => 'qa' ] ) . "\n"; @flush(); } $qa_id = $this->create_qa_assistant( $this->session['vector_id'] ); $draft = Context::load_json( 'draft-post.json' ) ?: []; $pass = $this->with_retry( fn() => $this->run_qa( $this->session['thread_id'], $qa_id, $draft ) ); $this->add_files_to_vector_store( $this->session['vector_id'], [ Context::dir() . 'post-qa.json' ] ); $this->session['qa_id'] = $qa_id; $this->session['qa_pass'] = $pass; $this->save_session(); if ( $stream ) { echo wp_json_encode( [ 'pass' => $pass, 'success' => true ] ) . "\n"; if ( function_exists( 'ini_set' ) && isset( $old_zlib ) ) { // phpcs:ignore WordPress.PHP.DiscouragedFunctions.Discouraged,Squiz.PHP.DiscouragedFunctions.Discouraged -- restore previous compression setting @ini_set( 'zlib.output_compression', $old_zlib ); unset( $old_zlib ); } } } /** Apply revisions if QA failed and save final-post.json. */ public function finalize_post( bool $stream = false ): void { $this->load_session(); if ( empty( $this->session['thread_id'] ) || empty( $this->session['vector_id'] ) ) { throw new \RuntimeException( 'Session not initialized.' ); } if ( $stream ) { $old_zlib = ini_get( 'zlib.output_compression' ); if ( function_exists( 'ini_set' ) ) { // phpcs:ignore WordPress.PHP.DiscouragedFunctions.Discouraged,Squiz.PHP.DiscouragedFunctions.Discouraged -- disable compression for this stream @ini_set( 'zlib.output_compression', 'Off' ); } if ( function_exists( 'apache_setenv' ) ) { @apache_setenv( 'no-gzip', '1' ); } while ( ob_get_level() ) { @ob_end_flush(); } header( 'Content-Type: text/plain; charset=utf-8' ); $this->session['prev_zlib'] = $old_zlib; echo wp_json_encode( [ 'msg' => 'finalizing' ] ) . "\n"; @flush(); } $draft = Context::load_json( 'draft-post.json' ) ?: []; if ( empty( $this->session['qa_pass'] ) ) { $assistant_id = $this->create_publisher_final_assistant( $this->session['vector_id'] ); $this->session['final_id'] = $assistant_id; $final_post = $this->with_retry( fn() => $this->revise_post( $this->session['thread_id'], $assistant_id, $draft ) ); } else { $final_post = $draft; } try { Context::save_json( 'final-post.json', $final_post ); } catch ( \Throwable $e ) { throw $e; } $this->save_session(); if ( $stream ) { echo wp_json_encode( [ 'success' => true ] ) . "\n"; if ( function_exists( 'ini_set' ) && isset( $old_zlib ) ) { // phpcs:ignore WordPress.PHP.DiscouragedFunctions.Discouraged,Squiz.PHP.DiscouragedFunctions.Discouraged -- restore previous compression setting @ini_set( 'zlib.output_compression', $old_zlib ); unset( $old_zlib ); } } } /** Generate image, insert the post and cleanup. */ public function generate_image( bool $stream = false ): int { $this->load_session(); if ( empty( $this->session['thread_id'] ) || empty( $this->session['vector_id'] ) ) { throw new \RuntimeException( 'Session not initialized.' ); } if ( $stream ) { $old_zlib = ini_get( 'zlib.output_compression' ); if ( function_exists( 'ini_set' ) ) { // phpcs:ignore WordPress.PHP.DiscouragedFunctions.Discouraged,Squiz.PHP.DiscouragedFunctions.Discouraged -- disable compression for this stream @ini_set( 'zlib.output_compression', 'Off' ); } if ( function_exists( 'apache_setenv' ) ) { @apache_setenv( 'no-gzip', '1' ); } while ( ob_get_level() ) { @ob_end_flush(); } header( 'Content-Type: text/plain; charset=utf-8' ); $this->session['prev_zlib'] = $old_zlib; echo wp_json_encode( [ 'msg' => 'image' ] ) . "\n"; @flush(); } $final_post = Context::load_json( 'final-post.json' ) ?: []; $prompt_vs_id = $this->create_vector_store([ Context::dir() . 'brand-strategy.json', Context::dir() . 'final-post.json', ]); $img_prompt_assistant = $this->create_image_prompt_assistant( $prompt_vs_id ); $prompt_thread = $this->create_thread(); $prompts = self::load_post_generation_prompts(); $img_block = $prompts['TransformX Image Prompt Generator']; $img_prompt = $this->with_retry( function() use ( $prompt_thread, $img_prompt_assistant, $img_block ) { $this->add_user_message( $prompt_thread, $img_block['user_message'] ); $this->run_assistant( $prompt_thread, $img_prompt_assistant, $img_block['assistant_instructions'] ); return trim( $this->wait_for_assistant_message( $prompt_thread ) ); } ); Context::save_json( 'image-prompt.json', [ 'prompt' => $img_prompt ] ); $this->cleanup_openai( [ $img_prompt_assistant ], $prompt_vs_id, $prompt_thread ); $img_id = $this->with_retry( fn() => $this->create_featured_image( $final_post, $img_prompt ) ); $post_id = $this->with_retry( fn() => $this->insert_wp_post( $final_post, $img_id ) ); // After insertion, update final-post.json with URL and resolved category names. $final_post['url'] = get_permalink( $post_id ); $final_post['categories'] = array_map( 'trim', wp_list_pluck( get_the_category( $post_id ), 'name' ) ); $target = Context::dir() . 'final-post.json'; try { Context::save_json( 'final-post.json', $final_post ); } catch ( \Throwable $e ) { aipub_debug_log( 'TransformX: failed to save final-post.json to ' . $target . ' - ' . $e->getMessage() ); } $assistant_ids = [ $this->session['publisher_id'] ?? '', $this->session['qa_id'] ?? '' ]; if ( ! empty( $this->session['final_id'] ) ) { $assistant_ids[] = $this->session['final_id']; } $this->cleanup_openai( array_filter( $assistant_ids ), $this->session['vector_id'], $this->session['thread_id'] ); Context::delete_file( self::SESSION_FILE ); Limits::record_generation(); // FAQPage schema generation triggered after post insertion. if ( $stream ) { $response = [ 'success' => true, 'post_id' => $post_id, 'post_edit' => admin_url( 'post.php?post=' . $post_id . '&action=edit' ), 'post_view' => get_permalink( $post_id ), ]; echo wp_json_encode( $response ) . "\n"; if ( function_exists( 'ini_set' ) && isset( $old_zlib ) ) { // phpcs:ignore WordPress.PHP.DiscouragedFunctions.Discouraged,Squiz.PHP.DiscouragedFunctions.Discouraged -- restore previous compression setting @ini_set( 'zlib.output_compression', $old_zlib ); unset( $old_zlib ); } } return $post_id; } /** * Scheduled trigger for post generation (via Cron). * * @return void */ public static function scheduled_run(): void { ( new self() )->generate_post(); } /** * Remove the persisted session file. */ public static function cleanup_session(): void { Context::delete_file( self::SESSION_FILE ); } /* ===== Setup guard ============================================= */ private function assert_setup_complete(): void { if ( ! get_option( 'aipub_openai_api_key' ) ) throw new \RuntimeException( 'OpenAI key missing.' ); if ( ! Brand_Strategy::is_complete() ) throw new \RuntimeException( 'Brand strategy missing.' ); if ( ! Context::load_json( 'keywords.json' ) ) throw new \RuntimeException( 'Keywords missing.' ); // Ensure post-generation prompts configuration is available. self::load_post_generation_prompts(); } /* ===== Thread & Vector-store =================================== */ private function create_thread(): string { return $this->post_json( 'https://api.openai.com/v1/threads', (object) [] )['id']; } private function generate_topic_suggestions(): array { $this->assert_setup_complete(); $thread_id = $this->create_thread(); $ctx_files = $this->collect_all_context_files(); $vector_store_id = $this->create_vector_store( $ctx_files ); $assistant_id = $this->create_topic_generation_assistant( $vector_store_id ); $prompts = self::load_post_generation_prompts(); $block = $prompts['TransformX Publisher (Topic Generation)']; $this->add_user_message( $thread_id, $block['user_message'] ); $this->run_assistant( $thread_id, $assistant_id, $block['assistant_instructions'] ); $resp = $this->wait_for_assistant_message( $thread_id ); $path = Context::dir() . 'topic-suggestions.json'; if ( false === file_put_contents( $path, $resp ) ) { throw new \RuntimeException( 'Failed to write topic suggestions file.' ); } $data = $this->parse_json_generic( $resp, 'topic-suggestions' ); if ( isset( $data['topics'] ) && is_array( $data['topics'] ) ) { $topics = $data['topics']; } elseif ( isset( $data[0] ) ) { $topics = $data; } else { $topics = []; } foreach ( $topics as &$t ) { if ( isset( $t['keywords'] ) && is_string( $t['keywords'] ) ) { $t['keywords'] = array_map( 'trim', preg_split( '/,\s*/', $t['keywords'] ) ); } } unset( $t ); // Remove the topic generation assistant once we have the response. OpenAI::delete_assistant( $assistant_id ); return [ 'thread_id' => $thread_id, 'vector_id' => $vector_store_id, 'topics' => $topics, ]; } private function generate_post_from_topic_text( string $topic, array $keywords ): int { $thread_id = $this->create_thread(); $ctx_files = $this->collect_all_context_files(); $vector_store_id = $this->create_vector_store( $ctx_files ); return $this->generate_post_with_topic( $thread_id, $vector_store_id, $topic, $keywords ); } private function generate_post_with_topic( string $thread_id, string $vector_id, string $topic, array $keywords ): int { $this->assert_setup_complete(); $this->load_session(); if ( ! OpenAI::vector_store_exists( $vector_id ) ) { $ctx_files = $this->collect_all_context_files(); $vector_id = $this->create_vector_store( $ctx_files ); $this->session['vector_id'] = $vector_id; $this->save_session(); } $this->session = array_merge( $this->session, [ 'thread_id' => $thread_id, 'vector_id' => $vector_id, ] ); $this->save_session(); $assistant_id = ''; $draft_post = $this->run_stage( function() use ( $thread_id, $vector_id, $topic, $keywords, &$assistant_id ) { $assistant_id = $this->create_topic_assistant( $vector_id ); $prompts = self::load_post_generation_prompts(); $block = $prompts['TransformX Publisher (Topic)']; $user = str_replace( [ '$topic', '$keywords' ], [ $topic, implode( ', ', $keywords ) ], $block['user_message'] ); $this->add_user_message( $thread_id, $user ); $this->run_assistant( $thread_id, $assistant_id, $block['assistant_instructions'] ); $post = $this->with_retry( fn() => $this->decode_post_json( $this->wait_for_assistant_message( $thread_id ), 'draft-post.json' ) ); $this->add_files_to_vector_store( $vector_id, [ Context::dir() . 'draft-post.json' ] ); return $post; }, 'draft' ); $this->session['progress'] = 'qa'; $this->save_session(); $qa_id = ''; $qa_pass = $this->run_stage( function() use ( $thread_id, $vector_id, $draft_post, $topic, $keywords, &$qa_id ) { $qa_id = $this->create_topic_qa_assistant( $vector_id ); $pass = $this->with_retry( fn() => $this->run_qa_topic( $thread_id, $qa_id, $draft_post, $topic, $keywords ) ); $this->add_files_to_vector_store( $vector_id, [ Context::dir() . 'post-qa.json' ] ); return $pass; }, 'qa' ); $this->session['progress'] = 'final'; $this->save_session(); $publisher_final_id = null; $final_post = $this->run_stage( function() use ( $thread_id, $vector_id, $draft_post, $topic, $keywords, $qa_pass, &$publisher_final_id ) { if ( ! $qa_pass ) { $publisher_final_id = $this->create_topic_assistant( $vector_id ); return $this->with_retry( fn() => $this->revise_post_topic( $thread_id, $publisher_final_id, $draft_post, $topic, $keywords ) ); } return $draft_post; }, 'final' ); try { Context::save_json( 'final-post.json', $final_post ); } catch ( \Throwable $e ) { throw $e; } $this->session['progress'] = 'image'; $this->save_session(); $post_id = $this->run_stage( function() use ( $final_post, $thread_id, $vector_id, $assistant_id, $qa_id, $publisher_final_id ) { $prompt_vs_id = $this->create_vector_store([ Context::dir() . 'brand-strategy.json', Context::dir() . 'final-post.json', ]); $img_prompt_assistant = $this->create_image_prompt_assistant( $prompt_vs_id ); $prompt_thread = $this->create_thread(); $prompts = self::load_post_generation_prompts(); $img_block = $prompts['TransformX Image Prompt Generator']; $img_prompt = $this->with_retry( function() use ( $prompt_thread, $img_prompt_assistant, $img_block ) { $this->add_user_message( $prompt_thread, $img_block['user_message'] ); $this->run_assistant( $prompt_thread, $img_prompt_assistant, $img_block['assistant_instructions'] ); return trim( $this->wait_for_assistant_message( $prompt_thread ) ); } ); Context::save_json( 'image-prompt.json', [ 'prompt' => $img_prompt ] ); $this->cleanup_openai( [ $img_prompt_assistant ], $prompt_vs_id, $prompt_thread ); $img_id = $this->with_retry( fn() => $this->create_featured_image( $final_post, $img_prompt ) ); $post_id = $this->with_retry( fn() => $this->insert_wp_post( $final_post, $img_id ) ); // After insertion, update final-post.json with URL and resolved category names. $final_post['url'] = get_permalink( $post_id ); $final_post['categories'] = array_map( 'trim', wp_list_pluck( get_the_category( $post_id ), 'name' ) ); $target = Context::dir() . 'final-post.json'; try { Context::save_json( 'final-post.json', $final_post ); } catch ( \Throwable $e ) { aipub_debug_log( 'TransformX: failed to save final-post.json to ' . $target . ' - ' . $e->getMessage() ); } $assistant_ids = [ $assistant_id, $qa_id ]; if ( ! empty( $publisher_final_id ) ) { $assistant_ids[] = $publisher_final_id; } $this->cleanup_openai( $assistant_ids, $vector_id, $thread_id ); return $post_id; }, 'image' ); return $post_id; } /** * Collect the core context files to seed the AI session. * * Includes brand strategy, keywords, pages snapshot (if available) and * a sitemap generated from existing posts and pages. * * @return string[] List of absolute file paths. */ private function collect_all_context_files(): array { $dir = Context::dir(); $files = [ $dir . 'brand-strategy.json', $dir . 'keywords.json', ]; // Optional: include pages snapshot if available if ( file_exists( $dir . 'pages.json' ) ) { $files[] = $dir . 'pages.json'; } // Generate sitemap.json from current posts and pages $smap_data = [ 'posts' => [], 'pages' => [] ]; $posts = \get_posts([ 'post_type' => 'post', 'post_status' => 'publish', 'numberposts' => -1, ]); foreach ( $posts as $p ) { $smap_data['posts'][] = [ 'title' => get_the_title( $p ), 'url' => get_permalink( $p ), 'tags' => \wp_get_post_tags( $p->ID, [ 'fields' => 'names' ] ), ]; } $pages = \get_posts([ 'post_type' => 'page', 'post_status' => 'publish', 'numberposts' => -1, ]); foreach ( $pages as $pg ) { $smap_data['pages'][] = [ 'title' => get_the_title( $pg ), 'url' => get_permalink( $pg ), ]; } $files[] = Context::save_json( 'sitemap.json', $smap_data ); // Include categories: export taxonomy definitions for assistant lookups. $terms = \get_terms( [ 'taxonomy' => 'category', 'hide_empty' => false ] ); $cat_data = []; foreach ( $terms as $term ) { $cat_data[] = [ 'term_id' => $term->term_id, 'name' => $term->name, 'slug' => $term->slug, ]; } $files[] = Context::save_json( 'categories.json', $cat_data ); return $files; } private function create_vector_store( array $files ): string { $file_ids = array_map( fn ( $f ) => $this->upload_file( $f ), $files ); return $this->post_json( 'https://api.openai.com/v1/vector_stores', [ 'name' => 'aipub_' . time(), 'file_ids' => $file_ids ] )['id']; } /** * Add additional files to an existing vector store. * * @param string $vs_id Vector store ID. * @param string[] $files Local file paths to add. * @return void */ private function add_files_to_vector_store( string $vs_id, array $files ): void { $file_ids = array_map( fn ( $f ) => $this->upload_file( $f ), $files ); OpenAI::add_files_to_vector_store( $vs_id, $file_ids ); } /* ===== Assistants ============================================== */ private function publisher_instructions(): string { $prompts = self::load_post_generation_prompts(); return $prompts['TransformX Publisher']['system_message']; } private function qa_instructions(): string { $prompts = self::load_post_generation_prompts(); return $prompts['TransformX QA']['system_message']; } /** Retrieve QA instructions for topic based generation. */ private function qa_topic_instructions(): string { $prompts = self::load_post_generation_prompts(); return $prompts['TransformX QA Topic']['system_message']; } private function topic_generation_instructions(): string { $prompts = self::load_post_generation_prompts(); return $prompts['TransformX Publisher (Topic Generation)']['system_message']; } private function topic_instructions(): string { $prompts = self::load_post_generation_prompts(); return $prompts['TransformX Publisher (Topic)']['system_message']; } private function create_publisher_assistant( string $vs_id ): string { $model = get_option( 'aipub_ai_model', 'o1' ); $payload = [ 'name' => 'TransformX Publisher', 'instructions' => $this->publisher_instructions(), 'tools' => [ [ 'type' => 'file_search' ] ], 'tool_resources' => [ 'file_search' => [ 'vector_store_ids' => [ $vs_id ] ] ], 'model' => $model, ]; if ( in_array( $model, [ 'o3-mini', 'o1' ], true ) ) { $payload['reasoning_effort'] = 'high'; } else { $payload['temperature'] = 0.4; } return $this->post_json( 'https://api.openai.com/v1/assistants', $payload )['id']; } private function create_topic_generation_assistant( string $vs_id ): string { $model = get_option( 'aipub_ai_model', 'o1' ); $payload = [ 'name' => 'TransformX Publisher (Topic Generation)', 'instructions' => $this->topic_generation_instructions(), 'tools' => [ [ 'type' => 'file_search' ] ], 'tool_resources' => [ 'file_search' => [ 'vector_store_ids' => [ $vs_id ] ] ], 'model' => $model, ]; if ( in_array( $model, [ 'o3-mini', 'o1' ], true ) ) { $payload['reasoning_effort'] = 'high'; } else { $payload['temperature'] = 0.4; } return $this->post_json( 'https://api.openai.com/v1/assistants', $payload )['id']; } private function create_topic_assistant( string $vs_id ): string { $model = get_option( 'aipub_ai_model', 'o1' ); $payload = [ 'name' => 'TransformX Publisher (Topic)', 'instructions' => $this->topic_instructions(), 'tools' => [ [ 'type' => 'file_search' ] ], 'tool_resources' => [ 'file_search' => [ 'vector_store_ids' => [ $vs_id ] ] ], 'model' => $model, ]; if ( in_array( $model, [ 'o3-mini', 'o1' ], true ) ) { $payload['reasoning_effort'] = 'high'; } else { $payload['temperature'] = 0.4; } return $this->post_json( 'https://api.openai.com/v1/assistants', $payload )['id']; } private function create_qa_assistant( string $vs_id ): string { $model = get_option( 'aipub_ai_model', 'o1' ); $payload = [ 'name' => 'TransformX QA', 'instructions' => $this->qa_instructions(), 'tools' => [ [ 'type' => 'file_search' ] ], 'tool_resources' => [ 'file_search' => [ 'vector_store_ids' => [ $vs_id ] ] ], 'model' => $model, ]; if ( in_array( $model, [ 'o3-mini', 'o1' ], true ) ) { $payload['reasoning_effort'] = 'medium'; } else { $payload['temperature'] = 0; } return $this->post_json( 'https://api.openai.com/v1/assistants', $payload )['id']; } /** Create QA assistant using topic specific prompts. */ private function create_topic_qa_assistant( string $vs_id ): string { $model = get_option( 'aipub_ai_model', 'o1' ); $payload = [ 'name' => 'TransformX QA Topic', 'instructions' => $this->qa_topic_instructions(), 'tools' => [ [ 'type' => 'file_search' ] ], 'tool_resources' => [ 'file_search' => [ 'vector_store_ids' => [ $vs_id ] ] ], 'model' => $model, ]; if ( in_array( $model, [ 'o3-mini', 'o1' ], true ) ) { $payload['reasoning_effort'] = 'medium'; } else { $payload['temperature'] = 0; } return $this->post_json( 'https://api.openai.com/v1/assistants', $payload )['id']; } /* ===== Draft, QA, Revise ======================================= */ private function draft_post( string $thread_id, string $assistant_id ): array { $prompts = self::load_post_generation_prompts(); $block = $prompts['TransformX Publisher']; $this->add_user_message( $thread_id, $block['user_message'] ); $this->run_assistant( $thread_id, $assistant_id, $block['assistant_instructions'] ); return $this->decode_post_json( $this->wait_for_assistant_message( $thread_id ), 'draft-post.json' ); } private function run_qa( string $thread_id, string $qa_id, array $draft ): bool { $prompts = self::load_post_generation_prompts(); $block = $prompts['TransformX QA']; $this->add_user_message( $thread_id, $block['user_message'] ); $this->add_user_message( $thread_id, 'DRAFT_JSON:' . wp_json_encode( $draft ) ); $this->run_assistant( $thread_id, $qa_id, $block['assistant_instructions'] ); $report = json_decode( $this->wait_for_assistant_message( $thread_id ), true ); Context::save_json( 'post-qa.json', $report ); return isset( $report['result'] ) && 'pass' === $report['result']; } /** Run QA using topic specific prompts. */ private function run_qa_topic( string $thread_id, string $qa_id, array $draft, string $topic, array $keywords ): bool { $prompts = self::load_post_generation_prompts(); $block = $prompts['TransformX QA Topic']; $user = str_replace( [ '$topic', '$keywords' ], [ $topic, implode( ', ', $keywords ) ], $block['user_message'] ); $this->add_user_message( $thread_id, $user ); $this->add_user_message( $thread_id, 'DRAFT_JSON:' . wp_json_encode( $draft ) ); $this->run_assistant( $thread_id, $qa_id, $block['assistant_instructions'] ); $report = json_decode( $this->wait_for_assistant_message( $thread_id ), true ); Context::save_json( 'post-qa.json', $report ); return isset( $report['result'] ) && 'pass' === $report['result']; } private function revise_post( string $thread, string $assistant, array $draft ): array { $prompts = self::load_post_generation_prompts(); $block = $prompts['TransformX Publisher (Final)']; $this->add_user_message( $thread, $block['user_message'] ); $this->add_user_message( $thread, 'DRAFT_JSON:' . wp_json_encode( $draft ) ); $this->add_user_message( $thread, 'POST_QA_JSON:' . wp_json_encode( Context::load_json( 'post-qa.json' ) ) ); $this->run_assistant( $thread, $assistant, $block['assistant_instructions'] ); return $this->decode_post_json( $this->wait_for_assistant_message( $thread ), 'final-post.json' ); } /** Revise using topic prompts and QA feedback. */ private function revise_post_topic( string $thread, string $assistant, array $draft, string $topic, array $keywords ): array { $prompts = self::load_post_generation_prompts(); $block = $prompts['TransformX Publisher (Topic)']; $user = str_replace( [ '$topic', '$keywords' ], [ $topic, implode( ', ', $keywords ) ], $block['user_message'] ); $this->add_user_message( $thread, $user ); $this->add_user_message( $thread, 'DRAFT_JSON:' . wp_json_encode( $draft ) ); $this->add_user_message( $thread, 'POST_QA_JSON:' . wp_json_encode( Context::load_json( 'post-qa.json' ) ) ); $this->run_assistant( $thread, $assistant, $block['assistant_instructions'] ); return $this->decode_post_json( $this->wait_for_assistant_message( $thread ), 'final-post.json' ); } private function decode_post_json( string $json, string $fname ): array { // Normalize output: strip code fences or surrounding text, then extract JSON block. $raw = trim( $json ); // Remove fenced code block if present. if ( preg_match( '/^```(?:json)?\s*([\s\S]*)\s*```$/im', $raw, $m ) ) { $raw = trim( $m[1] ); } // If still not pure JSON, extract the first {...} block. if ( '' !== $raw && ( $raw[0] !== '{' || substr( $raw, -1 ) !== '}' ) ) { if ( preg_match( '/\{[\s\S]*\}$/', $raw, $m2 ) ) { $raw = trim( $m2[0] ); } } $data = is_string( $raw ) ? json_decode( $raw, true ) : null; if ( ! is_array( $data ) ) { $data = []; } $content_md = $data['content'] ?? $data['markdown_content'] ?? ''; $content_html = $data['html_content'] ?? $data['post_content'] ?? ''; if ( '' === $content_html && '' !== $content_md ) { $content_html = Markdown::to_html( $content_md ); } if ( 'final-post.json' === $fname ) { $content_html = $this->add_heading_ids( $content_html ); } $content_html = OpenAI::clean_text( $content_html ); $post = [ 'title' => trim( OpenAI::clean_text( $data['title'] ?? $data['post_title'] ?? '' ) ) ?: 'no data', 'excerpt' => trim( OpenAI::clean_text( $data['excerpt'] ?? $data['post_excerpt'] ?? '' ) ) ?: 'no data', 'categories' => array_values( isset( $data['categories'] ) && is_array( $data['categories'] ) ? $data['categories'] : [] ), 'tags' => array_values( isset( $data['tags'] ) && is_array( $data['tags'] ) ? $data['tags'] : [] ), 'content' => $content_html ?: 'no data', ]; Context::save_json( $fname, $post ); return $post; } /** * Decode a generic JSON string, handling fenced blocks and extra text. * * @param string $json Raw JSON text from OpenAI. * @param string $label Context label for error reporting. * @return array Decoded data array or empty array on failure. */ private function parse_json_generic( string $json, string $label ): array { $raw = trim( $json ); if ( preg_match( '/^```(?:json)?\s*([\s\S]*?)\s*```$/i', $raw, $m ) ) { $raw = trim( $m[1] ); } if ( '' !== $raw && ! in_array( $raw[0], [ '{', '[' ], true ) ) { if ( preg_match( '/(\{[\s\S]*\})|(\[[\s\S]*\])/', $raw, $m2 ) ) { $raw = trim( $m2[0] ); } } $data = is_string( $raw ) ? json_decode( $raw, true ) : null; if ( ! is_array( $data ) ) { $data = []; } return $data; } /** * Add sanitized id attributes to all h2 and h3 elements. */ private function add_heading_ids( string $html ): string { if ( '' === trim( $html ) ) { return $html; } $doc = new \DOMDocument(); libxml_use_internal_errors( true ); $doc->loadHTML( '
' . $html . '
', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD ); libxml_clear_errors(); foreach ( [ 'h2', 'h3' ] as $tag ) { $nodes = $doc->getElementsByTagName( $tag ); for ( $i = 0; $i < $nodes->length; $i++ ) { $node = $nodes->item( $i ); if ( $node ) { $slug = Context::slugify( $node->textContent ); $node->setAttribute( 'id', $slug ); } } } $body = $doc->getElementsByTagName( 'div' )->item( 0 ); $out = ''; foreach ( $body->childNodes as $child ) { $out .= $doc->saveHTML( $child ); } return $out; } /* ===== Image Generation ======================================== */ private function create_featured_image( array $post, string $prompt ): int { // Ensure WP media, file, and image functions are available in this context (Cron, AJAX, front-end) if ( ! \function_exists( 'media_handle_sideload' ) ) { require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/media.php'; require_once ABSPATH . 'wp-admin/includes/image.php'; } // Save image prompt text for reference $prompt_path = Context::dir() . 'image-prompt.txt'; if ( false === file_put_contents( $prompt_path, $prompt ) ) { throw new \RuntimeException( 'Failed to write image prompt file.' ); } $img_json = $this->post_json( 'https://api.openai.com/v1/images/generations', [ 'model' => 'dall-e-3', 'prompt' => $prompt, 'n' => 1, 'size' => '1792x1024', ] ); $url = $img_json['data'][0]['url'] ?? ''; if ( ! $url ) { throw new \RuntimeException( 'Image generation failed.' ); } $tmp_png = \download_url( $url ); $tmp_webp = Image::convert_png_to_webp( $tmp_png ); $is_webp = ( $tmp_webp !== $tmp_png ); if ( $is_webp ) { wp_delete_file( $tmp_png ); } $file = [ 'name' => Context::slugify( $post['title'] ) . ( $is_webp ? '.webp' : '.png' ), 'tmp_name' => $tmp_webp, 'type' => $is_webp ? 'image/webp' : 'image/png', ]; $post_data = [ 'post_title' => $post['title'], ]; $id = \media_handle_sideload( $file, 0, null, $post_data ); \update_post_meta( $id, '_wp_attachment_image_alt', $post['title'] ); wp_delete_file( $tmp_webp ); if ( \is_wp_error( $id ) ) { throw new \RuntimeException( esc_html( $id->get_error_message() ) ); } return $id; } /* ===== WordPress Insertion ===================================== */ /** * Insert a WordPress post based on AI output and return the post ID. * * @param array $post AI-generated post data. * @param int $image_id Featured image attachment ID. * @return int Inserted post ID. */ private function insert_wp_post( array $post, int $image_id ): int { // Normalize typographic characters before insertion. $post = $this->replace_em_dashes( $post ); // Resolve categories by name without creating new ones. If none // match, fall back to the lowest category ID available. $existing_ids = array_filter( array_map( function( $c ) { $term = term_exists( $c, 'category' ); return $term ? (int) $term['term_id'] : 0; }, (array) ( $post['categories'] ?? [] ) ) ); if ( empty( $existing_ids ) ) { $first = get_terms( [ 'taxonomy' => 'category', 'hide_empty' => false, 'orderby' => 'id', 'order' => 'ASC', 'number' => 1, 'fields' => 'ids', ] ); $existing_ids = $first ? [ (int) $first[0] ] : []; } $cat_ids = $existing_ids; // Map JSON keys to WP fields: support 'content' or 'html_content' for body $post_content = OpenAI::clean_text( $post['content'] ?? $post['html_content'] ?? '' ); $post_excerpt = OpenAI::clean_text( $post['excerpt'] ?? '' ); $post_tags = array_map( [ OpenAI::class, 'clean_text' ], (array) ( $post['tags'] ?? [] ) ); $post_title = wp_strip_all_tags( OpenAI::clean_text( $post['title'] ) ); $post_id = wp_insert_post( [ 'post_title' => $post_title, 'post_content' => $post_content, 'post_excerpt' => $post_excerpt, 'post_status' => Settings::post_status(), 'post_category' => $cat_ids, 'tags_input' => $post_tags, 'post_author' => 1, ] ); if ( is_wp_error( $post_id ) || 0 === $post_id ) { throw new \RuntimeException( is_wp_error( $post_id ) ? esc_html( $post_id->get_error_message() ) : 'Failed to insert post.' ); } set_post_thumbnail( $post_id, $image_id ); update_post_meta( $post_id, '_yoast_wpseo_metadesc', $post['excerpt'] ); update_post_meta( $post_id, '_aipub_generated', 1 ); // Kick off FAQPage schema generation immediately. Faq::start_async_job( $post_id ); return $post_id; } /** * Load post-generation prompts from JSON config. * * @return array Associative array of prompts. * @throws \RuntimeException If the prompts file is missing or invalid. */ private static function load_post_generation_prompts(): array { static $prompts = null; if ( null === $prompts ) { $path = AIPUB_DIR . 'includes/data/post_generation_prompts.json'; if ( ! file_exists( $path ) ) { throw new \RuntimeException( 'Missing post_generation_prompts.json file.' ); } $json = file_get_contents( $path ); $data = json_decode( $json, true ); if ( ! is_array( $data ) ) { throw new \RuntimeException( sprintf( 'Invalid JSON in post_generation_prompts.json: %s', esc_html( json_last_error_msg() ) ) ); } $prompts = $data; } return $prompts; } /** * Create the Publisher (Final) assistant for post revision, using QA feedback. * * @param string $vs_id Vector store ID for context (brand strategy, keywords, sitemap). * @return string Assistant ID. */ private function create_publisher_final_assistant( string $vs_id ): string { $prompts = self::load_post_generation_prompts(); $block = $prompts['TransformX Publisher (Final)']; $model = get_option( 'aipub_ai_model', 'o1' ); $payload = [ 'name' => 'TransformX Publisher (Final)', 'instructions' => $block['system_message'], 'tools' => [ [ 'type' => 'file_search' ] ], 'tool_resources' => [ 'file_search' => [ 'vector_store_ids' => [ $vs_id ] ] ], 'model' => $model, ]; if ( in_array( $model, [ 'o3-mini', 'o1' ], true ) ) { $payload['reasoning_effort'] = 'high'; } else { $payload['temperature'] = 0.4; } return $this->post_json( 'https://api.openai.com/v1/assistants', $payload )['id']; } /** * Create the Image Prompt Generator assistant. * * @param string $vs_id Vector store containing brand-strategy.json and final-post.json. * @return string Assistant ID. */ private function create_image_prompt_assistant( string $vs_id ): string { $model = get_option( 'aipub_ai_model', 'o1' ); $payload = [ 'name' => 'TransformX Image Prompt Generator', 'instructions' => $this->image_prompt_instructions(), 'tools' => [ [ 'type' => 'file_search' ] ], 'tool_resources' => [ 'file_search' => [ 'vector_store_ids' => [ $vs_id ] ] ], 'model' => $model, ]; if ( in_array( $model, [ 'o3-mini', 'o1' ], true ) ) { $payload['reasoning_effort'] = 'medium'; } else { $payload['temperature'] = 0.7; } return $this->post_json( 'https://api.openai.com/v1/assistants', $payload )['id']; } /* ===== Cleanup ================================================== */ /** * Cleanup AI resources: assistants, vector stores, and thread. * * @param string[] $assistant_ids List of assistant IDs to delete. * @param string|string[] $vs_ids Vector store ID or list of vector store IDs to delete. * @param string $thread_id Thread ID to delete. */ private function cleanup_openai( array $assistant_ids, $vs_ids, string $thread_id ): void { $headers = [ 'Authorization' => 'Bearer ' . get_option( 'aipub_openai_api_key' ), 'OpenAI-Beta' => 'assistants=v2', ]; foreach ( $assistant_ids as $id ) { wp_remote_request( "https://api.openai.com/v1/assistants/{$id}", [ 'method' => 'DELETE', 'headers' => $headers ] ); } foreach ( (array) $vs_ids as $vs_id ) { wp_remote_request( "https://api.openai.com/v1/vector_stores/{$vs_id}", [ 'method' => 'DELETE', 'headers' => $headers ] ); } wp_remote_request( "https://api.openai.com/v1/threads/{$thread_id}", [ 'method' => 'DELETE', 'headers' => $headers ] ); } /** * Instructions for the Image Prompt Generator assistant. * * @return string */ private function image_prompt_instructions(): string { $prompts = self::load_post_generation_prompts(); return $prompts['TransformX Image Prompt Generator']['system_message']; } /* ===== Low-level Helpers ======================================= */ private function post_json( string $url, $body ): array { $res = wp_remote_post( $url, [ 'headers' => [ 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . get_option( 'aipub_openai_api_key' ), 'OpenAI-Beta' => 'assistants=v2', ], 'body' => wp_json_encode( $body ), 'timeout' => 60, ] ); $code = wp_remote_retrieve_response_code( $res ); $body = json_decode( wp_remote_retrieve_body( $res ), true ); if ( $code >= 400 || ! $body ) { throw new \RuntimeException( sprintf( 'OpenAI error: %s', esc_html( wp_remote_retrieve_body( $res ) ) ) ); } return $body; } private function upload_file( string $path ): string { return OpenAI::upload_file( $path ); } private function add_user_message( string $thread, string $content ): void { $this->post_json( "https://api.openai.com/v1/threads/{$thread}/messages", [ 'role'=>'user', 'content'=>$content ] ); } private function run_assistant( string $thread, string $assistant, string $instructions ): void { $this->post_json( "https://api.openai.com/v1/threads/{$thread}/runs", [ 'assistant_id' => $assistant, 'response_format' => 'auto', 'tools' => [ [ 'type'=>'file_search' ] ], 'instructions' => $instructions, 'model' => get_option( 'aipub_ai_model', 'o1' ), 'max_prompt_tokens' => 300000, ] ); } private function wait_for_assistant_message( string $thread ): string { $start = time(); do { sleep( 2 ); $data = $this->get_json( "https://api.openai.com/v1/threads/{$thread}/runs" ); $run = $data['data'][0] ?? []; $status = $run['status'] ?? ''; if ( in_array( $status, [ 'failed', 'cancelled', 'expired' ], true ) ) { $msg = $run['last_error']['message'] ?? ( 'Run ' . $status ); throw new \RuntimeException( sprintf( 'OpenAI run failed: %s', esc_html( $msg ) ) ); } if ( time() - $start > 300 ) { throw new \RuntimeException( 'OpenAI run timed out.' ); } } while ( 'completed' !== $status ); $msgs = $this->get_json( "https://api.openai.com/v1/threads/{$thread}/messages" ); foreach ( $msgs['data'] as $m ) { if ( 'assistant' === $m['role'] ) { $txt = $m['content'][0]['text']['value'] ?? ''; return OpenAI::clean_text( $txt ); } } throw new \RuntimeException( 'Assistant message missing.' ); } private function get_json( string $url ): array { // Perform a GET and ensure we return a parsed array or throw on error. $response = wp_remote_get( $url, [ 'headers' => [ 'Authorization' => 'Bearer ' . get_option( 'aipub_openai_api_key' ), 'OpenAI-Beta' => 'assistants=v2', ], 'timeout' => 60, ] ); if ( is_wp_error( $response ) ) { throw new \RuntimeException( sprintf( 'OpenAI request failed: %s', esc_html( $response->get_error_message() ) ) ); } $code = wp_remote_retrieve_response_code( $response ); $body = wp_remote_retrieve_body( $response ); $data = json_decode( $body, true ); if ( $code >= 400 || ! is_array( $data ) ) { throw new \RuntimeException( sprintf( 'OpenAI error: %s', esc_html( $body ) ) ); } return $data; } /** * Replace em dashes with a comma and space across all string values. * * @param array $post Post data array. * @return array Sanitized post data. */ private function replace_em_dashes( array $post ): array { array_walk_recursive( $post, static function ( &$value ) { if ( is_string( $value ) ) { $value = str_replace( '—', ', ', $value ); } } ); return $post; } /** * Execute a generator stage with retry logic for OpenAI errors. * * @param callable $stage Stage callback. * @param string $label Stage label for identification. * @return mixed Result of the callback. * @throws \RuntimeException When retries are exhausted or error is not OpenAI related. */ private function run_stage( callable $stage, string $label ) { for ( $i = 1; $i <= self::MAX_RETRIES; $i++ ) { try { $result = $stage(); return $result; } catch ( \RuntimeException $e ) { $msg = $e->getMessage(); if ( false === strpos( $msg, 'OpenAI' ) || $i === self::MAX_RETRIES ) { throw $e; } $this->load_session(); } } } /** * Execute a callable with retry logic for transient OpenAI failures. * * @param callable $step Operation to perform. * @return mixed Result of the callable. * @throws \RuntimeException When all retries fail or the error is not OpenAI related. */ private function with_retry( callable $step ) { for ( $i = 1; $i <= self::MAX_RETRIES; $i++ ) { try { return $step(); } catch ( \RuntimeException $e ) { $msg = $e->getMessage(); if ( false === strpos( $msg, 'OpenAI' ) || $i === self::MAX_RETRIES ) { throw $e; } $run_active = false !== strpos( $msg, 'run' ) && false !== strpos( $msg, 'active' ); $cant_add_msg = false !== strpos( $msg, "Can't add messages to thread" ); if ( $run_active || $cant_add_msg ) { sleep( 5 ); } else { } } } } } // class Generator // Register async job handler. add_action( 'aipub_process_post_job', [ '\\AiPublisher\\Generator', 'process_async_job' ], 10, 1 ); add_action( 'aipub_process_topic_job', [ '\\AiPublisher\\Generator', 'process_async_topic_job' ], 10, 1 );