Skip to content

Implement Incremental Resource Cleanup for Agent Lifecycle ManagementΒ #236

@bhouston

Description

@bhouston

Incremental Resource Cleanup for Agent Lifecycle Management

Problem

Currently, the system uses a single cleanupResources function in packages/cli/src/utils/cleanup.ts that attempts to clean up all browser sessions and shell processes at application exit. This approach has several limitations:

  1. It doesn't properly clean up resources when sub-agents complete their tasks
  2. Resources from terminated agents can linger until the application exits
  3. There's no robust handling for cleaning up resources when agents encounter exceptions
  4. The cleanup is not tied to the agent lifecycle, which can lead to resource leaks

Current Implementation

The current implementation:

  • Stores browser sessions in a global singleton BrowserManager
  • Stores shell processes in a global processStates map
  • Tracks background tools (browsers, shells, sub-agents) in per-agent BackgroundTools instances
  • Has no mechanism to clean up resources when agents complete or fail

Proposed Solution

Implement incremental resource cleanup that's tied to agent lifecycles:

  1. Add a cleanup method to the BackgroundTools class that:

    • Closes browser sessions associated with the agent
    • Terminates shell processes associated with the agent
    • Cleans up sub-agents associated with the agent
  2. Call this cleanup method:

    • When an agent completes its task successfully
    • When an agent encounters an exception
    • When an agent is explicitly terminated
  3. Enhance exception handling to ensure cleanup occurs even when agents fail

  4. Keep the existing global cleanup as a fallback for application exit

This approach will ensure resources are cleaned up promptly when they're no longer needed, rather than waiting for application exit.

Benefits

  • Reduced resource usage as agents complete their tasks
  • More robust cleanup in the presence of exceptions
  • Clearer ownership of resources by agents
  • Improved reliability of cleanup operations

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions