Anahata Core

An Enterprise ready, Domain-Driven abstraction of the Context Window. Engineered for stability, modularity, portability, observability, security and traceability.

Mission Statement

Core provides the atomic units of context (Messages, Parts, Tools) and the context augmentation and metabolic management systems (CwGC) required to sustain live, long-running, multi-modal, cross platform, super intelligent agentic sessions without provider lock-in.

The ASI Container

The AbstractAsiContainer acts as the authoritative JVM host for active Agi sessions. It is responsible for session lifecycle orchestration, global configuration registries, session passivation, active session routing, and platform-specific UI Look-and-Feel bootstrapping.

ASI Container Architecture & State Passivation Flow
graph TD subgraph JVM Memory Scopes [JVM Memory Scopes] AppMap[Application Map - Shared JVM-wide] ContMap[Container Map - Shared Application-wide] end subgraph AbstractAsiContainer [AbstractAsiContainer] ActiveAgis[Active Agi Sessions Pool] Preferences[AsiContainerPreferences] ToolPerms[Global Tool Permissions Registry] end subgraph PreferencesDNA [Preferences DNA Blueprint] AgiTemplate[AgiConfig Template] ReqTemplate[RequestConfig Template] DnaVersion[DNA Version & Drift Monitor] end subgraph PassivationPipeline [Passivation & Recovery] TmpFile[1. Write to Session .tmp] AtomicMove[2. Atomic Move to .kryo] RebindHook[3. State Healing via Rebindable] end AppMap --> AbstractAsiContainer ContMap --> AbstractAsiContainer ActiveAgis --> PassivationPipeline Preferences --> PreferencesDNA ToolPerms --> Preferences
Container Topology & Memory Scopes

Manages the active session pool (activeAgis). It exposes thread-safe, container-scoped (containerAttributes) and JVM-scoped (applicationAttributes) memory maps, allowing distinct Agi sessions to securely share runtime state, cached models, or collaborative tool assets.

Passivation & Atomic Saves

Orchestrates transaction-grade state serialization of active Agi sessions to binary .kryo files. Uses the atomic save pattern—writing first to a temporary .tmp file before executing a filesystem-level atomic move—to completely protect session history and state from unexpected power losses or system crashes.

DNA Templates & Request Blueprints

Exposes the AsiContainerPreferences to manage global defaults for new sessions. It configures the session's genetic blueprint (AgiConfig template) with predefined models, providers, and registered toolkits (e.g. Session, History, Resources), and templates the RequestConfig (temperature, top-p, and output token limits).

Global Tool Permissions & Drift

Maintains an authoritative map of tool fully qualified names (e.g. LocalFiles.readFile) to execution policies (PROMPT, APPROVE_ALWAYS, DENY) across all sessions. It also detects DNA Version Drift: if an application update introduces new toolkits, the container automatically reconciles and merges the disk-cached template with compiled defaults.

The AGI Container

The Agi class is the central orchestrator. It manages the session lifecycle, state persistence, and model communication.

  • Transactional States: Automatically triggers autoSave() on turn completion or terminal tool states (EXECUTED/FAILED) to ensure persistence.
  • Non-Blocking Inputs: Implements a stagedUserMessage queue, allowing users to submit input while the ASI is currently processing a turn.
  • Metabolic Policy: The AgiConfig defines default Turns to Keep (Max Depth) for different data types: Text (108), Thoughts (12), Tools (12), and Blobs (4).

AGI Configuration (DNA Blueprint)

The AgiConfig acts as the genetic blueprint ("DNA") for an individual Agi session. It defines the starting model configurations, enabled toolkits, and granular context window metabolic policies.

Default Sinking Stack Decay Policies (Max Depth)

Each multimodal part is registered with a designated Time-to-Live (TTL) counter, defined as Turns to Keep in the session's active context. When a turn completes, all active parts "sink" by 1 depth unit. Upon reaching 0, they are soft-recycled into Ghost hints.

Part Type Default Turns (Max Depth) Metabolic Purpose
TextPart 108 Turns Sustains high-level conversational memory and systemic behavioral rules.
ThoughtPart 12 Turns Retains the model's intermediate logical and chain-of-thought reasonings.
AbstractToolCall 12 Turns Maintains short-term tool arguments and result schemas for execution traceability.
BlobPart 4 Turns Mitigates memory inflation by aggressively recycling heavy binary payloads (images, audio).

