Java AI Agent Architecture: Memory, Task Scheduling, Skills, and Sandbox Practices
This article explains why a conversational Java agent is not yet a production system and what a practical agent runtime must provide. It covers a layered memory model that moves from in-process windows to file-based storage, long-term task scheduling with idempotency and recovery, hot-pluggable skills based on a registry, protocol-based tool integration, and sandboxed code execution. It closes with a recommended layered architecture and a safe rollout order.
1. Where the Problem Starts: Why “Being Able to Chat” Is Not “Being Able to Work”
Most teams building their first agent in the Java ecosystem follow the same path: connect a model, write a prompt, add a conversation window and a single function call. The demo looks good. In real business scenarios, the problems surface quickly:
- Context is lost after a process restart.
- Tasks that must run “tomorrow morning” have nowhere to live.
- Every new business capability requires changing the main flow and redeploying.
- External tools are integrated in different, incompatible ways.
- Model-generated code cannot be executed safely.
The common root cause is that what the agent lacks is not model capability but a runtime. A usable agent runtime must solve at least five things: state, time, extensibility, interoperability, and isolation. Each is covered below.
2. Memory Management: From In-Process Windows to File-Based Memory
2.1 Three Hard Limits of the In-Memory Window
Keeping history in a heap-resident list and retaining only the last N turns is common in the prototype stage. Its problems:
- Uncontrollable capacity and cost: long conversations push context overhead up linearly.
- Lifecycle bound to the process: a restart means amnesia.
- No sharing across instances: sessions drift after horizontal scaling.
2.2 A Layered Memory Model
A more reliable approach splits memory into three layers:
- Short-term session memory: the rolling window of the current task, preserving original message order and role information.
- Working memory: structured intermediate conclusions, such as confirmed parameters, pending items, and user preferences.
- Long-term memory: facts and experience retrievable across sessions, usually stored in files or object storage, organized as one record per fact.
2.3 File-Based Implementation Notes
When files serve as the long-term memory carrier, use “directory partitioning + one topic per file”: build hierarchical paths by session identifier and topic, with each file holding a self-contained, independently readable fact. Writes should be append-first and overwrite-cautious, and keep an update timestamp to support expiry-based eviction.
Illustrative structure:
memory/sessions/{sessionId}/short-term.jsonlprofiles/{userId}/preferences.mdknowledge/{topic}.md
On the retrieval side, a vector database is not required from day one. Start with keyword and tag matching; introduce vector retrieval only when hit rates fall short, and make “recall - rerank - trim” a separate stage so that the entire history is never blindly stuffed into the prompt.
3. Long-Term Task Scheduling: Giving the Agent a Time Dimension
The three most common requirements are one-off delayed execution, fixed-interval execution, and cron-expression periodic execution. There are two implementation routes: in-application scheduled scanning, or a dedicated task scheduling framework. The former is simple but lacks reliability and observability; the latter provides a persistent task table, retry policies, concurrency limits, and execution logs.
Design points:
- Decouple tasks from execution: task records hold intent and parameters, while the executor invokes the agent, making the implementation replaceable.
- Idempotency keys: generate a unique key per task to prevent retries from placing duplicate orders or sending duplicate notifications.
- A clear state machine: pending, running, succeeded, failed, canceled; state transitions must be auditable.
- Recoverable failures: set a maximum retry count and backoff interval; beyond the limit, move the task to a manual handling queue.
- Context compensation: hours may have passed since the original conversation when a task fires, so required context must be written explicitly into the task parameters rather than relying on session memory.
4. Hot-插拔 Skills: Turning Capability Extension from “Changing Code” into “Adding Configuration”
A skill can be abstracted as a declarative description + a set of callable actions + optional constraints. The declarative part states when to use it and which inputs are required; the action part maps to concrete functions; the constraint part limits permissions and resource ceilings.
The key to hot plugging is a registry + dynamic discovery. At startup, scan the skill directory, load description files, and register them into the capability table. At runtime, skills can be added or retired by refreshing the registry, with no process restart. To avoid prompt bloat, use a two-stage “coarse filter, then inject” approach: first show the model skill names with a one-line description, then load the full description and parameter schema only for matches.
// Illustrative: skill registration and retrievalSkillRegistry.register(skill); // register at startup or on hot loadList<Skill> candidates = registry.match(query); // coarse-filter candidatesString prompt = PromptBuilder.inject(candidates); // inject matched items only
Engineering practice also requires version management and canary rollout: multiple versions of the same skill coexist, traffic is switched by proportion, and rollback to the previous version is fast when anomalies appear.
5. Protocol-Based Tool Integration: Reusing External Capabilities Through a Unified Standard
Fragmented tool integration is the biggest bottleneck for extension efficiency. The value of a unified protocol is standardizing “transport, capability description, and invocation semantics”: the server exposes a capability list, the client discovers and invokes on demand, and adding a tool requires no change to the agent’s main flow.
The practical path for dynamic registration: configure the service address and access credentials -> fetch the capability list -> convert it into internal tool descriptions and register them -> route by identifier at invocation time. Governance deserves close attention: tool whitelists, timeout and retry ceilings, response size limits, masking of sensitive fields, and trace identifiers carried through the whole invocation chain for logging and tracing.
6. Sandboxed Code Execution: Confining Generated Code to an Isolated Environment
Letting the model execute code directly on the local machine is an unacceptable risk. A workable approach sends the code to a disposable container: no outbound network or whitelist-only egress, read-only root filesystem, a dedicated working directory, CPU and memory quotas, a hard kill on execution timeout, and destruction on exit. Input and output are exchanged via standard input/output or temporary files, and results are validated for length and format before being returned.
If file artifacts are involved, store them in object storage and return a controlled access address; execution logs go to a logging service, and abnormal behavior triggers monitoring alerts. It must be clear that the sandbox solves isolation, not correctness, so critical paths still need a human confirmation step.
7. Layered Architecture and Rollout Order
Recommended layers: an access layer for protocol and authentication, an orchestration layer for prompts and flows, a capability layer hosting skills and tools, a runtime layer providing memory, scheduling, and sandboxing, and a governance layer covering logs, metrics, and quotas.
For rollout, start with memory persistence and log tracing, then task scheduling, then skill registration and tool integration, and finally the sandbox. Each step should be accepted against the criteria of “rollbackable and observable”, avoiding the uncontrolled risk of a single big-bang rewrite.
