ndjsonfilter

package
v0.155.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 14, 2026 License: MIT Imports: 9 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package ndjsonfilter turns a structured (NDJSON / JSON-Lines) agent output stream into the two streams gofer captures (bd h-aii-rpky, bd h-aii-525u).

An `omp --mode json` or `claude --output-format stream-json` run emits one JSON event per line. Two things are wrong with writing that stream straight to stdout.log: the per-token incremental events (message_update / tool_execution_update / stream_event) inflate the log 10-30x and make the live web log unreadable, and the caller's actual deliverable — the agent's final answer — is buried in the middle of it, after the events. So the capture PROJECTS the stream instead of merely filtering it:

  • stdout gets the agent's FINAL text, written once when the run ends (the last assistant turn for omp, the `result` text for claude).
  • the event stream (stderr by default, like codex) gets one compact line per information-bearing event, each capped at MaxEventBytes with its long fields marked `…(truncated)`.

Guarantees:

  • Output stays valid JSONL for every line the capture could PARSE: only whole lines are ever written, and only the event stream gets JSON. A line it cannot parse (plain text, broken JSON, an over-long line it refuses to buffer) is never dropped — it lands on the event stream, bounded. A blank line is the one exception: it carries nothing, so it is dropped.
  • The `session` row is always read, whatever the whitelist says: the capture reports its id for session capture / resume (omp especially, whose session row only exists in json mode), and the row is kept in the event stream.
  • An empty whitelist means "no filtering at all": every line reaches the projector. A text agent is therefore unaffected by construction — it is not wrapped at all.
  • A line longer than MaxLineBytes (1MB by default) is neither parsed nor buffered whole; its head is kept for the event stream (which caps at 2KB anyway). A final answer that huge is out of scope — keep ndjson_raw on if your agent can produce one.

It is an io.Writer, so it drops into the capture path (the job service wraps the stdout.log writer with it and hands over stderr.log as the event stream), and it counts what it did: Kept+Dropped equals the number of lines seen, which is what the job result reports as ndjson_kept / ndjson_dropped, plus ndjson_truncated for the lines the event cap shortened.

Index

Constants

View Source
const (
	// ProjectorOMP projects an `omp --mode json` stream: per-token incremental
	// events are dropped, tool calls and turn summaries are compacted, and the
	// final answer is the last turn's assistant text.
	ProjectorOMP = "omp"
	// ProjectorClaude projects a `claude --output-format stream-json` stream: the
	// `result` line's text is the final answer, tool_use/tool_result blocks are
	// summarised, `stream_event` (per-token) is dropped.
	ProjectorClaude = "claude"
	// ProjectorGeneric is the fallback for an unknown command: every line the
	// whitelist lets through goes to the event stream unchanged (bounded), and
	// stdout stays empty unless Options.StdoutPath names where the answer lives.
	ProjectorGeneric = "generic"
)

Built-in projector kinds (Options.Projector). A projector turns ONE decoded agent event into the two capture streams (bd h-aii-525u): a compact event line for the log (stderr by default) and — for the line that carries the agent's final answer — the text that belongs on stdout.

The kinds mirror the built-in capture defaults of the same name (agent.builtinNDJSON), resolved in internal/agent by agent key and then by the base name of the agent's command; an agent with no built-in projector gets ProjectorGeneric.

View Source
const DefaultMaxEventBytes = 2048

DefaultMaxEventBytes caps ONE line written to the event stream. An event is a log line, not a payload: 2KB is enough for a tool call summary plus its usage counters, and the agent's real output is on stdout (or in stdout.raw.log when ndjson_raw is on).

View Source
const DefaultMaxLineBytes = 1 << 20

DefaultMaxLineBytes is the parse cap: a longer line is not worth parsing (and must not be buffered whole just to be discarded).

Variables

This section is empty.

Functions

This section is empty.

Types

type CompactEvent

type CompactEvent struct {
	// contains filtered or unexported fields
}

CompactEvent builds one compact event line in the capture's own shape (`{"type":…,…}`), for a caller that produces structured details of its own and wants them read by the same renderers as a captured agent stream. The acp runner is the one such caller (bd h-aii-rnxk): its tool calls/thoughts/permissions go to the job's stderr as these lines, so the web's NdjsonTimeline and `job logs stderr` show an acp-agent's work exactly like an omp/claude event stream.

func NewCompactEvent

func NewCompactEvent(typ string) *CompactEvent

NewCompactEvent starts a line whose first field is `type`.

func (*CompactEvent) Add

func (c *CompactEvent) Add(key string, val any) *CompactEvent

