Agent Runtime Framework Development: From Architecture to Secure Production Deployment

    This article explains how to build an agent runtime framework that moves beyond single model calls to reliable task execution. It covers task scoping, layered architecture, explicit state machines, controlled tool contracts, context and memory management, security boundaries, failure recovery, observability, and a staged validation path from prototype to production. The focus is on embedding probabilistic model decisions within deterministic engineering constraints so that agent actions are checkable, conclusions are traceable, and failures are explainable.

    1. From Model Calls to Task Execution Systems

    The core value of an agent runtime framework is to organize a model’s language understanding and decision-making capabilities into an execution system that can advance a task. The model is responsible for understanding goals, proposing actions, and generating results. The runtime framework is responsible for preserving state, scheduling tools, checking permissions, handling exceptions, and determining whether a task should continue.

    For example, a user may ask to “organize recent business materials, analyze abnormal changes, and produce a report.” This request typically involves several stages: material retrieval, data reading, definition alignment, analytical calculation, and report generation. A single model call cannot reliably cover the entire process. The model may lack necessary data, fail to recover correctly after a tool execution failure, or even describe an operation that has not been executed as if it were already complete.

    Therefore, when developing task-oriented agents, three basic principles should be established first:

    • Model output is an action proposal, not automatically a valid instruction.
    • A tool return is execution evidence, not automatically a trustworthy conclusion.
    • Task completion must be based on acceptance criteria, not solely on the model’s self-judgment.

    A runtime framework designed around these principles can help an agent move from “being able to answer” to “being able to complete work under constraints.”

    2. Define Task Boundaries Before Pursuing General Autonomy

    1. Define Goals Through a Business Loop

    Before development, the input, output, available resources, and acceptance standards should be clearly defined. Rather than defining an agent that “can handle all business problems,” it is better to focus first on a clearly bounded scenario, such as read-only material analysis.

    For this scenario, the system can specify that the input is a problem description, material scope, and time range; the output is an analysis report, cited evidence, and unresolved items; material retrieval and statistical calculation are allowed; and modifying source data or sending information externally is prohibited.

    These constraints not only reduce implementation complexity but also give testing a clear basis. Whether the report covers key questions, whether statistical definitions are consistent, and whether conclusions have sources can all become checkable acceptance items.

    2. Separate Deterministic Steps from Model Decisions

    Not every step should be left to free-form model planning. Permission checks, date format validation, numerical calculation, file writing, and approval status confirmation are better handled by deterministic logic.

    Models are well suited to intent understanding, information summarization, candidate action selection, and natural language expression. A reasonable division of labor between these two types of capabilities is key to improving reliability. For businesses with many fixed processes, process orchestration can control the main path and call the model only at nodes that require semantic judgment. For exploratory tasks, the model can be allowed to propose the next action, but the executor should still decide whether it can be executed.

    3. Build a Layered Runtime Architecture

    A general agent runtime system can be divided into the following responsibility layers:

    Layer Main responsibilities Practical focus
    Task entry Receive requests, verify identity, create tasks Input validation and permission binding
    Decision layer Understand goals, select the next action Structured output and constraint checking
    Execution layer Invoke tools, collect results, handle failures Timeouts, idempotency, and exception classification
    State layer Preserve progress, context, and execution records Recoverability and traceability
    Memory layer Store reusable preferences and knowledge Source, validity period, and isolation
    Security layer Control permissions, approvals, and resource boundaries Default deny and least privilege
    Observability layer Record events, metrics, and evaluation results End-to-end diagnosis and quality analysis

    These layers do not necessarily correspond to independent services. In the prototype stage, they can be implemented within a single application, but responsibility boundaries should remain clear. Tool execution, state updates, and model requests should not be mixed into the same untestable function.

    For business write operations, the execution layer should have final control. The decision layer can only submit a structured proposal to “request execution of an operation”; it must not bypass permission checks and directly reach external resources.

    4. Organize the Execution Loop with an Explicit State Machine

    Agents usually advance tasks through an “observe—decide—execute—update” loop. The loop itself is not complex. The complexity lies in how the system maintains consistency during failures, pending approvals, or service interruptions.

    It is recommended to define explicit states for tasks, such as pending execution, running, waiting for approval, completed, failed, and canceled. Every state change should preserve the reason and associated event, so that a task does not exist only in process memory.

    A task record should contain at least:

    • The user goal and task scope.
    • The current stage and completed steps.
    • Verified facts and related sources.
    • The most recent tool call and a summary of its result.
    • Remaining steps, time, or resource budget.
    • Operations pending approval and failure reasons.

    The following generic pseudocode is intended only to illustrate control logic and does not represent any actual framework interface:

    1. Create a task and bind access permissions
    2. While the task is not in a terminal state:
    3. Check cancellation requests, deadlines, and execution budget
    4. If the task cannot continue:
    5. Persist the termination reason
    6. End the loop
    7. Build the context for this round from task state
    8. Ask the model for a structured action proposal
    9. Validate action type, parameters, and permissions
    10. If the action is to submit a final result:
    11. Run business acceptance checks
    12. If completion conditions are met:
    13. Persist the result and end
    14. Else:
    15. Write missing items into state
    16. Continue the loop
    17. If the action requires approval:
    18. Persist the pending-approval state
    19. Pause execution
    20. Else:
    21. Invoke the tool
    22. Classify and handle the execution result
    23. Persist events and the latest state

    The loop must have termination mechanisms; otherwise, the model may repeatedly retrieve the same information or continuously revise the plan. In addition to total step and time limits, the system can also detect repeated actions, consecutive lack of progress, and recurrence of the same error. When a limit is triggered, the system should return the completed content and the blocking reason, rather than generating a seemingly complete result that lacks evidence.

    5. Design Tools as Controlled Capabilities

    1. Establish Clear Tool Contracts

    Tools are the boundary between the agent and the real environment. A tool should have a clear purpose, input structure, output structure, access permissions, and side-effect description.

    For example, “read business records” should specify the accessible data scope; “generate report file” should restrict the output location; “submit approval request” should require the target object, operation summary, and necessary authorization basis.

    Tool contracts should also specify data units, time ranges, pagination rules, and the meaning of missing values. Otherwise, even if a call succeeds, the model may reach an incorrect conclusion because it misunderstands field meanings.

    Tool granularity also needs to be moderate. Tools that are too broad are difficult to authorize and audit, while tools that are too fragmented increase the number of calls and the cost of state coordination. In general, tools should be divided around verifiable business actions rather than directly exposing all underlying operation capabilities.

    2. Separate Read and Write Capabilities

    Read-only operations and write operations carry different risks and should not share the same authorization path. Material retrieval can be executed directly according to data permissions, while deleting records, updating configurations, or submitting external requests should go through stricter checks and, when necessary, human approval.

    Write operations also need idempotency mechanisms. A network timeout does not mean the operation did not occur, and automatic retries may cause duplicate submissions. Business operation identifiers, execution records, and result query mechanisms can be used to determine whether an operation has already been completed. When multiple systems are involved, simple retries should not be assumed to achieve global consistency. Compensation operations or manual handling processes should be adopted according to business characteristics.

    3. Normalize Tool Results

    Tool output should distinguish between success, empty result, insufficient permission, parameter error, temporary unavailability, and unknown execution status. It should not return only a natural language error message and leave the model to guess what happened.

    In particular, avoid interpreting “no data was retrieved” as “the situation does not exist in the business.” The former may be caused by permissions, scope, or indexing delay, while the latter is a business conclusion that requires sufficient evidence.

    6. Context Management: Preserve Useful Information, Not Accumulated History

    Context space is limited. Appending all conversations, logs, and tool outputs in full increases computational overhead and can easily drown key constraints in noise.

    A more reasonable approach is to layer information:

    1. Stable rules: permission boundaries, output requirements, and security constraints.
    2. Task state: goals, current stage, completed items, and unresolved issues.
    3. Recent evidence: tool results that must be used for the current decision round.
    4. Historical index: locations and retrieval conditions of archived materials.

    For long execution histories, structured summaries can be stored, but summaries should not be treated as a lossless replacement. Important information such as amounts, dates, units, error codes, approval conditions, and key citations should retain original values or traceable records.

    Context compression should also avoid “summary drift”: repeated paraphrasing may gradually change facts. In practice, confirmed facts can be stored separately with source, verification status, and update time. Each time the model context is built, relevant content should be selected from these records rather than repeatedly compressing the previous summary.

    7. Memory Management: Distinguish Facts, Preferences, and Inferences

    Long-term memory can reduce repeated questions, but it can also amplify errors and privacy risks. During development, it should be clear what information is worth storing and what tasks the stored information can be used for.

    Common memory can be divided into three categories:

    • User preferences, such as report language, presentation format, and commonly used statistical definitions.
    • Confirmed business knowledge, such as terminology definitions and verified process descriptions.
    • Reusable task experience, such as which conditions should be checked first for a certain type of problem.

    Unverified model inferences should not directly become business facts. Temporary authorization should not automatically extend to future tasks simply because it has been recorded. Memory reads still require permission checks, especially to prevent information leakage between different users or different business spaces.

    Each important memory item should preferably include source, creation time, validity period, applicable scope, and verification status. The system should also support query, correction, and deletion, and should invalidate or revalidate related memories after source materials are updated.

    8. Secure Execution: Treat External Content as Data

    Agents may read documents, messages, and tool-returned content that contains text intended to induce them to change task goals, leak information, or invoke high-risk tools. Such content should not gain control over the system simply because it appears in retrieval results.

    A clear distinction should be made between trusted rules, user authorization, and external materials. External materials can only be treated as data to be analyzed; they cannot override permission boundaries or authorize new operations.

    Security controls should be implemented at the execution layer:

    • Validate user identity and resource permissions on every tool call.
    • Restrict accessible data scope and output locations.
    • Perform necessary redaction and minimization for sensitive information.
    • Store credentials in controlled configuration and prevent them from entering model context.
    • Provide explicit approval processes for high-risk operations.
    • Process untrusted code or files in restricted execution environments.
    • Retain audit records for access, modification, and export activities.

    Human approval should not be merely a generic “approve or reject.” The approval page should show the specific target, operation scope, and expected impact, and bind the approval result to that operation to prevent parameters from changing after approval.

    9. Failure Recovery and Observability

    Failure recovery should be based on error type rather than uniform retries. Temporary network problems can be retried within limits; parameter errors should be corrected by fixing the input; insufficient permissions should stop the related action; when the execution result is uncertain, the system should query the status first.

    For long-running tasks, checkpoints should be saved at key nodes. After a service restart, the system should decide whether to continue execution or wait for confirmation based on persisted state, avoiding repeated execution of operations with side effects.

    Observability should cover the entire task chain. It is recommended to record task identifiers, step order, tool category, latency, error type, retry count, and state changes. For model-related records, data protection requirements should be followed, and complete sensitive context should not be stored indiscriminately.

    Quality analysis should not only examine whether a request succeeded. It should also consider task completion rate, human intervention ratio, invalid tool calls, repeated actions, acceptance failure reasons, and resource consumption per task. These metrics need to be interpreted in context; fewer calls should not be simply equated with higher quality.

    10. Establish a Validation Path from Prototype to Production

    Deployment can proceed in stages.

    The first stage focuses on read-only tasks, validating tool contracts, context organization, and result acceptance. Priority should be given to ensuring that outputs have sources and can distinguish facts, judgments, and uncertainties.

    The second stage adds state persistence, failure classification, execution budgets, and recovery mechanisms to ensure that progress is not lost after a task interruption and that dangerous operations are not repeated.

    The third stage introduces controlled write operations, approvals, and auditing, with emphasis on testing duplicate requests, execution timeouts, permission changes, and uncertain operation results.

    The fourth stage establishes continuous evaluation. The test set should cover not only normal tasks but also abnormal scenarios such as missing materials, unavailable tools, malicious external instructions, contradictory evidence, and user cancellation midway. Conclusions involving business quality should be verified through a combination of rule-based validation and human sampling.

    Conclusion

    The essence of agent runtime framework development is to embed probabilistic model decisions within deterministic engineering constraints. The model provides understanding and planning capabilities; tools provide verifiable action results; the state system maintains execution continuity; security mechanisms define operation boundaries; and the evaluation system determines whether a task is truly complete.

    A reliable practice path is not to continuously expand the scope of autonomy, but to first establish clear task boundaries, explicit tool contracts, and recoverable execution flows, and then gradually add capabilities based on test results. Only when every action is checkable, every conclusion is traceable, and every failure is explainable can an agent have the engineering foundation to continuously take on complex tasks.