codexrunner

package
v1.40.2 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 10 Imported by: ? 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 codexrunner executes Codex CLI turns without depending on qmax-code's terminal or on any private cloud implementation.

A first turn invokes "codex exec [--model <model>] --json -". A continued turn invokes "codex exec resume [--model <model>] --json <thread_id> -" with a validated, explicit thread ID. When a model is supplied, it is validated against an exact allowlist before process start and is preserved in durable checkpoints. Prompts are supplied only through stdin. Raw provider events and diagnostics are never exposed through the structural event interfaces.

Because "codex exec resume" resolves a thread from the local Codex session store, a checkpoint also records the path of the rollout backing its thread. The package locates that file and nothing more: it never reads, uploads, or logs a rollout. Hosts that move a session between sandboxes are responsible for shipping the file and for restoring it before they resume, and Continuity.Restore refuses a checkpoint whose rollout is not present rather than resuming into a thread this box cannot reconstruct.

Index

Constants

View Source
const (
	// DefaultModel is the deterministic Codex model selected by QualityMax when
	// a product client chooses Auto or has no saved preference.
	DefaultModel = "gpt-5.6-terra"
)

Variables

View Source
var (
	// ErrInvalidThreadID means a caller or stream supplied a non-canonical UUID.
	ErrInvalidThreadID = errors.New("codex runner: invalid thread ID")
	// ErrInvalidRolloutPath means a checkpoint carried a rollout reference that
	// is not an absolute path, so it cannot be resolved on another box.
	ErrInvalidRolloutPath = errors.New("codex runner: invalid rollout path")
	// ErrRolloutUnavailable means a checkpoint named a rollout that is not
	// present on this box, which is the expected result of restoring a
	// checkpoint into a replacement sandbox. Callers must surface a recovery
	// reason and start a new thread rather than resume into an empty one.
	ErrRolloutUnavailable = errors.New("codex runner: checkpoint rollout unavailable")
	// ErrThreadMismatch means a resumed stream identified a different thread.
	ErrThreadMismatch = errors.New("codex runner: resumed thread does not match checkpoint")
	// ErrMissingThreadID means the stream ended without a thread.started event.
	ErrMissingThreadID = errors.New("codex runner: thread ID missing from stream")
	// ErrMalformedStream means stdout was not a valid Codex JSONL event stream.
	ErrMalformedStream = errors.New("codex runner: malformed event stream")
	// ErrStart means the Codex process could not be started.
	ErrStart = errors.New("codex runner: process start failed")
	// ErrProcess means Codex exited unsuccessfully.
	ErrProcess = errors.New("codex runner: process failed")
	// ErrModelUnavailable means Codex rejected the selected model. Raw CLI
	// diagnostics are never returned because they may contain provider data.
	ErrModelUnavailable = errors.New("codex runner: selected model unavailable")
	// ErrAuthentication means Codex reported that its local login is missing,
	// expired, or unauthorized.
	ErrAuthentication = errors.New("codex runner: authentication required")
	// ErrEventSink means a structural event consumer rejected an event.
	ErrEventSink = errors.New("codex runner: event sink failed")
	// ErrCheckpointSink means a checkpoint consumer rejected a checkpoint.
	ErrCheckpointSink = errors.New("codex runner: checkpoint sink failed")
	// ErrPresenter means the response presenter rejected an update.
	ErrPresenter = errors.New("codex runner: presenter failed")
	// ErrRunnerUnavailable means a Continuity was created without a Runner.
	ErrRunnerUnavailable = errors.New("codex runner: runner unavailable")
)
View Source
var (
	// ErrInvalidModel means a caller supplied a model outside the exact product
	// allowlist. The value is never forwarded to the process boundary.
	ErrInvalidModel = errors.New("codex runner: invalid model")
)

Functions

func SupportedModels

func SupportedModels() []string

SupportedModels returns a defensive copy of the exact Codex model allowlist shared by the QualityMax coding-agent contract.

func ValidateModel

func ValidateModel(model string) error

ValidateModel accepts only exact allowlisted model IDs. Empty and "auto" are product-level choices that must be resolved before a durable handoff.

Types

type Cancellation

type Cancellation interface {
	context.Context
}

Cancellation is the runner's cancellation boundary. A standard context.Context satisfies it, preserving deadlines and process teardown without coupling callers to a terminal implementation.

type Checkpoint

