Drive a Multi-Turn Daemon
Goal: Spawn claude-p daemon once from Node.js, verify liveness with ping/pong, run two back-to-back conversational turns in the same Claude Code session, and shut down cleanly on stdin EOF.
Time: 12 minutes. You need Node >= 18, claude, and claude-p.
Why not just call claude-p twice?
Section titled “Why not just call claude-p twice?”Every one-shot claude-p call allocates a fresh PTY, boots Ink, negotiates DEC queries, and tears down the process (~50–200 ms plus Claude initialization). If you are building an agent loop, chat bridge, or test harness that sends 20 turns, starting from scratch every turn wastes seconds and forces --resume replay.
claude-p daemon solves this by keeping one interactive claude session alive and turning stdin/stdout into a two-way NDJSON pipe:
Step 1: Test the wire protocol by hand
Section titled “Step 1: Test the wire protocol by hand”Before writing code, send a ping and a user turn from your terminal so you can watch the exact frames come back:
printf '%s\n' \ '{"type":"ping"}' \ '{"type":"user","message":{"role":"user","content":"Remember the word: ZIRCON. Reply OK."}}' \ | npx claude-p daemon --dangerously-skip-permissions \ | jq -c '{type, subtype, ts, session_id, result}'Look closely at the order of lines on stdout:
{"type":"pong","ts":1763859600123}— can arrive even beforesystem/initbecausepingis answered inline by the main event loop in any state!{"type":"system","subtype":"init","session_id":"..."}— emitted once as soon asSessionStartfires.- Raw transcript JSONL lines from Claude (
user,assistant, tool events) as they flush. {"type":"result","subtype":"success","session_id":"...","result":"OK",...}— emitted whenStopfires for that turn and stays unchallenged for a 150 ms confirmation window.- Because
printfclosed stdin (EOF), the daemon finishes the active turn, drains the queue, terminatesclaude, and exits0. Theuserframe arrived beforeSessionStart, so it waited in the queue (up to 64 prompts / 64 MiB) until the session was ready.
Step 2: Write a tiny Node.js daemon client
Section titled “Step 2: Write a tiny Node.js daemon client”Let’s build daemon-client.mjs that spawns claude-p daemon, waits for system/init, runs a health ping, asks two connected questions in the same session, and closes stdin to exit cleanly.
Create daemon-client.mjs:
import { spawn } from 'node:child_process';import readline from 'node:readline';
const child = spawn( 'npx', [ 'claude-p', 'daemon', '--dangerously-skip-permissions', '--idle-timeout', '120', ], { stdio: ['pipe', 'pipe', 'inherit'], env: { ...process.env, CLAUDE_P_PTY_TRACE: 'off' }, },);
const rl = readline.createInterface({ input: child.stdout });
// Simple waiter queue for the next frame matching a predicate.const waiters = [];rl.on('line', (line) => { if (!line.trim()) return; const frame = JSON.parse(line); const idx = waiters.findIndex((w) => w.match(frame)); if (idx !== -1) { const [w] = waiters.splice(idx, 1); w.resolve(frame); }});
function waitFor(match) { return new Promise((resolve) => waiters.push({ match, resolve }));}
function send(frame) { child.stdin.write(`${JSON.stringify(frame)}\n`);}
// 1. Wait until Claude finishes booting and SessionStart fires.const init = await waitFor((f) => f.type === 'system' && f.subtype === 'init');console.log('Session ready:', init.session_id);
// 2. Verify main loop liveness with a ping/pong round-trip.const pongPromise = waitFor((f) => f.type === 'pong');send({ type: 'ping' });const pong = await pongPromise;console.log('Loop alive at unix ms:', pong.ts);
// 3. Turn 1: plant a fact in session memory.const turn1Promise = waitFor((f) => f.type === 'result');send({ type: 'user', message: { role: 'user', content: 'Remember the codeword COBALT. Reply only: STORED', },});const turn1 = await turn1Promise;console.log('Turn 1:', turn1.result, `(${turn1.duration_ms} ms)`);
// 4. Turn 2: recall it in the exact same live PTY session.const turn2Promise = waitFor((f) => f.type === 'result');send({ type: 'user', message: { role: 'user', content: 'What was the codeword? Reply with one word.', },});const turn2 = await turn2Promise;console.log('Turn 2:', turn2.result, `(${turn2.duration_ms} ms)`);
// 5. Close stdin (EOF) so the daemon terminates claude and exits 0.child.stdin.end();const exitCode = await new Promise((resolve) => child.once('close', resolve));console.log('Daemon exited with code:', exitCode);Run it:
node daemon-client.mjsExpected output:
Session ready: 550e8400-e29b-41d4-a716-446655440000Loop alive at unix ms: 1763859642018Turn 1: STORED (2140 ms)Turn 2: COBALT (1480 ms)Daemon exited with code: 0Step 3: Understand the watchdogs and interrupt
Section titled “Step 3: Understand the watchdogs and interrupt”Look at how claude-p daemon protects a long-running controller from hanging:
--idle-timeout 120sets the busy-turn PTY silence watchdog to 120 seconds (default180 s;0disables).- While idle (waiting for your next
userframe), watchdogs never trip—your daemon can sit parked for hours. - The moment a prompt is dispatched (
idle → busy),claude-presets both watchdog baselines tonowso a long idle period never causes an instant false timeout.
- While idle (waiting for your next
--transcript-idle-timeout(default600 s;0disables) is the spinner-immune counterpart: even if Ink’s spinner keeps writing PTY bytes, this watchdog firestranscript_stalled(exit124) if the transcript JSONL file stops growing while busy. Before exiting on any watchdog, the daemon flushes a structured errorresultframe to stdout so your reader never hits a mysterious silent EOF. One-shot mode honors the same flag while awaitingStop(TranscriptStalled, exit124).{"type":"interrupt"}lets you cancel a runaway turn without restartingclaude: send it on stdin while busy and the daemon sends Escape (\x1b), waits up to 1.5 s, emits aresultwithsubtype: "interrupted"(is_error: false), and returns to.idleready for the next turn.CLAUDE_P_PTY_TRACE: 'off'keeps the periodic stderr trace off even if you later add--debug. The trace is off by default;--debugturns on a[pty-trace]line every 60 seconds showingpty_deltaandtranscript_pos.- A blocked permission prompt ends the turn, not the session. If Claude Code fires
PermissionRequestwhile busy, nobody can answer the prompt, so the daemon sends Escape, emits atype:"result"frame withsubtype: "error_during_execution"anderror: "permission_prompt_blocked", and returns to.idle. The client above resolves its turn on that frame too; checkis_error. - Every timeout exits
124.session_start_timeout(--timeout, default300 s),idle_timeout, andtranscript_stalledeach write one errorresultframe and exit124, the same code one-shotStopTimeoutuses.
Your controller sends {"type":"interrupt"} while Turn 1 is busy.
Escape stops Claude, 1.5 s pass without a Stop hook, and the daemon emits
subtype: “interrupted” and returns to idle. You immediately send Turn 2,
and 100 ms later a delayed Stop from Turn 1 finally arrives on the FIFO.
Does that late Stop prematurely end Turn 2?
Check your answer
No. After an interrupt window elapses, daemon.zig sets
after_interrupt = true. On Turn 2, stopBelongsToTurn() ignores any
Stop hook until Turn 2 proves it is live via UserPromptSubmit or new
transcript bytes. Before pasting Turn 2, the daemon also pumps stray transcript bytes,
advances turn_start_pos, and sends Ctrl-U to clear any restored input.
There are no dumb questions
Section titled “There are no dumb questions”Q: Why do we need TWO busy watchdogs (--idle-timeout and --transcript-idle-timeout)?
A: Ink draws an animated spinner while Claude waits on a hung tool or stalled network call. That spinner keeps writing ANSI frames to the PTY, which resets --idle-timeout (180 s) forever. --transcript-idle-timeout (600 s) watches actual byte growth in transcript.jsonl, so a ticking spinner can never mask a wedged turn.
Q: Why is is_error set to false on an interrupted result frame?
A: You asked for the interrupt. Setting is_error: false with subtype: "interrupted" lets a controller distinguish a caller-initiated cancellation from a fatal timeout (is_error: true, subtype: "error", error: "idle_timeout" and similar).
Q: What if I close stdin while a turn is still running?
A: The daemon does not kill the in-flight turn. It sets stdin_eof = true, lets the active turn and any queued prompts finish, drains the tailer, terminates claude, and exits 0.
Next steps
Section titled “Next steps”- Need exact frame schemas and edge cases? Read the Daemon Protocol Reference.
- Debugging a slow or stuck turn? See Debugging and Diagnostics.