> ## Documentation Index
> Fetch the complete documentation index at: https://docs.zappway.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Agent Skills

> Extend your AI Employee with custom skills — reusable instructions and behavioral rules that shape how the agent responds, reasons, and acts across every conversation.

> **What you will learn:**
> This page explains how Agent Skills work, how to create and manage them, how to use Skill Packs to get started quickly, and how to use AI-assisted skill proposal to build a knowledge-driven skill library automatically.

***

## 🔢 Table of Contents

1. [Overview](#1-overview)
2. [Endpoint Reference](#2-endpoint-reference)
3. [Authentication & Permissions](#3-authentication--permissions)
4. [Skills — Create & Manage](#4-skills--create--manage)
5. [Skill Packs](#5-skill-packs)
6. [AI-Proposed Skills](#6-ai-proposed-skills)
7. [Skill Optimization](#7-skill-optimization)
8. [Agent Cortex Mode](#8-agent-cortex-mode)
9. [Agent Specialists](#9-agent-specialists)
10. [Response Format](#10-response-format)
11. [Error Handling](#11-error-handling)
12. [Best Practices](#12-best-practices)
13. [Troubleshooting](#13-troubleshooting)

***

## 1. Overview

### What are Agent Skills?

Agent Skills are **structured knowledge units** that teach your AI Employee how to behave in specific situations. Each skill contains:

* **Name** — A clear label (e.g., "Handle Refund Request")
* **Slug** — A machine-readable unique identifier (e.g., `handle-refund-request`)
* **Description** — When this skill should activate
* **Content** — The detailed instructions the AI follows when this skill applies
* **Status** — `draft`, `active`, or `archived`
* **Scope** — `agent` (single AI) or `organization` (shared across all AIs)

### Why Use Skills?

Without skills, your AI Employee relies only on its base instructions and knowledge base. Skills allow you to:

* Define specific behaviors for recurring situations
* Reuse knowledge across multiple AI Employees (organization scope)
* Enable the AI Cortex to automatically select the right skill at runtime
* Maintain and version your AI's behavioral logic independently from its prompt

### How Skills are Used at Runtime

When a conversation is in progress, the **Agent Cortex** (in `advisory` or `active` mode) reads all active skills and selects the most relevant one based on context. The selected skill's **content** is injected into the AI's context window as an additional instruction layer.

```
Incoming message
      ↓
Agent Cortex evaluates active skills
      ↓
Most relevant skill(s) selected
      ↓
Skill content injected into context
      ↓
AI generates response using skill instructions
```

***

## 2. Endpoint Reference

| Method  | Endpoint                                   | Description                                      | Auth          | Classification |
| ------- | ------------------------------------------ | ------------------------------------------------ | ------------- | -------------- |
| `GET`   | `/api/agents/[id]/skills`                  | List all skills for an agent (agent + org scope) | Session + Org | User-facing    |
| `POST`  | `/api/agents/[id]/skills`                  | Create a new skill for an agent                  | Session + Org | User-facing    |
| `PATCH` | `/api/agents/[id]/skills/[skillId]`        | Update an existing skill                         | Session + Org | User-facing    |
| `GET`   | `/api/agents/[id]/skills/packs`            | List available Skill Packs for an agent          | Session + Org | User-facing    |
| `POST`  | `/api/agents/[id]/skills/packs/apply`      | Apply a Skill Pack to an agent                   | Session + Org | User-facing    |
| `POST`  | `/api/agents/[id]/skills/propose`          | AI-propose skills based on agent configuration   | Session + Org | User-facing    |
| `POST`  | `/api/agents/[id]/skills/propose-from-rag` | AI-propose skills from connected knowledge base  | Session + Org | User-facing    |
| `POST`  | `/api/agents/[id]/skills/optimize`         | Generate optimization approval suggestions       | Session + Org | User-facing    |
| `GET`   | `/api/agents/[id]/skills/cortex-mode`      | Get current Agent Cortex mode                    | Session + Org | User-facing    |
| `PATCH` | `/api/agents/[id]/skills/cortex-mode`      | Update Agent Cortex mode                         | Session + Org | User-facing    |
| `GET`   | `/api/agents/[id]/specialists`             | List specialist sub-agents linked to this agent  | Session + Org | User-facing    |
| `POST`  | `/api/agents/[id]/specialists`             | Activate/deactivate a specialist routing rule    | Session + Org | User-facing    |
| `PUT`   | `/api/agents/[id]/specialists`             | Link a new specialist (sub-agent)                | Session + Org | User-facing    |

***

## 3. Authentication & Permissions

All endpoints require an active **session cookie** tied to an authenticated user who belongs to the organization owning the agent.

| Permission                              | Endpoints                            |
| --------------------------------------- | ------------------------------------ |
| `agent_skills.read` OR `agents.read`    | All `GET` endpoints                  |
| `agent_skills.manage` OR `agents.write` | All `POST`, `PATCH`, `PUT` endpoints |

> The system verifies that `agentId` belongs to the authenticated user's current organization (`assertAgentBelongsToOrganization`) before any operation.

***

## 4. Skills — Create & Manage

### List Skills

Retrieves all skills for a given agent, including both **agent-scoped** and **organization-scoped** skills, plus any pending **action approvals** related to skills.

**Request:**

```bash theme={null}
GET /api/agents/{agentId}/skills
```

**Response:**

```json theme={null}
{
  "skills": [
    {
      "id": "skill_abc123",
      "organizationId": "org_xyz",
      "agentId": "agent_123",
      "slug": "handle-refund-request",
      "name": "Handle Refund Request",
      "description": "Activated when a customer requests a refund or mentions billing issues.",
      "content": "When handling a refund request:\n1. Acknowledge the customer's frustration\n2. Ask for the order number\n3. Check eligibility per the refund policy\n4. Process or escalate accordingly",
      "status": "active",
      "pinned": false,
      "origin": "manual",
      "scope": "agent",
      "metadata": null,
      "createdAt": "2025-01-15T10:00:00.000Z",
      "updatedAt": "2025-01-15T10:00:00.000Z",
      "lastReviewedAt": "2025-01-15T10:00:00.000Z"
    }
  ],
  "approvals": []
}
```

### Create a Skill

**Request:**

```bash theme={null}
POST /api/agents/{agentId}/skills
Content-Type: application/json
```

**Request Body:**

| Field         | Type                                | Required | Description                                               |
| ------------- | ----------------------------------- | -------- | --------------------------------------------------------- |
| `name`        | `string`                            | ✅        | Display name of the skill                                 |
| `content`     | `string`                            | ✅        | The instruction content the AI follows                    |
| `slug`        | `string`                            | ❌        | Machine-readable ID (auto-generated from name if omitted) |
| `description` | `string \| null`                    | ❌        | When this skill should activate                           |
| `status`      | `"draft" \| "active" \| "archived"` | ❌        | Default: `"draft"`                                        |
| `pinned`      | `boolean`                           | ❌        | Pin to top of skill list. Default: `false`                |
| `scope`       | `"agent" \| "organization"`         | ❌        | Default: `"agent"`                                        |
| `metadata`    | `object`                            | ❌        | Arbitrary JSON metadata                                   |

**Example:**

```json theme={null}
{
  "name": "Handle Refund Request",
  "description": "When a customer mentions billing, refund, or charge dispute.",
  "content": "When handling a refund request:\n1. Acknowledge the issue empathetically\n2. Ask for the order or invoice number\n3. Verify the purchase date (refunds accepted within 30 days)\n4. If eligible: confirm refund initiation and timeline (3-5 business days)\n5. If ineligible: explain the policy clearly and offer alternatives",
  "status": "active",
  "scope": "agent"
}
```

**cURL:**

```bash theme={null}
curl -X POST "https://your-domain.com/api/agents/agent_123/skills" \
  -H "Content-Type: application/json" \
  -H "Cookie: next-auth.session-token=YOUR_SESSION_TOKEN" \
  -d '{
    "name": "Handle Refund Request",
    "content": "When a refund is requested, acknowledge empathetically and verify eligibility.",
    "status": "active"
  }'
```

**TypeScript:**

```ts theme={null}
const response = await fetch(`/api/agents/${agentId}/skills`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    name: 'Handle Refund Request',
    content: 'When a refund is requested, acknowledge empathetically and verify eligibility.',
    status: 'active',
  }),
});

const skill = await response.json();
```

### Update a Skill

**Request:**

```bash theme={null}
PATCH /api/agents/{agentId}/skills/{skillId}
Content-Type: application/json
```

All fields from the create schema are optional. Only fields provided will be updated.

**Status Lifecycle:**

| Status     | Meaning                                               |
| ---------- | ----------------------------------------------------- |
| `draft`    | Skill exists but is NOT used by the Cortex at runtime |
| `active`   | Skill is live and the Cortex can select it            |
| `archived` | Skill is disabled and hidden from active selection    |

> Setting status to `active` or `archived` automatically updates `lastReviewedAt`.

**Slug Conflict:** If a new `slug` is provided that already exists in the organization, the API returns `409 Conflict`.

***

## 5. Skill Packs

Skill Packs are **pre-built collections of skills** curated by ZappWay for common use cases. They allow you to bootstrap a skill library in seconds.

### List Available Packs

```bash theme={null}
GET /api/agents/{agentId}/skills/packs
```

Returns packs adapted to the agent's locale and current skill configuration.

**Response:**

```json theme={null}
{
  "packs": [
    {
      "id": "pack_customer_support",
      "name": "Customer Support Essentials",
      "description": "Core skills for handling support inquiries, escalations, and common issues.",
      "skills": [
        { "name": "Escalate to Human", "description": "When to escalate to a human agent" },
        { "name": "Acknowledge Frustration", "description": "Empathetic de-escalation" },
        { "name": "Request More Information", "description": "When the AI needs more context" }
      ]
    }
  ]
}
```

### Apply a Skill Pack

```bash theme={null}
POST /api/agents/{agentId}/skills/packs/apply
Content-Type: application/json
```

**Request Body:**

| Field     | Type                        | Required | Description                                                  |
| --------- | --------------------------- | -------- | ------------------------------------------------------------ |
| `packId`  | `string`                    | ✅        | ID of the pack to apply                                      |
| `scope`   | `"agent" \| "organization"` | ✅        | Whether skills are created for this agent or shared org-wide |
| `channel` | `ConversationChannel`       | ❌        | Optionally filter skills to a specific channel               |

**Example:**

```json theme={null}
{
  "packId": "pack_customer_support",
  "scope": "agent"
}
```

***

## 6. AI-Proposed Skills

ZappWay can use AI to **automatically generate skill suggestions** based on your agent's configuration or knowledge base.

### Propose Skills from Configuration

Analyzes the agent's instructions and existing tools to suggest new skills.

```bash theme={null}
POST /api/agents/{agentId}/skills/propose
```

Returns an array of `ActionApproval` objects — suggested skills waiting for your review and acceptance.

### Propose Skills from Knowledge Base (RAG)

Analyzes the agent's connected datastores and datasources to extract recurring topics and create skill suggestions.

```bash theme={null}
POST /api/agents/{agentId}/skills/propose-from-rag
```

**Response:**

```json theme={null}
{
  "createdCount": 3,
  "approvals": [
    {
      "id": "approval_abc",
      "actionType": "agent_skill.create",
      "payload": {
        "name": "Handle Product Returns",
        "content": "When the customer asks about returning a product..."
      }
    }
  ],
  "skipped": 1
}
```

> Proposals that closely match existing skills are automatically skipped (`skipped` count).

***

## 7. Skill Optimization

Request AI-generated optimization suggestions for existing skills to improve their effectiveness.

```bash theme={null}
POST /api/agents/{agentId}/skills/optimize
```

Returns a list of `ActionApproval` objects with suggested improvements for existing skills. These are reviewed via the Approvals system before being applied.

**Response:**

```json theme={null}
{
  "approvals": [
    {
      "id": "approval_xyz",
      "actionType": "agent_skill.update",
      "payload": {
        "skillId": "skill_abc123",
        "content": "Improved content based on conversation patterns..."
      }
    }
  ]
}
```

***

## 8. Agent Cortex Mode

The **Agent Cortex** controls how the AI autonomously selects and applies skills at runtime.

### Get Current Mode

```bash theme={null}
GET /api/agents/{agentId}/skills/cortex-mode
```

**Response:**

```json theme={null}
{
  "configuredMode": "advisory",
  "effectiveMode": "advisory"
}
```

| Field            | Description                                                           |
| ---------------- | --------------------------------------------------------------------- |
| `configuredMode` | The mode explicitly set by the user                                   |
| `effectiveMode`  | The mode actually in effect (may differ if rollout constraints apply) |

### Update Mode

```bash theme={null}
PATCH /api/agents/{agentId}/skills/cortex-mode
Content-Type: application/json
```

**Request Body:**

```json theme={null}
{
  "mode": "active"
}
```

| Mode       | Behavior                                                                                  |
| ---------- | ----------------------------------------------------------------------------------------- |
| `passive`  | Cortex is disabled. Skills are not automatically selected.                                |
| `advisory` | Cortex suggests the most relevant skill but does not inject automatically.                |
| `active`   | Cortex automatically selects and injects the most relevant skill into every conversation. |

***

## 9. Agent Specialists

Specialists allow an agent to **delegate conversations** to other specialized agents based on routing rules.

### List Specialists

```bash theme={null}
GET /api/agents/{agentId}/specialists
```

**Response:**

```json theme={null}
{
  "tools": [...],
  "approvals": [...],
  "activeRules": [
    {
      "toolId": "tool_abc",
      "targetAgentId": "agent_specialist_456",
      "reason": "Customer is asking about enterprise pricing",
      "status": "active"
    }
  ]
}
```

### Activate/Deactivate a Routing Rule

```bash theme={null}
POST /api/agents/{agentId}/specialists
Content-Type: application/json
```

**Request Body:**

| Field           | Type                                     | Required | Description                                  |
| --------------- | ---------------------------------------- | -------- | -------------------------------------------- |
| `toolId`        | `string`                                 | ✅        | The tool that represents the specialist link |
| `targetAgentId` | `string`                                 | ✅        | ID of the specialist agent                   |
| `action`        | `"activate" \| "deactivate" \| "ignore"` | ✅        | What to do with the routing rule             |
| `approvalId`    | `string`                                 | ❌        | If resolving an AI-suggested routing rule    |
| `reason`        | `string`                                 | ❌        | Why this specialist should be triggered      |
| `confidence`    | `number`                                 | ❌        | Confidence score (0–1)                       |

### Link a Specialist

Creates a **new specialist link** between two agents. The system prevents self-loops and circular delegation chains.

```bash theme={null}
PUT /api/agents/{agentId}/specialists
Content-Type: application/json
```

**Request Body:**

```json theme={null}
{
  "targetAgentId": "agent_specialist_456",
  "name": "Enterprise Sales Specialist",
  "description": "Handles enterprise-level pricing and contracts"
}
```

> **Cycle Detection:** The system blocks delegation cycles at depth 1 (e.g., A→B when B→A already exists). Returns `400 Conflict` with `reasonCode: "CYCLE_BLOCKED"`.

***

## 10. Response Format

### Status Codes

| Status | Meaning                                                           |
| ------ | ----------------------------------------------------------------- |
| `200`  | Request successful                                                |
| `201`  | Resource created                                                  |
| `400`  | Invalid request body or business rule violation (e.g., self-loop) |
| `401`  | Not authenticated                                                 |
| `403`  | Insufficient permissions                                          |
| `404`  | Agent or skill not found in your organization                     |
| `409`  | Slug conflict — a skill with that slug already exists             |
| `500`  | Internal server error                                             |

***

## 11. Error Handling

| Error                                | Cause                                                  | How to Fix                                                 |
| ------------------------------------ | ------------------------------------------------------ | ---------------------------------------------------------- |
| `Agent not found for organization`   | `agentId` does not belong to your current organization | Verify the agent ID and your active organization           |
| `Skill not found`                    | `skillId` does not exist or is not accessible          | Confirm the skill ID belongs to the agent or org           |
| `Skill slug already exists`          | The new slug is already taken                          | Use a different slug or let the system auto-generate one   |
| `An agent cannot delegate to itself` | You tried to link an agent to itself as a specialist   | Use a different `targetAgentId`                            |
| `Delegation cycle detected`          | Circular delegation (A→B, B→A)                         | Review specialist links to eliminate circular dependencies |

***

## 12. Best Practices

### Writing Effective Skills

✅ **Do:**

* Keep each skill focused on **one specific situation or behavior**
* Use the `description` field to explain exactly **when** the skill should activate
* Write `content` as actionable step-by-step instructions
* Start with `draft` status while testing, then promote to `active`
* Use `organization` scope for skills shared across multiple AI Employees

❌ **Avoid:**

* Skills with vague names like "General Help" — be specific
* Packing too many behaviors into a single skill
* Leaving all skills in `draft` status (they won't be used by the Cortex)
* Creating duplicate skills with different names but the same behavior

### Cortex Mode Selection

| Mode       | Best For                                                                 |
| ---------- | ------------------------------------------------------------------------ |
| `passive`  | Simple agents with a single focused purpose                              |
| `advisory` | Testing mode — see which skills the Cortex selects without auto-applying |
| `active`   | Production agents with rich skill libraries                              |

### Organization vs Agent Scope

| Scope          | Use When                                                                                                        |
| -------------- | --------------------------------------------------------------------------------------------------------------- |
| `agent`        | Skill is highly specific to one AI's persona or use case                                                        |
| `organization` | Skill represents general company policy or process that all AIs should follow (e.g., "Always comply with LGPD") |

***

## 13. Troubleshooting

| Problem                                   | Possible Cause                                 | Solution                                                         |
| ----------------------------------------- | ---------------------------------------------- | ---------------------------------------------------------------- |
| Skills not being applied in conversations | Cortex is in `passive` mode                    | Set Cortex to `advisory` or `active`                             |
| Skills exist but Cortex selects wrong one | Skills are too generic or descriptions overlap | Refine `description` fields to be more specific                  |
| Skill created but not visible             | Skill was created with `draft` status          | Change status to `active`                                        |
| Propose-from-RAG returns 0 suggestions    | No datastores connected to the agent           | Connect at least one datastore with indexed content              |
| Specialist delegation not routing         | Routing rule is inactive                       | Use `POST /specialists` with `action: "activate"`                |
| `409 Conflict` on skill creation          | Slug already exists in the organization        | Omit the `slug` field to auto-generate, or provide a unique slug |
