streamjson

package
v0.21.0 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 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 streamjson re-emits the parsed claude session-JSONL entry stream onto a writer (typically pyry's stdout) and composes a single `type:"result"` trailer line when the run terminates. Output shape mirrors `claude -p --output-format stream-json` so the dispatcher's stream-json parser keeps working unchanged after the agent-run migration.

MUST NOT log entry content. The package logs only counts, durations, and error messages — never JSONLEntry.RawLine bytes nor per-entry usage values.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// Writer is where stream-json lines are written. Required; production
	// passes os.Stdout.
	Writer io.Writer

	// SessionID is the UUIDv4 the caller minted and passed to claude via
	// --session-id. Stamped into the leading init envelope's `session_id`
	// field and the trailer's `session_id` field. Required.
	SessionID string

	// Cwd is claude's working directory. Stamped into the leading init
	// envelope's `cwd` field. Required (non-empty).
	Cwd string

	// Tools is the human-readable tool allowlist stamped into the leading
	// init envelope's `tools` field. Required (non-nil); an empty slice is
	// accepted and marshals as `[]`. Runtime enforcement is performed by
	// the deny-default settings file ptyrunner writes; this list is the
	// wire-shape mirror of those names.
	Tools []string

	// Model is the model identifier stamped into the leading init
	// envelope's `model` field. Required (non-empty).
	Model string

	// Now is a clock seam; defaults to time.Now. New captures Now() at
	// construction; Close calls Now() again to compute duration_ms.
	Now func() time.Time

	// Logger is optional and defaults to slog.Default().
	Logger *slog.Logger
}

Config configures Emitter.

type Emitter

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

Emitter re-emits tuidriver.JSONLEntry values to its Writer and composes a single `type:"result"` trailer line on Close. Safe for concurrent use across Emit, SetExitReason, and Close.

func New

func New(cfg Config) (*Emitter, error)

New constructs an Emitter and writes the leading `{"type":"system","subtype":"init",...}` envelope to cfg.Writer before returning. Returns an error if Writer is nil, SessionID is empty, Cwd is empty, Tools is nil, or Model is empty. On init-write failure the returned *Emitter is nil and the error wraps the underlying writer error.

func (*Emitter) Close

func (e *Emitter) Close() error

Close writes the final `type:"result"` trailer line. MUST be called exactly once after Emit calls have stopped; calling Close while Emit is still firing is a race.

Default exit-reason classification when SetExitReason was not called:

  • end-of-turn was observed during Emit → ExitReasonCompletion
  • end-of-turn was NOT observed → ExitReasonError

Idempotent: second and subsequent calls return the first call's error verbatim without re-writing the trailer.

func (*Emitter) Emit

func (e *Emitter) Emit(entry tuidriver.JSONLEntry) error

Emit re-emits entry.RawLine verbatim followed by '\n', aggregates the per-entry usage counters, and counts logical assistant turns (consecutive assistant entries grouped by message.id). Safe for concurrent use.

Byte passthrough uses entry.RawLine (the verbatim source-line bytes captured by the tail goroutine). Re-marshalling from entry.Raw would normalise key order and whitespace, breaking the byte-equivalence contract the dispatcher relies on.

Once an underlying write fails, the error is sticky: subsequent Emit calls no-op (returning nil) so the watcher can keep parsing until end-of-turn or ctx cancel without thrashing on a broken pipe. Close still attempts to write the trailer (best-effort).

Emit after Close is a no-op returning nil — late entries from a slow watcher goroutine must not panic.

func (*Emitter) ExitReason added in v0.14.0

func (e *Emitter) ExitReason() ExitReason

ExitReason reports the run's terminal classification. Before Close it returns whatever SetExitReason recorded (possibly ""); Close resolves and persists the final reason (defaulting to ExitReasonError when no end-of-turn was seen), so after Close this returns that resolved value. The ptyrunner flight-recorder reads it to tag a recording by the run's REAL outcome — Run returns a nil error even on a watchdog-fired wedge, so the Go return alone cannot distinguish a wedge from a clean finish.

func (*Emitter) SetExitReason

func (e *Emitter) SetExitReason(r ExitReason)

SetExitReason overrides the default exit-reason classification used by Close. Pluggable seam for the future budget integration (#334), which calls SetExitReason(ExitReasonMaxTurns) from its Terminate hook before SIGTERMing claude.

Idempotent: only the first non-empty value sticks; later calls are no-ops. Safe for concurrent use.

func (*Emitter) SetTerminalDetail added in v0.16.0

func (e *Emitter) SetTerminalDetail(d string)

SetTerminalDetail records a precise, free-form termination cause used to fill the otherwise-empty `terminal_reason` of the error trailer — turning the empty `Agent error ()` into `Agent error (parent_canceled)` and friends. The ptyrunner sets it from the run's cancel path (watchdog arm, external context cancel, stream close). It is ONLY surfaced when the resolved reason is ExitReasonError (the default no-end-of-turn wedge); a completion or a max_turns stop keeps its own terminal_reason and ignores the detail.

Idempotent: only the first non-empty value sticks; later calls (and empty) are no-ops, so a watchdog fire recorded mid-run beats the runner's fall-through classification recorded after the event loop. Safe for concurrent use.

type ExitReason

type ExitReason string

ExitReason classifies how the run terminated. The internal value is translated into wire fields (`subtype` / `terminal_reason` / `is_error`) at trailer-composition time; see closeLocked.

const (
	// ExitReasonCompletion signals a clean, deterministic end-of-turn
	// observation from the watcher.
	ExitReasonCompletion ExitReason = "completion"

	// ExitReasonMaxTurns signals the budget Counter forcibly stopped the
	// run. Set via SetExitReason from #334's future Terminate hook.
	ExitReasonMaxTurns ExitReason = "max_turns"

	// ExitReasonError signals an unrecoverable failure — claude exited
	// non-zero, the watcher failed, or the run was torn down before
	// end-of-turn fired.
	ExitReasonError ExitReason = "error"
)

Jump to

Keyboard shortcuts

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