'edit_posts', 'page' => 'edit_pages']; /** @param \Closure(): int $userId the acting user's id, resolved when the tool runs (see the class docblock) */ public function __construct(private \Closure $userId) {} public function tools(): array { return [new Tool( 'draft_post', 'Create a DRAFT post or page on this WordPress site for the user to review and publish themselves. It never publishes. Returns the draft\'s id and its edit link.', [ new StringParameter('title', 'The post title.'), new StringParameter('content', 'The post body, as HTML or Markdown.'), new EnumParameter('post_type', 'What to create: a blog post (the default) or a page.', ['post', 'page'], false), ], fn(array $args): ToolResult => $this->draft((string) $args['title'], (string) $args['content'], (string) ($args['post_type'] ?? 'post')), )]; } public function guidelines(): string { return 'When the user asks you to write, create, or draft content for the site, use draft_post so they can review it in the editor before it goes live. Tell them it is a draft and give them the edit link. Never claim something was published.'; } private function draft(string $title, string $content, string $type): ToolResult { $userId = ($this->userId)(); if ($userId < 1) { return ToolResult::error(__('Nobody is logged in, so there is no one to own the draft.', 'alpaca-bot')); } $capability = self::TYPES[$type] ?? null; if ($capability === null || !user_can($userId, $capability)) { return ToolResult::error(__('You cannot create this kind of content on this site.', 'alpaca-bot')); } $id = wp_insert_post(wp_slash([ 'post_type' => $type, 'post_status' => 'draft', 'post_author' => $userId, 'post_title' => sanitize_text_field($title), 'post_content' => wp_kses_post($content), ]), true); if (is_wp_error($id)) { /* translators: %s: WordPress's reason the post could not be created */ return ToolResult::error(sprintf(__('The draft could not be created: %s', 'alpaca-bot'), $id->get_error_message())); } return ToolResult::json([ 'id' => $id, 'status' => 'draft', 'post_type' => $type, 'edit_url' => (string) get_edit_post_link($id, 'raw'), ]); } }