package thin import ( "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "io" "io/fs" "os" "path/filepath" "slices" "strings" "sync" "time" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/connect" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/provider/codex" "amadan.net/oficina/equipo/internal/wire" ) // CodexOptions pins the Codex binaries a coordinator may run. Tests pass // their fake's digests; production uses the pinned 0.165.0 build. type CodexOptions struct { Digest, HostDigest string } func (x *CodexOptions) defaults() { if x.Digest == "" { x.Digest = codex.ExecutableSHA256 } if x.HostDigest == "" { x.HostDigest = codex.CodeModeHostSHA256 } } // OpenCodex returns the person's coordinator on one Codex connection: // the pinned `codex app-server` in the converse containment (the same // bubblewrap namespace, egress to the provider only, no shell, no patch, // exactly the conversation's Equipo tools), driven over JSON-RPC. func OpenCodex(o ClaudeOptions, x CodexOptions, person string, b runner.AccountBinding) (Coordinator, error) { return openCodex(o, x, person, wire.LaneCoordinator, b) } func openCodex(o ClaudeOptions, x CodexOptions, person, lane string, b runner.AccountBinding) (Coordinator, error) { o.defaults() x.defaults() if b.Provider != "codex" || b.PersonID != person { return nil, provider.ErrIdentity } c := &codexCoordinator{x: x} if err := c.open(o, person, lane, b); err != nil { return nil, err } return c, nil } type codexCoordinator struct { coordBase x CodexOptions mu sync.Mutex proc *codexProcess idle *time.Timer idleAt time.Time } type codexProcess struct { access bool lease *provider.AccountLease process provider.Process cancel context.CancelFunc rpc *connect.AppServer exited chan struct{} thread string fresh bool turns int policy provider.Policy tool *toolSocket scratch string exitErr error // tally aggregates the thread's usage notices into attempt rows. tally *connect.CodexTally } func (c *codexCoordinator) Close() { c.mu.Lock() defer c.mu.Unlock() if c.idle != nil { c.idle.Stop() } c.stop(true) } func (c *codexCoordinator) idleExit() { c.mu.Lock() defer c.mu.Unlock() c.stop(true) } // Warm starts the app-server ahead of the first turn: initialize, the // account and configuration checks, and thread/start or thread/resume, // none of which is a turn, so the model is sent nothing. Unused, it // closes after WarmIdle. func (c *codexCoordinator) Warm(ctx context.Context) error { c.mu.Lock() defer c.mu.Unlock() if c.proc != nil { return nil } if err := c.start(ctx); err != nil { return err } if c.idle != nil { c.idle.Stop() } c.idle, c.idleAt = time.AfterFunc(c.o.WarmIdle, c.idleExit), time.Now().Add(c.o.WarmIdle) return nil } // codexItem is the part of an item notification the coordinator reads. type codexItem struct { ID string `json:"id"` Type string `json:"type"` Text string `json:"text"` Server string `json:"server"` Tool string `json:"tool"` Arguments json.RawMessage `json:"arguments"` // Command and Changes are a step's shell command and file changes. Command string `json:"command"` Changes []struct { Path string `json:"path"` } `json:"changes"` } func (c *codexCoordinator) Turn(ctx context.Context, in TurnInput, emit func(string)) TurnResult { c.mu.Lock() defer c.mu.Unlock() if err := c.desk.SavePlacementNotes(in.PlacementNotes); err != nil { return TurnResult{Reason: "account_unavailable"} } defer c.unstage() files, err := c.laneFiles(in.Attachments) if err != nil { return c.missing(ctx, in) } if c.idle != nil { c.idle.Stop() } if c.proc != nil && c.profile.action == "converse" && c.proc.access != (c.accessProtocol() >= wire.ProtocolAccess) { c.stop(true) } if p := c.proc; p != nil { select { case <-p.exited: c.stop(false) default: if time.Now().Add(c.o.MaxTurn + c.o.Margin).After(p.lease.FreshUntil()) { c.stop(true) } } } cold := c.proc == nil if c.proc == nil { if err := c.start(ctx); err != nil { c.log("codex coordinator start", err) if ctx.Err() != nil { return TurnResult{Reason: "cancelled"} } return TurnResult{Reason: reasonFor(err)} } } p := c.proc limit := min(c.o.MaxTurn, time.Until(p.lease.FreshUntil())-c.o.Margin) if limit < minTurn { c.stop(true) return TurnResult{Reason: "account_unavailable"} } if err := p.lease.CheckCopy(ctx); err != nil { c.log("codex coordinator copy", err) c.stop(false) return TurnResult{Reason: reasonFor(err)} } var catalog []wire.RepoInfo if c.o.Catalog != nil { catalog = c.o.Catalog() } prompt, explored := c.prompt(p.fresh && p.turns == 0, in, catalog) // Images go in as localImage inputs by their path in the namespace. var images []string shown := map[string]bool{} for _, f := range files { if f.Kind == wire.AttachmentImage { images = append(images, f.Path) shown[f.ID] = true } } prompt = strings.TrimLeft(prompt+attachmentNote(files, shown, c.lane)+c.earlierNote(in), "\n") tctx, cancel := context.WithTimeout(ctx, limit) defer cancel() tctx = context.WithValue(tctx, factsKey{}, factsFor(in)) c.setTurn(tctx, in.TurnID, in.Attempt, in.Kind) defer c.clearTurn() activity := in.Activity if activity == nil { activity = func(string, string) {} } start := time.Now() timing := &wire.TurnTiming{Cold: cold} if !in.Received.IsZero() { timing.StartMs = start.Sub(in.Received).Milliseconds() } mark := func(at *int64) { if *at == 0 { *at = max(time.Since(start).Milliseconds(), 1) } } raw, _, err := p.rpc.Call(tctx, "turn/start", codex.TurnParamsWithImages(p.policy, p.thread, prompt, images)) var started struct { Turn struct{ ID string } `json:"turn"` } if err != nil || json.Unmarshal(raw, &started) != nil || started.Turn.ID == "" { c.stop(false) if ctx.Err() != nil { return TurnResult{Reason: "cancelled"} } return TurnResult{Reason: "provider_failed"} } turnID := started.Turn.ID p.tally.Begin(turnID) usage := func() []wire.Usage { row := p.tally.Row() row.Model = c.account.Model return []wire.Usage{row} } var seen *connect.Limit plan := "" final := "" items := map[string]codexItem{} lastActivity := "" for { select { case <-tctx.Done(): // What the turn used so far is kept (complete: false). c.interrupt(p, turnID) c.stop(false) if ctx.Err() != nil { return TurnResult{Reason: "cancelled", Usage: usage()} } return TurnResult{Reason: "turn_timeout", Usage: usage()} case m, ok := <-p.rpc.Messages: if !ok { c.stop(false) if ctx.Err() != nil { return TurnResult{Reason: "cancelled", Usage: usage()} } return TurnResult{Reason: "provider_failed", Usage: usage()} } mark(&timing.FirstEventMs) if len(m.ID) > 0 { c.answer(p, m, items) continue } var n struct { ThreadID string `json:"threadId"` TurnID string `json:"turnId"` Delta string `json:"delta"` Item codexItem `json:"item"` Turn json.RawMessage `json:"turn"` RateLimits json.RawMessage `json:"rateLimits"` } if json.Unmarshal(m.Params, &n) != nil { continue } if n.ThreadID != "" && n.ThreadID != p.thread { c.stop(false) return TurnResult{Reason: "policy_rejected"} } switch m.Method { case "item/agentMessage/delta": if n.TurnID == turnID && n.Delta != "" { mark(&timing.FirstTextMs) timing.LastTextMs = max(time.Since(start).Milliseconds(), 1) emit(n.Delta) } case "item/started": kind, tool := "", "" switch n.Item.Type { case "reasoning": kind = wire.ActivityThink mark(&timing.FirstThinkingMs) case "mcpToolCall": items[n.Item.ID] = n.Item kind, tool = wire.ActivityTool, activityName(n.Item.Tool, c.accessToolSet(true).names) if n.Item.Server != "equipo" { tool = "other" } mark(&timing.FirstToolMs) } if kind != "" && kind+"/"+tool != lastActivity { lastActivity = kind + "/" + tool activity(kind, tool) } case "item/completed": if n.Item.Type == "agentMessage" && strings.TrimSpace(n.Item.Text) != "" { final = n.Item.Text } delete(items, n.Item.ID) case "account/rateLimits/updated": if l, pl, ok := connect.CodexRateLimits(n.RateLimits); ok { seen = &l if pl != "" { plan = pl } } case "thread/tokenUsage/updated": if thread, turn, total, last, ok := connect.CodexNotice(m.Params); ok { p.tally.Notice(thread, turn, total, last) } case "turn/completed": var t struct { ID string `json:"id"` Status string `json:"status"` Error json.RawMessage `json:"error"` } if json.Unmarshal(n.Turn, &t) != nil || t.ID != turnID { continue } p.tally.End() if t.Status != "completed" { proven := c.stop(false) switch { case ctx.Err() != nil || t.Status == "interrupted": return TurnResult{Reason: "cancelled", Usage: usage()} case connect.CodexFailure(t.Error) == connect.FailQuota || seen != nil && seen.Limited: l := connect.Limit{Limited: true} if seen != nil { l = *seen l.Limited = true } return TurnResult{Reason: "limited", Limit: &l, Plan: plan, Proven: proven, Usage: usage()} case connect.CodexFailure(t.Error) == connect.FailAuth: return TurnResult{Reason: "sign_in_again", SignIn: true, Proven: proven, Usage: usage()} } return TurnResult{Reason: "provider_failed", Seen: seen, Plan: plan, Usage: usage()} } p.turns++ if c.lane == wire.LaneCoordinator && settles(in.Kind) { if err := c.settled(in.Kind, explored, catalog); err != nil { c.log("codex coordinator desk", err) c.syncOut(p) return TurnResult{Reason: "desk_unavailable"} } } c.noteHash = noteHash(c.desk.Notebook(notebookContext)) c.syncOut(p) if err := c.o.State.saveSession(context.Background(), c.person, c.lane, "codex", c.sessionAccount(), p.thread, in.TurnID); err != nil { c.log("codex coordinator session", err) } idle := c.idleAfterTurn() c.idle, c.idleAt = time.AfterFunc(idle, c.idleExit), time.Now().Add(idle) timing.ResultMs = max(time.Since(start).Milliseconds(), 1) return TurnResult{Text: final, Usage: usage(), Timing: timing, Seen: seen, Plan: plan} } } } } // answer replies to a request the app-server makes: only the lane's own // Equipo tools are approved. func (c *codexCoordinator) answer(p *codexProcess, m connect.Message, items map[string]codexItem) { answerApproval(p.rpc, m, items, c.accessToolSet(true).names) } // answerApproval replies to a request the app-server makes. Only an // approval to call one of names on the Equipo server, correlated with the // tool call Codex started, is accepted; every other request (shell, // patch, questions, anything new) is refused. It reports whether it // accepted. func answerApproval(rpc *connect.AppServer, m connect.Message, items map[string]codexItem, names []string) bool { if m.Method == "mcpServer/elicitation/request" { server, args, ok := codex.ToolApproval(m.Params) if ok && server == "equipo" { for _, it := range items { if it.Server == "equipo" && slices.Contains(names, it.Tool) && codex.SameArguments(it.Arguments, args) { _ = rpc.Answer(m.ID, map[string]any{"action": "accept", "content": map[string]any{}}) return true } } } _ = rpc.Answer(m.ID, map[string]any{"action": "decline"}) return false } _ = rpc.Refuse(m.ID) return false } func (c *codexCoordinator) interrupt(p *codexProcess, turn string) { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() _, _, _ = p.rpc.Call(ctx, "turn/interrupt", map[string]string{"threadId": p.thread, "turnId": turn}) } func (c *codexCoordinator) start(ctx context.Context) (err error) { o := c.o direct, err := o.Runner.DirectBinding(c.account) if err != nil { return atStep("binding", err) } // The refresh's failures are told apart from the copy's own checks. refresh := o.Refresh if refresh != nil { refresh = func(ctx context.Context, b provider.Binding) (provider.Identity, error) { id, err := o.Refresh(ctx, b) return id, atStep("refresh", err) } } lease, err := provider.OpenRuntimeCopy(ctx, direct, refresh, o.LockWait) if err != nil { return atStep("copy", err) } p := &codexProcess{access: c.accessProtocol() >= wire.ProtocolAccess, lease: lease, exited: make(chan struct{})} defer func() { if err != nil { c.cleanup(p) } }() binding := lease.Binding() var row sessionRow found := false if !c.profile.ephemeral { if row, found, err = o.State.session(ctx, c.person, c.lane, "codex"); err != nil { return atStep("session", err) } } y1, m1, d1 := row.Updated.UTC().Date() y2, m2, d2 := time.Now().UTC().Date() resume := found && row.Account == c.sessionAccount() && y1 == y2 && m1 == m2 && d1 == d2 && validThread(row.SessionID) if resume { resume = copyRollouts(c.home, binding.Home, row.SessionID) == nil } if !resume { pruneRollouts(c.home) } if p.scratch, err = os.MkdirTemp(o.Runner.ScratchRoot, "policy-"); err != nil { return atStep("policy_scratch", err) } var call ToolReplyFunc if o.Tools != nil { call = c.toolReply } if p.tool, err = openReplySet(context.Background(), o.Runner.StateDir, c.accessToolSet(call != nil), call); err != nil { return atStep("tool_socket", err) } sel := provider.Selection{ConnectionID: c.account.LocalID, Provider: "codex", Family: c.account.Family, Model: c.account.Model, AccountID: c.account.AccountID} in, err := runner.PolicyInputs(ctx, o.Runner, sel, binding, c.workspace(), c.profile.action, p.scratch, c.accessProtocol() < wire.ProtocolAccess) if err != nil { return atStep("policy_inputs", err) } if p.policy, err = provider.BuildPolicy(binding, in); err != nil { return atStep("policy_build", err) } if err = codex.ValidateThinPolicy(binding, p.policy, c.x.Digest, c.x.HostDigest); err != nil { return atStep("policy_pin", err) } if err = lease.CheckCopy(ctx); err != nil { return atStep("copy_check", err) } personKey := sha256.Sum256([]byte(c.person)) launch := provider.Launch{ToolSocket: p.tool.Path, AttemptKey: c.profile.action + "/" + hex.EncodeToString(personKey[:8]) + "/" + uuid(), Workspace: c.workspace(), Selection: sel, Binding: binding, Policy: p.policy} pctx, cancel := context.WithCancel(context.Background()) p.cancel = cancel if p.process, err = o.Manager.StartRecorded(pctx, launch, in.Argv, nil); err != nil { return atStep("namespace", err) } p.rpc = connect.NewAppServer(p.process.Stdout(), p.process.Stdin()) go func() { _, _ = io.Copy(io.Discard, io.LimitReader(p.process.Stderr(), 1<<20)) }() go func() { _, p.exitErr = p.process.Wait(context.Background()) close(p.exited) }() sctx, done := context.WithTimeout(ctx, 30*time.Second) defer done() // The pinned version, its home the runtime copy, the expected // account, and the effective configuration the policy rendered. raw, _, err := p.rpc.Call(sctx, "initialize", codex.InitializeParams()) if err == nil { err = codex.CheckInitialize(raw) } if err == nil { err = p.rpc.Notify("initialized", map[string]any{}) } if err == nil { raw, _, err = p.rpc.Call(sctx, "account/read", map[string]bool{"refreshToken": false}) } if err == nil { var id provider.Identity if id, err = provider.CodexLoginIdentity(raw); err == nil && id.AccountID != c.account.AccountID { err = provider.ErrIdentity } } if err == nil { raw, _, err = p.rpc.Call(sctx, "config/read", map[string]any{"cwd": "/workspace", "includeLayers": true}) } if err == nil { err = codex.CheckConfig(raw, p.policy) } if err != nil { c.proc = p c.stop(false) return atStep("handshake", errors.Join(provider.ErrPolicy, err)) } p.fresh = !resume if resume { raw, _, err = p.rpc.Call(sctx, "thread/resume", codex.ThreadParams(p.policy, row.SessionID)) if err == nil { p.thread, err = codex.CheckThread(raw, c.threadModel(), row.SessionID) } if errors.Is(err, provider.ErrPolicy) { c.proc = p c.stop(false) return atStep("thread", err) } // A thread Codex cannot resume starts afresh, seeded like any new // session from the notebook and the tail. p.fresh = err != nil } if p.fresh { raw, _, err = p.rpc.Call(sctx, "thread/start", codex.ThreadParams(p.policy, "")) if err == nil { p.thread, err = codex.CheckThread(raw, c.threadModel(), "") } if err != nil { c.proc = p c.stop(false) return atStep("thread", errors.Join(provider.ErrPolicy, err)) } } p.tally = connect.NewCodexTally(p.thread, p.fresh) c.proc = p c.up.Store(true) return nil } // threadModel is the model the lane's thread runs: the connection's, or // for a glance its provider's small model. func (c *codexCoordinator) threadModel() string { return provider.LaunchModel(c.profile.action, "codex", c.account.Model) } // stop ends the process; the exit is observed by the containment before // the copy and scratch are removed. func (c *codexCoordinator) stop(clean bool) bool { p := c.proc if p == nil { return true } proven := p.process == nil c.proc = nil c.up.Store(false) if p.process != nil { if clean { p.process.Stdin().Close() select { case <-p.exited: case <-time.After(10 * time.Second): } } p.cancel() select { case <-p.exited: proven = p.exitErr == nil case <-time.After(30 * time.Second): c.log("codex coordinator stop", errors.New("exit not observed")) } c.syncOut(p) } c.cleanup(p) return proven } func (c *codexCoordinator) cleanup(p *codexProcess) { if p.cancel != nil { p.cancel() } if p.process != nil { c.forget(p.process.ID()) } if p.tool != nil { p.tool.Close() } if p.lease != nil { c.log("codex coordinator copy close", p.lease.Close()) } if p.scratch != "" { os.RemoveAll(p.scratch) } } // syncOut keeps the thread's rollout in the durable session home, so a // later process can resume it. func (c *codexCoordinator) syncOut(p *codexProcess) { if p.thread == "" || p.lease == nil { return } if err := copyRollouts(p.lease.Binding().Home, c.home, p.thread); err != nil && !errors.Is(err, fs.ErrNotExist) { c.log("codex coordinator rollout", err) } } // validThread is a Codex thread id (a UUID), never a path. func validThread(id string) bool { if len(id) < 8 || len(id) > 64 { return false } for _, r := range id { if !(r >= '0' && r <= '9' || r >= 'a' && r <= 'f' || r == '-') { return false } } return true } // copyRollouts copies the thread's rollout files under sessions/ from one // Codex home to another, keeping their place in the tree; links and // anything else are skipped. func copyRollouts(from, to, thread string) error { if !validThread(thread) { return fs.ErrInvalid } root := filepath.Join(from, "sessions") found := false err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { if err != nil { return err } if !d.Type().IsRegular() || !strings.HasSuffix(d.Name(), "-"+thread+".jsonl") { return nil } rel, err := filepath.Rel(from, path) if err != nil { return err } found = true return copyPrivate(path, filepath.Join(to, rel)) }) if err == nil && !found { err = fs.ErrNotExist } return err } // pruneRollouts keeps the session home to the thread in use. func pruneRollouts(home string) { os.RemoveAll(filepath.Join(home, "sessions")) }