package thin import ( "context" "encoding/json" "errors" "io" "os" "strings" "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/runner/workspace" "amadan.net/oficina/equipo/internal/wire" ) // runCodex runs a step's specialist on a Codex connection: the pinned // app-server in the action's containment (implement: the task tree // read-write; inspect: read-only), one thread and one turn, the step's // own tools over MCP after an approval correlated with the call, every // other request refused, and the namespace's exit proven before the // result counts. A Codex step keeps no session, so it cannot be asked // (kept sessions are Claude's for now). func (e *Engineer) runCodex(ctx context.Context, r stepRow, tree workspace.TaskTree, spec specialistRun) stepResult { o, x := e.O, e.Codex x.defaults() b := spec.binding if spec.resume != "" { return stepResult{reason: "session_gone", terminated: true} } direct, err := o.Runner.DirectBinding(b) if err != nil { return stepResult{reason: "account_unavailable", terminated: true} } lease, err := provider.OpenRuntimeCopy(ctx, direct, o.Refresh, o.LockWait) if err != nil { e.log("step account", err) return stepResult{reason: reasonFor(err), terminated: true} } defer lease.Close() binding := lease.Binding() scratch, err := os.MkdirTemp(o.Runner.ScratchRoot, "policy-") if err != nil { return stepResult{reason: "provider_failed", terminated: true} } defer os.RemoveAll(scratch) // Codex asks for each tool call through an elicitation, never a // permission tool: the socket lists only the step's own tools. tool, err := openToolSet(context.Background(), o.Runner.StateDir, toolSet{list: spec.tools, names: spec.names}, spec.call) if err != nil { return stepResult{reason: "provider_failed", terminated: true} } defer tool.Close() sel := provider.Selection{ConnectionID: b.LocalID, Provider: b.Provider, Family: b.Family, Model: b.Model, AccountID: b.AccountID} in, err := runner.PolicyInputs(ctx, o.Runner, sel, binding, tree.Dir, spec.action, scratch) if err != nil { e.log("step policy", err) return stepResult{reason: "policy_rejected", terminated: true} } policy, err := provider.BuildPolicy(binding, in) if err == nil { err = codex.ValidateThinPolicy(binding, policy, x.Digest, x.HostDigest) } if err != nil { e.log("step policy", err) return stepResult{reason: "policy_rejected", terminated: true} } if err = lease.CheckCopy(ctx); err != nil { return stepResult{reason: reasonFor(err), terminated: true} } bound := e.MaxStep if spec.limit > 0 { bound = spec.limit } limit := min(bound, time.Until(lease.FreshUntil())-o.Margin) if limit < minTurn { return stepResult{reason: "account_unavailable", terminated: true} } launch := provider.Launch{ToolSocket: tool.Path, AttemptKey: "step/" + stepKey(r) + "/" + uuid(), Workspace: tree.Dir, ResearchDir: spec.research, Selection: sel, Binding: binding, Policy: policy} pctx, kill := context.WithCancel(context.Background()) defer kill() record := spec.record if record == nil { record = func(ctx context.Context, id string) error { return e.O.State.setStepNamespace(ctx, r, id) } } proc, err := recordedStart(pctx, o.Manager, launch, in.Argv, record) if err != nil { e.log("step start", err) return stepResult{reason: "policy_rejected", terminated: true} } exited := make(chan error, 1) go func() { _, err := proc.Wait(context.Background()) exited <- err }() go func() { _, _ = io.Copy(io.Discard, io.LimitReader(proc.Stderr(), 1<<20)) }() var logFile io.WriteCloser = nopWriteCloser{} if !spec.noLog { logFile = e.openLog(r) } defer logFile.Close() rpc := connect.NewAppServer(proc.Stdout(), proc.Stdin()) refused := int64(0) res := e.codexStep(ctx, rpc, b, policy, limit, spec, logFile, &refused) res.refused = refused res.terminated = stopStep(func() { proc.Stdin().Close() }, exited, kill, ctx.Err() == nil && res.reason == "", 10*time.Second, 30*time.Second) if !res.terminated { // The namespace record stays: a restarted runner verifies it. e.log("step stop", errors.New("exit not verified")) return res } e.forget(proc.ID()) return res } // codexStep checks the app-server it talks to (pinned version, runtime // home, the expected account, the effective configuration, the thread's // policy), then runs the step as one turn and reads it to its end, // counting in refused each request it refuses. func (e *Engineer) codexStep(ctx context.Context, rpc *connect.AppServer, b runner.AccountBinding, policy provider.Policy, limit time.Duration, spec specialistRun, logFile io.Writer, refused *int64) stepResult { tail := &stepTail{} cancelled := func() stepResult { if ctx.Err() != nil { return stepResult{reason: "cancelled", tail: tail.String()} } return stepResult{reason: "step_timeout", tail: tail.String()} } tctx, cancel := context.WithTimeout(ctx, limit) defer cancel() sctx, done := context.WithTimeout(tctx, 30*time.Second) defer done() raw, _, err := rpc.Call(sctx, "initialize", codex.InitializeParams()) if err == nil { err = codex.CheckInitialize(raw) } if err == nil { err = rpc.Notify("initialized", map[string]any{}) } if err == nil { raw, _, err = 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 != b.AccountID { err = provider.ErrIdentity } } if err == nil { raw, _, err = rpc.Call(sctx, "config/read", map[string]any{"cwd": "/workspace", "includeLayers": true}) } if err == nil { err = codex.CheckConfig(raw, policy) } thread := "" if err == nil { raw, _, err = rpc.Call(sctx, "thread/start", codex.ThreadParams(policy, "")) } if err == nil { thread, err = codex.CheckThread(raw, b.Model, "") } if err != nil { if tctx.Err() != nil { return cancelled() } e.log("step codex", err) return stepResult{reason: "policy_rejected", tail: tail.String()} } raw, _, err = rpc.Call(tctx, "turn/start", codex.TurnParams(policy, thread, spec.prompt)) var started struct { Turn struct{ ID string } `json:"turn"` } if err != nil || json.Unmarshal(raw, &started) != nil || started.Turn.ID == "" { if tctx.Err() != nil { return cancelled() } return stepResult{reason: "provider_failed", tail: tail.String()} } turnID := started.Turn.ID tally := connect.NewCodexTally(thread, true) tally.Begin(turnID) usage := func() []wire.Usage { row := tally.Row() row.Model = b.Model return []wire.Usage{row} } var seen *connect.Limit final, lastActivity := "", "" items := map[string]codexItem{} written := 0 for { select { case <-tctx.Done(): ictx, stop := context.WithTimeout(context.Background(), 2*time.Second) _, _, _ = rpc.Call(ictx, "turn/interrupt", map[string]string{"threadId": thread, "turnId": turnID}) stop() res := cancelled() res.tokens, res.session = usage(), thread return res case m, ok := <-rpc.Messages: if !ok { return stepResult{reason: "provider_failed", tail: tail.String(), tokens: usage(), session: thread} } if line, err := json.Marshal(map[string]any{"method": m.Method, "params": m.Params}); err == nil && written+len(line) < stepLogLimit { n, _ := logFile.Write(append(line, '\n')) written += n } if len(m.ID) > 0 { if !answerApproval(rpc, m, items, spec.names) { *refused++ } continue } var n struct { ThreadID string `json:"threadId"` 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 != thread { return stepResult{reason: "policy_rejected", tail: tail.String(), tokens: usage(), session: thread} } switch m.Method { case "item/started": if n.Item.Type == "mcpToolCall" { items[n.Item.ID] = n.Item } kind, subject, line := itemActivity(n.Item) if line != "" { tail.add(line) } if kind != "" && spec.activity != nil && kind+"\x00"+subject != lastActivity { lastActivity = kind + "\x00" + subject spec.activity(kind, subject) } case "item/completed": if n.Item.Type == "agentMessage" && strings.TrimSpace(n.Item.Text) != "" { final = n.Item.Text tail.add(final) } delete(items, n.Item.ID) case "account/rateLimits/updated": if l, _, ok := connect.CodexRateLimits(n.RateLimits); ok { seen = &l } case "thread/tokenUsage/updated": if th, turn, total, last, ok := connect.CodexNotice(m.Params); ok { tally.Notice(th, 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 } tally.End() res := stepResult{tail: tail.String(), tokens: usage(), session: thread} if t.Status == "completed" { res.summary, res.seen = final, seen return res } switch failure := connect.CodexFailure(t.Error); { case ctx.Err() != nil || t.Status == "interrupted": res.reason = "cancelled" case failure == connect.FailQuota || seen != nil && seen.Limited: l := connect.Limit{Limited: true} if seen != nil { l = *seen l.Limited = true } res.reason, res.limit = "limited", &l case failure == connect.FailAuth: res.reason, res.auth = "sign_in_again", true default: res.reason, res.summary, res.seen = "provider_failed", final, seen } return res } } } } // itemActivity is what a Codex item shows: the activity kind and its // subject (clipped), and the line it adds to the step's tail. func itemActivity(it codexItem) (kind, subject, line string) { switch it.Type { case "commandExecution": kind, subject = wire.ActivityRun, it.Command case "fileChange": kind = wire.ActivityEdit if len(it.Changes) > 0 { subject = it.Changes[0].Path } case "mcpToolCall": kind, line = wire.ActivityOther, it.Tool default: return "", "", "" } subject = strings.TrimPrefix(strings.TrimSpace(strings.SplitN(strings.TrimSpace(subject), "\n", 2)[0]), "/workspace/") if line == "" { line = map[string]string{wire.ActivityRun: "Bash ", wire.ActivityEdit: "Edit "}[kind] + subject } return kind, clip(subject, wire.MaxActivitySubject), line }