Engineering Long-Horizon Tasks for General-Purpose AI Agents
This article explores the engineering practices required to turn general-purpose AI agents into controllable, auditable, and measurable production systems. It examines the technical challenges of long-horizon tasks, proposes a five-layer decoupled agent runtime, and details approaches for context and memory management, least-privilege tool execution, template-driven software and document generation, security tiering, embodied AI boundaries, and cost-latency evaluation. Readers will find a practical checklist for moving from read-only pilots to stable, governed agent operations.
1. From Answering Questions to Doing Work: The Capability Leap of General-Purpose Agents
The technical narrative around next-generation general-purpose large models is shifting from “generating a piece of text” to “completing a unit of work.” Taking a recently released class of flagship general models as a reference, their core characteristics can be summarized in four points: stronger complex reasoning and software engineering capabilities, the ability to operate computers and software interfaces, support for long-horizon agent tasks, and the ability to call external tools and independently complete multi-step tasks. These models typically offer context windows of around one million tokens and maximum output lengths of around one hundred thousand tokens, support text and image input with text output, and can combine capabilities such as web retrieval, file retrieval, and code writing and execution.
It is worth emphasizing that these capabilities are not a proprietary selling point of any single vendor, but a shared direction in the evolution of current general-purpose large models. For enterprise developers, the truly valuable question is not “which model is the strongest,” but “how to engineer these capabilities into a controllable, auditable, and measurable production system.”
2. Technical Characteristics and Challenges of Long-Horizon Agent Tasks
Long-horizon tasks refer to work that requires dozens or even hundreds of interactions to complete, such as repository-level refactoring, cross-system data reconciliation, automated report generation, and web information collection and organization. Compared with traditional single-turn question answering, they introduce four new categories of problems:
- Context bloat: Historical trajectories quickly fill the window, and early critical constraints are “forgotten.”
- Error accumulation: A small-probability mistake in a single step is amplified after being chained across multiple steps.
- Tool side effects: Operations such as writing files, sending requests, and changing configurations have real-world impact.
- Evaluation difficulty: A correct final answer does not mean the process was compliant, and a compliant process does not guarantee an optimal result.
Therefore, the design focus of agent systems should shift from “prompt engineering tricks” to “runtime architecture.”
3. Reference Architecture: A Five-Layer Decoupled Agent Runtime
It is recommended to split the system into five layers, with clear contracts for inter-layer communication:
- Capability layer: General-purpose large model reasoning, multimodal understanding, and code generation.
- Orchestration layer: Task decomposition, plan trees, state machines, retry and rollback strategies.
- Tool layer: Retrieval, code execution sandboxes, browser automation, and file and spreadsheet processing.
- Memory layer: Short-term trajectory caching, long-term vector and structured memory, and permission tags.
- Governance layer: Identity and permissions, audit logs, monitoring and alerting, and cost accounting.
Orchestration layer sketch (pseudocode, expressing only the idea of control flow):
plan = planner.decompose(goal) # Generate a verifiable task treefor node in plan.executable_nodes(): # Execute only nodes whose dependencies are metctx = memory.build_view(node, budget=64_000)result = runtime.act(node, ctx, tools=node.allowed_tools)if not verifier.check(node, result):runtime.rollback(node.snapshot())plan.repair(node, feedback=verifier.report())memory.commit(node, result, acl=node.acl)
The key points are: plans are verifiable, actions are rollbackable, memory carries permissions, and execution has budgets.
4. Context and Memory Management: Treating the Window as a Scarce Resource
A million-token context does not mean information can be stuffed in without limit. In practice, it is recommended to adopt a combination of “layered summarization + retrieval recall + structured state”:
- Layered summarization: Generate summaries of historical trajectories by time slice, retaining decisions and constraints while discarding redundant output.
- Retrieval recall: Put specifications, interface documentation, and historical tickets into a retrieval store, and recall on demand rather than injecting everything.
- Structured state: Use key-value or tabular structures to maintain “current goal, completed items, pending confirmation items, and risk items,” which is more resistant to forgetting than natural language.
- Budget control: Set separate budgets for input, output, and tool returns, and trigger compression rather than truncation when limits are exceeded.
An example of a deployable state structure:
{"goal": "Generate quarterly business analysis and validate definitions","done": ["Data pulled", "Definitions aligned"],"pending": ["Chart generation", "Conclusion review"],"risks": ["Two versions of metric definitions exist"],"budget": {"input": 64000, "output": 12800}}
5. Tool Invocation and Execution Safety: Least Privilege by Default
Tools are the boundary where agents interact with the real world, and must follow least privilege and default deny:
- Tiered authorization: Separate read-only, write-draft, and write-production levels; production write operations require secondary confirmation.
- Sandboxed execution: Code and commands run in isolated containers, with restricted network egress and filesystem scope.
- Idempotency and rollback: Design idempotency keys and snapshots for all write operations, so failures can be safely replayed or undone.
- Full audit: Record “who invoked which tool, when, with what permissions, with what parameters and result summaries”; logs go into a centralized logging service with monitoring and alerting configured.
For high-risk actions in model output, a policy engine should perform pre-checks rather than relying on the model’s own restraint.
6. Software Engineering and Document Generation: Templates Over Free Reign
In programming and office document scenarios, stability comes from constraints rather than freedom. It is recommended to:
- Templates first: Use fixed templates and field validation for documents, spreadsheets, and presentations; the model only fills constrained slots.
- Specification-driven: First produce interface contracts and test cases, then generate the implementation, and finally run tests automatically in a sandbox.
- Small commits: Break large refactors into small, independently verifiable changes, each with a verification script.
- Diagnosable failures: Return structured error messages to the model, forming a “fail-fix” loop rather than a one-shot retry.
7. Security Tiering and Compliance: Caging High-Risk Capabilities
General-purpose models with relatively strong network attack and defense capabilities should be treated as highly sensitive assets. Engineering recommendations include:
- Capability tiering: Rate model capabilities at different sensitivity levels; the higher the level, the narrower the scope of access.
- Phased rollout: First trial in controlled enterprise tenants and whitelist projects, then gradually expand.
- Dual controls: Perform sensitive intent recognition on the input side, dangerous content filtering on the output side, and policy interception on the action side.
- Circuit breaking: Automatically degrade to read-only or suspend tool permissions when abnormal invocation patterns appear.
8. Embodied AI Scenarios: Potential and Boundaries
Recent observations show that general-purpose models exhibit some potential for spatial understanding and cross-scenario generalization in robotic embodied tasks, even if not specifically designed for robots. But the engineering reality is: fine manipulation, dynamic control, real-machine stability, and cost remain the main bottlenecks. A viable path is “upper-layer general decision-making + lower-layer specialized control”: the general model handles task decomposition and exception handling, while traditional control and perception modules handle millisecond-level closed loops, avoiding handing real-time control to the large model.
9. Cost, Latency, and Evaluation Systems
The cost of long-horizon tasks grows nonlinearly, so measurement must be established:
- Metrics: Task success rate, average number of steps, cost per task, human takeover rate, and rollback rate.
- Evaluation: Build a private enterprise task set covering normal, boundary, and adversarial samples, and run regression tests on every model or prompt change.
- Optimization: Reduce overhead through caching, summarization, tool result trimming, and model tiered routing (small models handle simple steps).
- Observability: Use trace linking to connect every step of invocation, locating latency and failure hotspots.
10. Implementation Checklist
- Start from read-only scenarios, then gradually open write permissions.
- Solidify templates and contracts first, then introduce model freedom.
- Design permissions, audit, and rollback as first-class citizens.
- Drive iteration with a private evaluation set; reject “it feels better.”
- Apply tiering and circuit breaking for highly sensitive capabilities.
- In embodied scenarios, stick to a layered architecture; do not outsource real-time control to the large model.
The real dividend brought by general-purpose large models is not replacing engineers, but handing repetitive, cross-system, long-chain work to a governable runtime. Whoever engineers the four things—permissions, memory, evaluation, and cost—first will be able to turn “doing work” into “doing work stably” earlier.
