[RFC]: Robust Agent Task Space lifecycle: Daemon-side heartbeat leases, concurrency hard caps, and RAII auto-cleanup (#270)
Problem & Real-World Evidence
We recently encountered and systematically analyzed the exact issue tracked in #270 on the latest production release (ego-browser 0.5.0.32 / Chromium 152.0.7977.54 on Apple Silicon macOS).
During a normal automated development and verification session (debugging a Jenkins job configuration and verifying local React auth forms), an AI coding agent dispatched 54 ego-browser nodejs invocations across multiple trial-and-error steps:
- Because the agent performed exploratory checks (inspecting CodeMirror, finding selectors, checking error states), it initialized each step with
taskSpace("new-step-name"). - 18 active Agent Task Spaces were created in the browser.
- The agent exited each Node.js process without calling
task.finish({ keep: [] }). - Result: 7.0 GB of Resident Set Size (RSS) occupied by dozens of orphaned
ego Helperrenderer processes, persisting indefinitely until discovered and manually reaped via a custom script.
This reproduces the exact failure mode reported by @zizhen01 (64 leaked spaces, 35GB swap, WindowServer at 120%), @bleakbelladonnals, and @weivwang. The previously introduced 12-hour cleanup window does not prevent this failure mode: automated agent tasks operate on a scale of seconds to minutes, and developer machines exhaust memory or suffer severe compositing lag long before a multi-hour window elapses.
Architectural Root Cause: An ACI Anti-Pattern
In Agent-Computer Interfaces (ACI), placing 100% of resource lifecycle responsibility on the agent's explicit, unprompted cleanup is an architectural anti-pattern.
An agent will reliably omit task.finish({ keep: [] }) under several routine execution paths:
- Unhandled exceptions: If a selector lookup fails, network times out, or a page assertion throws, the Node.js script terminates before reaching
task.finish(). - Context dilution & attention drift: In complex sessions with 200k–300k+ tokens, cleanup instructions in the Skill specification lose salience.
- Exploratory trial-and-error: When an agent investigates an unexpected UI state, it treats each step as a sub-probe and defers cleanup because it expects to continue in the "next round," yet frequently forgets prior transient spaces.
- External termination: Harness timeouts, wrapper SIGKILL, or user interruptions (reproduced in #306).
Because ego-browser utilizes a Client-Daemon architecture (short-lived Node.js CLI controlling a persistent Ego Lite browser daemon), treating the client process exit as decoupled from the space lifecycle creates permanent background leaks.
Proposed Solution: A Multi-Layered Defense
We propose a layered model where authoritative resource reclamation resides in the Daemon / Resource Owner, backed by ergonomics in the SDK.
1. Daemon-Side Heartbeat Lease (The Durable Fix)
- Each Agent-created Task Space (
ownership === "agent") is assigned a renewable lease (e.g., default120s, configurable viaEGO_AGENT_LEASE_S). - While a CLI process is actively executing CDP / page actions, the IPC bridge automatically refreshes this lease.
- If the CLI process crashes, exits, or is terminated, the heartbeat ceases. Once the lease expires, the Ego Lite Daemon terminates the orphaned tabs and reclaims renderer memory automatically.
- User-owned spaces (
ownership === "user") and spaces explicitly delegated to users remain completely exempt from auto-reclamation.
2. Hard Concurrency Cap (Tripwire Defense)
- Enforce a configurable upper bound on concurrently active Agent-owned spaces (e.g., default
6to8, viaEGO_AGENT_MAX_SPACES). - When an agent attempts to call
taskSpace("new-name")while at the limit, the daemon rejects creation with an actionable error:This immediately provides the agent with the necessary IDs to self-correct and prevents runaway process accumulation.[EgoResourceLimitError] Agent Task Space limit reached (8). Active spaces: [67: "inspect-jenkins", 68: "update-jenkins", ...]. Please reuse an existing space using taskSpace(id) or complete an unused space with task.finish().
3. Expose Timestamps in listTaskSpaces()
Currently, listTaskSpaces() returns { id, name, createdBy, ownership, recentTabTitles, taskId } with zero temporal metadata. Integrations and harnesses cannot safely determine whether a space is abandoned without maintaining out-of-process shadow state.
- Add
createdAt(Unix timestamp ms). - Add
lastActiveAt(Unix timestamp ms of last CDP event/interaction). - Add
leaseExpiresAt(optional ms).
4. SDK Ergonomics: RAII / Context Manager (withTaskSpace)
Most agent scripts do not need to persist across arbitrary unbounded sessions. Provide a scoped helper in the public SDK that guarantees cleanup in a finally block:
// Proposed helper in ego-browser SDK
export async function withTaskSpace<T>(
nameOrId: string | number,
fn: (task: TaskSpace) => Promise<T>,
options?: { keep?: string[] }
): Promise<T> {
const task = await taskSpace(nameOrId);
try {
return await fn(task);
} finally {
try {
await task.finish({ keep: options?.keep ?? [] });
} catch (cleanupErr) {
// Log or suppress secondary cleanup errors
}
}
}5. Skill Specification Guidance
The current SKILL.md starter examples frequently illustrate taskSpace("name") followed by actions, without illustrating finish(). Updating the canonical examples in SKILL.md to emphasize withTaskSpace or explicit try...finally { await task.finish({ keep: [] }) } will directly improve the behavior of models ingesting the skill prompt.
Interim Mitigation
Until native daemon-level leases are integrated, we are adopting two local mitigations:
- Hard-capping agent space creation in the local agent skill with an alert if active spaces exceed 8.
- Recommending external userland reapers (such as
zizhen01/ego-reaper) for multi-hour unattended runs.
We would welcome feedback from maintainers on whether the lease-based approach aligns with current daemon roadmap plans.
Source: citrolabs/ego-lite