Skip to content

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.


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:

stdin (NDJSON) {"type":"user", ...} Queued (64 prompts / 64 MiB); pasted when idle. {"type":"ping"} Answered inline in any state. {"type":"interrupt"} Sends ESC while busy; keeps session open for next turn. EOF (stdin closed) Drains active turn + queue, terminates child, exits 0. blank line Ignored silently; no frame. daemon state loop waiting_for_ready --timeout (300 s → exit 124) · EOF → 0 idle watchdogs paused while parked busy --idle-timeout (180 s PTY) --transcript-idle-timeout (600 s) spinner-immune · exit 124 ESC → 1.5 s window → idle PermissionRequest ESC → permission_prompt_blocked → idle SessionStart dequeue Stop / ESC stdout (NDJSON) system / init Once on SessionStart + session_id transcript lines (raw) Live stream via pread Tailer {"type":"result", ...} Turn slice on confirmed Stop (150 ms) {"type":"pong","ts":…} Immediate reply to ping interrupted / error result Ends a turn or the session is_error: false on interrupted {"type":"error","error":…} Rejects one line; no turn ends
claude-p daemon keeps one interactive Claude session open across turns. ping is answered inline; interrupt cancels a busy turn without killing the session. type:"error" frames reject one input line; type:"result" frames end a turn or the session.

Before writing code, send a ping and a user turn from your terminal so you can watch the exact frames come back:

Terminal window
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:

  1. {"type":"pong","ts":1763859600123} — can arrive even before system/init because ping is answered inline by the main event loop in any state!
  2. {"type":"system","subtype":"init","session_id":"..."} — emitted once as soon as SessionStart fires.
  3. Raw transcript JSONL lines from Claude (user, assistant, tool events) as they flush.
  4. {"type":"result","subtype":"success","session_id":"...","result":"OK",...} — emitted when Stop fires for that turn and stays unchallenged for a 150 ms confirmation window.
  5. Because printf closed stdin (EOF), the daemon finishes the active turn, drains the queue, terminates claude, and exits 0. The user frame arrived before SessionStart, 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:

Terminal window
node daemon-client.mjs

Expected output:

Session ready: 550e8400-e29b-41d4-a716-446655440000
Loop alive at unix ms: 1763859642018
Turn 1: STORED (2140 ms)
Turn 2: COBALT (1480 ms)
Daemon exited with code: 0

Step 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:

  1. --idle-timeout 120 sets the busy-turn PTY silence watchdog to 120 seconds (default 180 s; 0 disables).
    • While idle (waiting for your next user frame), watchdogs never trip—your daemon can sit parked for hours.
    • The moment a prompt is dispatched (idle → busy), claude-p resets both watchdog baselines to now so a long idle period never causes an instant false timeout.
  2. --transcript-idle-timeout (default 600 s; 0 disables) is the spinner-immune counterpart: even if Ink’s spinner keeps writing PTY bytes, this watchdog fires transcript_stalled (exit 124) if the transcript JSONL file stops growing while busy. Before exiting on any watchdog, the daemon flushes a structured error result frame to stdout so your reader never hits a mysterious silent EOF. One-shot mode honors the same flag while awaiting Stop (TranscriptStalled, exit 124).
  3. {"type":"interrupt"} lets you cancel a runaway turn without restarting claude: send it on stdin while busy and the daemon sends Escape (\x1b), waits up to 1.5 s, emits a result with subtype: "interrupted" (is_error: false), and returns to .idle ready for the next turn.
  4. CLAUDE_P_PTY_TRACE: 'off' keeps the periodic stderr trace off even if you later add --debug. The trace is off by default; --debug turns on a [pty-trace] line every 60 seconds showing pty_delta and transcript_pos.
  5. A blocked permission prompt ends the turn, not the session. If Claude Code fires PermissionRequest while busy, nobody can answer the prompt, so the daemon sends Escape, emits a type:"result" frame with subtype: "error_during_execution" and error: "permission_prompt_blocked", and returns to .idle. The client above resolves its turn on that frame too; check is_error.
  6. Every timeout exits 124. session_start_timeout (--timeout, default 300 s), idle_timeout, and transcript_stalled each write one error result frame and exit 124, the same code one-shot StopTimeout uses.

Trace the state machine: what happens after an interrupt?

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.

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.