jsonl

package
v0.32.0 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2026 License: MIT Imports: 6 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 jsonl parses claude session JSONL output into structured events, surfacing every line (assistant, user, tool_use, tool_result, system, attachment, or unrecognised) with its verbatim bytes, alongside a deterministic end-of-turn signal on assistant entries.

MUST NOT log file contents at any layer. Claude session JSONL may contain user prompts, file contents, or other operator-supplied material; this package logs only offsets and error messages, never the line bytes.

Discovered by the Phase A spike (#329) and verified across 1151 real pyrycode sessions: the deterministic end-of-turn rule is an assistant entry with message.stop_reason == "end_turn" AND the sum of len(content[i].text) > 0. Empty-content end_turn entries are transitional thinking-block resolutions; they count as assistant entries but do NOT fire the end-of-turn signal.

Index

Constants

This section is empty.

Variables

View Source
var ErrLineTooLarge = errors.New("jsonl: line exceeds maximum size")

ErrLineTooLarge is returned when a single line without a trailing '\n' exceeds maxLineBytes buffered bytes. Mirrors stdlib bufio.ErrTooLong. The stream is structurally broken at this point; the consumer should abort.

Functions

This section is empty.

Types

type Config

type Config struct {
	Logger      *slog.Logger
	StartOffset int64
}

Config configures Reader. Logger is optional (defaults to slog.Default). StartOffset is informational: callers must Seek src to that position before constructing; the Reader uses StartOffset only to make Offset() report absolute file positions for resume.

type Event

type Event struct {
	// StopReason mirrors message.stop_reason verbatim ("end_turn",
	// "tool_use", "max_tokens", "stop_sequence", ""). Empty string when the
	// entry has no stop_reason field — a legitimate state for an assistant
	// entry mid-tool-call. Always "" on non-assistant entries.
	StopReason string

	// TextChars is sum(len(content[i].text)) over every content block on an
	// assistant entry. Content blocks without a "text" field (e.g.
	// "thinking", "tool_use") contribute 0 naturally. Always 0 on
	// non-assistant entries.
	TextChars int

	// EndOfTurn is true iff Kind == "assistant" AND StopReason == "end_turn"
	// AND TextChars > 0. This is the deterministic end-of-turn signal —
	// fire once per Event where this is true. Empty-content end_turn entries
	// (transitional thinking-block resolutions) have EndOfTurn == false even
	// though their StopReason is "end_turn". Always false on non-assistant
	// entries.
	EndOfTurn bool

	// Raw holds the verbatim line bytes the Reader consumed, with the
	// trailing '\n' stripped. A trailing '\r' (CRLF) is preserved. Backed
	// by a freshly-allocated slice, safe to retain past subsequent Next
	// calls. Typed as json.RawMessage so consumers can re-emit without
	// re-encoding.
	Raw json.RawMessage

	// Kind is the line's "type" field, whitelisted to one of "assistant",
	// "user", "tool_use", "tool_result", "system", "attachment", or "" for
	// any other value (including a missing field). Downstream re-emitters
	// can still pass unrecognised kinds through unchanged via Raw.
	Kind string

	// Usage is the per-entry token-usage block, populated only on assistant
	// entries that carry a "usage" object. nil on every other kind and on
	// assistant entries without a usage field.
	Usage *UsageBlock

	// Model mirrors message.model verbatim on an assistant entry — the model
	// that produced this entry's Usage, and therefore the key a consumer joins
	// on to size that usage against a window (#2107). Empty on every
	// non-assistant entry, on an assistant entry with no model field, and on one
	// whose model exceeds maxModelIDBytes (see that constant: over-cap yields no
	// key rather than a cut one).
	//
	// SECURITY: claude-authored, model-influenced text, bounded at
	// maxModelIDBytes and DELIBERATELY NOT SANITIZED — no control-character or
	// terminal-escape stripping happens here or anywhere upstream, so it may
	// carry either. Two obligations ride it, the pair
	// cmd/pyry's sessionModelWindowHold.ModelWindows states for the same text
	// arriving on the other channel. Sanitization is the CONSUMER's, should one
	// ever render it. And AN ID IS NOT AN ARGV TOKEN: this is claude's own
	// string with no allowlist check, no lookup against any published model
	// list and no rejection of a leading dash, so joining one back onto a
	// spawn's arguments as --model <id> would be argument injection into the
	// daemon's own child. It is a comparison key and nothing else; #2107's
	// consumer discharges both obligations by narrowing — it compares the value
	// and reports an integer, so the text reaches no wire surface and no log.
	Model string
}

Event is the parsed shape of a single JSONL line. Every well-formed line the Reader consumes surfaces as an Event; malformed-JSON lines are still logged-and-skipped (see Reader.Next). Most fields apply only to assistant entries — see each field's contract.

type Reader

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

Reader parses claude session JSONL from an io.Reader, surfacing one Event per call to Next for every well-formed line.

Not safe for concurrent use. Construct one Reader per source.

func NewReader

func NewReader(src io.Reader, cfg Config) *Reader

NewReader returns a Reader that consumes src. Does not read from src until the first Next call.

func (*Reader) AssistantCount

func (r *Reader) AssistantCount() int

AssistantCount returns the number of assistant entries consumed so far, including transitional empty-content end_turn entries.

func (*Reader) Next

func (r *Reader) Next() (Event, error)

Next returns the next Event from src, advancing internal state.

Every well-formed line surfaces as an Event — including non-assistant and unrecognised kinds. Only assistant entries populate StopReason, TextChars, EndOfTurn, and (optionally) Usage; non-assistant Events carry only Raw and Kind.

Returns io.EOF when src has signalled io.EOF AND no complete line is pending in the internal buffer. Partial bytes (a line without a trailing '\n') are retained across calls; the next call continues from where the previous left off, optionally after the underlying io.Reader has produced more bytes (the typical fsnotify-driven case).

Returns any non-EOF read error from src wrapped as "jsonl: read at offset %d: %w". Malformed-JSON lines are logged at Warn and skipped — they do NOT terminate iteration, do NOT surface as Events, and do NOT advance the assistant counter.

func (*Reader) Offset

func (r *Reader) Offset() int64

Offset returns the byte position of the next not-yet-consumed line — safe to persist as the resume point. Equals Config.StartOffset before the first Next call. After every successful Next (and after every silently-skipped malformed line), advances past the consumed line's trailing '\n'. Does NOT advance into a partial-line buffer.

type UsageBlock

type UsageBlock struct {
	InputTokens              int
	OutputTokens             int
	CacheCreationInputTokens int
	CacheReadInputTokens     int
}

UsageBlock mirrors the assistant message.usage JSON object. Pointer-valued on Event to distinguish "field absent" from "field present with all zeros".

Jump to

Keyboard shortcuts

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