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

# Multi-agent and supervisor

This page documents multi-agent orchestration constructs (`DELEGATE`, `HANDOFF`, `ESCALATE`, `COMPLETE`) and the `SUPERVISOR:` declaration for top-level routing.

***

## SUPERVISOR declaration

A Supervisor is a top-level orchestrator that routes user messages to the appropriate child agent based on intent, context, and declarative rules. Supervisor documents use the `SUPERVISOR:` keyword instead of `AGENT:` and define agent references, routing rules, state schemas, policies, and communication settings.

### Overview

While agents handle domain-specific tasks, the Supervisor decides which agent should handle each user message. It does not execute tools or gather information directly; it classifies intent and routes accordingly.

```yaml theme={null}
SUPERVISOR: Travel_Supervisor
VERSION: "2.0"
DESCRIPTION: "Routes customers to booking, support, or sales specialists"
GOAL: "Route requests to the right specialist with full context preservation"

PERSONA: |
  Professional travel booking assistant. Friendly, efficient, and helpful.
  Routes requests quickly and transparently.
```

### Agent references

The Supervisor declares which agents are available for routing. Each reference includes a file path, an alias, and a list of capabilities.

#### Syntax

```yaml expandable=true theme={null}
AGENTS:
  - REF: ./agents/flight_search.agent.abl
    ALIAS: Flight_Search
    CAPABILITIES: [flight_booking, fare_search, seat_selection]
    CHANNELS: [web, mobile, voice]
    REQUIRES_VALIDATION: false

  - REF: ./agents/support.agent.abl
    ALIAS: Support_Agent
    CAPABILITIES: [booking_management, cancellation, refund]
    REQUIRES_VALIDATION: true
```

#### Agent reference properties

| Property | Type | Required | Default | Description |
| - | - | - | - | - |
| `REF` | `string` | Yes | -- | File path to the agent's ABL definition. |
| `ALIAS` | `string` | Yes | -- | Local name used in routing rules and handoff targets. |
| `CAPABILITIES` | `string[]` | Yes | -- | List of capability tags describing what the agent can do. |
| `CHANNELS` | `string[]` | No | -- | Channels this agent supports (for example. `web`, `mobile`, `voice`). |
| `REQUIRES_VALIDATION` | `boolean` | No | `false` | Whether the user must be authenticated before routing to this agent. |

### Routing rules

Routing rules define conditional logic for directing messages to agents. Rules are evaluated in priority order.

#### Syntax

```yaml theme={null}
ROUTING:
  - NAME: escalation_route
    DESCRIPTION: "Route frustrated or explicitly requesting human"
    PRIORITY: 1
    WHEN: intent.category == "escalation" OR user.frustration_detected == true
    THEN: ROUTE_TO Live_Agent_Transfer
    FLAGS: [set_active]

  - NAME: booking_route
    PRIORITY: 5
    WHEN: intent.category == "new_booking"
    THEN: ROUTE_TO Sales_Agent
```

