is_user_logged_in() ? 403 : 401], ); } /** `retry_after` in the data mirrors the Retry-After header Rest\Controller adds, for clients that read the body only. */ public static function tooMany(int $retryAfter): \WP_Error { return new \WP_Error( 'alpaca_bot_rate_limited', __('Too many requests. Try again shortly.', 'alpaca-bot'), ['status' => 429, 'retry_after' => $retryAfter], ); } /** * 429 for a stream redemption that found this person already holding as many live streams as * the site allows (StreamBudget::claim()). Its own code rather than tooMany()'s, because the * two 429s are different waits: the per-minute bucket turns over within the minute and the * request was spent, while this one frees when one of the person's own streams ends and the * ticket is left unspent for the retry. A client that keys on the code can say so; one that * keys on the status alone still sees a 429 with Retry-After. The message names the number * because that is the thing the person can act on, and `limit` carries it for a client that * words its own. * * @since 0.6.0 */ public static function streamConcurrency(int $limit, int $retryAfter): \WP_Error { return new \WP_Error( 'alpaca_bot_stream_concurrency', sprintf( /* translators: %d: how many replies one person may have streaming at once */ _n( 'You already have %d stream open. Wait for it to finish, then send again.', 'You already have %d streams open. Wait for one to finish, then send again.', $limit, 'alpaca-bot', ), $limit, ), ['status' => 429, 'retry_after' => $retryAfter, 'limit' => $limit], ); } /** * 409 for an ability asked to start a turn while one is already running in the request * (Chat\Pipeline::running()): the ability was reached from inside a turn, through a tool the * turn was offered that runs abilities, and a turn does not start another (Kanboard #4538). * The abilities toolkit refuses `alpaca-bot/*` itself before this is asked (AbilitiesToolkit); * a tool from a toolkit a site adds is not held to that. Conflict rather than 400: the input is fine and the same call made * outside a turn runs. Reached through a tool, the message is the tool's result the model * reads, so it tells the model what to do instead. * * @since 0.6.0 */ public static function turnRunning(): \WP_Error { return new \WP_Error( 'alpaca_bot_turn_running', __('A chat turn is already running, and Alpaca Bot does not start another one inside it. Answer in the turn that is running instead.', 'alpaca-bot'), ['status' => 409], ); } /** * 402 Payment Required is the nearest status for "your monthly allowance is spent": not a * permission problem (403) and not the client's fault (4xx otherwise), and distinct enough * that a client can show the cap rather than a generic error. The message is CapExceeded's * own, which keeps the site-wide figures out of a user-facing reply, and the data follows * it: `limit` and `used` ride along for the user's own cap only. The site's cap and its * month-to-date total are what `GET /usage` withholds from a non-administrator, and anyone * who may chat can reach this error by chatting once past the cap. `scope` is always there, * so a client can say whose cap it was. */ public static function capExceeded(CapExceeded $e): \WP_Error { $data = ['status' => 402, 'scope' => $e->scope]; if ($e->scope === 'user') { $data += ['limit' => $e->limit, 'used' => $e->used]; } return new \WP_Error('alpaca_bot_cap_exceeded', $e->getMessage(), $data); } /** * 400 for a request the pipeline refused as the caller's mistake: an empty message, an image * that is not a base64 image data URL or images past the site's allowance, a model the * catalog does not list, a conversation that is not theirs. The pipeline's InvalidArgumentException messages are already written for the * person who sent the request, so a route passes them through as the message. * * `$code` is `alpaca_bot_bad_request` unless a route has a refusal a client needs to tell * apart: `PUT /settings` answers `alpaca_bot_mcp_address` for an MCP server address that did * not pass the check, and `alpaca_bot_mcp_row` for an MCP server row the schema would drop, * with the rows in `$data`. * * @param array $data added to the error's data beside `status` */ public static function badRequest(string $message, string $code = 'alpaca_bot_bad_request', array $data = []): \WP_Error { return new \WP_Error($code, $message, ['status' => 400] + $data); } /** * 405 for a method a route cannot answer. Core sends a HEAD to a route's GET handler when * no HEAD handler is registered, so a route whose GET has an effect (the stream route runs * a turn) refuses it here; the Allow header a 405 must carry is the route's to add. */ public static function methodNotAllowed(): \WP_Error { return new \WP_Error('alpaca_bot_method_not_allowed', __('This route does not answer that method.', 'alpaca-bot'), ['status' => 405]); } /** * 504 for a streamed turn that outran the site's wall-clock budget for one (Rest\StreamBudget * says how the budget is chosen). Gateway Timeout rather than 408: the client's request * arrived whole and on time, and what ran out of time was the turn behind it. It only ever * reaches a client inside an `error` frame — a stream that has already sent its headers has * no status left to set — so the code is what a client keys on, and `limit` is there so it * can say how long the site allows rather than guess. */ public static function streamTimeout(int $seconds): \WP_Error { return new \WP_Error( 'alpaca_bot_stream_timeout', __('This reply ran longer than the site allows for one streamed turn, so it was stopped. What had arrived is saved.', 'alpaca-bot'), ['status' => 504, 'limit' => $seconds], ); } /** `$what` is the (translated) noun, e.g. "Conversation"; used for another user's resource too, so existence is not leaked. */ public static function notFound(string $what): \WP_Error { /* translators: %s: the kind of thing that was asked for, e.g. Conversation */ return new \WP_Error('alpaca_bot_not_found', sprintf(__('%s not found.', 'alpaca-bot'), $what), ['status' => 404]); } /** * 502: the upstream model provider failed, so the client should not retry blindly and the * operator should look at the provider. * * The message is fixed. What the provider threw quotes its endpoint (the vendored client's * transport and HTTP errors both end in `for "http://host:port/v1/chat/completions"`), and * anyone who may chat can make it throw by posting while the provider is down, so the raw * text is not for the caller: it goes to the debug log, behind WP_DEBUG as core's own * logging is, and to `data.detail` when the request is an administrator's, who is the one * person it helps and may read the settings that hold the URL anyway. The code and status are * the wire contract and do not change with who asked. */ public static function provider(\Throwable $e): \WP_Error { $detail = $e->getMessage(); if (defined('WP_DEBUG') && WP_DEBUG) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Deliberate diagnostic, gated on WP_DEBUG exactly as core's own logging is; the provider's raw error is withheld from the response body and this is the only place an administrator can read it. error_log('[alpaca-bot] ' . $detail); } $data = ['status' => 502]; if (current_user_can('manage_options')) { $data['detail'] = $detail; } return new \WP_Error('alpaca_bot_provider_error', __('The model provider could not complete the request.', 'alpaca-bot'), $data); } /** * What a pipeline turn's failure becomes, for every caller that runs one: CapExceeded is the * 402, an InvalidArgumentException (the caller's mistake, in the pipeline's own words) the * 400, anything else the 502. * * The buffered route returns this and the stream route writes it into an `error` frame, so * one turn told two ways refuses the same way. It is a function rather than the same three * catch blocks in both because the policy has to stay one when a later phase adds a fourth * exception class: prose saying "these must match" does not fail a build, and the second * copy is the one that gets missed. */ public static function fromPipeline(\Throwable $e): \WP_Error { return match (true) { $e instanceof CapExceeded => self::capExceeded($e), $e instanceof \InvalidArgumentException => self::badRequest($e->getMessage()), default => self::provider($e), }; } }