codex

package
v0.186.5 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: Apache-2.0 Imports: 27 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 codex reads OpenAI Codex's session transcripts.

Codex is the easiest of the three agents to observe. It writes one JSONL "rollout" file per session under $CODEX_HOME/sessions/YYYY/MM/DD/ (moved to $CODEX_HOME/archived_sessions/ when the thread is archived), and that file already carries everything Caprock stores: the session id and working directory, the model, per-turn token counts split by kind, tool calls with their arguments, and the plan-limit windows. Nothing has to be installed, no config is rewritten, and no process is signalled — the observation is a read of files Codex was going to write anyway.

The two things worth knowing before changing anything here were measured against 100 real transcripts, not inferred from documentation:

  • `token_count` carries both a running `total_token_usage` and a per-turn `last_token_usage`, and the same values are frequently emitted twice in a row. Summing `last` therefore double-counts: on one real session it gave 261,111 tokens against a true 137,739. Deltas are taken from the *cumulative* field instead, which is monotonic in every transcript checked and reproduces the final total exactly on all 92 sessions that carry one.

  • Codex reports tokens but never a cost. Unlike OpenCode, whose own figure Caprock carries through, Codex sessions are priced by our own table — which is why pricing.json had to grow OpenAI rows (see .ai/19-codex.md and pricing/pricing.json).

Index

Constants

View Source
const Agent = "codex"

Agent is the value written to sessions.agent for Codex sessions.

View Source
const EnvDir = "CAPROCK_CODEX_DIR"

EnvDir overrides the transcript roots with one directory.

View Source
const EnvHome = "CODEX_HOME"

EnvHome is Codex's own override of its state directory.

View Source
const MaxToolOutput = 8000

MaxToolOutput caps the tool output kept per call, in runes. Codex's outputs are long — `exec` asks for up to 15,000 tokens — and every one is stored, so the cap bounds the database rather than the screen. Measured on the owner's 16,152 outputs (2026-10-09): 107MB of JSON at a 32KiB cap, 47MB at 8KiB.

Variables

View Source
var ErrNotASession = errors.New("codex: not a rollout transcript")

ErrNotASession is returned for a file with no session_meta record.

Functions

func Available

func Available() bool

Available reports whether Codex transcripts exist on this machine.

func ConfiguredModel added in v0.70.0

func ConfiguredModel() string

ConfiguredModel is the `model = "…"` set at the top of `$CODEX_HOME/config.toml` — what a session started without -m runs on — or "" when none is set. Only the top-level key is read: a `model` inside a [profile] table applies to that profile, not to a plain start.

func Dirs added in v0.63.0

func Dirs() []string

Dirs are the roots Codex writes rollout transcripts under: `sessions/` (YYYY/MM/DD/rollout-*.jsonl) and `archived_sessions/`, where archiving a thread moves its rollout — a rename into one flat directory, the file itself unchanged (codex-rs thread-store, archive_thread.rs). An archived session is still work that was done and paid for; reading only `sessions/` never counted one archived before Caprock was installed, and lost it from any total rebuilt from the transcripts afterwards.

CAPROCK_CODEX_DIR overrides both with a single root, for tests and for anyone whose transcripts live somewhere unusual.

func Home added in v0.63.0

func Home() string

Home is Codex's state directory: `$CODEX_HOME` when it is set, otherwise `~/.codex`. Codex documents CODEX_HOME as the override for everything it keeps locally, transcripts included, so a user who set it has no `~/.codex/sessions` for us to find — reading only the default path missed every one of their sessions.

It is the same path on every platform: Codex uses the home directory directly, with no XDG or %APPDATA% branching, so there is nothing to switch on here.

func IsTUI added in v0.70.0

func IsTUI(originator string) bool

IsTUI reports whether a rollout was written by the Codex terminal UI — the program Caprock starts — rather than the desktop app or the IDE extension. "codex-tui" is what 0.154–0.160 write; "codex_cli_rs" is the older name.

func LegacyKey added in v0.64.0

func LegacyKey(line int64, kind string) string

LegacyKey is the key versions before subagentKey gave the record on this line — the one a subagent's rows were stored under inside its parent's session, and the one the repair finds them by.

