package codex import ( "bytes" "context" "crypto/rand" "encoding/hex" "encoding/json" "errors" "fmt" "io" "path/filepath" "reflect" "sort" "strconv" "strings" "sync" "time" "amadan.net/oficina/equipo/internal/runner/provider" ) const Version = provider.CodexVersion const ExecutableSHA256 = "c06a67fd8ac76508dc78bd99ce20c9f317b8d568beda59485f3f4134df9962d5" const CodeModeHostSHA256 = "522935d4392ec9674fab60b239b5495992c6a93e4deb65113a216b6f5451ccd4" // AssistEffort is the Assistant's reasoning effort (turn/start effort). const AssistEffort = "low" // GlanceModel is the small model a glance runs (provider.LaunchModel). const GlanceModel = provider.CodexGlanceModel const errNotReady provider.Error = "codex_not_ready" const errUncertain provider.Error = "codex_turn_uncertain" const errFailed provider.Error = "codex_process_failed" var _ provider.Launcher = (*Launcher)(nil) type Launcher struct { host provider.ProcessHost captures provider.CaptureFactory digest, hostDigest string mu sync.Mutex sessions map[string]*sessionState } type sessionState struct { resumeUsagePending bool completedProviderTurn string lastUsage, completedUsage json.RawMessage startupNoticeSeen, turnStarted bool mcpCalls map[string]json.RawMessage nativeCalls map[string]json.RawMessage requests map[string]provider.Event mu sync.Mutex op sync.Mutex session provider.Session launch provider.Launch lease *provider.AccountLease process provider.Process capture *provider.Capture rpc *RPC ctx context.Context cancel context.CancelFunc events chan provider.Event done chan struct{} attached, active, closed, clean, finished bool err error turn provider.Turn providerTurn string used map[string]bool } type manifest struct { NativeTools []string Action string AuthHost string Argv, DeniedPaths, EgressHosts, Tools []string ProviderVersion, LauncherVersion, BwrapVersion, Workspace, Scratch, CredentialHome string Catalog, Settings, MCP, ThreadPolicy, TurnPolicy json.RawMessage Env map[string]string Files, Instructions []struct { Mount provider.Mount SHA256 string } } func New(host provider.ProcessHost, captures provider.CaptureFactory) (*Launcher, error) { if missing(host) || missing(captures) { return nil, errNotReady } return &Launcher{host: host, captures: captures, digest: ExecutableSHA256, hostDigest: CodeModeHostSHA256, sessions: map[string]*sessionState{}}, nil } func missing(v any) bool { if v == nil { return true } r := reflect.ValueOf(v) switch r.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice: return r.IsNil() } return false } func marshal(v any) json.RawMessage { raw, _ := json.Marshal(v); return raw } func sameJSON(a, b []byte) bool { var x, y any return uniqueJSON(a) && uniqueJSON(b) && json.Unmarshal(a, &x) == nil && json.Unmarshal(b, &y) == nil && reflect.DeepEqual(x, y) } func token() string { var b [16]byte if _, e := rand.Read(b[:]); e != nil { panic(e) } return hex.EncodeToString(b[:]) } // PolicyInputs renders the policy before BuildPolicy hashes the launch manifest. func PolicyInputs(b provider.Binding, in provider.PolicyInputs, model string) (provider.PolicyInputs, error) { if in.Action != "" { profile, err := provider.Profile(in.Action) // slices.Equal: a policy read back from its manifest lists no // tools as null (a glance). if err != nil || !profile.AcceptsTools(in.Tools) { return in, provider.ErrPolicy } } if b.Provider != "codex" || model == "" { return in, provider.ErrIdentity } // Only a glance runs another model than the bound one: its // provider's small model, on every surface (settings, catalog, thread). model = provider.LaunchModel(in.Action, "codex", model) fs := map[string]any{":root": "read", "/workspace": "write", "/tmp": "write"} if in.Action != "" { p, _ := provider.Profile(in.Action) if p.ReadOnly { fs["/workspace"] = "read" } } // /dev/fd resolves into /proc. Masking that symlink after /proc makes // pinned Codex fail its nested mount setup; the /proc deny covers both. // Likewise /tool already masks equipo.sock before child mounts are applied. for _, path := range append(append([]string{}, in.DeniedPaths...), b.CredentialHome, b.Home, "/home/runner", "/egress", "/tool", "/config", "/proc") { if !filepath.IsAbs(path) || filepath.Clean(path) != path || path == "/" || path == "/workspace" || path == "/tmp" { return in, provider.ErrPolicy } fs[path] = "deny" } settings := map[string]any{ "projects": map[string]any{"/workspace": map[string]any{"trust_level": "untrusted"}}, "skills": map[string]any{"bundled": map[string]any{"enabled": false}}, "model": model, "model_provider": "openai", "approval_policy": "on-request", "approvals_reviewer": "user", "default_permissions": "equipo", "permissions": map[string]any{"equipo": map[string]any{"filesystem": fs, "network": map[string]any{"enabled": false}}}, "features": map[string]any{"incremental_tools": true, "apps": false, "multi_agent": false, "remote_control": false, "memories": false, "goals": false, "plugins": false, "remote_plugin": false, "tool_suggest": false, "tool_call_mcp_elicitation": true}, "mcp_servers": map[string]any{"equipo": map[string]any{"tool_timeout_sec": 600, "command": "/opt/equipo-tool-proxy", "args": []string{"--socket", "/tool/equipo.sock"}}}, } // Code mode hides the native tool schemas from the captured catalog. The // v2 collaboration switches are independent of the legacy multi_agent flag. for _, key := range []string{"code_mode", "code_mode_only", "code_mode_host", "multi_agent_v2", "multi_agent_mode", "multi_agent_v2_dynamic_tools", "image_generation", "imagegenext"} { settings["features"].(map[string]any)[key] = false } coordinator := provider.CoordinatorAction(in.Action) research := provider.ResearchAction(in.Action) glance := in.Action == provider.GlanceAction if in.Action != "" && !coordinator && !research && !glance { configureSpecialistCatalog(settings, &in, model) } if coordinator || research || glance { // Both coordinators (the old coordinate and thin v1's converse) get // the same surface: no shell, no patch, no search, no apps, and the // Equipo server limited to exactly the profile's own tools. So // does a Research step, with its own two tools (spec ยง4), and a // glance, with none. profile, _ := provider.Profile(in.Action) configureCoordinator(settings, model, profile.Tools()) in.NativeTools = provider.CoordinatorNativeTools("codex") in.Catalog = coordinatorCatalog(model) } for _, tool := range in.Tools { if coordinator { continue } if research { if tool != "mcp__equipo__submit_findings" && tool != "mcp__equipo__keep_image" { return in, provider.ErrPolicy } continue } switch tool { case "mcp__equipo__ask_person", "mcp__equipo__submit_candidate", "mcp__equipo__submit_review", "mcp__equipo__submit_reproduction", "mcp__equipo__submit_acceptance", "mcp__equipo__submit_answer", "mcp__equipo__submit_render", // Thin v1's answering session: read-only git on the step's // commit, run by the runner outside the namespace. "mcp__equipo__git_log", "mcp__equipo__git_diff", "mcp__equipo__git_show": default: return in, provider.ErrPolicy } } in.ProviderVersion = Version in.Settings = marshal(settings) in.MCP = json.RawMessage(`{"mcpServers":{"equipo":{"type":"stdio","command":"/opt/equipo-tool-proxy","args":["--socket","/tool/equipo.sock"]}}}`) thread := map[string]any{"model": model, "modelProvider": "openai", "cwd": "/workspace", "approvalPolicy": "on-request", "approvalsReviewer": "user", "permissions": "equipo", "runtimeWorkspaceRoots": []string{"/workspace"}, "config": settings} thread["experimentalRawEvents"] = true in.ThreadPolicy = marshal(thread) in.TurnPolicy = json.RawMessage(`{}`) if in.Action == "assist" || glance { // The Assistant (and its glance) answers a person who is waiting: low reasoning // effort on every turn/start, on the connection's own model (the // person's choice, unchanged). The pinned app-server sends it as // the request's reasoning.effort; the team's turns keep the // model's default. in.TurnPolicy = marshal(map[string]string{"effort": AssistEffort}) } in.Argv = []string{"/opt/codex", "app-server", "--strict-config", "--listen", "stdio://"} keys := make([]string, 0, len(settings)) for k := range settings { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { in.Argv = append(in.Argv, "-c", k+"="+toml(settings[k])) } return in, nil } func toml(v any) string { switch x := v.(type) { case int: return strconv.Itoa(x) case string: return strconv.Quote(x) case bool: if x { return "true" } return "false" case []string: values := make([]string, len(x)) for i, v := range x { values[i] = strconv.Quote(v) } return "[" + strings.Join(values, ",") + "]" case map[string]any: keys := make([]string, 0, len(x)) for k := range x { keys = append(keys, k) } sort.Strings(keys) fields := make([]string, 0, len(keys)) for _, k := range keys { fields = append(fields, strconv.Quote(k)+"="+toml(x[k])) } return "{" + strings.Join(fields, ",") + "}" } panic("unsupported policy value") } func policyInputs(p provider.Policy) (provider.PolicyInputs, manifest, error) { var m manifest if !uniqueJSON(p.Manifest) || json.Unmarshal(p.Manifest, &m) != nil { return provider.PolicyInputs{}, m, provider.ErrPolicy } in := provider.PolicyInputs{NativeTools: m.NativeTools, Action: m.Action, AuthHost: m.AuthHost, Argv: m.Argv, DeniedPaths: append([]string{}, m.DeniedPaths...), EgressHosts: m.EgressHosts, Tools: m.Tools, ProviderVersion: m.ProviderVersion, LauncherVersion: m.LauncherVersion, BwrapVersion: m.BwrapVersion, Workspace: m.Workspace, Scratch: m.Scratch, Catalog: m.Catalog, Settings: m.Settings, MCP: m.MCP, ThreadPolicy: m.ThreadPolicy, TurnPolicy: m.TurnPolicy, Env: map[string]string{}} for _, path := range []string{m.CredentialHome, "/home/runner"} { for i, p := range in.DeniedPaths { if p == path { in.DeniedPaths = append(in.DeniedPaths[:i], in.DeniedPaths[i+1:]...) break } } } for _, f := range m.Files { in.RuntimeFiles = append(in.RuntimeFiles, f.Mount) } for _, f := range m.Instructions { in.InstructionFiles = append(in.InstructionFiles, f.Mount) } for _, key := range []string{"LANG", "LC_ALL", "TERM"} { if v, ok := m.Env[key]; ok { in.Env[key] = v } } return in, m, nil } func (l *Launcher) validatePolicy(b provider.Binding, p provider.Policy) (provider.PolicyInputs, error) { in, m, e := policyInputs(p) if e != nil { return in, e } if b.Provider != "codex" || b.Expected.ProviderVersion != Version || in.ProviderVersion != Version { return in, provider.ErrVersion } if e = p.ValidateSources(b); e != nil { return in, e } var tp struct{ Model string } if json.Unmarshal(in.ThreadPolicy, &tp) != nil { return in, provider.ErrPolicy } want, e := PolicyInputs(b, in, tp.Model) if e != nil { return in, e } for _, pair := range [][2]json.RawMessage{{in.Settings, want.Settings}, {in.MCP, want.MCP}, {in.ThreadPolicy, want.ThreadPolicy}, {in.TurnPolicy, want.TurnPolicy}} { if !sameJSON(pair[0], pair[1]) { return in, provider.ErrPolicy } } if !reflect.DeepEqual(in.NativeTools, want.NativeTools) || (in.Action != "" && !sameJSON(in.Catalog, want.Catalog)) || !reflect.DeepEqual(in.Argv, want.Argv) || p.Env["CODEX_HOME"] != "/home/runner" { return in, provider.ErrPolicy } binary, helper, toolHelper := false, false, false for _, f := range m.Files { if f.Mount.Target == "/opt/codex" { binary = f.SHA256 == l.digest } if f.Mount.Target == "/opt/equipo-tool-proxy" { toolHelper = f.Mount.ReadOnly } if f.Mount.Target == "/opt/codex-code-mode-host" { helper = f.SHA256 == l.hostDigest } if strings.HasPrefix(f.Mount.Target, "/etc/") { return in, provider.ErrPolicy } } if !binary || !helper || !toolHelper { return in, provider.ErrVersion } if len(in.InstructionFiles) != 0 { return in, provider.ErrPolicy } rebuilt, e := provider.BuildPolicy(b, in) if e != nil || rebuilt.Hash != p.Hash || rebuilt.ManifestHash != p.ManifestHash { return in, provider.ErrPolicy } return in, nil } func (l *Launcher) start(ctx context.Context, launch provider.Launch, handler func(provider.Frame) error) (provider.Process, *provider.Capture, *RPC, error) { in, _, e := policyInputs(launch.Policy) if e != nil { return nil, nil, nil, e } if _, e = provider.AttestLaunch(launch, in.Argv); e != nil { return nil, nil, nil, e } proc, e := l.host.Start(ctx, launch, in.Argv) if e != nil { return nil, nil, nil, e } cap, e := l.captures.Open(ctx, proc, launch) if e != nil { return proc, nil, nil, e } if cap == nil || cap.Input == nil || cap.Frames == nil || cap.Done == nil { return proc, cap, nil, errNotReady } return proc, cap, newFrameRPC(ctx, cap, handler), nil } func waitProcess(proc provider.Process) { if proc != nil { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() proc.Wait(ctx) } } func initialize(ctx context.Context, r *RPC) error { raw, e := r.Call(ctx, "initialize", marshal(map[string]any{"clientInfo": map[string]any{"name": "equipo", "version": "2"}, "capabilities": map[string]any{"experimentalApi": true}})) if e != nil { return e } var v struct{ UserAgent, CodexHome string } if json.Unmarshal(raw, &v) != nil || !strings.HasPrefix(v.UserAgent, "equipo/"+Version+" ") || v.CodexHome != "/home/runner" { return provider.ErrVersion } return r.initialized(ctx) } func readIdentity(ctx context.Context, r *RPC) (provider.Identity, error) { raw, e := r.Call(ctx, "account/read", json.RawMessage(`{"refreshToken":false}`)) if e != nil { return provider.Identity{}, e } return provider.CodexLoginIdentity(raw) } func readConfig(ctx context.Context, r *RPC, p provider.Policy) error { raw, e := r.Call(ctx, "config/read", json.RawMessage(`{"cwd":"/workspace","includeLayers":true}`)) if e != nil { return e } return validateConfig(raw, p) } func validateConfig(raw []byte, p provider.Policy) error { type origin struct { Name json.RawMessage Version string } var v struct { Config map[string]json.RawMessage Layers []struct { Name json.RawMessage Version string Config json.RawMessage DisabledReason *string } Origins map[string]origin } if json.Unmarshal(raw, &v) != nil || v.Layers == nil || v.Origins == nil { return provider.ErrPolicy } var want map[string]json.RawMessage json.Unmarshal(p.Settings, &want) // The pinned binary expands defaults; configured values must still match. if !effectiveConfigMatches(p, v.Config) { return provider.ErrPolicy } var expectedMCP, effectiveMCP map[string]json.RawMessage if json.Unmarshal(want["mcp_servers"], &expectedMCP) != nil || json.Unmarshal(v.Config["mcp_servers"], &effectiveMCP) != nil || len(expectedMCP) != len(effectiveMCP) { return provider.ErrPolicy } seenFlags, seenDisabledProject := false, false for _, layer := range v.Layers { if layer.Version == "" { return provider.ErrPolicy } if layer.DisabledReason != nil { if seenDisabledProject || !disabledEmptyProject(layer.Name, layer.Config, *layer.DisabledReason) { return provider.ErrPolicy } seenDisabledProject = true continue } switch { case sameJSON(layer.Name, []byte(`{"type":"sessionFlags"}`)): if seenFlags || !sameJSON(layer.Config, p.Settings) { return provider.ErrPolicy } seenFlags = true case emptyConfigLayer(layer.Name): if !sameJSON(layer.Config, []byte(`{}`)) { return provider.ErrPolicy } default: return provider.ErrPolicy } } for k, o := range v.Origins { if _, ok := want[strings.SplitN(k, ".", 2)[0]]; !ok || o.Version == "" || !sameJSON(o.Name, []byte(`{"type":"sessionFlags"}`)) { return provider.ErrPolicy } } if !seenFlags { return provider.ErrPolicy } return nil } func (l *Launcher) Preflight(ctx context.Context, b provider.Binding, p provider.Policy) (provider.Identity, error) { lease, e := b.AccountLease() if e != nil { return provider.Identity{}, e } in, e := l.validatePolicy(b, p) if e != nil { return provider.Identity{}, e } return l.preflight(ctx, b, lease, in) } func (l *Launcher) preflight(ctx context.Context, b provider.Binding, lease *provider.AccountLease, in provider.PolicyInputs) (provider.Identity, error) { var observed provider.Identity probe := func(ctx context.Context, b provider.Binding) (provider.Identity, error) { ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() p, e := provider.BuildPolicy(b, in) if e != nil { return provider.Identity{}, e } launch := provider.Launch{AttemptKey: "codex-preflight-" + token(), Workspace: in.Workspace, Binding: b, Policy: p, Selection: provider.Selection{Provider: "codex", AccountID: b.AccountID}} startupNoticeSeen := false proc, _, r, e := l.start(ctx, launch, func(frame provider.Frame) error { raw := frame.Bytes v, _ := parse(raw) if disabledRemoteControl(v) { return nil } if v.Method == "account/updated" { if !startupNoticeSeen && provider.CodexStartupNotice(v.ID, v.Method, v.Params) { startupNoticeSeen = true return nil } return provider.ErrIdentity } return errProtocol }) defer func() { if r != nil { r.close() } cancel() waitProcess(proc) if r != nil { <-r.done } }() if e != nil { return provider.Identity{}, e } if e = initialize(ctx, r); e != nil { return provider.Identity{}, e } observed, e = readIdentity(ctx, r) if e != nil { return observed, e } if e = readConfig(ctx, r, p); e != nil { return observed, e } return observed, nil } e := lease.Validate(ctx) if errors.Is(e, provider.ErrContainment) { return observed, fmt.Errorf("codex_preflight_lease: %w", e) } if errors.Is(e, provider.ErrRefreshPending) { return observed, provider.ErrAccountMaintenance } if e = lease.Preflight(ctx, probe); e != nil { return observed, fmt.Errorf("codex_preflight_probe: %w", e) } _, e = provider.BuildPolicy(b, in) return observed, e } func (l *Launcher) Open(ctx context.Context, launch provider.Launch) (provider.Session, error) { l.mu.Lock() defer l.mu.Unlock() if launch.AttemptKey == "" || l.sessions[launch.AttemptKey] != nil { return provider.Session{}, errNotReady } in, e := l.validatePolicy(launch.Binding, launch.Policy) if e != nil { return provider.Session{}, e } var tp struct{ Model string } json.Unmarshal(in.ThreadPolicy, &tp) if tp.Model != launch.Selection.Model { return provider.Session{}, provider.ErrIdentity } lease, e := launch.Binding.AccountLease() if e != nil { return provider.Session{}, e } var previous *sessionState for _, s := range l.sessions { s.mu.Lock() busy := s.launch.Binding == launch.Binding && !s.closed eligible := s.session.ID == launch.ResumeSessionID && s.closed && s.clean && s.finished && s.err == nil && s.launch.Policy.Hash == launch.Policy.Hash && s.launch.Binding == launch.Binding && s.launch.Selection == launch.Selection s.mu.Unlock() if busy { return provider.Session{}, provider.ErrAccountBusy } if eligible { previous = s } } if launch.ResumeSessionID != "" && previous == nil { return provider.Session{}, errUncertain } if _, e = l.preflight(ctx, launch.Binding, lease, in); e != nil { return provider.Session{}, e } if e = lease.ValidatePolicy(ctx); e != nil { return provider.Session{}, fmt.Errorf("codex_open_runtime_policy: %w", e) } attempt, cancel := context.WithCancel(ctx) s := &sessionState{launch: launch, lease: lease, ctx: attempt, cancel: cancel, events: make(chan provider.Event, 128), done: make(chan struct{}), used: map[string]bool{}} s.session = provider.Session{AttemptKey: launch.AttemptKey, Provider: launch.Selection.Provider, AccountID: launch.Selection.AccountID, Model: launch.Selection.Model, Family: launch.Selection.Family} s.process, s.capture, s.rpc, e = l.start(attempt, launch, s.handle) fail := func(e error) (provider.Session, error) { cancel() if s.rpc != nil { s.rpc.close() <-s.rpc.done } waitProcess(s.process) return provider.Session{}, e } if e != nil { return fail(e) } if e = initialize(attempt, s.rpc); e != nil { return fail(e) } if e = s.checkReadback(ctx); e != nil { return fail(e) } if previous != nil { previous.mu.Lock() s.mu.Lock() s.completedProviderTurn = previous.completedProviderTurn s.completedUsage = bytes.Clone(previous.completedUsage) s.session.ID = launch.ResumeSessionID s.mu.Unlock() previous.mu.Unlock() } method := "thread/start" if launch.ResumeSessionID != "" { method = "thread/resume" } id, e := s.thread(ctx, method, launch.ResumeSessionID) if e != nil { return fail(e) } s.mu.Lock() s.session.ID = id session := s.session s.mu.Unlock() if e = session.Validate(launch); e != nil { return fail(e) } if binding, ok := s.capture.Input.(provider.SessionBinding); ok { if e = binding.BindSession(ctx, session); e != nil { return fail(e) } } if previous != nil { previous.mu.Lock() previous.clean = false for k, v := range previous.used { s.used[k] = v } previous.mu.Unlock() } l.sessions[launch.AttemptKey] = s go s.monitor() return session, nil } func (s *sessionState) checkReadback(ctx context.Context) error { id, e := readIdentity(ctx, s.rpc) if e != nil { return e } if id.AccountID != s.launch.Binding.Expected.AccountID || id.ProviderVersion != s.launch.Binding.Expected.ProviderVersion { return provider.ErrIdentity } return readConfig(ctx, s.rpc, s.launch.Policy) } func (s *sessionState) thread(ctx context.Context, method, id string) (string, error) { if e := s.lease.ValidatePolicy(ctx); e != nil { return "", e } if method == "thread/resume" { s.mu.Lock() s.resumeUsagePending = len(s.completedUsage) > 0 s.mu.Unlock() } params := threadParams(s.launch.Policy.ThreadPolicy, method, id) raw, e := s.rpc.Call(ctx, method, marshal(params)) if e != nil { return "", e } var v struct { Thread struct{ ID string } Model, ModelProvider, Cwd, ApprovalPolicy, ApprovalsReviewer string ActivePermissionProfile *struct { ID string Extends json.RawMessage } RuntimeWorkspaceRoots []string } if json.Unmarshal(raw, &v) != nil || v.Thread.ID == "" || (id != "" && v.Thread.ID != id) || v.Model != s.session.Model || v.ModelProvider != "openai" || v.Cwd != "/workspace" || v.ApprovalPolicy != "on-request" || v.ApprovalsReviewer != "user" || v.ActivePermissionProfile == nil || v.ActivePermissionProfile.ID != "equipo" || !bytes.Equal(v.ActivePermissionProfile.Extends, []byte("null")) || !reflect.DeepEqual(v.RuntimeWorkspaceRoots, []string{"/workspace"}) { return "", provider.ErrPolicy } return v.Thread.ID, nil } func (l *Launcher) state(session provider.Session) (*sessionState, error) { l.mu.Lock() defer l.mu.Unlock() s := l.sessions[session.AttemptKey] if s == nil || s.session != session { return nil, provider.ErrIdentity } return s, nil } func (l *Launcher) Events(ctx context.Context, session provider.Session) (<-chan provider.Event, error) { s, e := l.state(session) if e != nil { return nil, e } s.mu.Lock() defer s.mu.Unlock() if e = ctx.Err(); e != nil { return nil, e } if s.attached { return nil, errNotReady } s.attached = true return s.events, nil } func (s *sessionState) stop(e error) error { s.mu.Lock() if s.err == nil { s.err = e } s.mu.Unlock() s.cancel() s.rpc.close() return e } func (l *Launcher) StartTurn(ctx context.Context, session provider.Session, t provider.Turn) error { s, e := l.state(session) if e != nil { return e } s.op.Lock() defer s.op.Unlock() s.mu.Lock() fresh := !s.turnStarted && s.launch.ResumeSessionID == "" ready := !s.closed && s.err == nil && !s.active && s.attached && t.ID != "" && t.AdmissionID != "" && t.Prompt != "" && !s.used[t.ID] && !s.used[t.AdmissionID] s.mu.Unlock() if !ready { return errNotReady } if e = ctx.Err(); e != nil { return e } e = s.lease.ValidatePolicy(ctx) if errors.Is(e, provider.ErrRefreshPending) || errors.Is(e, provider.ErrPreflightRequired) { if e = s.launch.Policy.ValidateSources(s.launch.Binding); e != nil { return s.stop(e) } in, _, inputErr := policyInputs(s.launch.Policy) if inputErr != nil { return s.stop(inputErr) } _, e = l.preflight(ctx, s.launch.Binding, s.lease, in) } if e != nil { return s.stop(e) } in, _, e := policyInputs(s.launch.Policy) if e != nil { return s.stop(e) } if _, e = provider.AttestLaunch(s.launch, in.Argv); e != nil { return s.stop(e) } if e = s.checkReadback(ctx); e != nil { return s.stop(e) } // A fresh pinned thread has no rollout until its first turn. Open already // verified its effective policy; later turns must reassert the saved thread. if !fresh { if _, e = s.thread(ctx, "thread/resume", session.ID); e != nil { return s.stop(e) } } if e = s.beginTurn(ctx, t); e != nil { return s.stop(e) } var params map[string]json.RawMessage json.Unmarshal(s.launch.Policy.TurnPolicy, ¶ms) params["threadId"] = marshal(session.ID) params["input"] = marshal([]any{map[string]any{"type": "text", "text": t.Prompt}}) if barrier, ok := s.capture.Input.(provider.TurnBarrier); ok { if e = barrier.BeginTurn(ctx, session, t); e != nil { return s.stop(e) } } s.mu.Lock() s.turnStarted = true s.mu.Unlock() raw, e := s.rpc.Call(ctx, "turn/start", marshal(params)) if e != nil { return s.stop(errUncertain) } var result struct{ Turn struct{ ID string } } if json.Unmarshal(raw, &result) != nil || result.Turn.ID == "" { return s.stop(errProtocol) } s.mu.Lock() if s.providerTurn == "" { s.providerTurn = result.Turn.ID } mismatch := s.providerTurn != result.Turn.ID currentErr := s.err s.mu.Unlock() if mismatch { return s.stop(provider.ErrIdentity) } return currentErr } func (l *Launcher) Respond(ctx context.Context, s provider.Session, a provider.Answer) error { return l.respond(ctx, s, a) } func (l *Launcher) Interrupt(ctx context.Context, session provider.Session) error { s, e := l.state(session) if e != nil { return e } s.mu.Lock() id := s.providerTurn active := s.active s.mu.Unlock() defer s.stop(errUncertain) if !active || id == "" { return nil } ctx, cancel := context.WithTimeout(ctx, time.Second) defer cancel() _, e = s.rpc.Call(ctx, "turn/interrupt", marshal(map[string]any{"threadId": session.ID, "turnId": id})) return e } func (l *Launcher) Close(ctx context.Context, session provider.Session) error { s, e := l.state(session) if e != nil { return e } s.mu.Lock() s.closed = true active := s.active s.mu.Unlock() if active { s.stop(errUncertain) } else { s.capture.Input.Close() } ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() select { case <-s.done: case <-ctx.Done(): s.stop(ctx.Err()) return ctx.Err() } s.mu.Lock() defer s.mu.Unlock() return s.err } func (s *sessionState) handle(frame provider.Frame) error { events, e := Decode(frame.Bytes) if e != nil { return e } s.mu.Lock() defer s.mu.Unlock() v, _ := parse(frame.Bytes) if v.Method == "account/updated" { if !s.turnStarted && !s.startupNoticeSeen && provider.CodexStartupNotice(v.ID, v.Method, v.Params) { s.startupNoticeSeen = true return nil } return provider.ErrContainment } for _, ev := range events { ev.Sequence = frame.Sequence if strings.HasPrefix(ev.Kind, "config/") { return provider.ErrContainment } if ev.SessionID != "" && s.session.ID != "" && ev.SessionID != s.session.ID { return provider.ErrIdentity } if ev.Kind == "usage" && ev.TurnID == s.completedProviderTurn && s.completedProviderTurn != "" { if !s.resumeUsagePending || !sameJSON(v.Params, s.completedUsage) { return errProtocol } s.resumeUsagePending = false continue } if ev.Kind == "usage" { s.lastUsage = bytes.Clone(v.Params) } if ev.TurnID == "" && ev.Kind == "request" { v, _ := parse(ev.Payload) if (v.Method == "execCommandApproval" || v.Method == "applyPatchApproval") && s.active && s.providerTurn != "" { ev.TurnID = s.providerTurn } } if ev.TurnID != "" { ev.ProviderTurnID = ev.TurnID if !s.active { return errProtocol } if s.providerTurn == "" { s.providerTurn = ev.TurnID } if ev.TurnID != s.providerTurn { return provider.ErrIdentity } ev.TurnID = s.turn.ID } else if ev.Kind == "turn.completed" || ev.Kind == "turn.failed" || ev.Kind == "usage" || ev.Kind == "request" { return errProtocol } var envelope struct { Method string Params struct { RequestID json.RawMessage `json:"requestId"` Item struct{ ID, Type string } } } _ = json.Unmarshal(ev.Payload, &envelope) if envelope.Method == "serverRequest/resolved" { delete(s.requests, string(envelope.Params.RequestID)) } if envelope.Params.Item.Type == "mcpToolCall" { if envelope.Method == "item/started" { if s.mcpCalls == nil { s.mcpCalls = map[string]json.RawMessage{} } if len(s.mcpCalls) >= 64 { return errProtocol } s.mcpCalls[envelope.Params.Item.ID] = bytes.Clone(ev.Payload) } else if envelope.Method == "item/completed" { delete(s.mcpCalls, envelope.Params.Item.ID) } } if envelope.Params.Item.Type == "fileChange" { if envelope.Method == "item/started" { if s.nativeCalls == nil { s.nativeCalls = map[string]json.RawMessage{} } if len(s.nativeCalls) >= 64 { return errProtocol } s.nativeCalls[envelope.Params.Item.ID] = bytes.Clone(ev.Payload) } else if envelope.Method == "item/completed" { delete(s.nativeCalls, envelope.Params.Item.ID) } } if ev.Kind == "request" { if !supportedRequest(envelope.Method) { return s.rpc.answer(s.ctx, s.session, s.turn.ID, requestRefusal(ev.RequestID)) } s.correlateMCP(&ev) s.correlateNative(&ev) if s.requests == nil { s.requests = map[string]provider.Event{} } if _, exists := s.requests[ev.RequestID]; exists || len(s.requests) >= 64 { return errProtocol } s.requests[ev.RequestID] = ev } if ev.Kind == "turn.completed" || ev.Kind == "turn.failed" { e = s.lease.EndTurn(context.Background()) s.active = false s.requests = nil s.mcpCalls = nil s.nativeCalls = nil if e != nil && !errors.Is(e, provider.ErrRefreshPending) { return e } s.finished = ev.Kind == "turn.completed" if s.finished { s.completedProviderTurn = s.providerTurn s.completedUsage = bytes.Clone(s.lastUsage) } if !s.finished { s.err = errFailed } } select { case s.events <- ev: default: return errProtocol } } return nil } func (s *sessionState) monitor() { defer close(s.done) defer close(s.events) <-s.rpc.done s.rpc.mu.Lock() rpcErr := s.rpc.err s.rpc.mu.Unlock() s.mu.Lock() closing := s.closed active := s.active s.mu.Unlock() if !closing || active || !errors.Is(rpcErr, io.EOF) { s.cancel() } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() exit, e := s.process.Wait(ctx) s.mu.Lock() defer s.mu.Unlock() if s.active { s.lease.EndTurn(context.Background()) s.active = false s.err = errUncertain } if e != nil || exit.Code != 0 || exit.Signal != 0 || !s.closed || !errors.Is(rpcErr, io.EOF) { if s.err == nil { s.err = errFailed } } s.clean = s.closed && s.finished && s.err == nil if s.err != nil { select { case s.events <- provider.Event{SessionID: s.session.ID, TurnID: s.turn.ID, Kind: "turn.failed"}: default: } } s.cancel() } func (s *sessionState) beginTurn(ctx context.Context, t provider.Turn) error { s.mu.Lock() defer s.mu.Unlock() if s.closed || s.err != nil || s.ctx.Err() != nil { return errNotReady } if e := s.lease.BeginTurn(ctx); e != nil { return e } s.active = true s.finished = false s.turn = t s.providerTurn = "" s.lastUsage = nil s.used[t.ID] = true s.used[t.AdmissionID] = true return nil } func emptyConfigLayer(raw []byte) bool { var n struct{ Type, File string } if json.Unmarshal(raw, &n) != nil { return false } return n.Type == "user" && n.File == "/home/runner/config.toml" || n.Type == "system" && n.File == "/etc/codex/config.toml" } func configSubset(want, got []byte) bool { var w, g map[string]json.RawMessage if json.Unmarshal(want, &w) != nil || json.Unmarshal(got, &g) != nil || w == nil || g == nil { return sameJSON(want, got) } for k, v := range w { if !configSubset(v, g[k]) { return false } } return true } func threadParams(policy json.RawMessage, method, id string) map[string]json.RawMessage { var params map[string]json.RawMessage _ = json.Unmarshal(policy, ¶ms) if method == "thread/resume" { delete(params, "experimentalRawEvents") params["excludeTurns"] = marshal(true) params["threadId"] = marshal(id) } return params }