Skip to content

Instantly share code, notes, and snippets.

@jordymeow
Created November 26, 2025 04:28
Show Gist options
  • Select an option

  • Save jordymeow/a0220b3001cee4da50cde959a57ce431 to your computer and use it in GitHub Desktop.

Select an option

Save jordymeow/a0220b3001cee4da50cde959a57ce431 to your computer and use it in GitHub Desktop.
Strips closures from AI Engine reply payloads to avoid serialization fatals on custom autoloaders.
<?php
/**
* Plugin Name: AI Engine Safe Serialize Guard
* Description: Strips closures from AI Engine reply payloads to avoid serialization fatals on custom autoloaders.
*/
function mwai_safe_normalize_closures( $value, $ctx = 'v', $depth = 0 ) {
if ( $depth > 10 ) {
return "[{$ctx}:max-depth]";
}
if ( $value instanceof \Closure ) {
return "[{$ctx}:closure]";
}
if ( is_array( $value ) ) {
foreach ( $value as $k => $v ) {
$value[ $k ] = mwai_safe_normalize_closures( $v, "{$ctx}.{$k}", $depth + 1 );
}
return $value;
}
if ( is_object( $value ) ) {
foreach ( get_object_vars( $value ) as $prop => $v ) {
$value->$prop = mwai_safe_normalize_closures( $v, "{$ctx}.{$prop}", $depth + 1 );
}
return $value;
}
return $value;
}
// Sanitize feedback payloads before AI Engine serializes them.
add_filter( 'mwai_ai_reply', function( $reply ) {
if ( !empty( $reply->needFeedbacks ) ) {
foreach ( $reply->needFeedbacks as $i => $nf ) {
if ( isset( $nf['rawMessage'] ) ) {
$reply->needFeedbacks[ $i ]['rawMessage'] = mwai_safe_normalize_closures( $nf['rawMessage'], 'rawMessage' );
}
}
}
return $reply;
}, 1 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment