transcript

package
v0.12.1 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: MIT Imports: 10 Imported by: 1 module, 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.

README

transcript

Package github.com/entireio/cli/transcript converts native agent transcripts into the Entire Transcript Format and reads that format into typed Go values.

The library is versioned with CLI releases. Its API and the format may change; consumers should pin a version.

Entire Transcript Format v1

The format has been called the "compact transcript" (CLI code, metadata key compact_transcript) and the "unified transcript" (entire-api). All three names refer to the same thing. Stored names are unchanged: the file is transcript.jsonl, the metadata key is compact_transcript, and the line field is cli_version.

One JSON object per line, each line terminated by \n.

Field Type Required Notes
v int yes Always 1.
type string yes user or assistant.
agent string no The CLI agent registry name (claude-code, codex, copilot-cli, cursor, factoryai-droid, opencode, pi, antigravity); otherwise the agent type string, e.g. for external agents. An open set.
cli_version string no Version of the producer that wrote the line. The name is historical.
ts string no RFC 3339 timestamp. May be omitted or empty (codex, gemini and copilot write ""). The generic JSONL converter copies the source timestamp verbatim, so a non-string value can occur; readers ignore it.
id string no Assistant message ID. Streaming fragments with the same ID are merged into one line.
input_tokens, output_tokens int no Assistant lines only.
content array of blocks, string, or null yes Normally an array. A string can appear when an assistant message's source content was a string. null can appear because the writer does not omit empty content.
Blocks
  • User text: {"id"?: string, "text": string}. There is no type field (a v1 quirk).
  • Assistant text: {"type": "text", "text": string}.
  • Tool use: {"type": "tool_use", "id"?: string, "name": string, "input": any, "result"?: {"output": string, "status": "success"|"error", "file"?: {"filePath": string, "numLines"?: int}, "matchCount"?: int, "agent"?: {"id": string}}}. Tool results are inlined into the tool_use block that requested them, matched by tool call ID where the agent records one, including the results of parallel calls that the agent writes separately. agent.id is the agent's own ID for the subagent session or thread the call launched (never the tool call ID, which is the block's id), when the parent transcript records one: Claude Code's toolUseResult.agentId (Agent, and forked Skill calls), Codex's SubAgentActivity thread for a spawn_agent call, OpenCode's task session (state.metadata.sessionId), and Copilot's subagent.started agent for a task call.
  • Image: passed through from the source verbatim. The image source is either inline base64 or an entire-asset:assets/… placeholder left by image externalization.
  • Any other block type is passed through verbatim. Thinking blocks are dropped by the converters.
Evolution rules
  1. Readers ignore unknown fields, keep unknown block types (available through Block.Raw), and return lines with an unknown type as they are, so consumers can skip them.
  2. New fields, block types and line types are additive and optional. v stays 1.
  3. v is bumped only for a breaking change.

Reading

Decode returns every line it could read. If it skipped any, it also returns a *SkippedLinesError listing each skipped line's 1-based physical line number and the reason. Blank lines are ignored (but still counted in line numbers).

A line is skipped when it:

  • is not a JSON object (including malformed JSON),
  • has no v, or a v other than 1,
  • has no type, or
  • has a known field of the wrong JSON type, for example "agent": 42 or "input_tokens": "x" (reason invalid field: <name>). A ts that is not a string is ignored rather than skipped.

Decode normalizes three v1 quirks:

  • A block that has text but no type gets Type "text", on any line type.
  • A content value that is a JSON string becomes a single text block.
  • A content value that is null, absent, or any other non-array, non-string JSON value becomes no blocks. The line is still returned.

Every block carries Raw, the block exactly as stored (for string content, the synthesized text block). A block that is not a JSON object, or whose known fields have the wrong JSON type, is returned with only Raw set; it never causes its line to be skipped.

lines, err := transcript.Decode(b)
// strict:   if err != nil { return err }
// tolerant: log err and use lines

var skipped *transcript.SkippedLinesError
if errors.As(err, &skipped) {
	for _, s := range skipped.Skipped {
		log.Printf("line %d: %s", s.Line, s.Reason)
	}
}

Parse accepts any supported format. Input whose first non-blank line is a JSON object with an integer v and a non-empty string type is decoded as is and the options are ignored. Anything else is converted first.

lines, err := transcript.Parse(native, transcript.Options{Agent: "claude-code", CLIVersion: "0.5.1"})

To get one checkpoint's portion of a session, convert with the boundary and slice the decoded lines:

full, boundary, err := transcript.ConvertWithBoundary(native, transcript.Options{
	Agent: "claude-code", CLIVersion: "0.5.1", StartLine: checkpointStart,
})
if err != nil {
	return err
}
lines, err := transcript.Decode(full)
// ...
checkpointLines := lines[boundary:]

There is no general-purpose writer for the format; the converters and the fold produce it.

Records and fold

A Record is one append-only change to a transcript. Records are never revised once emitted, so they can be streamed and stored as plain appends. Fold applies records in order and returns the transcript lines.

In this repository the fold is used by Convert: for Claude Code, Cursor and Droid, it runs a JSONLAdapter that turns the native transcript into records and then folds them. The other converters still write lines directly. The fold is meant to be shared with a backend that folds the same records to show a live session, so that a live view and a checkpoint's transcript.jsonl match byte for byte.

A live producer uses the same adapter (NewClaudeAdapter, NewCursorAdapter, NewDroidAdapter). Feed accepts the transcript in chunks split anywhere and returns the records for the lines it completed; Flush consumes a trailing partial line and is called only once the transcript is final. Fold keys are stable only when the adapter is fed from the transcript's first line, so a producer that restarts replays from line 1. Lines reports how many source lines have been consumed. Records carry the transcript's bytes as fed: redact before feeding.

Record wire format v1

One JSON object per record. An omitted field and a zero-length one mean the same: in Go, a nil or empty json.RawMessage is absent. This is about the field, not its JSON value: content of [] or null is present, and the visibility rules below treat it differently from absent content.

Field Type Ops Notes
op string all message, append, result, usage or drop.
id string all The fold key: unique and stable within a session. Required.
sourceId string message The agent's own message ID, printed as the line's id. Differs from id when the agent reuses an ID for a later, separate message.
role string message user or assistant; becomes the line's type. Required on message.
ts any JSON message, append Copied to the line's ts verbatim. An append without ts clears the timestamp.
content any JSON message, append Normally an array of blocks. message replaces the content; append adds the blocks of an array and ignores anything else. Appending to content that is not an array discards that content, since it has no blocks.
toolUseId string result The tool_use block to target, searching from the end. Empty targets the last tool_use block.
result object result The tool result object described under Blocks. Required on result.
inputTokens, outputTokens int message, append, usage A non-zero value replaces the previous one; agents report cumulative usage.

What each op does to the message id names:

  • message creates it, or restates it: role, source ID, timestamp and content are replaced, token counts are updated, and a dropped message is restored. A message keeps the position where it was first created.
  • append concatenates content blocks and replaces the timestamp. Appending to non-array content (a string, null, or none) replaces it with the appended blocks, possibly none: the result is always an array.
  • result sets the result of one tool_use block. Nothing changes when the content is not an array, when one of its blocks is not an object, or when no block matches.
  • usage updates token counts.
  • drop hides the message.

Every op except message must target a message created earlier, in this batch or a previous one.

Compatibility: new optional fields may be added, and readers ignore fields they do not know. A new op is a breaking change: Apply rejects a batch containing an op it does not know.

Incremental folding

A Folder folds incrementally. Apply validates a whole batch before changing anything and returns the IDs of the messages it touched. Line(id) returns one message's current line, or not visible when the message is dropped or is an assistant message whose content is [] or null. An assistant message with no content at all is visible and prints "content":null, as Convert always has. A live view re-renders the touched messages and removes those that are no longer visible:

f := transcript.NewFolder(transcript.Options{Agent: "claude-code", CLIVersion: "0.5.1"})
touched, err := f.Apply(records)
if err != nil {
	return err
}
for _, id := range touched {
	if line, ok := f.Line(id); ok {
		render(id, line)
	} else {
		remove(id)
	}
}

