opencode icon indicating copy to clipboard operation
opencode copied to clipboard

feat(tool): expose session context to child processes via environment variables

Open klimkin opened this issue 17 hours ago • 2 comments

What does this PR do?

Exposes the current opencode session ID and title to child processes via environment variables, enabling user scripts and tools to correlate their work with specific opencode sessions.

Changes

  • OPENCODE_SESSION_ID: Unique session identifier (e.g., ses_xyz123)
  • OPENCODE_SESSION_TITLE: Human-readable session name (e.g., "Fix bug in auth flow") These are set dynamically in two user-facing command execution contexts:
  1. Bash tool (bash.ts)
  2. Prompt shell (prompt.ts)

Motivation

Users running iterative workflows (e.g., Ralph loops with multiple sessions per iteration) need to correlate logs and outputs with the specific opencode session they're running in. Previously, child processes had no access to session metadata.

Implementation Notes

  • Environment variables are set per-spawn (not globally) because sessions can change during interactive work
  • Session lookup includes graceful error handling to avoid breaking existing tests with mock session IDs
  • Both variables are always exposed; OPENCODE_SESSION_TITLE gracefully degrades if session lookup fails

How did you verify your code works?

  • Added a unit test for OPENCODE_SESSION_TITLE environment variable exposure
  • Used bun run dev with a prompt to echo $OPENCODE_SESSION_ID to verify variables are correctly passed to child processes
  • Didn't test on Windows

Example Usage

#!/bin/bash
echo "Session: $OPENCODE_SESSION_TITLE ($OPENCODE_SESSION_ID)" >> logs.txt

Closes #9292

klimkin avatar Jan 18 '26 21:01 klimkin