AI Agent Execution and Security: Engineering Practices for Large Language Models

    This article examines the shift of large language models from text generation to closed-loop task execution, and the security risks that come with it. It covers layered model matrices, long-context memory design, reasoning modes and multi-agent collaboration, a real-world file deletion incident under high-privilege modes, a five-gate defense architecture, quota and capacity governance, and a pre-launch checklist for running agents safely in production.

    1. The Trend: From Writing to Doing

    Since 2026, competition among large language models has clearly shifted from text generation quality to closed-loop task execution. A closed loop means the model does more than propose a solution: it calls tools, reads and writes files, executes commands, verifies results, and self-corrects when something fails.

    This shift has two direct consequences. First, the capability boundary has widened considerably, covering programming, data processing, 3D content generation, and long-running office automation. Second, the risk model has escalated in parallel: model output is no longer just “text that might be wrong,” but “operations that might actually take effect.”

    As a result, the focus of engineering practice is moving from prompt tuning to execution environment governance. Whoever can constrain execution permissions without sacrificing efficiency is the one who can put agents into real production.

    2. Capability Breakdown: Layered Model Matrices and Very Long Context

    The current mainstream approach is to offer a layered model matrix rather than a single general-purpose model:

    • Flagship: built for complex reasoning and long-chain agent tasks, optimized for the upper bound;
    • Balanced: a trade-off between quality and cost, suited to most mainstream business traffic;
    • Lightweight: high-concurrency, low-latency scenarios such as classification, extraction, routing, and intent recognition.

    Once the entire lineup ships with million-token context (the industry has generally entered the million-token range), the real engineering question is no longer “does it fit?” but “is it still usable once it fits?” Long context dilutes attention and loses information in the middle, so retrieved key fragments can easily get buried. A practical countermeasure is layered memory: write stable facts to external storage, compress conversation summaries into structured state, keep original long documents in object storage and fetch them on demand, and retain only the fragments the current step actually needs in the prompt.

    Illustrative context assembly logic:

    1. def build_prompt(task, state, store):
    2. # Inject only the stable facts and recent state required by the current step
    3. facts = store.get_facts(task.domain, limit=8)
    4. recent = state.last_k_steps(k=3)
    5. return f"""
    6. [Stable facts]
    7. {facts}
    8. [Current state]
    9. {recent}
    10. [Goal of this turn]
    11. {task.goal}
    12. [Constraints]
    13. Only whitelisted tools may be called; destructive operations require a second confirmation.
    14. """

    3. Reasoning Modes: When to Use High-Compute Reasoning and Multi-Agent Collaboration

    High-reasoning mode (often called extended thinking or deep reasoning in the industry) essentially trades more reasoning tokens for a lower error rate, at the cost of higher latency and cost. A sensible strategy is to route by task tier: intent recognition and format conversion go to lightweight models; code generation and refactoring go to balanced models; only architecture design, hard defect localization, and cross-system migration are escalated to high-reasoning mode.

    Multi-agent collaboration suits tasks that can be split and run in parallel, for example a “planner-executor-reviewer” triangle: the planner decomposes the steps, the executor calls tools, and the reviewer issues veto opinions based on tests and static checks. Note that multi-agent setups amplify errors rather than eliminate them. Without a unified source of truth and convergence conditions, agents can reach a mutually confirming but wrong consensus. In engineering terms, set a maximum number of iterations, explicit termination criteria, and conflict arbitration rules.

    4. Core Risk Case: Accidental File Deletion Under High-Privilege Modes

    After a recent generation of models was fully rolled out, multiple users reported that in high-privilege modes such as “full access” and “full autonomy,” and while an AI coding tool was running without sandbox protection, files in their personal directories were deleted due to operational mistakes. The vendor later classified this as unintended behavior. Its measures included updating prompts, hardening protections, and, in subsequent versions, having the system intercept forced-deletion commands and return clearer refusal reasons, along with a commitment to publish a post-incident report.

    From an engineering perspective, this is not “the model going bad” but the inevitable exposure of flaws in the permission model and execution environment design:

    1. Excessive permissions: full read/write/delete access granted by default;
    2. No isolation: running directly in the host user directory, with no container or virtual machine boundary;
    3. No gate for destructive operations: recursive deletion and forced overwrite commands were neither recognized nor blocked;
    4. No recoverability: no snapshots, versioning, or recycle bin mechanism;
    5. No observability: operation logs were insufficient for post-hoc tracing and accountability.

    5. Designing the Defense System: Five Gates

    Gate one, least privilege. Default to read-only, limit writes to the workspace directory, and forbid out-of-bounds paths; issue credentials temporarily per task, with short validity and revocation support.

    Gate two, sandbox isolation. Execute all commands in a container or lightweight virtual machine, mount host directories read-only, use a copy-on-write layer when necessary, and destroy the environment when the task ends.

    Gate three, command gate. Build recognition and interception rules for destructive commands; on a match, refuse and return a readable reason instead of executing silently.

    1. DANGEROUS = ("rm -rf", "del /f", "mkfs", "dd if=", "> /dev/", "chmod -R 777")
    2. def guard(cmd: str, workspace: str) -> tuple[bool, str]:
    3. if any(p in cmd for p in DANGEROUS):
    4. return False, "This command is a destructive operation and has been blocked by policy; use recycle-bin-style deletion or narrow the scope instead."
    5. if not within(cmd, workspace):
    6. return False, "The target path is outside the current workspace; access denied."
    7. return True, "ok"

    Gate four, recoverability. Enable snapshots and versioning for the workspace; deletions first go to a recycle bin with a retention period; sync important data to object storage with versioning enabled, forming a baseline where “mistakes can be rolled back.”

    Gate five, observability and auditing. Fully record tool calls, parameters, return codes, and operator identity; send logs to a centralized logging service, and use monitoring and alerting to detect and automatically circuit-break abnormal bulk deletions, abnormal outbound connections, and privilege escalation in real time.

    6. Quota and Capacity Governance

    High-reasoning mode and multi-agent collaboration significantly raise resource consumption per task. After opening up, vendors typically go through adjustments such as quota resets, temporarily relaxed rate limits, inference-side optimizations that improve effective throughput, and expanded quota reserve coverage. For enterprises, quotas should be managed as a budgetable resource:

    • Establish tenant-level quotas and priority queues to protect core pipelines;
    • Set caps on prompt length, number of tool calls, and iteration rounds to prevent agents from “spinning”;
    • Cache deterministic results to reduce repeated reasoning;
    • Use message queues to smooth peaks, and container platforms to elastically scale the inference front end and the tool execution layer;
    • Build a cost dashboard that attributes token and execution-time consumption by business line.

    7. Pre-Launch Checklist

    Before going live, confirm item by item: are default permissions read-only; is the workspace isolated and destroyable; are destructive commands intercepted with a reason returned; are deletions rollback-capable; can logs be traced to a specific task and user; is abnormal circuit-breaking in place; are quotas isolated per tenant; does high-reasoning mode have routing and budget constraints; do multi-agent setups have termination conditions and an arbitration mechanism; are incident response and post-mortem processes prepared.

    8. Conclusion

    Large language models are evolving from content generators into task execution systems, and capability gains and risk exposure are two sides of the same coin. Making permissions smaller, isolating the environment, blocking destructive operations, making state rollback-capable, and making behavior observable is what allows agents to run stably in real business over the long term. General cloud capabilities (object storage, container platforms, message queues, logging services, monitoring and alerting) can serve as the underlying foundation; validate specific choices and configurations against your actual workload on Baidu AI Cloud before rolling them out more broadly.