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 Line
- type Op
- type Options
- type Record
- type SkippedLine
- type SkippedLinesError
- type ToolResult
- 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.
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 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"`
}
ToolResult is the result inlined into the tool_use block that requested it. Its JSON encoding is the stored "result" object.
type ToolResultFile ¶
type ToolResultFile struct {
FilePath string `json:"filePath"`
NumLines int `json:"numLines,omitempty"`
}
ToolResultFile carries file metadata from Read/Edit tool results.