| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "io" |
| 8 | "os" |
| 9 | "strings" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/equipo/internal/runner" |
| 13 | "amadan.net/oficina/equipo/internal/runner/connect" |
| 14 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 15 | "amadan.net/oficina/equipo/internal/runner/provider/codex" |
| 16 | "amadan.net/oficina/equipo/internal/runner/workspace" |
| 17 | "amadan.net/oficina/equipo/internal/wire" |
| 18 | ) |
| 19 | |
| 20 | // runCodex runs a step's specialist on a Codex connection: the pinned |
| 21 | // app-server in the action's containment (implement: the task tree |
| 22 | // read-write; inspect: read-only), one thread and one turn, the step's |
| 23 | // own tools over MCP after an approval correlated with the call, every |
| 24 | // other request refused, and the namespace's exit proven before the |
| 25 | // result counts. A Codex step keeps no session, so it cannot be asked |
| 26 | // (kept sessions are Claude's for now). |
| 27 | func (e *Engineer) runCodex(ctx context.Context, r stepRow, tree workspace.TaskTree, spec specialistRun) stepResult { |
| 28 | o, x := e.O, e.Codex |
| 29 | x.defaults() |
| 30 | b := spec.binding |
| 31 | if spec.resume != "" { |
| 32 | return stepResult{reason: "session_gone", terminated: true} |
| 33 | } |
| 34 | direct, err := o.Runner.DirectBinding(b) |
| 35 | if err != nil { |
| 36 | return stepResult{reason: "account_unavailable", terminated: true} |
| 37 | } |
| 38 | lease, err := provider.OpenRuntimeCopy(ctx, direct, o.Refresh, o.LockWait) |
| 39 | if err != nil { |
| 40 | e.log("step account", err) |
| 41 | return stepResult{reason: reasonFor(err), terminated: true} |
| 42 | } |
| 43 | defer lease.Close() |
| 44 | binding := lease.Binding() |
| 45 | scratch, err := os.MkdirTemp(o.Runner.ScratchRoot, "policy-") |
| 46 | if err != nil { |
| 47 | return stepResult{reason: "provider_failed", terminated: true} |
| 48 | } |
| 49 | defer os.RemoveAll(scratch) |
| 50 | // Codex asks for each tool call through an elicitation, never a |
| 51 | // permission tool: the socket lists only the step's own tools. |
| 52 | tool, err := openToolSet(context.Background(), o.Runner.StateDir, toolSet{list: spec.tools, names: spec.names}, spec.call) |
| 53 | if err != nil { |
| 54 | return stepResult{reason: "provider_failed", terminated: true} |
| 55 | } |
| 56 | defer tool.Close() |
| 57 | sel := provider.Selection{ConnectionID: b.LocalID, Provider: b.Provider, Family: b.Family, Model: b.Model, AccountID: b.AccountID} |
| 58 | in, err := runner.PolicyInputs(ctx, o.Runner, sel, binding, tree.Dir, spec.action, scratch) |
| 59 | if err != nil { |
| 60 | e.log("step policy", err) |
| 61 | return stepResult{reason: "policy_rejected", terminated: true} |
| 62 | } |
| 63 | policy, err := provider.BuildPolicy(binding, in) |
| 64 | if err == nil { |
| 65 | err = codex.ValidateThinPolicy(binding, policy, x.Digest, x.HostDigest) |
| 66 | } |
| 67 | if err != nil { |
| 68 | e.log("step policy", err) |
| 69 | return stepResult{reason: "policy_rejected", terminated: true} |
| 70 | } |
| 71 | if err = lease.CheckCopy(ctx); err != nil { |
| 72 | return stepResult{reason: reasonFor(err), terminated: true} |
| 73 | } |
| 74 | bound := e.MaxStep |
| 75 | if spec.limit > 0 { |
| 76 | bound = spec.limit |
| 77 | } |
| 78 | limit := min(bound, time.Until(lease.FreshUntil())-o.Margin) |
| 79 | if limit < minTurn { |
| 80 | return stepResult{reason: "account_unavailable", terminated: true} |
| 81 | } |
| 82 | launch := provider.Launch{ToolSocket: tool.Path, AttemptKey: "step/" + stepKey(r) + "/" + uuid(), Workspace: tree.Dir, ResearchDir: spec.research, Selection: sel, Binding: binding, Policy: policy} |
| 83 | pctx, kill := context.WithCancel(context.Background()) |
| 84 | defer kill() |
| 85 | record := spec.record |
| 86 | if record == nil { |
| 87 | record = func(ctx context.Context, id string) error { return e.O.State.setStepNamespace(ctx, r, id) } |
| 88 | } |
| 89 | proc, err := recordedStart(pctx, o.Manager, launch, in.Argv, record) |
| 90 | if err != nil { |
| 91 | e.log("step start", err) |
| 92 | return stepResult{reason: "policy_rejected", terminated: true} |
| 93 | } |
| 94 | exited := make(chan error, 1) |
| 95 | go func() { |
| 96 | _, err := proc.Wait(context.Background()) |
| 97 | exited <- err |
| 98 | }() |
| 99 | go func() { _, _ = io.Copy(io.Discard, io.LimitReader(proc.Stderr(), 1<<20)) }() |
| 100 | var logFile io.WriteCloser = nopWriteCloser{} |
| 101 | if !spec.noLog { |
| 102 | logFile = e.openLog(r) |
| 103 | } |
| 104 | defer logFile.Close() |
| 105 | rpc := connect.NewAppServer(proc.Stdout(), proc.Stdin()) |
| 106 | refused := int64(0) |
| 107 | res := e.codexStep(ctx, rpc, b, policy, limit, spec, logFile, &refused) |
| 108 | res.refused = refused |
| 109 | res.terminated = stopStep(func() { proc.Stdin().Close() }, exited, kill, ctx.Err() == nil && res.reason == "", 10*time.Second, 30*time.Second) |
| 110 | if !res.terminated { |
| 111 | // The namespace record stays: a restarted runner verifies it. |
| 112 | e.log("step stop", errors.New("exit not verified")) |
| 113 | return res |
| 114 | } |
| 115 | e.forget(proc.ID()) |
| 116 | return res |
| 117 | } |
| 118 | |
| 119 | // codexStep checks the app-server it talks to (pinned version, runtime |
| 120 | // home, the expected account, the effective configuration, the thread's |
| 121 | // policy), then runs the step as one turn and reads it to its end, |
| 122 | // counting in refused each request it refuses. |
| 123 | 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 { |
| 124 | tail := &stepTail{} |
| 125 | cancelled := func() stepResult { |
| 126 | if ctx.Err() != nil { |
| 127 | return stepResult{reason: "cancelled", tail: tail.String()} |
| 128 | } |
| 129 | return stepResult{reason: "step_timeout", tail: tail.String()} |
| 130 | } |
| 131 | tctx, cancel := context.WithTimeout(ctx, limit) |
| 132 | defer cancel() |
| 133 | sctx, done := context.WithTimeout(tctx, 30*time.Second) |
| 134 | defer done() |
| 135 | raw, _, err := rpc.Call(sctx, "initialize", codex.InitializeParams()) |
| 136 | if err == nil { |
| 137 | err = codex.CheckInitialize(raw) |
| 138 | } |
| 139 | if err == nil { |
| 140 | err = rpc.Notify("initialized", map[string]any{}) |
| 141 | } |
| 142 | if err == nil { |
| 143 | raw, _, err = rpc.Call(sctx, "account/read", map[string]bool{"refreshToken": false}) |
| 144 | } |
| 145 | if err == nil { |
| 146 | var id provider.Identity |
| 147 | if id, err = provider.CodexLoginIdentity(raw); err == nil && id.AccountID != b.AccountID { |
| 148 | err = provider.ErrIdentity |
| 149 | } |
| 150 | } |
| 151 | if err == nil { |
| 152 | raw, _, err = rpc.Call(sctx, "config/read", map[string]any{"cwd": "/workspace", "includeLayers": true}) |
| 153 | } |
| 154 | if err == nil { |
| 155 | err = codex.CheckConfig(raw, policy) |
| 156 | } |
| 157 | thread := "" |
| 158 | if err == nil { |
| 159 | raw, _, err = rpc.Call(sctx, "thread/start", codex.ThreadParams(policy, "")) |
| 160 | } |
| 161 | if err == nil { |
| 162 | thread, err = codex.CheckThread(raw, b.Model, "") |
| 163 | } |
| 164 | if err != nil { |
| 165 | if tctx.Err() != nil { |
| 166 | return cancelled() |
| 167 | } |
| 168 | e.log("step codex", err) |
| 169 | return stepResult{reason: "policy_rejected", tail: tail.String()} |
| 170 | } |
| 171 | raw, _, err = rpc.Call(tctx, "turn/start", codex.TurnParams(policy, thread, spec.prompt)) |
| 172 | var started struct { |
| 173 | Turn struct{ ID string } `json:"turn"` |
| 174 | } |
| 175 | if err != nil || json.Unmarshal(raw, &started) != nil || started.Turn.ID == "" { |
| 176 | if tctx.Err() != nil { |
| 177 | return cancelled() |
| 178 | } |
| 179 | return stepResult{reason: "provider_failed", tail: tail.String()} |
| 180 | } |
| 181 | turnID := started.Turn.ID |
| 182 | tally := connect.NewCodexTally(thread, true) |
| 183 | tally.Begin(turnID) |
| 184 | usage := func() []wire.Usage { |
| 185 | row := tally.Row() |
| 186 | row.Model = b.Model |
| 187 | return []wire.Usage{row} |
| 188 | } |
| 189 | var seen *connect.Limit |
| 190 | final, lastActivity := "", "" |
| 191 | items := map[string]codexItem{} |
| 192 | written := 0 |
| 193 | for { |
| 194 | select { |
| 195 | case <-tctx.Done(): |
| 196 | ictx, stop := context.WithTimeout(context.Background(), 2*time.Second) |
| 197 | _, _, _ = rpc.Call(ictx, "turn/interrupt", map[string]string{"threadId": thread, "turnId": turnID}) |
| 198 | stop() |
| 199 | res := cancelled() |
| 200 | res.tokens, res.session = usage(), thread |
| 201 | return res |
| 202 | case m, ok := <-rpc.Messages: |
| 203 | if !ok { |
| 204 | return stepResult{reason: "provider_failed", tail: tail.String(), tokens: usage(), session: thread} |
| 205 | } |
| 206 | if line, err := json.Marshal(map[string]any{"method": m.Method, "params": m.Params}); err == nil && written+len(line) < stepLogLimit { |
| 207 | n, _ := logFile.Write(append(line, '\n')) |
| 208 | written += n |
| 209 | } |
| 210 | if len(m.ID) > 0 { |
| 211 | if !answerApproval(rpc, m, items, spec.names) { |
| 212 | *refused++ |
| 213 | } |
| 214 | continue |
| 215 | } |
| 216 | var n struct { |
| 217 | ThreadID string `json:"threadId"` |
| 218 | Item codexItem `json:"item"` |
| 219 | Turn json.RawMessage `json:"turn"` |
| 220 | RateLimits json.RawMessage `json:"rateLimits"` |
| 221 | } |
| 222 | if json.Unmarshal(m.Params, &n) != nil { |
| 223 | continue |
| 224 | } |
| 225 | if n.ThreadID != "" && n.ThreadID != thread { |
| 226 | return stepResult{reason: "policy_rejected", tail: tail.String(), tokens: usage(), session: thread} |
| 227 | } |
| 228 | switch m.Method { |
| 229 | case "item/started": |
| 230 | if n.Item.Type == "mcpToolCall" { |
| 231 | items[n.Item.ID] = n.Item |
| 232 | } |
| 233 | kind, subject, line := itemActivity(n.Item) |
| 234 | if line != "" { |
| 235 | tail.add(line) |
| 236 | } |
| 237 | if kind != "" && spec.activity != nil && kind+"\x00"+subject != lastActivity { |
| 238 | lastActivity = kind + "\x00" + subject |
| 239 | spec.activity(kind, subject) |
| 240 | } |
| 241 | case "item/completed": |
| 242 | if n.Item.Type == "agentMessage" && strings.TrimSpace(n.Item.Text) != "" { |
| 243 | final = n.Item.Text |
| 244 | tail.add(final) |
| 245 | } |
| 246 | delete(items, n.Item.ID) |
| 247 | case "account/rateLimits/updated": |
| 248 | if l, _, ok := connect.CodexRateLimits(n.RateLimits); ok { |
| 249 | seen = &l |
| 250 | } |
| 251 | case "thread/tokenUsage/updated": |
| 252 | if th, turn, total, last, ok := connect.CodexNotice(m.Params); ok { |
| 253 | tally.Notice(th, turn, total, last) |
| 254 | } |
| 255 | case "turn/completed": |
| 256 | var t struct { |
| 257 | ID string `json:"id"` |
| 258 | Status string `json:"status"` |
| 259 | Error json.RawMessage `json:"error"` |
| 260 | } |
| 261 | if json.Unmarshal(n.Turn, &t) != nil || t.ID != turnID { |
| 262 | continue |
| 263 | } |
| 264 | tally.End() |
| 265 | res := stepResult{tail: tail.String(), tokens: usage(), session: thread} |
| 266 | if t.Status == "completed" { |
| 267 | res.summary, res.seen = final, seen |
| 268 | return res |
| 269 | } |
| 270 | switch failure := connect.CodexFailure(t.Error); { |
| 271 | case ctx.Err() != nil || t.Status == "interrupted": |
| 272 | res.reason = "cancelled" |
| 273 | case failure == connect.FailQuota || seen != nil && seen.Limited: |
| 274 | l := connect.Limit{Limited: true} |
| 275 | if seen != nil { |
| 276 | l = *seen |
| 277 | l.Limited = true |
| 278 | } |
| 279 | res.reason, res.limit = "limited", &l |
| 280 | case failure == connect.FailAuth: |
| 281 | res.reason, res.auth = "sign_in_again", true |
| 282 | default: |
| 283 | res.reason, res.summary, res.seen = "provider_failed", final, seen |
| 284 | } |
| 285 | return res |
| 286 | } |
| 287 | } |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | // itemActivity is what a Codex item shows: the activity kind and its |
| 292 | // subject (clipped), and the line it adds to the step's tail. |
| 293 | func itemActivity(it codexItem) (kind, subject, line string) { |
| 294 | switch it.Type { |
| 295 | case "commandExecution": |
| 296 | kind, subject = wire.ActivityRun, it.Command |
| 297 | case "fileChange": |
| 298 | kind = wire.ActivityEdit |
| 299 | if len(it.Changes) > 0 { |
| 300 | subject = it.Changes[0].Path |
| 301 | } |
| 302 | case "mcpToolCall": |
| 303 | kind, line = wire.ActivityOther, it.Tool |
| 304 | default: |
| 305 | return "", "", "" |
| 306 | } |
| 307 | subject = strings.TrimPrefix(strings.TrimSpace(strings.SplitN(strings.TrimSpace(subject), "\n", 2)[0]), "/workspace/") |
| 308 | if line == "" { |
| 309 | line = map[string]string{wire.ActivityRun: "Bash ", wire.ActivityEdit: "Edit "}[kind] + subject |
| 310 | } |
| 311 | return kind, clip(subject, wire.MaxActivitySubject), line |
| 312 | } |
| 313 | |