| 1 | package codex |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/rand" |
| 7 | "encoding/hex" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | "io" |
| 12 | "path/filepath" |
| 13 | "reflect" |
| 14 | "sort" |
| 15 | "strconv" |
| 16 | "strings" |
| 17 | "sync" |
| 18 | "time" |
| 19 | |
| 20 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 21 | ) |
| 22 | |
| 23 | const Version = provider.CodexVersion |
| 24 | const ExecutableSHA256 = "c06a67fd8ac76508dc78bd99ce20c9f317b8d568beda59485f3f4134df9962d5" |
| 25 | const CodeModeHostSHA256 = "522935d4392ec9674fab60b239b5495992c6a93e4deb65113a216b6f5451ccd4" |
| 26 | |
| 27 | // AssistEffort is the Assistant's reasoning effort (turn/start effort). |
| 28 | const AssistEffort = "low" |
| 29 | |
| 30 | // GlanceModel is the small model a glance runs (provider.LaunchModel). |
| 31 | const GlanceModel = provider.CodexGlanceModel |
| 32 | const errNotReady provider.Error = "codex_not_ready" |
| 33 | const errUncertain provider.Error = "codex_turn_uncertain" |
| 34 | const errFailed provider.Error = "codex_process_failed" |
| 35 | |
| 36 | var _ provider.Launcher = (*Launcher)(nil) |
| 37 | |
| 38 | type Launcher struct { |
| 39 | host provider.ProcessHost |
| 40 | captures provider.CaptureFactory |
| 41 | digest, hostDigest string |
| 42 | mu sync.Mutex |
| 43 | sessions map[string]*sessionState |
| 44 | } |
| 45 | type sessionState struct { |
| 46 | resumeUsagePending bool |
| 47 | completedProviderTurn string |
| 48 | lastUsage, completedUsage json.RawMessage |
| 49 | startupNoticeSeen, turnStarted bool |
| 50 | mcpCalls map[string]json.RawMessage |
| 51 | nativeCalls map[string]json.RawMessage |
| 52 | requests map[string]provider.Event |
| 53 | mu sync.Mutex |
| 54 | op sync.Mutex |
| 55 | session provider.Session |
| 56 | launch provider.Launch |
| 57 | lease *provider.AccountLease |
| 58 | process provider.Process |
| 59 | capture *provider.Capture |
| 60 | rpc *RPC |
| 61 | ctx context.Context |
| 62 | cancel context.CancelFunc |
| 63 | events chan provider.Event |
| 64 | done chan struct{} |
| 65 | attached, active, closed, clean, finished bool |
| 66 | err error |
| 67 | turn provider.Turn |
| 68 | providerTurn string |
| 69 | used map[string]bool |
| 70 | } |
| 71 | type manifest struct { |
| 72 | NativeTools []string |
| 73 | Action string |
| 74 | AuthHost string |
| 75 | Argv, DeniedPaths, EgressHosts, Tools []string |
| 76 | ProviderVersion, LauncherVersion, BwrapVersion, Workspace, Scratch, CredentialHome string |
| 77 | Catalog, Settings, MCP, ThreadPolicy, TurnPolicy json.RawMessage |
| 78 | Env map[string]string |
| 79 | Files, Instructions []struct { |
| 80 | Mount provider.Mount |
| 81 | SHA256 string |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | func New(host provider.ProcessHost, captures provider.CaptureFactory) (*Launcher, error) { |
| 86 | if missing(host) || missing(captures) { |
| 87 | return nil, errNotReady |
| 88 | } |
| 89 | return &Launcher{host: host, captures: captures, digest: ExecutableSHA256, hostDigest: CodeModeHostSHA256, sessions: map[string]*sessionState{}}, nil |
| 90 | } |
| 91 | func missing(v any) bool { |
| 92 | if v == nil { |
| 93 | return true |
| 94 | } |
| 95 | r := reflect.ValueOf(v) |
| 96 | switch r.Kind() { |
| 97 | case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice: |
| 98 | return r.IsNil() |
| 99 | } |
| 100 | return false |
| 101 | } |
| 102 | |
| 103 | func marshal(v any) json.RawMessage { raw, _ := json.Marshal(v); return raw } |
| 104 | func sameJSON(a, b []byte) bool { |
| 105 | var x, y any |
| 106 | return uniqueJSON(a) && uniqueJSON(b) && json.Unmarshal(a, &x) == nil && json.Unmarshal(b, &y) == nil && reflect.DeepEqual(x, y) |
| 107 | } |
| 108 | func token() string { |
| 109 | var b [16]byte |
| 110 | if _, e := rand.Read(b[:]); e != nil { |
| 111 | panic(e) |
| 112 | } |
| 113 | return hex.EncodeToString(b[:]) |
| 114 | } |
| 115 | |
| 116 | // PolicyInputs renders the policy before BuildPolicy hashes the launch manifest. |
| 117 | func PolicyInputs(b provider.Binding, in provider.PolicyInputs, model string) (provider.PolicyInputs, error) { |
| 118 | if in.Action != "" { |
| 119 | profile, err := provider.Profile(in.Action) |
| 120 | // slices.Equal: a policy read back from its manifest lists no |
| 121 | // tools as null (a glance). |
| 122 | if err != nil || !profile.AcceptsTools(in.Tools) { |
| 123 | return in, provider.ErrPolicy |
| 124 | } |
| 125 | } |
| 126 | if b.Provider != "codex" || model == "" { |
| 127 | return in, provider.ErrIdentity |
| 128 | } |
| 129 | // Only a glance runs another model than the bound one: its |
| 130 | // provider's small model, on every surface (settings, catalog, thread). |
| 131 | model = provider.LaunchModel(in.Action, "codex", model) |
| 132 | fs := map[string]any{":root": "read", "/workspace": "write", "/tmp": "write"} |
| 133 | if in.Action != "" { |
| 134 | p, _ := provider.Profile(in.Action) |
| 135 | if p.ReadOnly { |
| 136 | fs["/workspace"] = "read" |
| 137 | } |
| 138 | } |
| 139 | // /dev/fd resolves into /proc. Masking that symlink after /proc makes |
| 140 | // pinned Codex fail its nested mount setup; the /proc deny covers both. |
| 141 | // Likewise /tool already masks equipo.sock before child mounts are applied. |
| 142 | for _, path := range append(append([]string{}, in.DeniedPaths...), b.CredentialHome, b.Home, "/home/runner", "/egress", "/tool", "/config", "/proc") { |
| 143 | if !filepath.IsAbs(path) || filepath.Clean(path) != path || path == "/" || path == "/workspace" || path == "/tmp" { |
| 144 | return in, provider.ErrPolicy |
| 145 | } |
| 146 | fs[path] = "deny" |
| 147 | } |
| 148 | settings := map[string]any{ |
| 149 | "projects": map[string]any{"/workspace": map[string]any{"trust_level": "untrusted"}}, |
| 150 | "skills": map[string]any{"bundled": map[string]any{"enabled": false}}, |
| 151 | "model": model, "model_provider": "openai", "approval_policy": "on-request", "approvals_reviewer": "user", "default_permissions": "equipo", |
| 152 | "permissions": map[string]any{"equipo": map[string]any{"filesystem": fs, "network": map[string]any{"enabled": false}}}, |
| 153 | "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"}}}, |
| 154 | } |
| 155 | // Code mode hides the native tool schemas from the captured catalog. The |
| 156 | // v2 collaboration switches are independent of the legacy multi_agent flag. |
| 157 | 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"} { |
| 158 | settings["features"].(map[string]any)[key] = false |
| 159 | } |
| 160 | coordinator := provider.CoordinatorAction(in.Action) |
| 161 | research := provider.ResearchAction(in.Action) |
| 162 | glance := in.Action == provider.GlanceAction |
| 163 | if in.Action != "" && !coordinator && !research && !glance { |
| 164 | configureSpecialistCatalog(settings, &in, model) |
| 165 | } |
| 166 | if coordinator || research || glance { |
| 167 | // Both coordinators (the old coordinate and thin v1's converse) get |
| 168 | // the same surface: no shell, no patch, no search, no apps, and the |
| 169 | // Equipo server limited to exactly the profile's own tools. So |
| 170 | // does a Research step, with its own two tools (spec §4), and a |
| 171 | // glance, with none. |
| 172 | profile, _ := provider.Profile(in.Action) |
| 173 | configureCoordinator(settings, model, profile.Tools()) |
| 174 | in.NativeTools = provider.CoordinatorNativeTools("codex") |
| 175 | in.Catalog = coordinatorCatalog(model) |
| 176 | } |
| 177 | for _, tool := range in.Tools { |
| 178 | if coordinator { |
| 179 | continue |
| 180 | } |
| 181 | if research { |
| 182 | if tool != "mcp__equipo__submit_findings" && tool != "mcp__equipo__keep_image" { |
| 183 | return in, provider.ErrPolicy |
| 184 | } |
| 185 | continue |
| 186 | } |
| 187 | switch tool { |
| 188 | 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", |
| 189 | // Thin v1's answering session: read-only git on the step's |
| 190 | // commit, run by the runner outside the namespace. |
| 191 | "mcp__equipo__git_log", "mcp__equipo__git_diff", "mcp__equipo__git_show": |
| 192 | default: |
| 193 | return in, provider.ErrPolicy |
| 194 | } |
| 195 | } |
| 196 | in.ProviderVersion = Version |
| 197 | in.Settings = marshal(settings) |
| 198 | in.MCP = json.RawMessage(`{"mcpServers":{"equipo":{"type":"stdio","command":"/opt/equipo-tool-proxy","args":["--socket","/tool/equipo.sock"]}}}`) |
| 199 | thread := map[string]any{"model": model, "modelProvider": "openai", "cwd": "/workspace", "approvalPolicy": "on-request", "approvalsReviewer": "user", "permissions": "equipo", "runtimeWorkspaceRoots": []string{"/workspace"}, "config": settings} |
| 200 | thread["experimentalRawEvents"] = true |
| 201 | in.ThreadPolicy = marshal(thread) |
| 202 | in.TurnPolicy = json.RawMessage(`{}`) |
| 203 | if in.Action == "assist" || glance { |
| 204 | // The Assistant (and its glance) answers a person who is waiting: low reasoning |
| 205 | // effort on every turn/start, on the connection's own model (the |
| 206 | // person's choice, unchanged). The pinned app-server sends it as |
| 207 | // the request's reasoning.effort; the team's turns keep the |
| 208 | // model's default. |
| 209 | in.TurnPolicy = marshal(map[string]string{"effort": AssistEffort}) |
| 210 | } |
| 211 | in.Argv = []string{"/opt/codex", "app-server", "--strict-config", "--listen", "stdio://"} |
| 212 | keys := make([]string, 0, len(settings)) |
| 213 | for k := range settings { |
| 214 | keys = append(keys, k) |
| 215 | } |
| 216 | sort.Strings(keys) |
| 217 | for _, k := range keys { |
| 218 | in.Argv = append(in.Argv, "-c", k+"="+toml(settings[k])) |
| 219 | } |
| 220 | return in, nil |
| 221 | } |
| 222 | func toml(v any) string { |
| 223 | switch x := v.(type) { |
| 224 | case int: |
| 225 | return strconv.Itoa(x) |
| 226 | case string: |
| 227 | return strconv.Quote(x) |
| 228 | case bool: |
| 229 | if x { |
| 230 | return "true" |
| 231 | } |
| 232 | return "false" |
| 233 | case []string: |
| 234 | values := make([]string, len(x)) |
| 235 | for i, v := range x { |
| 236 | values[i] = strconv.Quote(v) |
| 237 | } |
| 238 | return "[" + strings.Join(values, ",") + "]" |
| 239 | case map[string]any: |
| 240 | keys := make([]string, 0, len(x)) |
| 241 | for k := range x { |
| 242 | keys = append(keys, k) |
| 243 | } |
| 244 | sort.Strings(keys) |
| 245 | fields := make([]string, 0, len(keys)) |
| 246 | for _, k := range keys { |
| 247 | fields = append(fields, strconv.Quote(k)+"="+toml(x[k])) |
| 248 | } |
| 249 | return "{" + strings.Join(fields, ",") + "}" |
| 250 | } |
| 251 | panic("unsupported policy value") |
| 252 | } |
| 253 | func policyInputs(p provider.Policy) (provider.PolicyInputs, manifest, error) { |
| 254 | var m manifest |
| 255 | if !uniqueJSON(p.Manifest) || json.Unmarshal(p.Manifest, &m) != nil { |
| 256 | return provider.PolicyInputs{}, m, provider.ErrPolicy |
| 257 | } |
| 258 | 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{}} |
| 259 | for _, path := range []string{m.CredentialHome, "/home/runner"} { |
| 260 | for i, p := range in.DeniedPaths { |
| 261 | if p == path { |
| 262 | in.DeniedPaths = append(in.DeniedPaths[:i], in.DeniedPaths[i+1:]...) |
| 263 | break |
| 264 | } |
| 265 | } |
| 266 | } |
| 267 | for _, f := range m.Files { |
| 268 | in.RuntimeFiles = append(in.RuntimeFiles, f.Mount) |
| 269 | } |
| 270 | for _, f := range m.Instructions { |
| 271 | in.InstructionFiles = append(in.InstructionFiles, f.Mount) |
| 272 | } |
| 273 | for _, key := range []string{"LANG", "LC_ALL", "TERM"} { |
| 274 | if v, ok := m.Env[key]; ok { |
| 275 | in.Env[key] = v |
| 276 | } |
| 277 | } |
| 278 | return in, m, nil |
| 279 | } |
| 280 | func (l *Launcher) validatePolicy(b provider.Binding, p provider.Policy) (provider.PolicyInputs, error) { |
| 281 | in, m, e := policyInputs(p) |
| 282 | if e != nil { |
| 283 | return in, e |
| 284 | } |
| 285 | if b.Provider != "codex" || b.Expected.ProviderVersion != Version || in.ProviderVersion != Version { |
| 286 | return in, provider.ErrVersion |
| 287 | } |
| 288 | if e = p.ValidateSources(b); e != nil { |
| 289 | return in, e |
| 290 | } |
| 291 | var tp struct{ Model string } |
| 292 | if json.Unmarshal(in.ThreadPolicy, &tp) != nil { |
| 293 | return in, provider.ErrPolicy |
| 294 | } |
| 295 | want, e := PolicyInputs(b, in, tp.Model) |
| 296 | if e != nil { |
| 297 | return in, e |
| 298 | } |
| 299 | for _, pair := range [][2]json.RawMessage{{in.Settings, want.Settings}, {in.MCP, want.MCP}, {in.ThreadPolicy, want.ThreadPolicy}, {in.TurnPolicy, want.TurnPolicy}} { |
| 300 | if !sameJSON(pair[0], pair[1]) { |
| 301 | return in, provider.ErrPolicy |
| 302 | } |
| 303 | } |
| 304 | 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" { |
| 305 | return in, provider.ErrPolicy |
| 306 | } |
| 307 | binary, helper, toolHelper := false, false, false |
| 308 | for _, f := range m.Files { |
| 309 | if f.Mount.Target == "/opt/codex" { |
| 310 | binary = f.SHA256 == l.digest |
| 311 | } |
| 312 | if f.Mount.Target == "/opt/equipo-tool-proxy" { |
| 313 | toolHelper = f.Mount.ReadOnly |
| 314 | } |
| 315 | if f.Mount.Target == "/opt/codex-code-mode-host" { |
| 316 | helper = f.SHA256 == l.hostDigest |
| 317 | } |
| 318 | if strings.HasPrefix(f.Mount.Target, "/etc/") { |
| 319 | return in, provider.ErrPolicy |
| 320 | } |
| 321 | } |
| 322 | if !binary || !helper || !toolHelper { |
| 323 | return in, provider.ErrVersion |
| 324 | } |
| 325 | if len(in.InstructionFiles) != 0 { |
| 326 | return in, provider.ErrPolicy |
| 327 | } |
| 328 | rebuilt, e := provider.BuildPolicy(b, in) |
| 329 | if e != nil || rebuilt.Hash != p.Hash || rebuilt.ManifestHash != p.ManifestHash { |
| 330 | return in, provider.ErrPolicy |
| 331 | } |
| 332 | return in, nil |
| 333 | } |
| 334 | func (l *Launcher) start(ctx context.Context, launch provider.Launch, handler func(provider.Frame) error) (provider.Process, *provider.Capture, *RPC, error) { |
| 335 | in, _, e := policyInputs(launch.Policy) |
| 336 | if e != nil { |
| 337 | return nil, nil, nil, e |
| 338 | } |
| 339 | if _, e = provider.AttestLaunch(launch, in.Argv); e != nil { |
| 340 | return nil, nil, nil, e |
| 341 | } |
| 342 | proc, e := l.host.Start(ctx, launch, in.Argv) |
| 343 | if e != nil { |
| 344 | return nil, nil, nil, e |
| 345 | } |
| 346 | cap, e := l.captures.Open(ctx, proc, launch) |
| 347 | if e != nil { |
| 348 | return proc, nil, nil, e |
| 349 | } |
| 350 | if cap == nil || cap.Input == nil || cap.Frames == nil || cap.Done == nil { |
| 351 | return proc, cap, nil, errNotReady |
| 352 | } |
| 353 | return proc, cap, newFrameRPC(ctx, cap, handler), nil |
| 354 | } |
| 355 | func waitProcess(proc provider.Process) { |
| 356 | if proc != nil { |
| 357 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 358 | defer cancel() |
| 359 | proc.Wait(ctx) |
| 360 | } |
| 361 | } |
| 362 | func initialize(ctx context.Context, r *RPC) error { |
| 363 | raw, e := r.Call(ctx, "initialize", marshal(map[string]any{"clientInfo": map[string]any{"name": "equipo", "version": "2"}, "capabilities": map[string]any{"experimentalApi": true}})) |
| 364 | if e != nil { |
| 365 | return e |
| 366 | } |
| 367 | var v struct{ UserAgent, CodexHome string } |
| 368 | if json.Unmarshal(raw, &v) != nil || !strings.HasPrefix(v.UserAgent, "equipo/"+Version+" ") || v.CodexHome != "/home/runner" { |
| 369 | return provider.ErrVersion |
| 370 | } |
| 371 | return r.initialized(ctx) |
| 372 | } |
| 373 | func readIdentity(ctx context.Context, r *RPC) (provider.Identity, error) { |
| 374 | raw, e := r.Call(ctx, "account/read", json.RawMessage(`{"refreshToken":false}`)) |
| 375 | if e != nil { |
| 376 | return provider.Identity{}, e |
| 377 | } |
| 378 | return provider.CodexLoginIdentity(raw) |
| 379 | } |
| 380 | func readConfig(ctx context.Context, r *RPC, p provider.Policy) error { |
| 381 | raw, e := r.Call(ctx, "config/read", json.RawMessage(`{"cwd":"/workspace","includeLayers":true}`)) |
| 382 | if e != nil { |
| 383 | return e |
| 384 | } |
| 385 | return validateConfig(raw, p) |
| 386 | } |
| 387 | func validateConfig(raw []byte, p provider.Policy) error { |
| 388 | type origin struct { |
| 389 | Name json.RawMessage |
| 390 | Version string |
| 391 | } |
| 392 | var v struct { |
| 393 | Config map[string]json.RawMessage |
| 394 | Layers []struct { |
| 395 | Name json.RawMessage |
| 396 | Version string |
| 397 | Config json.RawMessage |
| 398 | DisabledReason *string |
| 399 | } |
| 400 | Origins map[string]origin |
| 401 | } |
| 402 | if json.Unmarshal(raw, &v) != nil || v.Layers == nil || v.Origins == nil { |
| 403 | return provider.ErrPolicy |
| 404 | } |
| 405 | var want map[string]json.RawMessage |
| 406 | json.Unmarshal(p.Settings, &want) |
| 407 | // The pinned binary expands defaults; configured values must still match. |
| 408 | if !effectiveConfigMatches(p, v.Config) { |
| 409 | return provider.ErrPolicy |
| 410 | } |
| 411 | var expectedMCP, effectiveMCP map[string]json.RawMessage |
| 412 | if json.Unmarshal(want["mcp_servers"], &expectedMCP) != nil || json.Unmarshal(v.Config["mcp_servers"], &effectiveMCP) != nil || len(expectedMCP) != len(effectiveMCP) { |
| 413 | return provider.ErrPolicy |
| 414 | } |
| 415 | seenFlags, seenDisabledProject := false, false |
| 416 | for _, layer := range v.Layers { |
| 417 | if layer.Version == "" { |
| 418 | return provider.ErrPolicy |
| 419 | } |
| 420 | if layer.DisabledReason != nil { |
| 421 | if seenDisabledProject || !disabledEmptyProject(layer.Name, layer.Config, *layer.DisabledReason) { |
| 422 | return provider.ErrPolicy |
| 423 | } |
| 424 | seenDisabledProject = true |
| 425 | continue |
| 426 | } |
| 427 | switch { |
| 428 | case sameJSON(layer.Name, []byte(`{"type":"sessionFlags"}`)): |
| 429 | if seenFlags || !sameJSON(layer.Config, p.Settings) { |
| 430 | return provider.ErrPolicy |
| 431 | } |
| 432 | seenFlags = true |
| 433 | case emptyConfigLayer(layer.Name): |
| 434 | if !sameJSON(layer.Config, []byte(`{}`)) { |
| 435 | return provider.ErrPolicy |
| 436 | } |
| 437 | default: |
| 438 | return provider.ErrPolicy |
| 439 | } |
| 440 | } |
| 441 | for k, o := range v.Origins { |
| 442 | if _, ok := want[strings.SplitN(k, ".", 2)[0]]; !ok || o.Version == "" || !sameJSON(o.Name, []byte(`{"type":"sessionFlags"}`)) { |
| 443 | return provider.ErrPolicy |
| 444 | } |
| 445 | } |
| 446 | if !seenFlags { |
| 447 | return provider.ErrPolicy |
| 448 | } |
| 449 | return nil |
| 450 | } |
| 451 | func (l *Launcher) Preflight(ctx context.Context, b provider.Binding, p provider.Policy) (provider.Identity, error) { |
| 452 | lease, e := b.AccountLease() |
| 453 | if e != nil { |
| 454 | return provider.Identity{}, e |
| 455 | } |
| 456 | in, e := l.validatePolicy(b, p) |
| 457 | if e != nil { |
| 458 | return provider.Identity{}, e |
| 459 | } |
| 460 | return l.preflight(ctx, b, lease, in) |
| 461 | } |
| 462 | func (l *Launcher) preflight(ctx context.Context, b provider.Binding, lease *provider.AccountLease, in provider.PolicyInputs) (provider.Identity, error) { |
| 463 | var observed provider.Identity |
| 464 | probe := func(ctx context.Context, b provider.Binding) (provider.Identity, error) { |
| 465 | ctx, cancel := context.WithTimeout(ctx, 10*time.Second) |
| 466 | defer cancel() |
| 467 | p, e := provider.BuildPolicy(b, in) |
| 468 | if e != nil { |
| 469 | return provider.Identity{}, e |
| 470 | } |
| 471 | launch := provider.Launch{AttemptKey: "codex-preflight-" + token(), Workspace: in.Workspace, Binding: b, Policy: p, Selection: provider.Selection{Provider: "codex", AccountID: b.AccountID}} |
| 472 | startupNoticeSeen := false |
| 473 | proc, _, r, e := l.start(ctx, launch, func(frame provider.Frame) error { |
| 474 | raw := frame.Bytes |
| 475 | v, _ := parse(raw) |
| 476 | if disabledRemoteControl(v) { |
| 477 | return nil |
| 478 | } |
| 479 | if v.Method == "account/updated" { |
| 480 | if !startupNoticeSeen && provider.CodexStartupNotice(v.ID, v.Method, v.Params) { |
| 481 | startupNoticeSeen = true |
| 482 | return nil |
| 483 | } |
| 484 | return provider.ErrIdentity |
| 485 | } |
| 486 | return errProtocol |
| 487 | }) |
| 488 | defer func() { |
| 489 | if r != nil { |
| 490 | r.close() |
| 491 | } |
| 492 | cancel() |
| 493 | waitProcess(proc) |
| 494 | if r != nil { |
| 495 | <-r.done |
| 496 | } |
| 497 | }() |
| 498 | if e != nil { |
| 499 | return provider.Identity{}, e |
| 500 | } |
| 501 | if e = initialize(ctx, r); e != nil { |
| 502 | return provider.Identity{}, e |
| 503 | } |
| 504 | observed, e = readIdentity(ctx, r) |
| 505 | if e != nil { |
| 506 | return observed, e |
| 507 | } |
| 508 | if e = readConfig(ctx, r, p); e != nil { |
| 509 | return observed, e |
| 510 | } |
| 511 | return observed, nil |
| 512 | } |
| 513 | e := lease.Validate(ctx) |
| 514 | if errors.Is(e, provider.ErrContainment) { |
| 515 | return observed, fmt.Errorf("codex_preflight_lease: %w", e) |
| 516 | } |
| 517 | if errors.Is(e, provider.ErrRefreshPending) { |
| 518 | return observed, provider.ErrAccountMaintenance |
| 519 | } |
| 520 | if e = lease.Preflight(ctx, probe); e != nil { |
| 521 | return observed, fmt.Errorf("codex_preflight_probe: %w", e) |
| 522 | } |
| 523 | _, e = provider.BuildPolicy(b, in) |
| 524 | return observed, e |
| 525 | } |
| 526 | func (l *Launcher) Open(ctx context.Context, launch provider.Launch) (provider.Session, error) { |
| 527 | l.mu.Lock() |
| 528 | defer l.mu.Unlock() |
| 529 | if launch.AttemptKey == "" || l.sessions[launch.AttemptKey] != nil { |
| 530 | return provider.Session{}, errNotReady |
| 531 | } |
| 532 | in, e := l.validatePolicy(launch.Binding, launch.Policy) |
| 533 | if e != nil { |
| 534 | return provider.Session{}, e |
| 535 | } |
| 536 | var tp struct{ Model string } |
| 537 | json.Unmarshal(in.ThreadPolicy, &tp) |
| 538 | if tp.Model != launch.Selection.Model { |
| 539 | return provider.Session{}, provider.ErrIdentity |
| 540 | } |
| 541 | lease, e := launch.Binding.AccountLease() |
| 542 | if e != nil { |
| 543 | return provider.Session{}, e |
| 544 | } |
| 545 | var previous *sessionState |
| 546 | for _, s := range l.sessions { |
| 547 | s.mu.Lock() |
| 548 | busy := s.launch.Binding == launch.Binding && !s.closed |
| 549 | 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 |
| 550 | s.mu.Unlock() |
| 551 | if busy { |
| 552 | return provider.Session{}, provider.ErrAccountBusy |
| 553 | } |
| 554 | if eligible { |
| 555 | previous = s |
| 556 | } |
| 557 | } |
| 558 | if launch.ResumeSessionID != "" && previous == nil { |
| 559 | return provider.Session{}, errUncertain |
| 560 | } |
| 561 | if _, e = l.preflight(ctx, launch.Binding, lease, in); e != nil { |
| 562 | return provider.Session{}, e |
| 563 | } |
| 564 | if e = lease.ValidatePolicy(ctx); e != nil { |
| 565 | return provider.Session{}, fmt.Errorf("codex_open_runtime_policy: %w", e) |
| 566 | } |
| 567 | attempt, cancel := context.WithCancel(ctx) |
| 568 | s := &sessionState{launch: launch, lease: lease, ctx: attempt, cancel: cancel, events: make(chan provider.Event, 128), done: make(chan struct{}), used: map[string]bool{}} |
| 569 | s.session = provider.Session{AttemptKey: launch.AttemptKey, Provider: launch.Selection.Provider, AccountID: launch.Selection.AccountID, Model: launch.Selection.Model, Family: launch.Selection.Family} |
| 570 | s.process, s.capture, s.rpc, e = l.start(attempt, launch, s.handle) |
| 571 | fail := func(e error) (provider.Session, error) { |
| 572 | cancel() |
| 573 | if s.rpc != nil { |
| 574 | s.rpc.close() |
| 575 | <-s.rpc.done |
| 576 | } |
| 577 | waitProcess(s.process) |
| 578 | return provider.Session{}, e |
| 579 | } |
| 580 | if e != nil { |
| 581 | return fail(e) |
| 582 | } |
| 583 | if e = initialize(attempt, s.rpc); e != nil { |
| 584 | return fail(e) |
| 585 | } |
| 586 | if e = s.checkReadback(ctx); e != nil { |
| 587 | return fail(e) |
| 588 | } |
| 589 | if previous != nil { |
| 590 | previous.mu.Lock() |
| 591 | s.mu.Lock() |
| 592 | s.completedProviderTurn = previous.completedProviderTurn |
| 593 | s.completedUsage = bytes.Clone(previous.completedUsage) |
| 594 | s.session.ID = launch.ResumeSessionID |
| 595 | s.mu.Unlock() |
| 596 | previous.mu.Unlock() |
| 597 | } |
| 598 | method := "thread/start" |
| 599 | if launch.ResumeSessionID != "" { |
| 600 | method = "thread/resume" |
| 601 | } |
| 602 | id, e := s.thread(ctx, method, launch.ResumeSessionID) |
| 603 | if e != nil { |
| 604 | return fail(e) |
| 605 | } |
| 606 | s.mu.Lock() |
| 607 | s.session.ID = id |
| 608 | session := s.session |
| 609 | s.mu.Unlock() |
| 610 | if e = session.Validate(launch); e != nil { |
| 611 | return fail(e) |
| 612 | } |
| 613 | if binding, ok := s.capture.Input.(provider.SessionBinding); ok { |
| 614 | if e = binding.BindSession(ctx, session); e != nil { |
| 615 | return fail(e) |
| 616 | } |
| 617 | } |
| 618 | if previous != nil { |
| 619 | previous.mu.Lock() |
| 620 | previous.clean = false |
| 621 | for k, v := range previous.used { |
| 622 | s.used[k] = v |
| 623 | } |
| 624 | previous.mu.Unlock() |
| 625 | } |
| 626 | l.sessions[launch.AttemptKey] = s |
| 627 | go s.monitor() |
| 628 | return session, nil |
| 629 | } |
| 630 | func (s *sessionState) checkReadback(ctx context.Context) error { |
| 631 | id, e := readIdentity(ctx, s.rpc) |
| 632 | if e != nil { |
| 633 | return e |
| 634 | } |
| 635 | if id.AccountID != s.launch.Binding.Expected.AccountID || id.ProviderVersion != s.launch.Binding.Expected.ProviderVersion { |
| 636 | return provider.ErrIdentity |
| 637 | } |
| 638 | return readConfig(ctx, s.rpc, s.launch.Policy) |
| 639 | } |
| 640 | func (s *sessionState) thread(ctx context.Context, method, id string) (string, error) { |
| 641 | if e := s.lease.ValidatePolicy(ctx); e != nil { |
| 642 | return "", e |
| 643 | } |
| 644 | if method == "thread/resume" { |
| 645 | s.mu.Lock() |
| 646 | s.resumeUsagePending = len(s.completedUsage) > 0 |
| 647 | s.mu.Unlock() |
| 648 | } |
| 649 | params := threadParams(s.launch.Policy.ThreadPolicy, method, id) |
| 650 | raw, e := s.rpc.Call(ctx, method, marshal(params)) |
| 651 | if e != nil { |
| 652 | return "", e |
| 653 | } |
| 654 | var v struct { |
| 655 | Thread struct{ ID string } |
| 656 | Model, ModelProvider, Cwd, ApprovalPolicy, ApprovalsReviewer string |
| 657 | ActivePermissionProfile *struct { |
| 658 | ID string |
| 659 | Extends json.RawMessage |
| 660 | } |
| 661 | RuntimeWorkspaceRoots []string |
| 662 | } |
| 663 | 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"}) { |
| 664 | return "", provider.ErrPolicy |
| 665 | } |
| 666 | return v.Thread.ID, nil |
| 667 | } |
| 668 | func (l *Launcher) state(session provider.Session) (*sessionState, error) { |
| 669 | l.mu.Lock() |
| 670 | defer l.mu.Unlock() |
| 671 | s := l.sessions[session.AttemptKey] |
| 672 | if s == nil || s.session != session { |
| 673 | return nil, provider.ErrIdentity |
| 674 | } |
| 675 | return s, nil |
| 676 | } |
| 677 | func (l *Launcher) Events(ctx context.Context, session provider.Session) (<-chan provider.Event, error) { |
| 678 | s, e := l.state(session) |
| 679 | if e != nil { |
| 680 | return nil, e |
| 681 | } |
| 682 | s.mu.Lock() |
| 683 | defer s.mu.Unlock() |
| 684 | if e = ctx.Err(); e != nil { |
| 685 | return nil, e |
| 686 | } |
| 687 | if s.attached { |
| 688 | return nil, errNotReady |
| 689 | } |
| 690 | s.attached = true |
| 691 | return s.events, nil |
| 692 | } |
| 693 | func (s *sessionState) stop(e error) error { |
| 694 | s.mu.Lock() |
| 695 | if s.err == nil { |
| 696 | s.err = e |
| 697 | } |
| 698 | s.mu.Unlock() |
| 699 | s.cancel() |
| 700 | s.rpc.close() |
| 701 | return e |
| 702 | } |
| 703 | func (l *Launcher) StartTurn(ctx context.Context, session provider.Session, t provider.Turn) error { |
| 704 | s, e := l.state(session) |
| 705 | if e != nil { |
| 706 | return e |
| 707 | } |
| 708 | s.op.Lock() |
| 709 | defer s.op.Unlock() |
| 710 | s.mu.Lock() |
| 711 | fresh := !s.turnStarted && s.launch.ResumeSessionID == "" |
| 712 | ready := !s.closed && s.err == nil && !s.active && s.attached && t.ID != "" && t.AdmissionID != "" && t.Prompt != "" && !s.used[t.ID] && !s.used[t.AdmissionID] |
| 713 | s.mu.Unlock() |
| 714 | if !ready { |
| 715 | return errNotReady |
| 716 | } |
| 717 | if e = ctx.Err(); e != nil { |
| 718 | return e |
| 719 | } |
| 720 | e = s.lease.ValidatePolicy(ctx) |
| 721 | if errors.Is(e, provider.ErrRefreshPending) || errors.Is(e, provider.ErrPreflightRequired) { |
| 722 | if e = s.launch.Policy.ValidateSources(s.launch.Binding); e != nil { |
| 723 | return s.stop(e) |
| 724 | } |
| 725 | in, _, inputErr := policyInputs(s.launch.Policy) |
| 726 | if inputErr != nil { |
| 727 | return s.stop(inputErr) |
| 728 | } |
| 729 | _, e = l.preflight(ctx, s.launch.Binding, s.lease, in) |
| 730 | } |
| 731 | if e != nil { |
| 732 | return s.stop(e) |
| 733 | } |
| 734 | in, _, e := policyInputs(s.launch.Policy) |
| 735 | if e != nil { |
| 736 | return s.stop(e) |
| 737 | } |
| 738 | if _, e = provider.AttestLaunch(s.launch, in.Argv); e != nil { |
| 739 | return s.stop(e) |
| 740 | } |
| 741 | if e = s.checkReadback(ctx); e != nil { |
| 742 | return s.stop(e) |
| 743 | } |
| 744 | // A fresh pinned thread has no rollout until its first turn. Open already |
| 745 | // verified its effective policy; later turns must reassert the saved thread. |
| 746 | if !fresh { |
| 747 | if _, e = s.thread(ctx, "thread/resume", session.ID); e != nil { |
| 748 | return s.stop(e) |
| 749 | } |
| 750 | } |
| 751 | if e = s.beginTurn(ctx, t); e != nil { |
| 752 | return s.stop(e) |
| 753 | } |
| 754 | var params map[string]json.RawMessage |
| 755 | json.Unmarshal(s.launch.Policy.TurnPolicy, ¶ms) |
| 756 | params["threadId"] = marshal(session.ID) |
| 757 | params["input"] = marshal([]any{map[string]any{"type": "text", "text": t.Prompt}}) |
| 758 | if barrier, ok := s.capture.Input.(provider.TurnBarrier); ok { |
| 759 | if e = barrier.BeginTurn(ctx, session, t); e != nil { |
| 760 | return s.stop(e) |
| 761 | } |
| 762 | } |
| 763 | s.mu.Lock() |
| 764 | s.turnStarted = true |
| 765 | s.mu.Unlock() |
| 766 | raw, e := s.rpc.Call(ctx, "turn/start", marshal(params)) |
| 767 | if e != nil { |
| 768 | return s.stop(errUncertain) |
| 769 | } |
| 770 | var result struct{ Turn struct{ ID string } } |
| 771 | if json.Unmarshal(raw, &result) != nil || result.Turn.ID == "" { |
| 772 | return s.stop(errProtocol) |
| 773 | } |
| 774 | s.mu.Lock() |
| 775 | if s.providerTurn == "" { |
| 776 | s.providerTurn = result.Turn.ID |
| 777 | } |
| 778 | mismatch := s.providerTurn != result.Turn.ID |
| 779 | currentErr := s.err |
| 780 | s.mu.Unlock() |
| 781 | if mismatch { |
| 782 | return s.stop(provider.ErrIdentity) |
| 783 | } |
| 784 | return currentErr |
| 785 | } |
| 786 | func (l *Launcher) Respond(ctx context.Context, s provider.Session, a provider.Answer) error { |
| 787 | return l.respond(ctx, s, a) |
| 788 | } |
| 789 | func (l *Launcher) Interrupt(ctx context.Context, session provider.Session) error { |
| 790 | s, e := l.state(session) |
| 791 | if e != nil { |
| 792 | return e |
| 793 | } |
| 794 | s.mu.Lock() |
| 795 | id := s.providerTurn |
| 796 | active := s.active |
| 797 | s.mu.Unlock() |
| 798 | defer s.stop(errUncertain) |
| 799 | if !active || id == "" { |
| 800 | return nil |
| 801 | } |
| 802 | ctx, cancel := context.WithTimeout(ctx, time.Second) |
| 803 | defer cancel() |
| 804 | _, e = s.rpc.Call(ctx, "turn/interrupt", marshal(map[string]any{"threadId": session.ID, "turnId": id})) |
| 805 | return e |
| 806 | } |
| 807 | func (l *Launcher) Close(ctx context.Context, session provider.Session) error { |
| 808 | s, e := l.state(session) |
| 809 | if e != nil { |
| 810 | return e |
| 811 | } |
| 812 | s.mu.Lock() |
| 813 | s.closed = true |
| 814 | active := s.active |
| 815 | s.mu.Unlock() |
| 816 | if active { |
| 817 | s.stop(errUncertain) |
| 818 | } else { |
| 819 | s.capture.Input.Close() |
| 820 | } |
| 821 | ctx, cancel := context.WithTimeout(ctx, 5*time.Second) |
| 822 | defer cancel() |
| 823 | select { |
| 824 | case <-s.done: |
| 825 | case <-ctx.Done(): |
| 826 | s.stop(ctx.Err()) |
| 827 | return ctx.Err() |
| 828 | } |
| 829 | s.mu.Lock() |
| 830 | defer s.mu.Unlock() |
| 831 | return s.err |
| 832 | } |
| 833 | func (s *sessionState) handle(frame provider.Frame) error { |
| 834 | events, e := Decode(frame.Bytes) |
| 835 | if e != nil { |
| 836 | return e |
| 837 | } |
| 838 | s.mu.Lock() |
| 839 | defer s.mu.Unlock() |
| 840 | v, _ := parse(frame.Bytes) |
| 841 | if v.Method == "account/updated" { |
| 842 | if !s.turnStarted && !s.startupNoticeSeen && provider.CodexStartupNotice(v.ID, v.Method, v.Params) { |
| 843 | s.startupNoticeSeen = true |
| 844 | return nil |
| 845 | } |
| 846 | return provider.ErrContainment |
| 847 | } |
| 848 | for _, ev := range events { |
| 849 | ev.Sequence = frame.Sequence |
| 850 | if strings.HasPrefix(ev.Kind, "config/") { |
| 851 | return provider.ErrContainment |
| 852 | } |
| 853 | if ev.SessionID != "" && s.session.ID != "" && ev.SessionID != s.session.ID { |
| 854 | return provider.ErrIdentity |
| 855 | } |
| 856 | if ev.Kind == "usage" && ev.TurnID == s.completedProviderTurn && s.completedProviderTurn != "" { |
| 857 | if !s.resumeUsagePending || !sameJSON(v.Params, s.completedUsage) { |
| 858 | return errProtocol |
| 859 | } |
| 860 | s.resumeUsagePending = false |
| 861 | continue |
| 862 | } |
| 863 | if ev.Kind == "usage" { |
| 864 | s.lastUsage = bytes.Clone(v.Params) |
| 865 | } |
| 866 | if ev.TurnID == "" && ev.Kind == "request" { |
| 867 | v, _ := parse(ev.Payload) |
| 868 | if (v.Method == "execCommandApproval" || v.Method == "applyPatchApproval") && s.active && s.providerTurn != "" { |
| 869 | ev.TurnID = s.providerTurn |
| 870 | } |
| 871 | } |
| 872 | if ev.TurnID != "" { |
| 873 | ev.ProviderTurnID = ev.TurnID |
| 874 | if !s.active { |
| 875 | return errProtocol |
| 876 | } |
| 877 | if s.providerTurn == "" { |
| 878 | s.providerTurn = ev.TurnID |
| 879 | } |
| 880 | if ev.TurnID != s.providerTurn { |
| 881 | return provider.ErrIdentity |
| 882 | } |
| 883 | ev.TurnID = s.turn.ID |
| 884 | } else if ev.Kind == "turn.completed" || ev.Kind == "turn.failed" || ev.Kind == "usage" || ev.Kind == "request" { |
| 885 | return errProtocol |
| 886 | } |
| 887 | var envelope struct { |
| 888 | Method string |
| 889 | Params struct { |
| 890 | RequestID json.RawMessage `json:"requestId"` |
| 891 | Item struct{ ID, Type string } |
| 892 | } |
| 893 | } |
| 894 | _ = json.Unmarshal(ev.Payload, &envelope) |
| 895 | if envelope.Method == "serverRequest/resolved" { |
| 896 | delete(s.requests, string(envelope.Params.RequestID)) |
| 897 | } |
| 898 | if envelope.Params.Item.Type == "mcpToolCall" { |
| 899 | if envelope.Method == "item/started" { |
| 900 | if s.mcpCalls == nil { |
| 901 | s.mcpCalls = map[string]json.RawMessage{} |
| 902 | } |
| 903 | if len(s.mcpCalls) >= 64 { |
| 904 | return errProtocol |
| 905 | } |
| 906 | s.mcpCalls[envelope.Params.Item.ID] = bytes.Clone(ev.Payload) |
| 907 | } else if envelope.Method == "item/completed" { |
| 908 | delete(s.mcpCalls, envelope.Params.Item.ID) |
| 909 | } |
| 910 | } |
| 911 | if envelope.Params.Item.Type == "fileChange" { |
| 912 | if envelope.Method == "item/started" { |
| 913 | if s.nativeCalls == nil { |
| 914 | s.nativeCalls = map[string]json.RawMessage{} |
| 915 | } |
| 916 | if len(s.nativeCalls) >= 64 { |
| 917 | return errProtocol |
| 918 | } |
| 919 | s.nativeCalls[envelope.Params.Item.ID] = bytes.Clone(ev.Payload) |
| 920 | } else if envelope.Method == "item/completed" { |
| 921 | delete(s.nativeCalls, envelope.Params.Item.ID) |
| 922 | } |
| 923 | } |
| 924 | if ev.Kind == "request" { |
| 925 | if !supportedRequest(envelope.Method) { |
| 926 | return s.rpc.answer(s.ctx, s.session, s.turn.ID, requestRefusal(ev.RequestID)) |
| 927 | } |
| 928 | s.correlateMCP(&ev) |
| 929 | s.correlateNative(&ev) |
| 930 | if s.requests == nil { |
| 931 | s.requests = map[string]provider.Event{} |
| 932 | } |
| 933 | if _, exists := s.requests[ev.RequestID]; exists || len(s.requests) >= 64 { |
| 934 | return errProtocol |
| 935 | } |
| 936 | s.requests[ev.RequestID] = ev |
| 937 | } |
| 938 | if ev.Kind == "turn.completed" || ev.Kind == "turn.failed" { |
| 939 | e = s.lease.EndTurn(context.Background()) |
| 940 | s.active = false |
| 941 | s.requests = nil |
| 942 | s.mcpCalls = nil |
| 943 | s.nativeCalls = nil |
| 944 | if e != nil && !errors.Is(e, provider.ErrRefreshPending) { |
| 945 | return e |
| 946 | } |
| 947 | s.finished = ev.Kind == "turn.completed" |
| 948 | if s.finished { |
| 949 | s.completedProviderTurn = s.providerTurn |
| 950 | s.completedUsage = bytes.Clone(s.lastUsage) |
| 951 | } |
| 952 | if !s.finished { |
| 953 | s.err = errFailed |
| 954 | } |
| 955 | } |
| 956 | select { |
| 957 | case s.events <- ev: |
| 958 | default: |
| 959 | return errProtocol |
| 960 | } |
| 961 | } |
| 962 | return nil |
| 963 | } |
| 964 | func (s *sessionState) monitor() { |
| 965 | defer close(s.done) |
| 966 | defer close(s.events) |
| 967 | <-s.rpc.done |
| 968 | s.rpc.mu.Lock() |
| 969 | rpcErr := s.rpc.err |
| 970 | s.rpc.mu.Unlock() |
| 971 | s.mu.Lock() |
| 972 | closing := s.closed |
| 973 | active := s.active |
| 974 | s.mu.Unlock() |
| 975 | if !closing || active || !errors.Is(rpcErr, io.EOF) { |
| 976 | s.cancel() |
| 977 | } |
| 978 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 979 | defer cancel() |
| 980 | exit, e := s.process.Wait(ctx) |
| 981 | s.mu.Lock() |
| 982 | defer s.mu.Unlock() |
| 983 | if s.active { |
| 984 | s.lease.EndTurn(context.Background()) |
| 985 | s.active = false |
| 986 | s.err = errUncertain |
| 987 | } |
| 988 | if e != nil || exit.Code != 0 || exit.Signal != 0 || !s.closed || !errors.Is(rpcErr, io.EOF) { |
| 989 | if s.err == nil { |
| 990 | s.err = errFailed |
| 991 | } |
| 992 | } |
| 993 | s.clean = s.closed && s.finished && s.err == nil |
| 994 | if s.err != nil { |
| 995 | select { |
| 996 | case s.events <- provider.Event{SessionID: s.session.ID, TurnID: s.turn.ID, Kind: "turn.failed"}: |
| 997 | default: |
| 998 | } |
| 999 | } |
| 1000 | s.cancel() |
| 1001 | } |
| 1002 | |
| 1003 | func (s *sessionState) beginTurn(ctx context.Context, t provider.Turn) error { |
| 1004 | s.mu.Lock() |
| 1005 | defer s.mu.Unlock() |
| 1006 | if s.closed || s.err != nil || s.ctx.Err() != nil { |
| 1007 | return errNotReady |
| 1008 | } |
| 1009 | if e := s.lease.BeginTurn(ctx); e != nil { |
| 1010 | return e |
| 1011 | } |
| 1012 | s.active = true |
| 1013 | s.finished = false |
| 1014 | s.turn = t |
| 1015 | s.providerTurn = "" |
| 1016 | s.lastUsage = nil |
| 1017 | s.used[t.ID] = true |
| 1018 | s.used[t.AdmissionID] = true |
| 1019 | return nil |
| 1020 | } |
| 1021 | |
| 1022 | func emptyConfigLayer(raw []byte) bool { |
| 1023 | var n struct{ Type, File string } |
| 1024 | if json.Unmarshal(raw, &n) != nil { |
| 1025 | return false |
| 1026 | } |
| 1027 | return n.Type == "user" && n.File == "/home/runner/config.toml" || n.Type == "system" && n.File == "/etc/codex/config.toml" |
| 1028 | } |
| 1029 | func configSubset(want, got []byte) bool { |
| 1030 | var w, g map[string]json.RawMessage |
| 1031 | if json.Unmarshal(want, &w) != nil || json.Unmarshal(got, &g) != nil || w == nil || g == nil { |
| 1032 | return sameJSON(want, got) |
| 1033 | } |
| 1034 | for k, v := range w { |
| 1035 | if !configSubset(v, g[k]) { |
| 1036 | return false |
| 1037 | } |
| 1038 | } |
| 1039 | return true |
| 1040 | } |
| 1041 | |
| 1042 | func threadParams(policy json.RawMessage, method, id string) map[string]json.RawMessage { |
| 1043 | var params map[string]json.RawMessage |
| 1044 | _ = json.Unmarshal(policy, ¶ms) |
| 1045 | if method == "thread/resume" { |
| 1046 | delete(params, "experimentalRawEvents") |
| 1047 | params["excludeTurns"] = marshal(true) |
| 1048 | params["threadId"] = marshal(id) |
| 1049 | } |
| 1050 | return params |
| 1051 | } |
| 1052 | |