cctranscript

package
v0.269.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 19 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package cctranscript reads Claude Code's session transcript: the JSONL file the CLI appends one record to per message block, under ~/.claude/projects/<cwd-slug>/<session-id>.jsonl.

It is the ONE decoder of that format in muster. Two readers use it:

  • ccd (cmd/ccd), which locates one turn by its promptId and returns the reply a provisioned claude-code agent gave, plus — now — the tool calls the CLI ran during it, so the agent's chat shows them as collapsed rows;
  • muster-mirror (internal/mirrorhost), which tails a mirrored tmux pane's transcript and streams it as Events to muster's rendered view.

🔴 THINKING IS NEVER AN EVENT. A thinking block is the model's private reasoning; rendering it beside the reply presents it as if it were the answer. Every reader here drops it, and the tests pin that.

The record shapes relied on, all observed in real transcripts (CLI 2.1.289 / 2.1.296; cmd/ccd/testdata holds real records with their content replaced):

  • a human prompt: {"type":"user","promptId":P,"message":{"content":"<text>"}}
  • tool results in that turn: {"type":"user","promptId":P,"message":{"content": [{"type":"tool_result","tool_use_id":T,"content":<string|blocks>,"is_error":B}]}}
  • assistant output, ONE block per record: {"type":"assistant","message": {"content":[<thinking | text | tool_use{id,name,input}>]}}
  • an API failure: an assistant record with "isApiErrorMessage":true (a usage limit, "Not logged in", an API error: limit.go)
  • the end of a turn: {"type":"system","subtype":"turn_duration"}
  • injected context (skill bodies, caveats): a user record with "isMeta":true
  • a harness notice (a background task finishing, a local command's output): a user record with a prompt's shape whose text is wholly <tag>…</tag> blocks, or whose "origin" is {"kind":"task-notification"} (notice.go). A slash command has the first shape but is the human's.
  • a subagent's records: "isSidechain":true

Index

Constants

View Source
const (
	KindPrompt     = "prompt"
	KindText       = "text"
	KindToolCall   = "tool_call"
	KindToolResult = "tool_result"
	// KindError is an API failure the CLI recorded in place of a reply (rate
	// limit, auth failure); Text is the CLI's own message.
	KindError = "error"
	// KindNotice is a user record the harness wrote, not the human (a
	// background task finishing, a local command's output):
	// notice.go. Notice names its source, Status a task's status, Text its
	// one-line summary and Output the detail shown when the row is expanded.
	KindNotice = "notice"
	// KindInjected marks a record the CLI wrote to inject context into the next
	// request — an attachment record (a message typed while a tool ran,
	// diagnostics, an edited file, a skill listing, a hook's added context…).
	// Text is the attachment's type; it draws nothing. It exists so the
	// tool-context ledger (toolctx.go) knows the growth before the next turn
	// may not be the tool calls' alone — unless its type is one of the small
	// reminders negligibleInjected names. Only ReadLines (the mirrored view's
	// reader) emits it; Events, which every other reader uses, does not.
	KindInjected = "injected"
)

The Event kinds: what the rendered view draws. There is no "thinking" kind, by design (see the package doc).

View Source
const (
	// MaxText bounds a prompt, a reply segment or an error message.
	MaxText = 32 << 10
	// MaxInput bounds a tool call's input JSON (shown when the row is expanded).
	MaxInput = 2 << 10
	// MaxCwd bounds a prompt's working directory (Event.Cwd): a longer one is
	// dropped, never cut — a cut path names another directory.
	MaxCwd = 512
	// MaxOutput bounds a tool result's output (shown when the row is expanded).
	MaxOutput = 4 << 10
)

The size caps. An Event never carries a field past these, so a batch of events is bounded by its count, whatever the transcript holds: a 30 MiB tool result costs MaxOutput bytes on the wire, not 30 MiB.

View Source
const (
	NoticeTask          = "task"
	NoticeCommandOutput = "command-output"
	// NoticeOpenCode: a message opencode wrote into the session that the
	// person did not type (a synthetic or system message, a shell job, a
	// compaction, …), named in Text (internal/opencodehost's Render).
	NoticeOpenCode = "opencode"
)

The notice sources: Event.Notice.

View Source
const (
	QueueEnqueue = "enqueue"
	QueueDequeue = "dequeue"
	QueueRemove  = "remove"
	QueuePopAll  = "popAll"
)

The queue-operation operations (QueueOp.Op).

View Source
const (
	CostMeasured = "measured"
	CostSplit    = "split"
	CostEstimate = "estimate"
)

The ToolCost kinds.

View Source
const (
	WhyNoUsage     = "no-usage"
	WhyInterrupted = "interrupted"
	WhyShrank      = "shrank"
)

Why an estimate is one.

View Source
const MaxPromptRefText = 240

MaxPromptRefText bounds a PromptRef's Text, in bytes.

View Source
const MaxQueue = 64

MaxQueue bounds the messages a Queue holds; past it the oldest are dropped. The CLI's queue is a handful at most; this only bounds a transcript that never says what became of its enqueues.

View Source
const MaxTarget = 80

MaxTarget bounds a tool row's one-line summary, in runes.

View Source
const NativeToolItem = "native_tool_call"

NativeToolItem is the Responses-stream output item type ccd uses to carry a tool call the CLI RAN ITSELF (Bash, Read, Edit…) to muster, which draws it as a collapsed row (internal/agents.handleResponsesEvent).

🔴 muster DISPATCHES every function_call in a COMPLETED response as one of ITS tools and feeds the output back; a call the CLI already ran must never be run again. Two things keep it from that, and the first is the one that holds: ccd streams these items as output_item.done events and NEVER puts them in response.completed's output, which is the only place muster reads calls to dispatch from (mutation-checked: adding them there makes muster dispatch them). The distinct type name is the second, so a future reader of the completed output could not mistake one for a call either.

View Source
const ResultBytesPerToken = 2.2

ResultBytesPerToken is the calibrated size-to-tokens rate of a tool result: how many bytes of result text make one token of context.

CALIBRATED, NOT ASSUMED (cmd/muster-toolctx-calibrate; docs/mirroring.md has the method and the numbers). Over clean single-call gaps of a local transcript set — aggregates only — the measured growth minus the issuing turn's output_tokens was never negative, so the turn's output re-enters the context in full and the REST is the result's. Fitted on half the transcripts (split by a hash of the path) as the median of resultBytes / (growth − output) over results of 400 B or more: 2.16 (p25 1.94, p75 2.40, n=27366), used as 2.2. On the held-out half, |estimate − measured| / measured fell from a median of 0.61 (p90 0.78) for the old flat 4 bytes per token over the call and result alone to 0.05 (p90 0.12). The fit is Claude Code's alone: another runtime or model tokenizes differently, unmeasured.

View Source
const SyntheticModel = "<synthetic>"

SyntheticModel is the model Claude Code names on an assistant record it wrote itself rather than received from a model.

Variables

This section is empty.

Functions

func Cap

func Cap(s string, n int) string

Cap shortens s to at most n bytes, on a rune boundary, marking a cut with "…".

func CapInput

func CapInput(raw string) string

CapInput bounds a tool call's input JSON at MaxInput WHILE KEEPING IT JSON where it can: an oversized input (an Edit's old_string, a Write's content) has each string field shortened instead of the document being cut mid-token, so ToolTarget can still read the file path back out of what was stored. Only an input that is still too big after that is cut raw.

func EstimateTokens

func EstimateTokens(output, in, out int64, outputKnown bool) int64

EstimateTokens is a call's estimated context cost. With the issuing turn's output known (outputKnown), it is that output (output: its output_tokens, or this call's share of them when the turn made several calls — a share that may round to 0) plus the result's tokens at ResultBytesPerToken: the split the calibration found. With no output known (a runtime that records no usage, an older host), the call's input and result are sized at the same rate instead — a rate calibrated on Claude Code transcripts only, so for another runtime or model the figure is unvalidated in either direction.

func IsLimitText added in v0.253.0

func IsLimitText(msg string) bool

IsLimitText reports whether msg — the CLI's own text for a failed turn — says an account usage limit was hit (limitText). It is how ccd tells a usage limit from any other 429 (cmd/ccd classifyAPIError): the CLI gives a transient "API Error: Request rate limited" the same error code (rate_limit) as a usage limit, so the code alone cannot tell them apart.

func IsQueueEnvelope added in v0.129.0

func IsQueueEnvelope(s string) bool

IsQueueEnvelope reports whether a queued message is the harness's rather than the person's: text that opens with a markup tag (<task-notification>, <agent-message …>), the shape every harness enqueue measured has. A person's message that happens to open with a tag is left out too — it shows once Claude takes it.

func LimitReset

func LimitReset(text string, at time.Time) (time.Time, bool)

LimitReset is the reset time a usage-limit message written at `at` names, and false when it names none this can place: no reset clause, no zone, a zone this machine does not know, or a clock or date that does not exist.

The message names a wall-clock time in a zone, and sometimes a date with no year. It is read as the FIRST such time after `at` — the record's own timestamp, never the reader's clock, so a transcript read days later still says when that limit reset: a time of day is today's in that zone if it is still ahead of `at`, else tomorrow's; a date is this year's unless that is more than a day before `at`, then next year's.

func NegligibleInjected

func NegligibleInjected(t string) bool

NegligibleInjected reports whether attachment type t leaves a gap clean (negligibleInjected).

func OneLine added in v0.250.0

func OneLine(s string) string

OneLine is oneLine, for a caller that picks its own field (ui.ToolRowTarget, for muster's own tools).

func ToolTarget

func ToolTarget(tool, input string) string

ToolTarget is a tool call's one-line summary — the file a Read reads, the command a Bash runs, the pattern a Grep searches — from its input JSON. It is "" when the input carries no string worth showing (or is not JSON at all).

ONE function for every surface that draws a tool row: the mirrored rendered view (computed on the host, where the full input is), and the agent chat's persisted and live rows (computed from the stored args).

func UnescapePastedContentTag added in v0.250.0

func UnescapePastedContentTag(key string) string

UnescapePastedContentTag removes the backslash the CLI puts after a `<` that could be read as its paste-wrapper tag.

The CLI's rule, read from the pinned CLI's bundle (2.1.296) and measured on its real TUI: in ANY submitted prompt, wrapped or not, a `<` that is not already followed by a backslash, then any run of characters that are not name characters or angle brackets (so `/`, spaces, punctuation), then `pasted_content` in any case, then a non-name character or the end, has `\` inserted after the `<`. Measured: `<pasted_content id="abcd">` → `<\pasted_content id="abcd">`, `</pasted_content>` → `<\/pasted_content>`, `<PASTED_CONTENT>` → `<\PASTED_CONTENT>`, `< pasted_content` → `<\ pasted_content`, `<#/pasted_content` → `<\#/pasted_content`; a `<\pasted_content` already in the prompt is left as it is (2.1.296 in the image, `tengu_virtual_pancake` on, 2026-10-11; not measured with it off).

ccd cannot tell an inserted backslash from one the prompt already had, so it does not try: the backslash is removed on both sides of the comparison, and a real one cancels out.

⚠ ACCEPTED LIMITS. (1) Two prompts that differ ONLY in such a backslash have the same key, so an operator submitting `<\pasted_content` while ccd waits on the same text with `<pasted_content` would bind to ccd's turn. (2) The CLI also escapes look-alike spellings — a fullwidth `<`, which it REPLACES with `<\` (measured: `<pasted_content>` came back `<\pasted_content>`, a not_submitted), look-alike letters, other underscore-like characters. Those are not undone, so ccd's OWN prompt holding one is a not_submitted. The other direction is a wrong match ccd cannot prevent: a kickoff holding `<pasted_content>` and an operator typing the same text with `<` or `‹` are made byte-identical by the CLI (both reported as `<\pasted_content>`), so the operator's submit binds to ccd's turn. (3) The CLI requires the name to END there (`<pasted_contents` is not escaped); this does not check that. It only widens (1) to longer names.

func UnwrapPastedContent added in v0.250.0

func UnwrapPastedContent(reported string) (body string, ok bool)

UnwrapPastedContent returns the body of a prompt that is, whitespace around it aside, exactly ONE block of the CLI's paste wrapper:

\n\n<pasted_content id="1c0d">\n…body…\n</pasted_content id="1c0d">\n

The CLOSING tag repeats the opening tag's id. ok is false for anything else — text before or after the block, differing ids, an empty id, a plain `</pasted_content>` close (the pinned CLI never writes one), or a body holding another unescaped tag (two blocks) — so a prompt that merely CONTAINS the paste is still not ccd's turn. The body is returned as reported, tag escaping and all (cmd/ccd turnKey removes that).

What makes this safe is the anchoring and the id repeated in both tags, not the id's spelling: the pinned CLI writes four lowercase hex digits, and any non-empty run of ASCII letters, digits, `_` and `-` is accepted so that a CLI that lengthens its id does not bring the false not_submitted back.

Measured on the pinned CLI (2.1.296, the real TUI in the image, pasted by ccd, hook payloads captured with CCD_HOOK_LOG, 2026-10-11): with the CLI's `tengu_virtual_pancake` feature flag on, a paste the TUI collapses into a "[Pasted text]" placeholder is reported — in the hook's `prompt` and in the transcript alike — in that wrapper: 960, 3690, 10990 and 12000 characters and a single 900-character line were wrapped; 19 characters on one line and on two lines were not. With the flag off (a CLI with no cached flags) the same seven came back verbatim. The flag is served to the CLI per account, so which one a pod gets is not ccd's to know: both are accepted. A paste's trailing newline is not doubled inside the block (promptKey ignores it).

Types

type Ask

type Ask struct {
	Questions []askq.Question   `json:"questions,omitempty"`
	Answers   map[string]string `json:"answers,omitempty"`
}

Ask is Event.Ask.

type Block

type Block struct {
	Type string `json:"type"`
	// text
	Text string `json:"text"`
	// tool_use
	ID    string          `json:"id"`
	Name  string          `json:"name"`
	Input json.RawMessage `json:"input"`
	// tool_result
	ToolUseID string          `json:"tool_use_id"`
	Content   json.RawMessage `json:"content"`
	IsError   bool            `json:"is_error"`
}

Block is one content block of a record's message.

func (Block) ResultBytes

func (b Block) ResultBytes() int

ResultBytes is a tool_result block's SIZE for the tool-context ledger (Event.Bytes, toolctx.go): its text's bytes, with each image block counted as imageBytes — not as ResultText's 7-byte "image", which would make an image look free and hand its tokens to a sibling call in a split.

func (Block) ResultText

func (b Block) ResultText() string

ResultText is a tool_result block's content as text: the string itself, or the text of its text blocks (an image block contributes "image").

type ErrorEnd

type ErrorEnd struct {
	// Limit: the record reports a usage limit (the text says so).
	Limit bool
	// Code is the record's own error code ("rate_limit",
	// "authentication_failed", "server_error", …), "" when it names none.
	Code string
	// ResetsAt is when the limit resets: the record's quotaLimits.resetsAt
	// when it carries one, else the time its text names (LimitReset). Zero
	// when neither says, and always zero for a record that is not a limit.
	ResetsAt time.Time
}

ErrorEnd is what a synthetic error record says (ErrorEndOf).

type Event

type Event struct {
	Kind string `json:"kind"`
	// Text is a prompt's, a reply segment's or an error's text.
	Text string `json:"text,omitempty"`
	// ToolID links a tool_call to its tool_result.
	ToolID string `json:"toolId,omitempty"`
	// Tool is the tool's name (tool_call only: a result record does not name it).
	Tool string `json:"tool,omitempty"`
	// Target is the call's one-line summary: the file, the command, the pattern.
	Target string `json:"target,omitempty"`
	// Input is the call's input JSON, capped at MaxInput.
	Input string `json:"input,omitempty"`
	// OK is a result's status (is_error false).
	OK bool `json:"ok,omitempty"`
	// Output is a result's text, capped at MaxOutput (and a notice's detail).
	Output string `json:"output,omitempty"`
	// Bytes is the UNCAPPED size of a tool_call's input or a tool_result's
	// text: what a context estimate (toolctx.go) is sized by when there is no
	// usage to measure with. 0 from a host that predates it.
	Bytes int `json:"bytes,omitempty"`
	// Notice is a notice's source (NoticeTask, NoticeCommandOutput); Status a
	// task notice's status as the harness wrote it ("completed", "failed",
	// "killed"…), "" when it gave none.
	Notice string `json:"notice,omitempty"`
	Status string `json:"status,omitempty"`
	// Line names a PROMPT by where it is in its transcript: the byte offset
	// just past its record's line (Line.End). ReadLines sets it — Events, being
	// stateless, cannot — and Prompts names the same prompt by the same number,
	// which is how the message index finds a prompt's bubble. 0 = not known.
	Line int64 `json:"line,omitempty"`
	// Cwd is a PROMPT's working directory, as its record said ("" on every
	// other event, for one over MaxCwd, and from a host that predates it).
	// muster stores the newest with the session's focus, to decide whether
	// the fleet report may describe the session (internal/focus/cwd.go); it
	// is never rendered. Prompts only, so the stream grows by one path per
	// human turn, not per record.
	Cwd string `json:"cwd,omitempty"`

	// PromptAt is a PROMPT's own timestamp (its record's, Unix ms), 0 when the
	// record has none. It is what lets muster tell how recent a message the
	// person typed is (the chief nudge sweep only accepts the owner's last six
	// hours of instructions: internal/api chief_nudge.go).
	//
	// 🔴 NO VERSION BUMP, BACKWARD-COMPATIBLE BOTH WAYS: an older muster ignores
	// the field; an older host never sends it, and muster then has NO timed
	// prompt for that session, which the sweep reads as "no instruction it can
	// verify" (an ask, never a nudge). Set on prompts only, so an events batch
	// grows by one small number per prompt.
	PromptAt int64 `json:"promptAt,omitempty"`
	// Usage is the context an assistant turn used (usage.go), on the FIRST
	// event its record contributes; nil on every other event, and from a host
	// that predates it.
	Usage *Usage `json:"usage,omitempty"`
	// Ask is an AskUserQuestion call's questions (on its tool_call) or its
	// outcome — the questions and the answers given — (on its tool_result,
	// from the record's toolUseResult), each within askq's bounds; nil for any
	// other tool, for a question set past those bounds, and from a host that
	// predates it. Input cannot stand in for it: MaxInput cuts a real question
	// set's input to "…".
	Ask *Ask `json:"ask,omitempty"`

	// THE SUBAGENT SIGNALS (internal/mirrorhost's subagents.go reads them on
	// the host, where Events ran). 🔴 NEVER ON THE WIRE (json:"-"): what a
	// subagent card shows is computed on the host and sent as its own summary,
	// so the events stream is not one byte larger for them.
	//
	// At is the record's own timestamp (Unix ms; 0 when it has none), set on
	// a tool_result and on a task notice: the time a parent signal is compared
	// with the subagent's last row by.
	At int64 `json:"-"`
	// Agent and Async are a tool_result's toolUseResult, when the record
	// carries exactly one result and that result names a subagent (agentId):
	// its id, and whether the result is only the LAUNCH of a background agent
	// (isAsync, or status "async_launched") — which says nothing about the
	// agent having finished.
	Agent string `json:"-"`
	Async bool   `json:"-"`
	// TaskToolID is a task notice's <tool-use-id>: the Agent call whose agent
	// it reports on ("" when it names none).
	TaskToolID string `json:"-"`
}

Event is one thing the rendered view draws, in transcript order.

A tool call and its result are TWO events linked by ToolID, because they are two records written at different times — a call is on screen (status running) for as long as the tool runs, and its result can arrive many records later (Claude Code issues parallel calls before any result).

func Events

func Events(r Record) []Event

Events is what one record contributes to the rendered view, in order. It is STATELESS — a record's events depend on that record alone — which is what lets a reader start at any line boundary (a backfill window, a resume offset) and still produce the same events for every line after it. (A prompt's Line, its place in the file, is therefore set by the reader, never here.)

A user record is a prompt, a harness notice (notice.go) or tool results; a slash command is the human's prompt, as "/name args". An assistant record is its text and tool calls, or one error, and its context use (usage.go) rides on its FIRST event, adding none.

Dropped: thinking blocks, subagent (sidechain) records, injected context (isMeta, compaction summaries), and every record type that is not a message (attachments, hook summaries, mode changes, titles).

func Flatten

func Flatten(lines []Line) []Event

Flatten is lines' events in order.

func ReadEvents

func ReadEvents(r io.ReaderAt, off, size int64, maxBytes int) ([]Event, int64, error)

ReadEvents is ReadLines' events, flattened.

type Line

type Line struct {
	Events []Event `json:"events"`
	End    int64   `json:"end"`
	At     int64   `json:"at,omitempty"`
	// Queue is a queue-operation record's change to Claude Code's input queue
	// (queue.go), on a Line with no Events. 🔴 NEVER ON THE WIRE (json:"-"):
	// muster-mirror folds it into a Queue and sends the queue's list on its
	// own; a reader that wants only what draws drops such lines (Drawn).
	Queue *QueueOp `json:"-"`
}

Line is the events of one complete transcript line, and the offset just past its newline: a resume point that comes AFTER every one of its events. At is the record's own timestamp (Unix ms; 0 when it has none).

func Backfill

func Backfill(r io.ReaderAt, size int64, window, maxEvents int) ([]Line, int64, error)

Backfill is the tail of a transcript a fresh viewer starts with: the lines (with their events) in the LAST window bytes of the file, holding at most maxEvents events (the newest), and the offset to continue from.

🔴 IT NEVER SENDS THE FILE WHOLESALE. A long session's transcript runs to tens of MiB; what a viewer opening it needs is the recent conversation. The window starts at the first line boundary inside it, so the first record read is a whole one. A tool result whose call fell before the window arrives unpaired, and the view draws it as its own row.

func Drawn added in v0.129.0

func Drawn(lines []Line) []Line

Drawn is lines without the ones that carry no events (a queue operation's): what a reader that only draws events keeps.

func ReadLines

func ReadLines(r io.ReaderAt, off, size int64, maxBytes int) ([]Line, int64, error)

ReadLines decodes the complete lines in r between off and size, reading at most maxBytes, and returns those that produced events (in order) and the offset after the last line it consumed. A partial last line is left for the next call (the offset stops in front of it).

A single line longer than maxBytes is SKIPPED — consumed with no events — once its newline exists: no window could hold it, and stalling on it would stop the view for good. (Claude Code writes multi-MiB tool results on one line.)

type OpenAsk added in v0.151.0

type OpenAsk struct {
	ToolUseID string
	Questions []askq.Question
}

OpenAsk is an AskUserQuestion call a transcript shows OPEN (OpenAskOf): its tool_use id and its questions, as the call's Ask carries them.

func OpenAskOf added in v0.151.0

func OpenAskOf(events []Event) *OpenAsk

OpenAskOf is the AskUserQuestion a WAITING session's transcript events (oldest first) show open: the newest tool call after the last prompt that has no result, when that call is an AskUserQuestion carrying its questions (Event.Ask). nil otherwise — no such call, a call with a result (answered or dismissed), or a newest unanswered call of another tool.

Claude Code writes an AskUserQuestion's tool_use when its picker opens and its tool_result once the picker is answered or dismissed (measured on 2.1.289), so while the session waits with its picker on screen this is that call. It is the same call the host's PendingOf summarises (internal/mirrorhost); muster reads it from the transcript it streams (internal/api's open-question scan), so a question outlives a restart.

type Page added in v0.127.0

type Page struct {
	Session string `json:"session"`
	Next    int64  `json:"next"`
	Lines   []Line `json:"lines"`
}

Page is one incremental read of a session's transcript, as ccd serves it on GET /v1/transcript (cmd/ccd/transcript_route.go) and muster-server's officer transcript forwarder reads it (internal/officers/transcript).

  • Session is the CLI session id whose transcript this is. A caller that sent another session's offset was served this one from its start.
  • Next is the offset to read from next: always a line boundary (ReadLines), never past a partial last line.
  • Lines are the complete lines read, each with the events it produced, its end offset and its own time.

type PromptRef

type PromptRef struct {
	// Line is the prompt's Event.Line: the byte offset just past its record.
	Line int64 `json:"line"`
	// Text is the prompt's first non-blank line, capped at MaxPromptRefText.
	Text string `json:"text"`
}

PromptRef is one prompt in a transcript.

func Prompts

func Prompts(r io.ReaderAt, size int64) ([]PromptRef, error)

Prompts is every prompt in r's first size bytes, in order — exactly the records Events draws as a prompt (a slash command included, as "/name args"), each named by the Line ReadLines gives its event.

🔴 IT READS THE WHOLE FILE AND DECODES ALMOST NONE OF IT. Only a line that holds the JSON string "user" and not "tool_result" can be a prompt (a user record's type; inside a JSON string a quote is escaped, so text can spell neither token, and JSON's own spacing cannot split one); the rest is scanned past. Like every reader here, a trailing line with no newline is not consumed.

type Queue added in v0.129.0

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

Queue is Claude Code's input queue as a transcript's records describe it, folded from its Lines in order. The zero value is an empty queue.

🔴 THE CLI'S QUEUE LIVES IN ITS PROCESS'S MEMORY, AND DIES WITH IT. A CLI that exits with a message queued (SIGTERM, a crash) writes nothing that resolves the enqueue — measured, claude 2.1.289: the transcript ends enqueue, last-prompt, cost-state — and `claude --continue` / `--resume` APPEND to the same file under the same session id. So no record ever says the message left. DropBefore is how a reader that knows when the CLI process now writing the file started forgets what an earlier process queued.

func (*Queue) DropBefore added in v0.129.0

func (q *Queue) DropBefore(started int64) bool

DropBefore forgets every message enqueued — and every dequeue written — before started (Unix ms), the start of the CLI process now writing the transcript: an earlier process's queue died with it. It is also a floor: later Observe calls fold in no queue record written before it, so a dead process's unresolved dequeue never takes a later prompt for its message — call it BEFORE folding when the start is known. It reports whether List changed. started 0 (unknown) drops nothing; neither does a record with no time, which cannot be placed.

func (*Queue) List added in v0.129.0

func (q *Queue) List() []string

List is the person's messages waiting in the queue, oldest first: every queued message but the harness's envelopes (IsQueueEnvelope). nil when none.

func (*Queue) Observe added in v0.129.0

func (q *Queue) Observe(lines []Line) bool

Observe folds lines into the queue and reports whether List changed.

type QueueOp added in v0.129.0

type QueueOp struct {
	Op string
	// Content is the message an enqueue, remove or popAll names, capped at
	// MaxText like a prompt's text; "" on a dequeue.
	Content string
}

QueueOp is one queue-operation record (Line.Queue).

type Record

type Record struct {
	Type             string `json:"type"`
	Subtype          string `json:"subtype"`
	PromptID         string `json:"promptId"`
	IsSidechain      bool   `json:"isSidechain"`
	IsMeta           bool   `json:"isMeta"`
	IsCompactSummary bool   `json:"isCompactSummary"`
	IsAPIError       bool   `json:"isApiErrorMessage"`
	Error            string `json:"error"`
	APIErrorStatus   int    `json:"apiErrorStatus"`
	// Timestamp is when the CLI wrote the record (RFC 3339); Time reads it.
	Timestamp string `json:"timestamp"`
	// Cwd is the working directory the CLI was in when it wrote the record.
	// Only a prompt's travels (Event.Cwd).
	Cwd string `json:"cwd"`
	// Origin is who wrote a user record: "human", or "task-notification" for
	// one the harness injected (notice.go). Absent before CLI 2.1.22.
	Origin struct {
		Kind string `json:"kind"`
	} `json:"origin"`
	// ToolUseResult is the CLI's structured result of the record's tool call
	// (a user record carrying a tool_result). Read only for AskUserQuestion,
	// whose result holds the questions and the answers given (askq.Result).
	ToolUseResult json.RawMessage `json:"toolUseResult"`
	// Attachment is an attachment record's kind of injected context
	// (KindInjected, toolctx.go).
	Attachment struct {
		Type string `json:"type"`
	} `json:"attachment"`
	// QuotaLimits is on a usage-limit record the CLI wrote itself (limit.go):
	// when the limit resets, in Unix seconds. Absent on most.
	QuotaLimits *struct {
		ResetsAt int64 `json:"resetsAt"`
	} `json:"quotaLimits"`
	// Operation and QueueContent are a queue-operation record's (queue.go):
	// what happened to Claude Code's input queue, and the message it names
	// ("" on a dequeue, which names none).
	Operation    string          `json:"operation"`
	QueueContent json.RawMessage `json:"content"`

	Message struct {
		// ID is an assistant record's API message id: the CLI writes one
		// record per content block, each carrying the SAME message's usage, so
		// a turn's tokens are summed once per id (cmd/ccd transcript.go).
		ID      string          `json:"id"`
		Content json.RawMessage `json:"content"`
		// Model and Usage are an assistant record's (usage.go): its model id
		// only marks the CLI's own "<synthetic>" records.
		Model string `json:"model"`
		Usage *struct {
			InputTokens              int64 `json:"input_tokens"`
			CacheReadInputTokens     int64 `json:"cache_read_input_tokens"`
			CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"`
			OutputTokens             int64 `json:"output_tokens"`
		} `json:"usage"`
	} `json:"message"`
}

Record is one decoded transcript line, the fields muster reads and no others.

func DecodeLine

func DecodeLine(line []byte) (Record, bool)

DecodeLine decodes one JSONL line. A line that is not a JSON object is not a record (false), which a reader skips: one corrupt line must not end a read.

func (Record) Blocks

func (r Record) Blocks() []Block

Blocks decodes an array content; a string content (a prompt) yields nil.

func (Record) ErrorEndOf

func (r Record) ErrorEndOf() (ErrorEnd, bool)

ErrorEndOf is what r says when it is an assistant record the CLI wrote itself to report a failure, and false for any other record — a real reply, a user record, and a synthetic record with no error flag ("No response requested.").

func (Record) PromptText

func (r Record) PromptText() (string, bool)

PromptText is a prompt-shaped record's text, and whether r is one at all.

⚠ PROMPT-SHAPED, NOT NECESSARILY HUMAN: a record the harness injected (a task notification, a local command's output) has exactly this shape. Events tells the two apart (notice.go) and draws only a human's as a prompt.

A prompt is a main-conversation user record that is not injected context (isMeta, a compaction summary) and carries text rather than tool results: a string content, or an array of text blocks with no tool_result among them (a prompt with a pasted image is written that way).

func (Record) Time

func (r Record) Time() int64

Time is the record's timestamp in Unix milliseconds, 0 when it has none or one that does not parse.

type ToolContext

type ToolContext struct {

	// Negligible decides which attachment types leave a gap clean
	// (KindInjected's Text); nil is NegligibleInjected. The calibration
	// command sets its own, to measure every type.
	Negligible func(attachmentType string) bool
	// contains filtered or unexported fields
}

ToolContext attributes context growth to tool calls, fed every event of a transcript in order (Observe). In memory and bounded: it holds only the calls of the latest turn.

func (*ToolContext) Clone

func (c *ToolContext) Clone() ToolContext

Clone is an independent copy of the ledger: the state a reconnecting socket resumes with (internal/api's ledger checkpoints).

func (*ToolContext) Observe

func (c *ToolContext) Observe(ev Event) []ToolCost

Observe records ev and returns the costs it settled, if any.

type ToolCost

type ToolCost struct {
	ToolID string
	// Tokens is the call's cost: measured, a share of a measured total, or an
	// estimate (Kind).
	Tokens int64
	Kind   string
	// GroupTokens and GroupSize are the measured total a CostSplit share came
	// from and how many calls it covers (0 for the other kinds).
	GroupTokens int64
	GroupSize   int
	// Why is a CostEstimate's reason (WhyNoUsage, WhyInterrupted, WhyShrank).
	// OutputKnown says the issuing turn's output_tokens were known and counted
	// — Output is this call's share of them, which can round to 0 — else the
	// estimate is sizes alone.
	Why         string
	OutputKnown bool
	Output      int64
}

ToolCost is one call's context cost, once it is known.

type Usage

type Usage struct {
	// Tokens is the context used: input + cache read + cache creation.
	Tokens int64 `json:"tokens"`
	// Output is the turn's output_tokens: what it wrote (its text, its tool
	// calls, its thinking), which the tool-context ledger's estimate counts
	// (toolctx.go). 0 from a host that predates it.
	Output int64 `json:"output,omitempty"`
}

Usage is one assistant turn's context use (Event.Usage).

type UsageBucket added in v0.194.0

type UsageBucket struct {
	Session             string    `json:"session"`
	Hour                time.Time `json:"hour"`
	Turns               int64     `json:"turns"`
	APICalls            int64     `json:"api_calls"`
	InputTokens         int64     `json:"input_tokens"`
	OutputTokens        int64     `json:"output_tokens"`
	CacheReadTokens     int64     `json:"cache_read_tokens"`
	CacheCreationTokens int64     `json:"cache_creation_tokens"`
	Model               string    `json:"model,omitempty"`
}

UsageBucket is one session's Claude usage in one UTC hour.

  • Session is the CLI session the transcript belongs to: a subagent's transcript (nested under its parent session's directory) counts on the parent session.
  • Hour is the UTC hour, on the hour.
  • Turns: distinct prompts (promptId) of the main conversation, at the hour each was first seen. A subagent's prompts and injected context (isMeta, compaction summaries) are not turns.
  • APICalls: API calls, each counted ONCE however many block records the CLI wrote for it and however many transcript files hold it (a fork or a resumed session copies them), at the session and hour of its first record in sorted file order — subagent calls included (they are this instance's spend).
  • The tokens are those calls' usage, each call's largest value of each field.
  • Model is the model of the hour's calls (message.model) with the most output tokens among them, a tie going to the smaller model id; empty — and left out of the JSON, so an older reader sees the bytes it always did — when no call names one.

type UsagePage added in v0.194.0

type UsagePage struct {
	Since   time.Time     `json:"since"`
	Buckets []UsageBucket `json:"buckets"`
}

UsagePage is ccd's answer to GET /v1/usage.

  • Since is the window's start as ccd applied it: the caller's `since` truncated DOWN to the UTC hour, and clamped to at most 48 hours ago.
  • Buckets are the window's hours, sorted by Hour then Session. A bucket with no API call and no turn is left out; an empty window is [], never null.

Jump to

Keyboard shortcuts

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