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
- func Convert(content []byte, opts Options) ([]byte, error)
- func ConvertWithBoundary(content []byte, opts Options) (full []byte, boundary int, err error)
- func Fold(records []Record, opts Options) ([]byte, error)
- func IsInjectedPrompt(text string) bool
- func SliceFromLine(content []byte, startLine int) []byte
- func StripIDEContextTags(text string) string
- type Block
- type Folder
- type JSONLAdapter
- type Line
- type Op
- type Options
- type Record
- type SkippedLine
- type SkippedLinesError
- type ToolResult
- type ToolResultAgent
- type ToolResultFile
Constants ¶
const ( TypeUser = "user" TypeAssistant = "assistant" )
Message type constants for transcript lines.
const ( ContentTypeText = "text" ContentTypeToolUse = "tool_use" )
Content type constants for content blocks within messages.
const ( BlockText = ContentTypeText BlockToolUse = ContentTypeToolUse BlockImage = "image" )
Block types. Other values pass through verbatim; see Block.Raw.
const ( ToolStatusSuccess = "success" ToolStatusError = "error" )
Tool result statuses.
Variables ¶
This section is empty.
Functions ¶
func Convert ¶
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 ¶
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 IsInjectedPrompt ¶
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 ¶
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 ¶
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 ¶
NewFolder returns an empty Folder whose lines carry opts.Agent and opts.CLIVersion; opts.StartLine is ignored.
func (*Folder) Apply ¶
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 ¶
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.
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 ¶
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 ¶
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 ¶
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.