# How Background Sessions Work in OpenClaude for Long Prompts

> Discover how OpenClaude efficiently handles long prompts using background sessions and detached child processes. Learn about bgRouting bgRegistry and sdkEventQueue for a responsive REPL.

- Repository: [Gitlawb/openclaude](https://github.com/Gitlawb/openclaude)
- Tags: internals
- Published: 2026-09-05

---

**OpenClaude routes long-running prompts to isolated background processes via [`src/cli/bgRouting.ts`](https://github.com/Gitlawb/openclaude/blob/main/src/cli/bgRouting.ts), creating detached child sessions tracked in [`src/cli/bgRegistry.ts`](https://github.com/Gitlawb/openclaude/blob/main/src/cli/bgRegistry.ts) while streaming events through [`src/utils/sdkEventQueue.ts`](https://github.com/Gitlawb/openclaude/blob/main/src/utils/sdkEventQueue.ts) to keep the main REPL responsive.**

OpenClaude, the open-source CLI interface for Claude LLMs, solves the problem of foreground timeouts by implementing a robust background session architecture in the **Gitlawb/openclaude** repository. When a prompt exceeds interactive time limits or requires extensive token generation, the system transfers execution to a separate process that survives even if the user closes the terminal.

## Initiating a Background Session

Background sessions begin when the CLI detects the `--background` flag or a tool configuration marked `run_in_background: true`. In [`src/cli/bgRouting.ts`](https://github.com/Gitlawb/openclaude/blob/main/src/cli/bgRouting.ts), the router intercepts the request and instantiates a `LocalMainSessionTask` defined in [`src/tasks/LocalMainSessionTask.ts`](https://github.com/Gitlawb/openclaude/blob/main/src/tasks/LocalMainSessionTask.ts). This task encapsulates the message history, model configuration, and a unique session identifier before handing control to the process layer.

The task is immediately registered in [`src/cli/bgRegistry.ts`](https://github.com/Gitlawb/openclaude/blob/main/src/cli/bgRegistry.ts), which maintains an authoritative record of each session's **PID**, owner process, and lifecycle state (running, finished, or aborted). The registry performs strict **PID verification** (lines 1027–1032) to ensure that termination signals originate only from the owning process, preventing accidental cross-session interference.

## Process Isolation and Lifecycle Management

Once registered, OpenClaude spawns the background task as a **detached child process** using Node.js `spawn` or `fork`. This isolation ensures the session continues execution even if the foreground REPL exits or loses connection.

The [`src/utils/queryLifecycle.ts`](https://github.com/Gitlawb/openclaude/blob/main/src/utils/queryLifecycle.ts) module groups these background tasks under a "parent-ended" lifecycle (line 88), allowing the system to gracefully handle abort signals. When a user interrupts the foreground query, [`utils/replInterruption.ts`](https://github.com/Gitlawb/openclaude/blob/main/utils/replInterruption.ts) propagates the cancellation with a specific `background_handoff` reason, distinguishing between foreground cancellation and background termination.

## Event Streaming and Finalization

As the background session generates tokens or invokes tools, it emits standard SDK events (`task_progress`, `tool_use`, etc.). The **SDK event queue** in [`src/utils/sdkEventQueue.ts`](https://github.com/Gitlawb/openclaude/blob/main/src/utils/sdkEventQueue.ts) funnels these events to persistent log files without blocking the main thread.

When the session completes—whether naturally or via the `openclaude kill <session-id>` command—the **background finalizer** in [`src/cli/bgFinalizer.ts`](https://github.com/Gitlawb/openclaude/blob/main/src/cli/bgFinalizer.ts) executes. This module updates the registry, writes a termination summary, and cleans up process handles. Users can stream live output using `openclaude logs <session-id> -f` or inspect historical results after completion.

## Practical Usage Examples

Start a long-running prompt in the background using the CLI:

```bash

# Initiate a background session for a lengthy prompt

openclaude ask "Write a comprehensive 10,000-word analysis of quantum computing" --background

# → Started background session q1a2b3c4.

# Stream output in real-time

openclaude logs q1a2b3c4 -f

# Terminate the session early if needed

openclaude kill q1a2b3c4

# → Background session q1a2b3c4 killed.

```

Programmatically invoke background sessions via the Node API:

```typescript
import { Cli } from 'openclaude';

// Fire-and-forget a background request
await Cli.run([
  'ask',
  'Summarize the entire history of artificial intelligence in 5,000 words',
  '--background',
]);

// Retrieve session logs asynchronously
const logs = await Cli.run(['logs', '<session-id>', '-f']);
console.log(logs);

```

## Safety Mechanisms

OpenClaude implements several safeguards to ensure background sessions operate securely:

- **PID Validation**: The registry verifies process ownership before accepting termination commands, preventing unauthorized session kills.
- **Graceful Abort Propagation**: Abort signals carry the `background_handoff` reason, ensuring the foreground query exits cleanly while the background process continues or shuts down according to its own logic.
- **Resource Isolation**: Each background session runs in its own process space, preventing memory leaks or infinite loops in long prompts from crashing the interactive REPL.

## Summary

- **OpenClaude background sessions** bypass REPL timeouts by executing prompts in detached child processes spawned via [`src/cli/bgRouting.ts`](https://github.com/Gitlawb/openclaude/blob/main/src/cli/bgRouting.ts).
- The **background registry** in [`src/cli/bgRegistry.ts`](https://github.com/Gitlawb/openclaude/blob/main/src/cli/bgRegistry.ts) tracks PID ownership and validates lifecycle transitions at lines 1027–1032.
- **LocalMainSessionTask** encapsulates session state and configuration before process isolation occurs.
- Events stream through [`src/utils/sdkEventQueue.ts`](https://github.com/Gitlawb/openclaude/blob/main/src/utils/sdkEventQueue.ts) to persistent logs accessible via `openclaude logs -f`.
- Sessions terminate through [`src/cli/bgFinalizer.ts`](https://github.com/Gitlawb/openclaude/blob/main/src/cli/bgFinalizer.ts), which updates the registry and writes final status summaries.

## Frequently Asked Questions

### How do I start a background session in OpenClaude?

Append the `--background` flag to any `ask` command or configure your tool with `run_in_background: true`. The CLI routes the request through [`src/cli/bgRouting.ts`](https://github.com/Gitlawb/openclaude/blob/main/src/cli/bgRouting.ts) and immediately returns a session ID while the process continues in the background.

### What happens if I close the terminal while a background session is running?

The session continues executing because OpenClaude spawns it as a **detached child process**. The process survives terminal closure; you can reattach later using `openclaude logs <session-id>` to view completed or in-progress output.

### How can I monitor a running background session?

Use `openclaude logs <session-id> -f` to follow the live event stream. The [`src/utils/sdkEventQueue.ts`](https://github.com/Gitlawb/openclaude/blob/main/src/utils/sdkEventQueue.ts) module handles real-time event streaming from the background process to your terminal without blocking other CLI operations.

### Are background sessions isolated from foreground tasks?

Yes. Each background session operates in a separate Node.js process with its own memory space and event loop. The [`src/utils/queryLifecycle.ts`](https://github.com/Gitlawb/openclaude/blob/main/src/utils/queryLifecycle.ts) groups these under a parent-ended lifecycle (line 88) to ensure foreground aborts don't inadvertently kill background work, while [`src/cli/bgRegistry.ts`](https://github.com/Gitlawb/openclaude/blob/main/src/cli/bgRegistry.ts) enforces PID-based access control.