codex

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package codex reads the Codex CLI's rollout files: the JSONL files under ~/.codex/sessions/YYYY/MM/DD, one per thread. It imports the standard library alone.

Codex does not document the format. Its definition is the Rust source of openai/codex: the RolloutItem union and its wire form in codex-rs/history (lib.rs, rollout_payload.rs), the ResponseItem, SessionMeta, TurnContextItem and EventMsg types in codex-rs/protocol (models.rs, protocol.rs), and which items are written at all in codex-rs/rollout/src/policy.rs. This package follows the source at commit 7ae831991792744434027c431dfbc7e81dd5c12c (2026-10-15), and the layout rollouts had before September 2025, when the first line was a bare session meta and the items followed bare, with "record_type" state lines between (codex-rs/core/src/rollout.rs at 9dbe7284).

Every object keeps the members it does not declare and writes them back; a line of a shape the package does not expect keeps its raw bytes; a line that is not JSON is recorded and skipped, as Codex skips it. A zstd-compressed rollout (.jsonl.zst) is refused with ErrCompressed: the standard library has no zstd.

Read and ReadFile read; converting to the Agent Session Format is the convert subpackage's, and docs/formats/codex.md is the mapping.

Index

Constants

View Source
const (
	TypeSessionMeta                     = "session_meta"
	TypeResponseItem                    = "response_item"
	TypeEventMsg                        = "event_msg"
	TypeTurnContext                     = "turn_context"
	TypeCompacted                       = "compacted"
	TypeInterAgentCommunication         = "inter_agent_communication"
	TypeInterAgentCommunicationMetadata = "inter_agent_communication_metadata"
	TypeTokenUsageRecord                = "token_usage_record"
	TypeWorldState                      = "world_state"
	TypeRetainedContext                 = "retained_context"
	TypeSecurityRiskScore               = "security_risk_score"
	TypeRealtimeItem                    = "realtime_item"
	// TypeState is the kind of a legacy line {"record_type":"state"},
	// a session state snapshot rollouts before September 2025 wrote.
	TypeState = "state"
)

Line types: the "type" member of a rollout line, which names what its "payload" holds (RolloutItem's wire form).

View Source
const (
	ItemMessage              = "message"
	ItemAgentMessage         = "agent_message"
	ItemReasoning            = "reasoning"
	ItemLocalShellCall       = "local_shell_call"
	ItemFunctionCall         = "function_call"
	ItemToolSearchCall       = "tool_search_call"
	ItemFunctionCallOutput   = "function_call_output"
	ItemCustomToolCall       = "custom_tool_call"
	ItemCustomToolCallOutput = "custom_tool_call_output"
	ItemToolSearchOutput     = "tool_search_output"
	ItemWebSearchCall        = "web_search_call"
	ItemImageGenerationCall  = "image_generation_call"
	ItemCompaction           = "compaction"
	// ItemCompactionSummary is an alias Codex reads as ItemCompaction.
	ItemCompactionSummary   = "compaction_summary"
	ItemConfigurationUpdate = "configuration_update"
	ItemCompactionTrigger   = "compaction_trigger"
	ItemContextCompaction   = "context_compaction"
	ItemAdditionalTools     = "additional_tools"
	// ItemGhostSnapshot is a git snapshot for undo, which versions of
	// late 2025 and early 2026 recorded and never sent the model.
	ItemGhostSnapshot = "ghost_snapshot"
)

Item types: a response item's "type" (ResponseItem's variants, and the ones earlier versions wrote).

View Source
const (
	EventTokenCount               = "token_count"
	EventTurnStarted              = "turn_started"
	EventTurnComplete             = "turn_complete"
	EventTurnAborted              = "turn_aborted"
	EventThreadRolledBack         = "thread_rolled_back"
	EventThreadSettingsApplied    = "thread_settings_applied"
	EventThreadGoalUpdated        = "thread_goal_updated"
	EventItemCompleted            = "item_completed"
	EventUserMessage              = "user_message"
	EventAgentMessage             = "agent_message"
	EventAgentReasoning           = "agent_reasoning"
	EventAgentReasoningRawContent = "agent_reasoning_raw_content"
	EventContextCompacted         = "context_compacted"
	EventEnteredReviewMode        = "entered_review_mode"
	EventExitedReviewMode         = "exited_review_mode"
	EventPatchApplyEnd            = "patch_apply_end"
	EventMcpToolCallEnd           = "mcp_tool_call_end"
	EventWebSearchEnd             = "web_search_end"
	EventImageGenerationEnd       = "image_generation_end"
	EventSubAgentActivity         = "sub_agent_activity"
	EventUndoCompleted            = "undo_completed"
)

Event types this package names: those rollouts persist (policy.rs, and before it core/src/rollout/policy.rs).

View Source
const EventCollabAgentSpawnEnd = "collab_agent_spawn_end"

EventCollabAgentSpawnEnd is the event a spawn ends with, which Codex 0.120 to 0.130 wrote to rollouts in extended persistence.

View Source
const MaxLineSize = 256 << 20

MaxLineSize bounds one line. A longer line is reported as malformed and skipped rather than read into memory.

View Source
const MaxMetaSize = 8 << 20

MaxMetaSize bounds the session meta line ReadMeta reads. The line carries the thread's base instructions and dynamic tools, tens of kilobytes as a rule; one past this bound is reported as ErrMetaTooLong rather than read into memory.

View Source
const NamespaceMultiAgentV1 = "multi_agent_v1"

NamespaceMultiAgentV1 is the namespace of the multi_agent_v1 tools.

View Source
const ToolSpawnAgent = "spawn_agent"

ToolSpawnAgent is the name of the tool a thread spawns a sub-agent with: the collab tool of 0.98, the multi_agent_v1 namespace's later, and MultiAgentV2's.

Variables

View Source
var ErrCompressed = errors.New("codex: the rollout is zstd-compressed; decompress it with zstd -d first")

ErrCompressed is returned for a zstd-compressed rollout, which Codex writes for cold threads as .jsonl.zst. The standard library has no zstd; decompress it first (zstd -d) and read the .jsonl.

View Source
var ErrMetaTooLong = fmt.Errorf("codex: the session meta line is longer than %d bytes", MaxMetaSize)

ErrMetaTooLong is returned by ReadMeta for a session meta line longer than MaxMetaSize.

ItemTypes are the item types Codex defines, at the source this package follows or before. Codex reads any other as Other, which it neither writes nor sends.

Functions

func FindSessions

func FindSessions(root string) ([]string, error)

FindSessions returns the rollout files under root, every rollout-* .jsonl and .jsonl.zst at any depth, sorted. root may be ~/.codex/sessions, a day's directory, or a single file.

func IDFromFileName

func IDFromFileName(path string) string

IDFromFileName returns the thread id a rollout's file name carries, or "" when the name is not of Codex's form.

func SessionsRoot

func SessionsRoot(path string) (root string, tree bool, err error)

SessionsRoot returns where a rollout's relatives are looked for, as an absolute path with symbolic links resolved. A rollout Codex filed, sessions/YYYY/MM/DD/rollout-*.jsonl, gives the sessions directory and tree true: a sub-agent may be filed under another day. Any other rollout gives its own directory and tree false, to be indexed alone, so a rollout in a home directory does not walk the home directory.

Types

type BaseInstructions

type BaseInstructions struct {
	Text       string          `json:"text"`
	Provenance json.RawMessage `json:"provenance"`

	Members
}

BaseInstructions are the thread's model instructions, the request's "instructions".

func (BaseInstructions) MarshalJSON

func (b BaseInstructions) MarshalJSON() ([]byte, error)

MarshalJSON writes the instructions back as they were read.

func (*BaseInstructions) UnmarshalJSON

func (b *BaseInstructions) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the instructions, keeping undeclared members.

type Compacted

type Compacted struct {
	Message string `json:"message"`
	// ReplacementHistory is the new window's items, in order; absent in
	// older rollouts, which rebuilt it from the user messages on resume.
	ReplacementHistory         []json.RawMessage `json:"replacement_history"`
	ReplacementHistoryMetadata json.RawMessage   `json:"replacement_history_metadata"`
	WindowNumber               json.Number       `json:"window_number"`
	CompactionResponseID       string            `json:"compaction_response_id"`
	LatestTokenUsageRecord     json.RawMessage   `json:"latest_token_usage_record"`
	ResumeMetadata             json.RawMessage   `json:"resume_metadata"`

	Members
}

Compacted is a compaction: the summary text and, since late 2025, the whole history the model window was replaced with.

func (*Compacted) HasReplacement

func (c *Compacted) HasReplacement() bool

HasReplacement reports whether the compaction carries its replacement history, null or absent being the older form.

func (Compacted) MarshalJSON

func (c Compacted) MarshalJSON() ([]byte, error)

MarshalJSON writes the compaction back as it was read.

func (*Compacted) UnmarshalJSON

func (c *Compacted) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the compaction, keeping undeclared members.

type ContentItem

type ContentItem struct {
	Type     string `json:"type"`
	Text     string `json:"text"`
	ImageURL string `json:"image_url"`
	FileID   string `json:"file_id"`
	Detail   string `json:"detail"`
	AudioURL string `json:"audio_url"`
}

ContentItem is one part of a message's content.

type Event

type Event struct {
	Type string `json:"type"`

	// turn_started, turn_complete, turn_aborted.
	TurnID     string `json:"turn_id"`
	RootTurnID string `json:"root_turn_id"`
	// turn_aborted.
	Reason json.RawMessage `json:"reason"`

	// thread_rolled_back: how many user turns were dropped.
	NumTurns *int64 `json:"num_turns"`

	// token_count.
	Info       *TokenUsageInfo `json:"info"`
	RateLimits json.RawMessage `json:"rate_limits"`

	// user_message and agent_message.
	Message string `json:"message"`
	// user_message.
	Images json.RawMessage `json:"images"`
	// agent_reasoning and agent_reasoning_raw_content.
	Text string `json:"text"`

	// item_completed.
	Item json.RawMessage `json:"item"`

	Members
}

Event is an event_msg payload: one of Codex's events. It holds the members of the events rollouts persist; Type says which apply, and every other member is kept.

func (Event) MarshalJSON

func (e Event) MarshalJSON() ([]byte, error)

MarshalJSON writes the event back as it was read.

func (*Event) UnmarshalJSON

func (e *Event) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes an event, keeping undeclared members.

type File

type File struct {
	// Path is the file the rollout was read from; empty when it was read
	// from a reader.
	Path string
	// Lines are the lines that decoded as JSON objects, in file order.
	Lines []*Line
	// Errors lists the lines that could not be read, which the reader
	// skipped, as Codex skips them.
	Errors []LineError
	// Legacy says the file is in the layout before the envelope: a bare
	// session meta first, then bare items and state records.
	Legacy bool
}

File is one rollout file.

func Read

func Read(r io.Reader) (*File, error)

Read reads a rollout. A line that is not a JSON object is recorded in Errors and skipped, as Codex skips it; a line that is an object but not of the shapes this package declares is kept with Err or PayloadErr set. Read fails only when r does, or with ErrCompressed.

func ReadFile

func ReadFile(path string) (*File, error)

ReadFile reads a rollout from a file.

func (*File) LineCount

func (f *File) LineCount() int

LineCount is the number of lines the file had that a reader accounts for: those read and those that could not be. Blank lines are not counted.

func (*File) MetaLine

func (f *File) MetaLine() *Line

MetaLine returns the line of the thread's session meta: the first session_meta line that decodes, as Codex takes the first. Later ones are a forked thread's copies of its ancestors'.

type GitInfo

type GitInfo struct {
	CommitHash    string `json:"commit_hash"`
	Branch        string `json:"branch"`
	RepositoryURL string `json:"repository_url"`

	Members
}

GitInfo is the repository state when the thread started.

func (GitInfo) MarshalJSON

func (g GitInfo) MarshalJSON() ([]byte, error)

MarshalJSON writes the git state back as it was read.

func (*GitInfo) UnmarshalJSON

func (g *GitInfo) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the git state, keeping undeclared members.

type Index

type Index struct {
	// Root is the directory indexed, symbolic links resolved.
	Root string
	// Skipped lists the rollouts whose session meta could not be read
	// and the directories that could not be walked: a thread among them
	// is in no family.
	Skipped []Skip
	// contains filtered or unexported fields
}

Index maps the threads of a sessions tree to their rollouts and their parents to their children, from each rollout's session meta line alone. It holds every thread's ids and paths, a few hundred bytes a rollout, and none of their content.

func IndexDir

func IndexDir(root string) (*Index, error)

IndexDir indexes every rollout under root, at any depth. root is resolved through symbolic links first; a directory that cannot be read, or that vanishes during the walk, is listed in Skipped and passed over.

func IndexFlat

func IndexFlat(dir string) (*Index, error)

IndexFlat indexes the rollouts directly in dir, not below it.

func IndexFor

func IndexFor(path string) (*Index, error)

IndexFor indexes the tree a rollout's relatives are in: the sessions tree when the rollout sits where Codex files it, sessions/YYYY/MM/DD/, else the rollout's own directory alone. See SessionsRoot.

func (*Index) Ancestors

func (x *Index) Ancestors(id string) []string

Ancestors returns the threads above one, parent first, as far as the index holds them, each once: a thread that names itself, or a cycle, ends the chain.

func (*Index) Children

func (x *Index) Children(id string) []string

Children returns the ids of the threads a thread spawned, sorted. A nil index holds none.

func (*Index) Rollouts

func (x *Index) Rollouts(id string) []Thread

Rollouts returns the rollout files of a thread, oldest first: a reverted thread has several, the last being the one Codex continues. A nil index holds none.

type InterAgent

type InterAgent struct {
	ID               string          `json:"id"`
	Author           string          `json:"author"`
	Recipient        string          `json:"recipient"`
	OtherRecipients  json.RawMessage `json:"other_recipients"`
	Content          string          `json:"content"`
	EncryptedContent string          `json:"encrypted_content"`
	Passthrough      json.RawMessage `json:"internal_chat_message_metadata_passthrough"`
	TriggerTurn      bool            `json:"trigger_turn"`

	Members
}

InterAgent is a message between agents of a multi-agent thread, which Codex puts in the recipient's context as an agent_message item.

func (InterAgent) MarshalJSON

func (a InterAgent) MarshalJSON() ([]byte, error)

MarshalJSON writes the message back as it was read.

func (*InterAgent) ModelInput

func (a *InterAgent) ModelInput() map[string]any

ModelInput returns the agent_message item Codex puts in the recipient's context for the message (InterAgentCommunication's to_model_input_item): the text, or for an encrypted message a header naming the task and sender followed by the encrypted payload.

func (*InterAgent) UnmarshalJSON

func (a *InterAgent) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the message, keeping undeclared members.

type Item

type Item struct {
	Type   string `json:"type"`
	ID     string `json:"id"`
	Status string `json:"status"`

	// message, additional_tools.
	Role string `json:"role"`
	// message (content items), reasoning (reasoning text), agent_message.
	Content json.RawMessage `json:"content"`
	// message: commentary, partial_answer or final_answer.
	Phase string `json:"phase"`
	// Codex's own encrypted form of several items, and the reasoning or
	// compaction item's encrypted content.
	EncryptedContent *string `json:"encrypted_content"`

	// reasoning.
	Summary json.RawMessage `json:"summary"`

	// function_call, custom_tool_call and their outputs; local_shell_call,
	// tool_search_call and tool_search_output, where it may be null.
	CallID    string `json:"call_id"`
	Name      string `json:"name"`
	Namespace string `json:"namespace"`
	// function_call: a JSON string; tool_search_call: any value.
	Arguments             json.RawMessage `json:"arguments"`
	EncryptedFunctionArgs json.RawMessage `json:"encrypted_function_args"`
	// custom_tool_call: the free-form input.
	Input string `json:"input"`
	// function_call_output and custom_tool_call_output: a string or an
	// array of content items.
	Output json.RawMessage `json:"output"`

	// local_shell_call and web_search_call.
	Action json.RawMessage `json:"action"`
	// tool_search_call and tool_search_output.
	Execution string `json:"execution"`
	// tool_search_output and additional_tools.
	Tools json.RawMessage `json:"tools"`

	// agent_message.
	Author    string `json:"author"`
	Recipient string `json:"recipient"`

	// image_generation_call.
	RevisedPrompt string `json:"revised_prompt"`
	Result        string `json:"result"`

	// configuration_update.
	Reasoning json.RawMessage `json:"reasoning"`

	// ghost_snapshot.
	GhostCommit json.RawMessage `json:"ghost_commit"`

	// Passthrough is metadata Codex sends the Responses API beside the
	// item: the turn id, creation time, content kinds.
	Passthrough json.RawMessage `json:"internal_chat_message_metadata_passthrough"`

	Members
}

Item is a response item: a Responses API item as Codex records it. It holds the members of every item type; Type says which apply. Members whose shape varies by type are kept raw.

func (*Item) IsSpawnCall

func (it *Item) IsSpawnCall() bool

IsSpawnCall reports whether an item is a call of Codex's own spawn_agent: with no namespace (0.98's collab tool, MultiAgentV2's) or in the multi_agent_v1 namespace. A tool of that name in another namespace, an MCP server's, is not. A spawn made from code mode is no function call of its own, and is not one either.

func (Item) MarshalJSON

func (i Item) MarshalJSON() ([]byte, error)

MarshalJSON writes the item back as it was read.

func (*Item) Parts

func (i *Item) Parts() []ContentItem

Parts returns a message item's content parts; nil when the content is not an array of objects.

func (*Item) SpawnedTask

func (it *Item) SpawnedTask() string

SpawnedTask returns the agent path a MultiAgentV2 spawn's output names, {"task_name": "/root/<task>", ...}, or "". The spawned thread's session meta carries the same path in its thread_spawn source.

func (*Item) SpawnedThread

func (it *Item) SpawnedThread() string

SpawnedThread returns the thread a spawn call's output names, or "" when it names none. The spawn_agent of 0.98 and of multi_agent_v1 answers {"agent_id": "<thread id>"}; MultiAgentV2's answers with the agent's task name alone, and its thread is in a record beside the call (see Line.Spawn). The output is a string or a list of content items, as any function call output.

func (*Item) Texts

func (i *Item) Texts() []string

Texts returns the text of a message item's input_text and output_text parts, in order; nil when the content is not an array of parts.

func (*Item) UnmarshalJSON

func (i *Item) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes an item, keeping undeclared members.

type Line

type Line struct {
	Timestamp string `json:"timestamp"`
	// Ordinal is the line's position in the thread's history, which
	// newer rollouts write.
	Ordinal json.Number     `json:"ordinal"`
	Type    string          `json:"type"`
	Payload json.RawMessage `json:"payload"`
	// Metadata is a response item's harness metadata
	// (CodexHarnessMetadata), never sent to the model.
	Metadata json.RawMessage `json:"metadata"`

	Members

	// No is the line's 1-based number in its file.
	No int `json:"-"`
	// Raw is the line as read.
	Raw json.RawMessage `json:"-"`
	// Kind is what the line holds: Type for an envelope line; for a
	// legacy line TypeSessionMeta, TypeResponseItem or TypeState.
	Kind string `json:"-"`
	// Legacy says the line is in the layout before the envelope.
	Legacy bool `json:"-"`
	// Err is set when the line is JSON but not a rollout line: an object
	// with no type and no record_type past the first line.
	Err error `json:"-"`
	// PayloadErr is set when the payload of a kind this package types
	// does not decode as that kind; the typed field is then nil.
	PayloadErr error `json:"-"`

	Meta        *SessionMeta      `json:"-"`
	Item        *Item             `json:"-"`
	Event       *Event            `json:"-"`
	TurnContext *TurnContext      `json:"-"`
	Compacted   *Compacted        `json:"-"`
	InterAgent  *InterAgent       `json:"-"`
	UsageRecord *TokenUsageRecord `json:"-"`
}

Line is one line of a rollout: an envelope {timestamp, ordinal, type, payload} or, in the legacy layout, a bare session meta, item or state record. The payload of a kind this package types is decoded into the matching field; every line keeps its raw bytes and writes back as it was read.

func (Line) MarshalJSON

func (l Line) MarshalJSON() ([]byte, error)

MarshalJSON writes the line back as it was read.

func (*Line) MistypedMembers

func (l *Line) MistypedMembers() []string

MistypedMembers lists, as paths, the members of the line and its payload whose value was not of the type Codex defines for it, which the reader kept as written rather than fail the line.

func (*Line) PayloadRaw

func (l *Line) PayloadRaw() json.RawMessage

PayloadRaw is what the line's typed field decodes from: the envelope's payload, or the whole legacy line.

func (*Line) Spawn

func (l *Line) Spawn() (callID, threadID string, ok bool)

Spawn returns the spawn a record beside the call names: the call's id and the thread it started. Codex writes one of three, by version and history mode:

  • a sub_agent_activity event of kind "started", whose event_id is the spawn call's id (MultiAgentV2, legacy history);
  • an item_completed event holding a SubAgentActivity item of kind "started", whose id is the call's (MultiAgentV2, paginated);
  • an item_completed event holding a CollabAgentToolCall item of tool "spawn_agent", whose receiver_thread_ids name the thread (multi_agent_v1, paginated);
  • a collab_agent_spawn_end event, whose call_id and new_thread_id name both (0.120 to 0.130, extended persistence).

func (*Line) Time

func (l *Line) Time() time.Time

Time is the line's timestamp, zero when it has none or it does not parse.

func (*Line) UnmarshalJSON

func (l *Line) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes an envelope line, keeping undeclared members. The payload is decoded by [Line.decodePayload].

type LineError

type LineError struct {
	No  int
	Err error
}

LineError is a line the reader could not read.

func (LineError) Error

func (e LineError) Error() string

type Members

type Members = jsonline.Members

Members is embedded in every object this package decodes. It keeps the members the Go type does not declare, and remembers which declared members the input carried and which were null, so an object decoded and encoded again is the same JSON value.

type SessionMeta

type SessionMeta struct {
	// ID is the thread's id; SessionID the root thread's, which a
	// sub-agent shares.
	ID                         string            `json:"id"`
	SessionID                  string            `json:"session_id"`
	ForkedFromID               string            `json:"forked_from_id"`
	ForkedFromOrdinalExclusive json.Number       `json:"forked_from_ordinal_exclusive"`
	ParentThreadID             string            `json:"parent_thread_id"`
	Timestamp                  string            `json:"timestamp"`
	CWD                        string            `json:"cwd"`
	Originator                 string            `json:"originator"`
	CLIVersion                 string            `json:"cli_version"`
	Source                     json.RawMessage   `json:"source"`
	ThreadSource               string            `json:"thread_source"`
	AgentNickname              string            `json:"agent_nickname"`
	AgentRole                  string            `json:"agent_role"`
	AgentPath                  string            `json:"agent_path"`
	ModelProvider              string            `json:"model_provider"`
	BaseInstructions           *BaseInstructions `json:"base_instructions"`
	DynamicTools               json.RawMessage   `json:"dynamic_tools"`
	MemoryMode                 string            `json:"memory_mode"`
	// HistoryMode is "legacy" (the default) or "paginated".
	HistoryMode string `json:"history_mode"`
	// HistoryBase names a prefix of another rollout this thread
	// inherits by reference, not by copy.
	HistoryBase                 json.RawMessage `json:"history_base"`
	SubagentHistoryStartOrdinal json.Number     `json:"subagent_history_start_ordinal"`
	MultiAgentVersion           string          `json:"multi_agent_version"`
	ContextWindow               json.RawMessage `json:"context_window"`
	Git                         *GitInfo        `json:"git"`
	// Instructions is the legacy layout's user instructions, which later
	// versions moved to the turn context.
	Instructions *string `json:"instructions"`

	Members
}

