How to Run Long Non‑Interactive Prompts in OpenClaude: Headless and Background Modes
OpenClaude provides two distinct non‑interactive execution pathways—the headless --print flag for immediate output and the --bg flag for detached background sessions—allowing you to execute long‑running prompts without maintaining an active terminal window.
When working with the Gitlawb/openclaude CLI, you often need to run long non‑interactive prompts in OpenClaude without babysitting the REPL. The codebase implements specific utilities to detect non‑interactive contexts and manage detached process lifecycles, ensuring model selection, provider credentials, and tool usage remain fully functional even when no user interface is present.
Headless Print Mode for Single‑Shot Execution
The --print flag (aliased as -p) sends your prompt directly to the model, streams the final response to stdout, and exits immediately. This mode disables the interactive UI, session persistence, and any UI‑driven pauses that would normally block execution.
In src/utils/printFlag.ts, the hasPrintFlag utility parses raw CLI arguments to detect the exact -p or --print flag. When present, the isInteractiveSession function in src/utils/interactivity.ts (lines 14‑21) evaluates the session as non‑interactive, automatically implying --no‑session‑persistence and bypassing the terminal UI initialization entirely.
# Execute a prompt and print the result immediately
openclaude -p "Explain why recursive descent parsers work"
# Long‑form equivalent
openclaude --print "Explain why recursive descent parsers work"
Background Sessions for Fire‑and‑Forget Workflows
For tasks requiring extended execution time or continuous operation after shell logout, the --bg flag spawns a detached child process. The parent shell returns immediately with a session identifier, while the child continues running the full OpenClaude engine in the background.
The implementation resides in src/cli/bgRegistry.ts, where the createBackgroundSession function handles the complete lifecycle:
- Generates a UUID for the session
- Writes a JSON metadata file to
~/.openclaude/bg‑sessions/ - Creates log files for stdout and stderr
- Forks the current process using
child_process.spawn(viagetProcessCommand) - Stores status updates (
running,exited,failed,killed,stale) inbg‑sessions/terminal/(lines 64‑72)
Managing Background Sessions
Once detached, sessions are managed through dedicated CLI commands rather than the interactive REPL:
# Start a named background session
openclaude --bg --name refactor-auth "refactor auth middleware"
# List all running background processes
openclaude ps
# Stream logs from a specific session
openclaude logs refactor-auth
# Follow live log output (tail -f behavior)
openclaude logs refactor-auth -f
# Gracefully terminate a background session
openclaude kill refactor-auth
Technical Implementation Details
Detecting Non‑Interactive Contexts
Beyond the --print flag, the isInteractiveSession function in src/utils/interactivity.ts treats a session as forced non‑interactive if it detects --init‑only or any --sdk‑url argument (lines 14‑22). This centralized detection ensures consistent behavior across the CLI surface, preventing accidental REPL initialization in scripting contexts.
Background Session Storage Architecture
Background sessions persist metadata to the user's OpenClaude configuration directory (default ~/.openclaude/). Each session receives a dedicated subdirectory containing:
- Metadata JSON: Session ID, creation timestamp, command arguments, and PID
- Log files: Separated stdout and stderr streams for post‑execution analysis
- Status markers: File‑based state tracking in the
terminal/subdirectory
Feature Comparison
Headless Print Mode (--print) terminates immediately after output delivery, cannot be resumed, and supports optional liveness heartbeats via --heartbeat (requires --print). Background Sessions (--bg) persist indefinitely, support later inspection via openclaude logs, allow graceful termination with openclaude kill, and can be assigned human‑readable names using the --name flag.
Practical Usage Examples
Combine provider‑specific flags with non‑interactive execution for automated pipelines:
# Background execution with specific model and provider
openclaude --bg --provider openai --model gpt-4o "write a TypeScript CLI tool"
# Unattended documentation generation
openclaude --bg --name api-docs "generate OpenAPI documentation from ./src/routes"
For CI/CD environments requiring immediate feedback:
# Exit codes reflect execution status; stdout contains only the model response
openclaude --print --model claude-3-opus "review this code for security issues: $(cat input.js)"
Summary
- Headless mode (
--print): Use for single‑shot prompts requiring immediate output without session persistence; detected viahasPrintFlaginsrc/utils/printFlag.ts. - Background mode (
--bg): Use for long‑running tasks needing process detachment; managed throughsrc/cli/bgRegistry.tswith metadata stored in~/.openclaude/bg‑sessions/. - Non‑interactive detection: The
isInteractiveSessionutility automatically disables the REPL when--print,--init‑only, or--sdk‑urlflags are present. - Session management: Background jobs support naming (
--name), log retrieval (openclaude logs), and process termination (openclaude kill).
Frequently Asked Questions
What is the difference between --print and --bg in OpenClaude?
The --print flag executes the prompt immediately, prints the response to stdout, and exits, making it ideal for scripts requiring synchronous output. The --bg flag detaches the process into the background, returning control to your shell immediately while the session continues running and writes logs to disk for later inspection.
How does OpenClaude detect whether to run in interactive mode?
According to src/utils/interactivity.ts, the isInteractiveSession function checks for the presence of --print, --init‑only, or --sdk‑url arguments. If any are detected, the session is forced into non‑interactive mode, disabling the REPL and session persistence regardless of other configuration options.
Where are background session logs and metadata stored?
Background sessions store their metadata and log files in the user's OpenClaude configuration directory, specifically under ~/.openclaude/bg‑sessions/. Each session receives a UUID‑based subdirectory containing JSON metadata, stdout logs, and stderr logs, with status updates tracked in the bg‑sessions/terminal/ path.
Can I resume or interact with a background session after it starts?
No, background sessions cannot be resumed or reattached to an interactive REPL once detached. However, you can monitor their progress using openclaude logs <name> -f to follow live output, inspect completed output with openclaude logs <name>, or terminate them early using openclaude kill <name>.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →