Memory Management API Reference
This document describes the memory management APIs added to prevent memory leaks in long-running Hyperscape sessions.Overview
Recent stability improvements added proper resource cleanup across the codebase. All cleanup methods follow the established patterns inSystemBase for consistent resource management.
Core Pattern
All systems and managers that allocate resources (intervals, listeners, handlers) must implement cleanup methods:API Changes
ModelCache
Location:packages/shared/src/utils/rendering/ModelCache.ts
clear(): void
Clears all cached models and disposes GPU resources.
Changes:
- Now properly disposes geometry on all cached models
- Prevents GPU memory leaks during cache invalidation
remove(path: string): void
Removes a specific model from cache and disposes its geometry.
Changes:
- Now disposes geometry before removing from cache
- Prevents GPU memory accumulation
EventBridge
Location:packages/server/src/systems/ServerNetwork/event-bridge.ts
destroy(): void (NEW)
Cleans up all registered world event listeners.
Usage:
Logger
Location:packages/shared/src/utils/Logger.ts
destroy(): void (NEW)
Stops cleanup interval and releases resources.
Usage:
PlayerTokenManager
Location:packages/client/src/auth/PlayerTokenManager.ts
stopHeartbeat(): void (NEW)
Stops the token refresh heartbeat interval.
Usage:
AgentManager
Location:packages/server/src/eliza/AgentManager.ts
shutdown(): void
Enhanced to clean up COMBAT_DAMAGE_DEALT listener.
Changes:
- Now stores and removes combat damage listener
- Prevents memory accumulation during agent lifecycle
AutonomousBehaviorManager
Location:packages/plugin-hyperscape/src/managers/autonomous-behavior-manager.ts
stop(): void
Enhanced to clean up event handlers.
Changes:
- Now stores and removes all event handlers
- Prevents memory leaks during agent stop/start cycles
DuelBot
Location:packages/shared/src/testing/DuelBot.ts
Enhanced disconnect handling to clean up world event handlers.
Changes:
- Tracks
world.on()handler references - Removes all handlers on disconnect
Best Practices
1. Track All Resources
Store references to all allocated resources:2. Implement Cleanup Methods
Adddestroy(), shutdown(), or stop() methods:
3. Call Cleanup on Lifecycle Events
Ensure cleanup is called during:- Hot reload (development)
- System shutdown
- Component unmount
- Session end
4. Follow SystemBase Pattern
Use the same cleanup patterns asSystemBase for consistency:
Testing for Memory Leaks
Monitor memory usage during long-running sessions:- Increasing heap size over time
- Growing listener counts
- Accumulating interval handles
- GPU memory growth (check chrome://gpu)
Related Documentation
- CLAUDE.md - Memory Management section
- AGENTS.md - Memory Management Best Practices
- SystemBase - Base cleanup pattern