SessionMeta is the first line's payload: the thread, where it ran and what started it. In the legacy layout it is the first line itself, with Instructions and no source.

func ReadMeta

func ReadMeta(path string) (*SessionMeta, error)

ReadMeta reads a rollout's session meta from its first line and nothing after it: Codex writes the meta first, in the envelope and in the bare layout of 2025 alike. It returns nil with no error when the first line is not a session meta, ErrCompressed for a zstd-compressed rollout, and ErrMetaTooLong for a line past MaxMetaSize. A fork copies its ancestors' metas after its own, so a rollout whose first line is damaged is not taken for an ancestor's.

func (SessionMeta) MarshalJSON

func (m SessionMeta) MarshalJSON() ([]byte, error)

MarshalJSON writes the meta back as it was read.

func (*SessionMeta) ParentThread

func (m *SessionMeta) ParentThread() string

ParentThread returns the thread that spawned this one: the session meta's parent_thread_id, or the thread_spawn source's parent. A fork the user made names the thread it copied in forked_from_id instead, and has no parent here.

func (*SessionMeta) SourceKind

func (m *SessionMeta) SourceKind() string

SourceKind names the session source: "cli", "vscode", "exec", "mcp", a custom string, "subagent" or "internal"; empty when absent.

func (*SessionMeta) SpawnPath

func (m *SessionMeta) SpawnPath() string

SpawnPath returns the agent path a MultiAgentV2 thread was spawned at, which its parent's spawn_agent output names: the thread_spawn source's agent_path, or the meta's own.

func (*SessionMeta) SubAgent

func (m *SessionMeta) SubAgent() (kind string, spawn *ThreadSpawn)

SubAgent returns the source of a thread spawned by another, with the sub-agent's kind ("thread_spawn", "review", "compact", "memory_consolidation" or another), or nil when the thread is no sub-agent.

func (*SessionMeta) UnmarshalJSON

func (m *SessionMeta) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the meta, keeping undeclared members.

type Skip

type Skip struct {
	Path string
	Err  error
}

Skip is a rollout or directory an index left out, and why.

type Thread

type Thread struct {
	// ID is the thread's id; Parent the thread that spawned it, or "".
	ID, Parent string
	// AgentPath is the MultiAgentV2 path it was spawned at, or "".
	AgentPath string
	Path      string
}

Thread is one rollout as its session meta describes it.

type ThreadSpawn

type ThreadSpawn struct {
	ParentThreadID string `json:"parent_thread_id"`
	Depth          int    `json:"depth"`
	AgentPath      string `json:"agent_path"`
	AgentNickname  string `json:"agent_nickname"`
	AgentRole      string `json:"agent_role"`
}

ThreadSpawn is a sub-agent's source: the thread that spawned it.

type TokenUsage

type TokenUsage struct {
	InputTokens           int64 `json:"input_tokens"`
	CachedInputTokens     int64 `json:"cached_input_tokens"`
	CacheWriteInputTokens int64 `json:"cache_write_input_tokens"`
	OutputTokens          int64 `json:"output_tokens"`
	ReasoningOutputTokens int64 `json:"reasoning_output_tokens"`
	TotalTokens           int64 `json:"total_tokens"`

	Members
}

TokenUsage is Codex's token accounting for one response or a total. InputTokens counts the cached input among it, as OpenAI counts it.

func (TokenUsage) MarshalJSON

func (u TokenUsage) MarshalJSON() ([]byte, error)

