Harness Notes

Transcript format

Updated 2026-11-22,

On this page

The complete on-disk format of each harness’s session transcripts: every file a session writes, every record type and field, and how to rebuild the conversation from them. Where sessions live and how to resume, export or delete them is on the Transcripts page. Examples use placeholder values.

At a glance

Questionpi1.5.2
SpecificationPublished, versioned specification
Transcript file~/.pi/agent/sessions/--<cwd>--/<ISO timestamp with : and . replaced by ->_<session-id>.jsonl
StorageJSON Lines, one entry per line, appended as the session runs and uncompressed. The file is rewritten only when an older format version is migrated or a branch is extracted.
Record type fieldtype, then message.role for message entries.
Size18 record types, 4 content blocks

Records by purpose

Recordspi1.5.2
Session
Session header
Title
Model, directory and settings
Conversation
User message
Assistant message
System and injected context
Reasoning
Images, files and attachments
Tools
Tool call
Tool result
Context and accounting
Compaction
Summaries
Token usage
Other records

pi 1.5.2

Published, versioned specification. JSON Lines, one entry per line, appended as the session runs and uncompressed. The file is rewritten only when an older format version is migrated or a branch is extracted.

Files

~/.pi/agent/Agent directory (PI_CODING_AGENT_DIR overrides). Also holds settings.json, auth.json, models.json, prompts/, tools/, mcp.json, pi-debug.log — none session-scoped.
~/.pi/agent/sessions/--<cwd with leading separator removed and / \ : replaced by ->--/One directory per working directory. A custom --session-dir / PI_CODING_AGENT_SESSION_DIR / sessionDir setting is flat and filtered by header cwd.
~/.pi/agent/sessions/--<cwd>--/<ISO timestamp with : and . replaced by ->_<session-id>.jsonlThe entire session: header line plus append-only tree of entries, including all branches. Not created until the first user/assistant message (since 0.99.0; first assistant before).
<os.tmpdir()>/pi-bash-<16 hex>.logFull output of a truncated bash tool call or ! command, referenced by details.fullOutputPath / bashExecution.fullOutputPath. Temporary; not under the session dir and may be gone.

Fields on every record

Record type is chosen by type, then message.role for message entries..

FieldTypeMeaning
typestringEntry type.
idstring8 lowercase hex chars (first 8 of a random UUID, collision-checked); falls back to a full UUID. Absent on the session header (which uses the session id).
parentIdstring|nullParent entry id; null for a root. Absent on the header.
timestampstring (ISO 8601)Entry write time. Distinct from message.timestamp (Unix ms).

Records (18)

session

First line of every file: format version, session id, start time and working directory; not part of the entry tree.

Written built in memory by newSession()/createBranchedSession()/forkFrom(); written to disk together with all buffered entries when the first user or assistant message entry is appended (forkFrom writes it immediately).

FieldTypeMeaning
type"session"Discriminator.
versionoptionalnumberFormat version; absent means 1. Current is 3.
idstringSession id. UUIDv7 by default (since 0.67.1; UUIDv4 before); may be a caller-supplied id matching ^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$ via --session-id/SDK.
timestampstring (ISO 8601)Creation time; also used (with : and . replaced by -) as the file-name prefix.
cwdstringAbsolute working directory. Readers tolerate it missing/non-string on very old files (treated as empty).
parentSessionoptionalstringAbsolute path of the source session file for /fork, /clone, forkFrom() or newSession({parentSession}).
{"type":"session","version":3,"id":"01890a5d-ac96-774b-bcce-b302099a8057","timestamp":"2026-01-01T10:00:00.000Z","cwd":"/workspace/project"}

message

Wrapper entry holding one AgentMessage; the role-specific payloads are listed below as message / <role>.

Written on every agent message_end for roles system, user, assistant, toolResult and custom (custom is re-routed to custom_message); bashExecution messages are appended after a ! command (deferred until agent_end if a turn is streaming).

FieldTypeMeaning
type"message"Discriminator.
idstringEntry id (8 hex chars).
parentIdstring|nullParent entry id.
timestampstring (ISO 8601)Append time.
messageAgentMessageDiscriminated by message.role.
{"type":"message","id":"a1b2c3d4","parentId":"f0e1d2c3","timestamp":"2026-01-01T10:00:01.000Z","message":{"role":"user","content":"Hello","timestamp":1767261601000}}

message / systemsince 0.86.0

System prompt and tool loadout declaration (first request) or a delta that patches named prompt sections and adds/removes tools.

Written first model request of a session persists a leading system message with every section and full tool declarations; later prompt/tool changes persist delta system messages. Sessions from before 0.86.0 have none; the first request after upgrade declares the current prompt as a later system message.

Stored only since 0.86.0

FieldTypeMeaning
message.role"system"—
message.contentstring | TextContent[]Base prompt on the leading message; extra instructions on later ones (often empty string).
message.sectionsoptionalRecord<string, string|null>Named, ordered prompt sections; later messages replace by name, null removes.
message.toolsAddedoptionalTool[] ({name, description, parameters (JSON Schema), constrainedSampling?})Complete tool definitions becoming available.
message.toolsRemovedoptional{name}[]Tools that stop being available.
message.timestampnumber (ms)—
{"type":"message","id":"0a1b2c3d","parentId":null,"timestamp":"2026-01-01T10:00:00.500Z","message":{"role":"system","content":"","sections":{"preamble":"You are a coding assistant.","cwd":"/project"},"toolsAdded":[{"name":"read","description":"Read a file","parameters":{"type":"object","properties":{}}}],"timestamp":1767261600500}}

Replay every system message on the active path in order to reconstruct the current prompt and tools; there is no separate prompt-state entry.

Inside a compacted context, system messages in the kept range are dropped in favour of compaction.systemMessage.

message / user

A user prompt (typed, queued steering/follow-up, or SDK-sent).

Written message_end of the user message at the start of each prompt.

FieldTypeMeaning
message.role"user"—
message.contentstring | (TextContent|ImageContent)[]Plain string or blocks; images are inline base64.
message.timestampnumber (ms)—
{"type":"message","id":"a1b2c3d4","parentId":"0a1b2c3d","timestamp":"2026-01-01T10:00:01.000Z","message":{"role":"user","content":[{"type":"text","text":"Hello"}],"timestamp":1767261601000}}

message / assistant

One completed model response: text, thinking and tool calls plus model identity, usage and stop reason.

Written message_end of each model response (one per LLM call; a tool-using turn yields several). Streaming partials (stopReason pending) are never persisted; errored and aborted responses are.

FieldTypeMeaning
message.role"assistant"—
message.content(TextContent|ThinkingContent|ToolCall)[]—
message.apistringWire API, e.g. anthropic-messages, openai-responses, openai-completions, openai-codex-responses, azure-openai-responses, mistral-conversations, bedrock-converse-stream, google-generative-ai, google-vertex, pi-messages, or custom.
message.providerstringProvider id.
message.modelstringRequested (physical) model id.
message.responseModeloptionalstringConcrete model reported by the provider; may equal the requested model.
message.responseIdoptionalstringProvider response id.
message.providerThinkingLeveloptionalstringProvider-native effort actually used.
message.thinkingLeveloptionalenum(off,minimal,low,medium,high,xhigh,max)Pi thinking level requested.
message.diagnosticsoptional{type,timestamp,error?{name?,message,stack?,code?},details?}[]Redacted provider/runtime diagnostics, e.g. provider_transport_failure, bedrock_response_failure, pi_messages_response_failure.since 0.73.0
message.usageUsageUsage object: input, output, cacheRead, cacheWrite, cacheWrite1h?, reasoning?, totalTokens, cost{input,output,cacheRead,cacheWrite,total}
message.stopReasonenum(stop,length,toolUse,error,aborted,deferred)pending exists in the type but is not persisted.
message.deferredoptionalDeferredHandle {provider,modelId,api,id,expiresAt?,pollAfterMs?,data?}Handle to retrieve a deferred response.since 0.84.0
message.errorMessageoptionalstringError text when stopReason is error/aborted.
message.rawStopReasonoptionalstringProvider-native stop reason.
message.endTurnoptionalbooleanProvider explicit end-of-turn signal (Codex).since 0.84.2
message.timestampnumber (ms)Request start time.
message.durationMsoptionalnumberMonotonic duration of the response.since 1.1.0
{"type":"message","id":"b2c3d4e5","parentId":"a1b2c3d4","timestamp":"2026-01-01T10:00:03.000Z","message":{"role":"assistant","content":[{"type":"text","text":"Hi!"}],"api":"anthropic-messages","provider":"anthropic","model":"example-model","usage":{"input":10,"output":3,"cacheRead":0,"cacheWrite":0,"totalTokens":13,"cost":{"input":0.00003,"output":0.00004,"cacheRead":0,"cacheWrite":0,"total":0.00007}},"stopReason":"stop","timestamp":1767261602000,"durationMs":900}}

message / toolResult

Result of one tool call, linked to the call by toolCallId.

Written after a tool finishes; for parallel batches all results are appended after the batch completes, in the assistant's tool-call order.

FieldTypeMeaning
message.role"toolResult"—
message.toolCallIdstringToolCall.id of the originating block.
message.toolNamestring—
message.content(TextContent|ImageContent)[]What the model sees.
message.detailsoptionalJSONTool-specific UI/metadata, not sent to model. Built-ins: bash {truncation?, fullOutputPath?}; read {truncation?}; edit {diff, patch, firstChangedLine?}; ls {truncation?, entryLimitReached?}; find {truncation?, resultLimitReached?}; grep {truncation?, matchLimitReached?, linesTruncated?}.
message.usageoptionalUsageNested model work done by the tool; counted in session totals but not main-call accounting.
message.nestedCallsoptional{calls:{id,name,arguments?,argumentsBytes?,status(ok|error|unfinished),durationMs?,error?}[], complete:boolean}Bounded record of tool-to-tool calls (e.g. codemode).
message.isErrorboolean—
message.timestampnumber (ms)—
message.durationMsoptionalnumberTool execution time.since 1.1.0
{"type":"message","id":"c3d4e5f6","parentId":"b2c3d4e5","timestamp":"2026-01-01T10:00:04.000Z","message":{"role":"toolResult","toolCallId":"call_1","toolName":"bash","content":[{"type":"text","text":"ok"}],"isError":false,"timestamp":1767261604000}}

message / bashExecution

A user-initiated shell command (! or !! prefix, or RPC bash) with its output; not an LLM tool call.

Written after the command finishes; if a turn is streaming it is queued and appended at agent_end.

Stored only user runs a shell command

FieldTypeMeaning
message.role"bashExecution"—
message.commandstring—
message.outputstringPossibly truncated output.
message.exitCodenumber|undefinedOmitted from JSON when undefined.
message.cancelledboolean—
message.truncatedboolean—
message.fullOutputPathoptionalstringTemp file with full output (os.tmpdir()/pi-bash-<16hex>.log).
message.excludeFromContextoptionalbooleantrue for !! commands: not converted into model context.
message.timestampnumber (ms)—
{"type":"message","id":"d4e5f6a7","parentId":"c3d4e5f6","timestamp":"2026-01-01T10:01:00.000Z","message":{"role":"bashExecution","command":"ls","output":"README.md","exitCode":0,"cancelled":false,"truncated":false,"timestamp":1767261660000}}

Converted to user-role text for the model unless excludeFromContext.

message / custom

Legacy/alternate location for an extension context message; the agent re-routes role custom to a custom_message entry, so this appears only from SDK appendMessage() or v2 hookMessage migration.

Written rare: direct SessionManager.appendMessage() with a CustomMessage, or v1/v2 files whose hookMessage role is renamed on load.

Stored only SDK/legacy

FieldTypeMeaning
message.role"custom" (was "hookMessage" before v3)—
message.customTypestring—
message.contentstring | (TextContent|ImageContent)[]—
message.displayboolean—
message.detailsoptionalany—
message.timestampnumber (ms)—
{"type":"message","id":"e5f6a7b8","parentId":"d4e5f6a7","timestamp":"2026-01-01T10:02:00.000Z","message":{"role":"custom","customType":"my-ext","content":"note","display":true,"timestamp":1767261720000}}

model_change

User or runtime switched the selected model (may be a virtual model).

Written session start (SDK records initial model/thinking), /model, model cycling, fallback switching.

FieldTypeMeaning
providerstring—
modelIdstring—
{"type":"model_change","id":"f6a7b8c9","parentId":"e5f6a7b8","timestamp":"2026-01-01T10:03:00.000Z","provider":"openai","modelId":"example-model"}

thinking_level_change

Thinking/reasoning level changed.

Written session start and whenever the level changes.

FieldTypeMeaning
thinkingLevelstring (off|minimal|low|medium|high|xhigh|max)—
{"type":"thinking_level_change","id":"a7b8c9d0","parentId":"f6a7b8c9","timestamp":"2026-01-01T10:03:01.000Z","thinkingLevel":"high"}

usagesince 0.86.0

Model-attributed usage that is not an assistant message (e.g. prompt-cache warming).

Written cache warmer refreshes (kind cache_warm); any caller of appendUsage(). Not part of LLM context; hidden from the tree.

Stored only cache warming or extension

FieldTypeMeaning
kindstringOpen-ended category; treat unknown kinds as normal usage.
providerstring—
modelstring—
usageUsageUsage object: input, output, cacheRead, cacheWrite, cacheWrite1h?, reasoning?, totalTokens, cost{input,output,cacheRead,cacheWrite,total}
noteoptionalstringHuman-readable qualifier.
{"type":"usage","id":"b8c9d0e1","parentId":"a7b8c9d0","timestamp":"2026-01-01T10:04:00.000Z","kind":"cache_warm","provider":"anthropic","model":"example-model","usage":{"input":0,"output":1,"cacheRead":50000,"cacheWrite":0,"totalTokens":50001,"cost":{"input":0,"output":0.00001,"cacheRead":0.015,"cacheWrite":0,"total":0.01501}}}

compaction

Context compaction checkpoint: summary of earlier entries, the first kept entry, and the full system prompt/tool state at that point.

Written manual /compact, auto-compaction on threshold or overflow, or extension-driven compaction.

Stored only compaction runs

FieldTypeMeaning
summarystring—
firstKeptEntryIdstringFirst retained entry before the compaction; equals the compaction's own id for retain-none (since 0.87.0).
tokensBeforenumberContext tokens before compaction.
detailsoptionalanyDefault: {readFiles:string[], modifiedFiles:string[]}; extensions may store anything.
usageoptionalUsageCost of producing the summary; counted in session totals.
fromHookoptionalbooleantrue when an extension produced it.
systemMessageoptionalSystemMessageComplete prompt/tool checkpoint; becomes the leading system message of compacted context.since 0.86.0
{"type":"compaction","id":"c9d0e1f2","parentId":"b8c9d0e1","timestamp":"2026-01-01T11:00:00.000Z","summary":"Goal: ...","firstKeptEntryId":"a1b2c3d4","tokensBefore":120000,"details":{"readFiles":[],"modifiedFiles":[]}}

v1 files stored firstKeptEntryIndex (array index); migration converts it to firstKeptEntryId.

branch_summary

LLM summary of an abandoned branch, written when navigating /tree to another point with summarisation.

Written branchWithSummary(): parentId is the branch point (or null for a new root); fromId is the old leaf.

Stored only tree navigation with summary

FieldTypeMeaning
fromIdstringPrevious leaf whose path was summarised; literal "root" if there was no leaf.
summarystring—
detailsoptionalanyDefault {readFiles, modifiedFiles}.
usageoptionalUsage—
fromHookoptionalboolean—
{"type":"branch_summary","id":"d0e1f2a3","parentId":"a1b2c3d4","timestamp":"2026-01-01T11:05:00.000Z","fromId":"c9d0e1f2","summary":"Tried approach A ..."}

custom

Extension state that never enters model context.

Written appendCustomEntry() by extensions; built-in uses: pi.virtual-model-state {provider, modelId, state}, pi.bug-report {id, createdAt, hint, sessionIncluded, summaryIncluded, delivery, path?}.

Stored only extensions

FieldTypeMeaning
customTypestringExtension identifier.
dataoptionalany—
{"type":"custom","id":"e1f2a3b4","parentId":"d0e1f2a3","timestamp":"2026-01-01T11:06:00.000Z","customType":"my-extension","data":{"count":1}}

custom_message

Extension-injected message that does enter model context (as user-role content).

Written pi.sendMessage() and other extension message injection (agent message_end with role custom).

