From 070609c01ee805e3fd74d6cfa760e83e679f852d Mon Sep 17 00:00:00 2001 From: Nol de Roos <108540791+nolderoos@users.noreply.github.com> Date: Tue, 12 May 2026 21:54:50 +0200 Subject: [PATCH 1/7] fix: route SSE streaming through wp_safe_remote_post + http_api_curl (#14) --- .../class-opentrust-chat-provider.php | 180 ++++++++++-------- 1 file changed, 97 insertions(+), 83 deletions(-) diff --git a/includes/providers/class-opentrust-chat-provider.php b/includes/providers/class-opentrust-chat-provider.php index f233fad..af890d5 100644 --- a/includes/providers/class-opentrust-chat-provider.php +++ b/includes/providers/class-opentrust-chat-provider.php @@ -513,111 +513,125 @@ final protected function stream_post(string $url, array $payload, array $headers return ['ok' => false, 'error' => __('Refused outbound request to disallowed host.', 'opentrust')]; } + // SSE chunk callbacks require cURL transport. Streams/fsockopen buffer the full response. + if (!function_exists('curl_init')) { + return ['ok' => false, 'error' => __('AI streaming requires the PHP cURL extension.', 'opentrust')]; + } + $body = wp_json_encode($payload); if ($body === false) { return ['ok' => false, 'error' => 'Payload JSON encoding failed.']; } - $curl_headers = ['Content-Type: application/json', 'Accept: text/event-stream']; - foreach ($headers as $k => $v) { - $curl_headers[] = $k . ': ' . $v; - } + // Shared state between the http_api_curl callback and the post-request branch. + $state = (object) [ + 'url' => $url, + 'on_line' => $on_line, + 'buffer' => '', + 'error_body' => '', + 'early_status' => 0, + 'response_headers' => [], + 'connect_timeout' => 15, + ]; - $buffer = ''; - $error_body = ''; - $response_headers = []; - $early_status = 0; - - // phpcs:disable WordPress.WP.AlternativeFunctions.curl_curl_init, WordPress.WP.AlternativeFunctions.curl_curl_setopt, WordPress.WP.AlternativeFunctions.curl_curl_exec, WordPress.WP.AlternativeFunctions.curl_curl_getinfo, WordPress.WP.AlternativeFunctions.curl_curl_errno, WordPress.WP.AlternativeFunctions.curl_curl_error, WordPress.WP.AlternativeFunctions.curl_curl_close -- SSE streaming requires CURLOPT_WRITEFUNCTION; wp_remote_* does not support streaming callbacks. - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_POST, true); - curl_setopt($ch, CURLOPT_POSTFIELDS, $body); - curl_setopt($ch, CURLOPT_HTTPHEADER, $curl_headers); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); - curl_setopt($ch, CURLOPT_HEADER, false); - curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); - curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15); - curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); - curl_setopt($ch, CURLOPT_HEADERFUNCTION, function ($ch, string $line) use (&$early_status, &$response_headers): int { - $len = strlen($line); - $trimmed = trim($line); - if ($trimmed === '') { - return $len; + // wp_safe_remote_post collapses connect + total timeout into one 'timeout' arg, + // and never sets CURLOPT_WRITEFUNCTION / CURLOPT_HEADERFUNCTION. Inject those on + // the live cURL handle via the documented http_api_curl escape hatch, scoped to + // this request's URL so it doesn't leak to other outbound HTTP calls in the same + // PHP request. + $filter = function ($handle, $args, $filter_url) use ($state): void { + if ((string) $filter_url !== $state->url) { + return; } - if (preg_match('#^HTTP/[\d.]+\s+(\d{3})#', $trimmed, $m)) { - $early_status = (int) $m[1]; + // phpcs:disable WordPress.WP.AlternativeFunctions.curl_curl_setopt -- documented http_api_curl escape hatch for SSE streaming. + curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, $state->connect_timeout); + curl_setopt($handle, CURLOPT_FOLLOWLOCATION, false); + curl_setopt($handle, CURLOPT_HEADERFUNCTION, function ($ch, string $line) use ($state): int { + $len = strlen($line); + $trimmed = trim($line); + if ($trimmed === '') { + return $len; + } + if (preg_match('#^HTTP/[\d.]+\s+(\d{3})#', $trimmed, $m)) { + $state->early_status = (int) $m[1]; + return $len; + } + $colon = strpos($trimmed, ':'); + if ($colon !== false) { + $k = strtolower(trim(substr($trimmed, 0, $colon))); + $v = trim(substr($trimmed, $colon + 1)); + $state->response_headers[$k] = $v; + } return $len; - } - $colon = strpos($trimmed, ':'); - if ($colon !== false) { - $k = strtolower(trim(substr($trimmed, 0, $colon))); - $v = trim(substr($trimmed, $colon + 1)); - $response_headers[$k] = $v; - } - return $len; - }); - curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, string $chunk) use (&$buffer, &$error_body, &$early_status, $on_line): int { - // Non-2xx response — accumulate the body as an error payload - // instead of feeding it to the SSE parser. Anthropic returns - // plain JSON like {"type":"error","error":{"type":"...","message":"..."}} - // on errors, which doesn't match the SSE line shape and would - // otherwise be silently dropped. - if ($early_status >= 300) { - $error_body .= $chunk; + }); + curl_setopt($handle, CURLOPT_WRITEFUNCTION, function ($ch, string $chunk) use ($state): int { + // Non-2xx: accumulate as an error payload. Anthropic returns plain JSON + // ({"type":"error",…}) that doesn't match SSE line shape. + if ($state->early_status >= 300) { + $state->error_body .= $chunk; + if (function_exists('connection_aborted') && connection_aborted()) { + return 0; + } + return strlen($chunk); + } + + $state->buffer .= $chunk; + + while (($pos = strpos($state->buffer, "\n")) !== false) { + $line = substr($state->buffer, 0, $pos); + $state->buffer = substr($state->buffer, $pos + 1); + $line = rtrim($line, "\r"); + ($state->on_line)($line); + } + + // Honor visitor aborts; short write cancels the transfer. if (function_exists('connection_aborted') && connection_aborted()) { return 0; } + return strlen($chunk); - } + }); + // phpcs:enable WordPress.WP.AlternativeFunctions.curl_curl_setopt + }; - $buffer .= $chunk; + add_action('http_api_curl', $filter, 10, 3); - // Process complete lines. SSE line terminator is LF; events separated by blank line. - while (($pos = strpos($buffer, "\n")) !== false) { - $line = substr($buffer, 0, $pos); - $buffer = substr($buffer, $pos + 1); - $line = rtrim($line, "\r"); - $on_line($line); - } + $response = wp_safe_remote_post($url, [ + 'timeout' => $timeout, + 'redirection' => 0, + 'sslverify' => true, + 'blocking' => true, + 'headers' => array_merge( + ['Content-Type' => 'application/json', 'Accept' => 'text/event-stream'], + $headers + ), + 'body' => $body, + ]); - // Honor visitor aborts. - if (function_exists('connection_aborted') && connection_aborted()) { - return 0; // return value < chunk length aborts curl - } + remove_action('http_api_curl', $filter, 10); + + // Status code lives in $state (header callback), not the WP response body, since + // our WRITEFUNCTION suppresses Requests' default body/header collectors. + $http_code = $state->early_status > 0 + ? $state->early_status + : (is_wp_error($response) ? 0 : (int) wp_remote_retrieve_response_code($response)); - return strlen($chunk); - }); - - $ok = curl_exec($ch); - $http_code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE); - $curl_errno = curl_errno($ch); - $curl_err = curl_error($ch); - curl_close($ch); - // phpcs:enable - - // Flush any trailing line not followed by newline — but only on success; - // on an error response the buffer holds the JSON error body, which the - // SSE parser would mis-interpret. - if ($buffer !== '' && $http_code >= 200 && $http_code < 300) { - $on_line(rtrim($buffer, "\r")); + // Flush trailing partial line — only on success; on error the buffer holds JSON. + if ($state->buffer !== '' && $http_code >= 200 && $http_code < 300) { + ($state->on_line)(rtrim($state->buffer, "\r")); } - if ($ok === false && $curl_errno !== 0) { - return ['ok' => false, 'code' => $http_code, 'error' => $curl_err ?: 'cURL request failed.']; + if (is_wp_error($response)) { + return ['ok' => false, 'code' => $http_code, 'error' => $response->get_error_message()]; } if ($http_code < 200 || $http_code >= 300) { - // Some hosts return the body via WRITEFUNCTION before - // HEADERFUNCTION has set $early_status; fall back to $buffer. - if ($error_body === '' && $buffer !== '') { - $error_body = $buffer; + // Race: WRITEFUNCTION can fire before HEADERFUNCTION captures non-2xx status, + // so a small first chunk may land in $buffer instead of $error_body. + if ($state->error_body === '' && $state->buffer !== '') { + $state->error_body = $state->buffer; } - $detail = $this->describe_streaming_error($error_body, $response_headers, $http_code); - // Log unconditionally so post-mortem doesn't depend on whether - // the message survived translation to the client. + $detail = $this->describe_streaming_error($state->error_body, $state->response_headers, $http_code); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- diagnostic for upstream provider failures error_log('[OpenTrust] ' . $detail); return ['ok' => false, 'code' => $http_code, 'error' => $detail]; From 8917a73a62aa3ffcf1d3f485aa6560deade87988 Mon Sep 17 00:00:00 2001 From: Nol de Roos <108540791+nolderoos@users.noreply.github.com> Date: Tue, 12 May 2026 22:24:44 +0200 Subject: [PATCH 2/7] chore: regenerate POT --- languages/opentrust.pot | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/languages/opentrust.pot b/languages/opentrust.pot index 716de4f..32b7f6e 100644 --- a/languages/opentrust.pot +++ b/languages/opentrust.pot @@ -9,7 +9,7 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"POT-Creation-Date: 2026-05-11T15:00:11+00:00\n" +"POT-Creation-Date: 2026-05-12T20:24:36+00:00\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "X-Generator: WP-CLI 2.12.0\n" "X-Domain: opentrust\n" @@ -2148,9 +2148,13 @@ msgstr "" msgid "Refused outbound request to disallowed host." msgstr "" +#: includes/providers/class-opentrust-chat-provider.php:518 +msgid "AI streaming requires the PHP cURL extension." +msgstr "" + #. translators: %d: HTTP status code returned by the provider -#: includes/providers/class-opentrust-chat-provider.php:638 -#: includes/providers/class-opentrust-chat-provider.php:693 +#: includes/providers/class-opentrust-chat-provider.php:652 +#: includes/providers/class-opentrust-chat-provider.php:707 #, php-format msgid "Provider returned HTTP %d" msgstr "" From 5fabfcee12dab847b5e9b5bb0c5409e18ac20e3c Mon Sep 17 00:00:00 2001 From: Nol de Roos <108540791+nolderoos@users.noreply.github.com> Date: Tue, 12 May 2026 22:32:03 +0200 Subject: [PATCH 3/7] fix: error out when http_api_curl hook never fires --- includes/providers/class-opentrust-chat-provider.php | 8 ++++++++ languages/opentrust.pot | 10 +++++++--- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/includes/providers/class-opentrust-chat-provider.php b/includes/providers/class-opentrust-chat-provider.php index af890d5..5588d57 100644 --- a/includes/providers/class-opentrust-chat-provider.php +++ b/includes/providers/class-opentrust-chat-provider.php @@ -532,6 +532,7 @@ final protected function stream_post(string $url, array $payload, array $headers 'early_status' => 0, 'response_headers' => [], 'connect_timeout' => 15, + 'curl_hook_ran' => false, ]; // wp_safe_remote_post collapses connect + total timeout into one 'timeout' arg, @@ -543,6 +544,7 @@ final protected function stream_post(string $url, array $payload, array $headers if ((string) $filter_url !== $state->url) { return; } + $state->curl_hook_ran = true; // phpcs:disable WordPress.WP.AlternativeFunctions.curl_curl_setopt -- documented http_api_curl escape hatch for SSE streaming. curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, $state->connect_timeout); curl_setopt($handle, CURLOPT_FOLLOWLOCATION, false); @@ -610,6 +612,12 @@ final protected function stream_post(string $url, array $payload, array $headers remove_action('http_api_curl', $filter, 10); + // If WP picked Streams/fsockopen, http_api_curl never fired and our SSE callbacks + // never installed — the response body was buffered, not streamed. Fail loudly. + if (!$state->curl_hook_ran) { + return ['ok' => false, 'error' => __('AI streaming requires the WordPress cURL transport.', 'opentrust')]; + } + // Status code lives in $state (header callback), not the WP response body, since // our WRITEFUNCTION suppresses Requests' default body/header collectors. $http_code = $state->early_status > 0 diff --git a/languages/opentrust.pot b/languages/opentrust.pot index 32b7f6e..3ac314a 100644 --- a/languages/opentrust.pot +++ b/languages/opentrust.pot @@ -9,7 +9,7 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"POT-Creation-Date: 2026-05-12T20:24:36+00:00\n" +"POT-Creation-Date: 2026-05-12T20:31:58+00:00\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "X-Generator: WP-CLI 2.12.0\n" "X-Domain: opentrust\n" @@ -2152,9 +2152,13 @@ msgstr "" msgid "AI streaming requires the PHP cURL extension." msgstr "" +#: includes/providers/class-opentrust-chat-provider.php:618 +msgid "AI streaming requires the WordPress cURL transport." +msgstr "" + #. translators: %d: HTTP status code returned by the provider -#: includes/providers/class-opentrust-chat-provider.php:652 -#: includes/providers/class-opentrust-chat-provider.php:707 +#: includes/providers/class-opentrust-chat-provider.php:660 +#: includes/providers/class-opentrust-chat-provider.php:715 #, php-format msgid "Provider returned HTTP %d" msgstr "" From 53cd31d2b8bf8bf9d2cd562354a6ab8468c770e0 Mon Sep 17 00:00:00 2001 From: Nol de Roos <108540791+nolderoos@users.noreply.github.com> Date: Tue, 12 May 2026 22:40:27 +0200 Subject: [PATCH 4/7] fix: detach http_api_curl hook via try/finally --- .../class-opentrust-chat-provider.php | 30 +++++++++++-------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/includes/providers/class-opentrust-chat-provider.php b/includes/providers/class-opentrust-chat-provider.php index 5588d57..9c14701 100644 --- a/includes/providers/class-opentrust-chat-provider.php +++ b/includes/providers/class-opentrust-chat-provider.php @@ -598,19 +598,23 @@ final protected function stream_post(string $url, array $payload, array $headers add_action('http_api_curl', $filter, 10, 3); - $response = wp_safe_remote_post($url, [ - 'timeout' => $timeout, - 'redirection' => 0, - 'sslverify' => true, - 'blocking' => true, - 'headers' => array_merge( - ['Content-Type' => 'application/json', 'Accept' => 'text/event-stream'], - $headers - ), - 'body' => $body, - ]); - - remove_action('http_api_curl', $filter, 10); + try { + $response = wp_safe_remote_post($url, [ + 'timeout' => $timeout, + 'redirection' => 0, + 'sslverify' => true, + 'blocking' => true, + 'headers' => array_merge( + ['Content-Type' => 'application/json', 'Accept' => 'text/event-stream'], + $headers + ), + 'body' => $body, + ]); + } finally { + // $on_line is caller-supplied; if it throws inside WRITEFUNCTION the + // exception unwinds through cURL → wp_safe_remote_post. Always detach. + remove_action('http_api_curl', $filter, 10); + } // If WP picked Streams/fsockopen, http_api_curl never fired and our SSE callbacks // never installed — the response body was buffered, not streamed. Fail loudly. From 3c0131353d86f9ed593e99c695a16ce2f955fa7f Mon Sep 17 00:00:00 2001 From: Nol de Roos <108540791+nolderoos@users.noreply.github.com> Date: Tue, 12 May 2026 22:42:55 +0200 Subject: [PATCH 5/7] chore: regenerate POT --- languages/opentrust.pot | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/languages/opentrust.pot b/languages/opentrust.pot index 3ac314a..3f12b1c 100644 --- a/languages/opentrust.pot +++ b/languages/opentrust.pot @@ -9,7 +9,7 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"POT-Creation-Date: 2026-05-12T20:31:58+00:00\n" +"POT-Creation-Date: 2026-05-12T20:42:50+00:00\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "X-Generator: WP-CLI 2.12.0\n" "X-Domain: opentrust\n" @@ -2152,13 +2152,13 @@ msgstr "" msgid "AI streaming requires the PHP cURL extension." msgstr "" -#: includes/providers/class-opentrust-chat-provider.php:618 +#: includes/providers/class-opentrust-chat-provider.php:622 msgid "AI streaming requires the WordPress cURL transport." msgstr "" #. translators: %d: HTTP status code returned by the provider -#: includes/providers/class-opentrust-chat-provider.php:660 -#: includes/providers/class-opentrust-chat-provider.php:715 +#: includes/providers/class-opentrust-chat-provider.php:664 +#: includes/providers/class-opentrust-chat-provider.php:719 #, php-format msgid "Provider returned HTTP %d" msgstr "" From d54bc42450522557f2828e43d3e23c552cbdb2d4 Mon Sep 17 00:00:00 2001 From: Nol de Roos <108540791+nolderoos@users.noreply.github.com> Date: Wed, 13 May 2026 15:38:37 +0200 Subject: [PATCH 6/7] fix(chat): stop overriding CURLOPT_HEADERFUNCTION in stream_post MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The previous code installed both CURLOPT_WRITEFUNCTION and CURLOPT_HEADERFUNCTION via the http_api_curl filter. Replacing HEADERFUNCTION clobbered WP's Requests Curl transport stream_headers() method, leaving its internal $this->headers buffer empty. After curl_exec, Requests::parse_response() called strpos('', "\r\n\r\n"), got false, and threw \WpOrg\Requests\Exception('Missing header/body separator', 'requests.no_crlf_separator') out of wp-includes/Requests/src/Requests.php:737. WP wrapped it as WP_Error, the upstream Anthropic call returned ['ok' => false, 'error' => 'Missing header/body separator'], and the chat UI rendered that exact string as a red error banner beneath an empty assistant bubble — even on successful upstream streams. The round-2 analysis at wporg-review/04-curl-vs-http-api/analysis.md:16 predicted $this->headers would stay empty but assumed WP would "bubble up a response array with empty body, empty headers, falsy code." It does not; parse_response throws before WP can wrap the response. Fix: - Remove the CURLOPT_HEADERFUNCTION setopt entirely so Requests' stream_headers runs unmodified and accumulates the header block ending in \r\n\r\n. After our WRITEFUNCTION consumes the body, Requests' parser finds the separator (headers + empty body) and returns a normal response array. - Capture early_status lazily inside WRITEFUNCTION via curl_getinfo($ch, CURLINFO_HTTP_CODE). cURL guarantees the status line is parsed before any body callback fires, so this is reliable. Keeps the same error-body routing semantics for non-2xx upstream responses. - After wp_safe_remote_post returns, copy headers from wp_remote_retrieve_headers($response) into $state->response_headers so describe_streaming_error() still surfaces retry-after / anthropic-ratelimit-* / x-ratelimit-* hints in the error path. - Add a load-bearing comment above the filter explaining why HEADERFUNCTION must not be re-added. Net diff: +38 / -28. No change to streaming semantics, visitor-abort handling, host allowlist, SSL verification, or error-body shape. The wp.org reviewer's constraint (route outbound HTTP through wp_safe_remote_post / wp_safe_remote_get and use http_api_curl only as the documented escape hatch for setopt) is preserved — and tightened, since this drops one setopt call. Co-Authored-By: Claude Opus 4.7 (1M context) --- .../class-opentrust-chat-provider.php | 66 +++++++++++-------- 1 file changed, 38 insertions(+), 28 deletions(-) diff --git a/includes/providers/class-opentrust-chat-provider.php b/includes/providers/class-opentrust-chat-provider.php index 9c14701..9572274 100644 --- a/includes/providers/class-opentrust-chat-provider.php +++ b/includes/providers/class-opentrust-chat-provider.php @@ -536,37 +536,35 @@ final protected function stream_post(string $url, array $payload, array $headers ]; // wp_safe_remote_post collapses connect + total timeout into one 'timeout' arg, - // and never sets CURLOPT_WRITEFUNCTION / CURLOPT_HEADERFUNCTION. Inject those on - // the live cURL handle via the documented http_api_curl escape hatch, scoped to - // this request's URL so it doesn't leak to other outbound HTTP calls in the same - // PHP request. + // and never sets CURLOPT_WRITEFUNCTION. Inject ours on the live cURL handle via the + // documented http_api_curl escape hatch, scoped to this request's URL so it doesn't + // leak to other outbound HTTP calls in the same PHP request. + // + // We deliberately do NOT install CURLOPT_HEADERFUNCTION. WP's Requests Curl + // transport sets it to its own stream_headers() in setup_handle(), which + // populates the transport's internal $this->headers buffer. If we replace that, + // $this->headers stays empty, and after curl_exec the Requests parser throws + // "Missing header/body separator" out of WpOrg\Requests\Requests::parse_response + // (it splits on \r\n\r\n and finds nothing) → WP returns a WP_Error and the + // upstream call fails before we can read the response. The early HTTP status we + // need for our error-body branch is fetched lazily inside WRITEFUNCTION via + // curl_getinfo(); response headers are read after the call via + // wp_remote_retrieve_headers(). Do not re-add a header callback here. $filter = function ($handle, $args, $filter_url) use ($state): void { if ((string) $filter_url !== $state->url) { return; } $state->curl_hook_ran = true; - // phpcs:disable WordPress.WP.AlternativeFunctions.curl_curl_setopt -- documented http_api_curl escape hatch for SSE streaming. + // phpcs:disable WordPress.WP.AlternativeFunctions.curl_curl_setopt, WordPress.WP.AlternativeFunctions.curl_curl_getinfo -- documented http_api_curl escape hatch for SSE streaming. curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, $state->connect_timeout); curl_setopt($handle, CURLOPT_FOLLOWLOCATION, false); - curl_setopt($handle, CURLOPT_HEADERFUNCTION, function ($ch, string $line) use ($state): int { - $len = strlen($line); - $trimmed = trim($line); - if ($trimmed === '') { - return $len; - } - if (preg_match('#^HTTP/[\d.]+\s+(\d{3})#', $trimmed, $m)) { - $state->early_status = (int) $m[1]; - return $len; - } - $colon = strpos($trimmed, ':'); - if ($colon !== false) { - $k = strtolower(trim(substr($trimmed, 0, $colon))); - $v = trim(substr($trimmed, $colon + 1)); - $state->response_headers[$k] = $v; - } - return $len; - }); curl_setopt($handle, CURLOPT_WRITEFUNCTION, function ($ch, string $chunk) use ($state): int { + // cURL has parsed the response status line before any body callback + // fires, so CURLINFO_HTTP_CODE is reliable here. Capture once. + if ($state->early_status === 0) { + $state->early_status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE); + } + // Non-2xx: accumulate as an error payload. Anthropic returns plain JSON // ({"type":"error",…}) that doesn't match SSE line shape. if ($state->early_status >= 300) { @@ -593,7 +591,7 @@ final protected function stream_post(string $url, array $payload, array $headers return strlen($chunk); }); - // phpcs:enable WordPress.WP.AlternativeFunctions.curl_curl_setopt + // phpcs:enable WordPress.WP.AlternativeFunctions.curl_curl_setopt, WordPress.WP.AlternativeFunctions.curl_curl_getinfo }; add_action('http_api_curl', $filter, 10, 3); @@ -622,8 +620,19 @@ final protected function stream_post(string $url, array $payload, array $headers return ['ok' => false, 'error' => __('AI streaming requires the WordPress cURL transport.', 'opentrust')]; } - // Status code lives in $state (header callback), not the WP response body, since - // our WRITEFUNCTION suppresses Requests' default body/header collectors. + // Copy parsed response headers (Requests' stream_headers still ran since we + // didn't override it) into our state so describe_streaming_error() can surface + // rate-limit hints (retry-after, anthropic-ratelimit-*, x-ratelimit-*). + if (!is_wp_error($response)) { + foreach (wp_remote_retrieve_headers($response) as $k => $v) { + $state->response_headers[strtolower((string) $k)] + = is_array($v) ? implode(', ', $v) : (string) $v; + } + } + + // early_status is populated by the first WRITEFUNCTION call via curl_getinfo. + // Fall back to the WP response code if for any reason it wasn't captured (e.g., + // 0-byte response, transport never invoked the write callback). $http_code = $state->early_status > 0 ? $state->early_status : (is_wp_error($response) ? 0 : (int) wp_remote_retrieve_response_code($response)); @@ -638,8 +647,9 @@ final protected function stream_post(string $url, array $payload, array $headers } if ($http_code < 200 || $http_code >= 300) { - // Race: WRITEFUNCTION can fire before HEADERFUNCTION captures non-2xx status, - // so a small first chunk may land in $buffer instead of $error_body. + // Paranoia: if early_status was 0 on the very first WRITEFUNCTION call (the + // status hadn't been parsed yet for some transports), the first chunk landed + // in $buffer instead of $error_body. Rescue it. if ($state->error_body === '' && $state->buffer !== '') { $state->error_body = $state->buffer; } From 324843abb248d937e073e2450f9792f0c0e974dd Mon Sep 17 00:00:00 2001 From: Nol de Roos <108540791+nolderoos@users.noreply.github.com> Date: Wed, 13 May 2026 17:28:55 +0200 Subject: [PATCH 7/7] chore: regenerate POT after HEADERFUNCTION removal MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Line refs in includes/providers/class-opentrust-chat-provider.php shifted when the CURLOPT_HEADERFUNCTION block was deleted in d54bc42: - "AI streaming requires the WordPress cURL transport.": 622 → 620 - "Provider returned HTTP %d": 664 → 674, 719 → 729 Co-Authored-By: Claude Opus 4.7 (1M context) --- languages/opentrust.pot | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/languages/opentrust.pot b/languages/opentrust.pot index 3f12b1c..23e4689 100644 --- a/languages/opentrust.pot +++ b/languages/opentrust.pot @@ -9,7 +9,7 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"POT-Creation-Date: 2026-05-12T20:42:50+00:00\n" +"POT-Creation-Date: 2026-05-13T15:28:45+00:00\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "X-Generator: WP-CLI 2.12.0\n" "X-Domain: opentrust\n" @@ -2152,13 +2152,13 @@ msgstr "" msgid "AI streaming requires the PHP cURL extension." msgstr "" -#: includes/providers/class-opentrust-chat-provider.php:622 +#: includes/providers/class-opentrust-chat-provider.php:620 msgid "AI streaming requires the WordPress cURL transport." msgstr "" #. translators: %d: HTTP status code returned by the provider -#: includes/providers/class-opentrust-chat-provider.php:664 -#: includes/providers/class-opentrust-chat-provider.php:719 +#: includes/providers/class-opentrust-chat-provider.php:674 +#: includes/providers/class-opentrust-chat-provider.php:729 #, php-format msgid "Provider returned HTTP %d" msgstr ""