MarshalJSON writes usage back as it was read.

func (*TokenUsage) UnmarshalJSON

func (u *TokenUsage) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes usage, keeping undeclared members.

type TokenUsageInfo

type TokenUsageInfo struct {
	TotalTokenUsage    *TokenUsage `json:"total_token_usage"`
	LastTokenUsage     *TokenUsage `json:"last_token_usage"`
	ModelContextWindow *int64      `json:"model_context_window"`

	Members
}

TokenUsageInfo is a token_count event's usage: the thread's running total and the last response's.

func (TokenUsageInfo) MarshalJSON

func (u TokenUsageInfo) MarshalJSON() ([]byte, error)

MarshalJSON writes the usage info back as it was read.

func (*TokenUsageInfo) UnmarshalJSON

func (u *TokenUsageInfo) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the usage info, keeping undeclared members.

type TokenUsageRecord

type TokenUsageRecord struct {
	ThreadID         string      `json:"thread_id"`
	TurnID           string      `json:"turn_id"`
	SessionID        string      `json:"session_id"`
	RootTurnID       string      `json:"root_turn_id"`
	ResponseID       string      `json:"response_id"`
	Usage            *TokenUsage `json:"usage"`
	TurnTokenUsage   *TokenUsage `json:"turn_token_usage"`
	ThreadTokenUsage *TokenUsage `json:"thread_token_usage"`

	Members
}

TokenUsageRecord is one completed response's usage, with the response id, which newer rollouts write as a line of its own.

func (TokenUsageRecord) MarshalJSON

func (r TokenUsageRecord) MarshalJSON() ([]byte, error)

MarshalJSON writes the record back as it was read.

func (*TokenUsageRecord) UnmarshalJSON

func (r *TokenUsageRecord) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the record, keeping undeclared members.

type TurnContext

type TurnContext struct {
	TurnID            string          `json:"turn_id"`
	RootTurnID        string          `json:"root_turn_id"`
	CWD               string          `json:"cwd"`
	ApprovalPolicy    json.RawMessage `json:"approval_policy"`
	SandboxPolicy     json.RawMessage `json:"sandbox_policy"`
	PermissionProfile json.RawMessage `json:"permission_profile"`
	Model             string          `json:"model"`
	// Effort is the reasoning effort: none, minimal, low, medium, high,
	// xhigh, or absent for the model's default.
	Effort string `json:"effort"`
	// Summary is the reasoning summary setting: auto, concise, detailed
	// or none.
	Summary           json.RawMessage `json:"summary"`
	CollaborationMode json.RawMessage `json:"collaboration_mode"`
	// UserInstructions and DeveloperInstructions are what versions of
	// early 2026 recorded here; the text the model saw is in the
	// developer and user message items.
	UserInstructions      *string `json:"user_instructions"`
	DeveloperInstructions *string `json:"developer_instructions"`
	// TruncationPolicy is how tool output was cut before it was sent,
	// {"mode":"bytes"|"tokens","limit":n}, which those versions recorded.
	TruncationPolicy json.RawMessage `json:"truncation_policy"`

	Members
}

TurnContext is the settings of one turn, written once per user turn and after a compaction re-established them: a snapshot, not a delta.

func (TurnContext) MarshalJSON

func (t TurnContext) MarshalJSON() ([]byte, error)

MarshalJSON writes the turn context back as it was read.

func (*TurnContext) SummaryMode

func (t *TurnContext) SummaryMode() string

SummaryMode returns the reasoning summary setting when it is a string.

func (*TurnContext) Truncation

func (t *TurnContext) Truncation() (mode string, limit int64, ok bool)

Truncation returns the turn's tool output truncation policy, when it recorded one.

func (*TurnContext) UnmarshalJSON

func (t *TurnContext) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the turn context, keeping undeclared members.

Directories

Path Synopsis
Package convert converts Codex CLI rollouts into the Agent Session Format.
Package convert converts Codex CLI rollouts into the Agent Session Format.

Jump to

Keyboard shortcuts

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