codex

package
v0.16.196 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: Apache-2.0 Imports: 28 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 is the runtime's side of the OpenAI Codex CLI: whether it runs in a pane and which session, what its rollout transcript says about the turn, what its hook payloads mean, and the launcher line and arguments that start or resume it.

Index

Constants

View Source
const (
	ProviderID  = agents.Codex
	DisplayName = "Codex"
	PanelType   = agents.CodexPanel
	Binary      = "codex"
)
View Source
const (

	// StaleInterrupted is the quiet window after an agent message, StaleAwaitingAPI after a prompt.
	StaleInterrupted = 20_000
	StaleAwaitingAPI = 90_000
)
View Source
const GuardTimeoutSeconds = 15

GuardTimeoutSeconds is how long Codex waits for the apps' guard (apps.GuardTimeoutSeconds).

View Source
const (
	// ScanDays is how many local days of session folders a lookup reads, today first.
	ScanDays = 30
)

Variables

View Source
var ContainerSandboxArgs = []string{"-c", `sandbox_mode="danger-full-access"`, "-c", `approval_policy="never"`}

ContainerSandboxArgs let Codex run commands without its own sandbox, which needs user namespaces a container does not give; the container is the boundary.

View Source
var ErrNeedsStart = errors.New("a launch with apps needs RuntimeStart: its arguments alone would leave out the wall")

ErrNeedsStart: a launch with apps was built where only the arguments are kept, which would drop the apps' wall.

View Source
var ErrNoProfiles = errors.New("Backend profiles are not available on this machine")

ErrNoProfiles: a launch names a backend profile and this deployment has none.

