# Agents

AI Agents are autonomous assistants that work on tasks independently. Agents help you automate content management, application development, and browser-based workflows. For recurring or scheduled execution, use [Workflows](/docs/dashboard/ai/workflows) to run agents on a schedule.

**Access Requirements**: AI Agents are available to users with **Admin** or **Developer** bucket roles only. Editor and Contributor roles do not have access to these features.

**Where agents live**: Agents are project-scoped, so they are available across every bucket in the project. **Team Agents** have their own top-level section in the project sidebar (**Project > Team Agents**). **Content, Code, and Computer Use agents** are managed as **Automations** inside the project's **AI Studio**, alongside multi-step **Workflows**.

## Agent Types

Cosmic provides four specialized agent types, each designed for specific automation tasks:

### Team Agent

The Team Agent joins your communication channels as a fully conversational AI team member. Define a persona with a custom name, role, and personality. Set measurable goals and let the agent communicate with your team on Slack, WhatsApp, Telegram, and more. Team Agents can read and write CMS content, build and deploy applications, and manage connected GitHub repositories, all while carrying on natural conversations.

**Capabilities:**
- Multi-channel presence on Slack, WhatsApp, Telegram, API, Webhook, and Email
- Persona-driven conversations with custom name and personality
- Measurable goal tracking aligned with business objectives
- Scheduled heartbeats for proactive check-ins (Mon-Fri, daily, etc.)
- Lead qualification and customer support automation
- CMS read and write access for content-aware responses
- Code read and write access for connected GitHub repositories
- Runtime log analysis to diagnose production errors and create fixes
- Build and deploy full web applications from a conversation

**Example prompts:**
- "You are Lisa, our CMO. You are strategic, data-driven, and creative. Ask clarifying questions about target audience and goals before proposing campaigns."
- "You are Sam, our Customer Success Manager. Be warm and empathetic. Help customers get the most value from our product. Escalate bugs to engineering."

### Content Agent

The Content Agent works directly with your Cosmic CMS to create, update, and manage content at scale. It understands your existing content structure, researches topics via progressive web discovery, and generates perfectly formatted objects that match your schema.

**Capabilities:**
- Generate blog posts, landing pages, and product catalogs
- Create and modify object types with custom metafields
- Progressive web discovery for research-backed content
- Batch operations for bulk content creation
- Auto-publish or human review workflow
- Email notifications on task completion

**Example prompts:**
- "Research the latest AI trends from Hacker News and TechCrunch, then create a 5-part blog series covering each major development"
- "Create a complete product catalog for our new summer collection with 20 products, descriptions, and pricing"

### Code Agent

The Code Agent connects to your GitHub repository and writes production-ready code autonomously. It discovers relevant files, understands your codebase structure, creates feature branches, commits changes, and opens pull requests.

**Capabilities:**
- Progressive file discovery to understand codebases
- Automatic branch creation and PR submission
- Conflict detection and auto-resolution
- Multi-iteration development with checkpoints
- CMS integration for content-aware features
- Email notifications with commit summaries

**Example prompts:**
- "Build a user notification system with real-time updates, API endpoints, and React components with TypeScript"
- "Create a dynamic landing page that pulls content from our Cosmic CMS with hero section, feature grid, and testimonials"

### Computer Use Agent

The Computer Use Agent sees and controls browsers exactly like a human. It can fill out forms, record demo videos, download and upload media across platforms, and automate any workflow you can do manually.