Decode each streamed record into a zero Record. encoding/json leaves fields the input omits unchanged, so a reused variable would carry an earlier ts into an append that has none.

Resource use

A Folder keeps every message in memory and has no limits of its own. Applying a record costs time in the record's size, with one exception: the first append or result after a message record splits that record's content into blocks, once. Until an append or a matching result takes the split blocks over as the content, they are kept beside the original bytes, so such a message briefly costs twice its size. Producing a line costs time in that message's size, and Lines in the size of all messages. A caller folding records from an untrusted source must bound the number and size of records and messages itself.

Documentation

Overview

Package transcript converts native agent transcripts into the Entire Transcript Format (also called compact or unified transcripts), decodes that format into typed lines (Decode, Parse), and folds transcript records into it (Fold, Folder). The format is specified in README.md. This API is versioned with the CLI and may change; consumers should pin a version.

Index

Constants

View Source
const (
	TypeUser      = "user"
	TypeAssistant = "assistant"
)

Message type constants for transcript lines.

View Source
const (
	ContentTypeText    = "text"
	ContentTypeToolUse = "tool_use"
)

Content type constants for content blocks within messages.

View Source
const (
	BlockText    = ContentTypeText
	BlockToolUse = ContentTypeToolUse
	BlockImage   = "image"
)

Block types. Other values pass through verbatim; see Block.Raw.

View Source
const (
	ToolStatusSuccess = "success"
	ToolStatusError   = "error"
)

Tool result statuses.

Variables

This section is empty.

Functions

func Convert

func Convert(content []byte, opts Options) ([]byte, error)

Convert converts a full.jsonl transcript into the condensed transcript.jsonl format. The output format puts version, agent, and cli_version on every line, merges streaming assistant fragments with the same message ID, and inlines tool results into the preceding assistant's tool_use blocks:

{"v":1,"agent":"claude-code","cli_version":"0.42.0","type":"user","ts":"...","content":"..."}
{"v":1,"agent":"claude-code","cli_version":"0.42.0","type":"assistant","ts":"...","id":"msg_xxx","content":[{"type":"text","text":"..."},{"type":"tool_use","id":"...","name":"...","input":{...},"result":{"output":"...","status":"..."}}]}

func ConvertWithBoundary

func ConvertWithBoundary(content []byte, opts Options) (full []byte, boundary int, err error)

ConvertWithBoundary compacts the entire transcript — ignoring opts.StartLine for the purpose of truncation — and returns the full compact bytes together with the boundary: the line index in the compact output at which this checkpoint's data (the content from opts.StartLine onward in the raw transcript) begins.

Storing the full compact transcript on every checkpoint makes each checkpoint self-contained: the session is reconstructable from any single surviving checkpoint, and downstream readers segment this checkpoint's slice as fullCompactLines[boundary:]. boundary is 0 when StartLine <= 0 (the first checkpoint of a session, whose data starts at the beginning).

boundary is derived as lineCount(full) - lineCount(delta), where delta is the existing per-checkpoint sliced compaction (Convert with the original StartLine). This reuses each format's existing, independently-tested slicing behavior — line offsets for JSONL/Copilot/Droid/pi, message-index for OpenCode/Gemini, response-item index for Codex — rather than threading source indices through every emitter.

A single compact line can carry content from both sides of StartLine when its source straddles the boundary — most notably same-ID streaming assistant fragments, which compaction merges into one line. No integer line offset can split within a line, so the boundary rounds toward inclusion: such a merged line is counted as part of this checkpoint's slice. fullCompactLines[boundary:] therefore never drops this checkpoint's content, but its first line may repeat up to one merged line that began in the previous checkpoint. Downstream segmenters must tolerate this bounded head overlap. See the straddle case in TestFullWithBoundary_StraddlingAssistantFragments_RoundsToInclusion.

Likewise, a tool result can arrive after StartLine for a call made before it, even after a later prompt. The full conversion inlines it into that earlier line, which is before the boundary; the delta, which lacks the call, drops it.

