Skip to content

fix(sdk): strip nested-session env vars before SDK query#41

Open
MateusJuni0 wants to merge 1 commit intoearlyaidopters:mainfrom
MateusJuni0:fix/nested-session-env-strip
Open

fix(sdk): strip nested-session env vars before SDK query#41
MateusJuni0 wants to merge 1 commit intoearlyaidopters:mainfrom
MateusJuni0:fix/nested-session-env-strip

Conversation

@MateusJuni0
Copy link
Copy Markdown

Problem

When ClaudeClaw is launched from inside an active Claude Code session (e.g. spawned by PM2 from a shell where Claude Code was running, or invoked as a child of another CC session), the vendored CLI aborts with:

Claude Code cannot be launched inside another Claude Code session.

This is because @anthropic-ai/claude-agent-sdk's query() inherits process.env, which includes markers that the CLI reads to detect nested sessions:

  • CLAUDECODE
  • CLAUDE_CODE_ENTRYPOINT
  • CLAUDE_CODE_EXECPATH
  • CLAUDE_AGENT_SDK_VERSION
  • CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH
  • CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST
  • CLAUDE_INTERNAL_FC_OVERRIDES

Since ClaudeClaw is itself an orchestrator that spawns the SDK CLI, those markers are stale — they describe the parent shell, not the ClaudeClaw runtime.

Fix

Build a sanitized sdkEnv by filtering those keys out of process.env before passing to query(). Small, surgical change; no behavior change for normal (non-nested) launches.

Test plan

  • Bot launched under PM2 spawned from an active CC session — previously failed, now runs cleanly
  • Normal desktop launch (no parent CC) still works
  • Telegram bot responds to messages, SDK streams tokens, no regressions observed over ~1 hour of use

Context

Found while deploying ClaudeClaw v1.1.0 as a Telegram bot (`@timecm_BOT`) on a Windows workstation where Claude Code was the parent shell. Root cause confirmed by inspecting the vendored `node_modules/@anthropic-ai/claude-code/cli.js` nested-session check.

When ClaudeClaw runs inside or downstream of another Claude Code
session (common with PM2/systemd services started from an interactive
CC terminal), the inherited env contains CLAUDECODE=1 plus other
CLAUDE_CODE_* markers. The vendored CLI in claude-agent-sdk aborts
with "Claude Code cannot be launched inside another Claude Code
session" and the bot replies "subprocess failed to start" for every
message.

Strip 7 nested-session marker vars from sdkEnv before passing it to
query() so the SDK subprocess runs clean.

Repro: start PM2 from inside a Claude Code terminal, send any message
to the bot; logs show exit code 1 at sdk.mjs. After this fix: bot
responds normally.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant