transcript

package
v0.13.4 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 14 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 Source timestamp where available, normally RFC 3339. May be omitted or empty when the native transcript has no timestamp. The generic JSONL converter copies source timestamps 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. The Codex item path writes the item ID on user lines too.
model string no Assistant lines only. The model the source reports for this call, verbatim; omitted when it reports none. Never inferred from a session-wide default, and never a placeholder: a value the agent writes in place of a model (Claude Code's <synthetic> on API-error entries) is omitted.
input_tokens int no Assistant lines only. Input not counted in the line's cache_read_tokens or cache_write_tokens; see below.
output_tokens int no Assistant lines only; includes reasoning tokens when the source reports them as part of output.
cache_read_tokens, cache_write_tokens int no Assistant lines only; per-call cached input read and total cached input written. Cache counts are separate from fresh input_tokens.
cache_write_5m_tokens, cache_write_1h_tokens int no Assistant lines only; an optional breakdown of cache_write_tokens, emitted only when the source reports the split (even when a reported value is zero). Absence means unknown, not zero or all 5m. Do not add the split to the total when summing usage.
reasoning_tokens int no Assistant lines only; subset of output_tokens when reported by the source, not additional output.
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.

Usage and model fields are per call, never copied from a session aggregate. A zero omitted by JSON encoding does not assert that the source reported zero.

On every line, input_tokens excludes the tokens in that line's cache_read_tokens and cache_write_tokens, so adding them never double counts. The sum is the call's total input only on lines from a converter that writes the cache fields. Lines written before that carry no cache fields, and their input_tokens is one of two things:

  • Fresh input only (Claude Code, and Pi except as below): the cached input is missing from the line, so the sum understates the call's input.
  • Fresh plus cached input (Codex, and Pi on Google models before pi-ai subtracted cached tokens in March 2026): the total is right, but its cache share is unknown, so pricing it at the fresh-input rate overstates the cost.

Other agents' lines copy the native input count as the agent defines it. Only agent and the cli_version that wrote a line tell these cases apart; no field marks a line as old or new, and model in particular says nothing about how input_tokens was counted.

Converters fill only what the native transcript reports per call. Claude Code, Codex and Pi record per-call usage and model, and their converters write them (below). Copilot CLI has only a shutdown aggregate, Cursor is hook-only, and external plugins and Antigravity report usage out of band, so their lines do not get these fields. Native timestamps are preserved where present; a missing one stays empty rather than fabricated.

Per-call usage

An assistant line can carry usage with empty content ("content":[] or "content":null, for example an aborted or thinking-only call): readers that render transcripts should skip it, and readers that count usage must keep it.

Claude Code (Options.Agent claude-code, and NewClaudeAdapter; Cursor and Droid keep legacy counts): streaming fragments of one message ID become one line carrying the whole usage row with the strictly highest output_tokens (earlier wins ties) and the model of the first fragment that reports one, skipping Claude Code's <synthetic> placeholder; ts is the last fragment's. The 5m/1h cache-write split is emitted only when both durations are reported. A message with no usage object on any fragment has no model or usage fields. User entries holding only tool results between fragments of one ID do not split the call: the later fragments become separate lines without usage, and the best row stays on the call's first line (the first with visible content, since a thinking-only message has no line), so a call's usage is counted once. Read per-call usage from the full converted transcript: in a checkpoint slice (ConvertWithBoundary), a usage row that arrives after a tool result goes to the call's first line, which can sit before the slice boundary.

Codex, response_item path (rollouts from Codex versions that do not record items): one assistant line per model call, made of the reasoning, message and tool-call items up to the token_count that closes it (real order: call, output, token_count; outputs attach to their call by call_id). Usage is the difference between consecutive cumulative info.total_token_usage snapshots, and ts is the closing snapshot's when present, otherwise the last item's. Fresh input is input - cached clamped at zero; Codex lines carry no cache-write fields. Repeated snapshots and snapshots missing the input, cached-input or output counter are ignored, reasoning_tokens needs both adjacent snapshots to report it, and a decrease in any counter stops usage on later lines. A call with usage but no text or tool calls (for example reasoning-only) emits content: [], so consumers may see empty assistant lines; a call with neither usage nor content is omitted. Without usable total_token_usage snapshots (flat per-event totals are not read), no token_count closes a call, so consecutive assistant items merge into one line until the next user line or tool output; with usable snapshots, a tool output does not end its call. After a counter decrease, total snapshots still close calls but carry no usage, starting with the call the decrease closes. With StartLine, the last line before the boundary is part of the slice when its tool output or closing snapshot arrives after it (a one-line head overlap, which can repeat that call's usage); a later output for any earlier call lands only on that call's earlier line.

Codex, item path (current rollouts; see Blocks): one line per item, not per call. A call is the items up to the token_count that closes it, and its usage is computed exactly as on the response_item path: the same snapshot differences, fresh input, cached reads and reasoning, the model from turn_context, repeated snapshots ignored, and a counter decrease stopping usage. The usage goes on the call's last assistant line, so the call's earlier lines carry none. A call with usage but no assistant line (reasoning only) gets a usage-only line with "content":null and no id, whose ts is the closing snapshot's; other lines keep their item's ts. A user message ends the open call. With StartLine, the skipped lines seed the usage baseline, and the last line before the boundary is part of the slice when its call's closing snapshot arrives after it (a one-line head overlap).

Pi, one native message per call (no fragments to merge): model is message.model, and Pi's input is used as input_tokens unchanged, since the backends that report cached tokens already exclude them from it (a backend that folds cache reads into input cannot be told apart per call). cache_write_1h_tokens is Pi's cacheWrite1h and cache_write_5m_tokens the rest of cacheWrite (clamped at 0 if 1h exceeds it), only when Pi reports cacheWrite1h. reasoning_tokens is Pi's reasoning when reported. An assistant message with no visible content but non-zero usage (thinking-only, aborted) gets a line with "content":null ("content":[] before Pi went through the fold), so per-line usage sums to the session totals; one with zero usage gets none. Abandoned branches are excluded. Read per-call usage from the full converted transcript. Pi user image items pass through verbatim in Pi's native shape (data, mimeType) and in source order, so an image-only user message still has a line; data is the inline base64, or an entire-asset:assets/… placeholder when image externalization (redaction.externalize_images) moved the image to the checkpoint's assets.

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", "exitCode"?: int, "declined"?: bool, "cwd"?: string, "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. exitCode is the exit code of the command the call ran, when the agent records one: 0 is a recorded success, and absence means unknown, never success. declined is true for a call the user declined, which never ran; its status is error, as it was before the field existed, so a reader that only checks status counts it as failed. cwd is the working directory of the call as the agent records it. Only the Codex item path writes these three: a command's exit code and own cwd, and for a file change (whose paths are absolute) the cwd of its turn, from the rollout's latest turn_context. Older lines and other agents' lines have none of them.
  • 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.

Codex: rollouts from Codex versions that record items (the first turn has a user message item_completed event) convert item by item: each item_completed item becomes its own line or lines. Commands are Bash tool uses whose input is the script inside <shell> -lc or <shell> -c (other commands are shown whole), with the command's output, exit code and working directory; file changes are FileChange with each file's diff, and their turn's working directory on the result; a command or file change the user declined has an error result marked declined; MCP calls are named server.tool; web searches are WebSearch and image views ImageView; a sub-agent spawn is spawn_agent, an interrupt interrupt_agent and any other interaction (a message or a follow-up task, which the item doesn't tell apart) interact_agent, each with the sub-agent's agent.id. Code-mode wrapper calls no longer appear. Lines carry their item's time (RFC 3339 UTC with milliseconds), and usage is per model call (see Per-call usage). Items it can't read (such as one without an ID) or doesn't map (reasoning, plans such as update_plan, compaction and other items) are skipped and add no line. Older rollouts keep the response_item path, and so do rollouts whose first turn has its prompt only as a response_item (a guardian sub-session, whose agent message is an item) and thread_spawn sub-agent rollouts (no items in the first turn, the task prompt as a response_item). CodexNotificationRecords maps a Codex app-server item/started or item/completed notification to records with the same mapping, so a live stream of a Codex session shows a completed item exactly as it is stored. Its CodexLive argument carries what the stream knows beyond the item: the agent text and command output so far, whether the turn ended while the item was running (shown failed), a fallback time, and the turn's working directory (TurnCWD, shown on a file change's result as the stored line shows its turn_context cwd). Usage is not part of it: a stream attaches each call's usage itself, as an OpUsage record.

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. Old v1 lines without the new usage and model fields remain valid.
  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.

For optional scalar fields, JSON null is treated like absence, not a wrong type: strings (including model) become empty, token totals (including the historical input_tokens and output_tokens) become zero, and cache-write splits remain unknown (nil). These values do not cause a line to be 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, for Pi a PiAdapter, and for OpenCode the records OpenCodeAdapter sends for each message. 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, NewPiAdapter; OpenCode's differs, see below). 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.

The Pi adapter keys each message by its Pi entry ID and sends it whole as a message record, with its tool results spliced in; it sends the message again when a result it shows changes, and drops it when it leaves the active branch (a message record restores it in place if the branch comes back). A line that only grows the active branch is read without walking the tree, so a session that only grows reads in linear time. Like the JSONL adapters, it has no line size limit: a long line is held until its newline arrives and read whole. Convert still fails on a Pi line of 10 MiB or more (newline excluded), as it always has, so the fold matches Convert wherever Convert succeeds.

OpenCode

OpenCode keeps a session in its database and rewrites a message's rows in place as the message grows, so there is no append-only transcript to feed. A live producer exports the session again once it changes (opencode export <id> on 1.x, opencode session export --standalone <id> on 2.x) and feeds OpenCodeAdapter (NewOpenCodeAdapter) snapshot lines: one message per line, {"info":{...},"parts":[...]} in the OpenCode 1 shape, as OpenCodeSnapshotLines splits an export of either version (a 2.x export is converted by the internal opencodev2 package). FeedExport does both: it feeds every message of an export in order, then drops the messages sent before that the export no longer has (a revert or a compaction), in the order they were first sent. A producer feeding lines itself calls Drop(messageID) for those.

A pending revert (OpenCode's undo sets the session's info.revert; the next prompt deletes the reverted messages, redo clears it) hides what OpenCode hides: OpenCodeSnapshotLines leaves out the reverted message and every later one, or, for a revert of one of its parts, that message's parts from it on. So an undo drops them from the stream at once and a redo restores them. Convert still writes them, as the database holds them until the next prompt.

Each message is keyed by its info.id (also the assistant line's id) and sent whole as a message record. It is sent again only when its record changed: a repeated snapshot, or a change that does not show (a step-finish part, a completion time), sends nothing, and a changed one replaces the message under the same key. A dropped message's next snapshot restores it where it was first created. Its tokens are a usage snapshot (input_tokens and output_tokens, as Convert writes them), replaced whole with the message. An assistant message with no text or tool parts is sent with content [], which the fold hides but which keeps its place; once it has tokens it is sent with no content, a "content":null line carrying its usage. A tool still pending or running has no result yet.

Folding every record from a sequence of snapshots equals Convert of the export made of each message's latest snapshot, dropped messages left out, when messages are first fed in session order (a message keeps the position at which it was first fed) and message IDs are present and unique, as OpenCode writes them. Lines that are not such a message, or whose role is neither user nor assistant, are consumed and ignored; Lines counts them.

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.
usage object message, append, usage Optional per-call snapshot (model, inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens, cacheWrite5mTokens, cacheWrite1hTokens, reasoningTokens). When present it replaces the message's whole snapshot, and the line's usage fields come from it instead of inputTokens/outputTokens.
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 and any usage snapshot 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 and, when it carries usage, the per-call snapshot.
  • 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/Codex, message-index for OpenCode/Gemini) 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 IsInstructionFileDump added in v0.13.3

func IsInstructionFileDump(text string) bool

IsInstructionFileDump reports whether text is an agent's dump of its instruction files (AGENTS.md), the one kind of injected content that carries text from outside the conversation. Callers that must not store that text blank exactly what this matches.

func OpenCodeSnapshotLines added in v0.13.2

func OpenCodeSnapshotLines(export []byte) ([][]byte, error)

OpenCodeSnapshotLines splits an OpenCode export, either version, into the snapshot lines OpenCodeAdapter reads: the messages of the normalized export (opencodev2.Normalize), in order, each compacted onto one line with no trailing newline. Feed them each followed by "\n".

A pending revert (the session's info.revert, set by OpenCode's undo) hides the messages from its message on, as OpenCode shows the session: the reverted message and every later one, or, when the revert names a part of that message, its parts from that one on. OpenCode deletes them with the next prompt, or brings them back with redo; Convert keeps them, as the database still holds them, so for such an export the fold of these lines is Convert of the export without 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 CallUsage added in v0.12.2

type CallUsage struct {
	Model              string `json:"model,omitempty"`
	InputTokens        int64  `json:"inputTokens,omitempty"`
	OutputTokens       int64  `json:"outputTokens,omitempty"`
	CacheReadTokens    int64  `json:"cacheReadTokens,omitempty"`
	CacheWriteTokens   int64  `json:"cacheWriteTokens,omitempty"`
	CacheWrite5mTokens *int64 `json:"cacheWrite5mTokens,omitempty"`
	CacheWrite1hTokens *int64 `json:"cacheWrite1hTokens,omitempty"`
	ReasoningTokens    int64  `json:"reasoningTokens,omitempty"`
}

