exists = $exists === null ? function_exists(...) : \Closure::fromCallable($exists); } /** On `wp_abilities_api_categories_init`: the category the three abilities claim. */ public function registerCategory(): void { if (!($this->exists)('wp_register_ability_category')) { return; } wp_register_ability_category(self::CATEGORY, [ 'label' => __('Alpaca Bot', 'alpaca-bot'), 'description' => __('Chat with the site\'s model, summarize text, and draft posts through Alpaca Bot.', 'alpaca-bot'), ]); } /** * On `wp_abilities_api_init`: definitions() through filter `alpaca_bot/abilities` * (array>: id => the wp_register_ability() arguments), then * one wp_register_ability() per entry. The filter is where a site drops an ability it does * not want reachable, or adds one of its own under any namespace; an entry whose key is not * a string or whose value is not an array is dropped rather than handed to core, which * would refuse it with a notice. */ public function register(): void { if (!($this->exists)('wp_register_ability')) { return; } /** * Filters the abilities the plugin registers with the WordPress Abilities API, keyed by * ability id. Drop an entry to keep that ability off every surface the API feeds (WP-CLI, * MCP servers, other plugins) without touching the REST routes, or add one of your own * under any namespace. An entry whose key is not a string or whose value is not an array * is dropped before core sees it, which would otherwise refuse it with a notice. * * @since 0.5.0 * @param array> $abilities ability id => the wp_register_ability() arguments * @var mixed $filtered what the filter returned, checked before it is trusted */ $filtered = apply_filters('alpaca_bot/abilities', $this->definitions()); foreach (is_array($filtered) ? $filtered : [] as $id => $args) { if (is_string($id) && is_array($args)) { wp_register_ability($id, $args); } } } /** * The three abilities as wp_register_ability() takes them, by id. Pure: nothing is read * from WordPress or the settings until a callback runs. * * @return array> */ public function definitions(): array { return [ self::CHAT => $this->ability( __('Chat', 'alpaca-bot'), __('Send one message to the site\'s assistant and get its reply. Continues a conversation the caller owns when a conversation id is given, else starts one. Counts against the caller\'s monthly usage.', 'alpaca-bot'), [ 'message' => ['type' => 'string', 'minLength' => 1, 'description' => __('The message to send.', 'alpaca-bot')], 'conversation_id' => ['type' => 'integer', 'minimum' => 0, 'description' => __('A conversation of the caller\'s to continue; 0 or absent starts a new one.', 'alpaca-bot')], 'model' => ['type' => 'string', 'description' => __('A model to use for this turn, when the site lets users choose one.', 'alpaca-bot')], ], ['message'], [ 'conversation_id' => ['type' => 'integer', 'description' => __('The conversation the turn was stored in.', 'alpaca-bot')], 'reply' => ['type' => 'string', 'description' => __('The assistant\'s reply.', 'alpaca-bot')], 'receipt' => ['type' => 'object', 'description' => __('The usage receipt: model, tokens, duration.', 'alpaca-bot')], ], ['conversation_id', 'reply', 'receipt'], true, fn(mixed $input = null): bool => $this->canChat(), fn(mixed $input = null): array|\WP_Error => $this->chat(is_array($input) ? $input : []), ), self::SUMMARIZE => $this->ability( __('Summarize', 'alpaca-bot'), __('Condense a piece of text with the site\'s model. Neither the text nor the summary is stored; the tokens count against the caller\'s monthly usage.', 'alpaca-bot'), [ 'text' => ['type' => 'string', 'minLength' => 1, 'description' => __('The text to summarize.', 'alpaca-bot')], 'length' => ['type' => 'string', 'enum' => ['short', 'medium', 'long'], 'description' => __('How long the summary should be; medium is the default.', 'alpaca-bot')], ], ['text'], ['summary' => ['type' => 'string', 'description' => __('The summary.', 'alpaca-bot')]], ['summary'], false, fn(mixed $input = null): bool|\WP_Error => $this->can('edit_posts') ? $this->gate('summarize') : false, fn(mixed $input = null): array|\WP_Error => $this->summarize(is_array($input) ? $input : []), ), self::DRAFT_POST => $this->ability( __('Draft a post', 'alpaca-bot'), __('Create a draft post or page, authored by the caller, for review in the editor. It never publishes.', 'alpaca-bot'), [ 'title' => ['type' => 'string', 'description' => __('The post title.', 'alpaca-bot')], 'content' => ['type' => 'string', 'description' => __('The post body, as HTML or Markdown.', 'alpaca-bot')], 'post_type' => ['type' => 'string', 'enum' => array_keys(DraftPostToolkit::TYPES), 'description' => __('A post (the default) or a page.', 'alpaca-bot')], ], ['title', 'content'], [ 'id' => ['type' => 'integer', 'description' => __('The draft\'s post id.', 'alpaca-bot')], 'edit_url' => ['type' => 'string', 'description' => __('Where to review it in the editor.', 'alpaca-bot')], ], ['id', 'edit_url'], false, fn(mixed $input = null): bool|\WP_Error => $this->canDraft(is_array($input) ? $input : []), fn(mixed $input = null): array|\WP_Error => $this->draft(is_array($input) ? $input : []), ), ]; } /** * One definition in core's argument shape (WP_Ability::prepare_properties() is the list). * * @param array> $input the input properties * @param list $required which of them are required * @param array> $output the output properties * @param list $produced which of them are always there * @param bool $destructive the `destructive` annotation (the class docblock says why each is what it is) * @return array */ private function ability(string $label, string $description, array $input, array $required, array $output, array $produced, bool $destructive, \Closure $permission, \Closure $execute): array { return [ 'label' => $label, 'description' => $description, 'category' => self::CATEGORY, 'input_schema' => ['type' => 'object', 'properties' => $input, 'required' => $required, 'additionalProperties' => false], 'output_schema' => ['type' => 'object', 'properties' => $output, 'required' => $produced], 'permission_callback' => $permission, 'execute_callback' => $execute, 'meta' => [ 'show_in_rest' => true, 'public' => true, 'annotations' => ['readonly' => false, 'destructive' => $destructive, 'idempotent' => false], ], ]; } /** Whether the acting user, if there is one, holds `$capability`; '' (no capability named) is never held. */ private function can(string $capability): bool { $userId = ($this->userId)(); return $capability !== '' && $userId > 0 && user_can($userId, $capability); } /** * Whether the acting user may chat: `edit_posts`, and then the Chat row of Settings › Access * that the REST chat routes, the chat screen and the drawer ask, so an administrator who * narrows that row narrows this ability too (core's run route and every MCP adapter expose * it). Asked only once `edit_posts` is held, so the row can narrow who may call and cannot * widen it, as the tool rows do for summarize and draft-post. */ private function canChat(): bool { return $this->can('edit_posts') && ($this->access === null || $this->access->allows(($this->userId)(), 'chat')); } /** * Whether the acting user may create the requested post type: its own capability, and the * draft_post toolkit on. An unknown type is refused outright; the schema refuses it first. * * @param array $input */ private function canDraft(array $input): bool|\WP_Error { return $this->can(self::draftCapability($input)) ? $this->gate('draft_post') : false; } /** * The capability the requested post type asks for, from the map DraftPostToolkit enforces * itself; '' for a type it does not know, which can() never grants. * * @param array $input */ private static function draftCapability(array $input): string { return DraftPostToolkit::TYPES[(string) ($input['post_type'] ?? 'post')] ?? ''; } /** True while the toolkit `$id` is switched on for the acting user; else the refusal that names the switch. */ private function gate(string $id): true|\WP_Error { $toolkit = $this->toolkit($id); return $toolkit instanceof \WP_Error ? $toolkit : true; } /** * The toolkit under `$id` for the acting user, as Registry::enabled() hands it out (the * setting, the tool's Access row for this user, then the `alpaca_bot/toolkits` filter), or * the refusal that names both things an administrator can change. */ private function toolkit(string $id): ToolkitInterface|\WP_Error { $toolkit = $this->registry->enabled(($this->userId)())[$id] ?? null; if ($toolkit !== null) { return $toolkit; } return new \WP_Error( 'alpaca_bot_toolkit_disabled', /* translators: %s: the tool's id, e.g. summarize */ sprintf(__('The %s tool is not available to you: it is switched off on this site, or Settings › Access keeps it from your role. An administrator can change either under Alpaca Bot > Settings.', 'alpaca-bot'), $id), ['status' => 403], ); } /** * True while no turn is running in this request; else the refusal. Asked by the two * abilities that start a turn, before the limiter is hit, so a refused call costs nothing * (the class docblock says why the two). */ private function idle(): true|\WP_Error { return $this->pipeline->running() ? Errors::turnRunning() : true; } /** * One hit on the limiter the REST routes share, for the acting user, in their `chat` * bucket; the 429 when the minute is spent. */ private function limit(): true|\WP_Error { $hit = (new RateLimit())->hit(($this->userId)(), 'chat'); return $hit['allowed'] ? true : Errors::tooMany($hit['retry_after']); } /** * One stored turn as the acting user. The options are built from the named keys only, the * way Rest\ChatController::create() builds them. * * @param array $input * @return array{conversation_id: int, reply: string, receipt: array}|\WP_Error */ private function chat(array $input): array|\WP_Error { if (!$this->canChat()) { return Errors::forbidden(); } $idle = $this->idle(); if ($idle instanceof \WP_Error) { return $idle; } $limit = $this->limit(); if ($limit instanceof \WP_Error) { return $limit; } try { $result = $this->pipeline->complete(($this->userId)(), (string) ($input['message'] ?? ''), [ 'conversation_id' => max(0, (int) ($input['conversation_id'] ?? 0)), 'model' => sanitize_text_field((string) ($input['model'] ?? '')), ]); } catch (\Throwable $e) { return Errors::fromPipeline($e); } return ['conversation_id' => $result->conversation->id, 'reply' => $result->reply->content, 'receipt' => $result->receipt]; } /** * The summarize toolkit's own turn, called directly so a throw keeps its type (the class * docblock), or a swapped-in toolkit's `summarize` tool as the model runs it. The * capability and the switch are asked again here: the setting can change between the * permission check and the run, and a client that calls execute_callback without * check_permissions must still meet both. * * @param array $input * @return array{summary: string}|\WP_Error */ private function summarize(array $input): array|\WP_Error { if (!$this->can('edit_posts')) { return Errors::forbidden(); } $toolkit = $this->toolkit('summarize'); if ($toolkit instanceof \WP_Error) { return $toolkit; } $idle = $this->idle(); if ($idle instanceof \WP_Error) { return $idle; } $limit = $this->limit(); if ($limit instanceof \WP_Error) { return $limit; } $text = (string) ($input['text'] ?? ''); if ($toolkit instanceof SummarizeToolkit) { try { $result = $toolkit->summarize($text, (string) ($input['length'] ?? 'medium')); } catch (\Throwable $e) { return Errors::fromPipeline($e); } return ['summary' => $result->content]; } $args = ['text' => $text]; if (isset($input['length'])) { $args['length'] = (string) $input['length']; } $summary = self::run($toolkit, 'summarize', $args); return $summary instanceof \WP_Error ? $summary : ['summary' => $summary]; } /** * The draft_post tool as the model runs it, its JSON answer reduced to the two keys the * output schema promises. The post type's capability and the switch are asked again here, * as summarize() says. * * @param array $input * @return array{id: int, edit_url: string}|\WP_Error */ private function draft(array $input): array|\WP_Error { if (!$this->can(self::draftCapability($input))) { return Errors::forbidden(); } $toolkit = $this->toolkit('draft_post'); if ($toolkit instanceof \WP_Error) { return $toolkit; } $args = ['title' => (string) ($input['title'] ?? ''), 'content' => (string) ($input['content'] ?? '')]; if (isset($input['post_type'])) { $args['post_type'] = (string) $input['post_type']; } $content = self::run($toolkit, 'draft_post', $args); if ($content instanceof \WP_Error) { return $content; } $data = json_decode($content, true); $data = is_array($data) ? $data : []; return ['id' => (int) ($data['id'] ?? 0), 'edit_url' => (string) ($data['edit_url'] ?? '')]; } /** * The tool named `$name` in `$toolkit` (Registry::tool()) run with `$args`, as the model * runs it: its content on success, else its text refusal as `alpaca_bot_tool_error` (400), * or a 500 when the toolkit has no such tool. Only the arguments the tool's schema declares * are passed: php-agents 0.17 refuses undeclared ones, and a toolkit swapped in through * `alpaca_bot/toolkits` may not offer an optional one such as `length` or `post_type`. * * @param array $args */ private static function run(ToolkitInterface $toolkit, string $name, array $args): string|\WP_Error { $tool = Registry::tool($toolkit, $name); if ($tool === null) { /* translators: %s: the tool's id, e.g. draft_post */ return new \WP_Error('alpaca_bot_tool_error', sprintf(__('The %s tool is not available.', 'alpaca-bot'), $name), ['status' => 500]); } $declared = $tool->toFunctionSchema()['function']['parameters']['properties'] ?? []; $result = $tool->execute(array_intersect_key($args, is_array($declared) ? $declared : [])); if ($result->status !== ToolResultStatus::Success) { return new \WP_Error('alpaca_bot_tool_error', $result->content, ['status' => 400]); } return $result->content; } }