Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
188 changes: 105 additions & 83 deletions includes/providers/class-opentrust-chat-provider.php
Original file line number Diff line number Diff line change
Expand Up @@ -513,111 +513,133 @@ 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,
'curl_hook_ran' => false,
];
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

$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];
$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);
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);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

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"));
// 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')];
}

if ($ok === false && $curl_errno !== 0) {
return ['ok' => false, 'code' => $http_code, 'error' => $curl_err ?: 'cURL request failed.'];
// 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));

// 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 (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];
Expand Down
14 changes: 11 additions & 3 deletions languages/opentrust.pot
Original file line number Diff line number Diff line change
Expand Up @@ -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: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"
Expand Down Expand Up @@ -2148,9 +2148,17 @@ 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 ""

#: 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:638
#: includes/providers/class-opentrust-chat-provider.php:693
#: includes/providers/class-opentrust-chat-provider.php:660
#: includes/providers/class-opentrust-chat-provider.php:715
#, php-format
msgid "Provider returned HTTP %d"
msgstr ""
Expand Down
Loading