CallUsage is an authoritative per-call usage snapshot for an assistant message. InputTokens excludes cache reads and writes, and ReasoningTokens is a subset of OutputTokens. A nil cache-write split means unreported; a pointer to zero means reported as zero.

type CodexLive added in v0.13.0

type CodexLive struct {
	Text        *string // agent text so far (from deltas); nil: the item's own text
	Output      *string // command output so far; nil: the item's own output
	Interrupted bool    // the item's turn ended while it was in progress: show it failed
	TS          string  // fallback time (RFC 3339), used when the item has none
	TurnCWD     string  // the turn's working directory, shown on a file change's result; empty: none
}

CodexLive is what a live stream knows about an item beyond the item itself.

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. Convert uses the same constructors, so folding the records reproduces Convert's output for that agent.

The constructor fixes the behavior. NewClaudeAdapter also emits per-call usage snapshots (model, fresh input, cache and output tokens) by the rules below; NewCursorAdapter and NewDroidAdapter keep the legacy per-message input and output token counts. NewDroidAdapter unwraps Droid's envelope before parsing each line.

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.
  • For Claude Code, the fragment with the strictly highest output tokens supplies the message's usage snapshot (an earlier one wins ties) and the first fragment naming a model supplies its model. User entries holding only tool results between fragments of one message ID do not split the API call: later fragments become continuation messages that carry no usage, and any improved snapshot goes to the call's first visible message in a usage record. A message whose content is empty has no line, so the next fragment takes over the call's usage instead of continuing it.

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 and the Options.Agent that selects this constructor ("claude-code" for NewClaudeAdapter). 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
	Model              string
	InputTokens        int64 // excludes CacheReadTokens and CacheWriteTokens
	OutputTokens       int64
	CacheReadTokens    int64
	CacheWriteTokens   int64
	CacheWrite5mTokens *int64 // nil means the split is unknown
	CacheWrite1hTokens *int64 // nil means the split is unknown
	ReasoningTokens    int64
	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 or per-call usage snapshot.
	OpUsage Op = "usage"
	// OpDrop hides a message.
	OpDrop Op = "drop"
)

type OpenCodeAdapter added in v0.13.2

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

OpenCodeAdapter turns snapshots of an OpenCode session's messages into transcript records as the session changes. OpenCode keeps a session in its database and rewrites a message's rows in place while the message grows, so there is no append-only transcript to follow: a live producer exports the session again whenever it changes and feeds every message's latest snapshot.