Stored only extensions

FieldTypeMeaning
customTypestring—
contentstring | (TextContent|ImageContent)[]—
displaybooleanRender in TUI or hide.
detailsoptionalanyNot sent to model.
{"type":"custom_message","id":"f2a3b4c5","parentId":"e1f2a3b4","timestamp":"2026-01-01T11:07:00.000Z","customType":"my-extension","content":"Injected context","display":true}

context_editsince 0.87.0

Append-only edit that omits or replaces one earlier entry's content in future model context, without changing raw history.

Written appendContextEdit(); used by extensions and by error recovery, which omits a failed assistant attempt and its tool results (replacement null).

Stored only edits/recovery

FieldTypeMeaning
targetIdstringA user/assistant/toolResult message entry or custom_message entry on the active branch.
replacement{content: string|block[]} | nullnull omits; string content for assistant/toolResult is normalized to one text block.
{"type":"context_edit","id":"a3b4c5d6","parentId":"f2a3b4c5","timestamp":"2026-01-01T11:08:00.000Z","targetId":"b2c3d4e5","replacement":null}

labelsince 0.31.0

User bookmark on an entry (set or clear).

Written /tree label action (l), extensions, branch-summary labelling; createBranchedSession re-emits resolved labels at the end of the new file.

Stored only labelling

FieldTypeMeaning
targetIdstring—
labelstring|undefinedOmitted from JSON (undefined) or empty to clear.
{"type":"label","id":"b4c5d6e7","parentId":"a3b4c5d6","timestamp":"2026-01-01T11:09:00.000Z","targetId":"a1b2c3d4","label":"checkpoint-1"}

session_info

Session display name.

Written /name, --name/-n, pi.setSessionName(); latest entry in the file wins, empty name clears.

Stored only naming

FieldTypeMeaning
nameoptionalstringNewlines collapsed to spaces, trimmed.
{"type":"session_info","id":"c5d6e7f8","parentId":"b4c5d6e7","timestamp":"2026-01-01T11:10:00.000Z","name":"Refactor auth module"}

Content blocks (4)

text

Plain text (user, assistant, toolResult, system, custom content).

Written inside message.content arrays.

FieldTypeMeaning
type"text"—
textstring—
textSignatureoptionalstringOpaque provider metadata (legacy id string or JSON {v:1,id,phase?:commentary|final_answer} for OpenAI Responses).
{"type":"text","text":"Hello"}

image

Inline base64 image (user, toolResult, custom content).

Written inside content arrays.

FieldTypeMeaning
type"image"—
datastring (base64)—
mimeTypestring—
{"type":"image","data":"iVBORw0KGgo=","mimeType":"image/png"}

thinking

Model reasoning (assistant only).

Written inside assistant content.

FieldTypeMeaning
type"thinking"—
thinkingstringMay be empty when redacted.
thinkingSignatureoptionalstringOpaque replay data / encrypted payload.
redactedoptionalboolean—
{"type":"thinking","thinking":"Consider the file layout...","thinkingSignature":"sig"}

toolCall

Model's request to run a tool (assistant only).

Written inside assistant content; result follows as a toolResult message entry.

FieldTypeMeaning
type"toolCall"—
idstringMatched by toolResult.toolCallId.
namestring—
argumentsobject{} when argumentsError is set.
thoughtSignatureoptionalstringGoogle opaque signature.
namespaceoptionalstringOpenAI Responses tool namespace.
argumentsErroroptionalstringRaw text and error when model sent invalid JSON arguments.since 1.3.0
{"type":"toolCall","id":"call_1","name":"bash","arguments":{"command":"ls"}}

Rebuilding the conversation

ordering
File order is append order. Line 1 is the header. Conversation order on a branch comes from walking parentId, not from line order, because branches interleave in one file.
message parent links
Every non-header entry (all types, including model_change, label, usage) is a tree node whose parentId is the leaf at append time. Build an id index, then walk parentId from a leaf to null.
branches/rewind
The active leaf is not stored: on load it is the last entry in the file. Branching moves the leaf in memory and the next append gets an earlier parentId; branch_summary records a summarised switch (parentId = branch point, fromId = old leaf). resetLeaf()/branchWithSummary(null) can create extra roots (parentId null). Leaves = entries with no children.
tool call ↔ result
assistant content block {type:toolCall,id} pairs with a later message entry with role toolResult and the same toolCallId; results for one assistant message are appended in call order after the whole batch completes.
turns
No explicit turn records. A turn starts with a user (or custom_message) entry and runs through assistant/toolResult entries until an assistant message whose stopReason is not toolUse.
compaction
Use the latest compaction on the active path: model context = compaction.systemMessage (if any) + compactionSummary, then non-system entries from firstKeptEntryId up to the compaction, then everything after it. Raw entries are kept on disk.
context edits
For each target, the latest context_edit on the selected path wins; replacement null removes it from model context; display/history/usage still use the original.
forks
/fork and /clone (createBranchedSession) write a new file containing only the root→leaf path (labels dropped and re-emitted at the end, parentIds rechained) with header.parentSession = source path. forkFrom() copies all source entries verbatim into a new file in another cwd. Entry ids are preserved in both.
session settings
Current model = last model_change or assistant (provider, model) on the path; thinking level = last thinking_level_change (default off).
resume
Resume reopens the same file and appends; continueRecent picks the newest file in the cwd directory.
subagents
No core subagent lineage; subagents are an example extension running separate pi sessions.
sidecar references
toolResult.details.fullOutputPath and bashExecution.fullOutputPath point to temp files outside the session directory.

Token usage

message(assistant).usage.input/output/cacheRead/cacheWrite
Per-response tokens. reasoning (optional) is a subset of output; cacheWrite1h a subset of cacheWrite.
usage.totalTokens
Provider total for the call.
usage.cost.{input,output,cacheRead,cacheWrite,total}
USD. Components are catalogue-derived estimates; total can instead be a provider-reported billed amount when totalFromProvider is true.
toolResult.usage
Nested model work by the tool; counted in session totals.
usage entry, compaction.usage, branch_summary.usage
Non-conversation model calls; included in session totals. Sum across all branches in the file for total spend; across the active path only for that branch.
usage.cost.totalFromProvider
True means total is provider-reported billed cost; false or absent means catalogue estimate. Individual component costs remain catalogue derived, so their sum need not equal a provider-billed total.

Versions

Header.version: absent=1 (linear, no id/parentId; compaction used firstKeptEntryIndex), 2 (id/parentId tree, since 0.31.0), 3 (message role hookMessage renamed to custom, since 0.35.0). CURRENT_SESSION_VERSION=3 at v1.5.2. Older files are migrated in memory on load and the file is rewritten in place. Additive fields since v3 are not versioned: system messages and compaction.systemMessage (0.86.0), usage entries (0.86.0), context_edit (0.87.0), retain-none compaction (0.87.0), Usage.reasoning (0.80.3), endTurn (0.84.2), durationMs (1.1.0), argumentsError (1.3.0). File is created at first user message since 0.99.0. The 1.5.2 writer rolls back its in-memory entry/leaf on a failed append. responseModel may equal the requested model. Usage.cost.totalFromProvider optionally distinguishes billed provider totals from catalogue estimates.

Parsing pitfalls

  • Branches share one file: reading lines in order mixes alternate branches. Walk parentId from the chosen leaf.
  • The active leaf is not persisted; pi assumes the last line is the leaf, which after a non-summarised branch switch may be on a different branch than an earlier tail.
  • Two timestamps: entry.timestamp is ISO 8601; message.timestamp is Unix ms (request start for assistant).
  • Non-message entries (model_change, label, usage, custom, context_edit) are tree nodes too and sit between messages on the parent chain.
  • role custom normally appears as a custom_message entry, not inside a message entry; compactionSummary and branchSummary roles are never persisted as messages.
  • Errored and aborted assistant messages are persisted; error recovery may later hide them via context_edit rather than deleting them.
  • user content may be a plain string or a block array.
  • Opening an old-version file rewrites it on disk with the current version.
  • label clear is written as a label entry without a label key (undefined dropped by JSON.stringify).
  • branch_summary.fromId can be the literal string "root".
  • Source audit 2026-11-15: version and commit identify inspected release source, not a passing runtime probe or a compatibility guarantee. Earlier source pins and observations are retained in the audit evidence manifest.

Sources

pi