C-03 Agent Loop Controller
Brick C: Agents, autonomy, execution. French version: C-03-agent-loop-controller
1. Role and responsibilities
Drives an agent turn with enterprise_ai.runtime.AgentRunner: model call, then tool calls, until the final answer, under budgets (steps, tool calls, cost, duration). The Navin continuation rules (enterprise_ai.runtime.continuation.default_rules) prompt the model again when work remains (remaining_work), when the user already said go (go_ahead), when it must verify before finishing (verify_before_done, verify_failed), when the answer is empty or truncated (empty_final_response, length_recovery) or makes no progress (no_progress, wrap_up). The run plan is carried by enterprise_ai.loop.plan.RunPlan, which starts the next ready step automatically.
2. Position in the architecture and interactions
- Called by
AgentLoop.run_once()for each message or pending run. - Checks the heartbeat (
POST /v1/runs/{id}/heartbeat) before every model or tool call and stops onaction=stop. - Records steps (
POST /v1/runs/{id}/steps) and checkpoints.
3. Open source component and developed part
- Engine: Navin architecture of the Python SDK, with no declared graph.
enterprise_ai.loop.AgentLooptakes in messages, prepares the context, manages sessions, resumes a run after a crash, handles stop, cron and heartbeat, and exposesserve();enterprise_ai.runtime.AgentRunnerruns one turn;enterprise_ai.subagents.SubagentManagerruns sub-agents in parallel;enterprise_ai.loop.plan.RunPlancarries the plan;enterprise_ai.runtime.bus.MessageBuslinks channels and engine. - Optional adapters: LangGraph (
enterprise_ai.runtime.langgraph.build_graph) and Temporal (enterprise_ai.runtime.temporal.build_workflow) reuse the same steps; neither is required. - Server side,
python -m eai.workerruns the periodic jobs: scheduler tick, event outbox drain, quota reservation expiry, stale heartbeat detection, retention.
4. Data model
Tables (schema eai, tenant_id RLS):
eai.run_stepseai.runs
Common columns: id uuid, tenant_id uuid NOT NULL, created_at, updated_at; RLS policy current_setting('app.tenant_id', true)::uuid.
5. Contract
- Applied contract: execution-contract
- JSON Schema:
contracts/v1/execution-contract.schema.json - Key fields:
steps[].kind, steps[].status, budgets.max_steps, budgets.used - Validation:
POST /v1/contracts/{name}/validate; manifest apply:POST /v1/manifests/apply.
6. API endpoints
POST /v1/runs/{id}/stepsGET /v1/runs/{id}/stepsPOST /v1/context/plan
Request POST /v1/runs/{id}/steps:
{
"kind": "tool_call",
"name": "jira.search",
"input": {
"q": "INC-42"
},
"fingerprint": "sha256:9ab..."
}
Response:
{
"step_index": 4,
"status": "recorded",
"budgets": {
"steps_used": 4,
"max_steps": 20
}
}
7. SDK examples
Python:
from enterprise_ai import EnterpriseAI
from enterprise_ai.loop import AgentLoop
from enterprise_ai.loop.plan import RunPlan
client = EnterpriseAI(base_url="<control-plane-url>", api_key="eai_xxx_secret")
plan = RunPlan()
plan.add("collect", "Collect the ticket history")
plan.add("summarize", "Write the summary", depends_on=["collect"])
loop = AgentLoop(client=client, model="claude-sonnet-eu", agent_id="agt_support")
result = loop.run_once("Summarize INC-42")
plan.complete("collect", evidence="12 messages read") # the next ready step starts on its own
TypeScript:
import { EnterpriseAI, AgentRunner } from "@enterprise-ai/sdk";
const client = new EnterpriseAI({ baseUrl: "<control-plane-url>", apiKey: process.env.EAI_API_KEY });
const runner = new AgentRunner({ client, model: "claude-sonnet-eu", agentId: "agt_support" });
const turn = await runner.runTurn([{ role: "user", content: "Summarize INC-42" }]);
Java:
EnterpriseAIClient client = EnterpriseAIClient.builder()
.baseUrl("<control-plane-url>")
.apiKey(System.getenv("EAI_API_KEY"))
.build();
var run = client.runs().start("agt_support", Map.of("task", "Summarize INC-42"));
var answer = client.heartbeats().beat(run.get("id").asText(), Map.of("step", "plan"));
Go:
c, _ := eai.NewClient(eai.WithBaseURL("<control-plane-url>"), eai.WithAPIKey(os.Getenv("EAI_API_KEY")))
run, _ := c.Runs.Start(ctx, "agt_support", map[string]any{"task": "Summarize INC-42"})
answer, _ := c.Heartbeats.Heartbeat(ctx, "run_01J9", map[string]any{"step": "plan"})
8. Configuration
- Environment variables:
EAI_DATABASE_URL - Helm keys:
controlPlane.config - Client side:
AgentRunnerandLoopBudgetbudgets (steps, tool calls, cost, duration)
9. Security controls
- Every tool action goes through the Tool Gateway (policy, DLP)
- spec.autonomy level bounds actions without approval
- Every request carries the tenant resolved from the credential; PostgreSQL RLS
- Every mutation and policy decision writes a hash-chained audit event
10. Observability
- Prometheus metrics:
eai_loop_steps_total,eai_loop_detected_total,eai_loop_stop_reason_total{reason} - Traces: OpenTelemetry spans with GenAI semantic conventions (
gen_ai.operation.name,gen_ai.agent.id,gen_ai.tool.name), attributeseai.tenant_id,eai.run_id,traceparentpropagation. - Audit actions:
run.transition
11. FinOps units
- Tokens per step, cumulative cost per run.
- Emitted as Usage Event (
POST /v1/finops/usage) with tenant, project, agent and run.
12. Failure modes and resilience
- Loop without progress: the
no_progressthenwrap_uprules force a conclusion - Budget reached: the turn stops with the reason of the limit reached
- Stop requested by heartbeat or kill switch: stop before the next call
13. Standalone adoption (client of a client)
- enterprise_ai.agent (local loop) + model gateway only.
- SDK:
enterprise_ai.agent(AgentsClient,RunsClient,SessionsClient) - Minimal deployment: Helm chart with
controlPlane.enabled=trueand PostgreSQL; disabled external components use their in-process fallback.
14. Acceptance tests
- 3 identical calls -> loop_detected stop
- max_steps reached -> state failed budget_exceeded
- Cross-tenant access refused
- Error returned in fr with Accept-Language: fr