func Fold

func Fold(records []Record, opts Options) ([]byte, error)

Fold applies records to an empty Folder and returns its lines.

func IsInjectedPrompt

func IsInjectedPrompt(text string) bool

IsInjectedPrompt reports whether text is agent-injected rather than user-authored. It is the single source of truth for that question: callers that pick a session title, count user turns, or compact a transcript all use it so the classification cannot drift between them.

func SliceFromLine

func SliceFromLine(content []byte, startLine int) []byte

SliceFromLine returns the content starting from line number `startLine` (0-indexed). This is used to extract only the checkpoint-specific portion of a cumulative transcript. For example, if startLine is 2, lines 0 and 1 are skipped and the result starts at line 2. Returns empty slice if startLine exceeds the number of lines.

func StripIDEContextTags

func StripIDEContextTags(text string) string

StripIDEContextTags removes IDE-injected context tags from prompt text. The VSCode extension injects tags like:

  • <ide_opened_file>...</ide_opened_file> - currently open file
  • <ide_selection>...</ide_selection> - selected code in editor

Also removes system-injected tags like:

  • <local-command-caveat>...</local-command-caveat>
  • <system-reminder>...</system-reminder>
  • <command-name>...</command-name>

Cursor's <user_query> wrapper is unwrapped (content kept) and its prepended <timestamp> line is removed (content included, leading position only).

These shouldn't appear in commit messages or session descriptions. Not idempotent: the unwrap can expose user content at the start of the message, so callers must apply it exactly once per text.

Types

type Block

type Block struct {
	Type   string // BlockText, BlockToolUse, BlockImage, or a passthrough type
	ID     string
	Text   string
	Name   string
	Input  json.RawMessage
	Result *ToolResult
	Raw    json.RawMessage // the block exactly as stored
}

Block is one content block of a Line.

type Folder

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

Folder applies records incrementally. Messages keep the order in which their IDs were first created. The zero value is not usable; call NewFolder.

A Folder keeps every message in memory and has no limits of its own. Applying a record costs time in the record's size, except that the first append or result after a message record splits that record's content into blocks, once. Until an append or a matching result decodes the message, the split blocks are kept beside the raw content. Producing a line costs time in that message's size, and Lines in the size of all messages. Callers folding records from an untrusted source must bound the number and size of records and messages.

func NewFolder

func NewFolder(opts Options) *Folder

NewFolder returns an empty Folder whose lines carry opts.Agent and opts.CLIVersion; opts.StartLine is ignored.

func (*Folder) Apply

func (f *Folder) Apply(records []Record) ([]string, error)

Apply applies records in order and returns the IDs of the messages they touched, each once, in order of first touch. Apply validates every record before changing anything, so on error the Folder is unchanged.

func (*Folder) Line

func (f *Folder) Line(id string) (line []byte, visible bool)

Line returns the compact line (without a trailing newline) for message id. visible is false when the message is unknown, dropped, or an assistant message whose content is [] or null; such a message has no line in Lines. An assistant message with no content at all is visible and prints "content":null, as Convert always has.

func (*Folder) Lines

func (f *Folder) Lines() []byte

Lines returns the compact transcript: one newline-terminated line per visible message, in creation order.

type JSONLAdapter added in v0.12.1

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

JSONLAdapter turns a Claude Code, Cursor or Droid JSONL transcript into transcript records. It is incremental: Feed accepts the transcript in chunks split anywhere, and the records depend only on the bytes fed, not on how they were chunked. Folding the records reproduces what compaction produced before it was split into adapter and fold.

The compaction rules live here, as decisions about which message a record targets:

  • Consecutive assistant entries with the same message ID are fragments of one message: the first opens it, the rest append to it.
  • A tool result in a user entry becomes a result record on the assistant message holding the tool_use with its tool_use_id, wherever the result falls. Claude Code writes the results of parallel tool calls one user entry each, sometimes after the next assistant message began or after text it injected (isMeta). A result without a tool_use_id targets the last assistant message, until a user entry with text or images (whose own results still count). Other results are dropped, as is a user entry that held only such results.
  • The text and images of a user entry become a separate user message.