View Source
var HookEvents = []string{"SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "Stop", "PermissionRequest"}

Hook events the runtime registers with Codex.

Functions

func AppServerArgs added in v0.16.154

func AppServerArgs(s agents.CodexAppServer, tokenEnv string) []string

AppServerArgs are the `-c` flags of one MCP server of an app. The headers that carry the launch's token read it from tokenEnv, so it is on no command line; like the runtime's own, the server's tools need no approval of Codex's (the apps' guard decides every call).

func EnsureLauncher

func EnsureLauncher(path string, content []byte) error

EnsureLauncher writes the launcher script (0700) when it is missing or differs, and narrows its mode when equal.

func LauncherFlags

func LauncherFlags(l *agents.Launch) ([]string, error)

LauncherFlags are `--model '<m>' --effort '<e>'` for the launcher script, which forwards them; checked first.

func LauncherScript

func LauncherScript(c LauncherScriptConfig) []byte

LauncherScript is the Node script the pane runs: it asks the runtime for codex's arguments (POST LaunchArgsPath with {workspaceId, resumeSessionId, forkSessionId, model, effort}), appends the prompt, and runs codex with the token in TokenEnv, mirroring its exit.

func LoginMode added in v0.16.5

func LoginMode(text string) string

LoginMode reads `codex login status`'s text: "Logged in using ChatGPT", "Logged in using an API key - sk-…".

func MCPArgs

func MCPArgs(m MCP) []string

MCPArgs configures a server already authorized by the runtime or by the person's connections. Server-level approval avoids a hidden terminal prompt in otherwise unattended conversations.

func MCPURL

func MCPURL(port int, path string) string

MCPURL is the address of the runtime's MCP route on loopback.

func MatchesProcess

func MatchesProcess(command string, args []string) bool

MatchesProcess tells Codex by a pane's foreground command and, for node, the process's arguments.

func ParsePaneTitle

func ParsePaneTitle(string) *string

ParsePaneTitle: Codex sets no conversation title in the pane.

func ReadHistoryStats

func ReadHistoryStats(path string) agents.HistoryStats

ReadHistoryStats reads a finished turn from the rollout's last 128 KiB, newest line first: prompt and answer, their times, the turn's duration, the tools used and the files a patch or an edit touched.

func ResumeID

func ResumeID(args string) string

ResumeID is the session a Codex command line resumes (`resume <id>`, `--resume-session-id=<id>`), standing as a word of its own, optionally quoted; "" when none.

func RuntimeLaunchArgs

func RuntimeLaunchArgs(l *agents.Launch) ([]string, error)

RuntimeLaunchArgs are codex's own `-m <model> -c model_reasoning_effort="<e>"` (argv, no shell).

func SessionIDFromPath

func SessionIDFromPath(jsonlPath string) string

SessionIDFromPath is the session id at the end of a rollout file's name, "" when there is none.

func ShouldEmit

func ShouldEmit(payload map[string]any, cliState string) bool

ShouldEmit: a SessionStart that is not a /clear only moves a tab that is inactive or unknown (a resumed Codex mid-turn is not reset to idle); every other event always goes on.

func Status added in v0.16.5

Status is how Codex stands on the machine, from `codex login status` (its exit code says whether it is signed in, its text how). The same login shell and env files as a tab's launch.

func SummarizeFunctionCall

func SummarizeFunctionCall(name string, raw any) string

SummarizeFunctionCall is the one-line description of a tool call (its arguments as the rollout holds them: a JSON string or a value), as the current action and the timeline show it.

func TOMLBasicString

func TOMLBasicString(s string) string

TOMLBasicString encodes text as a one-line TOML basic string (a JSON string is one).

func TailEntries

func TailEntries(path string, size int64) ([]*agents.Obj, error)

TailEntries decodes the complete lines of a rollout's last 128 KiB.

func TranslateEvent

func TranslateEvent(payload map[string]any) *agents.Event

TranslateEvent is the work-state event of a payload's hook_event_name.

Types

type Detector

type Detector struct {
	// Dir is Codex's folder (~/.codex), sessions under sessions/YYYY/MM/DD.
	Dir   string
	Procs proc.Procs
	Match agents.Match
	// Installed is asked only when Dir is missing; nil counts as not installed.
	Installed func() bool
	// Now gives today's local day for the session folders.
	Now func() time.Time
}

Detector looks for Codex under a pane's shell.

func NewDetector

func NewDetector(home string) *Detector

NewDetector looks at the machine's processes and <home>/.codex.

func (*Detector) Detect

func (d *Detector) Detect(children []int, allowCwdFallback bool) agents.SessionInfo

Detect finds the Codex process among the pane shell's children and grandchildren and the session it resumes. With allowCwdFallback (the timeline only) a fresh Codex gets the newest session of its folder that started with it. A new session's id normally comes from the hooks, not from here.

func (*Detector) DirOf added in v0.16.123

func (d *Detector) DirOf(pid int) string

DirOf is the home the Codex process pid uses: its own $CODEX_HOME, else Dir.

func (*Detector) FindSession added in v0.16.123

func (d *Detector) FindSession(id string) (SessionMeta, bool)

FindSession is a session's rollout in any of SessionsRoots.

func (*Detector) IsRunning

func (d *Detector) IsRunning(children []int) bool

IsRunning: one of the shell's children or grandchildren is Codex (its launcher counts).

func (*Detector) SessionsRoot

func (d *Detector) SessionsRoot() string

SessionsRoot holds the session folders.

func (*Detector) SessionsRoots added in v0.16.123

func (d *Detector) SessionsRoots() []string

SessionsRoots are SessionsRoot and the session folders of the homes running Codexes were seen to use instead.

type HookConfig

type HookConfig struct {
	// Script is the hook script Codex runs for every event.
	Script string
	// UserConfig is the person's ~/.codex/config.toml.
	UserConfig string
	// BudgetScript is the hub's limit script (hooksetup); "" adds nothing. It runs after Script on UserPromptSubmit
	// and PreToolUse, where it can stop the chat.
	BudgetScript string
	// contains filtered or unexported fields
}

HookConfig builds the `-c hooks.<Event>=[…]` flags of a Codex launch: the runtime's hook script first, then the person's own valid entries for that event from their config.toml (read only, re-read when it changes). Codex gets its hooks per launch; no file of the person's is written.

func (*HookConfig) Flags

func (h *HookConfig) Flags() (args []string, parseError bool, err error)

Flags are `-c hooks.<Event>=[ours, theirs…]` for every event; parseError reports a config.toml that could not be read as TOML (only the runtime's hook applies then, and the person should be told once).

func (*HookConfig) FlagsWithGuard added in v0.16.154

func (h *HookConfig) FlagsWithGuard(guard string) (args []string, parseError bool, err error)

FlagsWithGuard is Flags with the apps' guard command as the first PreToolUse hook of the launch, before the runtime's own and the person's: the hook comes by `-c` on the launch line, so the agent has no file to edit it out of. "" adds none.

type LaunchConfig

type LaunchConfig struct {
	// LauncherScript is where the launcher script lives (written by EnsureLauncher), LauncherContent its text.
	LauncherScript  string
	LauncherContent []byte
	Hooks           *HookConfig
	// MCP is the runtime's MCP server; its URL needs the port the runtime listens on.
	MCP MCP
	// ExtraMCP gives, at every launch, more servers reached through the runtime with the same token (the person's MCP
	// servers from Settings → Connections); nil adds none.
	ExtraMCP func() []MCP
	// WorkspacePrompt is a workspace's developer-instructions file; nil when workspaces have none.
	WorkspacePrompt func(workspaceID string) string
	// SkipPermissions adds --yolo when it says so.
	SkipPermissions func() bool
	// ContainerSandbox: the runtime runs in a container that is the sandbox, where Codex's own (bubblewrap) cannot start.
	// Codex then runs with sandbox_mode "danger-full-access" and approval_policy "never" instead.
	ContainerSandbox bool
	// PassServiceEnv lets the commands Codex runs see the variables the workspace's services need (BOARDS_TOKEN,
	// ARTIFACTS_TOKEN): by default Codex drops every variable whose name has KEY, SECRET or TOKEN in it. ShellEnvExclude
	// are variables that still stay out (the runtime's own CLI token).
	PassServiceEnv  bool
	ShellEnvExclude []string
	// Profiles points a launch on a backend profile at the vendor; nil refuses such a launch.
	Profiles agents.ProfileLauncher
	// Apps gives a launch with apps their guard, servers, instructions and wall; nil refuses such a launch.
	Apps agents.AppLauncher
}

LaunchConfig is what a Codex launch is built from; the deployment fills it.

func (LaunchConfig) ForkArgs added in v0.15.40

func (c LaunchConfig) ForkArgs(workspaceID, sessionID string, launch *agents.Launch) (args []string, configParseError bool, err error)

ForkArgs are RuntimeArgs that start codex on a fork of the session (`codex fork <id>`): a session of its own that begins with the other's history.

func (LaunchConfig) ForkLauncherLine added in v0.15.40

func (c LaunchConfig) ForkLauncherLine(workspaceID, sessionID string, launch *agents.Launch) (string, error)

ForkLauncherLine is the LauncherLine of a fork of the session: `--fork-session-id <id>`.

func (LaunchConfig) ForkStart added in v0.16.154

func (c LaunchConfig) ForkStart(workspaceID, sessionID string, launch *agents.Launch) (Start, bool, error)

ForkStart is ForkArgs with the words codex runs behind (Start.Prefix).

func (LaunchConfig) LauncherLine

func (c LaunchConfig) LauncherLine(workspaceID, resumeID string, launch *agents.Launch) (string, error)

LauncherLine is what is typed into the pane: `node '<launcher>' [--workspace-id …] [--resume-session-id …] [--model …] [--effort …]`. The launcher script is written first when it differs.

func (LaunchConfig) RuntimeArgs

func (c LaunchConfig) RuntimeArgs(workspaceID, resumeID string, launch *agents.Launch) (args []string, configParseError bool, err error)

RuntimeArgs are the arguments the launcher script receives from the runtime and passes to codex: resume, hooks, the MCP server, hook trust and update check off (their dialogs are invisible to the web composer), the workspace's instructions, permissions, model and effort. ConfigParseError reports an unreadable config.toml.

func (LaunchConfig) RuntimeStart added in v0.16.154

func (c LaunchConfig) RuntimeStart(workspaceID, resumeID string, launch *agents.Launch) (Start, bool, error)

RuntimeStart is RuntimeArgs with the words codex runs behind (Start.Prefix), which a launch with apps has.

type LauncherScriptConfig

type LauncherScriptConfig struct {
	// DataDirs are data folders, relative to the home or absolute; the first that exists is used (the last when none does).
	DataDirs []string
	// PortFile and TokenFile are file names in the data folder.
	PortFile, TokenFile string
	// LaunchArgsPath is the runtime route answering {args}.
	LaunchArgsPath string
	// TokenHeaders carry the token to the route; TokenEnv is the variable codex gets it in.
	TokenHeaders []string
	TokenEnv     string
}

LauncherScriptConfig is what the launcher script needs to find the runtime.

type MCP

type MCP struct {
	// Server is the server's name in Codex's config; URL its address.
	Server string
	URL    string
	// TokenHeader is the header the server checks, TokenEnv the variable Codex reads its value from.
	TokenHeader string
	TokenEnv    string
}

MCP is the runtime's own MCP server as Codex is told about it. The token travels in an environment variable the launcher sets, never in argv.

type Message

type Message struct {
	Role string // "user" or "assistant"
	Text string
	// Source is the record type it came from (event_msg or response_item), Phase Codex's phase tag.
	Source string
	Phase  string
}

Message is a prompt or an answer read from a rollout line.

func ReadMessage

func ReadMessage(record *agents.Obj) *Message

ReadMessage reads a prompt or answer from a rollout record (event_msg user_message/agent_message or a response_item message); nil for anything else or an empty text.

type Meta

type Meta struct {
	// SessionID and JSONLPath are nil when the payload names none (the stored ones stay).
	SessionID *string
	JSONLPath *string
	// LastUserMessage and AgentSummary come with a prompt.
	LastUserMessage *string
	AgentSummary    *string
	// ClearMessages: the session was cleared (/clear), the old summary and messages go.
	ClearMessages bool
	// SetPermission: Permission replaces the pending request (nil clears it).
	SetPermission bool
	Permission    *PermissionRequest
}

Meta is what a hook payload changes on the tab.

type PatchEntry

type PatchEntry struct {
	Path      string `json:"path"`
	Operation string `json:"operation"`
	Diff      string `json:"diff,omitempty"`
	Content   string `json:"content,omitempty"`
}

PatchEntry is one file of a patch Codex asks to apply.

type PermissionRequest

type PermissionRequest struct {
	Type        string            `json:"type"`
	Command     string            `json:"command,omitempty"`
	Patches     []PatchEntry      `json:"patches,omitempty"`
	Permissions []string          `json:"permissions,omitempty"`
	CallID      string            `json:"callId,omitempty"`
	Cwd         string            `json:"cwd,omitempty"`
	Env         map[string]string `json:"env,omitempty"`
}

PermissionRequest is what Codex asks the person to approve: a command (ExecApprovalRequest), a patch (ApplyPatchApprovalRequest) or extra permissions (RequestPermissions).

func ParsePermissionRequest

func ParsePermissionRequest(p map[string]any) *PermissionRequest

ParsePermissionRequest reads what a PermissionRequest hook asks to approve; nil when it cannot be told.

type ScanResult

type ScanResult struct {
	agents.Snapshot
	NeedsStaleRecheck bool
}

ScanResult is a snapshot and whether its idle flag must be re-read from the file's age.

func ScanLines

func ScanLines(entries []*agents.Obj, elapsed float64) ScanResult

ScanLines reads a rollout's tail from the newest line back; elapsed is the file's age in milliseconds.

Every line of the tail is read: a completion anywhere in it (an earlier turn's too) makes the snapshot idle, and the quiet window is the one of the oldest prompt or message after the newest completion. This is how the previous runtime read it, kept so both answer alike.

type SessionMeta

type SessionMeta struct {
	// SessionID as recorded (a JSON value, a string in practice).
	SessionID any
	JSONLPath string
	// Cwd is the session's folder, "" when not a string.
	Cwd       string
	StartedAt *float64
}

SessionMeta is what a rollout's first line (its session_meta) says.

func FindLatestForCwd

func FindLatestForCwd(root, cwd string, now time.Time, days int) (SessionMeta, bool)

FindLatestForCwd is the most recently written rollout of the last days whose session ran in cwd.

func FindSessionByID

func FindSessionByID(root, id string, now time.Time, days int) (SessionMeta, bool)

FindSessionByID is the rollout of a session among the last days' folders, by its name and its session_meta.

func ReadMeta

func ReadMeta(path string) (SessionMeta, bool)

ReadMeta reads a rollout's session_meta; false when the first line is not one or names no id.

type SnapshotReader

type SnapshotReader struct {
	Now func() time.Time
	// contains filtered or unexported fields
}

SnapshotReader reads rollout snapshots, keeping the last 256 by path until the file changes.

func NewSnapshotReader

func NewSnapshotReader() *SnapshotReader

NewSnapshotReader reads with the wall clock.

func (*SnapshotReader) Read

func (r *SnapshotReader) Read(path string, force bool) agents.Snapshot

Read is the snapshot of the rollout at path; force skips the cache. An empty file is idle, an unreadable one says nothing.

type Start added in v0.16.154

type Start struct {
	Args   []string
	Prefix string
}

Start is what a Codex launch is built to: codex's own arguments, and the shell words it runs behind (the apps' token and wall, which only the pane's shell can put in front of it); Prefix is "" for a launch without apps.

type Tabs

type Tabs struct{}

Tabs reads a layout tab's stored Codex session (only the provider-neutral state, when it is Codex's).

func (Tabs) ProviderID

func (Tabs) ProviderID() string

func (Tabs) ReadJSONLPath

func (Tabs) ReadJSONLPath(t agents.TabAgent) string

func (Tabs) ReadSessionID

func (Tabs) ReadSessionID(t agents.TabAgent) string

func (Tabs) ReadSummary

func (Tabs) ReadSummary(t agents.TabAgent) string

type Translation

type Translation struct {
	Meta Meta
	// Event is the work-state event, nil for a hook that names none.
	Event *agents.Event
	// SessionInfo is set by SessionStart, for the session watchers; ClearSession when it was a /clear.
	SessionInfo  *agents.SessionInfo
	ClearSession bool
}

Translation is a Codex hook payload in the runtime's terms.

func ProcessHook

func ProcessHook(payload map[string]any) Translation

ProcessHook translates a Codex hook payload (the body Codex pipes to the hook script, passed through verbatim).

Jump to

Keyboard shortcuts

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