Coordination

View Source

Single agents go a long way — often further than you expect when paired with good tools and Skills. Reach for multi-agent coordination when distinct roles need separate instructions, models, permissions or state ownership, or when you want deterministic Elixir control over a multi-step pipeline.

What ExAgent simplifies:

  • Inherited budgets & permissions: Delegated child agents automatically share the parent's UsageLimits, spend budget, deadline, cancellation and permission ceiling — a sub-agent can never escalate privileges or silently bypass your cost cap.
  • Honest subtree accounting: Parent results roll up every child's requests, tool calls and token usage once without double-counting.
  • One durability model everywhere: Delegations, handoffs, sequential Compositions and parallel Flows all plug into the same PostgreSQL ExAgent.Continuation pause, approval and crash-recovery engine.

Choosing the right coordination pattern

PatternEntry pointWho decides the next step?Best for
DelegationCoordination.delegation_tool/2, ExAgent.run_child/4Parent LLM calls specialist like a tool.Research, summarization or multimodal sub-tasks that report back to a coordinator.
AdvisorExAgent.Tool.Advisor.new/1Fast LLM consults a stronger model on tough steps.Keeping latency/cost low while letting the agent phone a frontier model when stuck.
Handoff (candidate)ExAgent.Handoff.new/1Triage LLM transfers the user's turn via transfer_to_<id>.Customer support routing (billing vs. tech support) where the specialist replies directly.
Shared-state SessionExAgent.SessionPluggable TurnPolicy (round-robin, supervisor, initiative).Humans and agents collaborating over one supervised Elixir state struct.
Durable SequenceExAgent.Coordination.CompositionYour Elixir code (fixed ordered steps).Deterministic multi-stage pipelines (extract → validate → draft → approve).
Router & Parallel FlowExAgent.Coordination.FlowYour Elixir router + bounded fan-out/fan-in.Batch document review, parallel specialist analysis, map/reduce workflows.

Need exact workflow manifest schemas or C7 frame rules?

For complete durable delegation bindings, Flow error shapes and recovery invariants, see Runtime & ops contracts.

Delegate inside the parent's scope

Wrap any specialist %ExAgent{} as a tool with ExAgent.Coordination.delegation_tool/2. When the parent invokes it, the child runs inside the parent's execution scope and returns its validated output as a normal tool result:

alias ExAgent.Message.{Part.ToolCall, Usage}

usage = %Usage{input_tokens: 1, output_tokens: 1}
helper = ExAgent.new(model: %ExAgent.Models.Test{label: "A concise summary.", usage: usage})
delegate = ExAgent.Coordination.delegation_tool(helper, name: "summarize")

model = %ExAgent.Models.Test{
  usage: usage,
  script: [
    {:tool_calls, [
      %ToolCall{tool_name: "summarize", tool_call_id: "summary-1",
        args: %{"prompt" => "Summarize this note."}}
    ]},
    "Summary received."
  ]
}

parent = ExAgent.new(model: model, tools: [delegate])
{:ok, result} = ExAgent.run(parent, "Summarize my note.")
result.output
# => "Summary received."

Notice result.usage.input_tokens automatically reflects both parent requests plus the child's request (3 total).

Bind a durable delegate

To preserve child progress and approvals across crashes in a persisted continuation, fingerprint the delegate with ExAgent.Catalog.fingerprint/1, attach continuation: binding on delegation_tool/2, and include the child entry in your Catalog:

alias ExAgent.{Catalog, Coordination, Models.Test}

codec = %{
  dump: fn %Test{index: index} -> {:ok, %{"index" => index}} end,
  load: fn %Test{} = model, %{"index" => index} -> {:ok, %{model | index: index}} end
}

policy = %{"id" => "summarizer-policy", "version" => "1"}
model_ref = %{"id" => "summarizer-model", "version" => "1"}

{:ok, ref} =
  Catalog.fingerprint(id: "summarizer", agent: helper, policy: policy,
    model_ref: model_ref, model_codec: codec)

binding = %{definition: ref, policy: policy, model_ref: model_ref, model_codec: codec}
delegate = Coordination.delegation_tool(helper, name: "summarize", continuation: binding)
helper_entry = {ref, helper, binding}

Delegate an attachment and track it in Plan

delegation_tool/2 accepts a string prompt from the model. To pass an image or trusted attachment from ctx.deps, call ExAgent.run_child/4 inside your own tool — here combined with ExAgent.Plan and streamed child events (child_events: :all):

alias ExAgent.{Message, Models.Test, Plan, Tool, UsageLimits}
alias ExAgent.Message.Part

png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVR4nGP4DwABAQEAsTj2FAAAAABJRU5ErkJggg=="
check_image = fn messages, _params ->
  [%Part.User{content: [_, %{"type" => "image", "data" => ^png}]}] =
    Message.parts(messages)
  "Chart attached."
end
specialist = ExAgent.new(model: %Test{script: [check_image]})

inspect_chart = Tool.new(name: "inspect_chart", call: fn ctx, _ ->
  parts = [
    %{type: "text", text: "Check Figure 1."},
    %{type: "image", data: ctx.deps.chart, media_type: "image/png"}
  ]

  with {:ok, child} <- ExAgent.run_child(ctx, specialist, parts), do: {:ok, child.output}
end)

call = fn name, id, args ->
  {:tool_calls, [%Part.ToolCall{tool_name: name, tool_call_id: id, args: args}]}
end
write_plan = fn status ->
  item = %{"id" => "chart", "content" => "Check Figure 1", "status" => status}
  call.("write_todos", status, %{"items" => [item]})
end
complete_plan = fn messages, _params ->
  [%Part.ToolReturn{status: :succeeded}] =
    for %Part.ToolReturn{tool_name: "inspect_chart"} = part <- Message.parts(messages), do: part
  write_plan.("completed")
end

model = %Test{script: [
  write_plan.("pending"), call.("inspect_chart", "chart-1", %{}),
  complete_plan, "Figure checked."
]}
parent = ExAgent.new(model: model, tools: [inspect_chart], capabilities: [Plan.capability()],
  usage_limits: %UsageLimits{request_limit: 5})

events = Enum.to_list(ExAgent.run_stream(parent, "Check the document.",
  deps: %{chart: png}, child_events: :all))
{:result, result} = List.last(events)
result.plan

Pair this stream with the delegation progress reducer and Plan and workspace.

Consult a stronger model

Run your main loop on a fast, inexpensive model and give it a bounded ExAgent.Tool.Advisor tool to consult a frontier reasoning model only when it hits a hard edge case:

advisor = ExAgent.Tool.Advisor.new(model: strong_model, max_uses: 3)
agent = ExAgent.new(model: fast_model, tools: [advisor | tools])

Let a model hand off the turn

With ExAgent.Handoff (candidate), list specialist destinations in :handoffs on a triage agent. ExAgent exposes transfer_to_<id> tools automatically; when the triage model transfers, the destination receives a bounded, provider-neutral history view and answers the user directly (protected by the same ExAgent.Permissions rules and approvals):

returns =
  ExAgent.Handoff.new(
    id: "returns",
    description: "Handle returns and refund policy questions.",
    agent: returns_specialist
  )

triage = ExAgent.new(model: model, handoffs: [returns])

Share audio with a destination

Attachments are withheld across handoffs by default. Opt in explicitly per destination (share_images: true, share_audio: true, or share_file_references: true) when the destination model supports them:

ExAgent.Handoff.new(
  id: "audio",
  description: "Answer questions about a recording",
  agent: ExAgent.new(model: "google:gemini-3.5-flash-lite"),
  share_audio: true,
  max_history_bytes: 131_072
)

Resume a persisted transfer

In a durable continuation, version each destination's guardrails via :policy on Handoff.new/1 so a pause inside the specialist resumes cleanly under its own policy (Recover a persisted handoff):

ExAgent.Handoff.new(
  id: "returns",
  description: "Handle a return",
  agent: specialist,
  policy: %{"id" => "returns-guardrails", "version" => "1"}
)

Give shared state one writer

When multiple agents — or a mix of agents and humans — collaborate on one evolving document or workflow state, ExAgent.Session serializes every mutation through a single supervised process governed by a TurnPolicy (:round_robin, {:initiative, order: [...]}, :supervisor, or your own behaviour module):

alias ExAgent.Session
alias ExAgent.Session.Participant

{:ok, session} = Session.start_link(
  shared_state: %{notes: []},
  participants: [
    Participant.new(id: "writer", kind: :agent),
    Participant.new(id: "editor", kind: :human)
  ],
  policy: {:initiative, order: ["writer", "editor"]}
)