type Checkpoint struct {
	ThreadID string
	Model    string
	// RolloutPath is the local Codex rollout for ThreadID, or "" when the
	// executor cannot locate one. Callers upload it and record the result as
	// checkpoint.codex.rollout_ref; this package never reads or ships the
	// file itself.
	RolloutPath string
}

Checkpoint is the minimum durable state required to continue a Codex thread on the same exact model.

ThreadID alone is only sufficient on the box that produced it: "codex exec resume" resolves a thread from the local Codex session store, so a thread ID restored into a fresh sandbox names a rollout that no longer exists there. RolloutPath is what makes the thread portable.

type CheckpointSink

type CheckpointSink interface {
	OnCheckpoint(context.Context, Checkpoint) error
}

CheckpointSink persists a validated checkpoint as soon as thread.started is observed, including when the turn later fails or is canceled.

type CheckpointSinkFunc

type CheckpointSinkFunc func(context.Context, Checkpoint) error

CheckpointSinkFunc adapts a function to CheckpointSink.

func (CheckpointSinkFunc) OnCheckpoint

func (f CheckpointSinkFunc) OnCheckpoint(ctx context.Context, checkpoint Checkpoint) error

OnCheckpoint implements CheckpointSink.

type CodexHomeLocator

type CodexHomeLocator struct {
	// Home overrides the Codex home directory. Empty resolves $CODEX_HOME,
	// then $HOME/.codex.
	Home string
}

CodexHomeLocator finds rollouts in a Codex session store. Codex writes one rollout per thread under sessions/<yyyy>/<mm>/<dd>/rollout-<timestamp>-<thread_id>.jsonl.

func (CodexHomeLocator) LocateRollout

func (locator CodexHomeLocator) LocateRollout(threadID string) string

LocateRollout implements RolloutLocator. It returns an absolute path, or "" when the store is absent or holds no rollout for threadID.

type Command

type Command struct {
	Executable       string
	Args             []string
	Stdin            io.Reader
	WorkingDirectory string
}

Command describes one direct process invocation. Stdin carries the prompt; Args is always one of the fixed, allowlisted command shapes documented by this package. Stderr is deliberately absent so raw diagnostics cannot be logged.

type Continuity

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

Continuity serializes turns and remembers only the exact validated thread and model checkpoint. It stores no prompts, responses, source, or provider payloads. Durable callers should also provide Hooks.Checkpoints on every turn.

func NewContinuity

func NewContinuity(runner *Runner) *Continuity

NewContinuity creates an empty continuity adapter for runner.

func (*Continuity) Checkpoint

func (continuity *Continuity) Checkpoint() Checkpoint

Checkpoint returns the current exact continuity state.

func (*Continuity) Reset

func (continuity *Continuity) Reset()

Reset forgets the current thread so the next Run starts a new one.

func (*Continuity) Restore

func (continuity *Continuity) Restore(checkpoint Checkpoint) error

Restore validates and installs a durable checkpoint. An empty checkpoint is equivalent to Reset.

A checkpoint naming a rollout that is not present on this box is refused with ErrRolloutUnavailable and not installed, so a replacement sandbox cannot resume into a thread whose transcript it does not have. Callers recover by reporting the reason and restoring the same checkpoint with RolloutPath cleared, which starts a new thread.

func (*Continuity) Run

func (continuity *Continuity) Run(ctx Cancellation, prompt string, hooks Hooks) (Result, error)

Run executes a turn using the current checkpoint and atomically adopts the validated checkpoint emitted by the runner, even if the turn later fails.

type Event

type Event struct {
	Kind  EventKind
	Usage Usage
}

Event is safe for lifecycle observation and metrics. It never contains raw provider content.

type EventKind

type EventKind uint8

EventKind identifies a safe structural lifecycle event. Events intentionally contain no prompt, response, source, tool arguments, provider message, or raw JSON payload.

const (
	EventThreadStarted EventKind = iota + 1
	EventTurnStarted
	EventAssistantMessage
	EventTurnCompleted
	EventProviderError
	EventPlanLimit
)

type EventSink

type EventSink interface {
	OnEvent(context.Context, Event) error
}

EventSink consumes structural runner events.

type EventSinkFunc

type EventSinkFunc func(context.Context, Event) error

EventSinkFunc adapts a function to EventSink.

func (EventSinkFunc) OnEvent

func (f EventSinkFunc) OnEvent(ctx context.Context, event Event) error

