claude -p looks like a one-shot command, but it can also be a long-lived child process that talks to your program in both directions. That is how you build your own chat UI, bot, or review tool around Claude Code without scraping a terminal.
The part that surprised me is that the CLI can ask your program a question in the middle of a run and then wait for the answer. If you don't know that, your wrapper hangs. If you do, you get proper question cards, plan approvals, and permission prompts.
This post shows the handshake with a runnable host, one real run I captured, and the mistakes that are easy to make. I tested it on Claude Code 2.1.332 on Windows.
You start the CLI with stream-JSON on both sides:
claude -p --input-format stream-json --output-format stream-json \
--verbose --permission-prompt-tool stdio
system/init, assistant, user (tool results), result, and the interesting one, control_request.
--permission-prompt-tool stdio is what routes "this tool needs a human" decisions to you instead of handling them inside the CLI. Without a reply from you, those decisions can't be made.
This is the whole thing. 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));
Two details worth knowing:
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.NO_REPLY switch exists for the experiment further down. It makes the host stay silent on purpose.
Here is the output from a single 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."
The model called AskUserQuestion; the CLI turned that into a control_request and stopped; the host answered; the model read the answer and finished. The timings are from one run on a small model, so treat them as a shape, not a benchmark.
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:
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.
can_use_tool is not only for questions. It is the CLI's way of saying "a tool wants to run and the decision belongs to the host". Your policy is yours to define. This is what we settled on in AnBoWork, with the reason for each row:
A few of these are worth explaining:
ExitPlanMode, we render the plan as a card, then interrupt: true so the run ends instead of waiting forever.
The message you send with a deny is read by the model. Write it like an instruction, not like an error code.
What happens if the host just doesn't reply? I ran the same script with NO_REPLY=1:
+2.5s system/init
+6.2s assistant
+6.2s control_request/can_use_tool
+6.2s (not replying on purpose)
+25.0s timeout, killing
Nothing happened for about 19 seconds, until my own timer killed the process. I didn't wait longer to find out whether the CLI has a timeout of its own, so I can't tell you what that limit is, only that a wrapper which forgets to answer looks exactly like a hung session.
request_id``--help on 2.1.332 documents --permission-prompts host and --permission-prompt-tool as the way to receive these prompts. I would still re-run a script like this after every upgrade.
If you just want the same idea without parsing JSON lines yourself, the official Agent SDK exposes it as a canUseTool callback. Writing the host by hand is mostly useful when you want to understand what the SDK is doing, or when you are wrapping the binary in a language the SDK doesn't cover.
claude -p with stream-JSON on both sides is a two-way protocol, not just a pipe.control_response. allow with updatedInput.answers is how a question gets answered; deny with a good message is how you steer the model.
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.