{:ok, "writer"} = Session.start(session)
{:ok, state, "editor"} = Session.take_turn(session, "writer", fn current ->
  {:ok, %{current | notes: ["Draft ready" | current.notes]}}
end)
state.notes
# => ["Draft ready"]

Subscribe to session transitions via ExAgent.Event.session_topic/2, and version your state map if human forms need optimistic concurrency checks.

Add durable orchestration

When your Elixir code should control the workflow graph instead of asking an LLM to plan every step, use:

  • ExAgent.Coordination.Composition — fixed sequential pipelines where each step maps the previous step's validated output into the next agent's prompt, with full checkpointing and human approvals at any step.
  • ExAgent.Coordination.Flow — versioned Elixir routers and bounded parallel fan-out/fan-in (with ordered results and :fail_fast or :collect error modes).

See Coordination recipes (and the runnable examples/coordination_workflows.exs in the repository) for sequential Composition and host-router examples.

Budget durable tool batches

Durable workflow leaves share the root's UsageLimits, ExAgent.UsageLimits.Budget (spend_budget: (candidate)) and tool quotas — size your step limits and parallel concurrency so a wide fan-out never starves sibling branches.

Run a Flow over a manifest

Use kind: :map (candidate) when every item follows the same versioned branch template (max_items defaults to 32, error policy defaults to :collect, empty manifest runs zero branches, and duplicate item IDs fail before creating the record):

alias ExAgent.{Models.Test, Store}
alias ExAgent.Coordination.Flow

ref = fn id -> %{"id" => id, "version" => "1"} end

{:ok, _} = Store.ETS.start_link(name: DocumentReviewStore)

continuation = %{
  store: Store.scoped({Store.ETS, DocumentReviewStore}, "document-review"),
  id: "batch-9",
  policy: ref.("batch-policy"),
  durability: :ephemeral,
  expires_at: nil,
  lease_ms: 30_000
}

template = %{
  id: "reviewer",
  agent: ExAgent.new(model: %Test{label: "reviewed"}),
  definition: ref.("review-agent"),
  policy: ref.("review-policy"),
  model_ref: ref.("review-model"),
  output_ref: ref.("review-output"),
  model_codec: %{
    dump: fn _ -> {:ok, %{}} end,
    load: fn model, %{} -> {:ok, model} end
  }
}

flow =
  Flow.new(
    id: "review-documents",
    version: "1",
    kind: :map,
    template: template,
    max_items: 12,
    max_concurrency: 2
  )

manifest = [
  %{id: "doc-17", input: %{title: "Meeting notes", text: "Reserve the room."}},
  %{id: "doc-03", input: %{title: "Agenda", text: "Review the draft."}}
]

{:ok, result} = Flow.run(flow, manifest, continuation: continuation)
["doc-17", "doc-03"] = Enum.map(result.steps, & &1.id)

For heterogeneous parallel specialists (each with its own versioned agent), use kind: :parallel with steps: [legal_step, finance_step], max_concurrency: 2 and on_error: :fail_fast (or :collect), reading ordered branch outputs from result.steps. Key any shared :step_options by step/template ID.

Recover a workflow after an owner crash

If a node dies mid-workflow, recover its expired lease with ExAgent.Continuation.recover/3, resolve the versioned workflow from your Catalog, and call Flow.resume/3 (or Composition.resume/3) — completed branches stay preserved and never re-run:

alias ExAgent.Continuation
alias ExAgent.Coordination.Flow

{:ok, info} = Continuation.get(store, id)

{:ok, recovered} =
  Continuation.recover(store, id,
    record_id: info.record_id,
    revision: info.revision,
    operation_id: recovery_id,
    actor: actor,
    authorize: authorize
  )

case recovered do
  %{status: :ready, continuation: reference} ->
    Flow.resume(flow, reference, continuation: config)

  other ->
    other
end

For uncertain leaf effects, follow Reconcile an effect or Continuation.retry_effect/4 before resuming.

API: ExAgent.Coordination, ExAgent.Coordination.Composition, ExAgent.Coordination.Flow, ExAgent.Handoff, ExAgent.Session, ExAgent.Tool.Advisor, ExAgent.run_child/4.