**Capabilities:**
- Professional demo video recording with animated cursors
- Cross-platform media transfer and downloads
- AI-powered content extraction from web pages
- Visual navigation with stealth mode
- Screenshot and file operations
- Authenticated browser sessions with [Saved Authentications](/docs/dashboard/account#saved-authentications)

**Pre-Authentication:**

Computer Use Agents can start with pre-authenticated browser sessions, so they can access protected sites without manual login. Manage reusable credentials in your [Account settings > Saved Authentications](/docs/dashboard/account#saved-authentications), then select one or more from the agent's Pre-Authentication section. Saved Authentications persist across runs and can be shared between agents and workflows.

**Real-time input and unblocking:**

You can give a Computer Use Agent input while it is running, directly from the run detail page. This is useful when the agent hits something only you can resolve, or when you simply want to steer it.

- **When the agent asks**: If the agent runs into a blocker it cannot resolve on its own, such as a verification or 2FA code, a CAPTCHA, or an ambiguous choice, it pauses and shows a **Waiting for input** prompt with its question and a screenshot of the current screen. Type your response and the agent continues from where it left off.
- **Proactive steering**: While a run is in progress, you can send the agent input at any time using the **Send input to the agent** field, even if it did not ask. Your message is added to the conversation and taken into account on the next step.
- **Email notice**: When the agent pauses for input, an email is sent to you with the agent's question and a link to the run, as long as Email Notifications are enabled for the agent. This way you do not have to keep the run open to know it needs you.
- The browser session stays open while the agent waits, so no progress is lost. If no input is provided within 15 minutes, the run stops automatically.

**Execution Limits:**
- Each Computer Use Agent execution is limited to **100 steps** (actions) by default
- This limit helps prevent runaway costs and ensures efficient task completion
- The agent automatically stops when the goal is achieved, typically well before reaching the limit
- If your task doesn't complete within 100 steps, consider breaking it into smaller, more focused tasks

**Example prompts:**
- "Record a 2-minute demo video of our new dashboard feature, navigate through the analytics section, and export a report"
- "Download our top-performing video from TikTok, then upload it to YouTube Shorts and Instagram Reels with optimized captions"

## Creating an Agent

Team Agents and Automations are created in separate places in the project sidebar.

**To create a Team Agent:**

1. Open your project and click **Team Agents** in the project sidebar
2. Click **"Create Team Agent"**
3. Give the agent a name, persona, and prompt, then configure channels (Slack, WhatsApp, Telegram, Email, API, Webhook) and capabilities
4. (Optional) Enable a heartbeat schedule for proactive check-ins

**To create a Content, Code, or Computer Use automation:**

1. Open your project and click **AI Studio** in the project sidebar, then choose **Automations**
2. Click **"Create Automation"**
3. Choose your agent type (Content, Code, or Computer Use)
4. Describe the task you want the automation to complete
5. (Optional) For content automations, enable Progressive Discovery to crawl web content
6. (Optional) Set a schedule or an event trigger so the automation runs automatically

**Tip**: From any bucket you can also jump into **AI Studio > Create with AI** to describe what you want in natural language, and Cosmic will help scaffold the right agent or automation for you.

**Note**: Content, Code, and Computer Use automations can run on a recurring schedule or be chained inside [Workflows](/docs/dashboard/ai/workflows). Team Agents support heartbeat schedules directly from the Team Agent form for proactive check-ins.

## Event Triggers

Agents can be triggered automatically when content events occur. When enabled, your agent runs automatically whenever selected events happen on matching object types.

**Available Events:**
- **Object Created**: Triggers when a new object is added
- **Object Edited**: Triggers when an existing object is modified
- **Object Deleted**: Triggers when an object is removed
- **Object Published**: Triggers when an object's status changes to published
- **Object Unpublished**: Triggers when a published object is unpublished

**Event Context Data:**

When an event triggers your agent, the following data is automatically included in the prompt context:
- **Event Type**: The action that triggered the agent (created, edited, published, etc.)
- **Object Type**: The content type that was affected
- **Object ID**: The unique identifier of the object
- **Object Title**: The title of the triggered object
- **Object Slug**: The slug of the triggered object
- **Object Status**: Current status (draft, published, etc.)
- **Object Metadata**: All field values from the object

**Using Event Data for Conditional Logic:**

You can reference this event data in your prompt to implement conditional behavior:
```
If the object status is "draft", generate SEO metadata for the content.
If the object is already "published", complete early without changes.
If the object type is "blog-posts" and the title contains "urgent",
prioritize this task and notify the team.

```
**Example Use Cases:**
- Auto-generate social media posts when a blog is published
- Create translations when new content is added
- Update related content when a product price changes
- Send notifications based on specific field values

## Team Agent Configuration

Team Agents are conversational by default. They receive messages and respond through multiple channels, maintain conversation context, use tools to interact with your CMS and external services, and support both real-time chat and automated scheduled messaging. When you create a Team Agent, channels, capabilities, and memory settings are available directly in the agent form.

Just ask your agent "What can you do?" and it will tell you exactly which capabilities are enabled and what tools it has access to. This is the fastest way to understand what your agent can help with.

### Channels

Channels determine how messages reach your agent. You can enable multiple channels simultaneously.

- **REST API**: Send messages to your agent programmatically using a [Personal Access Token](/docs/dashboard/account#api-tokens). After creating a Team Agent, the endpoint URL is shown on the agent detail page. Create a token at [Account Settings > API Tokens](https://app.cosmicjs.com/account/api-tokens), then authenticate requests with it:
```bash
curl -X POST https://dapi.cosmicjs.com/v3/ai/agents/AGENT_ID/messages \
  -H "Authorization: Bearer cos_YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"message": "Hello, agent!"}'

```
Use this for custom integrations, scripts, or any application that needs to communicate with your agent programmatically.

- **Inbound Webhook**: Receive messages from external systems without Cosmic authentication. When enabled, a webhook endpoint and secret are shown on the agent detail page. Use the **Reveal** button to view the secret and **Copy** to copy it.

Authenticate webhook requests using one of these methods:

| Method | How to use |
|---|---|
| Query parameter | `?secret=YOUR_WEBHOOK_SECRET` |
| Header | `X-Webhook-Secret: YOUR_WEBHOOK_SECRET` |
| Header (alternate) | `X-Cosmic-Webhook-Secret: YOUR_WEBHOOK_SECRET` |
| HMAC signature | `X-Webhook-Signature: sha256=HMAC_HEX` (HMAC-SHA256 of the raw request body using the secret as the key) |
```bash
curl -X POST https://dapi.cosmicjs.com/v3/ai/agents/AGENT_ID/webhook?secret=YOUR_WEBHOOK_SECRET \
  -H "Content-Type: application/json" \
  -d '{"message": "New deployment completed successfully"}'

```
The request body should include a `message` field (string, required). Optional fields: `conversation_id` (to continue an existing conversation) and `metadata` (object, passed to the agent as context). If a webhook secret is compromised, click **Regenerate** on the agent detail page to generate a new secret. The old secret stops working immediately. Use this for third-party integrations like Zapier, GitHub Actions, or any automation platform.

- **Slack**: Chat with your agent directly in a Slack channel. Requires the Slack integration to be configured in your Bucket Settings > Integrations (see [Setting up Slack](#setting-up-slack)). Once connected, select a Slack channel and your agent will respond to messages there. The agent can see recent channel history (up to 50 messages), so it has full context of the team conversation when responding. For thread replies, the agent sees the full thread context. Enable **"Only respond when @mentioned"** to limit the agent to only replying when explicitly tagged with `@Cosmic Agent`. When this option is on, the agent still sees the full channel conversation but only responds to @mentions. Supports [conversation commands](#conversation-commands) like `/reset` and `/tokens`.

- **Telegram**: Chat with your agent through a Telegram bot. Set up the bot token in your Bucket Settings > Integrations (see [Setting up Telegram](#setting-up-telegram)), then generate a connect code in the agent edit page and send `/connect ` to the bot in your Telegram chat to link the agent. Supports [conversation commands](#conversation-commands) like `/reset` and `/tokens`.

- **WhatsApp**: Chat with your agent on WhatsApp. Cosmic supports two modes: a **shared number** hosted by Cosmic (quick start), or **Bring Your Own Number (BYON)** where you connect your own WhatsApp Business number for full control. Enable WhatsApp on your agent, generate a connect code, and tap the "Open WhatsApp" link to send the activation code. Once paired, any message from that phone number is routed to the agent. See [Setting up WhatsApp](#setting-up-whatsapp) for configuration details. Supports [conversation commands](#conversation-commands) like `/reset` and `/tokens`.

- **Email**: Receive and respond to messages via email. When enabled, the agent can participate in email-based conversations with your team or customers.

### Capabilities

Capabilities control what your agent can do when processing messages. Enable only the capabilities your agent needs. Each capability unlocks a set of tools that the agent can call autonomously.

#### CMS Read

Query and read objects, object types, and media from your bucket.

**Tools:**

- **get_objects**: Fetch objects from the CMS, filtered by object type, search query, with pagination. Parameters: `type`, `query`, `limit`, `skip`, `props`
- **get_object_types**: List all content models (object types) in the bucket and their metafield schemas
- **get_media**: Fetch media files from the media library with optional search and pagination. Parameters: `limit`, `skip`, `query`

**Example prompts:**
- "List all published blog posts"
- "Show me the schema for the products object type"
- "Find media files with 'hero' in the name"

#### CMS Write

Create, update, and delete objects and object types in your bucket. Also includes AI image generation and media uploads.

**Tools:**

- **create_object_type**: Create a new content model with metafield definitions. Parameters: `title`, `slug`, `singular`, `emoji`, `metafields`. Supports `show_when` on metafields for [conditional visibility](/docs/api/metafields#conditional-visibility)

- **update_object_type**: Update an existing content model (rename, add/remove metafields). Parameters: `type_slug`, `title`, `singular`, `emoji`, `metafields_to_add`, `metafields_to_remove`. Supports `show_when` on metafields for [conditional visibility](/docs/api/metafields#conditional-visibility)

- **create_object**: Create a new CMS object. Parameters: `type`, `title`, `slug`, `thumbnail`, `metadata`, `status`, `publish_at`, `unpublish_at`
- **update_object**: Edit an existing object by ID. Parameters: `id`, `title`, `slug`, `thumbnail`, `metadata`, `status`, `publish_at`, `unpublish_at`
- **delete_object**: Delete an object by ID. Parameters: `id`
- **batch_objects**: Create, update, or delete up to 25 objects in a single call. Each operation succeeds or fails independently. Parameters: `operations` (array of `{ method, type, id, title, metadata, status, ... }`)
- **generate_image**: Generate an AI image from a text description and upload it to the media library. Parameters: `prompt`, `size`, `aspect_ratio`
- **upload_media**: Upload a file from a public URL to the media library. Parameters: `url`, `name`, `folder`

**Example prompts:**
- "Create a new blog post about AI trends"
- "Generate a hero image for the homepage"
- "Upload the image from this URL to the media library"
- "Update the status of all draft posts to published"

#### Code Read

Read files and browse the directory structure of a connected GitHub repository. The agent can discover relevant files, understand your codebase structure, and search for specific content.

**Tools:**

- **list_repository_files**: List files and directories in the connected repo, filtered by an optional path prefix. Parameters: `path` (optional), `branch` (optional)
- **read_file**: Read the contents of a file from the repo. Parameters: `path` (required), `branch` (optional)
- **search_files**: Search for files by filename pattern (e.g. "*.tsx", "package.json"). Parameters: `pattern` (required), `path` (optional directory filter)
- **list_branches**: List all branches in the repo with their latest commit SHA and protection status
- **get_repository_info**: Get metadata about the connected repository including production URL, GitHub URL, framework, and Vercel project details
- **get_deployments**: List recent Vercel deployments with status, URLs, commit info, and timestamps. Parameters: `limit` (optional, default 5, max 20)
- **get_deployment_logs**: Get build and deployment logs for a specific Vercel deployment. Use `get_deployments` first to find the deployment ID, then use this tool to see the full build output including any errors. Parameters: `deployment_id` (required)
- **get_access_logs**: Get runtime access logs and function console output for a deployed Vercel project. Shows HTTP requests with status codes, paths, and methods, plus any `console.log`/`console.error` output from serverless functions. Useful for diagnosing production errors like 500s, 404s, or failed form submissions. Defaults to showing errors (status >= 400) from the last 24 hours. Parameters: `time_range` (optional: `1h`, `6h`, `24h`, `3d`), `status_filter` (optional: `errors`, `client_errors`, `server_errors`, `all`), `method` (optional), `path` (optional, supports regex), `limit` (optional, default 50, max 100)

**Example prompts:**
- "Show me the contents of src/index.ts"
- "List all files in the components directory"
- "Search for files that - "Fix the bug in the header component and open a PR"
- "Merge pull request #42 using squash"

- "Set the GMAIL_CLIENT_ID and GMAIL_CLIENT_SECRET env vars on the gmail-utils repo"
- "Build me a blog app with posts, categories, and an author page"
- "Check the status of my app build"
- "Deploy the app we just built"

#### Web Browse

Fetch and read content from web page URLs. The agent can research information, read linked articles, and gather context from the web.

**Tools:**

- **fetch_url**: Fetch and read web page content (HTML stripped to text). Parameters: `url`

**Example prompts:**
- "Read the content of https://example.com/blog/ai-trends"
- "Summarize the article at this URL"

#### API Requests

Make HTTP requests to any external REST API or service. Supports all standard HTTP methods (GET, POST, PUT, PATCH, DELETE) with custom headers for authentication. Use this to integrate with third-party services like Zapier, Shopify, Stripe, Gmail API, or any REST endpoint. All requests must use HTTPS.

**Secrets** allow you to store sensitive values like API keys and tokens securely. Values are encrypted at rest using AES-256-GCM and never exposed in conversations or logs. You can manage secrets from the agent form UI or let the agent manage them conversationally. Reference a secret in any endpoint URL or header value using the template syntax ``. The template is resolved server-side at runtime, so raw credentials are never sent to the model.

**API Endpoints** let you save reusable endpoint configurations (URL, method, headers, body template) so the agent can call them by name instead of rebuilding requests from scratch. Endpoints can reference secrets in their headers and URLs.

**Tools:**

- **api_request**: Make an HTTP request to an external API. Parameters: `url` (required, HTTPS only), `method` (required: GET/POST/PUT/PATCH/DELETE), `headers` (optional), `body` (optional JSON for POST/PUT/PATCH). Secret references (``) in URLs and headers are resolved automatically before the request is sent.
- **manage_api_endpoints**: Save, update, list, and remove reusable API endpoint configurations. Actions: `list`, `add`, `update`, `remove`. When adding or updating, the agent can include `` references in headers and URLs.
- **manage_secrets**: Securely store, list, and remove API keys and tokens. Actions: `list` (returns names and IDs only, never raw values), `add` (encrypts and stores a new secret), `remove` (deletes a secret, with a warning if referenced by any saved endpoints).

**Example prompts:**
- "Save my Stripe API key as a secret, then add an endpoint for listing customers"
- "POST the updated product data to the Shopify API"
- "GET the latest orders from the Stripe API and summarize them"
- "Send a trigger to my Zapier webhook with the new content data"
- "List my saved secrets and endpoints"

#### Send Notifications

Send messages to project members via email, Slack, Telegram, or WhatsApp. Email recipients are restricted to confirmed project members for security. Slack, Telegram, and WhatsApp require the respective integration to be connected in Project Settings > Integrations.

**Tools:**

- **send_email**: Send an email to project members. Use `to: "owner"` for the project owner, `to: "team"` for all members, or a specific project member email address. Parameters: `to`, `subject`, `body`
- **send_slack_message**: Post a message to a Slack channel. Uses the agent's configured Slack channel by default. Parameters: `message`, `channel_id` (optional), `blocks` (optional Block Kit JSON)
- **send_telegram_message**: Send a message to a Telegram chat. Uses the agent's configured Telegram chat by default. Parameters: `message`, `chat_id` (optional)
- **send_whatsapp_message**: Send a message to a WhatsApp user. Uses the agent's connected WhatsApp phone number by default. Parameters: `message`, `phone_number` (optional)

**Example prompts:**
- "Email the team that the content migration is complete"
- "Post a summary of today's published articles to the Slack channel"
- "Send a Telegram alert that the scheduled workflow finished"
- "Send a WhatsApp message to let them know the order shipped"

#### Agent Delegate

Hand off tasks to other agents in the same project. Useful for orchestrating specialized agents where one agent coordinates work across others.

**Tools:**

- **message_agent**: Send a message to another agent and receive its response. Parameters: `agent_id`, `message`

**Example prompts:**
- "Ask the content-writer agent to draft a blog post about this topic"
- "Delegate the image generation to the media agent"

#### Agent Manage

Create, list, update, and delete agents and workflows in the project. Allows agents to self-manage and orchestrate other agents programmatically.

**Tools:**

- **list_agents**: List all agents in the project with their IDs, names, types, and status
- **create_agent**: Create a new agent (content, repository, or computer_use type)
- **update_agent**: Update an agent's configuration (name, prompt, capabilities, schedule, status)
- **delete_agent**: Delete an agent and all its execution history
- **list_workflows**: List all workflows in the project
- **get_workflow**: Get a single workflow's full configuration, including all steps and their prompts
- **create_workflow**: Create a new multi-step workflow with ordered agent steps
- **update_workflow**: Update an existing workflow in place (name, steps, schedule, status) without changing its ID
- **delete_workflow**: Delete a workflow and its execution history

When building workflow steps, set `agent_type` to `content`, `repository`, `computer_use`, or `team`. A `team` step runs an existing team agent with its own capabilities and tools (including `api_request`); it requires `config.agent_id` set to that team agent's ID. Use this when a step needs the full team-agent toolset rather than the limited content/code/computer-use toolset.

**Example prompts:**
- "Create a new content agent called weekly-reporter"
- "List all agents in this project"
- "Pause the daily-digest agent"
- "Create a workflow that runs the content agent then the code agent"
- "Add a step to the orders workflow that runs my Hunter team agent to enrich the data"

#### Execute Workflows

Run workflows and check their execution status. Workflows are multi-step automated processes that chain agents together.

**Tools:**

- **execute_workflow**: Run a workflow by ID with optional trigger data. Parameters: `workflow_id`, `trigger_data`
- **get_workflow_status**: Check the status of a running workflow execution. Parameters: `execution_id`

**Example prompts:**
- "Run the content-pipeline workflow"
- "Check the status of the last workflow execution"

#### Always Available Tools

These tools are available to all Team Agents regardless of which capabilities are enabled:

- **send_message**: Send a formatted message to the current conversation channel
- **request_approval**: Pause execution and request human approval before proceeding with an action

### Conversation Memory

Memory controls how your agent retains conversation history.

- **Session**: Conversation history resets when the conversation ends. Best for stateless interactions.
- **Persistent**: Conversation history is maintained across sessions. The agent remembers previous interactions, which is useful for ongoing relationships with users or long-running tasks.

#### How conversations work under the hood

A conversation is a single thread of messages between a user and an agent on one channel (the dashboard, a Slack channel/thread, a Telegram chat, a WhatsApp number, an API session, etc.). Each turn carries the conversation forward, but the agent never sees the entire raw history at once. Instead, every turn is built from three layers:

1. **System context**: the agent's prompt, tool list, and AI Context content. This is the same on every turn and is cached so subsequent turns only pay for it once.
2. **Recent messages (verbatim)**: the most recent messages in the conversation are passed in word-for-word.
- **Solo agents**: last **30 messages** are kept in full.
- **Team agents** (those with connected_agents that can delegate via `message_agent`): last **15 messages** are kept in full. The smaller window leaves room for cross-agent context blocks without blowing the prompt budget.
3. **Compressed summary of older messages**: anything beyond the recent-message window is summarized into a single `[CONVERSATION SUMMARY - N earlier messages condensed]` block by Claude Haiku. The summary captures key decisions, tool calls and their outcomes, - "Every Monday, review all draft blog posts and suggest improvements"
- "Every hour, check for new support tickets and categorize them by priority"

## AI Context

AI Context gives your agent knowledge beyond its base prompt. When configured, the selected content is included in every conversation, allowing the agent to reference your actual data when responding.

You can include:
- **Object Types**: Specific content types and their schemas
- **Objects**: Individual content items and their field values
- **Media**: Media library items
- **Links**: URLs for web crawling and progressive discovery. The agent fetches and indexes linked pages to inform its responses.
- **Brand Guidelines**: Include your project's brand guidelines so the agent maintains a consistent voice and style across all generated content.
- **Reference Screenshots**: Screenshot URLs that give the agent visual reference for design-aware tasks.
- **MCP Servers**: Connect external [Model Context Protocol](https://modelcontextprotocol.io) servers to extend the agent's tool set with custom integrations.

This is configured through the AI Context modal when creating or editing an agent. Context helps agents give accurate, content-aware responses without users needing to describe the data in every message.

## Setting up Slack

1. Go to your **Bucket Settings > Integrations**
2. Click **Connect Slack** to start the OAuth flow
3. Authorize the Cosmic app in your Slack workspace
4. Once connected, create or edit a Team Agent
5. Toggle the **Slack** channel and select a channel from the dropdown
6. Optionally enable **"Only respond when @mentioned"** for busy channels

The agent will now respond to messages in the selected Slack channel. It sees up to 50 recent messages for context and has full thread awareness.

## Setting up Telegram

1. Create a Telegram bot via [BotFather](https://t.me/BotFather) and copy the bot token
2. Go to your **Bucket Settings > Integrations**
3. Paste the bot token and click **Connect**
4. Create a Team Agent and toggle the **Telegram** channel
5. Save the agent, then edit it to click **Generate Connect Code**
6. In your Telegram chat with the bot, send `/connect ` to link the agent

The agent will now respond to messages in that Telegram chat. Connect codes expire after 10 minutes.

## Setting up WhatsApp

Cosmic supports two WhatsApp modes:

**Option 1: Shared Number (Quick Start)**

Use Cosmic's hosted WhatsApp Business number. No Meta account required.

1. Create or edit a Team Agent
2. Toggle the **WhatsApp** channel
3. Save the agent, then edit it and click **Generate Connect Code**
4. Click **Open WhatsApp** to open a pre-filled message with the activation code
5. Send the message from your WhatsApp to pair your phone number with the agent

The agent will now respond to messages from that phone number. Connect codes expire after 10 minutes.

**Option 2: Bring Your Own Number (BYON)**

Connect your own WhatsApp Business number for full control and branding.

1. Create a WhatsApp Business App in the [Meta Developer Dashboard](https://developers.facebook.com/apps/)
2. Generate a System User access token with `whatsapp_business_messaging` permission
3. Go to your **Bucket Settings > Integrations**
4. Under WhatsApp, select **Bring Your Own Number** and enter your access token and phone number ID
5. Configure the webhook URL in your Meta App to point to the URL shown in Integrations
6. Create a Team Agent, toggle **WhatsApp**, and generate a connect code

With BYON, messages are sent from your own branded number and the integration is fully isolated to your project.

## Conversation commands

Team Agents support a small set of conversation commands in the Cosmic dashboard chat as well as on Slack, Telegram, and WhatsApp. Commands are nearly free: they are handled locally and never hit the agent's main model. `/reset` makes one short call to a small summarization model (Claude Haiku) to produce a handoff summary; the other commands don't call any model.

| Command | Aliases | What it does |
|---|---|---|
| `/reset` | `/new`, `/clear` | Ends the current conversation and starts a fresh one. A short handoff summary is generated from the closing conversation and carried into the next session as preloaded context, so the agent remembers what you were working on without paying for the full transcript. |
| `/reset --hard` | `/reset --wipe` | Same as `/reset`, but skips the handoff summary entirely. The next message starts with no memory of the previous session. Use this when you want a true clean slate. |
| `/tokens` | `/stats` | Shows the message count and token usage (input, output, total) for the current conversation. |
| `/help` | `/commands` | Lists the available commands. |

**Parser rules:**

- The entire message must be exactly the command (case-insensitive). `/reset` works; `/reset please` is treated as a normal message and passed to the agent.
- On Slack, commands work whether the bot is `@mentioned` or not; the mention is stripped before parsing.
- Commands are scoped to the current conversation. In the dashboard, that's the conversation you have open; on Slack, the channel or thread; on Telegram, the chat; on WhatsApp, the sender's phone number.

**When to use `/reset`:**

- The conversation has drifted and you want the agent to start fresh while keeping the high-level context.
- Token usage (visible via `/tokens`) is getting high and you want to reduce cost on the next turn without losing what you were working on.
- You are about to switch topics. Use `--hard` if you don't want any prior context bleeding in.

In the dashboard, after a soft `/reset` the chat pivots to the new conversation immediately: the message count and token counter reset to zero, and the `/reset` exchange (your command and the handoff summary) is persisted to the new session so it stays visible after a page refresh.

## Sharing conversations

Each conversation has its own shareable URL. When you switch between conversations in the rail (or start a new one), the dashboard reflects the active conversation in the address bar as `?conversation=`, for example:
```
https://app.cosmicjs.com/projects/PROJECT_ID/agents/AGENT_ID?conversation=CONVERSATION_ID

```
Copy that URL to share a direct link to the conversation with anyone who has access to the project. Refreshing the page or opening the link in a new tab loads the same conversation rather than the most recent one. Use `/reset` (or click "New chat") to switch to a fresh conversation and update the URL.

## Agent Messaging API Reference

### Send a message
```
POST /v3/ai/agents/:agentId/messages

```
**Authentication**: [Personal Access Token](/docs/dashboard/account#api-tokens) or session JWT via `Authorization: Bearer` header.

**Request body**:

| Field | Type | Required | Description |
|---|---|---|---|
| `message` | string | Yes | The message text |
| `conversation_id` | string | No | Continue an existing conversation |
| `channel_metadata` | object | No | Additional context passed to the agent |
| `model` | string | No | Override the agent's default AI model |
| `context` | object | No | Extra context for this message |
| `stream` | boolean | No | Set to `true` to receive a streaming SSE response instead of JSON |

**Example**:
```bash
curl -X POST https://dapi.cosmicjs.com/v3/ai/agents/AGENT_ID/messages \
  -H "Authorization: Bearer cos_YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"message": "Summarize our latest blog posts"}'

```
### Streaming

Pass `stream: true` in the request body to receive a streaming response via [Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) (`Content-Type: text/event-stream`). Each event is a `data:` line containing JSON.

**Example**:
```bash
curl -N -X POST https://dapi.cosmicjs.com/v3/ai/agents/AGENT_ID/messages \
  -H "Authorization: Bearer cos_YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"message": "Summarize our latest blog posts", "stream": true}'

```
**Event types**:

| Event type | Description |
|---|---|
| `info` | Sent immediately with `conversation_id` and `model` |
| `text_delta` | Incremental text chunk with `text` and accumulated `fullText` |
| `tool_progress` | Status label while the agent executes a tool |
| `done` | Final event with `conversation_id`, complete `message`, `tokens_used`, and `model` |
| `awaiting_approval` | Agent is waiting for approval, includes `pending_approval` details |
| `error` | An error occurred, includes `message` |

**Example event stream**:
```
data: {"type":"info","conversation_id":"abc123","model":"claude-opus-4-8"}

data: {"type":"text_delta","text":"Here","fullText":"Here"}

data: {"type":"text_delta","text":" are","fullText":"Here are"}

data: {"type":"tool_progress","label":"Fetching content..."}

data: {"type":"text_delta","text":"The latest","fullText":"The latest"}

data: {"type":"done","conversation_id":"abc123","message":"The latest posts cover...","tokens_used":1234,"model":"claude-opus-4-8"}

```
### Inbound webhook
```
POST /v3/ai/agents/:agentId/webhook

```
**Authentication**: Webhook secret (no Bearer token required). See [Inbound Webhook](#channels) for authentication methods.

**Request body**:

| Field | Type | Required | Description |
|---|---|---|---|
| `message` | string | Yes | The message text |
| `conversation_id` | string | No | Continue an existing conversation |
| `metadata` | object | No | Additional context passed to the agent |

### List conversations
```
GET /v3/ai/agents/:agentId/conversations

```
**Authentication**: Personal Access Token or session JWT.

### Get conversation history
```
GET /v3/ai/agents/:agentId/conversations/:conversationId

```
**Authentication**: Personal Access Token or session JWT.

## Key Features

- **Parallel Execution**: Run multiple agents simultaneously (limits based on your plan)
- **Branch Isolation**: Code agents work on separate Git branches to prevent conflicts
- **Progress Tracking**: Monitor commits, files changed, and real-time status updates
- **Email Notifications**: Receive updates when agents complete their work
- **Pull Request Management**: Agents can create PRs for code review before merging
- **Progressive Discovery**: Content agents can crawl web content to inform their work

## Plan Limits

**Plan-Based Limits** (varies by plan):
- **Free Plan**: 2 agents at a time
- **Paid Plans**: More agents based on your plan (check your plan details)

## Agent Limits by Plan

Agent, automation, and workflow limits are tracked in three separate pools and apply at the project level (for standalone projects) or workspace level (for workspace projects). Only `active` entities count toward each cap, so drafts, paused, archived, or deleted items free a slot. Workflow steps do not consume team agent or automation slots.

| Plan | Team agents | Automations | Workflows |
|---|---|---|---|
| Free | 1 | 2 (manual only) | 1 |
| Builder | 3 | 5 (with scheduling) | 3 |
| Team | 10 | 25 (with scheduling) | 10 |
| Business | 25 | 100 (with scheduling) | 50 |
| Small Workspace | 25 | 100 (with scheduling) | 50 |
| Large Workspace | 75 | 300 (with scheduling) | 150 |
| Enterprise | Custom | Custom | Custom |

- **Team Agents**: Persistent AI agents connected to channels like Slack, WhatsApp, or Telegram.
- **Automations**: Standalone agents (content, code, or computer use) that run on demand, on a schedule, or on content events.
- **Workflows**: Multi-step orchestrations that chain agents and logic.

**Note**: Scheduled execution is available through [Workflows](/docs/dashboard/ai/workflows) on paid plans.

## Progressive Discovery

Content Agents can use Progressive Discovery to crawl and analyze web content before generating or updating CMS content. This feature allows agents to:

- Research current trends and topics from specified websites
- Gather real-world examples and data
- Reference actual sources with accurate URLs
- Create content informed by the latest information

To use Progressive Discovery, enable it when creating a content agent and specify the URLs or topics you want the agent to explore.