{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "copilot-docs",
  "title": "Copilot",
  "description": "AI-powered text completion suggestions.",
  "files": [
    {
      "path": "../../content/docs/(plugins)/(ai)/copilot.mdx",
      "content": "---\ntitle: Copilot\ndescription: AI-powered text completion suggestions.\ndocs:\n  - route: https://pro.platejs.org/docs/examples/copilot\n    title: Plus\n  - route: /docs/components/ghost-text\n    title: Ghost Text\n---\n\n<ComponentPreview name=\"copilot-demo\" />\n\n<PackageInfo>\n\n## Features\n\n- Renders ghost text suggestions as you type\n- Two trigger modes:\n  - Shortcut (e.g. `Ctrl+Space`). Press again for alternative suggestions.\n  - Debounce mode: automatically triggers after a space at paragraph ends\n- Accept suggestions with Tab or word-by-word with `Cmd+→`\n- Built-in support for Vercel AI SDK completion API\n\n</PackageInfo>\n\n## Kit Usage\n\n<Steps>\n\n### Installation\n\nThe fastest way to add Copilot functionality is with the `CopilotKit`, which includes pre-configured `CopilotPlugin` along with `MarkdownKit` and their [Plate UI](/docs/installation/plate-ui) components.\n\n<ComponentSource name=\"copilot-kit\" />\n\n- [`GhostText`](/docs/components/ghost-text): Renders the ghost text suggestions.\n\n### Add Kit\n\n```tsx\nimport { createPlateEditor } from 'platejs/react';\nimport { CopilotKit } from '@/components/editor/plugins/copilot-kit';\n\nconst editor = createPlateEditor({\n  plugins: [\n    // ...otherPlugins,\n    ...CopilotKit,\n    // Place tab-using plugins after CopilotKit to avoid conflicts\n    // IndentPlugin,\n    // TabbablePlugin,\n  ],\n});\n```\n\n**Tab Key Handling**: The Copilot plugin uses the Tab key to accept suggestions. To avoid conflicts with other plugins that use Tab (like `IndentPlugin` or `TabbablePlugin`), ensure `CopilotKit` is placed before them in your plugin configuration.\n\n### Add API Route\n\nCopilot requires a server-side API endpoint to communicate with the AI model. Add the pre-configured Copilot API route:\n\n<ComponentSource name=\"copilot-api\" />\n\n### Configure Environment\n\nEnsure your AI Gateway key is set in your environment variables:\n\n```bash title=\".env.local\"\nAI_GATEWAY_API_KEY=\"your-api-key\"\n```\n\n</Steps>\n\n## Manual Usage\n\n<Steps>\n\n### Installation\n\n```bash\nnpm install @platejs/ai @platejs/markdown\n```\n\n### Add Plugins\n\n```tsx\nimport { CopilotPlugin } from '@platejs/ai/react';\nimport { MarkdownPlugin } from '@platejs/markdown';\nimport { createPlateEditor } from 'platejs/react';\n\nconst editor = createPlateEditor({\n  plugins: [\n    // ...otherPlugins,\n    MarkdownPlugin,\n    CopilotPlugin,\n    // Place tab-using plugins after CopilotPlugin to avoid conflicts\n    // IndentPlugin,\n    // TabbablePlugin,\n  ],\n});\n```\n\n- `MarkdownPlugin`: Required for serializing editor content to send as a prompt.\n- `CopilotPlugin`: Enables AI-powered text completion.\n\n**Tab Key Handling**: The Copilot plugin uses the Tab key to accept suggestions. To avoid conflicts with other plugins that use Tab (like `IndentPlugin` or `TabbablePlugin`), ensure `CopilotPlugin` is placed before them in your plugin configuration.\n\n### Configure Plugins\n\n```tsx\nimport { CopilotPlugin } from '@platejs/ai/react';\nimport { serializeMd, stripMarkdown } from '@platejs/markdown';\nimport { GhostText } from '@/components/ui/ghost-text';\n\nconst plugins = [\n  // ...otherPlugins,\n  MarkdownPlugin.configure({\n    options: {\n      remarkPlugins: [remarkMath, remarkGfm, remarkMdx],\n    },\n  }),\n  CopilotPlugin.configure(({ api }) => ({\n    options: {\n      completeOptions: {\n        api: '/api/ai/copilot',\n        onError: () => {\n          // Mock the API response. Remove when you implement the route /api/ai/copilot\n          api.copilot.setBlockSuggestion({\n            text: stripMarkdown('This is a mock suggestion.'),\n          });\n        },\n        onFinish: (_, completion) => {\n          if (completion === '0') return;\n\n          api.copilot.setBlockSuggestion({\n            text: stripMarkdown(completion),\n          });\n        },\n      },\n      debounceDelay: 500,\n      renderGhostText: GhostText,\n    },\n    shortcuts: {\n      accept: { keys: 'tab' },\n      acceptNextWord: { keys: 'mod+right' },\n      reject: { keys: 'escape' },\n      triggerSuggestion: { keys: 'ctrl+space' },\n    },\n  })),\n];\n```\n\n- `completeOptions`: Configures the Vercel AI SDK `useCompletion` hook.\n  - `api`: The endpoint for your AI completion route.\n  - `onError`: A callback for handling errors (used for mocking during development).\n  - `onFinish`: A callback to handle the completed suggestion. Here, it sets the suggestion in the editor.\n- `debounceDelay`: The delay in milliseconds for auto-triggering suggestions after the user stops typing.\n- `renderGhostText`: The React component used to display the suggestion inline.\n- `shortcuts`: Defines keyboard shortcuts for interacting with Copilot suggestions.\n\n### Add API Route\n\nCreate an API route handler at `app/api/ai/copilot/route.ts` to process AI requests. This endpoint will receive the prompt from the editor and call the AI model.\n\n```tsx title=\"app/api/ai/copilot/route.ts\"\nimport type { NextRequest } from 'next/server';\n\nimport { createGateway, generateText } from 'ai';\nimport { NextResponse } from 'next/server';\n\nexport async function POST(req: NextRequest) {\n  const {\n    apiKey: key,\n    instructions,\n    model = 'gpt-4o-mini',\n    prompt,\n  } = await req.json();\n\n  const apiKey = key || process.env.AI_GATEWAY_API_KEY;\n\n  if (!apiKey) {\n    return NextResponse.json(\n      { error: 'Missing AI Gateway API key.' },\n      { status: 401 }\n    );\n  }\n\n  const gateway = createGateway({ apiKey });\n\n  try {\n    const result = await generateText({\n      abortSignal: req.signal,\n      instructions,\n      maxOutputTokens: 50,\n      model: gateway(`openai/${model}`),\n      prompt,\n      temperature: 0.7,\n    });\n\n    return NextResponse.json(result);\n  } catch (error) {\n    if (error instanceof Error && error.name === 'AbortError') {\n      return NextResponse.json(null, { status: 408 });\n    }\n\n    return NextResponse.json(\n      { error: 'Failed to process AI request' },\n      { status: 500 }\n    );\n  }\n}\n```\n\nThen, set your `AI_GATEWAY_API_KEY` in `.env.local`.\n\n### Instructions\n\nInstructions define the AI's role and behavior. Modify the `body.instructions` property in `completeOptions`:\n\n```tsx\nCopilotPlugin.configure(({ api }) => ({\n  options: {\n    completeOptions: {\n      api: '/api/ai/copilot',\n      body: {\n        instructions: `You are an advanced AI writing assistant, similar to VSCode Copilot but for general text. Your task is to predict and generate the next part of the text based on the given context.\n\nRules:\n- Continue the text naturally up to the next punctuation mark (., ,, ;, :, ?, or !).\n- Maintain style and tone. Don't repeat given text.\n- For unclear context, provide the most likely continuation.\n- Handle code snippets, lists, or structured text if needed.\n- Don't include \"\"\" in your response.\n- CRITICAL: Always end with a punctuation mark.\n- CRITICAL: Avoid starting a new block. Do not use block formatting like >, #, 1., 2., -, etc. The suggestion should continue in the same block as the context.\n- If no context is provided or you can't generate a continuation, return \"0\" without explanation.`,\n      },\n      // ... other options\n    },\n    // ... other plugin options\n  },\n})),\n```\n\n### User Prompt\n\nThe user prompt (via `getPrompt`) determines what context is sent to the AI. You can customize it to include more context or format it differently:\n\n```tsx\nCopilotPlugin.configure(({ api }) => ({\n  options: {\n    getPrompt: ({ editor }) => {\n        const contextEntry = editor.api.block({ highest: true });\n\n        if (!contextEntry) return '';\n\n        const prompt = serializeMd(editor, {\n          value: [contextEntry[0] as TElement],\n        });\n\n        return `Continue the text up to the next punctuation mark:\n\"\"\"\n${prompt}\n\"\"\"`;\n      },\n    // ... other options\n  },\n})),\n```\n\n</Steps>\n\n\n\n## Plate Plus\n\n<ComponentPreviewPro name=\"copilot-pro\" />\n\n## Customization\n\n### Switching AI Models\n\nConfigure different AI models and providers in your API route:\n\n```tsx title=\"app/api/ai/copilot/route.ts\"\nimport { createGateway, generateText } from 'ai';\n\nexport async function POST(req: NextRequest) {\n  const {\n    instructions,\n    model = 'openai/gpt-4o-mini',\n    prompt,\n  } = await req.json();\n\n  const gateway = createGateway({ apiKey: process.env.AI_GATEWAY_API_KEY });\n\n  const result = await generateText({\n    instructions,\n    maxOutputTokens: 50,\n    model: gateway(model),\n    prompt,\n    temperature: 0.7,\n  });\n\n  return NextResponse.json(result);\n}\n```\n\nConfigure the model in your `CopilotPlugin`:\n\n```tsx\nCopilotPlugin.configure(({ api }) => ({\n  options: {\n    completeOptions: {\n      api: '/api/ai/copilot',\n      body: {\n        instructions: 'Continue the current paragraph in the same tone.',\n        model: 'anthropic/claude-3-haiku-20240307',\n      },\n    },\n    // ... other options\n  },\n})),\n```\n\nFor more AI providers and models, see the [Vercel AI SDK documentation](https://sdk.vercel.ai/providers/ai-sdk-providers).\n\n### Custom Trigger Conditions\n\nControl when suggestions are automatically triggered:\n\n```tsx\nCopilotPlugin.configure(({ api }) => ({\n  options: {\n    triggerQuery: ({ editor }) => {\n      // Only trigger in paragraph blocks\n      const block = editor.api.block();\n      if (!block || block[0].type !== 'p') return false;\n      \n      // Standard checks\n      return editor.selection && \n             !editor.api.isExpanded() && \n             editor.api.isAtEnd();\n    },\n    autoTriggerQuery: ({ editor }) => {\n      // Custom conditions for auto-triggering\n      const block = editor.api.block();\n      if (!block) return false;\n      \n      const text = editor.api.string(block[0]);\n      \n      // Trigger after question words\n      return /\\b(what|how|why|when|where)\\s*$/i.test(text);\n    },\n    // ... other options\n  },\n})),\n```\n\n### Security Considerations\n\nImplement security best practices for Copilot API:\n\n```tsx title=\"app/api/ai/copilot/route.ts\"\nexport async function POST(req: NextRequest) {\n  const { instructions, prompt } = await req.json();\n\n  // Validate prompt length\n  if (!prompt || prompt.length > 1000) {\n    return NextResponse.json({ error: 'Invalid prompt' }, { status: 400 });\n  }\n\n  // Rate limiting (implement with your preferred solution)\n  // await rateLimit(req);\n\n  // Content filtering for sensitive content\n  if (containsSensitiveContent(prompt)) {\n    return NextResponse.json({ error: 'Content filtered' }, { status: 400 });\n  }\n\n  // Process AI request...\n}\n```\n\n**Security Guidelines:**\n- **Input Validation**: Limit prompt length and validate content\n- **Rate Limiting**: Prevent abuse with request limits\n- **Content Filtering**: Filter sensitive or inappropriate content\n- **API Key Security**: Never expose API keys client-side\n- **Timeout Handling**: Handle request timeouts gracefully\n\n## Plugins\n\n### `CopilotPlugin`\n\nPlugin for AI-powered text completion suggestions.\n\n<API name=\"CopilotPlugin\">\n<APIOptions>\n  <APIItem name=\"autoTriggerQuery\" type=\"(options: { editor: PlateEditor }) => boolean\" optional>\n    Additional conditions to auto trigger copilot.\n    - **Default:** Checks:\n      - Block above is not empty\n      - Block above ends with a space\n      - No existing suggestion\n  </APIItem>\n  <APIItem name=\"completeOptions\" type=\"Partial<CompleteOptions>\">\n    AI completion configuration options. See [AI SDK useCompletion Parameters](https://sdk.vercel.ai/docs/reference/ai-sdk-ui/use-completion#parameters).\n  </APIItem>\n  <APIItem name=\"debounceDelay\" type=\"number\" optional>\n    Delay for debouncing auto-triggered suggestions.\n    - **Default:** `0`\n  </APIItem>\n  <APIItem name=\"getNextWord\" type=\"(options: { text: string }) => { firstWord: string; remainingText: string }\" optional>\n    Function to extract the next word from suggestion text.\n  </APIItem>\n  <APIItem name=\"getPrompt\" type=\"(options: { editor: PlateEditor }) => string\" optional>\n    Function to generate the prompt for AI completion.\n    - **Default:** Uses markdown serialization of ancestor node\n  </APIItem>\n  <APIItem name=\"renderGhostText\" type=\"(() => React.ReactNode) | null\" optional>\n    Component to render ghost text suggestions.\n  </APIItem>\n  <APIItem name=\"triggerQuery\" type=\"(options: { editor: PlateEditor }) => boolean\" optional>\n    Conditions to trigger copilot.\n    - **Default:** Checks:\n      - Selection is not expanded\n      - Selection is at block end\n  </APIItem>\n</APIOptions>\n</API>\n\n## Transforms\n\n### `tf.copilot.accept()`\n\nAccepts the current suggestion and applies it to the editor content.\n\nDefault Shortcut: `Tab`\n\n### `tf.copilot.acceptNextWord()`\n\nAccepts only the next word of the current suggestion, allowing for granular acceptance of suggestions.\n\nExample Shortcut: `Cmd + →`\n\n## API\n\n### `api.copilot.reject()`\n\nResets the plugin state to its initial condition:\nDefault Shortcut: `Escape`\n\n### `api.copilot.triggerSuggestion()`\n\nTriggers a new suggestion request. The request may be debounced based on the plugin configuration.\n\nExample Shortcut: `Ctrl + Space`\n\n### `api.copilot.setBlockSuggestion()`\n\nSets suggestion text for a block.\n\n<API name=\"setBlockSuggestion\">\n<APIParameters>\n  <APIItem name=\"options\" type=\"SetBlockSuggestionOptions\">\n    Options for setting the block suggestion.\n  </APIItem>\n</APIParameters>\n\n<APIOptions type=\"SetBlockSuggestionOptions\">\n  <APIItem name=\"text\" type=\"string\">\n    The suggestion text to set.\n  </APIItem>\n  <APIItem name=\"id\" type=\"string\" optional>\n    Target block ID.\n    - **Default:** Current block\n  </APIItem>\n</APIOptions>\n</API>\n\n### `api.copilot.stop()`\n\nStops ongoing suggestion requests and cleans up:\n\n- Cancels debounced trigger calls\n- Aborts current API request\n- Resets abort controller\n",
      "type": "registry:file",
      "target": "content/docs/plate/(plugins)/(ai)/copilot.mdx"
    }
  ],
  "type": "registry:file"
}