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

# Multi-agent systems

> Assign Agents to a coordinator as sub-agents, deploy the team from config files, follow the Sub-Objectives it starts, and route work with an Agent Pool.

An Agent delegates by calling another Agent the way it calls a tool. Assign a specialist to the coordinator's [Agent Variation](https://cadenya.com/docs/guides/the-basics/agents.md#variations), and the coordinator's model gets a function that starts the specialist on a Sub-Objective. The specialist works in its own Context Window, with its own model, prompt, and tools. The coordinator hears back when it stops.

This guide deploys a three-Agent team for the Swagger Petstore from [config files](https://cadenya.com/docs/config-files.md), runs it, and follows the work from one Objective to the next. The last section swaps a fixed specialist for an Agent Pool that picks one at call time.

## How a handoff runs

```mermaid theme={null}
sequenceDiagram
  participant App as Your app
  participant Front as Front Desk
  participant Pets as Pet Finder
  participant Orders as Order Desk
  App->>Front: Create Objective
  Front->>Pets: subagent_pet_finder
  Front->>Orders: subagent_order_desk
  Note over Front: Turn ends. The Objective waits.
  Pets-->>Front: Notice: waiting for another message
  Orders-->>Front: Notice: completed
  Front->>Pets: get_sub_agent_last_message
  Front->>Orders: get_sub_agent_last_message
  Front-->>App: Final answer
```

No step in a handoff blocks:

1. **Each sub-agent becomes one function.** The name is `subagent_` plus the Agent's name in lowercase with underscores, cut at 63 characters: `Pet Finder` becomes `subagent_pet_finder`. The Agent's `description` becomes the function's description, so write it for a model that has to decide when to call it.
2. **A call starts a Sub-Objective and returns at once.** The result carries the new Objective's ID, not an answer. So the coordinator can start several specialists in one turn, and they run side by side.
3. **A specialist that stops running reports in.** Cadenya adds a notice to the coordinator's conversation when a Sub-Objective waits for input, completes, fails, or times out. A coordinator that already ended its turn starts a new one to read it.
4. **The coordinator reads the reply and carries on.** It can also send a follow-up, and the specialist picks the conversation back up with its history intact.

Cadenya gives the coordinator the tools for steps 3 and 4. They load on any Objective whose variation has a sub-agent or an Agent Pool, with nothing to configure:

| Tool | What the coordinator does with it |
| - | - |
| `list_sub_agents` | Lists the Sub-Objectives it started, newest first, with each one's ID, Agent, state, and start time. |
| `get_sub_agent_status` | Checks the state of one or more of them. |
| `get_sub_agent_last_message` | Reads a specialist's latest reply. A specialist with [structured output](https://cadenya.com/docs/guides/the-basics/agents.md#structured-output) returns that JSON. |
| `send_message_to_sub_agent` | Sends a follow-up. A waiting specialist starts on it. A busy one reads it after its current turn, or right away with `interrupt` set. |
| `interrupt_sub_agent` | Stops a specialist's current turn. The specialist keeps its conversation and waits for the next message. |
| `wait` | Pauses for up to 300 seconds. A notice ends the pause early. |

A coordinator reaches only the Sub-Objectives it started. Any other Objective ID reads as not found, so a model can't steer someone else's work by guessing an ID.

> [!NOTE]
>
> Sub-agents and Agent Pools always load as tools, even on a variation that uses progressive discovery.

## Before you start

You need:

1. The [Cadenya CLI](https://cadenya.com/docs/guides/the-basics/cli.md), version 1.11.0 or later, signed in with `cadenya auth login`.
2. A workspace to deploy into. The example uses one with the external ID `development`.
3. The Petstore host on your account's trusted endpoints:

```bash theme={null}
cadenya trusted-endpoints create --name "Swagger Petstore" --host petstore3.swagger.io
```

## Describe the team

The team has a coordinator and two specialists. The Front Desk has no store tools. Pet Finder and Order Desk each get the Petstore Tool Set and a narrow job.

```text theme={null}
cadenya.yaml
.cadenya/
  toolSets/
    petstore.yaml
  agents/
    front-desk.yaml
    front-desk/
      default.yaml     # assigns both specialists
    pet-finder.yaml
    pet-finder/
      default.yaml
    order-desk.yaml
    order-desk/
      default.yaml
```

**1. Add the settings and the Tool Set**

`cadenya.yaml` names the bundle and the workspace. The Tool Set points at the Petstore's OpenAPI document, and Cadenya syncs a tool for each operation:

```yaml cadenya.yaml theme={null}
bundleKey: petstore-team
workspaceId: development
```

```yaml .cadenya/toolSets/petstore.yaml theme={null}
metadata:
  name: Swagger Petstore
spec:
  description: Find pets, place orders, and manage the store inventory
  adapter:
    type: openapi
    openapi:
      type: url
      url: https://petstore3.swagger.io/api/v3/openapi.json
```

**2. Add a specialist that takes a message**

Pet Finder is the plain case. With no input schema, its function takes one argument, `message`, and that text becomes the first user message of the Sub-Objective.

```yaml .cadenya/agents/pet-finder.yaml theme={null}
state: published
metadata:
  name: Pet Finder
spec:
  # The Front Desk's model reads this as the tool description.
  description: Looks up pets by status, tag, or ID. Use it for any question about which pets the store has.
```

```yaml .cadenya/agents/pet-finder/default.yaml theme={null}
metadata:
  name: Default
spec:
  systemPromptTemplate: |
    You look up pets in the Swagger Petstore. Answer from tool results only,
    and say so when a lookup returns nothing. Reply with the facts and stop.
  constraints:
    maxToolCalls: 10
  assignments:
    - type: toolSetId
      toolSetId: external_id:petstore
```

A Sub-Objective needs a published Agent, the same as any other Objective. Hence `state: published` on every Agent in the team, not only the coordinator.

**3. Add a specialist with typed input and output**

Order Desk shows both ends of a stricter contract:

* `systemPromptDataSchema` adds a required `data` argument to the function. Cadenya rejects a call whose `data` doesn't match the schema. The values render into the specialist's system prompt as `system_prompt_data`.
* `outputDefinition` makes the specialist finish with JSON in that shape. `get_sub_agent_last_message` returns the JSON, so the coordinator parses nothing out of prose.

```yaml .cadenya/agents/order-desk.yaml theme={null}
state: published
metadata:
  name: Order Desk
spec:
  description: Reads store orders and inventory counts. Use it for order status and stock questions.
  # With a schema, the Front Desk must pass matching `data` on every call.
  systemPromptDataSchema:
    type: object
    properties:
      orderId:
        type: integer
        description: The order to look up
    required: [orderId]
  # With an output definition, the Front Desk reads this JSON, not prose.
  outputDefinition:
    type: object
    properties:
      orderId:
        type: integer
      status:
        type: string
        enum: [placed, approved, delivered, unknown]
      complete:
        type: boolean
    required: [orderId, status]
```

```yaml .cadenya/agents/order-desk/default.yaml theme={null}
metadata:
  name: Default
spec:
  systemPromptTemplate: |
    You read orders in the Swagger Petstore. The order in question is
    {{ system_prompt_data.orderId }}. Look it up and report its status.
  constraints:
    maxToolCalls: 10
  assignments:
    - type: toolSetId
      toolSetId: external_id:petstore
```

The output definition also changes how the specialist ends. Order Desk extracts its output and completes, so it takes no follow-ups. Pet Finder ends its turn and waits, so the Front Desk can ask it a second question in the same conversation.

**4. Add the coordinator**

The Front Desk's variation assigns both specialists with `subAgentId`. Inside a bundle, an Agent refers to another by external ID, which defaults to the filename.

```yaml .cadenya/agents/front-desk.yaml theme={null}
state: published
metadata:
  name: Front Desk
spec:
  description: Answers Petstore customers by delegating to specialist agents
```

```yaml .cadenya/agents/front-desk/default.yaml theme={null}
metadata:
  name: Default
spec:
  systemPromptTemplate: |
    You run the front desk of a pet store. You have no store tools of your
    own. Hand each question to the right specialist, start them together
    when a request has several parts, and answer the customer once every
    specialist has reported.
  constraints:
    # A cost guardrail: one objective starts at most four Sub-Objectives.
    maxSubObjectives: 4
  assignments:
    - type: subAgentId
      subAgentId: external_id:pet-finder
    - type: subAgentId
      subAgentId: external_id:order-desk
```

`maxSubObjectives` caps how many Sub-Objectives one Objective starts. Past the cap, the call fails with a message that tells the model it can't start another, and the model works with what it has. `0` (the default) means no cap. Two calls in the same turn can both slip past the check, so read the number as a budget, not a hard wall.

![Behavior assignments panel with Pet Finder and Order Desk assigned as Sub-Agents](https://mintcdn.com/cadenya/IHOEKSSCqtwMFT3f/images/guides/advanced-use-cases/multi-agent-assignments.webp?fit=max\&auto=format\&n=IHOEKSSCqtwMFT3f\&q=85\&s=4e98b33725256e481b5366460d27e054)

The Front Desk variation assigns Pet Finder and Order Desk as sub-agents.

Every variation here leaves out `modelConfig`, so each runs on the workspace default model. To give a specialist a smaller or a stronger model than its coordinator, set `modelConfig.modelId` on that specialist's variation.

## Deploy the team

Check the files first. Validation runs offline and catches a `subAgentId` that points at an Agent the bundle doesn't have:

```bash theme={null}
cadenya config validate
```

You should see:

```
Valid bundle petstore-team: 7 resources
```

Then plan and apply:

```bash theme={null}
cadenya config plan    # reads the workspace, changes nothing
cadenya config apply
```

The plan lists a `create` for the Tool Set, the three Agents, and the three variations, then a `publish` for each Agent. Apply creates every Agent before any variation, so a variation can assign an Agent from the same run.

To deploy on every merge, run the same commands from [GitHub Actions](https://cadenya.com/docs/config-files.md#apply-from-github-actions). To promote the team to another workspace, point the same files at it with `CADENYA_WORKSPACE_ID`.

### Assign a sub-agent without config files

One call attaches a specialist to an existing variation. Here it is for a variation with the external ID `default`:

```bash CLI theme={null}
cadenya agents variations add-assignment external_id:front-desk external_id:default \
  --sub-agent-id external_id:pet-finder
```

```bash cURL theme={null}
curl --request POST \
  "https://api.cadenya.com/v1/workspaces/${CADENYA_WORKSPACE_ID}/agents/external_id:front-desk/variations/external_id:default:addAssignment" \
  --header "Authorization: Bearer ${CADENYA_API_KEY}" \
  --header "Content-Type: application/json" \
  --data '{"type": "subAgentId", "subAgentId": "external_id:pet-finder"}'
```

Cadenya refuses two assignments, because both spend money in a loop: an Agent as its own sub-agent, and a specialist that already delegates back to the coordinator, directly or through other Agents.

## Run it

Ask a question with two parts, so the Front Desk has a reason to start both specialists:

```bash theme={null}
EXTERNAL_ID="front-desk-$(date +%s)"

cadenya objectives create \
  --agent-id external_id:front-desk \
  --external-id "$EXTERNAL_ID" \
  --first-user-message 'Which pets are available right now, and what is the status of order 3?'

cadenya objectives stream-events "$EXTERNAL_ID"
```

Look for these events in the Front Desk's log:

| Event | What happened |
| - | - |
| `toolCalled` | The model calls `subagent_pet_finder` and `subagent_order_desk`, and later `get_sub_agent_last_message` for each reply. |
| `subAgentSpawned` | One per handoff. Each records the call's arguments as `task`, plus the specialist's Agent and the new Objective. |
| `subAgentUpdated` | A specialist stopped running. `status` says how. |
| `assistantMessage` | The Front Desk answers the customer. |

`subAgentUpdated` carries one of four statuses:

| Status | Meaning |
| - | - |
| `STATUS_WAITING` | The specialist ended its turn and has a reply. It still takes follow-ups. |
| `STATUS_COMPLETED` | The specialist produced its structured output and finished. |
| `STATUS_FAILED` | The specialist hit an error. `message` says what went wrong. |
| `STATUS_TIMED_OUT` | The specialist sat idle past its inactivity timeout. |

A cancelled specialist sends no update. Whoever cancelled it already knows.

### Know when the coordinator is done

Between starting its specialists and hearing from them, the Front Desk has nothing to do, so it ends its turn and its Objective moves to `OBJECTIVE_STATE_WAITING`. That's the same state it lands in after its final answer. **A waiting coordinator may still have specialists at work, and it resumes on its own when one reports.**

To tell the difference:

1. **Give the coordinator an `outputDefinition`.** An Objective with structured output doesn't finalize while a Sub-Objective it started is pending or running. `OBJECTIVE_STATE_FINALIZED` then means the whole team is done, and the answer sits in `output`.
2. **Check the Sub-Objectives.** A waiting coordinator with no pending or running Sub-Objectives has given its answer.

## Follow the Sub-Objectives

In the dashboard, open the coordinator's Objective and select **Sub-Agents**. Each row links to a specialist's Objective, with the task it received and its current state.

![Sub-Agents tab listing Order Desk and Pet Finder with their delegated questions and Cancelled states](https://mintcdn.com/cadenya/IHOEKSSCqtwMFT3f/images/guides/advanced-use-cases/multi-agent-sub-objectives.webp?fit=max\&auto=format\&n=IHOEKSSCqtwMFT3f\&q=85\&s=3a411e0cf416b348b49e821b0d8d012b)

The Front Desk starts one Sub-Objective for each part of the customer's question.

A Sub-Objective is an ordinary Objective with `parentObjectiveId` set. Everything that works on an Objective works on it: events, tool calls, diagnostics, feedback. List the ones a coordinator started:

```bash CLI theme={null}
cadenya objectives list --parent-objective-id "$PARENT_OBJECTIVE_ID"
```

```bash cURL theme={null}
curl --request GET \
  "https://api.cadenya.com/v1/workspaces/${CADENYA_WORKSPACE_ID}/objectives?parentObjectiveId=${PARENT_OBJECTIVE_ID}" \
  --header "Authorization: Bearer ${CADENYA_API_KEY}"
```

`PARENT_OBJECTIVE_ID` is the Front Desk Objective's `obj_` ID. Then stream any one of them the way you streamed the parent:

```bash theme={null}
cadenya objectives stream-events "$SUB_OBJECTIVE_ID"
```

### What a Sub-Objective starts with

A Sub-Objective starts clean. It gets two things from the call: `message` as its first user message, and `data` as its system prompt data. The rest comes from the specialist's own Agent and the variation Cadenya selects for it.

So the coordinator's conversation doesn't carry over, and neither do the secrets, memory references, or pinned parameters you passed when you created the parent Objective. Anything a specialist needs has to arrive in `message` or `data`, or live on the specialist: a [Memory Layer](https://cadenya.com/docs/guides/the-basics/memory.md) on its variation, a secret on its Tool Set.

Variation selection runs for each Sub-Objective, so a specialist with several variations gets one picked per handoff. [Feedback](https://cadenya.com/docs/api-reference/objectiveservice/submit-feedback-for-an-objective.md) on a Sub-Objective scores the specialist's variation, not the coordinator's.

### Webhooks

Each Agent sends its own Objectives' events to its own [webhook URL](https://cadenya.com/docs/guides/the-basics/webhooks.md). So the Front Desk's endpoint receives [`objective_event.sub_agent_spawned`](https://cadenya.com/docs/api-reference/objective-sub-agent-spawned-event) and [`objective_event.sub_agent_updated`](https://cadenya.com/docs/api-reference/objective-sub-agent-updated-event), while the tool calls a specialist makes go to the specialist's endpoint.

To tie the two together, every delivery from a Sub-Objective carries two extra keys in `data`:

| Key | Names |
| - | - |
| `parentObjective` | The Objective that started this one. |
| `rootObjective` | The top of the chain. For a specialist started by a top-level Objective, it matches `parentObjective`. |

Both are absent on a top-level Objective. Route on `rootObjective.externalId`, and the events of a whole team land on the record in your system that asked the question.

### When the coordinator ends

A coordinator that reaches a terminal state (finalized, failed, cancelled, or timed out) takes its unfinished Sub-Objectives with it. Cadenya cancels them, and each cancelled Sub-Objective cancels its own, down the tree. So cancelling the top Objective stops the whole team:

```bash theme={null}
cadenya objectives cancel "$PARENT_OBJECTIVE_ID"
```

A waiting coordinator cancels nothing. Its specialists keep their conversations until it speaks to them again or their inactivity timeout runs out.

## Route to one of several Agents with an Agent Pool

A sub-agent assignment is a fixed line: this coordinator, that specialist. An Agent Pool is a switchboard. The coordinator's model sees one function for the whole pool, and Cadenya picks the member that fits each call.

Use a pool when the specialists are interchangeable from the coordinator's side (one per product line, one per language) and you'd rather add a member than edit the coordinator.

Config files don't create Agent Pools, so this part uses the CLI or the API.

**1. Create the pool**

The pool's `description` tells the coordinator's model when to call it. Each member's Agent `description` tells Cadenya which member fits, and `instructions` frames that choice.

```bash CLI theme={null}
cadenya agent-pools create \
  --name "Store Specialists" \
  --external-id store-specialists \
  --description "Answers any question about pets, orders, or stock in the store" \
  --instructions "Pick the agent whose description covers the request" \
  --assignment agent-id="$PET_FINDER_ID" \
  --assignment agent-id="$ORDER_DESK_ID"
```

```bash cURL theme={null}
curl --request POST \
  "https://api.cadenya.com/v1/workspaces/${CADENYA_WORKSPACE_ID}/agent_pools" \
  --header "Authorization: Bearer ${CADENYA_API_KEY}" \
  --header "Content-Type: application/json" \
  --data '{
    "metadata": {"name": "Store Specialists", "externalId": "store-specialists"},
    "spec": {
      "description": "Answers any question about pets, orders, or stock in the store",
      "instructions": "Pick the agent whose description covers the request",
      "assignments": [
        {"agentId": "'"${PET_FINDER_ID}"'"},
        {"agentId": "'"${ORDER_DESK_ID}"'"}
      ]
    }
  }'
```

Members take canonical `agent_` IDs. `cadenya agents list` prints them. Leave `instructions` out and Cadenya asks "Which agent is best suited to handle this request?"

**2. Activate it**

A pool starts inactive and routes nothing. Activation needs at least one published member:

```bash theme={null}
cadenya agent-pools activate external_id:store-specialists
```

Copy the `apool_` ID from the output for the next step.

**3. Assign it to the coordinator**

A pool assignment takes the canonical ID. In a config file, it sits in the variation's `assignments` next to the others:

```yaml .cadenya/agents/front-desk/default.yaml theme={null}
metadata:
  name: Default
spec:
  systemPromptTemplate: |
    You run the front desk of a pet store. You have no store tools of your
    own. Hand each question to the store specialists, and answer the
    customer once they have reported.
  constraints:
    maxSubObjectives: 4
  assignments:
    - type: agentPoolId
      agentPoolId: apool_01HXKD2E5NQM3T9AYWCF2R43QW
```

```bash CLI theme={null}
cadenya agents variations add-assignment external_id:front-desk external_id:default \
  --agent-pool-id apool_01HXKD2E5NQM3T9AYWCF2R43QW
```

![Active Store Specialists Agent Pool showing Pet Finder, Order Desk, their descriptions, and routing instructions](https://mintcdn.com/cadenya/IHOEKSSCqtwMFT3f/images/guides/advanced-use-cases/multi-agent-pool.webp?fit=max\&auto=format\&n=IHOEKSSCqtwMFT3f\&q=85\&s=27bf733672de6ba6e3f2bf341bae9783)

Store Specialists is active, with two members and instructions for choosing between them.

From here a pool call behaves like a sub-agent call: it starts a Sub-Objective, returns at once, and the coordinator follows it with the same tools. It differs in these details:

* **The function name** is `agent_pool_` plus the pool's name in lowercase with underscores: `agent_pool_store_specialists`.
* **The arguments** are one `request` string. To take structured arguments, set a JSON Schema on the pool's `spec.state`. Cadenya validates each call against it.
* **Routing reads the arguments and the member descriptions.** Only published members are candidates. A pool with no published member, or one that is inactive or archived, fails the call.
* **The chosen member gets the arguments as its first user message**, as JSON. A member with a `systemPromptDataSchema` also gets them as its system prompt data.

Deactivate a pool to stop new handoffs without touching its members or its assignments. Sub-Objectives already running finish their work.

## Where to go next

* The [config files](https://cadenya.com/docs/config-files.md) page covers bundle keys, deletes, and the GitHub Action that deploys on every push.
* The [Objectives guide](https://cadenya.com/docs/guides/the-basics/objectives.md#objective-events) lists every event in an Objective's log.
* The API reference has the full contract for [variation assignments](https://cadenya.com/docs/api-reference/agentvariationservice/add-an-assignment-to-a-variation.md) and [Agent Pools](https://cadenya.com/docs/api-reference/agentpoolservice/create-a-new-agent-pool.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.