Skip to content
Talk to our solutions team

Agents & Orchestration

How work reaches a machine. This covers the agent fabric that AI Flow uses to route each task to a healthy agent, and how the selectors you write in a flow resolve to a real worker.

This page describes the transport as it runs: one gRPC stream carrying opaque bytes, with the resilience primitives covered below.

┌───────────────────────────────────────────────┐
│ Orchestrator (gRPC server) │
│ │
│ AgentSelector (least CPU/mem, tag, model, gpu)│
│ per-agent outbound queue (1000) + health map │
└───┬───────────────┬───────────────┬────────────┘
KeepAlive│ KeepAlive │ KeepAlive │ (bidirectional streams)
▼ ▼ ▼
Agent A Agent B Agent C
heartbeat ↑ heartbeat ↑ heartbeat ↑ (CPU/mem/GPU/disk, capacity)
run task ↓ run task ↓ run task ↓
  • Orchestrator = the gRPC server. Agents connect to it; it selects one for each task.
  • Agent = a gRPC client worker node. It also can run a small server for direct agent-to-agent data pipes (high-throughput streaming that bypasses the orchestrator).

Each aiflow.svc process is a cluster node that can play either role; a deployment runs a small number of orchestrators and a fleet of agents.

A single bidirectional streaming RPC carries everything:

service OrchestratorService {
rpc KeepAlive(stream AgentMessage) returns (stream ServerMessage) {}
}

The same stream multiplexes three kinds of message, discriminated by which field is populated:

KindFieldPayload
HeartbeatheartbeatJSON-encoded AgentParameters (metrics + metadata), the first message on a stream must be a heartbeat.
DatamessageOpaque bytes (a JSON-encoded typed message).
Chunked datachunkid + chunkendParts of a payload > 3.5 MiB, reassembled in order.

Typed message concepts (type/priority/TTL/control-action) live in Go and are serialized into the opaque bytes field. The wire itself stays simple.

Control messages travel the same way, in both directions: the orchestrator’s drain request, and an agent’s Drained, AtCapacity and capacity-available reports. The fabric handles them itself rather than passing them to a worker.

  1. Dial & register. The agent dials the orchestrator and sends an initial heartbeat carrying its AgentParameters: Status: active, TypeParameter: remote, and metadata, tags, capabilities.models (the model names it serves), tenants, exclusive, max_concurrent_tasks, its addresses, a session id for the process, and the agent protocol version it speaks. The orchestrator checks the agent’s service name and version (see Security) and its certificate identity, then registers it. Messages for the agent go through one ordered outbound queue, which outlives a reconnect (see Resilience).

  2. Heartbeat. A dedicated goroutine sends heartbeats on a jittered (±10%) interval, each carrying fresh metrics, the agent’s current task count, whether it is at capacity, and whether it is draining. A per-send mutex (streamSendMu) is held only across a single stream.Send, so a heartbeat can slip between chunks of a large transfer. A busy agent is never wrongly flagged unhealthy.

  3. Health classification. A per-agent watchdog compares the last heartbeat time to 2× the heartbeat interval. If stale, it marks the agent degraded (still selectable) when transport is otherwise alive, or unhealthy otherwise.

  4. Reconnect. When a connection ends, the agent dials again after a jittered heartbeat interval and keeps trying until it connects. Messages it sends meanwhile wait in its own queue, in order. The orchestrator takes a disconnected agent out of selection at once and gives it a grace window, five heartbeat intervals by default, to come back. A reconnect within the grace from the same process finds its queue intact, and the waiting messages go out in order. A newer connection of an agent takes over from an older one, so the cleanup of a stale connection leaves a reconnected agent in place.

    When the grace passes, or the agent comes back as a new process (a new session id), the orchestrator reports the agent lost. The messages queued for the old process are discarded, and its in-flight work goes to the engine’s agent-failure handling, which clears the agent’s affinity bindings and resumes or restarts each run that had a task on it.

  5. Drain. Drain(timeout) marks every agent that takes work (ready, at capacity or degraded) as draining and asks each one to drain. Draining and drained agents are offered no new work, including work pinned to them by id (an execution plan’s assignment or an affinity binding), which waits in the overflow queue for the agent’s return. A lookup of an agent’s address still reaches it for the work it holds. Each agent finishes the tasks its worker holds and sends their responses, which keep flowing during the drain, then reports Drained. Drain returns as soon as no agent is still draining, or with a drain-timeout error when the timeout passes first. An agent that reconnects in the middle of a drain registers as draining, or drained.

Agent states: Initializing → Connecting → Ready. From Ready an agent moves to AtCapacity while it holds its task limit and back to Ready when a slot frees, to Degraded, to Draining and then Drained, to Disconnected, or to Stopped. Agent types: local, remote, build.

Metrics per heartbeat: CPU cores & usage %, memory total/used/available/cached, data inflow/outflow, and (when present) GPU count/usage/VRAM/temperature and disk total/used/free. GPU metrics come from shelling out to nvidia-smi; disk from statfs.

For each Task node, the engine asks the orchestrator’s selector for a worker, the default selector, LeastCpuMemoryUseAgentSelector, keeps a hot in-memory cache (updated every heartbeat) plus a DB-backed store (written on connect/disconnect/health change).