Add appends a field, dropping empty values (the capture's rule everywhere).

func (*CompactEvent) Line

func (c *CompactEvent) Line() []byte

Line renders the event within DefaultMaxEventBytes, without a trailing newline.

type Filter

type Filter struct {
	// contains filtered or unexported fields
}

Filter is an io.Writer that projects an NDJSON agent stream onto two sinks: the agent's final text (stdout.log) and the compact event stream (stderr.log). It is NOT safe for concurrent writers — it is wired to one child process' stdout.

func New

func New(stdout, events io.Writer, opt Options) *Filter

New builds a Filter. stdout receives the agent's final text and events the compact event lines; Options.EventsToStdout / Options.StdoutEvents may route the events back onto stdout.

func (*Filter) Close

func (f *Filter) Close() error

Close flushes what is left, then writes the agent's final answer to stdout if the run produced one. It does not close the underlying writers: the caller owns them. Calling it twice is harmless (the answer is emitted once).

func (*Filter) Counts

func (f *Filter) Counts() (kept, dropped int)

Counts returns the number of lines kept in and dropped from the captured stream. Kept counts every line whose information was retained (an event, a stdout fragment, a session id, or a final-answer source); Kept+Dropped is the total number of lines the agent emitted.

func (*Filter) SessionID

func (f *Filter) SessionID() string

SessionID returns the session id the projected stream carried ("" when it carried none). It is the capture's own answer, and takes precedence over the regex capture that scans the log files.

func (*Filter) Signals

func (f *Filter) Signals() Signals

Signals returns what the stream said about turns / tool calls / model so far.

func (*Filter) Truncated

func (f *Filter) Truncated() int

Truncated returns how many event-stream lines the MaxEventBytes cap shortened.

func (*Filter) Usage

func (f *Filter) Usage() *runner.Usage

Usage returns the token/cost accounting the projected stream carried (SUP-01 E): the LAST usage an agent reported, or nil when the stream carried none. Like SessionID it is the capture's own answer — the projector knows which row of the agent's stream holds the run's final tally, a log scan does not.

func (*Filter) Write

func (f *Filter) Write(p []byte) (int, error)

Write implements io.Writer. Bytes are always accepted in full (the capture never rejects output); only a failing underlying writer surfaces as an error.

type Options

type Options struct {
	// Keep is the event-type whitelist. A bare entry ("message_end") matches the
	// JSON top-level `type`; a dotted entry ("message.role") is a nested path and
	// matches when that path holds a non-empty string. Empty = keep everything.
	// It gates what reaches the projector; the session row always does.
	Keep []string
	// Raw, when non-nil, receives every line VERBATIM (dropped ones included,
	// before any projection) — the stdout.raw.log sidecar for troubleshooting.
	// Write errors are ignored: a debugging artifact must never break a job.
	Raw io.Writer
	// MaxLineBytes overrides DefaultMaxLineBytes; <= 0 uses the default.
	MaxLineBytes int
	// Projector selects the built-in projection rules (ProjectorOMP /
	// ProjectorClaude / ProjectorGeneric). "" or an unknown value falls back to
	// ProjectorGeneric, so a config typo can never lose output.
	Projector string
	// EventsToStdout routes the event stream to the STDOUT writer instead of the
	// event writer (the pre-525u behaviour, for anyone who wants the events where
	// they used to be).
	EventsToStdout bool
	// StdoutEvents puts the compact events on stdout and disables final-text
	// extraction entirely (the pre-525u behaviour of the capture).
	StdoutEvents bool
	// AllAssistantText makes stdout carry EVERY non-empty assistant message the
	// stream completed, in order and blank-line separated (the agent's narration
	// plus its final answer), instead of only the last one. It exists because the
	// "last assistant message" is not always the answer: a harness that injects a
	// trailing notification (a todo reminder, a background-task notice) makes the
	// agent reply once more with a one-liner, and the real report before it was
	// lost (bd h-aii-lvo9). The intermediate texts are short (tens of chars each,
	// a few KB per run), so this stays far from the raw stream it replaces.
	AllAssistantText bool
	// StdoutPath is a dotted JSON path (e.g. "result.result") whose value is the
	// agent's final answer. Set it for an agent whose final text the built-in
	// projectors do not know how to find; it overrides their final-text rules and
	// writes the value as soon as the line carrying it arrives.
	StdoutPath string
	// UsagePath is a dotted JSON path (e.g. "usage", "result.usage") of the usage OBJECT
	// of an agent the built-in projectors do not know (the `ndjson_usage_path` config).
	// The LAST line that carries an object there wins (a running tally's final value),
	// and it is read even from a line the keep whitelist drops. UsageSource labels it.
	UsagePath   string
	UsageSource string
	// Fields overrides the emitted event content per event type (the
	// `ndjson_fields` config): the line carries exactly those dotted paths, in
	// that order. It replaces the built-in shape for that type, and works for a
	// type the projector would otherwise drop.
	Fields map[string][]string
	// MaxEventBytes overrides DefaultMaxEventBytes; <= 0 uses the default.
	MaxEventBytes int
	// OnSession, when non-nil, is called ONCE with the first session id the
	// stream carries, the moment it is read — not at Close. It is how a caller
	// persists the id while the run is still in flight (a run that never reaches
	// Close, because the process died with its serve, would otherwise carry the id
	// only in memory). Called from Write, i.e. on the goroutine feeding the filter:
	// keep it short and non-blocking. SessionID() still reports the same id.
	OnSession func(id string)
	// Meter, when non-nil, is the job's budget meter (N2 §B GATE-02): every parsed line
	// is offered to it (see meterEvent) before any keep/projection decision.
	Meter *runner.BudgetMeter
}

Options configures a Filter.

type Signals

type Signals struct {
	Turns     int64
	ToolCalls int64
	Model     string
	Known     bool
}

Signals is what a structured agent stream says about the run's shape, for the dashboard's job metrics (gofer-yelm P2): how many agent turns it took, how many tool calls it made, and the model it ran on. Known=false means the stream dialect is not one the counter understands (generic agents) or it carried no evidence — the metrics then record nothing rather than a guessed zero.

func CountCompactSignals

func CountCompactSignals(r io.Reader, projector string) Signals

CountCompactSignals reads a job's COMPACT event stream (the stderr.log this filter wrote) and recovers the same Signals for a job that ended before the live counter existed (`gofer tool stats-backfill`). The compact lines are whatever the keep whitelist let through, so this is best-effort: claude needs its `result` line (the compact `assistant` line lists its tool_use blocks under `tools`), omp its `turn_end` / `tool_execution_start` lines. A dialect it does not know reports Known=false.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL