opencode icon indicating copy to clipboard operation
opencode copied to clipboard

[FEATURE]: Expose session context to child processes via environment variables

Open klimkin opened this issue 19 hours ago • 1 comments

Feature hasn't been suggested before.

  • [x] I have verified this feature I'm about to request hasn't been suggested before.

Describe the enhancement you want to request

Problem

User scripts and tools that are executed via opencode (bash tool, shell commands) have no way to identify which opencode session they're running in. This makes it difficult to correlate logs, metrics, and outputs when running multiple opencode sessions, such as in iterative workflows (e.g., Ralph loops).

Use Case

A user running a Ralph loop that spawns a new opencode session per iteration needs to log which session each iteration corresponds to. Currently, child processes spawned by opencode have no access to session metadata.

Solution

Expose session context to child processes via environment variables:

  • OPENCODE_SESSION_ID: The unique identifier of the current session (e.g., ses_xyz123)
  • OPENCODE_SESSION_TITLE: The human-readable title of the current session (e.g., "Fix bug in auth flow") These variables are set in two user-facing command execution contexts:
  1. Bash tool: When users execute commands via the bash tool
  2. Prompt shell: When commands are executed via direct shell invocation

Implementation Details

  • Environment variables are set dynamically per spawn (not globally at startup like AGENT and OPENCODE)
  • This is necessary because users can switch between sessions during interactive work
  • Session lookup includes graceful error handling to avoid breaking existing tests and mock contexts

Example Usage

#!/bin/bash
# User script can now access session context
echo "Running in session: $OPENCODE_SESSION_TITLE ($OPENCODE_SESSION_ID)" >> /var/log/opencode-iterations.log

This enables proper tracking and correlation of work across multiple concurrent or sequential opencode sessions.

klimkin avatar Jan 18 '26 21:01 klimkin