Documentation

Automatic Coordination

LeafMesh includes built-in automatic coordination across your agent mesh. It is configured under a single manager: section in your YAML and activates when the platform starts. You do not write code for it.

The platform observes every event in the control plane — agent responses, errors, mesh calls, session lifecycle, workflow completions, health checks — and decides whether anything needs to happen. For normal-flow events, nothing happens. When something goes wrong, the platform takes the appropriate action.


What It Does

For every event, the platform makes a single decision: does anything need to happen? Most of the time, the answer is no, and execution continues without interruption.

When the platform detects a problem, it picks the appropriate response — for example: retry transient failures, halt persistent errors that cannot self-resolve, or escalate to human review. The decision is grounded in the current event status, not stale history — old errors are ignored once an agent has succeeded.

Domain-Specific Analysis

The platform tailors event analysis based on the domain you configure:

DomainFocus
generalIntent classification, entity extraction, workflow coordination
ecommerceProduct interest, purchase intent, cart signals, personalization
data_analysisData source validation, schema analysis, monitoring setup

Domain affects how events are interpreted; it does not change which events are observed.

Coordination Decisions

When intervention is needed, the platform takes one of a small set of qualitative actions: it can retry an agent, cancel the in-flight chain, halt the session, re-run from a known state, or escalate to human review. Transient errors are retried; persistent errors (such as a missing API key or invalid model name) are halted rather than retried. You don't need to enumerate or wire these decisions — they're internal to the platform.


How It Behaves

The platform is reactive only. It does not initiate actions on its own and does not orchestrate normal agent flow. Agents communicate via the mesh as usual — the platform only steps in when something goes wrong.

Observation is asynchronous and does not block agent execution. For normal-flow events, overhead is negligible.


Retry and Rerun

When an agent fails, the platform can re-execute it with feedback about the prior failure so the agent self-corrects rather than blindly repeating the same output.

Reruns can be triggered automatically (the platform detects a recoverable failure) or explicitly:

SurfaceHow
Python SDKawait leafmesh.rerun_agent(agent_name, session_id, ...) — see [API Reference](../api-reference/leafmesh-adk)
StudioSession inspector → per-agent rerun button
Strict yieldsSet enforce_yields: true + enforce_yields_retry: N on the agent — the platform auto-triggers retries on contract violations

How feedback is surfaced per agent type

Agent typeWhat the agent sees on retry
LLMPrompt is augmented with retry context describing the prior failure and the expected shape. The original output schema is still enforced.
Human (inbox)Studio inbox renders the failed field with an error annotation.
Human (channel)Channel adapter posts a follow-up message asking the human to retry the missing piece.
External (n8n / CrewAI / etc.)Connector receives retry context in the payload — workflows can read it and adjust.
ProgrammaticFunction receives retry context alongside its input.

Deterministic agents and corrected input

Programmatic and external connector agents are deterministic — same input, same output. When the platform detects that a failure was caused by a fixable input issue (case mismatch, typo, missing field, wrong format), it can propose a corrected input and use it on the retry. The deterministic function then runs against the corrected input and succeeds without code changes.

Callers can also override the retry input directly via sdk.rerun_agent(new_input=...); an override always takes precedence over a platform-proposed correction.

Retry budgets

coordination_rules.max_retries sets a per-session retry ceiling. When the budget is exhausted, the platform routes through manager.escalation: if configured. For yields-validation specifically, the per-agent enforce_yields_retry (see agent-config-fields.md / Yields Enforcement) overrides the global budget — 0 fails on the first violation, N allows N self-correction attempts before escalating.


YAML Configuration

Configure automatic coordination under a single manager: section:

manager: enabled: true model: "gpt-4o-mini" # Model used for event analysis domain: "generic" # "generic" | "ecommerce" | "data_analysis" prompt: | # Optional: evaluation criteria This mesh handles customer support tickets. Escalate if the same issue loops more than twice. Watch for advisor confidence scores below 0.6. coordination_rules: score_threshold: 0.7 # Minimum confidence score for approvals max_retries: 3 # Max retries before escalating agent_rules: processor_agent: min_items: 1 max_items: 100 health_check_interval: 60 # Seconds between health checks (default: 60, configurable) agent_timeout_threshold: 180 # Seconds before an agent is considered timed out (default: 180, configurable) chain_completion_timeout: 1800 # Seconds to wait for can_call chain (default: 1800, configurable)

Configuration Fields