Fold keys are the agent's message ID where it has one and it is unused, otherwise derived from the source line number (1-based, counting every line fed, including blank and dropped ones). A message ID the agent reuses for a later, non-adjacent message gets "<id>@L<line>" as its key and keeps the agent's ID as SourceID; messages without an ID, including all user messages, get "@L<line>" and no SourceID. Keys are stable only for a transcript fed from its first line, so a stream that resumes must replay from line 1 rather than start a fresh adapter mid-file.

Folding every record from Feed and a final Flush reproduces Convert's output for the same bytes (with Options.StartLine 0). Records carry no redaction: redact the transcript before feeding it, as checkpoints do.

func NewClaudeAdapter added in v0.12.1

func NewClaudeAdapter() *JSONLAdapter

NewClaudeAdapter returns an adapter for a Claude Code JSONL transcript.

func NewCursorAdapter added in v0.12.1

func NewCursorAdapter() *JSONLAdapter

NewCursorAdapter returns an adapter for a Cursor JSONL transcript, which shares Claude Code's line format.

func NewDroidAdapter added in v0.12.1

func NewDroidAdapter() *JSONLAdapter

NewDroidAdapter returns an adapter for a Factory AI Droid JSONL transcript, unwrapping each line's envelope first.

func (*JSONLAdapter) Feed added in v0.12.1

func (a *JSONLAdapter) Feed(chunk []byte) []Record

Feed consumes the next chunk of the transcript and returns the records implied by every line it completed. A trailing partial line is held until a later chunk completes it, or until Flush.

func (*JSONLAdapter) Flush added in v0.12.1

func (a *JSONLAdapter) Flush() []Record

Flush treats a held partial line as complete. Call it only once the transcript is final; while an agent is still writing, a partial line is usually an unfinished write.

func (*JSONLAdapter) Lines added in v0.12.1

func (a *JSONLAdapter) Lines() int

Lines returns the number of source lines consumed so far: every newline-terminated line fed, including blank and dropped ones, plus a partial line once Flush has consumed it. A held partial line is not counted. Line-derived keys ("@L<n>") use the same numbering.

type Line

type Line struct {
	Version      int
	Type         string // TypeUser, TypeAssistant, or a future additive type
	Agent        string
	CLIVersion   string
	Timestamp    string
	ID           string
	InputTokens  int
	OutputTokens int
	Blocks       []Block
}

Line is one decoded line of the Entire Transcript Format.

func Decode

func Decode(b []byte) ([]Line, error)

Decode reads Entire Transcript Format bytes into typed lines.

Like go/parser.ParseFile, Decode returns a usable partial result together with the error: every readable line is returned, and if any line was skipped the error is a *SkippedLinesError listing each one. Callers choose their policy:

lines, err := transcript.Decode(b)
// strict:   if err != nil { return err }
// tolerant: log err; use lines

A line is skipped when it is not a JSON object, has no "v", has a "v" other than 1, has no "type", or has a known field of the wrong JSON type ("ts" is the exception: a non-string "ts" is ignored). Blank lines are ignored. Unknown fields are ignored, and lines with an unknown "type" are returned as they are.

func Parse

func Parse(raw []byte, o Options) ([]Line, error)

Parse decodes a transcript in any supported format into typed lines.

Input that is already in the Entire Transcript Format is passed to Decode and o is ignored; a caller holding a checkpoint boundary from ConvertWithBoundary slices the result with lines[boundary:]. Any other input is converted with Convert and the result decoded. A Convert error is returned as is.

type Op

type Op string

Op names what a record does to its target message.

const (
	// OpMessage creates a message, or replaces the role, timestamp, source ID
	// and content of a known one and restores it if it was dropped.
	OpMessage Op = "message"
	// OpAppend appends content blocks to a message. The record's timestamp
	// replaces the message's, so an append without one clears it. Content
	// that is not an array adds no blocks, and appending to a message whose
	// content is not an array discards that content.
	OpAppend Op = "append"
	// OpResult sets the result of a tool_use block in a message. Nothing
	// changes when the content is not an array, when one of its blocks is not
	// an object, or when no tool_use block matches.
	OpResult Op = "result"
	// OpUsage sets a message's token counts.
	OpUsage Op = "usage"
	// OpDrop hides a message.
	OpDrop Op = "drop"
)