func ReadThreadNames added in v0.59.0

func ReadThreadNames(ctx context.Context, path string) (map[string]ThreadName, error)

ReadThreadNames reads every thread's name and first message. A database whose `threads` table lacks a column is a Codex release this was not built against, and is reported as an error rather than half-read.

func StateDB added in v0.59.0

func StateDB(sessionsDir string) string

StateDB returns the newest `state_<N>.sqlite` in the Codex home that holds the sessions directory, or "" when there is none. The number is Codex's own schema generation; the newest one is the one it writes.

Types

type Ingester

type Ingester struct {

	// Link files a thread under the Caprock session that started it, when
	// Caprock did (see internal/sessionlink). Nil leaves every thread under
	// its own id, which is what every session not started from the dashboard
	// is anyway.
	Link *sessionlink.Linker

	// Subscription is set on an importer reading a subscription's CODEX_HOME
	// rather than the user's own (ADR-048): its sessions are recorded on it,
	// its plan windows are stored under LimitPrefix, and the files it has read
	// are remembered under a key of their own. Empty is the Default sign-in.
	Subscription string
	// LimitPrefix replaces store.CodexRateLimitPrefix when set.
	LimitPrefix string

	// OnTurnDone is told, once per finished request, that a thread a
	// person started (not a subagent's, not an imported one) finished its
	// request and nothing runs after it (Session.TurnDoneAt), with the
	// session it is stored under. Called on Run's goroutine; nil tells no
	// one. The daemon's end_when_done reads it (daemon/enddone.go).
	OnTurnDone func(sessionID string, at time.Time)
	// contains filtered or unexported fields
}

Ingester copies Codex's rollout transcripts into Caprock's store.

It polls rather than watches. The transcripts are append-only files, so a poll that re-reads one it has already seen costs a read and produces nothing: every event carries a key derived from the record's ordinal, and `(session_id, key)` is unique in the store.

Only files whose modification time moved are re-read, which on a machine with a hundred transcripts is one stat per file per tick and no parsing at all. A file that grew is read from where the last pass stopped (see tail), and only what the new lines added is offered to the store.

func NewIngester

func NewIngester(dirs []string, rec *rollup.Recorder, log *slog.Logger, every time.Duration) *Ingester

NewIngester builds an ingester over Codex's transcript roots (see Dirs). The first root is the one whose parent holds Codex's state index (§ Names).

func (*Ingester) Kick added in v0.117.2

func (in *Ingester) Kick()

Kick asks for a pass now instead of at the next tick: input was just typed into a Codex session Caprock holds, and its transcript is about to say so. A pass already asked for and not yet run is enough; this never blocks.

func (*Ingester) Run

func (in *Ingester) Run(ctx context.Context) error

Run polls until the context is cancelled. It imports once immediately so a fresh daemon shows history straight away rather than after the first tick.

func (*Ingester) Stats

func (in *Ingester) Stats() Stats

Stats returns a snapshot of what has been imported.

func (*Ingester) Work added in v0.134.0

func (in *Ingester) Work() Work

Work returns what the passes have read and offered so far.

type LimitWindow added in v0.63.0

type LimitWindow struct {
	Minutes     int
	UsedPercent float64
	// ResetsAt is unix seconds; 0 where Codex wrote null (CLI 0.4x did).
	ResetsAt int64
}

LimitWindow is one window as Codex reports it.

type Limits

type Limits struct {
	// At is when Codex wrote the sample, not when Caprock read it — which can
	// be days later for a transcript imported on first run.
	At      time.Time
	Windows []LimitWindow
}

Limits is the plan-limit sample a transcript last recorded.

The windows are a list, not a fixed primary/secondary pair, because which window sits in which slot depends on the plan. Measured on the 72 of 176 transcripts that carry limits on the owner's machine: a `plus` account writes `primary` = 300 minutes and `secondary` = 10080; a `prolite` account writes `primary` = 10080 and `secondary` = null — it has no five-hour window at all. Reading `primary` as "the 5-hour window" would have put a weekly figure under a five-hour label.

type Model added in v0.70.0

type Model struct {
	ID    string `json:"id"`
	Label string `json:"label"`
}

