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
- Variables
- func EnsureLauncher(path string, content []byte) error
- func LauncherFlags(l *agents.Launch) ([]string, error)
- func LauncherScript(c LauncherScriptConfig) []byte
- func MCPArgs(m MCP) []string
- func MCPURL(port int, path string) string
- func MatchesProcess(command string, args []string) bool
- func ParsePaneTitle(string) *string
- func ReadHistoryStats(path string) agents.HistoryStats
- func ResumeID(args string) string
- func RuntimeLaunchArgs(l *agents.Launch) ([]string, error)
- func SessionIDFromPath(jsonlPath string) string
- func ShouldEmit(payload map[string]any, cliState string) bool
- func SummarizeFunctionCall(name string, raw any) string
- func TOMLBasicString(s string) string
- func TailEntries(path string, size int64) ([]*agents.Obj, error)
- func TranslateEvent(payload map[string]any) *agents.Event
- type Detector
- type HookConfig
- type LaunchConfig
- type LauncherScriptConfig
- type MCP
- type Message
- type Meta
- type PatchEntry
- type PermissionRequest
- type ScanResult
- type SessionMeta
- type SnapshotReader
- type Tabs
- type Translation
Constants ¶
const ( ProviderID = agents.Codex DisplayName = "Codex" PanelType = agents.CodexPanel Binary = "codex" )
const ( // StaleInterrupted is the quiet window after an agent message, StaleAwaitingAPI after a prompt. StaleInterrupted = 20_000 StaleAwaitingAPI = 90_000 )
const (
// ScanDays is how many local days of session folders a lookup reads, today first.
ScanDays = 30
)
Variables ¶
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.
var HookEvents = []string{"SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "Stop", "PermissionRequest"}
Hook events the runtime registers with Codex.
Functions ¶
func EnsureLauncher ¶
EnsureLauncher writes the launcher script (0700) when it is missing or differs, and narrows its mode when equal.
func LauncherFlags ¶
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, model, effort}), appends the prompt, and runs codex with the token in TokenEnv, mirroring its exit.
func MatchesProcess ¶
MatchesProcess tells Codex by a pane's foreground command and, for node, the process's arguments.
func ParsePaneTitle ¶
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 ¶
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 ¶
RuntimeLaunchArgs are codex's own `-m <model> -c model_reasoning_effort="<e>"` (argv, no shell).
func SessionIDFromPath ¶
SessionIDFromPath is the session id at the end of a rollout file's name, "" when there is none.
func ShouldEmit ¶
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 SummarizeFunctionCall ¶
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 ¶
TOMLBasicString encodes text as a one-line TOML basic string (a JSON string is one).
func TailEntries ¶
TailEntries decodes the complete lines of a rollout's last 128 KiB.
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 ¶
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) IsRunning ¶
IsRunning: one of the shell's children or grandchildren is Codex (its launcher counts).
func (*Detector) SessionsRoot ¶
SessionsRoot holds the session folders.
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
// 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).
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
// 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
}
LaunchConfig is what a Codex launch is built from; the deployment fills it.
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.
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 ¶
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 ¶
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 ¶
FindLatestForCwd is the most recently written rollout of the last days whose session ran in cwd.
func FindSessionByID ¶
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 ¶
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.
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 ¶
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).