The Context Manager

The ContextManager is the absolute heart of the session's Working Memory. It is responsible for chronological timeline auditing, on-the-fly RAG context fusion, and orchestrating the active garbage collection loop.

Turn Lifecycle & Context Fusion Pipeline
sequenceDiagram participant User as User / Host participant CM as ContextManager participant RM as ResourceManager participant GC as CwGC (Garbage Collector) participant Model as AI Model Provider User->>CM: 1. Send Message CM->>RM: 2. Just-In-Time Sense & Poll Live Resources RM-->>CM: 3. Return Fresh Resource Views (LIVE policy) CM->>CM: 4. Compile Unified RAG Message CM->>Model: 5. Execute API Generation Request Model-->>User: 6. Stream Response & Execute Tools User->>GC: 7. Turn Complete: Calculate Metabolism GC->>GC: 8. Expire Remaining Depth (Sinking Stack) GC->>CM: 9. Hard-Prune effectivelyPruned Messages
Memory Consolidation

Maintains the sequential ID generator for all conversation turns and parts, ensuring strict temporal ordering. It builds the visible history list before dispatching payloads to the provider.

Sensory Fusion (RAG Compiler)

Compiles the unified RagMessage dynamically right before generation. It polls active ContextProviders, and parses resources to fetch the most up-to-date workspace views.

Messages & Parts

Anahata treats context as a rich graph. A conversation is a sequence of AbstractMessage turns, each containing a collection of AbstractPart objects tracking their own metadata and metabolic state.

classDiagram AbstractMessage *-- AbstractPart AbstractPart <|-- TextPart AbstractPart <|-- BlobPart AbstractPart <|-- AbstractToolCall AbstractToolCall *-- AbstractToolResponse

In-Band Metadata Injection

Self-awareness is achieved by interleaving invisible metadata headers before every component. Even when a part is effectively pruned to save tokens, the Pruned Hint ensures the ASI maintains a "Semantic Ghost" of the action.

Metabolic Part Lifecycle

Depth 0
Thought (12)
Text (108)
User Blob (4)
Tool Call (12)
Depth 4
Thought (8)
Text (104)
Blob Ghost
Tool Call (8)
Depth 12
Thought Ghost
Text (96)
Blob Ghost
Tool Ghost
Depth 108
Recycling...
Recycling...
Recycling...
Recycling...
Example: Ghost Metadata Header
[x-anahata-part-id: 19 | Type: JavaMethodToolCall | Status: EXECUTED | Remaining Depth: 0 | Hint: Tool: NbFiles.updateTextFile | Result: Success]

Garbage Collection (CwGC)

Metabolic Logic Dashboard

Formula Engine
getDepth() = distance from head
turnsToKeep = MaxDepth policy
getRemainingDepth() = turnsToKeep - getDepth()
Ghost State Trigger
isEffectivelyPruned() == true

1. Omit body content
2. Inject Metadata Hint

One-Pass Token Metabolism Calculation

Rather than traversing the active history multiple times, the ContextWindowGarbageCollector executes a highly optimized, single-pass calculation. It aggregates token weights for system instructions, tools, active history, and pruned "Ghosts", compiling precise diagnostics in milliseconds to prevent context window congestion under high-concurrency environments.

Sinking Stack Desaturation

Visual feedback is synchronized with history decay. In the JNDI Context Explorer, effectively pruned message parts undergo visual desaturation—icons fade out and text titles gray-scale dynamically—letting developers witness their session's active cognitive span at a glance.

pruningStateSymbolBehavior
AUTOSoft-pruned when depth expires.
PINNEDThe Messi State. Immune to GC. Permanent awareness.
PRUNEDImmediately recycled into a Ghost.

Context Providers

Context Providers are the sensors of the ASI. They contribute high-salience information to the RAG Message via a hierarchical tree structure.