Selection considers healthy, tenant-matching agents with capacity, and leaves out agents that are draining or drained. Every selector given applies together:

  • id / a list of ids names the agent; it must also meet the rest, and skips the capacity filter. A dispatch to a draining agent is refused.
  • tag: one of the agent’s tags.
  • model: one of the agent’s capabilities.models.
  • gpu / freegpu: a GPU with enough free VRAM %.
  • cpu / memory: a preference among the matching agents, not a floor.

Among the matches the pick rotates: per tag (an agent with a free slot preferred over a full one), per model, or by score (100 − CPU%) + FreeMem% [+ 0.5 × FreeGPUMem%] with the agent id breaking ties. A tag, model or id no agent ever declared refuses the start; one whose agents are all busy, draining or away makes the task wait.

These map directly to the selectors: you write in a flow (see authoring-flows.md §10).

  • Reservation (on the engine dispatch path) increments the agent’s task count under a lock and rejects at max_concurrent_tasks, TOCTOU-safe, so two dispatches can’t overfill an agent.
  • At capacity: an agent counts the tasks its worker holds and reports that count in each heartbeat. When it reaches max_concurrent_tasks it reports AtCapacity, and dispatch skips it until it reports a free slot. A draining agent stays draining whatever capacity it reports.
  • Transient vs permanent errors are load-bearing:
    • Transient (NoFreeAgent: matching agents exist but are full/unhealthy) → the engine queues the task and retries.
    • Permanent (NoMatchingAgent: nothing could ever match this tag/model/id) → fail fast.
  • Task groups (groups: in the flow, group: on a task) get one agent, chosen once for every member’s selectors together, within one run. Members wait for it while it is busy; when it is lost partway, the tasks left fail, or the group runs again from its first task (onagentlost: rerun).
  • Affinity pins across runs (single-agent / definition / payload), with bindings in aiflow_affinity_binding. On agent failure, bindings are cleared and the run resumes or restarts.

See authoring-flows.md §11.

PrimitiveBehaviorDefault
Per-agent queueOne ordered outbound queue for each agent, kept across reconnects. A failed send goes back to the head of the queue and ends the connection; the next connection sends it first. A send past the limit is refused with a queue-full error and counted in backpressure.count. Control messages, such as a drain request, are always queued.1000 waiting messages
Lost-agent graceA disconnected agent leaves selection at once and keeps its queue while it reconnects. Past the grace, or on return as a new process, it is reported lost and its work is re-placed. Set with agentlostheartbeats, or agentlostgrace as a duration.5 × heartbeat interval
Message sizeA message between the orchestrator and an agent carries a task’s request with the run’s context and memory, or a task’s output. One past the bound is refused at the sender with a message-too-large error, and one that arrives past it is dropped and logged. Control messages are not bounded. Set with maxmessagesize in bytes, -1 for none.20 KB
Circuit breaker3-state, one per connection; opens after N send failures, one probe to close after the reset window.5 failures / 30 s reset
Inbound deliveryMessages from an agent reach the engine in the order sent. Each one waits as long as the engine’s queue takes to accept it, so a slow consumer slows the agent’s stream through gRPC flow control.In send order
ReconnectThe agent dials again after a jittered heartbeat interval, until it connects.1 × heartbeat interval, ±10%

A message for an agent waits in that agent’s queue until it is sent. The queue empties only by sending, or when the agent is reported lost and the engine re-places its work.

When selection returns a transient “no free agent”, the flow engine persists the task as a aiflow_work_item and marks the instance Queued. A drain loop retries pending items (priority then age), continue-ing past starved tenants so one tenant can’t block others. Orphaned instances are re-queued on orchestrator restart. Depth is orchestrator.queue.maxdepth (0 = unlimited).

  • Transport: gRPC with mutual TLS. Every listener requires a client certificate and verifies it against the configured CA. Credentials come from the node’s workload identity, or from a grpccreds block: cacert, servercert / serverkey for the orchestrator’s listener and an agent’s own port, and clientcert / clientkey for an agent dialling in. An endpoint that lacks a credential it needs stops at startup with an error naming that credential. Plaintext gRPC runs only when the deployment sets zerotrust: false.
  • Version gating: an agent must carry the orchestrator’s service name and service version. The orchestrator and its agents are one build and are upgraded together, so an agent of any other service version is refused.
  • Agent identity: the orchestrator reads the identity of each agent’s verified client certificate (its SPIFFE ID, or else its subject common name). While an agent id is held, by a connected agent or one within its reconnect grace, a connection under another identity is refused with PermissionDenied; the same identity may reconnect. An agent’s tenants and exclusive flag are fixed when it registers, and its heartbeats leave them unchanged.
MeterMetricMeaning
kis.agentconnected (gauge)Currently connected agents.
kis.agentconnect.count / disconnect.countConnection churn.
kis.agentheartbeat.countHeartbeat volume.
kis.agentstate_change.countState transitions (tagged from→to).
kis.agentbackpressure.countSends refused because an agent’s queue was full (attribute kis.agent.id).
kis.selectorduration (histogram)Selection latency.
kis.selectorsuccess.count / fail.countSelection outcomes.
agent (OTel gauges)CPU/mem/GPU/disk, data.inflow/outflowPer-agent load.

Rising selector.fail.count, or a growing overflow queue, means you need more agents, or agents carrying the right tags and models. Rising backpressure.count points at one agent whose queue is full: its connection is slow or failing, or it takes work with no max_concurrent_tasks limit. See Operations for the knobs.