1, 'm' => 60, 'h' => 3600, 'd' => 86400]; /** @var array the text this request already produced, by cache key */ private array $served = []; /** * @var array the rendered notice for each turn this request already tried * and lost, by cache key. Rendered, not raw: a failure is never cached across requests * (the class docblock says why), so unlike `$served` there is nothing here for output() * to format later. */ private array $failures = []; public function __construct( private Store $store, private ModelCatalog $catalog, private ConversationStore $conversations, private UserPrefs $prefs, private Pipeline $pipeline, private Markdown $markdown, private Assets $assets, private Access $access, ) {} public function register(): void { add_shortcode(self::TAG, [$this, 'render']); } /** * The shortcode handler, as core calls one: `$atts` is '' when the shortcode has none. * * @param array|string $atts */ public function render(array|string $atts = '', ?string $content = null, string $tag = self::TAG): string { $a = self::attributes($atts); if ($a['prompt'] === '') { return $this->shell(); } $model = $this->authorModel($a['model']); // The identity is what will shape the text, as far as this can know it without asking // the catalog: the author's model where the site honours it (else that none was named, // authorModel()), and the system prompt the site resolves, so a `model=` the site does // not honour and none are the same entry, and a site prompt the administrator edits is // a new one. $identity = [ 'prompt' => $a['prompt'], 'model' => $model, 'system' => $a['system'] !== '' ? $a['system'] : (string) $this->store->get('chat.system_prompt'), 'temperature' => $a['temperature'], ]; return $this->answer(self::TAG, $identity, $a['cache'], $a['format'], function (int $userId) use ($a, $model): string { $options = ['ephemeral' => true, 'context' => []]; if ($model !== '') { $options['model'] = $model; } if ($a['system'] !== '') { $options['system'] = $a['system']; } if ($a['temperature'] !== null) { $options['temperature'] = $a['temperature']; } return trim($this->pipeline->complete($userId, $a['prompt'], $options)->reply->content); }); } /** * The capability and cache rules of the class docblock around one generation, for this * shortcode and for the `[alpacabot_agent]` shim, which is the same rules over a different * generator. `$identity` is what shapes the text (the attributes, less the ones about * presentation), `$generate` produces it for the viewer's id and may throw, and its text is * what is cached and memoised, before `$format` is applied. * * @param array $identity * @param \Closure(int): string $generate */ public function answer(string $tag, array $identity, int $cacheSeconds, string $format, \Closure $generate): string { $postId = self::postId(); $key = self::cacheKey($tag, $identity, $postId, $cacheSeconds); // What this request already made, else the transient (never read with the cache off). $cached = $this->served[$key] ?? ($cacheSeconds > 0 ? get_transient($key) : false); if (!$this->viewerMayGenerate($postId, $tag)) { /** * Whether a viewer who may not generate, because they are not logged in or because * they fail the Shortcodes row of Settings › Access, may be shown a cached shortcode * answer. Default false: they see a notice. True serves them what an editor's view * cached for this post, and only that: a viewer the filter admits never triggers a * generation, so a page with no cache entry (expired, or never primed) shows them * the notice until someone the row admits opens it. * * @since 0.5.0 * @param bool $allow false * @param int $postId the post being rendered, 0 outside a post * @param string $tag the shortcode, `alpacabot` or `alpacabot_agent` */ $allowed = (bool) apply_filters('alpaca_bot/shortcode/allow_guests', false, $postId, $tag); if ($allowed && is_string($cached)) { return $this->output($cached, $format); } return $this->refused(); } if (is_string($cached)) { return $this->output($cached, $format); } if (wp_is_rest_endpoint()) { // A REST response is being produced (a standalone request, or an internal // dispatch): the cache was not there, and generating here is the class docblock's // hundred-turns-in-one-request case. return $this->notice(__('Alpaca Bot answers here when the page is viewed on the site; there is no cached answer yet.', 'alpaca-bot')); } // This turn already failed in this request. Before the limiter, because showing the // notice again is not a generation and must not count as one, and because the point of // the memo is the cost it saves: a turn that ends in the provider's timeout is the most // expensive thing on this path, and a theme that runs `the_content` twice would pay it // twice. Nothing is written to the transient, so the next request tries again. if (isset($this->failures[$key])) { return $this->failures[$key]; } // Only a generation is a hit: the limiter the REST routes and the abilities share, in // their bucket, as the class docblock says. $hit = (new RateLimit())->hit(get_current_user_id(), 'chat'); if (!$hit['allowed']) { // Not memoised: the class docblock's rule for the 429 is that every refused // shortcode on the page is counted, as the routes count one, so a second copy has // to reach the limiter rather than be answered from here. return $this->failed(Errors::tooMany($hit['retry_after'])->get_error_message()); } try { $text = $generate(get_current_user_id()); } catch (\Throwable $e) { $this->failures[$key] = $this->failed(Errors::fromPipeline($e)->get_error_message()); return $this->failures[$key]; } $this->served[$key] = $text; if ($cacheSeconds > 0) { set_transient($key, $text, $cacheSeconds); } return $this->output($text, $format); } /** * The model the author named, where the site honours it: the `model` attribute while * `chat.user_can_change_model` is on (the rule the pipeline applies to the option), else ''. * That is the only model a shortcode sends the pipeline, and the only one the cache * identity records. Given none, the pipeline resolves the model as it does for a chat turn: * the viewer's own stored preference where users may change it, else the site's default * with the catalog's grace (ModelCatalog::defaultId(): a default the provider has since * dropped falls back to the first listed model rather than refusing every turn), and the * identity records that none was named, never a model the turn may not have run on. * * Not the stored `models.default`, sent as an explicit option: the pipeline holds an * explicit model strictly to the catalog, so a default the provider dropped refused every * shortcode on the site while the chat screen, REST and the CLI kept answering. Not the * catalog's resolution either, because the catalog discovers over the network when it is * cold, and this runs for a visitor's view too, which must cost nothing. The cost, said in * the README: with no `model=` the page's answer runs on whichever model the editor who * primed it runs on, and changing the site's default model does not start a new answer. * Public for the shim, whose `model` attribute is the same attribute. */ public function authorModel(string $requested): string { if ($requested !== '' && (bool) $this->store->get('chat.user_can_change_model')) { return $requested; } return ''; } /** * The attributes, parsed: trimmed strings, `temperature` a float in the schema's range or * null when the attribute is absent or not a number (null is "the model's setting", never * 0), `format` one of the two the class knows (anything else is markdown, the path that * strips), `cache` in seconds. Through shortcode_atts(), so core's `shortcode_atts_alpacabot` * filter applies and an attribute the shortcode does not know is dropped. * * @param array|string $atts * @return array{prompt: string, model: string, system: string, temperature: float|null, format: string, cache: int} * @internal Public only so the tests can call it; not part of the plugin's API. */ public static function attributes(array|string $atts): array { $a = shortcode_atts(['prompt' => '', 'model' => '', 'system' => '', 'temperature' => '', 'format' => 'markdown', 'cache' => self::DEFAULT_CACHE], is_array($atts) ? $atts : [], self::TAG); $temperature = trim((string) $a['temperature']); return [ 'prompt' => trim((string) $a['prompt']), 'model' => trim((string) $a['model']), 'system' => trim((string) $a['system']), // min() over a float first: a numeric string past the float range is INF, and the range holds it. 'temperature' => is_numeric($temperature) ? max(0.0, min(2.0, (float) $temperature)) : null, 'format' => strtolower(trim((string) $a['format'])) === 'text' ? 'text' : 'markdown', 'cache' => self::cacheSeconds((string) $a['cache']), ]; } /** * A `cache` attribute in seconds: `off` is 0, a positive count with an optional unit * (`45s`, `30m`, `1h`, `2d`; bare is seconds) is that, held to a year, and anything else, * `0` and a blank included, is the default hour. The word is the only way off on purpose: * the cache is what keeps a page from generating on every view, and a value that is not a * duration is far more often a slip than a decision to spend on every view. * * The arithmetic is in floats and clamped before the cast: a digit run is the author's, * and one long enough overflows an int product to a float, which the int return type * would refuse with a TypeError, here, outside answer()'s try and before the capability * check, from any Contributor's attribute, for every visitor of the published page. * * @internal Public only so the tests and the shim can call it; not part of the plugin's API. */ public static function cacheSeconds(string $spec): int { $spec = strtolower(trim($spec)); if ($spec === 'off') { return 0; } if (preg_match('/^(\d+)\s*([smhd])?$/', $spec, $m) === 1 && (float) $m[1] > 0) { return (int) min((float) $m[1] * self::UNITS[$m[2] ?? 's'], (float) self::MAX_SECONDS); } return self::DEFAULT_SECONDS; } /** * The transient name for one shortcode's answer: the tag, the post, the identity and the * cache duration, hashed (a transient name is bounded at 172 characters and a prompt is * not). The post is part of it so two pages with the same shortcode are two entries; the * tag so the shim's `url` never collides with a prompt; the duration so two shortcodes that * differ only in `cache` are two entries, and the `off` one's per-request memo can never * stand in for the other's transient, or keep it from being written. * * @param array $identity * @internal Public only so the tests and the shim can call it; not part of the plugin's API. */ public static function cacheKey(string $tag, array $identity, int $postId, int $cacheSeconds): string { return self::TRANSIENT_PREFIX . md5((string) wp_json_encode([$tag, $postId, $identity, $cacheSeconds])); } /** * A notice in the page, escaped: the login or permission text, or why a turn failed. Its few * rules are enqueued with it, here and in the two other places that print the classes * (output() and the visitor's link in refused()), so the stylesheet rides with the markup * and nowhere else; the shell's markup does not use them. */ public function notice(string $text): string { $this->assets->enqueueShortcode(); return '

' . esc_html($text) . '

'; } /** * The notice for a generation that did not happen, with the reason in the words the REST * routes use: the cap, a refused model, the fixed provider message, or the minute's limit. */ private function failed(string $reason): string { /* translators: %s: the reason, in the words the REST routes use: the cap, a refused model, the rate limit, or the fixed provider message */ return $this->notice(sprintf(__('Alpaca Bot could not answer: %s', 'alpaca-bot'), $reason)); } /** The post the shortcode is being rendered in, or 0 outside a post (a widget, a template part). */ private static function postId(): int { $id = get_the_ID(); return is_int($id) && $id > 0 ? $id : 0; } /** * Whether this viewer may make the page spend: logged in, and past the Shortcodes row of * Settings › Access for the post and tag being rendered. The login check stays in front of * the row because `exist` is an honoured capability name and user_can(0, 'exist') is true; * a visitor must never trigger a generation, whatever a row or a filter says. */ private function viewerMayGenerate(int $postId, string $tag): bool { return is_user_logged_in() && $this->access->allows((int) get_current_user_id(), 'shortcode', $postId, $tag); } /** * What a viewer who may not generate sees: a login link for a visitor (back to this page), * and for a logged-in user the Shortcodes row does not admit, that the page is not for their * account, since a login link would send them round in a circle. */ private function refused(): string { if (is_user_logged_in()) { return $this->notice(__('Alpaca Bot does not answer here for your account.', 'alpaca-bot')); } $this->assets->enqueueShortcode(); $link = '' . esc_html__('Log in', 'alpaca-bot') . ''; /* translators: %s: a "Log in" link */ return '

' . sprintf(esc_html__('%s to see what Alpaca Bot answers here.', 'alpaca-bot'), $link) . '

'; } /** The text as the page shows it: markdown (raw HTML stripped, then kses) or escaped text with its line breaks. */ private function output(string $text, string $format): string { $this->assets->enqueueShortcode(); $inner = $format === 'text' ? '

' . nl2br(esc_html($text)) . '

' : $this->markdown->toHtml($text); return '
' . $inner . '
'; } /** * The chat screen on the page, as Admin\ChatScreen builds it, a new conversation and the * viewer's own history. Never inside a REST request, under the rule answer() applies to a * prompt: `content.rendered` is produced per item of a collection, and a shell is a history * query and a full markup build carrying the viewer's `wp_rest` nonce, which belongs in a * page they are looking at, not in a hundred items of a listing. */ private function shell(): string { if (!$this->viewerMayGenerate(self::postId(), self::TAG)) { return $this->refused(); } if (wp_is_rest_endpoint()) { return $this->notice(__('Alpaca Bot opens its chat here when the page is viewed on the site.', 'alpaca-bot')); } $userId = get_current_user_id(); $history = $this->conversations->listFor($userId, max(1, (int) $this->store->get('chat.history_limit'))); // The page itself is where "New chat" goes, and passing it is also what makes this the // front-end page's shell, `ab-wrap--front` (Shell's docblock). Without it the shell's // "New chat" link and the history select's matching option both carried admin_url(), so // a visitor of a front-end `[alpacabot]` page was navigated out of the site into // wp-admin. The permalink is the same URL refused() sends a visitor back to after logging // in; the home page stands in for a render with no post behind it, where there is no // permalink to return to. $home = (string) get_permalink(); $shell = new Shell($this->store, $this->catalog, null, $history, 0, null, $this->prefs->modelFor($userId, $this->catalog, $this->store), $home !== '' ? $home : home_url('/')); $this->assets->enqueueFront(); return $shell->render(); } }