classDiagram class ContextProvider { <<interface>> +getId() String +getName() String +isProviding() boolean +getContextPosition() ContextPosition +getSystemInstructions() List +populateMessage(RagMessage) } class BasicContextProvider { -String id -String name -boolean providing } class ContextManager { -List providers +addMessage(AbstractMessage) } class ResourceManager { -Map resources } class Resource { -ResourceHandle handle -ResourceView view -RefreshPolicy policy -ContextPosition position } class ContextPosition { <<enumeration>> SYSTEM_INSTRUCTIONS PROMPT_AUGMENTATION } class RefreshPolicy { <<enumeration>> LIVE SNAPSHOT } ContextProvider <|.. BasicContextProvider BasicContextProvider <|-- ContextManager BasicContextProvider <|-- ResourceManager BasicContextProvider <|-- Resource Resource o-- ContextPosition Resource o-- RefreshPolicy ContextManager "1" *-- "*" ContextProvider : manages

Reactive Events

The JASI platform follows a Data-First Reactive UI pattern. Core components implement the PropertyChangeSource interface, allowing the Swing UI to remain perfectly synchronized with the domain state.

Example: PropertyChangeSource Implementation
public class ResourceManager extends BasicPropertyChangeSource {
    public void register(Resource resource) {
        resources.put(resource.getId(), resource);
        // Fires event to trigger UI tree refresh
        propertyChangeSupport.firePropertyChange("resources", null, getResourcesList());
    }
}
Example: Swing UI Binding
agi.addPropertyChangeListener("status", evt -> {
    statusIndicator.update((AgiStatus) evt.getNewValue());
});

Universal Resource Pipeline (V2)

The V2 architecture introduces a URI-centric, capability-based resource model that decouples the source of data from its interpretation. Resources are "Self-Aware" and automatically bind the appropriate view based on detected MIME types.

Dual-Role Positioning

A single Resource can be loaded into either the SYSTEM_INSTRUCTIONS position (providing high-level behavioral guidance) or the PROMPT_AUGMENTATION (RAG) position for just-in-time facts. The system automatically routes the processed content to the correct section of the prompt.

Reactive Awareness

The ResourceManager identifies resources that are registered but disabled, injecting their metadata headers into the RAG message. This ensures the ASI remains aware of available but silent assets.

The Source Nexus: Universal Connectivity

graph LR subgraph Sources L[local file] Z[zip/jar entry] F[ftp/http server] NB[netbeans fileObject] end L --> PathHandle Z --> UrlHandle F --> UrlHandle NB --> NbHandle PathHandle --> Resource UrlHandle --> Resource NbHandle --> Resource subgraph Policies Resource -- "Refresh: LIVE" --> P1[Auto-Reload on Turn] Resource -- "Refresh: SNAPSHOT" --> P2[Static Memory] end subgraph Delivery P1 -- "Position: RAG" --> RAG[Prompt Augmentation] P1 -- "Position: SYSTEM" --> SYS[System Instructions] P2 --> RAG P2 --> SYS end

Resource Component Hierarchy

classDiagram class Resource { -ResourceHandle handle -ResourceView view -RefreshPolicy policy -ContextPosition position +reload() } class ResourceHandle { <<interface>> +openStream() InputStream +getLastModified() long } class ResourceView { <<interface>> +reload(ResourceHandle) +populateRag(RagMessage, ResourceHandle) } class RefreshPolicy { <<enumeration>> LIVE SNAPSHOT } class ContextPosition { <<enumeration>> SYSTEM_INSTRUCTIONS PROMPT_AUGMENTATION } class TextView class MediaView class PathHandle class UrlHandle class NbHandle Resource o-- ResourceHandle Resource o-- ResourceView Resource o-- RefreshPolicy Resource o-- ContextPosition ResourceView <|.. TextView ResourceView <|.. MediaView ResourceHandle <|.. PathHandle ResourceHandle <|.. UrlHandle ResourceHandle <|.. NbHandle

Toolkits & Tools

AsiContainer

Global lifecycle orchestrator. Spawns, lists, and terminates active sessions.

Session

Metadata & depth governor. Manages task dashboards and session policies.

History

Pruning, pinning, and metadata injection manager for the sliding context window.

Resources

URI-centric workspace, file, and web reader with live optimistic locking.

Java

Singularity hot-reload engine. JIT-compiles and executes Java on the fly.

Shell

Direct host-level OS terminal interaction and process streaming.

Audio

Autonomous hardware line selection, WAVE recording, and playback controls.

Advanced State Management

Toolkits manage three scopes of memory: Session (AGI turn), Container (all sessions), and Application (JVM-wide). Deserialization is handled via rebind().