A snapshot line is one message as OpenCodeSnapshotLines writes it: the message of a normalized export (opencodev2.Normalize, so OpenCode 1 shape for either version), {"info":{...},"parts":[...]}, on one line. Each message is keyed by its info.id, which is also its SourceID on assistant lines, and sent whole (OpMessage). Feeding a message again sends it again only when its record changed (text grew, a tool's state moved on, its tokens were counted), and the new record replaces the old one in the fold; an unchanged snapshot sends nothing. Drop hides a message the session no longer has (a revert, or a compaction OpenCode applied), and feeding it again restores it where it was first created.

Folding every record from a sequence of snapshots reproduces Convert of the export made of each message's latest snapshot (with Options.StartLine 0), dropped messages left out, provided messages are first fed in the session's order: a message keeps the position at which it was first fed, so a message first fed after a later one stays after it. Feeding every export whole (FeedExport) satisfies that. An assistant message with no text or tool parts is still sent, with content [], which the fold does not show; this keeps its position for when its content arrives.

Lines that are not a JSON object with a non-empty info.id, and messages whose role is neither user nor assistant, are consumed and ignored. Lines have no size limit: a long line is held whole until its newline arrives. Records carry no redaction: redact the snapshots before feeding them.

func NewOpenCodeAdapter added in v0.13.2

func NewOpenCodeAdapter() *OpenCodeAdapter

NewOpenCodeAdapter returns an adapter for one OpenCode session's snapshots.

func (*OpenCodeAdapter) Drop added in v0.13.2

func (a *OpenCodeAdapter) Drop(id string) []Record

Drop hides message id: it returns an OpDrop when the message was sent and not dropped since, and nothing otherwise. The next snapshot of the message sends it again, restored at its first position.

func (*OpenCodeAdapter) Feed added in v0.13.2

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

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

func (*OpenCodeAdapter) FeedExport added in v0.13.2

func (a *OpenCodeAdapter) FeedExport(export []byte) ([]Record, error)

FeedExport reads a whole export of the session, either version: it feeds every message's snapshot in order, then drops every message sent before that the export no longer has, in the order they were first sent. Do not call it while a partial line from Feed is held. An export that cannot be read returns an error and changes nothing.

func (*OpenCodeAdapter) Flush added in v0.13.2

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

Flush treats a held partial line as complete.

func (*OpenCodeAdapter) Lines added in v0.13.2

func (a *OpenCodeAdapter) Lines() int

Lines returns the number of snapshot lines consumed so far: every newline-terminated line fed, including blank and ignored ones, plus a partial line once Flush has consumed it, plus every message FeedExport read. A held partial line is not counted.

type Options

type Options struct {
	// Agent is written to every line, e.g. "claude-code". Claude Code and
	// Cursor share a JSONL line format, so for that format Agent also selects
	// the accounting: "claude-code" emits per-call usage (model, fresh input,
	// cache and output tokens), and any other value converts as Cursor, with
	// legacy per-message input and output counts.
	Agent      string
	CLIVersion string // e.g. "0.42.0"
	StartLine  int    // checkpoint_transcript_start (0 = no truncation)
}

Options provides metadata fields written to every output line, and picks the conversion where the transcript's format alone does not.

type PiAdapter added in v0.13.0

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

PiAdapter turns a Pi session transcript into transcript records as it is written. Feed accepts the transcript in chunks split anywhere, and the records depend only on the bytes fed, not on how they were chunked. Convert uses the same adapter, so after any complete line, folding every record so far reproduces Convert of the bytes so far (with Options.StartLine 0), wherever Convert succeeds: it still fails on a line of 10 MiB or more, which the adapter reads whole.

Pi sessions are trees: every entry has an id and a parentId, and /tree and branching continue from an earlier entry. The conversation is the active branch, the path from the last message entry to the root (pijsonl.ResolveActiveBranch). While no entry has a non-empty parentId there is no tree, and every message is active.

Each message is keyed by its entry ID, which is also its SourceID, and sent whole (OpMessage) with the results of its tool calls spliced in: per tool call ID, the last toolResult entry on the active branch. It is sent again when a result it shows changes (one arrives, or a branch switch leaves it behind), and dropped (OpDrop) when it leaves the active branch. An OpMessage on a dropped key restores it where it was first created, so returning to an earlier branch needs no new keys. An assistant message with no visible content but non-zero usage is sent with no content, which the fold keeps and prints as "content":null, so its usage has a line.

A line that only grows the active branch (the usual case: a message whose parent is the tip, perhaps through entries that are not messages) is read without going over the whole tree, so reading a long session that only grew takes linear time. Any other line reconciles the whole tree, as does every line while there is no tree yet, which Pi (session version 3) has only for its first line or two.

Lines have no size limit: a long line is held whole until its newline arrives, as JSONLAdapter holds one.

Entry IDs are unique in transcripts Pi writes. A repeated ID is re-read as the entry it names, which keeps its first position. Records carry no redaction: redact the transcript before feeding it.

func NewPiAdapter added in v0.13.0

func NewPiAdapter() *PiAdapter

NewPiAdapter returns an adapter for one Pi transcript, to be fed from its first line.

func (*PiAdapter) Feed added in v0.13.0

func (a *PiAdapter) 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 (*PiAdapter) Flush added in v0.13.0

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

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

func (*PiAdapter) Lines added in v0.13.0

func (a *PiAdapter) Lines() int

Lines returns the number of source lines consumed so far: every newline-terminated line fed, including blank and invalid ones, plus a partial line once Flush has consumed it. A held partial line is not counted.

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"`

	// Usage, when non-nil, replaces the message's whole per-call usage
	// snapshot, zeros included. An assistant message with a snapshot ignores
	// the token counts above.
	Usage *CallUsage `json:"usage,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.

func CodexNotificationRecords added in v0.13.0

func CodexNotificationRecords(method string, params []byte, live CodexLive) (recs []Record, ok bool)

CodexNotificationRecords maps one Codex app-server item notification (method item/started or item/completed, its params) to records, with the same mapping as Convert's Codex item path. ok is false for anything else, including an item it can't read or one without an ID. An item that isn't shown (reasoning, …) is ok with no records.

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
	// ExitCode is the exit code of the command the call ran, when the agent
	// records one. nil means unknown, never success.
	ExitCode *int `json:"exitCode,omitempty"`
	// Declined reports that the user declined the call, so it never ran.
	// Its Status is ToolStatusError, as before the field existed.
	Declined bool `json:"declined,omitempty"`
	// CWD is the working directory of the call, as the agent records it:
	// for a Codex command its own, for a Codex file change the turn's.
	CWD        string          `json:"cwd,omitempty"`
	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.

Jump to

Keyboard shortcuts

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