DEV Community

Cover image for Your Claude Code wrapper isn't broken. It's waiting for your answer
AnBoWork
AnBoWork

Posted on Edited on

Your Claude Code wrapper isn't broken. It's waiting for your answer

Suppose you have wrapped claude -p in a small service. It runs well for days. Then one afternoon a job never finishes: no output, no error, no exit code, and the process is still alive. You restart it, everything works, and two days later it happens again.

I reproduced exactly this symptom on purpose. The cause turned out to be simpler than any of the usual suspects: the CLI had asked my program a question, and my program never answered.

Three conclusions, up front

Before the details, here is what I would like you to take away:

  1. The CLI can stop and ask you. In the middle of a run, claude -p can send your program a question and pause until it gets an answer.
  2. Waiting is silent. While it waits there is no output, no error and no exit. In my test, 123 seconds of nothing.
  3. The cure is small. Answer every request with allow or deny, and run a timer of your own.

Three conclusions: the CLI can stop and ask you, waiting is silent, the cure is small

The rest of this post shows where each conclusion comes from. I tested on Claude Code 2.1.332 on Windows.

claude -p is a conversation, not a pipe

Most people first meet claude -p as a command that takes a prompt and prints an answer. Used that way, it is a pipe: text goes in, text comes out.

There is a second way to use it, and an analogy helps. Think of a contractor renovating your flat. He works alone for most of the day. When he reaches a decision that is not his to make, say which tile you want in the bathroom, he phones you and waits on site until you answer. Then he carries on.

Side-by-side: a contractor phoning the client and the CLI sending a control_request to the host

Where does the analogy break? A real contractor would call again after a while, or give up and go home. In my test, the CLI did neither. It waited, silently, for as long as I let it. I will come back to that.

In technical terms, your program starts the CLI with stream-JSON on both sides and plays the client:

claude -p --input-format stream-json --output-format stream-json \
  --verbose --permission-prompt-tool stdio
Enter fullscreen mode Exit fullscreen mode

Architecture: your host app talks to claude -p over stdin and stdout, one JSON object per line

  • stdin takes one JSON object per line: your user messages, and your replies to the CLI's questions.
  • stdout emits one JSON object per line: system/init, assistant, user (tool results), result, and the one that matters here, control_request.

--permission-prompt-tool stdio is what sends "this tool needs a decision" requests to you, instead of letting the CLI handle them internally.

The question arrives as one line of JSON

Here is a host in about 35 lines. It sends one prompt that forces the AskUserQuestion tool, answers the question itself, and prints every event with a timestamp.

// A tiny "host" for Claude Code: drives the CLI over stdin/stdout, answers can_use_tool itself.
// Usage: node host-experiment.mjs <empty-working-dir>
import { spawn } from 'node:child_process';
import readline from 'node:readline';

const cwd = process.argv[2];
const env = { ...process.env };
delete env.CLAUDECODE; delete env.CLAUDE_CODE_ENTRYPOINT;
const child = spawn('claude', [
  '-p', '--input-format', 'stream-json', '--output-format', 'stream-json',
  '--verbose', '--permission-prompt-tool', 'stdio', '--model', 'haiku',
], { cwd, env, shell: process.platform === 'win32' });

const send = (obj) => child.stdin.write(JSON.stringify(obj) + '\n');
const t0 = Date.now();
const log = (...a) => console.log(`+${((Date.now() - t0) / 1000).toFixed(1)}s`, ...a);

send({ type: 'user', message: { role: 'user', content: [{ type: 'text',
  text: 'Use the AskUserQuestion tool to ask me whether to name the project "alpha" or "beta" (two options). After I answer, reply with one short sentence naming my choice. Do not use any other tool.' }] } });

readline.createInterface({ input: child.stdout }).on('line', (line) => {
  let m; try { m = JSON.parse(line); } catch { return log('non-json:', line.slice(0, 80)); }
  const sub = m.subtype ? `/${m.subtype}` : m.request?.subtype ? `/${m.request.subtype}` : '';
  log(m.type + sub);
  if (m.type === 'control_request' && m.request.subtype === 'can_use_tool' && process.env.NO_REPLY) { log('  (not replying on purpose)'); return; }
  if (m.type === 'control_request' && m.request.subtype === 'can_use_tool') {
    log('  tool_name =', m.request.tool_name, '| input keys =', Object.keys(m.request.input).join(','));
    log('  questions =', JSON.stringify(m.request.input.questions).slice(0, 400));
    const q = m.request.input.questions[0];
    send({ type: 'control_response', response: { subtype: 'success', request_id: m.request_id,
      response: { behavior: 'allow', updatedInput: { ...m.request.input, answers: { [q.question]: q.options[1].label } } } } });
    log('  -> replied allow + answers');
  }
  if (m.type === 'result') { log('  result =', JSON.stringify(m.result).slice(0, 200)); child.stdin.end(); setTimeout(() => { child.kill(); process.exit(0); }, 300); }
});
setTimeout(() => { log('timeout, killing'); child.kill(); process.exit(0); }, Number(process.env.TIMEOUT_MS ?? 120000));
Enter fullscreen mode Exit fullscreen mode

Two details worth knowing:

  • I delete CLAUDECODE and CLAUDE_CODE_ENTRYPOINT from the environment only because I launch this from inside another Claude Code session. You probably don't need that.
  • The NO_REPLY switch exists for the experiment in the next section. It makes the host stay silent on purpose.