Model is one model the Codex CLI offers in its own picker.

func ListedModels added in v0.70.0

func ListedModels() []Model

ListedModels is the models Codex itself lists, read from the catalog it caches at `$CODEX_HOME/models_cache.json`, in the order of its own picker.

Read from the CLI's cache rather than written into Caprock: the catalog is per account and changes with Codex releases, and the Claude and Gemini lists in the dialog were both wrong the first time they were written from memory. Only `visibility: "list"` entries are offered — the rest are Codex's own machinery (`codex-auto-review`) or hidden. Empty when there is no cache.

type Prompt added in v0.92.0

type Prompt struct {
	At   time.Time
	Key  string
	Line int64
	// Text is the message's text parts joined with a newline, clipped like
	// Claude Code's prose. An attached image adds nothing.
	Text string
}

Prompt is one message the person typed.

type Session

type Session struct {
	ID         string
	Path       string
	Cwd        string
	Model      string
	CLIVersion string
	// Originator is what launched the session ("Codex Desktop", "codex_cli_rs").
	// Kept because a desktop session and a terminal session are different
	// things to a reader looking at where their money went.
	Originator string
	StartedAt  time.Time
	Turns      []Turn
	Tools      []ToolCall
	// Prompts are what the person typed (§ Chat in .ai/19-codex.md). Empty for
	// imported and subagent threads: the first replays another agent's
	// session, the second its parent's history and a brief its parent wrote.
	Prompts []Prompt
	// Results are what each tool call handed back, paired to its call by
	// CallID.
	Results []ToolResult
	// Limits is the most recent plan-limit sample in the transcript, when the
	// session carried one.
	Limits *Limits
	// Imported marks a thread Codex built by importing another agent's
	// session (its "import from Claude Code"): every turn id is
	// `external-import-turn-N` and the replay ends on an
	// `<EXTERNAL SESSION IMPORTED>` message. Its assistant messages are that
	// other agent's prose and tool calls replayed as text, which Caprock
	// already holds from the original transcript, so none is kept as Codex's.
	Imported bool
	// Subagent marks a thread Codex spawned for a sub-task or for its guardian
	// reviewer (`session_meta.source.subagent`). Such a file opens with a copy
	// of its parent's history and carries the parent's session id, so ID is
	// the parent's and ThreadID the subagent's own.
	Subagent bool
	// TurnDoneAt is when the newest request Codex finished ended — its
	// `task_complete` — while no request runs after it; zero while one
	// runs, after a `turn_aborted`, and before any finished. It is Codex's
	// "the turn ended", read for end_when_done (Ingester.OnTurnDone).
	TurnDoneAt time.Time
	// ThreadID is this file's own thread id (`session_meta.id` of its first
	// record). For a session a person started it equals ID; for a subagent it
	// names the subagent, and its event keys carry it (see subagentKey).
	ThreadID string
}

Session is one Codex rollout transcript, parsed.

func Parse

func Parse(r io.Reader, path string) (*Session, error)

Parse reads a rollout transcript from r. path is used only for the returned Session's Path field.

The record-by-record work lives in parser (parser.go), which a growing file keeps between reads (tail.go); Parse is that parser run once over the whole file, and is the reference every incremental read is tested against.

func ParseFile

func ParseFile(path string) (*Session, error)

ParseFile reads one rollout transcript.

A malformed line is skipped rather than failing the file: these are written by another program while it runs, so the last line of a live session is routinely a partial write, and refusing the whole transcript for it would mean a session is invisible until it ends.

type Stats

type Stats struct {
	Sessions int `json:"sessions"`
	Events   int `json:"events"`
	Unpriced int `json:"unpriced,omitempty"`
	// Repriced counts turns that were stored before the model could be read
	// and have since been given one from their transcript.
	Repriced int   `json:"repriced,omitempty"`
	LastPoll int64 `json:"last_poll_ms,omitempty"`
}

Stats is what the daemon reports about Codex ingest.

type ThreadName added in v0.59.0

type ThreadName struct {
	Name         string
	FirstMessage string
}

ThreadName is Codex's name for one thread.

type ToolCall

type ToolCall struct {
	At   time.Time
	Key  string
	Line int64
	Name string
	// Input is the raw argument payload, stored so the dashboard can show what
	// a call actually did.
	Input string
	// TurnKey is the Key of the turn that paid for this call: the first turn
	// recorded after it. Codex writes a response's items (reasoning, message,
	// function calls) first and the token_count that bills that response
	// after them, so the call's turn is the next one in the file. Empty when
	// no turn followed, as at the end of an aborted response.
	TurnKey string
	// CallID is Codex's own id for the call, which its output record repeats.
	// Stored as the call's `tool_use_id`, the key Claude Code pairs a call
	// with its result by.
	CallID string
}

ToolCall is one tool invocation.

type ToolResult added in v0.92.0

type ToolResult struct {
	At     time.Time
	Key    string
	Line   int64
	CallID string
	// Name is the call's tool, from the call record with the same CallID; ""
	// when the call is not in the file.
	Name string
	// Output is the text handed back, clipped to MaxToolOutput runes.
	Output string
	// Failed is set when the output says so: an `exec` script that failed, a
	// shell command with a non-zero exit code, or a call Codex refused.
	Failed bool
	// ExitCode is the shell's exit code where Codex recorded one (the
	// `shell` tool's metadata); nil elsewhere — an `exec` script reports only
	// whether the script itself completed.
	ExitCode *int
	// Interrupted marks a call whose request ended — Codex wrote
	// `turn_aborted` or `task_complete`, or the next request started — with
	// no output record for it. Nothing ran on after that point, so the call
	// is over, not running; Output is empty. Line is the call's own line, so
	// the key is fixed however many times the file is read.
	Interrupted bool
}

ToolResult is what one tool call handed back: a `custom_tool_call_output` or `function_call_output` record.

type Transcript

type Transcript struct {
	Path     string
	Modified time.Time
	Size     int64
}

Transcript is a rollout file on disk, before it is parsed.

func List

func List(dir string) ([]Transcript, error)

List finds every rollout transcript under dir, newest first.

It walks rather than globbing a fixed depth: the layout is YYYY/MM/DD today, and a walk keeps working if Codex changes it. Directories it cannot read are skipped rather than failing the scan — a transcript root is someone else's directory and may contain anything.

func ListAll added in v0.63.0

func ListAll(dirs []string) ([]Transcript, error)

ListAll lists the transcripts under every root, newest first. A root that does not exist contributes nothing: most machines have never archived a Codex thread, so `archived_sessions/` is usually absent.

type Turn

type Turn struct {
	At time.Time
	// Key is stable across re-reads: the transcript is append-only, so the
	// line of the record that produced the turn identifies it forever.
	Key string
	// Line is that record's line number, kept so the key an earlier version
	// gave a subagent's turn can be rebuilt (LegacyKey).
	Line       int64
	In         int64
	CacheRead  int64
	CacheWrite int64
	Out        int64
	// Reasoning tokens are billed as output and are already included in Out.
	// Carried separately only so a reader can see the split.
	Reasoning int64
	// TotalOnly marks a turn whose transcript reported a total with no
	// breakdown, so `In` holds that total rather than a measured input figure.
	// Its cost is therefore an upper bound: any part of it that was really a
	// cached read would have been billed at a tenth.
	TotalOnly bool
	// Text is the prose the assistant wrote in this turn — the `output_text`
	// of the assistant messages the sampling request produced — clipped like
	// Claude Code's (ingest.ClipAssistantText). Empty for a turn that only
	// called tools, and for imported and subagent threads (see Session).
	Text string
}

Turn is one assistant turn's token usage, already reduced to a delta.

type Work added in v0.134.0

type Work struct {
	BytesRead int64 `json:"bytes_read"`
	Records   int64 `json:"records_decoded"`
	Offered   int64 `json:"offered"`
	Stored    int64 `json:"stored"`
	// Last is the most recent pass alone.
	Last *Work `json:"last,omitempty"`
}

Work is what the importer's passes have read and offered to the store, in total and in the last pass. Offered minus Stored is what the store turned away as already held: the waste a full re-read of a growing file paid.

Jump to

Keyboard shortcuts

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