Alternatively, routing can be declared using the `HANDOFF:` block within a Supervisor, following the same syntax as [agent handoffs](#handoff):

```yaml theme={null}
HANDOFF:
  - TO: Sales_Agent
    WHEN: intent.category == "new_booking"
    CONTEXT:
      pass: [search_context, user_preferences, budget]
      summary: "User looking to book new travel"
    EXPECT_RETURN: false
```

#### Routing rule properties

| Property | Type | Required | Default | Description |
| - | - | - | - | - |
| `NAME` | `string` | Yes | -- | Unique name for the routing rule. |
| `DESCRIPTION` | `string` | No | -- | Human-readable description. |
| `PRIORITY` | `number` | Yes | -- | Evaluation order. Lower values are evaluated first. |
| `WHEN` | `string` | Yes | -- | Condition expression that must be true for this rule to activate. |
| `THEN` | `RoutingAction` | Yes | -- | Action to take. See [Routing actions](#routing-actions). |
| `FLAGS` | `string[]` | No | -- | Behavioral flags. See [Routing flags](#routing-flags). |
| `CONSTRAINTS` | `object` | No | -- | Additional constraints on when this rule applies. |

#### Routing actions

| Action | Syntax | Description |
| - | - | - |
| Route to agent | `ROUTE_TO Agent_Name` | Send the message to a specific agent. |
| Route to user | `ROUTE_TO_USER "message"` | Send a message and wait for user input. |
| Route by variable | `ROUTE_TO_VARIABLE var_name` | Route to the agent named in a variable. |
| Intent-based routing | `INTENT_MATCH` | Route based on detected intent. See below. |
| End conversation | `END_CONVERSATION` | End the session. |
| System action | `SYSTEM_ACTION action_name` | Execute a system-level action (for example. handoff). |

#### Intent-based routing

For more granular routing, use `INTENT_MATCH` with intent-to-agent mappings:

```yaml expandable=true theme={null}
ROUTING:
  - NAME: intent_router
    PRIORITY: 10
    WHEN: true
    THEN:
      INTENT_MATCH:
        - INTENTS: [flight_search, hotel_search]
          ACTION: ROUTE_TO Sales_Agent
        - INTENTS: [manage_booking, cancel_booking]
          ACTION: ROUTE_TO Support_Agent
        FALLBACK: ROUTE_TO Fallback_Handler
```

#### Routing flags

| Flag | Effect |
| - | - |
| `set_active` | Mark the target agent as the active agent for subsequent messages. |
| `silent` | Route without sending a user-visible message. |
| `no_log` | Do not log this routing decision in the trace store. |
| `priority_boost` | Apply a priority boost in the target agent's queue. |

#### Conditional routing (WHEN clauses)

WHEN clauses use the same expression syntax as [Expressions & functions](https://koreai.mintlify.site/agent-platform/abl/reference/expressions-and-functions.md), with the same [size limits](https://koreai.mintlify.site/agent-platform/abl/reference/expressions-and-functions.md#size-limits-for-conditions-and-regex-patterns). A long `WHEN` can combine parts with `OR` / `AND`, but each single comparison or list stays under 4,096 characters and each regex pattern under 500. Common patterns include:

```yaml expandable=true theme={null}
# Intent-based
WHEN: intent.category == "complaint"

# State-based
WHEN: user.is_authenticated == true AND intent.category == "manage_booking"

# Negation
WHEN: NOT intent.has_specific_request

# Compound
WHEN: intent.unclear == true OR intent.confidence < 0.5

# Variable check
WHEN: handoff_count >= 4
```

##### Conditions that read `before_turn` values

A routing rule `WHEN`, a `HANDOFF` `WHEN`, or an `ENABLED_WHEN` can read a value that the `before_turn` hook writes. In an agent or supervisor without a `FLOW`, such a route is judged after the hook, in the same turn. This happens before the agent's model call and before an intent shortcut or classifier routes the message. A route that matches hands off without the agent's own model call, and the destination answers.

```yaml theme={null}
TOOLS:
  lookup_case(customer_id: string) -> object

HOOKS:
  before_turn:
    CALL: lookup_case(customer_id: customer_id) AS case_lookup

HANDOFF:
  - TO: Delivery_Case_Agent
    WHEN: case_lookup.open == true
```

* The hook writes its `SET` keys, its `CALL` result variable, and what the called tool's `on_result` or `on_error` writes or clears. A value that the hook clears no longer routes on its old value.
* Routes keep their authored order. Routing rules run by priority, then handoffs in the order you wrote them. A route before the first route that reads a hook value is judged before the hook. So a guard that does not read hook values, such as an identity check, still runs ahead of the hook's `CALL`. The first route that reads a hook value, and every route after it, is judged after the hook.
* For such an agent, `before_turn` also runs on a turn that an intent shortcut or classifier then answers. On that turn the shortcut's answer wins.
* The earlier order stays in these cases: the agent has a `FLOW`, the agent has `GATHER` fields, the runtime awaits a specific reply (a pending choice, a queued offer, or a sequential continuation), or the hook calls a tool that the agent does not declare.

#### Routing constraint blocks

Add constraints to limit when a rule applies beyond the WHEN condition:

```yaml expandable=true theme={null}
ROUTING:
  - NAME: voice_only_route
    PRIORITY: 3
    WHEN: intent.category == "voice_action"
    THEN: ROUTE_TO Voice_Agent
    CONSTRAINTS:
      channels: [voice]
      requiresState: [user.is_authenticated]
      ignoreIntents: [greeting, farewell]
```

| Constraint | Type | Description |
| - | - | - |
| `ignoreIntents` | `string[]` | Intents that should not trigger this rule. |
| `channels` | `string[]` | Channels where this rule applies (for example. `[web, voice]`). |
| `requiresState` | `string[]` | State variables that must be set for this rule to activate. |

### State schema

The Supervisor can declare a state schema that defines typed variables organized by namespace.

```yaml expandable=true theme={null}
STATE:
  user:
    is_authenticated:
      type: boolean
      required: false
      default: false
      description: "Whether the user has been authenticated"
    language:
      type: string
      required: false
      source: user
  system:
    routing_failures:
      type: number
      required: false
      default: 0
      source: system
```

State variables follow the same [VariableDefinition](https://koreai.mintlify.site/agent-platform/abl/reference/data-types-and-utilities.md) structure as agent variables, with the addition of namespace grouping.

#### State variable properties

| Property | Type | Required | Default | Description |
| - | - | - | - | - |
| `type` | See [Data types](https://koreai.mintlify.site/agent-platform/abl/reference/data-types-and-utilities.md) | Yes | -- | Variable type. |
| `required` | `boolean` | No | `false` | Whether the variable must have a value. |
| `default` | any | No | -- | Default value. |
| `description` | `string` | No | -- | Human-readable description. |
| `source` | `system`, `user` , `agent`, `computed` | No | -- | Origin of the variable value. |
| `updatedBy` | `string[]` | No | -- | List of agent aliases that can update this variable. |

### Policies

Policies define high-level behavioral rules for the Supervisor, constraining what it is allowed and forbidden to do.

```yaml expandable=true theme={null}
POLICIES:
  - NAME: no_direct_booking
    DESCRIPTION: "Supervisor must not make bookings directly"
    RULES:
      forbiddenWhen: intent.category == "booking" AND active_agent IS NOT SET
      behavior: "Route to Sales_Agent instead of handling directly"

  - NAME: auth_required_for_account
    DESCRIPTION: "Account operations require authentication"
    RULES:
      allowedWhen: user.is_authenticated == true
      triggerSignal: "auth_required"
```

#### Policy properties

| Property | Type | Required | Default | Description |
| - | - | - | - | - |
| `NAME` | `string` | Yes | -- | Unique policy name. |
| `DESCRIPTION` | `string` | No | -- | Human-readable description. |
| `RULES` | `object` | Yes | -- | Policy rule definitions. See below. |

#### Policy rule properties

| Property | Type | Required | Default | Description |
| - | - | - | - | - |
| `allowedWhen` | `string` | No | -- | Condition under which the action is allowed. |
| `forbiddenWhen` | `string` | No | -- | Condition under which the action is forbidden. |
| `triggerSignal` | `string` | No | -- | Signal to emit when the policy is triggered. |
| `behavior` | `string` | No | -- | Description of the expected behavior when triggered. |

### Communication settings

Communication settings define the Supervisor's language, tone, and vocabulary preferences.

```yaml expandable=true theme={null}
COMMUNICATION:
  language: en
  formality: neutral
  pronouns:
    use: "we"
    avoid: "I"
  vocabulary:
    prefer: [assist, help, guide]
    avoid: [unfortunately, regrettably]
  constraints:
    - "Never reveal internal agent names to the user"
    - "Always explain why a transfer is happening"
```

#### Communication properties

| Property | Type | Required | Default | Description |
| - | - | - | - | - |
| `language` | `string` | Yes | -- | Primary language code (for example. `en`, `es`). |
| `formality` | `formal`, `informal`, `neutral` | Yes | -- | Communication tone. |
| `pronouns` | `object` | No | -- | Pronoun preferences (`use` and `avoid`). |
| `vocabulary` | `object` | No | -- | Preferred and avoided vocabulary. |
| `constraints` | `string[]` | Yes | -- | Communication behavioral constraints. |

### Behavior settings

The `BEHAVIOR` block declares the Supervisor's execution **role**, which governs how it participates
in coordination.

```yaml theme={null}
BEHAVIOR:
  role: orchestrator     # router | orchestrator | assistant
```

| Property | Type | Required | Default | Description |
| - | - | - | - | - |
| `role` | `string` | No\* | -- | Execution role: `router`, `orchestrator`, or `assistant`. See [Execution roles](#execution-roles). |
| `canRespondDirectly` | `boolean` | No | -- | **Deprecated** — migrate to `role`. Retained as a compatibility fallback (see below). |
| `allowedDirectActions` | `string[]` | No | `[]` | **Deprecated** compatibility field; does not authorize runtime operations. |
| `forbiddenActions` | `string[]` | No | `[]` | **Deprecated** compatibility field; does not authorize runtime operations. |

> [!NOTE]
>
> \*`role` is optional, but omitting it on an agent that has a `BEHAVIOR` block produces a deprecation warning and falls back to legacy inference. Declaring `role` is the recommended, forward-compatible form.

#### Execution roles

| Role | Responds directly? | Can `DELEGATE`? | Meaning |
| - | - | - | - |
| `router` | No | No | Routes each message to a child agent via `HANDOFF`. Requires at least one `HANDOFF` target. |
| `orchestrator` | Yes | Yes | Coordinates child agents and may also synthesize/respond directly. Required to use `DELEGATE`. |
| `assistant` | Yes (leaf) | Yes | A leaf agent that handles conversations directly. **Not valid on a `SUPERVISOR` document.** |

> [!WARNING]
>
> **Breaking changes in this release - Artemis 1.4.0:**
>
> * `canRespondDirectly` is deprecated in favor of `role`. If both are present and **conflict**
>   (`canRespondDirectly: true` ↔ `orchestrator`, `false` ↔ `router`), compilation fails
>   ([`AGENT_EXECUTION_ROLE_CONFLICT`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#agent_execution_role_conflict)). Remove the deprecated field or pick the matching role.
> * A `SUPERVISOR` must be `router` or `orchestrator` — `role: assistant` fails compilation.
> * `role: router` requires at least one `HANDOFF` ownership target.
> * Only an `orchestrator` may declare `DELEGATE:` — a `router` (or `assistant`) that uses
>   `DELEGATE` fails compilation ([`AGENT_RETURNED_WORK_REQUIRES_ORCHESTRATOR`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#agent_returned_work_requires_orchestrator)). Routers hand off;
>   orchestrators own returned work.

### Intents

In addition to `INTENT_MATCH` inside a routing rule, a Supervisor may declare a top-level `INTENTS:` block listing intent labels (and optional lexical-fallback behavior) that routing and classification draw on. Supervisors can also hand off to **other supervisors**, enabling hierarchical composition, and may declare an `ON_ERROR` block to handle routing failures.

### Execution pipeline (pre-classification)

> [!NOTE]
>
> This is an advanced, opt-in optimization. Most supervisors do not need it — routing works without an `EXECUTION` block.

A Supervisor can enable a pre-classification pipeline that runs a smaller, faster model before the main reasoning LLM. The classifier detects user intent and can short-circuit routing for obvious cases, avoiding the cost of a full reasoning call.

```yaml expandable=true theme={null}
SUPERVISOR: Support_Router

EXECUTION:
  model: claude-sonnet-4-5-20250929   # main reasoning model
  pipeline:
    enabled: true
    mode: sequential          # 'parallel' | 'sequential'
    shortCircuit:
      enabled: true
      confidenceThreshold: 0.85
    toolFilter:
      enabled: true
      maxTools: 6
    keywordVeto:
      enabled: true
      keywords: [reset, cancel, undo]
    intentBridge:
      enabled: true
      programmaticThreshold: 0.85
      guidedThreshold: 0.5
      outOfScopeDecline: true
      multiIntentSignal: true

HANDOFF:
  - TO: Billing_Agent
    WHEN: intent.category == "billing"
  - TO: General_Inquiry
    WHEN: true
```

> [!NOTE]
>
> The classifier **model** is not selected in the agent's `EXECUTION.pipeline` block — it is resolved from **project-level runtime configuration** via `modelSource` (`default` uses the platform's tool-selection model; `tenant` uses a specific tenant model identified by `tenantModelId`). A `model:` key inside the `pipeline` block is deprecated and ignored by the runtime. The top-level `EXECUTION.model` still sets the **main reasoning** model as usual.

#### Pipeline options

| Option | Type | Default | Description |
| - | - | - | - |
| `enabled` | Boolean | `false` | Enable the pre-classification pipeline. The setting has no effect unless the project runtime configuration also turns the pipeline on. |
| `mode` | String | `parallel` | `parallel` — classifier and main LLM run simultaneously; `sequential` — classifier runs first, main LLM only if no short-circuit. |
| `shortCircuit.enabled` | Boolean | `true` | Allow direct routing when classifier confidence is high. |
| `shortCircuit.confidenceThreshold` | Number | `0.85` | Minimum confidence to skip the reasoning loop. |
| `toolFilter.enabled` | Boolean | `true` | Filter tools to only relevant ones before reasoning. |
| `toolFilter.maxTools` | Number | `6` | Maximum tools passed to the reasoning loop. |
| `keywordVeto.enabled` | Boolean | `true` | Prevent short-circuit when the user mentions local tool keywords. |
| `keywordVeto.keywords` | String | `[]` | Additional keywords that veto short-circuit routing. |
| `intentBridge.enabled` | Boolean | `true` | Bridge classifier intent into routing decisions. |
| `intentBridge.programmaticThreshold` | Number | `0.85` | Confidence at/above which the runtime declines an out-of-scope request. It is not used for other routing. |
| `intentBridge.guidedThreshold` | Number | `0.5` | Confidence at/above which intent is offered to the model as guidance. |
| `intentBridge.outOfScopeDecline` | Boolean | `true` | Decline out-of-scope requests detected by the classifier. |
| `intentBridge.multiIntentSignal` | Boolean | `true` | Allow guided multi-intent detection when every detected intent reaches `guidedThreshold`. |

#### Parent return options

When a supervisor hands off with `RETURN: true`, the runtime checks the caller's replies against the supervisor's routes while the specialist is active, so a caller who changes topic can be routed back. The `parentReturn` options control that check. Each is read from the supervisor's `EXECUTION.pipeline.parentReturn` block first, then the project's `pipeline.parentReturn` runtime configuration (Studio: Runtime Config → Pipeline), then the default.

| Option | Type | Default | Description |
| - | - | - | - |
| `parentReturn.minConfidence` | Number | compiled threshold | Minimum confidence for a route to take the caller out of the specialist. |
| `parentReturn.ignoreAmbiguous` | Boolean | `false` | Keep the specialist in charge when the check is ambiguous. |
| `parentReturn.answerFirst` | Boolean | `false` | Give each reply to the active specialist before any topic check. Studio: **Answer Pending Question First**. |

```yaml theme={null}
EXECUTION:
  pipeline:
    enabled: true
    parentReturn:
      answerFirst: true
```

By default the check runs before the specialist sees the reply, and a matching route wins even when the reply answers the specialist's question. A short answer such as "no" to "Does anyone else have access to this card?" can be classified as another route.

With `answerFirst: true` the specialist gets the reply first:

| Active specialist | `answerFirst: false` (default) | `answerFirst: true` |
| - | - | - |
| Flow step waiting on `GATHER` | The topic check runs first. Its route wins. | The reply is extracted first. If it gives a valid value for every pending customer-facing field, the check is skipped. A whole reply captured into a lone free-text field does not count. Other replies are checked as before. |
| Reasoning agent | The topic check (decision model, then classifier) runs before every turn. | No check. The specialist answers, and calls `__return_to_parent__` when the request is outside its scope. Only then does the supervisor route it. |

A skipped check is traced as a `pipeline_classifier_skipped` decision with reason `parent_return_answer_first`.

* A flow reply that answers the pending question and also names a new topic stays with the flow.
* Instruct a reasoning specialist to hand back requests outside its scope with `__return_to_parent__`. Without that instruction, a caller who changes topic stays with the specialist.

Write the pipeline keys in camelCase in an agent file, such as `shortCircuit` and `confidenceThreshold`. Snake\_case keys are dropped without a message. An agent file does not range-check the threshold values. The project runtime configuration does.

For pure routing supervisors, `sequential` mode with `shortCircuit.enabled: true` gives the best cost savings. In `parallel` mode the classifier adds latency protection but no cost savings, since both calls run regardless.

***

## HANDOFF

HANDOFF transfers conversational control from the current agent to another agent, passing context and optionally expecting a return.

> [!NOTE]
>
> When a handoff enters a target agent whose entry point is a REASONING zone (or a scripted flow step), the target begins executing **immediately on entry** — it does not wait for a new user message. This lets a receiving agent act on the forwarded context (see `history`, below) as soon as control transfers.

### Syntax

```yaml expandable=true theme={null}
HANDOFF:
  - TO: Compliance_Officer
    WHEN: sanctions_clear == false
    PRIORITY: 0
    CONTEXT:
      pass: [customer_id, beneficiary_name, amount, sanctions_match_score]
      summary: "Wire flagged during sanctions screening (score: {{sanctions_match_score}})."
      history: full
      memory_grants:
        - path: user.compliance_notes
          access: readwrite
    EXPECT_RETURN: true
    ON_FAILURE: ESCALATE
    ON_RETURN:
      action: continue
      map:
        compliance_decision: sanctions_clear
        review_notes: compliance_review_notes
```

### Properties

| Property | Type | Required | Default | Description |
| - | - | - | - | - |
| `TO` | `string` | Yes | -- | Target agent name. |
| `WHEN` | `string` | Yes | -- | Condition that triggers the handoff. |
| `ENABLED_WHEN` | `string` | No | -- | Condition deciding whether this route exists for the session at all, evaluated once before any turn. See [Availability (ENABLED\_WHEN)](#availability-enabled_when). |
| `PRIORITY` | `number` | No | -- | Evaluation priority. Lower values are evaluated first when multiple handoff rules match. |
| `CONTEXT` | `object` | Yes | -- | Context to pass to the target agent. See [Context](#handoff-context). |
| `EXPECT_RETURN` | `boolean` | Yes | `false` | Whether control should return to this agent after the target completes. `RETURN` is accepted as a backward-compatible alias. |
| `HAND_BACK` | `string` | No | `after_reply` | For a handoff with `EXPECT_RETURN: true`. Decides when a reasoning target with no `COMPLETE` condition hands the customer back: `after_reply` or `when_finished`. See [Handing back](#handing-back-hand_back). |
| `ON_FAILURE` | `string` / `object` | No | -- | Parent-side fallback for setup or dispatch failures **before** the target accepts the handoff. See [Handoff failure strategies](#handoff-failure-strategies). |
| `ON_RETURN` | `string` / `object` | No | -- | How to handle the target returning control. See [Return expectations](#return-expectations). |
| `EXPERIENCE_MODE` | `string` | No | -- | End-user experience when the transfer happens. See [Experience modes](#experience-modes). |
| `REMOTE` | `object` | No | -- | Remote agent configuration. Can also be expressed as top-level `LOCATION`/`ENDPOINT`/`PROTOCOL` keys. See [Remote agent support](#remote-agent-support). |
| `ASYNC` | `boolean` | No | `false` | Use async dispatch with push notifications for remote agents. |
| `TIMEOUT` | `number` | No | `300` | Timeout in seconds for async handoff. The platform caps it at a configured maximum. In YAML, use `async_timeout`. Text ABL ignores an `ASYNC_TIMEOUT` key without a message. |

> [!NOTE]
>
> The primary keyword is **`EXPECT_RETURN`**. The older `RETURN` keyword is still parsed for backward compatibility, but new agents should use `EXPECT_RETURN`. The legacy top-level `MAP` block is superseded by `ON_RETURN.map` (see [Return expectations](#return-expectations)).

### Handoff context

The `CONTEXT` block defines what information the target agent receives.

| Property | Type | Required | Default | Description |
| - | - | - | - | - |
| `pass` | `string[]` | Yes | -- | Session variable names to include in the handoff context. |
| `summary` | `string` | Yes | -- | Human-readable summary of why the handoff is occurring. Supports `{{}}` interpolation. |
| `history` | `string` / `object` | No | `full` | Conversation history strategy. See [History strategies](#history-strategies). |
| `set` | `Record<string,string>` | No | -- | Route-scoped variable assignments applied **before** the target agent is invoked (inject computed values without a separate step). |
| `memory_grants` | `object[]` | No | -- | Persistent memory paths to grant the target agent access to. See [Memory grants](#memory-grants). |

> [!WARNING]
>
> The legacy `grant_memory: [path, ...]` form is **no longer supported** and produces a parse error. Use `memory_grants` with explicit `path`/`access` entries instead (see [Memory grants](#memory-grants)).

`CONTEXT` may also be expressed as a shorthand where `pass`, `summary`, and `history` appear as direct siblings of the handoff entry rather than nested under `CONTEXT:`.

### History strategies

The `history` property controls how much conversation history the target agent receives.

| Value | Behavior |
| - | - |
| `full` | **Platform default** — applied when `history` is omitted. The complete parent conversation history is passed. |
| `auto` | Uses the handoff summary when available; otherwise falls back to a bounded recent transcript (the last 5 messages). |
| `none` | No conversation history is passed. The target agent starts fresh. |
| `summary_only` | Only the `summary` text is passed, no raw messages. |
| `{ mode: last_n, count: <n> }` | The last N messages are passed. |

```yaml theme={null}
CONTEXT:
  pass: [customer_id, amount]
  summary: "Customer needs fraud review."
  history:
    mode: last_n
    count: 10
```

> [!NOTE]
>
> The legacy shorthand `history: last_10` is still accepted during the compatibility window, but new agents should use the typed `mode` + `count` block.

> [!WARNING]
>
> Three forms parse without error and are silently ignored, each falling back to `full`: a single-line flow-mapping value such as `history: { mode: last_n, count: 3 }` (use the indented block shown above instead); an uppercase key inside `CONTEXT:`, such as `HISTORY:` or `PASS:` (keys inside `CONTEXT:` must be lowercase, unlike the handoff entry's own `TO:` / `WHEN:` keys); and a misspelled value, such as `history: recent`. Check the Request view of the target agent's first LLM step (see [LLM step request and response](https://koreai.mintlify.site/agent-platform/sessions.md#llm-step-request-and-response)) if the history you expect isn't showing up.

### Return expectations

When `EXPECT_RETURN: true`, the calling agent pauses and waits for the target agent to complete.
When the target explicitly returns control (via its built-in return capability), the parent resumes.
When `EXPECT_RETURN: false`, the handoff is a one-way transfer and the calling agent's turn ends — the parent does not automatically get control back.

> [!NOTE]
>
> `EXPECT_RETURN: false` disables *automatic* return, not every path back. If the child agent (while that same nested handoff call is still unwinding) itself authors a `HANDOFF` route back to that exact direct parent, and the route is otherwise authorized, Runtime resumes the parent's completed thread as the conversation owner — it does not re-enable automatic returns, and it does not make any *other* completed ancestor resumable. For a FLOW child, this only applies while its authored FLOW is still live; once the child reaches `COMPLETE`, that parent frame is closed for good. Routes to an unrelated or non-direct ancestor remain blocked as a cycle.

A queued request that targets a FLOW step belongs to the agent activation that queued it. Only that activation runs it or offers it. If that agent completes or returns to its parent before the step runs, the runtime removes the request and records a `multi_intent_queue_retired` trace. The parent never runs or offers the step. If that agent is paused while another agent has the conversation, its queued steps stay queued until it resumes. Requests that target an agent are not affected. See [Multi-intent handling](https://koreai.mintlify.site/agent-platform/abl/reference/nlu.md#multi-intent-handling-multi_intent).

### Handing back (`HAND_BACK`)

A target reached with `EXPECT_RETURN: true` normally decides when it is done: a `COMPLETE` condition, a FLOW that finishes, or a return to the parent. A target with none of these runs on reasoning alone. It has no `COMPLETE`, no domain tools, and no required `GATHER` field. The runtime hands the customer back as soon as such a target shows a reply. `HAND_BACK` sets what "done" means for that target, for each handoff.

| Value | The target hands the customer back |
| - | - |
| `after_reply` (default) | After any reply. The same applies when `HAND_BACK` is not written. |
| `when_finished` | After a reply that finishes the customer's request. A reply that still waits on the customer, such as a question, keeps the target in control. The customer's answer then reaches the agent that asked. |

```yaml theme={null}
HANDOFF:
  - TO: TransfersStatus
    WHEN: intent.category == "transfers"
    EXPECT_RETURN: true
    HAND_BACK: when_finished
    ON_RETURN:
      action: continue
```

With `when_finished`, TransfersStatus can ask "Has it been more than 24 hours since the payment?" and keep the conversation. The customer's "yes" goes to TransfersStatus, and its answer hands the customer back. With `after_reply`, the question hands the customer back at once, and the "yes" reaches the supervisor.

* **How the runtime judges a reply.** It makes one small model call on the target's own model binding. The call asks whether the reply finished the customer's latest message or still waits on the customer. It runs only for a `when_finished` handoff, only on a reply that would otherwise hand back, and at most once per reply.
* **A reply that cannot be judged hands back.** This covers no model, an open classifier circuit, a timeout, an unreadable verdict, and an interrupted turn. The trace records `handoff_return_backstop_hand_back_unjudged`. A reply that the judgement keeps records `handoff_return_backstop_withheld`.
* **What it does not change.** A target with a `COMPLETE` condition, a FLOW, domain tools, a required `GATHER` field, or a pending input keeps its own completion rules. The same applies to a handoff whose `ON_RETURN` is `resume_intent`. The completion rules of a multi-intent plan decide before `HAND_BACK`. A return to the parent still works at any time. Realtime speech-to-speech targets do not use this rule.
* **When it takes effect.** A session already inside the target keeps the handoff it entered with. A changed `HAND_BACK` applies from the next handoff.
* **Diagnostics.** An unknown value is ignored, and the handoff keeps `after_reply` ([`W324`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#w324)). `HAND_BACK` on a handoff without `EXPECT_RETURN: true` has no effect ([`W325`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#w325)).

`ON_RETURN` controls what happens when the target returns. It accepts either a **string** (the name of a named return handler, or a built-in action) or a **structured block**:

```yaml expandable=true theme={null}
HANDOFF:
  - TO: Authentication_Agent
    WHEN: user.is_authenticated == false
    CONTEXT:
      pass: [session_context]
      summary: "User needs authentication"
    EXPECT_RETURN: true
    ON_RETURN:
      action: continue          # continue | resume_intent
      handler: route_to_booking # optional: named RETURN_HANDLERS entry
      resume_with: latest_session_user_utterance
      map:                      # child result field -> parent variable
        user_id: auth_result.user_id
        auth_token: auth_result.token
      set:                      # parent assignments after mapping
        auth_summary: "Authenticated {{auth_result.user_id}}"
```

#### `ON_RETURN` properties

| Property | Type | Description |
| - | - | - |
| `action` | `string` | Built-in resume behavior: `continue` (resume the parent's current flow) or `resume_intent` (re-run routing against the original user intent with the returned context). |
| `handler` | `string` | Name of a [named return handler](#return-handlers) declared in the top-level `RETURN_HANDLERS:` block. |
| `resume_with` | `string` | Which utterance to replay when resuming. One of `original_handoff_utterance`, `latest_child_user_utterance`, `latest_session_user_utterance`, `forwarded_return_message`. |
| `map` | `Record<string,string>` | Copies child return fields into parent variables (child key → parent variable). |
| `set` | `Record<string,string>` | Parent assignments applied after `map`, using the same templated assignment shape as flow `ON_RESULT` branches. |

### Return handlers

A top-level `RETURN_HANDLERS:` block declares reusable named handlers that run on the parent after a `EXPECT_RETURN: true` child returns. Reference one from `ON_RETURN.handler`.

```yaml theme={null}
RETURN_HANDLERS:
  route_to_booking:
    RESPOND: "You're verified — let's finish your booking."
    CLEAR: [pending_auth_reason]
    CONTINUE: true          # leave the parent waiting for the next user turn
    # RESUME_INTENT: true   # or replay the parent's last user message
```

| Property | Type | Description |
| - | - | - |
| `RESPOND` | `string` | Message to send when the handler runs. |
| `CLEAR` | `string[]` | Session variables to reset after the child returns. |
| `CONTINUE` | `boolean` | Leave the parent waiting for the next user turn. |
| `RESUME_INTENT` | `boolean` | Replay the parent's last user message through routing. |

A handler runs `CLEAR` before `map`, and `RESPOND` after `set`. If any `CLEAR`, `map`, or `set` target is one the parent cannot write, the runtime applies none of that return's effects, including `RESPOND`.

The parent's `ON_RETURN` also runs when a child completes on a silence route turn, that is, after the caller's silence retries run out. From 1.9.1 the `map`, handler, and resume behavior apply the same way as when the child completes on a caller answer.

For a reasoning parent without a FLOW, a non-blank forwarded customer request belongs to bounded `continue`. This includes a named handler with `CONTINUE: true`.

* The handler runs once. Completion and deterministic routing come before model-based routing.
* Within the forwarded continuation's own deterministic coordination chain, the runtime dispatches each authored `DELEGATE` entry automatically by `WHEN` at most once, even if `WHEN` stays true. Nested ordinary continuations keep their earlier dispatch policy. Explicit model-selected delegation stays eligible. Distinct same-target entries keep their own input and result mappings.
* The parent can synthesize successful typed results. Later customer turns can select the entries again.
* The returned child keeps its waiting state and cannot block its own forwarded request. Other pending children keep their waiting-work protection while they still hold open work: pending input, an unfilled required `GATHER` field, or pending actions. They also keep it while the parent's interrupted-child resume can still resume them on this turn. A child with no open work, parked by its own hand-back on an earlier turn, does not block the forwarded request.
* A return without an authoritative forwarded request keeps the existing continuation policy.

### Handoff failure strategies

`ON_FAILURE` defines a parent-side fallback for failures that occur **before** the target accepts the handoff — for example target lookup, pre-transfer validation, or dispatch failures. It does not replace the timeout path after an accepted returnable handoff, and it does not fire when a downstream child later reports its own failure.

```yaml theme={null}
HANDOFF:
  - TO: Specialist_Agent
    WHEN: needs_specialist == true
    CONTEXT:
      pass: [user_id, query]
      summary: "User needs specialist help"
    ON_FAILURE: ESCALATE          # CONTINUE | ESCALATE | RESPOND "message"
```

| Value | Behavior |
| - | - |
| `CONTINUE` | Silently continue in the current agent. |
| `ESCALATE` | Trigger human escalation. |
| `RESPOND "message"` | Send a message and continue in the current agent. |

### Experience modes

`EXPERIENCE_MODE` shapes how the transfer is presented to the end user. It is valid on both `HANDOFF` and `DELEGATE`.

| Value | Behavior |
| - | - |
| `shared_voice_handoff` | Voice channels — hand off while keeping a single shared voice experience. |
| `visible_handoff` | The user is told the conversation is being transferred. |
| `silent_delegate` | The sub-agent runs without a user-visible transfer. |
| `human_escalation` | Present the transfer as an escalation to a human. |

### Async dispatch

For remote agents, set `ASYNC: true` to dispatch the handoff asynchronously. The calling agent receives a notification when the remote agent completes rather than blocking.

```yaml expandable=true theme={null}
HANDOFF:
  - TO: External_Review
    WHEN: requires_external_review == true
    CONTEXT:
      pass: [case_id, documents]
      summary: "Documents require external review."
    EXPECT_RETURN: true
    REMOTE:
      location: remote
      endpoint: "https://review.partner.com/api/v1/submit"
      protocol: a2a
    ASYNC: true
    TIMEOUT: 3600
```

### Memory grants

Use `memory_grants` to give the target agent scoped access to specific persistent memory paths. Without this, the target agent cannot read or write the parent's persistent variables. Each grant declares a `path` and an `access` level.

```yaml expandable=true theme={null}
CONTEXT:
  pass: [user_id, booking_reference]
  summary: "User needs to authenticate to manage booking."
  memory_grants:
    - path: user.last_verified_at
      access: read
    - path: workflow.auth_token
      access: readwrite
```

| Property | Type | Required | Default | Description |
| - | - | - | - | - |
| `path` | `string` | Yes | -- | Persistent memory path being granted. |
| `access` | `string` | No | `read` | Access level: `read` or `readwrite`. |

***

## DELEGATE

DELEGATE invokes a sub-agent synchronously, waits for it to complete, and maps the result back into the calling agent's context. The sub-agent runs in its own scope and does not have direct access to the parent's session variables.

> [!WARNING]
>
> **Breaking changes in this release - Artemis 1.4.0:**
>
> * `DELEGATE` may only be declared by an [`orchestrator`](#execution-roles). A `router` or
>   `assistant` that uses `DELEGATE` fails compilation.
> * `DELEGATE` is a one-shot internal call — it cannot wait for multi-turn user input. If the target
>   agent has **required** `GATHER` fields, you must supply them in `INPUT:` (or make them
>   optional/defaulted). An unmapped required field fails compilation
>   ([`DELEGATE_CHILD_GATHER_INPUT_UNMAPPED`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#delegate_child_gather_input_unmapped)); model a user-interactive child as an
>   `EXPECT_RETURN: true` `HANDOFF` instead.

### Syntax

```yaml expandable=true theme={null}
DELEGATE:
  - AGENT: Sanctions_Screening
    WHEN: beneficiary_name IS SET AND beneficiary_country IS SET
    PURPOSE: "Screen beneficiary against OFAC SDN and EU sanctions lists"
    INPUT:
      name: beneficiary_name
      account: beneficiary_account
      country: beneficiary_country
    RETURNS:
      cleared: sanctions_clear
      match_score: sanctions_match_score
    USE_RESULT: "Block if match_score > 85. Proceed only if cleared."
    TIMEOUT: "15s"
    ON_FAIL: escalate
```

### Properties

| Property | Type | Required | Default | Description |
| - | - | - | - | - |
| `AGENT` | `string` | Yes | -- | Name of the sub-agent to invoke. `TO` is accepted as an alias. |
| `WHEN` | `string` | Yes | -- | Condition that must be true for delegation to occur. |
| `ENABLED_WHEN` | `string` | No | -- | Condition deciding whether this route exists for the session at all, evaluated once before any turn. See [Availability (ENABLED\_WHEN)](#availability-enabled_when). |
| `PURPOSE` | `string` | Yes | -- | Description of why this delegation exists. Included in trace events. `SUMMARY` is accepted as an alias. |
| `INPUT` | `Record<string,string>` | Yes | -- | Input mapping. Keys are sub-agent parameter names; values are expressions from the parent's context. `PASS` is accepted as an alias. |
| `RETURNS` | `Record<string,string>` | Yes | -- | Output mapping. Keys are sub-agent result fields; values are parent context variable names to write to. |
| `USE_RESULT` | `string` | Yes | -- | Instructions for interpreting the sub-agent's result. |
| `MEMORY_GRANTS` | `object[]` | No | -- | Persistent memory paths to grant the sub-agent, each with `path` and `access` (`read` / `readwrite`). Same shape as [handoff memory grants](#memory-grants). |
| `TIMEOUT` | `string` | No | -- | Maximum time to wait for the sub-agent. Format: `"Ns"` (seconds). |
| `ON_FAIL` | `string`, `object` | No | -- | Action when the sub-agent fails or times out. See [Failure strategies](#delegate-failure-strategies). |
| `EXPERIENCE_MODE` | `string` | No | -- | End-user experience for the delegation. See [Experience modes](#experience-modes). |
| `REMOTE` | `object` | No | -- | Remote agent configuration. Can also be given as top-level `LOCATION`/`ENDPOINT`/`PROTOCOL` keys. See [Remote agent support](#remote-agent-support). |
| `FAILURE_MESSAGE` | `string` | No | -- | Message to display when delegation fails. |

### Input/output mapping

The `INPUT` block maps values from the parent agent's session context into the sub-agent's input parameters:

```yaml theme={null}
INPUT:
  name: beneficiary_name          # parent's beneficiary_name -> sub-agent's "name" parameter
  account: beneficiary_account
  amount: amount
```

The `RETURNS` block maps the sub-agent's result fields back into the parent's session variables:

```yaml theme={null}
RETURNS:
  cleared: sanctions_clear        # sub-agent's "cleared" field -> parent's sanctions_clear
  match_score: sanctions_match_score
```

### Delegate failure strategies

| Value | Behavior |
| - | - |
| `respond` | Send a message and continue. Requires `FAILURE_MESSAGE`. |
| `continue` | Silently continue without the sub-agent's result. |
| `escalate` | Trigger human escalation. |
| `retry` | Retry the delegation. Accepts a `count` for max retries. |

Structured failure example:

```yaml theme={null}
ON_FAIL:
  type: retry
  count: 2
```

### Remote agent support

DELEGATE supports invoking agents running on remote services. Add a `REMOTE` block to configure the connection.

```yaml expandable=true theme={null}
DELEGATE:
  - AGENT: External_Compliance
    WHEN: amount > 10000
    PURPOSE: "External compliance check for high-value transfers"
    INPUT:
      transaction_id: wire_reference
      amount: amount
    RETURNS:
      approved: compliance_approved
    USE_RESULT: "Proceed only if approved."
    REMOTE:
      location: remote
      endpoint: "https://compliance.partner.com/api/v1/check"
      protocol: a2a
      auth:
        type: bearer
      timeout: "30s"
```

#### Remote properties

| Property | Type | Required | Default | Description |
| - | - | - | - | - |
| `location` | `local`, `remote` | No | `local` | Whether the agent is co-located or remote. |
| `endpoint` | `string` | No | -- | URL for remote agent invocation. |
| `protocol` | `a2a` , `rest` | No | -- | Communication protocol. `a2a` for Agent-to-Agent, `rest` for REST API. |
| `auth` | `object` | No | -- | Authentication configuration. `type` is `bearer` or `api_key`; an optional `header` names the header to carry the credential. Credential values are resolved from runtime config / auth-profile resolution — never inlined in ABL. |
| `timeout` | `string` | No | -- | Override timeout for the remote call. |

A remote agent's credentials never live in the ABL file. The project's external agent registry record holds them. The record either references an Auth Profile through `authProfileId`, or stores inline `authType` (`bearer`, `api_key`, or `none`) plus an `authConfig` reference to the project secret. When `authProfileId` is set, it takes precedence and the runtime ignores inline auth.

* Header-rendering profiles add headers to the outgoing request. These are bearer, header API key, basic, custom header, OAuth client credentials, OAuth app and token grants, and Azure AD.
* An `aws_iam` profile makes the runtime SigV4-sign every request to the agent. In Assume role mode (`credentialMode: assume_role`, recommended), the runtime assumes the customer's IAM role. In Access keys mode (`credentialMode: static_keys`), it signs with the stored keys. Use access keys where the runtime has no AWS workload identity.
* AWS credential-pair, mTLS, query-parameter API key, and personal profiles are rejected.

Rotating a credential is a registry or profile update, not an agent edit.

> [!NOTE]
>
> `LOCATION: remote` is explicit and recommended, but the compiler also treats an `ENDPOINT` without `LOCATION` as remote. The remote block can be authored either nested under `REMOTE:` or as top-level `LOCATION`/`ENDPOINT`/`PROTOCOL` keys on the entry.

### Availability (`ENABLED_WHEN`)

`ENABLED_WHEN` turns a `HANDOFF` or `DELEGATE` route on or off for the whole session, decided once before any turn is understood. `WHEN` still decides which available route a given turn takes — `ENABLED_WHEN` decides which routes exist at all:

```yaml theme={null}
INTENTS:
  vehicles: "The customer is looking for automotive options."
  products: "The customer is looking for product options."

HANDOFF:
  - TO: Automotive_Search
    WHEN: intent.category == "vehicles"
    ENABLED_WHEN: _metadata.country != "SGP"
    ON_FAILURE: RESPOND "Vehicle search is not offered in your region."
  - TO: Product_Search
    WHEN: intent.category == "products"
```

**Writing the condition.** Put `ENABLED_WHEN:` on the entry, after `WHEN:` (YAML key: `enabled_when`). Read only session data known before the turn: `_metadata.*`, `env.*`, `caller.*`, `session.*`, `user.*`, and memory fields. Don't read what the current turn means (`intent`, `routing.*`, `input`) or write natural language — both are compile errors ([`ENABLED_WHEN_SEMANTIC_REFERENCE`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#enabled_when_semantic_reference)). A long condition can continue on deeper-indented lines, after an inline value, an empty value, or a block indicator (`|`, `>`, `>-`); a line that looks like a key or starts a new entry ends it, and `#` lines are comments. The compiler warns ([`ROUTE_WHEN_MULTILINE_JOINED`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#route_when_multiline_joined)) when it joins lines written after an inline or empty value; a condition opened with a block indicator is joined without the warning.

**How availability is decided.** Each target is judged by its own entries: a `HANDOFF` to X by the `HANDOFF` entries for X, a `DELEGATE` to X by the `DELEGATE` entries for X. The target is available when *any* of its entries is enabled — an entry without `ENABLED_WHEN` is always enabled, so one unconditional entry keeps the target permanently available (the compiler warns, [`ENABLED_WHEN_SHADOWED_BY_UNCONDITIONAL_ENTRY`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#enabled_when_shadowed_by_unconditional_entry)).

The decision **fails closed**: a condition that can't be evaluated disables the entry, and so does one that reads a value the session doesn't have (unset, `null`, or an empty string) — even inside `OR` — *unless* the condition explicitly allows that value to be missing. A value compared with `== null`, `!= true`, or `IS NOT SET` anywhere in the condition counts as known, and an unset value then reads as `null`:

```yaml theme={null}
ENABLED_WHEN: _metadata.restricted != true   # enabled when the caller sends nothing
ENABLED_WHEN: _metadata.country != "SGP"     # disabled when country is missing
ENABLED_WHEN: _metadata.region IS NOT SET OR _metadata.region != "EU"   # guard explicitly
```

`_metadata` changes made during the session apply to every agent in the conversation, including agents waiting for a child to return.

**When a target isn't available.** The route is withheld from the model entirely — left out of prompt route lists in both text and voice. A model that calls it anyway is refused and told which routes are available. A route the *author* wrote (a FLOW step `HANDOFF`, `ON_ACTION`, a digression, a tool hook, `ON_ERROR`, an `ON_START` handoff) is refused and runs its own failure policy: the entry's `ON_FAILURE` for a handoff, the delegate's `ON_FAILURE` for a delegate. `RESPOND` shows its message, `ESCALATE` escalates the same turn, `CONTINUE` skips the route and runs the rest of the step. A handoff with no `ON_FAILURE` tells the user the option isn't available and the agent stays on its current step; a delegate with no `ON_FAILURE` is simply skipped — a refused route never leaves a turn without an answer. A constraint's `ON_FAIL`/`ON_EXHAUSTED` handoff is a safety route that must always be reachable, so its target can't be fully conditional: the compiler rejects one whose every `HANDOFF` entry has `ENABLED_WHEN` ([`ENABLED_WHEN_SAFETY_ROUTE_CONDITIONAL`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#enabled_when_safety_route_conditional)). When every route of an agent is unavailable, the agent answers the user directly.

**Diagnostics**

| Code | Severity | Meaning |
| - | - | - |
| [`ENABLED_WHEN_EMPTY`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#enabled_when_empty) | error | `ENABLED_WHEN` has no condition. |
| [`ENABLED_WHEN_LINE_COMMENT`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#enabled_when_line_comment) | error | A YAML `enabled_when` read as one line carries a `//` comment (use `#`, or a literal block). |
| `ROUTE_WHEN_MULTILINE_JOINED` | warning | A condition without a block indicator was read from several lines. |
| `ENABLED_WHEN_SEMANTIC_REFERENCE` | error | The condition reads turn meaning, or is natural language. |
| [`INVALID_CEL_SYNTAX`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#invalid_cel_syntax) | error | The condition isn't a valid expression. |
| [`ENABLED_WHEN_ALL_DISABLED_RISK`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#enabled_when_all_disabled_risk) | warning | Every route of a routing agent is conditional. |
| `ENABLED_WHEN_SHADOWED_BY_UNCONDITIONAL_ENTRY` | warning | A target has entries both with and without `ENABLED_WHEN`. |
| [`ENABLED_WHEN_AUTHORED_ROUTE_NO_FALLBACK`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#enabled_when_authored_route_no_fallback) | warning | An authored route targets a conditional handoff with no `ON_FAILURE`. |
| `ENABLED_WHEN_SAFETY_ROUTE_CONDITIONAL` | error | A constraint `ON_FAIL`/`ON_EXHAUSTED` handoff targets a fully conditional handoff. |
| [`ENABLED_WHEN_ON_START_UNSTABLE_DATA`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#enabled_when_on_start_unstable_data) | warning | An `ON_START` delegate's condition reads data that may not exist yet at session start. |

> [!WARNING]
>
> `_metadata` is supplied by the caller. Use `ENABLED_WHEN` to shape the experience, not as an authorization boundary. Availability is always enforced — there's no runtime setting that turns it off, and an entry without `ENABLED_WHEN` behaves exactly as before this feature existed. The trace records which routes were offered and withheld on each model turn, and every refusal, with the condition text — never the session values it evaluated.

***

## Parallel delegation (fan-out)

> [!NOTE]
>
> There is no `FAN_OUT:` section in ABL. Fan-out is a runtime capability, not an authored construct — agents do not declare it directly.

When a single user message contains **multiple distinct requests** that need different specialists, a supervisor's runtime can dispatch them in parallel and then synthesize the branch results into one unified response. This is exposed to the reasoning model as a built-in `__fan_out__` system tool (you never write this tool yourself) and is bounded to **2–5 sub-tasks** per message.

Separately, when multiple `DELEGATE` entries have their `WHEN` conditions satisfied on the same turn, the runtime can run those delegations concurrently. Each delegation runs in its own scope and its `RETURNS` are mapped back into the parent context as it completes.

```yaml expandable=true theme={null}
DELEGATE:
  - AGENT: Sanctions_Screening
    WHEN: beneficiary_name IS SET
    PURPOSE: "Screen beneficiary"
    INPUT:
      name: beneficiary_name
    RETURNS:
      cleared: sanctions_clear

  - AGENT: Fraud_Detection
    WHEN: amount IS SET
    PURPOSE: "Score fraud risk"
    INPUT:
      amount: amount
      account: source_account
    RETURNS:
      score: fraud_score
```

***

## ESCALATE

ESCALATE transfers the conversation to a human operator. It is designed for situations where the agent cannot or should not continue autonomously.

### Syntax

```yaml expandable=true theme={null}
ESCALATE:
  triggers:
    - WHEN: sanctions_screening_unavailable == true AND retry_count >= 2
      REASON: "Sanctions screening service down. Compliance check cannot be bypassed."
      PRIORITY: critical
      TAGS: [compliance, service_outage]

    - WHEN: user.wants_human_agent == true
      REASON: "Customer requesting human specialist."
      PRIORITY: medium
      TAGS: [human_request]

  context_for_human:
    - customer_id
    - customer_name
    - amount
    - conversation_history

  routing:
    connection: livechat
    queue: "wire_operations_l2"
    skills: [wire_transfer, compliance]
    priority: 1
    voice:                            # voice-channel transfer settings (see below)
      transfer_method: refer
      call_transfer_type: sip
      sip_headers:
        X-Escalation-Reason: "sanctions_review"

  on_human_complete:
    - IF human.resolved == true: COMPLETE
    - IF human.needs_agent == true: HANDOFF to specified_agent

  CONNECTOR_ACTION: create_servicenow_incident
```

### Trigger properties

| Property | Type | Required | Default | Description |
| - | - | - | - | - |
| `WHEN` | `string` | Yes | -- | Condition that triggers escalation. |
| `REASON` | `string` | Yes | -- | Human-readable reason for the escalation. |
| `PRIORITY` | `string` / `number` | No | `medium` | Priority level: `low`, `medium`, `high`, `critical`, or a non-negative integer. |
| `TAGS` | `string[]` | No | -- | Tags for routing and categorization in the human agent queue. |
| `SET` | `Record<string,string>` | No | -- | Session variable assignments applied when this trigger fires (`key = value`). |
| `GENESYS_SIP_HEADERS` | `object` | No | -- | Per-trigger override of the Genesys SIP transfer headers attached when this escalation transfers a voice call. See [Genesys SIP transfer headers](#genesys-sip-transfer-headers). |

> [!NOTE]
>
> `PRIORITY` is optional and defaults to `medium`. Note that `ESCALATE` inside an `ON_ERROR` handler is **not** parsed — to escalate from an error handler use `THEN: ESCALATE with REASON: "..."` instead of an inline `ESCALATE:` block.

### Connector action

`CONNECTOR_ACTION` names a connector action to invoke for ITSM integration when the escalation fires (for example, opening an incident in an external ticketing system). It is declared at the top level of the `ESCALATE` block, alongside `triggers`, `context_for_human`, `routing`, and `on_human_complete`.

### Priority levels

| Level | Use case |
| - | - |
| `low` | Non-urgent requests (for example. general feedback). |
| `medium` | Standard requests (for example. customer asks to speak with a human). |
| `high` | Urgent issues (for example. service outages, repeated failures). |
| `critical` | Immediate attention required (for example. compliance violations, fraud). |

### Context for human

The `context_for_human` block lists session variable names to include in the escalation package. The human agent sees these values in their interface.

```yaml theme={null}
context_for_human:
  - customer_id
  - customer_name
  - source_account
  - amount
  - fraud_score
  - conversation_history
```

You can also use structured context items with templates:

```yaml theme={null}
context_for_human:
  - NAME: case_summary
    TEMPLATE: "Customer {{customer_name}} requesting wire of {{amount}} {{currency}}"
    INCLUDE: [fraud_score, sanctions_match_score]
```

### Routing configuration

The `routing` block controls how the escalation is routed in the human agent system.

| Property | Type | Required | Default | Description |
| - | - | - | - | - |
| `connection` | `string` | No | -- | Human-agent connection/channel to route through. |
| `queue` | `string` | No | -- | Target queue name in the human agent system. |
| `skills` | `string[]` | No | -- | Required skills for the human agent. |
| `priority` | `number` | No | -- | Numeric routing priority for the queue entry. |
| `post_agent` | `string` | No | -- | What happens after the human agent finishes: `return` or `end`. |
| `voice` | `object` | No | -- | Voice-channel transfer settings — how the live call leg is handed off at the SIP/transport layer. See [Voice transfer settings](#voice-transfer-settings). |

> [!NOTE]
>
> Earlier drafts used `skill_tags` and `priority_boost`. The current runtime contract uses `skills` and `priority` — the older keys are silently ignored. The `routing` block also accepts several [advanced routing keys](#advanced-routing-keys) for richer human-agent integrations.

#### Conditional routing entries

`routing:` accepts two shapes, distinguished purely by what follows the colon:

* A **mapping** (`routing: { connection: ..., queue: ..., ... }`, as above) — a single, unconditional destination. This is the legacy, still-supported form.
* A **YAML sequence** (a list of `-`-prefixed entries) — an **ordered list of conditional routing entries**, each with the same fields as the single form plus `id` and `when`. When authored as a list, `routing` itself is left unset and the entries compile into `routing_entries` instead.

```yaml theme={null}
ESCALATE:
  triggers:
    - WHEN: intent.category == "human_escalation"
      REASON: "Caller requested a live agent"
      PRIORITY: high

  routing:
    - id: whatsapp
      WHEN: system.channel == "whatsapp"
      connection: "Genesys Agent Transfer"

    - id: voice_es
      WHEN: system.channel == "voice" && system.locale == "es"
      voice:
        call_transfer_type: sip
        transfer_method: refer
        sip_transfer_id: "sip:es_billing_queue@sbc.example.com"

    - id: fallback
      WHEN: always
      connection: "Default Queue"
```

| Field | Type | Description |
| - | - | - |
| `id` | `string` | Optional label for authoring/observability. Defaults to `entry_<index>` if omitted. |
| `when` | `string` | Condition selecting this entry, in the same deterministic expression grammar as trigger `WHEN` clauses (comparisons, `AND`/`OR`/`NOT`, `IS [NOT] SET`, `has(...)`, `abl.<fn>(...)`) — **not** free text. `WHEN` (uppercase) is also accepted. Omit, or use `always` / `*`, for the unconditional default entry. |

Every other field (`connection`, `queue`, `skills`, `priority`, `post_agent`, `voice`, and all the [advanced routing keys](#advanced-routing-keys)) means exactly the same thing per entry as it does in the single-object form.

> [!NOTE]
>
> A routing entry's `when` must be **deterministic** — it's evaluated in code against session data and the reserved `system.*` values (`system.channel`, `system.locale`, and similar), never deferred to the model. This is stricter than a trigger's `WHEN`, which may be prompt-only/semantic: a condition that's valid on a `triggers.WHEN` but isn't deterministic is a **compile-time error** on a routing entry (`ESCALATE_ROUTING_WHEN_PROMPT_ONLY`) — a live transfer destination can never depend on model judgment.

**Evaluation is first-match-wins, in authored order.** The compiler enforces the entry list's shape:

| Rule | Enforcement |
| - | - |
| At most one unconditional (default) entry | More than one entry with no `when` (or `always`/`*`) is a compile error. |
| A default entry, if present, must be last | A default entry followed by other entries is a compile error — those entries would be unreachable. |
| No entry is required to match | A list with no default entry is valid; this isn't a compile-time exhaustiveness check. If none of the entries' conditions match at runtime, routing **fails closed**: no connector or voice transfer is attempted (the escalation's `HumanTask`/HITL fallback still stands). List-form routing never falls back to the project's `agentTransfer.defaultRouting` connection — that backstop applies only to the legacy single-object `routing:` form. To reach the project default from a list, author an explicit trailing default entry (omit `when`, or use `when: always`) with your own `connection`/`voice`. |

> [!NOTE]
>
> An entry whose `WHEN` guards `system.channel == "voice"` without a `voice:` block, or guards a non-voice channel without a `connection`, gets an advisory (non-blocking) warning — worth checking, since a matched entry with neither is unlikely to route anywhere useful.

##### `sip_transfer_id`

A voice routing entry (or the legacy single `routing.voice` block) may declare an explicit SIP transfer destination directly in the DSL with `sip_transfer_id` — a literal or `{{ }}`-templated SIP URI:

```yaml theme={null}
voice:
  call_transfer_type: sip
  sip_transfer_id: "sip:{{escalation_skill}}@sbc.example.com"
```

This requires `call_transfer_type: sip` — declaring `sip_transfer_id` under `pstn` or `custom` is a compile error (PSTN transfers always use the project's PSTN transfer target, not a SIP transfer id). The compiler **always** stamps the resulting destination's provenance as `config` itself — an authored `sip_transfer_id_source` value is discarded and never trusted verbatim, the same trust posture as the `call_transfer` tool's `default_source: config` gate. Omit `sip_transfer_id` to keep today's behavior: the transfer target comes from the project-configured Agent Transfer settings.

#### Advanced routing keys

Beyond `connection` / `queue` / `skills` / `priority`, the `routing` block accepts additional keys for richer human-agent (contact center) integrations. Some are structured; others (`flow_policy`, `provider_config`, `metadata`) are **opaque pass-throughs** whose shape is defined by the receiving human-agent integration rather than validated by the ABL compiler. Every key accepts `snake_case` or `camelCase`.

```yaml expandable=true theme={null}
ESCALATE:
  routing:
    connection: livechat
    queue: "wire_operations_l2"
    skills: [wire_transfer, compliance]
    priority: 1

    # Route to specific named human agents, optionally waiting for one to be free
    named_agents: ["jane.doe", "john.smith"]
    named_agent_options:
      wait_for_agent: true
      wait_duration_seconds: 120

    # Constrain which agents may pick up the conversation
    agent_matching_conditions:
      skills: [wire_transfer]
      skill_groups: [compliance_l2]
      agent_groups: [emea_desk]

    # Provider-defined routing sub-type and adapter configuration
    sub_type: "priority_callback"
    provider_config:
      campaign_id: "Q3-collections"
      disposition_required: true

    # Wait / no-agent behavior, declared in a TRANSFER_FLOW_POLICIES block
    flow_policy_ref: standard_wait

    # Opaque key-value pairs forwarded on the transfer payload's metadata
    metadata:
      case_id: "{{case_id}}"
      segment: "gold"
  triggers:
    - WHEN: user.wants_human_agent == true
      REASON: "User requested human support"
      PRIORITY: high
```

| Key | Type | Description |
| - | - | - |
| `sub_type` | `string` | Provider-defined routing sub-type / channel hint for the human-agent system. |
| `named_agents` | `string[]` | Request specific human agents by name or id. |
| `named_agent_options` | `object` | Options that apply when `named_agents` is set: `wait_for_agent` (`boolean`) and `wait_duration_seconds` (`number`). |
| `agent_matching_conditions` | `object` | Constrain who may receive the transfer: `skills`, `skill_groups`, and `agent_groups` (each `string[]`). |
| `flow_policy_ref` / `transfer_flow_policy_ref` | `string` | Name of a policy declared in a `TRANSFER_FLOW_POLICIES:` block that governs wait / no-agent behavior. See [Transfer flow policies](#transfer-flow-policies). |
| `flow_policy` / `transfer_flow_policy` | `object` | The same policy authored **inline** instead of by reference. Free-form; shape defined by the integration. |
| `provider_config` | `object` | Opaque provider-specific adapter configuration. Shape defined by the human-agent integration, not the ABL parser. |
| `metadata` | `object` | Opaque key-value pairs delivered with the escalation on the transfer payload's metadata. Supports `{{ }}` interpolation. Reserved keys (`reason`, `priority`, flow policy) are always set by the runtime and cannot be overridden here. For CCAI, the values travel in `customData` for AI for Service flow routing. |
| `user_info` | `map<label, scalar or template>` | Display context for the human agent. Use it with CCAI `webhook_channel` connections only. See [Handoff context for CCAI](#handoff-context-for-ccai). |
| `user_info_in_custom_data` | `boolean` | Default `false`. When `true`, also copies the surviving `user_info` values to `customData.userInfo`. |

> [!NOTE]
>
> These keys are hints for the receiving human-agent system — the valid `sub_type` values, `provider_config` shape, and inline `flow_policy` structure are defined by that integration, not the ABL compiler. Voice-channel transfer settings live under `routing.voice` (see [Voice transfer settings](#voice-transfer-settings)).

#### Handoff context for CCAI

A routing object, or each conditional routing entry, can declare `user_info` as a map of display labels to scalar literals or `{{...}}` templates. Use it only for CCAI `webhook_channel` connections. Select the connection by its connector name or connection ID, not its display name. The camelCase aliases `userInfo` and `userInfoInCustomData` are also accepted.

* A `null` member is valid. The runtime drops it.
* An object or array member is a compile error (`ESCALATE_ROUTING_USER_INFO_NON_SCALAR`). A `user_info` value that is not a map is also a compile error (`ESCALATE_ROUTING_USER_INFO_NOT_MAP`).
* An empty map (`user_info: {}`) is still an explicit opt-in.
* By default the values are display context only. Set `user_info_in_custom_data: true` to copy the surviving values into `customData.userInfo`. The flag applies per entry. A flag without a `user_info` map produces the warning `ESCALATE_ROUTING_USER_INFO_COPY_WITHOUT_USER_INFO`.
* A transfer with handoff context replaces the AI for Service user's `UserContext.customData`. Do not rely on existing custom data being merged.
* The values are a snapshot taken when the transfer starts. AI for Service flows that route on time-sensitive values should compare `customData.artemis.updatedAt` with the queue time. Gate priority or other sensitive routing on `customData.artemis.identityVerified`.
* When a template directly references a `SENSITIVE: true` field or entity, the compiler warns. Mask the value at the source, for example by having the CRM tool return the masked value.
* With PII redaction on (the default in staging and production), a `user_info` value that contains a vault token is sent as `[protected]`. `metadata` values, including vault tokens, are forwarded as stored.
* AI for Service stores `customData` unencrypted for up to 24 hours. Send only the values its flows need. For metadata keys that AI for Service flows address by path, use letters, digits, `_`, and `-`.

Republish agents after you upgrade so the compiled IR includes `user_info`. Agents compiled before the release do not contain it.

```yaml theme={null}
ESCALATE:
  triggers:
    - WHEN: caller.requests_human == true
      REASON: "Caller requested an agent"
      PRIORITY: high
  routing:
    connection: smartassist # connector name or connection ID, not display name
    user_info:
      firstName: "{{masked_first_name}}"
      segment: "{{crm.segment}}"
      optional_value: null
    user_info_in_custom_data: true
```

#### Handoff language

The first CCAI call carries the session's current interaction language in `InteractiveLanguage`, `metaInfo.agentTransferConfig.language`, and, with handoff context, `customData.artemis.language`. Follow-up messages keep the language the transfer started with.

To transfer in the language the customer writes in:

1. Turn on the project's language detection setting. The runtime also needs a Language Detection service.
2. Apply the detection with `SET_INTERACTION_LANGUAGE` in a `before_turn` hook. See [Hook action properties](https://koreai.mintlify.site/agent-platform/abl/reference/lifecycle-and-hooks.md#hook-action-properties). The language is set before the escalating turn's reply, so the first call carries it.

`{{session.languageDetection.language}}` and `{{session.languageDetection.status}}` are ordinary session values. You can send them in `user_info` or `metadata`. The language value keeps the region (`zh-CN`) that the language fields drop.

```yaml theme={null}
HOOKS:
  before_turn:
    WHEN: session.languageDetection.status == "detected" AND session.languageDetection.confidence >= 0.85
      SET_INTERACTION_LANGUAGE: session.languageDetection.language

ESCALATE:
  routing:
    connection: smartassist
    user_info:
      Language: "{{session.languageDetection.language}}"
    user_info_in_custom_data: true
    metadata:
      detected_language: "{{session.languageDetection.language}}"
      detection_status: "{{session.languageDetection.status}}"
```

The escalation confirmation the customer sees follows the same interaction language. The runtime looks for a Localization asset for that language first: `<locale>/<agent>.json`, then `<locale>/_shared.json`, using the channel key (for example `escalation.digital`) and then `escalation_format`. It falls back to the project's Escalation Templates and then the built-in English text. Add one asset for each supported language in **Settings > Localization**, for example `hi/_shared.json`.

#### Voice transfer settings

When an escalation routes over a **voice** channel, the optional `routing.voice` block controls how the live call leg is handed off at the SIP/transport layer. It is ignored on non-voice channels.

```yaml theme={null}
ESCALATE:
  routing:
    connection: livechat
    queue: "wire_operations_l2"
    voice:
      transfer_method: refer            # invite | refer | bye
      call_transfer_type: sip           # sip | pstn | custom (omit sip/pstn to infer from project config)
      sip_headers:                      # forwarded to the receiving SBC / contact center
        X-Escalation-Reason: "sanctions_review"
        X-Priority: "1"
```

| Field | Type | Description |
| - | - | - |
| `transfer_method` | `"invite"` \| `"refer"` \| `"bye"` | SIP signaling method used to transfer the active call leg. |
| `call_transfer_type` | `"sip"` \| `"pstn"` \| `"custom"` | Whether to move the call over SIP or PSTN, or run a **custom** tool sequence (see below). Omit `sip`/`pstn` to infer from project configuration — SIP when a `sipTransferTargetUri` is configured, PSTN when only a `pstnTransferTargetNumber` is. |
| `sip_headers` | `Record<string,string>` | Custom SIP headers forwarded on the transfer to the receiving SBC or contact center. |
| `sip_transfer_id` | `string` | Explicit SIP transfer destination URI (literal or `{{ }}`-templated). Requires `call_transfer_type: sip`. See [Conditional routing entries](#sip_transfer_id) above. |
| `custom_tools` | `string[]` | Required when `call_transfer_type: custom` — an ordered list of existing project tool names run as the transfer sequence. See [Custom voice transfer](#custom-voice-transfer). |

> [!NOTE]
>
> Without `sip_transfer_id`, `call_transfer_type` selects a **transport, not a destination** — the transfer target is project-owned (Agent Transfer settings), and authored DSL cannot name a phone number or SIP URI, the same boundary the built-in `call_transfer` tool enforces by default. `sip_transfer_id` is the one explicit exception to that rule (see above). For a Genesys Audio Connector transfer specifically, use the dedicated `genesys_sip_headers` block below to reach the Genesys `TRANSFER_TO_AGENT` callevents call — `sip_headers` here also reaches that transfer, but only on the call-ending SIP BYE (see the note under [Genesys SIP transfer headers](#genesys-sip-transfer-headers)), which is a separate wire from the callevents POST.

#### Custom voice transfer

`call_transfer_type: custom` replaces the SIP/PSTN leg transfer with an ordered sequence of **project tools**. Instead of moving the call, the runtime keeps the Artemis audio leg live and runs the named tools serially as a notification sequence — for example, obtaining a token from one HTTP tool and signaling an external contact-center API with the next.

```yaml theme={null}
ESCALATE:
  triggers:
    - WHEN: caller.requests_human == true
      REASON: "Caller requested an agent"
      PRIORITY: high
  routing:
    voice:
      call_transfer_type: custom
      custom_tools:
        - nice_token        # first tool may capture a SecretRef result
        - signal_api        # next tool may consume that reference
```

* `custom_tools` is an ordered list of **1–8** exact, existing project **HTTP** tool names, invoked in the authored order. The first tool may capture a [SecretRef](https://koreai.mintlify.site/agent-platform/abl/reference/tools.md#reuse-secrets-across-tools-secretref) that a later tool consumes.
* `custom` routing is **mutually exclusive** with a `connection` — a custom escalation has no SIP/PSTN connection.
* The compiler validates shape (blocking errors): the transfer type must be `sip`/`pstn`/`custom`; `custom` requires 1–8 `custom_tools`; each name must be a non-empty ASCII identifier (`^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$`); names must be unique. Tool **existence and HTTP kind** are enforced at runtime (a non-HTTP or unknown tool is rejected then).

> [!WARNING]
>
> Custom voice transfer is **notification-only** in this version — it signals an external system while the caller stays on the Artemis leg; it does not hand the live call off to a human queue. Use `sip`/`pstn` (or `ESCALATE` routing to a human connection) when the call itself must be transferred.

#### Genesys SIP transfer headers

When an escalation transfers a **voice** call to Genesys (through the Genesys Audio Connector), `genesys_sip_headers` attaches custom SIP headers to the transfer — carrying the target queue, a reason code, and optional metadata. Declare a default under `routing:` and/or an override on individual triggers with the `GENESYS_SIP_HEADERS:` block. A trigger's block takes precedence over the routing default.

```yaml expandable=true theme={null}
ESCALATE:
  triggers:
    - WHEN: intent.category == "billing_dispute"
      REASON: "Billing dispute requires a specialist."
      PRIORITY: high
      GENESYS_SIP_HEADERS:                 # per-trigger override
        queue_header_key: "X-Genesys-Queue"
        queue_name: "billing_disputes"
        reason_header_key: "X-Genesys-Reason"
        reason: "billing_dispute"
        metadata_header_key: "X-Genesys-Data"
        metadata:
          tier: "gold"
          region: "us-east"
        additional_headers:                 # arbitrary extra headers, template-resolved
          X-Interaction-Id: "{{interaction_id}}"
          X-Brand: "{{brand}}"

  routing:
    connection: livechat
    queue: "billing_l2"
    genesys_sip_headers:                    # routing-level default for all triggers
      queue_header_key: "X-Genesys-Queue"
      queue_name: "billing_default"
```

Each field is optional. The `*_header_key` fields name a SIP header; the paired field supplies its value.

| Field | Type | Description |
| - | - | - |
| `queue_header_key` | `string` | SIP header **name** that carries the queue. |
| `queue_name` | `string` | Value placed in the queue header. |
| `reason_header_key` | `string` | SIP header **name** that carries the reason. |
| `reason` | `string` | Value placed in the reason header. |
| `metadata_header_key` | `string` | SIP header **name** that carries the metadata. |
| `metadata` | `string` or `object` | A string is sent verbatim; a map is serialized to a compact JSON string. |
| `additional_headers` | `object` | Map of header name → value. Arbitrary extra headers alongside the queue/reason/metadata trio — see below. |

The compiler validates the block against the same limits the runtime transfer enforces:

* Header-name fields (`*_header_key`) must be RFC 3261 tokens, at most 64 characters.
* Header values must contain no CR/LF/NUL characters. `queue_name` and `reason` emit as real SIP headers and stay within 1024 UTF-8 bytes; the serialized `metadata` and `additional_headers` values ride the HTTP callevents body instead of a SIP header, so they are **not** byte-bounded.
* `metadata` must be a string or a non-empty map — arrays and scalar values are rejected; an empty `{}` is ignored.
* Two header-name fields must not resolve to the same SIP header key (compared case-insensitively). A collision ([`GENESYS_SIP_HEADER_KEY_COLLISION`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#genesys_sip_header_key_collision)) is a compile error, because the transfer rejects colliding header keys at runtime.
* Unrecognized fields are ignored with a warning. Keys may be written in `snake_case` or `camelCase` (for example `queue_header_key` or `queueHeaderKey`).

> [!NOTE]
>
> `genesys_sip_headers` and the plain `sip_headers` (under [Voice transfer settings](#voice-transfer-settings)) are two different wires on the same Genesys Audio Connector transfer, and both can be authored together: `genesys_sip_headers` (plus `additional_headers`, below) populates the `TRANSFER_TO_AGENT` callevents call; `sip_headers` is carried separately on the SIP `BYE` that ends the call leg once the transfer succeeds. A conversation-summary `User-to-User` (UUI) header on that same BYE is planned but not yet wired for an `ESCALATE`-triggered transfer as of this release — it's currently only populated on the `call_transfer` tool path.

**`additional_headers`** (map of header name → value) adds arbitrary extra headers to the callevents `TRANSFER_TO_AGENT` payload, each as its own header alongside the queue/reason/metadata trio — the equivalent of a contact-center "additional context" bag. UNLIKE the verbatim fields above, its values are **template-resolved against session values at runtime**, so a `{{...}}` reference is substituted on the wire (a key that resolves empty is dropped); header names are still validated as RFC 3261 tokens at compile time. A name that collides (case-insensitively) with the resolved queue/reason/metadata key, or a reserved platform header, fails the transfer.

#### Transfer flow policies

`routing.flow_policy_ref` (or `transfer_flow_policy_ref`) names a policy declared in a top-level `TRANSFER_FLOW_POLICIES:` block. A transfer flow policy defines what happens while a caller waits in queue or when no agent is available — for example, playing a message or triggering a follow-up workflow. The policy body is free-form (its shape is defined by the human-agent integration, not the ABL parser).

```yaml expandable=true theme={null}
TRANSFER_FLOW_POLICIES:
  standard_wait:
    on_queued:
      type: message
      text: "Hello {{user.first_name}}, you're in the queue — a specialist will join shortly."
    on_no_agents:
      type: workflow
      workflow_id: no_agents_followup

ESCALATE:
  routing:
    connection: livechat
    queue: support
    flow_policy_ref: standard_wait
  triggers:
    - WHEN: user.wants_human_agent == true
      REASON: "User requested human support"
      PRIORITY: high
```

### Post-completion actions

The `on_human_complete` block defines what happens after the human agent finishes.

```yaml theme={null}
on_human_complete:
  - IF human.resolved == true: COMPLETE
  - IF human.needs_agent == true: HANDOFF to specified_agent
  - IF human.needs_followup == true: CONTINUE
```

Each entry has a `condition` and an `action`. The action can be `COMPLETE` (end the conversation), `HANDOFF` (transfer to another agent), or `CONTINUE` (resume the current agent).

> [!NOTE]
>
> When the human agent closes the conversation, a `FEEDBACK` survey card can be shown — authored either on the agent itself or inside a `FLOW:` step. See [Post-transfer surveys](https://koreai.mintlify.site/agent-platform/abl/reference/rich-content.md#post-transfer-surveys-escalate-to-a-human-agent) for exactly which block is picked and when.

***

## COMPLETE

COMPLETE defines the conditions under which the agent considers its task finished. Each completion condition specifies a `WHEN` expression and an optional response.

### Syntax

```yaml expandable=true theme={null}
COMPLETE:
  - WHEN: confirmation_number IS SET AND transfer_status == "released"
    RESPOND: |
      Your wire transfer has been executed successfully.

      **Confirmation:** {{confirmation_number}}
      **Amount:** {{amount}} {{currency}}
      **To:** {{beneficiary_name}}
      **Estimated Arrival:** {{estimated_arrival}}
    STORE: "wire_transfers"

  - WHEN: transfer_status == "queued"
    RESPOND: "Your wire has been queued for the next processing window."
```

### Properties

| Property | Type | Required | Default | Description |
| - | - | - | - | - |
| `WHEN` | `string` | Yes | -- | Boolean condition over session state. The agent completes when this evaluates to true. |
| `RESPOND` | `string` | No | -- | Final message to the user. Supports `{{}}` template interpolation. |
| `SET` | `Record<string,string>` | No | -- | Session assignments applied when the completion fires (for example, clear the sticky flag that triggered it). |
| `TERMINAL` | `boolean` | No | `true` | When `false`, the response renders (including interactive widgets like a closing feedback collector) **without** ending the session — control returns to the agent for the next turn. |
| `STORE` | `string` | No | -- | Collection or path name to store the completion result for analytics. |
| `MODEL_CONTEXT` | `string` | No | -- | Text retained for the model instead of the delivered `RESPOND` in future model calls. See [MODEL\_CONTEXT on a response](https://koreai.mintlify.site/agent-platform/abl/reference/flow.md#model_context-on-a-response). |

The runtime reads only `- WHEN:` conditions under `COMPLETE:`. A line written directly under `COMPLETE:` is ignored, so the agent gets no completion condition from it. The compiler reports [`W362`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#w362). A condition property (`RESPOND`, `MODEL_CONTEXT`, `SET`, `STORE`, `TERMINAL`, or a response payload block) written at or left of the indent of its `- WHEN:` line is still read into that condition, so a `TERMINAL: false` there keeps the session open. The compiler reports [`W363`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#w363). Indent each property under its condition.

> [!WARNING]
>
> `COMPLETE`'s `WHEN` is **deterministic** — it must be a boolean expression over session state. Plain-English / intent-style text is rejected at compile time ([`PLAIN_ENGLISH_COMPLETE_WHEN`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#plain_english_complete_when)). Use `NLU`/routing for intent matching, not `COMPLETE WHEN`. A fully-quoted `WHEN` (`WHEN: "status == \"done\""`) is unwrapped and evaluated the same as an unquoted one when it contains an operator — see [Quoting a condition](https://koreai.mintlify.site/agent-platform/abl/reference/expressions-and-functions.md#quoting-a-condition).

> [!NOTE]
>
> A `COMPLETE` condition that matches does **not** complete the agent if the agent's own `CONSTRAINTS` fail on the state it would complete with — the failing constraint's `ON_FAIL` runs instead, so a completion can never bypass a constraint that would otherwise block the same state.

Example of a non-terminal completion that collects feedback and then keeps the session open:

```yaml theme={null}
COMPLETE:
  - WHEN: feedback_requested == true
    RESPOND: "Thanks! How would you rate this conversation?"
    SET:
      feedback_requested: "false"
    TERMINAL: false
```

> [!NOTE]
>
> Always clear the condition that triggered a `COMPLETE` block when using `TERMINAL: false` (for example, by using `SET`). Otherwise, the same completion condition may be evaluated again on the next user message, creating a completion loop. When such a loop is detected, the platform automatically closes the session and logs a warning.

**Voice calls on KoreVG.** Every `COMPLETE` ends the call after its message plays, whether or not it is `TERMINAL`. Caller speech or keys heard while that message plays are not a new turn. The runtime acknowledges and ignores them, and the `voice_caller_input_ignored_call_ending` trace records the reason. The message plays once, even when the agent that handed back already said the same line in that turn. The `voice_duplicate_final_suppressed` trace records the removed copy.

### Rich content in completion

COMPLETE responses support voice configuration and rich content, the same as any RESPOND:

```yaml expandable=true theme={null}
COMPLETE:
  - WHEN: booking_confirmed == true
    RESPOND: "Your booking is confirmed!"
    VOICE:
      ssml: "<speak>Your booking is confirmed!</speak>"
    RICH_CONTENT:
      MARKDOWN: |
        ## Booking Confirmed
        | Detail | Value |
        |--------|-------|
        | Reference | {{booking_ref}} |
        | Date | {{travel_date}} |
    ACTIONS:
      - id: view_itinerary
        type: button
        label: "View Itinerary"
```

`FORMATS`/`RICH_CONTENT`, `VOICE`, and `ACTIONS` are recognized regardless of where they appear in the condition — immediately after `RESPOND`, after `STORE`/`SET`/`TERMINAL`, or on a condition with **no** `RESPOND` at all (for example, a completion that renders only a `FEEDBACK` card):

```yaml theme={null}
COMPLETE:
  - WHEN: transfer_status == "released"
    STORE: "wire_transfers"
    RICH_CONTENT:
      FEEDBACK:
        FEEDBACK_TEMPLATE: Post_Chat_NPS
```

### SIP headers on the closing BYE (voice)

A condition's `VOICE` block can name the SIP headers sent on the BYE that ends a KoreVG voice call. A contact center that receives the call back can route on them, for example `X-RouteType: hangup`.

```yaml theme={null}
COMPLETE:
  - WHEN: issue_resolved
    RESPOND: "Thanks for calling, goodbye."
    VOICE:
      sip_headers:
        X-RouteType: hangup
        X-Disposition: "{{disposition}}"
```

* Names must be RFC 3261 tokens of at most 64 characters. Values must be strings without control characters. Violations are compile errors: `COMPLETE_SIP_HEADERS_INVALID_NAME`, `COMPLETE_SIP_HEADERS_INVALID_VALUE`, and `COMPLETE_SIP_HEADERS_WRONG_TYPE`. Quote a value that starts with `{{`.
* The platform adds its own correlation headers to the BYE: `x-session-id`, `x-project-id`, `x-tenant-id`, and the call metadata `x-caller-number` and `x-call-start-time` (the same set a transfer sends). You cannot set or override these names. `X-RouteType` is not an ABL or platform header. It is an example of a header that a contact center such as Five9 reads, and `hangup` is the value that example uses. The set of values is defined by the system that receives the BYE, so use the names and values from its routing documentation. The runtime sends any valid string value as written.
* `{{variable}}` placeholders resolve from session values when the condition fires. A header whose value resolves empty is not sent.
* The headers pass the project's outbound SIP header policy. Its block list and `headerPassthrough: false` apply. The runtime drops authored headers that use reserved platform names (`x-session-id`, `x-tenant-id`, and similar), and the count and size limits hold. These headers need no allow-list row, and the project's transfer allow rows are never added to a hangup.
* The platform always sets `X-ArtemisReason: BotHangup` and you cannot override it.
* The headers apply to pipeline and realtime voice calls that this condition ends.
* `sip_headers` anywhere other than a COMPLETE condition's `VOICE` block is ignored with a warning ([`VOICE_SIP_HEADERS_ILLEGAL_PLACEMENT`](https://koreai.mintlify.site/agent-platform/abl/reference/errors-and-warnings#voice_sip_headers_illegal_placement)). Transfer headers belong in `ESCALATE.routing.voice.sip_headers`.

### Completion evaluation

Completion conditions are evaluated after every turn, in declaration order. The first matching condition triggers completion. If no condition matches, the agent continues the conversation.

***

## Context passing

### Evaluation order across constructs

When multiple multi-agent constructs apply on the same turn, the runtime evaluates them in this order:

1. **ESCALATE triggers** -- checked first; critical safety and compliance.
2. **HANDOFF rules** -- evaluated by priority (lower first).
3. **DELEGATE conditions** -- evaluated in declaration order.
4. **COMPLETE conditions** -- checked last.

***

## Complete supervisor example

```yaml expandable=true theme={null}
SUPERVISOR: Customer_Service_Hub
VERSION: "2.0"
GOAL: "Route customers to the right specialist"

PERSONA: |
  Professional customer service coordinator. Routes requests
  efficiently and preserves context across agent transfers.

HANDOFF:
  - TO: Live_Agent
    WHEN: intent.category == "escalation"
    CONTEXT:
      pass: [user_id, conversation_summary]
      summary: "User requests human assistance"
    EXPECT_RETURN: false

  - TO: Sales_Agent
    WHEN: intent.category == "new_booking"
    CONTEXT:
      pass: [search_context, preferences]
      summary: "User looking to book"
    EXPECT_RETURN: false

ESCALATE:
  triggers:
    - WHEN: routing_failures >= 3
      REASON: "Multiple routing failures"
      PRIORITY: high

ON_ERROR:
  routing_failure:
    RESPOND: "Let me connect you with someone who can help."
    RETRY: 1
    THEN: HANDOFF Live_Agent

COMPLETE:
  - WHEN: handoff_successful == true
    RESPOND: "I've connected you with the right specialist."
```

***

**Related articles:**

* [NLU](https://koreai.mintlify.site/agent-platform/abl/reference/nlu.md) -- intent classification that drives routing decisions
* [Memory and Constraints](https://koreai.mintlify.site/agent-platform/abl/reference/memory-and-constraints.md) -- session and persistent state used in routing conditions
* [Expressions and functions](https://koreai.mintlify.site/agent-platform/abl/reference/expressions-and-functions.md) -- condition syntax for WHEN clauses
* [Lifecycle and hooks](https://koreai.mintlify.site/agent-platform/abl/reference/lifecycle-and-hooks.md) -- ON\_START and hooks that interact with multi-agent flows
* [Rich content](https://koreai.mintlify.site/agent-platform/abl/reference/rich-content.md) -- formatting for RESPOND and COMPLETE messages


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