Agent Harness Architecture Design and State Machine Practices: A Guide to Building Production-Ready AI Agents

    This article explains what an Agent Harness actually handles, why a business state machine is a requirement rather than an option, and how to structure real-time interaction, task orchestration, function calling, and compensation logic. It covers interrupt semantics, protocol correlation and acknowledgment barriers, host-side validation order, layered code review automation at scale, and a practical checklist for avoiding unmaintainable agent systems.

    1. Start With the Conclusion

    When teams begin building agent applications, the first instinct is often to find an all-in-one framework and expect it to solve business problems automatically. In practice, a mature Agent Harness can support multiple business scenarios, but it carries only two things: the real-time interaction layer and the task orchestration layer.

    It will not define your business states, perform rule validation for you, or provide cross-system transactions and compensation. You must add a “business state machine” layer on top of the framework.

    This leads to three engineering conclusions:

    • A general-purpose toolset is viable, but it is essentially just a protocol declaration. Tool descriptions define what can be done and what the parameters look like; the actual decision logic still lives inside the tool and is dispatched per scenario.
    • General-purpose tools cannot cover every scenario. High-risk, multi-step, strongly real-time business flows still require dedicated tools and dedicated validation paths.
    • A state machine is not optional. As soon as a business flow has multiple transitions, failure rollback, or human intervention, a state machine becomes a necessity.

    The goal of this article is to help you stay in the “designing an agent with high expectations” stage, rather than sliding into the “whack-a-mole in a bug swamp” and “self-deprecating memes” stages.

    2. What an Agent Harness Is Actually Responsible For

    2.1 Two Layers of Responsibility

    It is clearer to think of the Harness as a two-layer structure:

    Layer Responsible for Not responsible for
    Real-time interaction layer Session lifecycle, input/output channels, interruption and resumption Business rules, data consistency
    Task orchestration layer Task decomposition, tool dispatch, result return, timeout control Transaction rollback, compliance validation

    This table is the foundation of the whole article. Any approach that pushes business rules into the orchestration layer may work in the short term, but over time it inevitably evolves into an unmaintainable mess patched together through endless changes.

    2.2 Event-Driven, Not Blocking Execution

    The traditional calling habit is: receive a request, block while executing all tools, then return everything at once. The core model of a Harness is the opposite: an event-driven architecture of real-time foreground conversation + asynchronous background tasks + result return.

    A schematic flow looks like this:

    1. User input
    2. ↓
    3. Interaction layer parses intent → emits session event
    4. ↓
    5. Orchestration layer subscribes to event → dispatches background task (async)
    6. ↓
    7. Tool execution → produces intermediate events / final result event
    8. ↓
    9. Result return → interaction layer pushes at the right moment (interruptible, resumable)

    The benefits of this design are controllable latency and continuous experience: the foreground does not have to wait for all background work to finish before speaking, and a failed background task will not drag down the entire session.

    2.3 Three Distinct Semantics of Interruption

    A common mistake is treating “interruption” as a single operation. In reality it is at least three completely different actions:

    1. Interrupt the conversation: stop the current output while the task keeps running.
    2. Modify the background task: the task is still running, but its parameters or goal change.
    3. Cancel the background task: actually terminate execution and release resources.

    The three have completely different state transitions, idempotency requirements, and acknowledgment handling. If a single interface carries all of them, you will almost certainly see incidents where “the user only wanted to add a remark, but the whole task got canceled.”

    3. Protocol Correlation and Acknowledgment Barriers

    A Harness usually provides strict protocol correlation and acknowledgment barriers, but no cross-system transaction rollback. This statement needs to be unpacked.

    • Protocol correlation: every request, every tool call, and every returned result carries a traceable correlation identifier, used to reattach asynchronous results to the correct session.
    • Acknowledgment barrier: before a critical point, an explicit success acknowledgment must be received before the flow is allowed to advance; without an acknowledgment, the flow keeps waiting or enters a timeout branch.
    • Missing capability: cross-system consistency is something you must compensate for yourself.

    The engineering recommendation is therefore to introduce a “compensable business state machine” that achieves eventual consistency through states rather than rollback:

    1. # Illustrative: minimal skeleton of a business-side state machine (not tied to a specific product API)
    2. STATES = {"CREATED", "RUNNING", "AWAIT_CONFIRM", "DONE", "COMPENSATING"}
    3. def transition(ctx, event):
    4. if event == "tool_ok" and ctx.state == "RUNNING":
    5. ctx.state = "AWAIT_CONFIRM"
    6. elif event == "user_confirm" and ctx.state == "AWAIT_CONFIRM":
    7. ctx.state = "DONE"
    8. elif event in ("timeout", "tool_fail") and ctx.state in ("RUNNING", "AWAIT_CONFIRM"):
    9. ctx.state = "COMPENSATING" # trigger a compensation action, not a rollback
    10. return ctx.state

    Compensation actions should be idempotent and re-entrant, and every step should be written to a logging service, forming an observable closed loop together with monitoring and alerting.

    4. Function Calling: Give the Model an Interface Contract

    The essence of function calling is not that “the model learned to call code,” but that the model’s output is turned from free text into structured intent plus parameters, with schema constraints at the protocol layer (the industry commonly uses JSON Schema-style descriptions) limiting the shape.

    In a single inference pass, the model actually does three things:

    • Intent recognition: deciding whether an external capability is needed;
    • Route classification: choosing which tool to use;
    • Slot filling: filling in parameters under type constraints.

    The model is only responsible for “expressing the intent to call”; execution and validation are done by the host program. This leads to an important practice: validation must be repeated on the host side, because structured output can still contain semantic errors (parameters are valid, but the business case is not).

    A reusable validation order is: schema validation → business rule validation → permission and quota validation → idempotency key check → actual execution.

    5. Code Review Automation: Engineering Constraints at Large-Scale PR Volume

    A large social and professional networking platform has disclosed that it needs to review tens of thousands of code changes per week, across more than ten thousand repositories. Scenarios like this impose real constraints on an agent’s retrieval and review capabilities, and they confirm the conclusions above:

    • Failures are silent: a wrong review conclusion does not trigger an alert immediately.
    • Cost is unpredictable: the longer the context, the higher the overhead.
    • Security risk discovery lags: by the time it surfaces, the change has often already been merged into the main branch.

    A practical approach is to layer the process: first use rules and static checks to intercept deterministic problems, then let the model handle the parts that require semantic understanding, and finally hand high-risk changes to human review. The state transitions of the whole process should also be managed by a state machine rather than scattered across scripts.

    6. Four Stages of the Developer Journey and a Pitfall Checklist

    The typical path is: designing an agent with high expectations → “casting spells” in prompts → whack-a-mole in a bug swamp → self-deprecating memes.

    Three axioms are worth establishing up front:

    1. A mess is not written; it is “changed” into existence.
    2. In the agent era, a mess is not piled up by people, but by nobody reviewing while generation capability keeps getting added.
    3. Generation capability does not create a mess; it only amplifies problems in the existing structure.

    The corresponding pitfall checklist:

    • Externalize business state into a state machine; do not write it into prompts;
    • Distinguish interrupt semantics explicitly; do not merge interfaces;
    • Keep tools as “protocol declaration + internal dispatch,” with general-purpose and dedicated tools coexisting;
    • Full-chain correlation identifiers + acknowledgment barriers + compensation actions;
    • Keep human confirmation checkpoints for high-risk scenarios.

    If you are building similar capabilities from scratch, Baidu AI Cloud provides directly composable infrastructure in general categories such as container platforms, message queues, logging services, and monitoring and alerting, making it easier to put the state machine and observability chain described above into practice quickly without building every underlying component yourself.

    7. Conclusion

    The value of an Agent Harness lies in standardizing real-time interaction and task orchestration, shifting complexity from “missing framework” to “business modeling.” What truly determines system quality is whether the state machine layer you build on top of the framework is rigorous: whether states are explicit, whether transitions are verifiable, whether compensation is idempotent, and whether acknowledgments are traceable. Get these four things right, and agent applications can move from demo to production.