FieldDefaultDescription
enabledtrueEnable or disable automatic coordination
model--LLM model used for event analysis. A fast, cost-effective model like gpt-4o-mini is recommended. Supports OpenAI, Anthropic, Google, and DeepSeek models.
domain"generic"Domain-specific analysis. Options: "generic", "ecommerce", "data_analysis"
promptnullEvaluation criteria — tell the platform what success looks like, what to escalate on, and what patterns to watch. Supports multiline YAML (`\`).
coordination_rules{}Rule engine configuration (see Coordination Rules below)
human_input_rules, timeout_rules, workflow_pause_rules, human_response_rulessee [Human-in-the-Loop Rules](#human-in-the-loop-rules)Human-in-the-loop limits. These sit directly under manager:, not under coordination_rules
health_check_interval60Seconds between background health checks (configurable)
agent_timeout_threshold180Seconds with no heartbeat before an agent is considered timed out (configurable)
chain_completion_timeout1800Seconds to wait for all can_call targets to complete before flagging missing agents (configurable)

Minimal Configuration

If you just want the defaults:

manager: enabled: true model: "gpt-4o-mini"

This enables both components with sensible defaults: generic domain analysis, 60-second health checks, 180-second agent timeout, 1800-second chain completion timeout, and no custom coordination rules.


Routing Authority

LeafMesh supports an optional learning mode that adapts routing based on past outcomes. This is configured via the routing section under manager:.

How Learning Mode Works

When mode: "learning" is enabled, the platform tracks routing outcomes — which agent was called, from where, and whether it succeeded or failed — and uses that history to prefer routes with a strong track record. Routes with no history are always tried (exploration); routes that fall below the configured confidence threshold are excluded.

Routing Configuration

manager: routing: mode: "learning" # "static" (default) or "learning" confidence_threshold: 0.7 # Min success rate to keep a route (0.0–1.0)
FieldDefaultDescription
mode"static""static" routes to all available targets. "learning" filters based on past success.
confidence_threshold0.7Minimum success rate for a route to be considered reliable

Static vs Learning Mode

  • Static mode (default): All matching can_call targets are called. No filtering, no learning. Predictable and deterministic.
  • Learning mode: Targets are filtered based on historical success rates. New routes with no history are always included.

Start with "static" for new deployments. Switch to "learning" once you have stable agent chains and want the system to self-optimize.

Routing Quality Feedback

The platform evaluates every routing decision as either correct, acceptable, or misrouted, and feeds the result back into routing memory automatically. You do not need to write any code for this loop.


Narration Routing

Conditions handle definitive, boolean routes. But some routing intent is fuzzy — it depends on tone, context, or semantic understanding that can't be reduced to category == 'billing'. The narration field on agent configs lets mesh designers express these non-definitive routing hints in plain English.

agents: triage: name: "triage" can_call: - agent: "billing_agent" condition: "category == 'billing'" - agent: "technical_agent" condition: "category == 'technical'" narration: > If the customer mentions cancelling, route to retention_agent. If the customer mentions a competitor by name, route to win_back_agent. If the customer asks about enterprise plans, route to sales_agent.

How Narration Works

Narration does not add a new LLM call — it is folded into the platform's existing event analysis. When an agent's output is observed, narration hints are considered alongside the rest of the context and any narration-suggested agents are dispatched in addition to whatever the explicit condition routes already handled.

Key Rules

  • Conditions first. Condition targets dispatch instantly. Narration targets arrive shortly after via automatic coordination.
  • Additive only. Narration adds to condition routing — it never removes from it.
  • Any agent. Narration can reference any registered agent in the mesh, not just those in can_call.
  • Coordination required. If automatic coordination is disabled, narrations are ignored.
  • Zero overhead without narration. If no agents declare a narration field, there is no extra work.

See Agent Config — Narration for YAML reference and Message Routing — Narration for the routing flow.


Escalation Targets

When the platform decides to escalate (either for a recoverable issue that needs human review, or a persistent error that cannot self-resolve), it can dispatch escalations to multiple targets simultaneously. Configure targets under manager.escalation:

Configuration

manager: escalation: targets: - type: "human_agent" agent: "senior_support" entry_point: "escalation_request" - type: "webhook" connection: "escalation-webhook" # Outbound webhook record: address, headers, token method: "POST" payload_template: customer_id: "{{customer_id}}" issue: "{{issue_summary}}" severity: "critical" - type: "channel" provider: "slack" channel_id: "C0123456789" message_template: "Escalation: {{issue}} for {{customer}}"

Target Types

TypeWhat Happens
human_agentTriggers a human agent's entry point via mesh call. The human workflow takes over.
webhookSends an HTTP POST with a rendered payload to the address held in the connection: record. Useful for ticketing systems, PagerDuty, or custom APIs.
channelSends a message to a native channel (e.g., Slack). Requires a channel adapter configured on a human agent.

The webhook's address, header and query rows and token are an Add custom record on Studio's Infrastructure page with service type Outbound webhook; the target names it with connection:. A URL or header written inline is refused at load.

The simplest escalation needs no record: escalate to an Inbox seat (a human agent with human_interface: default):

manager: escalation: targets: [{type: human_agent, agent: senior_support}]

Template Variables

Both payload_template and message_template support {{variable}} substitution. Variables are resolved from the escalation context, which includes session data, agent yields, and error details.

Parallel Dispatch

All configured targets fire in parallel — not sequentially. If one target fails (e.g., a webhook times out), the others still execute. Failures are logged but do not block the escalation.

Auto-Escalation

The platform automatically triggers escalation when certain thresholds are exceeded:

manager: coordination_rules: max_retries: 3 # Escalate after 3 failed retries timeout_rules: max_timeouts_before_escalation: 2 # Escalate after 2 human timeouts

Persistent errors (such as wrong model names, missing API keys, authentication failures, configuration errors) are treated as critical escalations and dispatched immediately, without further retries.


Coordination Rules

Coordination rules let you define per-agent business logic that the Manager enforces.

Global Rules

manager: coordination_rules: score_threshold: 0.7 # Global confidence threshold max_retries: 3 # Max retries before outage max_call_depth: 5 # Max chain depth before loop detection reflection_budget: 2 # Default 2 completion_threshold: 100 # Percentage required for workflow completion

Per-Agent Rules

Define rules for specific agents under agent_rules:

manager: coordination_rules: agent_rules: processor_agent: min_items: 1 # Minimum items to process max_items: 100 # Maximum items to process always_approved: false # Skip all rule checks for this agent score_threshold: 0.8 # Override global threshold for this agent request_keywords: # Only approve if input contains these keywords - "process" - "transform" require_keywords: true # Block if no keywords match requires_progress: true # Require other agents to have completed first min_completed_agents: 1 # Minimum agents that must complete before this one runs

Human-in-the-Loop Rules

Control human agent interaction patterns. These four rule sets sit directly under manager:, next to coordination_rules, not inside it:

manager: human_input_rules: max_concurrent_requests: 3 # Max simultaneous human input requests max_agent_requests: 5 # Max requests a single agent can make to humans enable_request_queuing: true timeout_rules: max_timeouts_before_escalation: 2 # Escalate after N human timeouts timeout_escalation_enabled: true escalation_notify_managers: true workflow_pause_rules: max_pause_duration_minutes: 30 # Max time a workflow can stay paused max_concurrent_paused_workflows: 2 # Max paused workflows at once pause_monitoring_enabled: true human_response_rules: # What happens after each kind of human reply approval: requires_manager_review: false auto_escalate: false escalation: requires_manager_review: true auto_escalate: true timeout: requires_manager_review: true auto_escalate: false

The values shown are the defaults. From 2.4.482, if a file still nests any of these under manager.coordination_rules:, LeafMesh moves it to manager: at load and logs a warning.

Approval Workflow Rules

Configure multi-level approval workflows:

manager: coordination_rules: manager_max_resolution: 500 # Max amount Manager can approve manager_max_discount: 100 # Max discount Manager can authorize manager_can_override_policy: false

Health Monitoring

The platform runs background health monitoring that periodically checks whether agents are responsive.

How It Works

Agents emit heartbeats while executing. If an agent goes silent for longer than the configured timeout, it is marked unhealthy and the platform takes the appropriate intervention. When the agent recovers, it is marked healthy again automatically.

Configuration

manager: health_check_interval: 60 # Check every 60 seconds (configurable) agent_timeout_threshold: 180 # No heartbeat for 3 minutes = unhealthy (configurable)

Lower these values for latency-sensitive applications. Raise them for batch processing where agents may be idle for extended periods.

Chain Completeness Monitoring

The platform also monitors can_call chain completeness. If an agent has declared targets and one of them never completes within chain_completion_timeout seconds, the platform flags the missing agent so coordination can step in. This catches cases where a chain silently drops a target due to a condition mismatch, timeout, or unexpected error.


Events

Automatic coordination publishes events to the internal event backbone. Customers consume them via the SSE endpoint (see Event System). The high-level categories you can subscribe to include:

  • manager.* — coordination decisions and interventions
  • human.* — handoffs to and from human reviewers
  • session.* — session lifecycle changes triggered by coordination

All coordination decisions are persisted, providing a complete audit trail across sessions.


Next Steps


LeafMesh -- Automatic coordination, configured in YAML

Last updated: 11/10/2026