Java: Scoped Persistence & Rebinding
@AgiToolkit(value = "Task Orchestration", maxDepth = 12)
public class TaskToolkit extends AnahataToolkit {
    private List<String> persistentTasks = new ArrayList<>(); // Serialized by Kryo
    private transient Map<String, Long> runtimeMetrics; // Cleared on save

    @Override
    public void rebind() {
        this.runtimeMetrics = new ConcurrentHashMap<>(); // Restored upon deserialization
    }

    @AgiTool("Shares a task across the ASI Container.")
    public String createGlobalTask(String task) {
        getSessionMap().put("last", task);      // Local turn memory
        getContainerMap().put("latest", task);   // Shared across all app AGIs
        getApplicationMap().put("sys", "UP");    // Shared across entire JVM
        return "Broadcasting task...";
    }
}

Java: On-the-Fly Tool Creation

The Java toolkit enables the Singularity Loop: scouting a new capability and integrating it into the starting XI in just two turns.

The Singularity Loop: 2-Turn Self-Evolution

sequenceDiagram participant AI as ASI Model participant M as Maven Toolkit participant J as Java Toolkit Note over AI, J: TURN 1: Scout & Acquire AI->>M: downloadDependencyArtifact("org.apache.commons") M-->>AI: Success: math3.jar saved to disk Note over AI, J: TURN 2: Integration & Debut AI->>J: compileAndExecute(source, extraClassPath: "math3.jar") J-->>AI: Success: Model-generated logic executing Math3 code!

The Hot-Reload Onboarding Engine

Child-First Isolation
1. In-memory Bytecode Compilation
2. URLClassLoader prepends extraClassPath
3. PARENT-FIRST Filter for ToolContext
4. Onboarding instance into Agi/Asi
Context Propagation

Dynamic tools inherit multi-threaded logging and can call other toolkits using getToolkit(Class). Other kits can reference the originating call to add rich attachments or errors.

Java ↔ JSON Schema (J2S)

Java: Recursive IssueNode DTO
@Schema(description = "Recursive dependency analysis.")
public class IssueNode {
    private String id;
    private List<IssueNode> children;
}
Generated JSON Schema (Recursive)
{
  "title": "uno.anahata.asi.model.IssueNode",
  "properties": {
    "children": {
      "type": "array",
      "items": { "description": "Recursive reference to IssueNode" }
    }
  }
}

Flight Recorder & Persistence

The Agi Container is designed from the ground up for ultra-fast passivation / serialization of the entire container. This includes the state of: container settings and state, history, context providers, resources, and toolkits.

Passivation (Kryo)

Uses the Kryo framework for high-performance binary persistence. Handles complex circular references and large object graphs natively.

State Healing (Rebindable)

The uno.anahata.asi.internal.kryo.Rebindable interface allows any Java class in the entire object graph to restore transient fields post-deserialization.

Decorator-Driven State Healing

When restoring a session, our custom RebindableWrapperSerializer intercepts Kryo's read stream. Any deserialized node implementing Rebindable is automatically captured, and its rebind() hook is triggered to cleanly reconstruct ephemeral locks, thread-local contexts, and active workspace listeners.

Hidden Class & Proxy Shielding

Kryo reflection is highly sensitive to JVM-internal types. The RebindableSerializerFactory protects serialization pipelines from fatal classloader errors by detecting hidden classes (such as dynamic lambda proxies and un-addressable JRE internals), safely shielding them under a no-op null-serializer.

Example: Post-Deserialization State Recovery
public class NbHandle extends AbstractResourceHandle implements Rebindable {
    private transient FileObject fileObject; // Lost during serialization
    private String path;

    @Override
    public void rebind() {
        // Restore the live FileObject pointer from the persisted path string
        this.fileObject = FileUtil.toFileObject(new File(path));
        if (this.fileObject != null) {
            setupListeners(); // Re-attach IDE hooks
        }
    }
}

Recording Modes

  • Auto Save (Default): The Agi container is serialized on every turn and every tool execution to the same backup file. This allows for transactional-grade crash recovery.
  • Flight Recorder (Storage Intensive): The Agi container is serialized to a different backup file on every turn and every tool execution. This allows for fully auditable/replayable sessions.