type Options

type Options struct {
	Agent      string // e.g. "claude-code"
	CLIVersion string // e.g. "0.42.0"
	StartLine  int    // checkpoint_transcript_start (0 = no truncation)
}

Options provides metadata fields written to every output line.

type Record

type Record struct {
	Op       Op     `json:"op"`
	ID       string `json:"id"`
	SourceID string `json:"sourceId,omitempty"`
	Role     string `json:"role,omitempty"`

	// TS is the agent's timestamp, passed through verbatim.
	TS json.RawMessage `json:"ts,omitempty"`
	// Content is a JSON array of compact content blocks. Adapters may pass a
	// non-array value through on OpMessage when the agent wrote one.
	Content json.RawMessage `json:"content,omitempty"`

	// ToolUseID selects the tool_use block an OpResult targets. Empty selects
	// the last tool_use block in the message.
	ToolUseID string      `json:"toolUseId,omitempty"`
	Result    *ToolResult `json:"result,omitempty"`

	// Token counts. A non-zero value replaces the message's previous value.
	InputTokens  int `json:"inputTokens,omitempty"`
	OutputTokens int `json:"outputTokens,omitempty"`
}

Record is one transcript record. Which fields apply depends on Op; Role is TypeUser or TypeAssistant.

ID is the fold key. It is unique within a session and stable: the same transcript yields the same IDs on every run. SourceID is the agent's own ID for the message and is what the compact line prints as "id"; it is empty when the agent has none. The two differ when the adapter had to derive a key, for example when the agent reuses a message ID for a second, non-adjacent message that compaction keeps separate.

Zero-length TS and Content mean absent, as they do once the record is encoded. JSON null or [] content is present.

When decoding a stream, decode each record into a zero Record: a field the next record omits keeps its old value otherwise, so an append without "ts" would inherit the previous record's timestamp instead of clearing it.

type SkippedLine

type SkippedLine struct {
	Line   int // 1-based physical line number
	Reason string
}

SkippedLine describes one line Decode could not read.

type SkippedLinesError

type SkippedLinesError struct {
	Skipped []SkippedLine
}

SkippedLinesError reports the lines Decode skipped.

func (*SkippedLinesError) Error

func (e *SkippedLinesError) Error() string

type ToolResult

type ToolResult struct {
	Output     string          `json:"output"`
	Status     string          `json:"status"` // ToolStatusSuccess or ToolStatusError
	File       *ToolResultFile `json:"file,omitempty"`
	MatchCount int             `json:"matchCount,omitempty"`
	// Agent identifies the subagent this tool call launched, when the agent
	// records one in the parent transcript.
	Agent *ToolResultAgent `json:"agent,omitempty"`
}

ToolResult is the result inlined into the tool_use block that requested it. Its JSON encoding is the stored "result" object.

func (*ToolResult) UnmarshalJSON added in v0.12.1

func (r *ToolResult) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes a tool result. An "agent" that is not an object with a non-empty string "id" decodes as absent rather than failing the result, so a malformed one neither drops the block around it nor folds into an empty agent.

type ToolResultAgent added in v0.12.1

type ToolResultAgent struct {
	// ID is the agent's own ID for the child session or thread, never the
	// tool call ID (that is the tool_use block's id).
	ID string `json:"id"`
}

ToolResultAgent identifies a subagent launched by a tool call.

type ToolResultFile

type ToolResultFile struct {
	FilePath string `json:"filePath"`
	NumLines int    `json:"numLines,omitempty"`
}

ToolResultFile carries file metadata from Read/Edit tool results.

Directories

Path Synopsis
Package pijsonl provides shared parsing primitives for Pi's session JSONL format.
Package pijsonl provides shared parsing primitives for Pi's session JSONL format.

Jump to

Keyboard shortcuts

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