Daemon

Sessions and streaming

Start sessions, read their ordered event log, and stream it to a viewer without gaps or duplicates.

A session is one supervised run with an ordered, persisted event log. Every event has a seq (1, 2, 3, ... per session) and an at timestamp. The daemon persists each event before any subscriber sees it.

Events

typeWhat it carries
statusstatus, previous: every status change
outputraw process output: stream (pty, stdout, stderr), data or data_b64
messagemessage_id, role, content. partial: true chunks are deltas; the final message with the same message_id supersedes them
tool_callcall_id, tool_name, args, status (started, completed, failed), result or error
model_callmodel, usage (tokens, cost_usd)
approval_requested, approval_resolvedsee Approvals
exitexit_code, signal: the last event before the terminal status
errorerror: { code, message }. The session may continue

Statuses: starting, running, waiting_input, waiting_approval, then one terminal status: exited (the process ended, any exit code), failed (could not start, or the runner failed), stopped (stop() or shutdown).

Claude Code

The claude-code runner drives Claude Code through the Claude Agent SDK, one query() per turn. Partial text arrives as partial messages, tools as tool_call pairs, usage as one model_call per model per turn. The Claude session id becomes the session's agent_session_id, which later turns and resumed sessions continue.

The runner takes its query through loadQuery. The example injects a scripted one so it runs with no binary, no key and no network:

examples/ts/claude-code-stream/main.ts
/** SDK messages, reduced to the fields the runner reads. */
const sdk = (message: Record<string, unknown>) => message as unknown as SDKMessage;
const CLAUDE_SESSION = "6f1c2d4e-0000-4000-8000-000000000001";

const turn: SDKMessage[] = [
  sdk({ type: "system", subtype: "init", session_id: CLAUDE_SESSION, model: "fake-model" }),
  sdk({ type: "stream_event", parent_tool_use_id: null, event: { type: "message_start", message: { id: "api_1" } } }),
  sdk({
    type: "stream_event",
    parent_tool_use_id: null,
    event: { type: "content_block_start", index: 0, content_block: { type: "text" } },
  }),
  ...["Running ", "the tests."].map((text) =>
    sdk({
      type: "stream_event",
      parent_tool_use_id: null,
      event: { type: "content_block_delta", index: 0, delta: { type: "text_delta", text } },
    }),
  ),
  sdk({
    type: "assistant",
    parent_tool_use_id: null,
    message: {
      id: "api_1",
      content: [
        { type: "text", text: "Running the tests." },
        { type: "tool_use", id: "tu_1", name: "Bash", input: { command: "npm test" } },
      ],
    },
  }),
  sdk({
    type: "user",
    parent_tool_use_id: null,
    message: {
      content: [{ type: "tool_result", tool_use_id: "tu_1", content: "41 passed, 1 failed", is_error: false }],
    },
  }),
  sdk({
    type: "assistant",
    parent_tool_use_id: null,
    message: { id: "api_2", content: [{ type: "text", text: "One test fails in parse.ts." }] },
  }),
  sdk({
    type: "result",
    subtype: "success",
    is_error: false,
    result: "One test fails in parse.ts.",
    modelUsage: {
      "fake-model": {
        inputTokens: 1200,
        outputTokens: 80,
        cacheReadInputTokens: 0,
        cacheCreationInputTokens: 0,
        costUSD: 0.0042,
      },
    },
  }),
];

const prompts: string[] = [];
/** Each call is one turn. A real `query()` also takes `interrupt()` and `close()`; these turns end on their own. */
const fakeQuery: ClaudeQuery = ({ prompt }) => {
  prompts.push(prompt);
  const messages = (async function* () {
    yield* turn;
  })();
  return { [Symbol.asyncIterator]: () => messages, interrupt: async () => {}, close: () => {} };
};
examples/ts/claude-code-stream/main.ts
const supervisor = createTestSupervisor({
  runners: [claudeCodeRunner({ loadQuery: async () => fakeQuery })], // replaces the built-in claude-code
});
const server = await serve(supervisor, { direct: { port: 0 }, name: "build-box", clock: supervisor.clock });

With a prompt, a session runs one turn and exits 0. Without one it is interactive: it waits in waiting_input and each input(text) is the next turn. Over the wire, session.start has no interactive field; omit the prompt to get an interactive session.

Streaming to a viewer

RemoteSession.events() subscribes, replays stored events after afterSeq, then follows live ones. It drops seqs it already yielded, fills session.lagged gaps (a slow viewer loses only output events, then fetches them with session.events), and ends after the terminal status event.

examples/ts/claude-code-stream/main.ts
const session = await client.startSession({
  runner: "claude-code",
  cwd: os.tmpdir(),
  prompt: "Find the failing test",
});
const seen: SessionEvent[] = [];
for await (const event of session.events()) {
  seen.push(event);
  switch (event.type) {
    case "status":
      console.log(`${event.seq} status ${event.previous} -> ${event.status}`);
      break;
    case "message":
      console.log(`${event.seq} ${event.role}${event.partial ? " (partial)" : ""}: ${JSON.stringify(event.content)}`);
      break;
    case "tool_call":
      console.log(`${event.seq} tool ${event.tool_name} ${event.status} ${JSON.stringify(event.result ?? event.args)}`);
      break;
    case "model_call":
      console.log(
        `${event.seq} model_call ${event.model}: ${event.usage.input_tokens} in, ${event.usage.output_tokens} out, $${event.usage.cost_usd}`,
      );
      break;
    case "exit":
      console.log(`${event.seq} exit ${event.exit_code}`);
      break;
  }
}
const info = await session.info();
console.log(`agent_session_id ${info.agent_session_id}`);

The transcript:

1 status null -> starting
2 status starting -> running
3 user: "Find the failing test"
4 assistant (partial): "Running "
5 assistant (partial): "the tests."
6 assistant: "Running the tests."
7 tool Bash started {"command":"npm test"}
8 tool Bash completed "41 passed, 1 failed"
9 assistant: "One test fails in parse.ts."
10 model_call fake-model: 1200 in, 80 out, $0.0042
11 exit 0
12 status running -> exited

Listing and watching

client.list(filter) returns one page of SessionInfo, newest first (status, pending_approvals, tenant, limit, before). client.watch() yields the current list, then every session.updated push, so a session list stays live without subscribing to every stream. Keep the copy with the higher last_seq.

Control

A controller may call input, resize, interrupt and stop on a RemoteSession, with the same meaning as on a local Session. session.input is not deduplicated: after a lost channel, check the events before sending it again.

Reconnecting

The client does not reconnect by itself yet. When client.closed resolves, connect() again and resume each stream with events({ afterSeq: lastSeqYouRendered }). Nothing is lost: the log is on the daemon.

On this page