Agent stream
Reading an agent session as it happens — the agent contract (agent-v1) in, a small event vocabulary out, how to write to a session, the draft in flight, and usage summaries.
Why it exists
A delegated task runs under an agent app, whose runner drives its harness (Claude Code, Codex,
Mistral Vibe, or one you wrote) in the sandbox. Every runner speaks the same contract, agent-v1: five
verbs on stdin, our vocabulary on stdout, one JSON object per line. The translation from a harness's
own dialect happens in the runner, before the line leaves the machine. This module is the platform's
side of that seam, and nothing here knows which harness is on the other end.
Two rules everything else depends on:
- The vocabulary is what gets stored, never the harness's own shape. A CLI's JSON output is an
output format, not an API; persisting it would date the history the first time the vendor
reshuffles a field. Anything the reader cannot place becomes
rawrather than being dropped. - A malformed line is never fatal. This reads another program's output on a read path. Garbage in a line costs that line, not the task.
The event vocabulary, field by field, is documented in Formats → Agent events.
import {
userTurnLine,
splitCompleteLines,
parseLines,
summarizeUsage,
type AgentProtocol,
} from "@spunto/build/agent-stream"Everything here is pure: lines in, events out. No network, no environment, no clock beyond what you pass in.
Until 0.31.0 this module also read the harnesses' own dialects (claude-json, claude-stream,
jsonl, claude-runner, codex-runner), with applyProtocol, PROJECT_AGENT_PROTOCOLS, the title
probe of Claude's transcript (sessionTitleProbe, parseSessionTitle, readsTitleOutOfBand) and
the model-window helpers (contextWindowOf, resolveContextWindow…). They are gone: reading a
harness is its runner's job.
Protocols
AGENT_PROTOCOLS / AgentProtocol
const AGENT_PROTOCOLS = ["none", "agent-v1"] as const
type AgentProtocol = (typeof AGENT_PROTOCOLS)[number]| Protocol | Meaning |
|---|---|
none | Nothing to read: a task with no session, or one whose session has ended and whose history is already stored. Every function below returns nothing (or the bare text) for it. |
agent-v1 | The Spunto agent contract, what every agent app's runner prints. Read by one strict reader, with no adapter of anyone's. |
isInteractive(protocol)
function isInteractive(protocol: AgentProtocol): booleanDoes this protocol keep the harness alive, listening on stdin, between turns? True for agent-v1.
Writing to a session
RunnerInput
type RunnerInput =
| { type: "user"; text: string }
| { type: "interrupt"; id: string }
| { type: "title"; id: string; description: string }
| { type: "answer"; callId: string; answers: QuestionAnswer[] }
| { type: "mcp.reload"; id: string; servers?: AgentMcpServer[] }The whole input side of the contract: five verbs, the same for every harness, so the platform never
writes a harness's own shape into a runner. Closing stdin ends the session once its turn is over.
Each helper below returns one of them as a newline-terminated JSON line, to be written as a single
write: under PIPE_BUF that is atomic, which is what stops two messages from interleaving into one
unparseable line.
userTurnLine(protocol, text)
function userTurnLine(protocol: AgentProtocol, text: string): stringOne turn of the conversation: {"type":"user","text":…} for agent-v1, the text itself otherwise.
stdin.write(userTurnLine("agent-v1", "Now add tests for it."))
// → '{"type":"user","text":"Now add tests for it."}\n'interruptLine(protocol, requestId)
function interruptLine(protocol: AgentProtocol, requestId: string): string | nullStops what the harness is doing without killing it: {"type":"interrupt","id":…} for
agent-v1, null otherwise. The runner ends the turn and stays alive, so the next message is a
normal turn, not a resume.
answerLine(protocol, callId, answers) / QuestionAnswer
type QuestionAnswer = { question: string; selected: string[]; text?: string | null }
function answerLine(protocol: AgentProtocol, callId: string, answers: QuestionAnswer[]): string | nullThe human's choice, for a question the agent asked and whose turn is waiting on it:
{"type":"answer","callId":…,"answers":[…]} for agent-v1, null otherwise. One QuestionAnswer
per question, keyed by the question's text as the agent wrote it: the labels of the options picked
(selected) and/or the human's own words (text). The runner restates the question as answered,
then the turn carries on.
const line = answerLine("agent-v1", event.payload.callId, [
{ question: "Which database?", selected: ["Postgres"] },
])
if (line) stdin.write(line)mcpReloadLine(protocol, requestId, servers)
function mcpReloadLine(protocol: AgentProtocol, requestId: string, servers: AgentMcpServer[]): string | nullAsks the session to reload its MCP servers now, mid-turn included:
{"type":"mcp.reload","id":…,"servers":[{name,path}]} for agent-v1, null otherwise. servers is
the platform's list as it stands today (same shape as SPUNTO_AGENT_MCP): one turned on since the
session started is added, one turned off removed. The runner reconnects every server — save one with
a call in flight, reconnected once that call is over — and answers with an mcp.reloaded event under
requestId.
sessionTitleRequestLine(protocol, requestId, description)
function sessionTitleRequestLine(protocol: AgentProtocol, requestId: string, description: string): string | nullAsks the session to name the conversation: {"type":"title","id":…,"description":…}, with
requestId passed as is and description (the human's prompt) trimmed. null for none or an empty
description. The runner answers with a session.title event if its harness can name a conversation
at all; the harness picks the words, nothing of ours.
const line = sessionTitleRequestLine("agent-v1", sessionId, task.prompt)
if (line) stdin.write(line)Parsing a stream
TASK_EVENT_TYPES / TaskEventType / NormalizedEvent
const TASK_EVENT_TYPES = [
"session.started", "session.title", "message", "thinking", "tool.call", "tool.result",
"plan", "usage", "session.ended", "session.background", "subagent",
"context.compacted", "skill.loaded", "question", "mcp.reloaded", "raw",
] as const
type TaskEventType = (typeof TASK_EVENT_TYPES)[number]
type NormalizedEvent = { type: TaskEventType; payload: Record<string, unknown> }The normalised vocabulary. Deliberately short — it has to be translatable from several harnesses, so anything specific to one of them does not belong in it. Payloads, field by field, are on Agent events.
Text fields are clipped at 8,000 characters with truncated: true, so the UI can say so
instead of quietly lying about what the agent saw. A single tool result can be a 2 MB file read.
parseStreamLine(protocol, line)
function parseStreamLine(protocol: AgentProtocol, line: string): NormalizedEvent[]Parses one line into zero or more events. Zero is a normal answer (a blank line, a
message.delta, any line under none). A line of the contract becomes its event, type lifted out
and the rest as payload. A line the contract does not allow (an unknown type, an unknown field, a
field of the wrong shape) becomes raw, with the object as json and the reason as invalid. A
non-JSON line becomes a raw event with its text — a harness that also prints a banner to stdout is
common, and that must not be invisible either.
parseStreamLine("agent-v1", '{"type":"message","role":"assistant","text":"Done."}')
// → [{ type: "message", payload: { role: "assistant", text: "Done." } }]A session.ended ends the turn, not necessarily the work. If a background task is still
running, the harness wakes itself up for another turn, and another session.ended, when it
finishes. A turn is a hand-back only if the latest session.background lists nothing.
SourcedEvent and parseLines(protocol, lines, budget)
type SourcedEvent = NormalizedEvent & { source: string }
function parseLines(protocol: AgentProtocol, lines: string[], budget: number): SourcedEvent[]Parses whole lines, keeping each event attached to what it was read from: the harness's own message,
which the runner puts on the line as source, or the (trimmed) line itself when it gave none. That
pairing is what makes normalisation reversible: type/payload is a reading, source is what
was read — get the reading wrong and the source is still there to read again. budget caps how many
events one pass may produce, so a runaway session cannot blow past a per-task ceiling in one chunk.
A line the reader throws on costs that line (with a console.warn), not the pass.
splitCompleteLines(chunk)
function splitCompleteLines(chunk: Uint8Array): { lines: string[]; consumed: number }Splits a chunk of bytes into whole lines and says how many bytes that consumed. The cursor only
ever advances past a complete line; a read that lands mid-line leaves the tail for the next one.
Without this, a 3 KB JSON event straddling two reads would be parsed as two invalid halves. Takes a
Uint8Array so a Node Buffer passes straight through and the package stays runnable anywhere.
let offset = 0
async function poll(taskId: string) {
const chunk = await readFrom(worker, logPath, offset) // bytes from `offset`
const { lines, consumed } = splitCompleteLines(chunk)
offset += consumed
const events = parseLines("agent-v1", lines, 500)
await saveEvents(taskId, events) // store type, payload and source
}The draft in flight
foldDraft(protocol, lines, draft) / AgentDraft
type AgentDraft = { text: string; truncated: boolean }
function foldDraft(protocol: AgentProtocol, lines: string[], draft: AgentDraft | null): AgentDraft | nullA runner whose harness streams tokens prints the message being written ahead of it, as
message.delta lines (only when the platform sets SPUNTO_AGENT_STREAM=1). Those are not
events: one row per token would bury a session under rows the finished message then repeats in
full. foldDraft folds them into the one text block in flight instead, starting from the value the
previous read left: a delta with start: true opens a fresh draft, any other appends to it, and a
message, thinking, tool.call, tool.result or session.ended closes it (null). Clipped at
8,000 characters, like the message that will replace it. Never stored; where the draft is kept
between two reads is the caller's business. Always null under none.
drafts.set(taskId, foldDraft("agent-v1", lines, drafts.get(taskId) ?? null))Titles and limits
cleanTitle(value)
function cleanTitle(value: unknown): string | nullOne line, whitespace runs collapsed, trimmed, at most 200 characters; null for a non-string or an
empty result. The shape a session's name is kept in.
TurnLimit / TURN_LIMIT_KINDS
const TURN_LIMIT_KINDS = ["usage", "rate", "overloaded"] as const // plan quota · burst limit · vendor API
type TurnLimit = {
kind: TurnLimitKind
status: number | null // the HTTP status the harness reported (429, 529)
message: string // what the harness said, verbatim
resetsAt: string | null // ISO 8601, when the runner could tell
}A turn can end because the account ran out rather than because the work did. The runner says so
with limit on that turn's session.ended (and on the message that carries it); which of its
harness's messages is a limit is the runner's reading. Declared in ./agent-contract, re-exported
here.
Usage
UsageInput and summarizeUsage(input)
type UsageInput = {
calls: { count: number; inputTokens: number; outputTokens: number; cacheReadTokens: number; cacheCreationTokens: number }
latestCall: Record<string, unknown> | null // most recent scope: "call" payload
latestSession: Record<string, unknown> | null // most recent scope: "session" payload
started: Record<string, unknown> | null // most recent session.started payload
}
function summarizeUsage(input: UsageInput): SessionUsage | nullFolds a task's usage events into the one recap a reader wants. Which number comes from where is the whole content of the function:
- tokens are summed from per-call events, because a turn in flight has not produced a harness total yet — and "0 tokens" under a session that has worked for ten minutes is never true. The harness total is the fallback for a harness that only reports at the end;
- cost, turns and duration only ever come from the harness: pricing a call needs a rate card, and a platform that made one up would be quoting a number it cannot stand behind;
- context is the latest call's prompt size, against the window the session was opened with
(
session.started.contextWindow, as the runner said it). The platform never guesses a window from a model's name: unknown, and the meter stays out.
Returns null when nothing was measured at all — nothing measured is not zero measured.
SessionUsage
Prop
Type
Next to it: ./agent-contract
The contract itself lives in @spunto/build/agent-contract: the reader this module calls
(readContractLine), its JSON Schema (agentContractSchema, shipped as
@spunto/build/agent-contract/schema.json), a conformance suite that drives a runner like the
platform does (runConformance), and fake-agent.mjs, a whole runner with no SDK that passes it.
The runner's side of the seam is there too, and nothing harness-specific with it: the shell that
starts a runner (runnerCommand, on AGENT_NODE under AGENT_HOME), the variables a runner is
handed (RUNNER_ENV, OPTIONS_ENV, STREAM_ENV, MCP_ENV), and the shape of what an app lets a
task choose (AgentCatalog, AgentModel, AgentParam, checked by agentOptionsError).
No harness lives in @spunto/build since 0.32.0, which removed @spunto/build/agent-runners.
Spunto's own runners (Claude Code, Codex, Mistral Vibe), with their adapters, the install scripts
of their SDKs and their catalogs of models, are the package @spunto/agent-runners, for the apps
that are those harnesses. A control plane never imports it.
Types
The canonical shapes a worker's environment is described by, the status it reports back, and the worker status vocabulary with its transition graph.
Terminal
The half of a persistent worker terminal that is a string — the dtach scripts, the session layout, and the parsing of what they print back.