OnEvent implements EventSink.

type Hooks

type Hooks struct {
	Events      EventSink
	Checkpoints CheckpointSink
	Presenter   Presenter
}

Hooks are optional per-turn observation and presentation boundaries.

type OSExecutor

type OSExecutor struct{}

OSExecutor starts the local Codex executable directly, without a shell. Stderr is retained only in a small private buffer and reduced to safe error categories; raw provider diagnostics never cross the process boundary.

func (OSExecutor) Start

func (OSExecutor) Start(ctx context.Context, command Command) (ToolProcess, error)

Start implements ToolExecutor.

type Options

type Options struct {
	Executable       string
	WorkingDirectory string
	Executor         ToolExecutor
	// Rollouts resolves the local rollout backing a thread. A nil locator uses
	// CodexHomeLocator.
	Rollouts RolloutLocator
}

Options configures an immutable Runner.

type Presentation

type Presentation struct {
	Kind PresentationKind
	Text string
}

Presentation is the only callback value that may contain response or tool content.

type PresentationKind

type PresentationKind uint8

PresentationKind distinguishes response text from a sanitized provider notice. PresentationText contains model output and must be rendered directly, not logged or copied into metrics.

const (
	PresentationText PresentationKind = iota + 1
	PresentationPlanLimit
	// PresentationTool carries exposed tool activity only to the content boundary.
	PresentationTool
)

type Presenter

type Presenter interface {
	Present(context.Context, Presentation) error
}

Presenter is the terminal-neutral rendering boundary. Cloud callers may omit it and consume Result.Response through their protected artifact boundary.

type PresenterFunc

type PresenterFunc func(context.Context, Presentation) error

PresenterFunc adapts a function to Presenter.

func (PresenterFunc) Present

func (f PresenterFunc) Present(ctx context.Context, presentation Presentation) error

Present implements Presenter.

type Result

type Result struct {
	ThreadID  string
	Model     string
	Response  string
	Usage     Usage
	Canceled  bool
	PlanLimit bool
	// RolloutPath mirrors Checkpoint.RolloutPath for the thread this turn ran
	// on, so a caller adopting a Result as durable state does not silently
	// drop the rollout reference the checkpoint sink already received.
	RolloutPath string
}

Result contains the exact validated Codex thread ID, selected model, and response. Response is transcript data and must not be logged or placed in workflow history.

type RolloutLocator

type RolloutLocator interface {
	LocateRollout(threadID string) string
}

RolloutLocator resolves the local Codex rollout file backing a validated thread ID. It returns an empty path when no rollout can be found, which the runner records as "not locatable" rather than as an error: a checkpoint without a rollout is still a usable same-sandbox checkpoint.

Implementations must not read or log rollout contents. A rollout is a full transcript, and this package never moves transcript data outside Presenter.

type RolloutLocatorFunc

type RolloutLocatorFunc func(threadID string) string

RolloutLocatorFunc adapts a function to RolloutLocator.

func (RolloutLocatorFunc) LocateRollout

func (f RolloutLocatorFunc) LocateRollout(threadID string) string

LocateRollout implements RolloutLocator.

type Runner

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

Runner executes terminal-neutral Codex turns.

func New

func New(options Options) *Runner

New returns a runner. An empty executable uses "codex", a nil executor uses the local OS process implementation, and a nil rollout locator uses CodexHomeLocator.

func (*Runner) Run

func (r *Runner) Run(ctx Cancellation, turn Turn) (Result, error)

Run executes one turn. Cancellation is controlled exclusively by ctx.

type ToolExecutor

type ToolExecutor interface {
	Start(context.Context, Command) (ToolProcess, error)
}

ToolExecutor starts Codex without coupling the runner to a terminal or a particular process host.

type ToolProcess

type ToolProcess interface {
	Stdout() io.Reader
	Wait() error
}

ToolProcess is the minimal process boundary required by Runner.

type Turn

type Turn struct {
	Prompt   string
	ThreadID string
	Model    string
	Hooks    Hooks
}

Turn contains the sensitive prompt, an optional exact continuity ID, and an optional exact model. When Model is present, it must be allowlisted and is passed on both initial and resumed commands. Callers must not log Prompt.

type Usage

type Usage struct {
	InputTokens  int
	OutputTokens int
}

Usage is aggregate token accounting reported by Codex for one turn.

Jump to

Keyboard shortcuts

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