Intelligent Programming Agent Architecture: From Bootstrapping to Multi-Agent Scaling

    This article explores the architecture of intelligent programming agents, moving beyond simple reasoning loops to address complex requirements like interactive execution, unattended operation, and session recovery. It covers the startup chain, runtime core design using explicit state machines, tool governance, permission boundaries, background task management, and multi-agent scaling. By establishing clear execution boundaries and robust verification mechanisms, teams can build reliable agent systems that prevent unbounded complexity.

    1. Defining the Problem: An Agent System Needs More Than an Inference Loop

    The basic form of an intelligent programming agent is not complex: receive a goal, call a model, execute a tool, and pass the result back to the model for further judgment. However, when a system simultaneously supports interactive execution, headless execution, remote connections, background tasks, and session recovery, this simple loop easily becomes a focal point of complexity.

    For example, a file modification operation can wait for user confirmation in a local interactive environment, but in an unattended environment, it must rely on preset policies. A foreground user exiting does not necessarily mean a background task should terminate immediately. When resuming a historical session, it is unsafe to assume that past permissions remain valid. If all these differences are crammed into the main loop, the system will be dragged around by numerous branching conditions.

    Therefore, when analyzing such systems, what matters more than the number of features is how it divides responsibilities, constrains state changes, and handles failure and recovery.

    This article discusses general architecture design. The layered approach to startup routing and process initialization is derived from original materials, while sections on tool governance, task scheduling, and multi-agent collaboration are supplementary engineering practices centered on this topic and should not be interpreted as source code conclusions for any specific implementation.

    2. The Startup Chain: Choose the Running Mode Before Building the Execution Environment

    1. The Entry Layer Should Route Traffic, Not Handle All Initialization

    The entry layer must first answer three questions:

    • What type of task needs to be executed for this startup?
    • What runtime capabilities are required?
    • Which components can be completely left unloaded?

    Displaying help information, processing simple configurations, and starting a full interactive session clearly do not require the same initialization costs. A reasonable design first identifies the startup intent and then loads the corresponding components, preventing every entry point from initializing the interface, network connections, tool registration, and task scheduler.

    Lazy loading is not a case of “the more, the better.” Loading components too late may defer startup errors to the time of first use; lacking unified management during loading can also lead to duplicate initializations. In practice, components should be divided according to dependency relationships, and it should be explicitly stated whether initialization allows reentrancy and whether it can retry upon failure.

    2. Process Initialization and Session Assembly Must Be Separate

    Process-level facilities typically include configuration reading, diagnostic logging, resource cleanup, connection management, and shared caching. They serve the entire process and should not be directly bound to a specific user goal or conversation segment.

    Session-level state includes:

    • Current working directory and accessible resource scope;
    • Session identity, history, and context budget;
    • Available toolset for the current task;
    • Permission policies, approval channels, and cancellation signals;
    • Input/output methods and recovery position.

    Mixing the two will result in global objects carrying session state. Single-session testing might not reveal issues, but when multiple sessions run in parallel, working directories, permissions, and messages may experience cross-talk.

    The startup process can be abstracted as:

    1. Parse startup intent
    2. ↓
    3. Select running mode
    4. ↓
    5. Initialize process-level facilities
    6. ↓
    7. Assemble session context
    8. ↓
    9. Start execution loop

    The value of this sequence lies in converging mode differences early, allowing the subsequent execution engine to face a clear environment rather than constantly guessing which host it is running in.

    3. Session Recovery Should Restore Task State, Not Revive Old Environments

    When recovering a session, the system should read historical messages, task checkpoints, and execution results, but it must re-verify the working directory, tool availability, resource access scope, and current permissions.

    The reason is straightforward: during the session pause, files may have changed, credentials may have expired, and administrators may have modified authorization policies. Historical records can serve as factual evidence, but the old environment cannot be directly treated as the current environment.

    It is especially important to distinguish between “recovering a conversation” and “recovering execution.” Recovering a conversation means continuing to understand the history; recovering execution may re-trigger external side effects, which must have stricter conditions.

    3. The Runtime Core: Constraining Models, Tools, and Events with State Machines

    1. Models Determine Candidate Actions; the Runtime Enforces Execution Constraints

    A model can propose tool calls, but it should not be the final executor of permission, concurrency, and persistence rules. Otherwise, the system boundaries will change as prompts and context change.

    A more stable approach is to design the runtime core as an explicit state machine, for example:

    1. Waiting for input → Building context → Requesting model → Checking action
    2. ↓
    3. Waiting for approval or executing tool
    4. ↓
    5. Recording result and continuing reasoning

    Completion, failure, and cancellation should have explicit states; waiting for approval cannot simply be viewed as “tool running” because the timeout, recovery, and user interaction requirements are different.

    The core significance of a state machine is restricting which transitions are legal. For instance, after a session is canceled, it should not re-enter reasoning due to a late tool result; a completed task should not consume duplicate completion events.

    2. Convert Tool Results to Events to Avoid Directly Modifying the Session

    The tool executor should ideally not directly rewrite conversation history, UI state, or task phases. Instead, it should return structured results to be uniformly processed by the runtime core.

    Events can express facts such as tool start, tool end, approval request, cancellation request, and subtask completion. This way, interactive interfaces and remote connections act merely as display or transport layers for events, without needing to maintain their own business semantics.

    Note that event-based design does not mean storing all content indefinitely. Large files, sensitive fields, and binary results can be stored in controlled storage, with events retaining only references, necessary summaries, and status. Event ordering also requires clear rules to prevent concurrent results from altering the logical sequence of the session.

    3. Retries Must Consider Side Effects

    Model request failures and file write failures cannot use the same retry strategy.

    Reading a file can typically be repeated; sending notifications, creating tasks, or committing changes may produce duplicate side effects. For write operations, the system should first determine whether it can use idempotency identifiers, execution logs, or state verification to avoid duplicate processing.

    A typical risk is that an external operation succeeds, but the result fails to persist. Upon recovery, the runtime only sees “incomplete” and executes it again. To handle this, the system should record execution intent and confirmation results, and provide a verification process for uncertain states; high-risk actions that cannot be verified should be transferred to manual confirmation rather than blindly retried.

    4. Tool Governance: Unified Contracts Are More Important Than Increasing Tool Count

    1. Tools Need More Than Just Input Parameter Descriptions

    A unified tool contract should cover both functionality and runtime constraints:

    • Input structure and validation rules;
    • Required permissions and resource scope;
    • Whether it produces side effects;
    • Timeout, cancellation, and concurrency limits;
    • Return results, error types, and retryable conditions.

    The following is a schematic structure and does not correspond to any actual product interface:

    1. Tool Definition:
    2. Name
    3. Input Constraints
    4. Required Capabilities
    5. Side Effect Category
    6. Execution Timeout
    7. Result Constraints

    Tool descriptions tell the model “what this tool can do”; tool contracts tell the runtime “under what conditions this action is allowed.” The two are not interchangeable.

    2. Correct Parameters Do Not Mean Safe Operations

    A valid file path syntactically does not mean it is within an authorized directory; a resolvable network address does not mean access is permitted; a modification request matching the input format does not mean the current user has write permissions.

    Therefore, validation should be divided into at least two layers:
    The first layer checks structure and types, rejecting malformed calls.
    The second layer performs semantic checks combining session identity, working directory, resource scope, and policies.

    For file access, situations like symbolic links, path normalization, and resource changes after inspection should also be considered. When conditions permit, isolated environments and actual access controls should be combined, rather than relying solely on a single string check before execution.

    3. Extension Access Must Not Bypass the Unified Execution Path

    Whether tools come from built-in modules or external extensions, they should go through the same parameter validation, permission checks, audit logging, and result processing flow.

    If extensions can directly obtain internal process objects or execute arbitrary callbacks, the so-called permission model will easily constrain only built-in tools while failing to constrain extensions. A safer approach is to provide limited capability interfaces to extensions rather than exposing the entire runtime.

    5. Permission Boundaries: Prompts Are Not Security Controls

    1. Permissions Must Be Evaluated Before Actual Execution

    “Do not delete important files” can be written into a prompt, but this is merely behavioral guidance, not a deterministic security boundary. Real authorization should occur before the tool call enters the executor.

    Permission decisions typically include at least three outcomes: allow, deny, and request approval. In unattended modes where interactive approval is impossible, the system should deny or pause based on preset policies, rather than converting “unable to ask the user” into a default allow.

    Approvals should also be bound to specific actions. A user approving an operation should not automatically become unlimited authorization for all subsequent similar operations.

    2. Tool Output Is Data, Not Inherently Authoritative Instructions

    File contents, external returned text, and sub-agent messages may all contain seemingly reasonable instructions. The runtime needs to retain their source and trust level, avoiding upgrading “read content” into system rules.

    For example, if a file segment requests an expansion of access scope, this can only be treated as file content and cannot be used to change permissions. For inputs that might induce the model to perform dangerous actions, deterministic tool authorization, restricted execution environments, and approval mechanisms remain key defense lines.

    3. Permission Checks and Log Desensitization Must Be Designed Together

    Auditing requires sufficient information to explain why an action was allowed, but this does not mean writing complete credentials, sensitive file contents, and all tool outputs into logs.

    A reasonable audit record should include the subject, action category, target resource, decision result, and necessary policy basis. Sensitive values should be desensitized or only retain controlled references, with access permissions and retention periods set.

    6. Background Tasks: Decouple Work Lifecycle from Connection Lifecycle

    A disconnected foreground connection only means the user is temporarily unable to interact; it does not necessarily mean task termination. Background execution requires independent task identifiers, state storage, output buffers, and reconnection mechanisms.

    At the same time, not all tasks are suitable for continued execution. For example, a high-risk operation waiting for approval cannot be automatically executed just because the user left; tasks depending on temporary resources may also need to be paused or canceled.

    Background scheduling should limit concurrency, execution duration, model consumption, output size, and pending queue length. Without these constraints, an agent continuously creating subtasks could exhaust system resources.

    Cancellation should also be viewed as a process, not a button state. Cancellation requests need to propagate along the call chain; the executor should stop new side effects and attempt to interrupt running operations. If an external action cannot be interrupted immediately, the system must honestly mark it as “canceling” or “termination unconfirmed,” rather than prematurely declaring success.

    7. Multi-Agent Scaling: Division of Labor Requires Isolation and Aggregation

    1. The Value of Multi-Agent Systems Comes from Independently Verifiable Task Division

    Increasing the number of agents does not automatically improve quality. Work suitable for splitting usually has clear inputs, independent boundaries, and checkable deliverables—for example, separately analyzing API constraints, sorting out test scenarios, and checking risks, before aggregation by the main agent.

    If multiple agents simultaneously modify the same set of files without ownership, version checks, or merge rules, parallel execution will only amplify conflicts.

    Therefore, multi-agent design should first determine task boundaries and then decide the parallelization method, rather than first creating multiple roles and then looking for work to assign them.

    2. Sub-Agents Should Receive Minimum Necessary Context and Permissions

    The information a sub-agent needs typically includes the task goal, relevant materials, allowed tools, resource scope, and result format, rather than the entire history of the main session.

    This trimming reduces irrelevant context and sensitive information exposure, but it comes at a cost: if critical constraints are omitted, the sub-agent may produce results that are locally correct but globally inapplicable. Therefore, task descriptions should explicitly include acceptance criteria, prohibited actions, and dependency conditions.

    Permissions should also be converged according to the task. The parent agent having write permissions does not mean every sub-agent responsible for analysis needs write permissions; a specific approval by the parent agent should not automatically authorize the sub-agent to perform different actions.

    3. Subtasks Require Limited Recursion, Budgets, and Lifecycles

    Sub-agents should record their parent task, execution status, budget, deadline, and result location. For behaviors that continue to create sub-agents, limits should be placed on task count, recursion depth, and overall resource consumption.

    When the parent task ends, it must be clear how subtasks are handled: cancel, wait for completion, or run independently after receiving explicit authorization. Otherwise, the system is prone to generating orphaned background tasks that are difficult to track and reclaim resources from.

    4. Verify Evidence Before Aggregating Results

    The main agent cannot directly treat sub-agent conclusions as facts. Sub-agents should state what they completed, the basis for it, what objects they modified, what unverified items exist, and whether they encountered permission or resource limits.

    The main agent then checks the actual deliverables based on task requirements. For code modifications, the scope of changes and test results should be verified; for analysis conclusions, consistency between evidence and conclusions should be checked. Multi-agent systems do not eliminate model errors; they only provide clearer division of responsibility and cross-validation opportunities.

    8. Observability and Testing: Verify Boundaries, Not Just Ideal Flows

    A complex task should be able to correlate sessions, tasks, model requests, tool calls, approvals, and subtasks. When an anomaly occurs, developers need to know whether the failure happened during reasoning, authorization, execution, persistence, or result aggregation.

    Testing should also be designed around these boundaries, focusing on:

    • Unattended mode encountering an approval request;
    • Tool executes successfully, but result writing fails;
    • Cancellation and tool completion events arriving simultaneously;
    • Multiple sessions accessing the same resource;
    • Permissions or file state changed upon session recovery;
    • Sub-agent timeout, duplicate returns, or loss of parent task;
    • External content inducing expanded permissions;
    • Output too large causing context or storage budget exhaustion.

    Model outputs are uncertain, so automated testing should not merely compare reply text. What is more important is to assert: whether unauthorized actions are blocked, whether state transitions are legal, whether side effects are duplicated, whether resources are released, and whether audit information is complete.

    9. Implementation Order: Establish Execution Boundaries Before Expanding Intelligence

    For teams building intelligent programming agents, progress can be advanced in the following order:

    First, unify entry routing, separate process initialization from session assembly, and prevent different running modes from forming different business rules.

    Second, establish explicit state machines and tool contracts, moving permissions, timeouts, cancellations, and error handling out of prompts.

    Third, complete execution logs, checkpoints, and recovery rules, prioritizing operations with side effects.

    Fourth, decouple background tasks from foreground connections, introducing queues, resource budgets, and task reclamation mechanisms.

    Fifth, add multi-agents only after single-agent execution is reliable, while simultaneously designing least privilege, conflict resolution, and result verification.

    Sixth, verify the system using fault injection and security boundary testing, rather than judging maturity solely through success demos.

    The long-term quality of an intelligent programming agent depends on whether it places uncertainty in the right position: the model is responsible for understanding and proposing candidate actions, the runtime is responsible for constraining execution, tools are responsible for completing specific operations, the permission system is responsible for guarding boundaries, and the task system is responsible for coordinating lifecycles. Only when these responsibilities can be independently verified will expanded capabilities not evolve into uncontrolled complexity.