[BUG] claude -m sonnet -p "plan this project" style prompt usually hanging on an error

Status Closed — duplicate
Maintainer reply ✓ Yes — rboyce-ant
Activity 13 comments · opened Jun 6, 2025 · closed Jul 12, 2025
💡 Likely answer: A maintainer (rboyce-ant, contributor) responded on this thread — see the highlighted reply below.

Environment

  • Platform (select one):
  • [ ] Anthropic API
  • [ ] AWS Bedrock
  • [ ] Google Vertex AI
  • [ x ] Other: Claude Max
  • Claude CLI version: 1.0.16
  • Operating System: macOS 15.4.1
  • Terminal: iTerm2

Bug Description

I have a script that calls claude-p to plan the next task, then again to do dev, then a third time to review the code. The first part, the planner, has been hanging most of the time lately (not always) on a particular error. I don't know what it's doing at that time; it could be running a build or something?

==================================================================
This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason:
Error: Expected content to be an assistant message, but got "user"
at yS2 (file:///opt/homebrew/lib/node_modules/@anthropic-ai/claude-code/cli.js:2342:9744)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async bE5 (file:///opt/homebrew/lib/node_modules/@anthropic-ai/claude-code/cli.js:2356:8265)

Steps to Reproduce

  1. run claude -m sonnet -p 'do planning'
  2. try again if it doesn't fail
  3. <!-- And so on... -->

Expected Behavior

do work

Actual Behavior

error displayed, and then it never completes

Additional Context

View original on GitHub ↗

13 Comments

willer · 1 year ago

I reset my .claude.json, and it's still happening, most of the time (but not all). This is a blank config, so no MCP's.
It also made it through my planner prompt, then stalled again with the reviewer prompt ... so it's not the prompt. also one of the runs had --dangerously-skip-permissions set and another one didn't.
factors eliminated, then: the config, the prompt, the MCP's, the --dangerously-skip-permissions arg

michael-hedgineer · 1 year ago

When you add --output-format "stream-json" --verbose does that give any more details on what it is doing when failing? You could try piping this to claude -p --output-format "stream-json" --verbose >> test.log

michael-hedgineer · 1 year ago

And do you need the -m sonnet call? I never add that and without it is always defaulting to sonnet 4.

xbno · 1 year ago

I'm getting the same error - yesterday occasionally, but now its every time - running an async subprocess calling claude, it seems to error at the end of an interaction. my typical workflow runs for ~3mins and it runs through the todos, completes all of them, and then fails. heres the tail of the output:

[STDOUT] {"type":"assistant","message":{"id":"msg_01GHh85dHQavjhRedyAy98u7","type":"message","role":"assistant","model":"claude-sonnet-4-20250514","content":[{"type":"tool_use","id":"toolu_013AnXW3pygGViNXUxULoNBd","name":"TodoWrite","input":{"todos":[{"id":"1","content":"Read the current strategy file to understand implementation","status":"completed","priority":"high"},{"id":"2","content":"Analyze the performance metrics and identify improvement areas","status":"completed","priority":"high"},{"id":"3","content":"Improve strategy parameters and logic within EVOLVE-BLOCK sections","status":"completed","priority":"high"},{"id":"4","content":"Validate the improved strategy using strategy_validator.py","status":"completed","priority":"medium"},{"id":"5","content":"Provide summary of improvements and reasoning","status":"completed","priority":"low"}]}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":6,"cache_creation_input_tokens":265,"cache_read_input_tokens":33211,"output_tokens":1,"service_tier":"standard"}},"session_id":"e5668ab2-1a8f-4ef5-be45-c40c82d38fd9"}
[STDOUT] {"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_013AnXW3pygGViNXUxULoNBd","type":"tool_result","content":"Todos have been modified successfully. Ensure that you continue to use the todo list to track your progress. Please proceed with the current tasks if applicable"}]},"session_id":"e5668ab2-1a8f-4ef5-be45-c40c82d38fd9"}
[STDERR] This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason:
[STDERR] Error: Expected content to be an assistant message, but got "user"
[STDERR]     at yS2 (file:///opt/homebrew/lib/node_modules/@anthropic-ai/claude-code/cli.js:2342:9744)
[STDERR]     at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
[STDERR]     at async bE5 (file:///opt/homebrew/lib/node_modules/@anthropic-ai/claude-code/cli.js:2356:8265)
michael-hedgineer · 1 year ago

Have you tried going into the session to inspect what's going on? Probably wont help but may be good to check:

claude -r e5668ab2-1a8f-4ef5-be45-c40c82d38fd9

michael-hedgineer · 1 year ago

Are your stderr's (coppied below) from your process logging or directly from claude?

[STDERR] This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason:
[STDERR] Error: Expected content to be an assistant message, but got "user"
[STDERR]     at yS2 (file:///opt/homebrew/lib/node_modules/@anthropic-ai/claude-code/cli.js:2342:9744)
[STDERR]     at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
[STDERR]     at async bE5 (file:///opt/homebrew/lib/node_modules/@anthropic-ai/claude-code/cli.js:2356:8265)

When claude has an error it is not piped to stdout but to stderr so make sure you are capturing that. But looking at it, this log makes me think it is from claude not your logs:

_Error: Expected content to be an assistant message, but got "user"_

xbno · 1 year ago

I've checked a few of sessions with the command claude -r e5668ab2-1a8f-4ef5-be45-c40c82d38fd9 and each time the todo list is complete. For example:

  The strategy successfully implements a VC-style mindset with asymmetric risk/reward profiles, cutting losses quickly while letting winners run for maximum upside capture.
  ⎿  ☒ Examine project structure and identify strategy file
     ☒ Read and analyze current strategy implementation
     ☒ Identify EVOLVE-BLOCK sections for optimization
     ☒ Improve strategy parameters and logic for better Calmar Ratio
     ☒ Validate strategy using strategy_validator.py
     ☒ Provide summary of improvements made

It seems like an issue exiting gracefully - probably something wrong with the way I'm doing the async call.

michael-hedgineer · 1 year ago

Yeah it may be the way you are doing the async call. Do you know if the error I mentiond above is from your code or claude?

_Error: Expected content to be an assistant message, but got "user"_

That looks interesting to me, and curious where that message is coming from. If not your code then that is helpful. Are you using those variables (user, assistant, message) in your code? If yes then it may be in how you are handling the subprocess and async.

Also do you know if you are capturing the stderr of the claude process? For example when I am wrapping claude with async processes I store the session id, so that I can continue them later on (this is actually a really cool feature and also helpul for debugging). However claude occasionally cleans these up so when I would call an async process with an old session id, I was gettting failures without any error message. Once I started to also pipe out stderr it became clear what the issue was.

Just mentioning this as there are not many docs or forums of people doing stuff like this. Are you streaming out the logs anywhere that you can review outside of the process with verbose turned on? This has also helped me quite a bit with tracing back issues.

rboyce-ant contributor · 1 year ago

I believe this is likely the same issue as #473, just showing a different error message in -p mode.

xbno · 1 year ago

I'm not specifically referencing any user/assistant roles so I'm pretty sure thats coming from claude code, but its not present in the session when i reopen, so I could be wrong.

Heres my async call:

            cmd_executable = "claude"
            cmd_arguments = f"/project:evolve {Path(temp_path).parent} {temp_path} {calmar} {profit_factor} {returns}".split()
            cmd_flags = [
                "--max-turns",
                "20",
                # "--print",
                # # "--dangerously-skip-permissions",
                # "--output-format",
                # "stream-json",
                # "--verbose",
            ]
            cmd_list = [cmd_executable, *cmd_flags, *cmd_arguments]

            # Create log file path
            log_file = os.path.join(output_dir, "claude_output.log")

            # Open log file and process
            with open(log_file, "w", encoding="utf-8") as f:
                process = await asyncio.create_subprocess_exec(
                    *cmd_list,
                    stdin=asyncio.subprocess.DEVNULL,
                    stdout=asyncio.subprocess.PIPE,
                    stderr=asyncio.subprocess.PIPE,
                )

                stdout_task = asyncio.create_task(
                    self._log_stream(process.stdout, f, "STDOUT")
                )
                stderr_task = asyncio.create_task(
                    self._log_stream(process.stderr, f, "STDERR")
                )

                await asyncio.gather(stdout_task, stderr_task)
            if process.returncode == 0:
                with open(temp_path, "r", encoding="utf-8") as f_improved:
                    improved_code = f_improved.read()
                return True, improved_code, self.claude_stats
            else:
                print(
                    f"\nClaude process exited with error code: {process.returncode}. Check log: {log_file}"
                )
                return False, code, self.claude_stats

I'm wondering if I should be doing the cmd -p --verbose > claude.log type instead?

My observation has been that when I downgrade the big model to haiku it doesn't seem to happen as much. I definately was seeing it nearly everytime when I had some async timeout at 180s. I removed that and it makes it rarer but still present.

willer · 1 year ago

The errors are coming in stderr. One thing I've noticed with claude -r is a ton of sessions with content in them but the description complains about being authenticated. a) I don't know yet why there are so many sessions when it's running more like 4 per hour, not 40, and b) this is on a Claude Max subscription, and I'm not getting these auth errors in any interactive session. Is there a problem with auth handling, maybe related to sub-agent tool use or something?

All of this activity relates to a shell script running claude -p a few times per loop, and like I said, approx loops approx once an hour. Nothing is backgrounded.

Modified Created # Messages Summary
❯ 1. 1m ago 7m ago 61 You are an expert megathinker static code rev...

  1. 8m ago 15m ago 91 Invalid API key · Please run /login
  2. 16m ago 18m ago 35 Invalid API key · Please run /login
  3. 19m ago 21m ago 51 Invalid API key · Please run /login
  4. 22m ago 26m ago 101 Invalid API key · Please run /login
  5. 27m ago 28m ago 29 Invalid API key · Please run /login
  6. 29m ago 32m ago 98 Invalid API key · Please run /login
  7. 33m ago 47m ago 275 Invalid API key · Please run /login
  8. 48m ago 49m ago 55 Invalid API key · Please run /login
  9. 50m ago 55m ago 101 Invalid API key · Please run /login
  10. 55m ago 1h ago 248 Invalid API key · Please run /login
  11. 1h ago 1h ago 41 Invalid API key · Please run /login
  12. 1h ago 1h ago 48 Invalid API key · Please run /login
  13. 1h ago 1h ago 87 Invalid API key · Please run /login
  14. 1h ago 1h ago 45 Invalid API key · Please run /login
  15. 1h ago 1h ago 25 Invalid API key · Please run /login
  16. 1h ago 1h ago 66 Invalid API key · Please run /login
  17. 1h ago 1h ago 24 Invalid API key · Please run /login
  18. 1h ago 1h ago 46 Invalid API key · Please run /login
  19. 1h ago 1h ago 91 Invalid API key · Please run /login
  20. 1h ago 1h ago 38 Invalid API key · Please run /login
willer · 1 year ago

I tried changing my ANTHROPIC_API_KEY in my environment to something else, and apparently it was an old key. Here's the problem: I'm running claude on a Claude Max account, so it shouldn't be touching the API key at all. I feel like maybe this is related?

Invalid API key · Fix external API key

github-actions[bot] · 1 year ago

This issue has been automatically locked since it was closed and has not had any activity for 7 days. If you're experiencing a similar issue, please file a new issue and reference this one if it's relevant.