This is the output of one run, which I then drew as a timeline:

+2.3s system/init
+5.8s assistant
+5.8s control_request/can_use_tool
+5.8s   tool_name = AskUserQuestion | input keys = questions
+5.8s   -> replied allow + answers
+5.8s user
+9.1s assistant
+9.7s result/success
+9.7s   result = "You chose \"beta\" as the project name."
Enter fullscreen mode Exit fullscreen mode

Timeline of the run: init, assistant, control_request, control_response, user, assistant, result

The model called AskUserQuestion. The CLI turned that into a control_request and stopped. The host answered, the model read the answer, and the run finished. The timings come from one run on a small model, so treat them as a shape, not a benchmark.

What do the request and the reply look like? The request carries the tool name and the tool's input. For AskUserQuestion that input is a list of questions, each with a header, options and a multiSelect flag. Your reply is a control_response that echoes the request_id. To allow the tool, return behavior: "allow" and an updatedInput, which is the original input plus an answers object keyed by the question text:

The control_request on the left and the control_response on the right, side by side

In our own host, a multi-select answer is joined with ", " and any free-text note from the user is appended to the same string. I only ran a single-select question for this post, so check multi-select against your CLI version before relying on it.

Silence looks exactly like a hang

What happens if the host never answers? I ran the same script with NO_REPLY=1, twice, and stopped each run with my own timer.

run 1:  +6.2s control_request/can_use_tool   ...   +25.0s timeout, killing
run 2:  +6.5s control_request/can_use_tool   ...  +130.0s timeout, killing
Enter fullscreen mode Exit fullscreen mode

The first run sat for 19 seconds, the second for 123. In both, the CLI printed nothing after the request: no warning, no error, no exit. It never timed out on its own within the time I gave it.

Three horizontal bars: an answered run that ends at 9.7 seconds, and two unanswered runs paused for 19 and 123 seconds

I want to be precise about the limits of this test. It is two runs, on one version, on one machine, with a small model. I stopped at 130 seconds, so I cannot tell you whether the CLI has a timeout beyond that. What I can tell you is that a wrapper which forgets to answer looks exactly like a hung process.

An answer can be "no", and the model will read it

Every control_request goes through the same life cycle: the CLI emits it, pauses, your host decides, replies with the same request_id, and the CLI resumes.

The five steps in the life of a control_request, with a dashed branch for the case where the host never replies

can_use_tool is not only for questions. It is the CLI's way of saying that a tool wants to run and the decision belongs to the host, so your policy is yours to define. This is the policy AnBoWork's host uses today:

A table of tool situations and the reply the host sends

A few of these rows deserve a sentence each:

  • Plan approval. When the model calls ExitPlanMode, we render the plan as a card and then deny the call with a message telling the model to stop and wait. The turn ends there, and the user's decision starts the next turn. Letting the call through would have the model start implementing before anyone approved anything.
  • Already approved. After approval the model sometimes calls ExitPlanMode again, misled by the plan still in its history. If the host keeps showing plan cards, the user never reaches implementation. We deny with a message saying that plan mode is off and that it should start implementing.
  • User skipped the question. If the user types a new message instead of answering, we deny with a reason but do not interrupt, so the model reads the new message and carries on.
  • Stopped session. If nobody will ever answer, deny with interrupt: true, so the run ends instead of waiting forever.

The message you send with a deny is read by the model. Write it as an instruction, not as an error code.

Three rules that keep a host from hanging

Each rule below comes from something I measured or something we had to fix.

Three rules: answer every request, run a timer of your own, pin the version you tested

First, answer every request. Allow, deny, or, for subtypes you do not know, an empty success response. A request left open is a paused run. This is the whole point of the experiment above.

Second, run a timer of your own. The CLI will not tell you it is stuck, so your host has to decide when to show a pending state and when to give up. I found no built-in limit within 123 seconds; pick yours deliberately.

Third, pin the version you tested. This is how a host talks to the CLI, not a stable public API. On 2.1.332, --help documents --permission-prompts host and --permission-prompt-tool as the way to receive these prompts, and I would still re-run a script like this after every upgrade.

If you would rather not parse JSON lines yourself, the official Agent SDK exposes the same idea as a canUseTool callback. Writing the host by hand is mostly useful for understanding what the SDK does for you, or for wrapping the binary from a language the SDK does not cover.

Three sentences to keep

  1. claude -p is a conversation, and your host is the other speaker.
  2. A control_request pauses the run until you send a matching control_response.
  3. When nobody answers, the symptom is silence, so measure it yourself.

Three sentences to keep, and a question to think about

And a question to take with you: if your user closes the window while a question is still pending, what should your host answer?

Disclosure: I work on AnBoWork, a desktop workbench that drives the official Claude Code and Codex command-line programs and shows them as a chat interface. The policy table above is what our host does today. The host script is a minimal demo, not our production code.

Top comments (1)

Collapse
 
anbowork profile image
AnBoWork •

One thing I couldn't settle in this test: how long the CLI waits for a reply. I stopped at 130 seconds with no output and no error, so I don't know whether there is a longer limit, or none at all.

If you have left a control_request unanswered for longer, or seen a version that gives up on its own, I'd like to hear what you saw: the version, how long it waited, and what the CLI printed. I'll update the post with anything useful.

And the question from the end: if your user closes the window while a question is still pending, what does your host answer? We deny with interrupt: true, but I'm not sure that is the only sensible choice.