| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/sha256" |
| 6 | "encoding/hex" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "io" |
| 10 | "io/fs" |
| 11 | "os" |
| 12 | "path/filepath" |
| 13 | "slices" |
| 14 | "strings" |
| 15 | "sync" |
| 16 | "time" |
| 17 | |
| 18 | "amadan.net/oficina/equipo/internal/runner" |
| 19 | "amadan.net/oficina/equipo/internal/runner/connect" |
| 20 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 21 | "amadan.net/oficina/equipo/internal/runner/provider/codex" |
| 22 | "amadan.net/oficina/equipo/internal/wire" |
| 23 | ) |
| 24 | |
| 25 | // CodexOptions pins the Codex binaries a coordinator may run. Tests pass |
| 26 | // their fake's digests; production uses the pinned 0.165.0 build. |
| 27 | type CodexOptions struct { |
| 28 | Digest, HostDigest string |
| 29 | } |
| 30 | |
| 31 | func (x *CodexOptions) defaults() { |
| 32 | if x.Digest == "" { |
| 33 | x.Digest = codex.ExecutableSHA256 |
| 34 | } |
| 35 | if x.HostDigest == "" { |
| 36 | x.HostDigest = codex.CodeModeHostSHA256 |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | // OpenCodex returns the person's coordinator on one Codex connection: |
| 41 | // the pinned `codex app-server` in the converse containment (the same |
| 42 | // bubblewrap namespace, egress to the provider only, no shell, no patch, |
| 43 | // exactly the conversation's Equipo tools), driven over JSON-RPC. |
| 44 | func OpenCodex(o ClaudeOptions, x CodexOptions, person string, b runner.AccountBinding) (Coordinator, error) { |
| 45 | return openCodex(o, x, person, wire.LaneCoordinator, b) |
| 46 | } |
| 47 | |
| 48 | func openCodex(o ClaudeOptions, x CodexOptions, person, lane string, b runner.AccountBinding) (Coordinator, error) { |
| 49 | o.defaults() |
| 50 | x.defaults() |
| 51 | if b.Provider != "codex" || b.PersonID != person { |
| 52 | return nil, provider.ErrIdentity |
| 53 | } |
| 54 | c := &codexCoordinator{x: x} |
| 55 | if err := c.open(o, person, lane, b); err != nil { |
| 56 | return nil, err |
| 57 | } |
| 58 | return c, nil |
| 59 | } |
| 60 | |
| 61 | type codexCoordinator struct { |
| 62 | coordBase |
| 63 | x CodexOptions |
| 64 | |
| 65 | mu sync.Mutex |
| 66 | proc *codexProcess |
| 67 | idle *time.Timer |
| 68 | idleAt time.Time |
| 69 | } |
| 70 | |
| 71 | type codexProcess struct { |
| 72 | access bool |
| 73 | lease *provider.AccountLease |
| 74 | process provider.Process |
| 75 | cancel context.CancelFunc |
| 76 | rpc *connect.AppServer |
| 77 | exited chan struct{} |
| 78 | thread string |
| 79 | fresh bool |
| 80 | turns int |
| 81 | policy provider.Policy |
| 82 | tool *toolSocket |
| 83 | scratch string |
| 84 | exitErr error |
| 85 | // tally aggregates the thread's usage notices into attempt rows. |
| 86 | tally *connect.CodexTally |
| 87 | } |
| 88 | |
| 89 | func (c *codexCoordinator) Close() { |
| 90 | c.mu.Lock() |
| 91 | defer c.mu.Unlock() |
| 92 | if c.idle != nil { |
| 93 | c.idle.Stop() |
| 94 | } |
| 95 | c.stop(true) |
| 96 | } |
| 97 | |
| 98 | func (c *codexCoordinator) idleExit() { |
| 99 | c.mu.Lock() |
| 100 | defer c.mu.Unlock() |
| 101 | c.stop(true) |
| 102 | } |
| 103 | |
| 104 | // Warm starts the app-server ahead of the first turn: initialize, the |
| 105 | // account and configuration checks, and thread/start or thread/resume, |
| 106 | // none of which is a turn, so the model is sent nothing. Unused, it |
| 107 | // closes after WarmIdle. |
| 108 | func (c *codexCoordinator) Warm(ctx context.Context) error { |
| 109 | c.mu.Lock() |
| 110 | defer c.mu.Unlock() |
| 111 | if c.proc != nil { |
| 112 | return nil |
| 113 | } |
| 114 | if err := c.start(ctx); err != nil { |
| 115 | return err |
| 116 | } |
| 117 | if c.idle != nil { |
| 118 | c.idle.Stop() |
| 119 | } |
| 120 | c.idle, c.idleAt = time.AfterFunc(c.o.WarmIdle, c.idleExit), time.Now().Add(c.o.WarmIdle) |
| 121 | return nil |
| 122 | } |
| 123 | |
| 124 | // codexItem is the part of an item notification the coordinator reads. |
| 125 | type codexItem struct { |
| 126 | ID string `json:"id"` |
| 127 | Type string `json:"type"` |
| 128 | Text string `json:"text"` |
| 129 | Server string `json:"server"` |
| 130 | Tool string `json:"tool"` |
| 131 | Arguments json.RawMessage `json:"arguments"` |
| 132 | // Command and Changes are a step's shell command and file changes. |
| 133 | Command string `json:"command"` |
| 134 | Changes []struct { |
| 135 | Path string `json:"path"` |
| 136 | } `json:"changes"` |
| 137 | } |
| 138 | |
| 139 | func (c *codexCoordinator) Turn(ctx context.Context, in TurnInput, emit func(string)) TurnResult { |
| 140 | c.mu.Lock() |
| 141 | defer c.mu.Unlock() |
| 142 | if err := c.desk.SavePlacementNotes(in.PlacementNotes); err != nil { |
| 143 | return TurnResult{Reason: "account_unavailable"} |
| 144 | } |
| 145 | |
| 146 | defer c.unstage() |
| 147 | files, err := c.laneFiles(in.Attachments) |
| 148 | if err != nil { |
| 149 | return c.missing(ctx, in) |
| 150 | } |
| 151 | if c.idle != nil { |
| 152 | c.idle.Stop() |
| 153 | } |
| 154 | if c.proc != nil && c.profile.action == "converse" && c.proc.access != (c.accessProtocol() >= wire.ProtocolAccess) { |
| 155 | c.stop(true) |
| 156 | } |
| 157 | if p := c.proc; p != nil { |
| 158 | select { |
| 159 | case <-p.exited: |
| 160 | c.stop(false) |
| 161 | default: |
| 162 | if time.Now().Add(c.o.MaxTurn + c.o.Margin).After(p.lease.FreshUntil()) { |
| 163 | c.stop(true) |
| 164 | } |
| 165 | } |
| 166 | } |
| 167 | cold := c.proc == nil |
| 168 | if c.proc == nil { |
| 169 | if err := c.start(ctx); err != nil { |
| 170 | c.log("codex coordinator start", err) |
| 171 | if ctx.Err() != nil { |
| 172 | return TurnResult{Reason: "cancelled"} |
| 173 | } |
| 174 | return TurnResult{Reason: reasonFor(err)} |
| 175 | } |
| 176 | } |
| 177 | p := c.proc |
| 178 | limit := min(c.o.MaxTurn, time.Until(p.lease.FreshUntil())-c.o.Margin) |
| 179 | if limit < minTurn { |
| 180 | c.stop(true) |
| 181 | return TurnResult{Reason: "account_unavailable"} |
| 182 | } |
| 183 | if err := p.lease.CheckCopy(ctx); err != nil { |
| 184 | c.log("codex coordinator copy", err) |
| 185 | c.stop(false) |
| 186 | return TurnResult{Reason: reasonFor(err)} |
| 187 | } |
| 188 | var catalog []wire.RepoInfo |
| 189 | if c.o.Catalog != nil { |
| 190 | catalog = c.o.Catalog() |
| 191 | } |
| 192 | prompt, explored := c.prompt(p.fresh && p.turns == 0, in, catalog) |
| 193 | // Images go in as localImage inputs by their path in the namespace. |
| 194 | var images []string |
| 195 | shown := map[string]bool{} |
| 196 | for _, f := range files { |
| 197 | if f.Kind == wire.AttachmentImage { |
| 198 | images = append(images, f.Path) |
| 199 | shown[f.ID] = true |
| 200 | } |
| 201 | } |
| 202 | prompt = strings.TrimLeft(prompt+attachmentNote(files, shown, c.lane)+c.earlierNote(in), "\n") |
| 203 | tctx, cancel := context.WithTimeout(ctx, limit) |
| 204 | defer cancel() |
| 205 | tctx = context.WithValue(tctx, factsKey{}, factsFor(in)) |
| 206 | c.setTurn(tctx, in.TurnID, in.Attempt, in.Kind) |
| 207 | defer c.clearTurn() |
| 208 | activity := in.Activity |
| 209 | if activity == nil { |
| 210 | activity = func(string, string) {} |
| 211 | } |
| 212 | start := time.Now() |
| 213 | timing := &wire.TurnTiming{Cold: cold} |
| 214 | if !in.Received.IsZero() { |
| 215 | timing.StartMs = start.Sub(in.Received).Milliseconds() |
| 216 | } |
| 217 | mark := func(at *int64) { |
| 218 | if *at == 0 { |
| 219 | *at = max(time.Since(start).Milliseconds(), 1) |
| 220 | } |
| 221 | } |
| 222 | raw, _, err := p.rpc.Call(tctx, "turn/start", codex.TurnParamsWithImages(p.policy, p.thread, prompt, images)) |
| 223 | var started struct { |
| 224 | Turn struct{ ID string } `json:"turn"` |
| 225 | } |
| 226 | if err != nil || json.Unmarshal(raw, &started) != nil || started.Turn.ID == "" { |
| 227 | c.stop(false) |
| 228 | if ctx.Err() != nil { |
| 229 | return TurnResult{Reason: "cancelled"} |
| 230 | } |
| 231 | return TurnResult{Reason: "provider_failed"} |
| 232 | } |
| 233 | turnID := started.Turn.ID |
| 234 | p.tally.Begin(turnID) |
| 235 | usage := func() []wire.Usage { |
| 236 | row := p.tally.Row() |
| 237 | row.Model = c.account.Model |
| 238 | return []wire.Usage{row} |
| 239 | } |
| 240 | var seen *connect.Limit |
| 241 | plan := "" |
| 242 | final := "" |
| 243 | items := map[string]codexItem{} |
| 244 | lastActivity := "" |
| 245 | for { |
| 246 | select { |
| 247 | case <-tctx.Done(): |
| 248 | // What the turn used so far is kept (complete: false). |
| 249 | c.interrupt(p, turnID) |
| 250 | c.stop(false) |
| 251 | if ctx.Err() != nil { |
| 252 | return TurnResult{Reason: "cancelled", Usage: usage()} |
| 253 | } |
| 254 | return TurnResult{Reason: "turn_timeout", Usage: usage()} |
| 255 | case m, ok := <-p.rpc.Messages: |
| 256 | if !ok { |
| 257 | c.stop(false) |
| 258 | if ctx.Err() != nil { |
| 259 | return TurnResult{Reason: "cancelled", Usage: usage()} |
| 260 | } |
| 261 | return TurnResult{Reason: "provider_failed", Usage: usage()} |
| 262 | } |
| 263 | mark(&timing.FirstEventMs) |
| 264 | if len(m.ID) > 0 { |
| 265 | c.answer(p, m, items) |
| 266 | continue |
| 267 | } |
| 268 | var n struct { |
| 269 | ThreadID string `json:"threadId"` |
| 270 | TurnID string `json:"turnId"` |
| 271 | Delta string `json:"delta"` |
| 272 | Item codexItem `json:"item"` |
| 273 | Turn json.RawMessage `json:"turn"` |
| 274 | RateLimits json.RawMessage `json:"rateLimits"` |
| 275 | } |
| 276 | if json.Unmarshal(m.Params, &n) != nil { |
| 277 | continue |
| 278 | } |
| 279 | if n.ThreadID != "" && n.ThreadID != p.thread { |
| 280 | c.stop(false) |
| 281 | return TurnResult{Reason: "policy_rejected"} |
| 282 | } |
| 283 | switch m.Method { |
| 284 | case "item/agentMessage/delta": |
| 285 | if n.TurnID == turnID && n.Delta != "" { |
| 286 | mark(&timing.FirstTextMs) |
| 287 | timing.LastTextMs = max(time.Since(start).Milliseconds(), 1) |
| 288 | emit(n.Delta) |
| 289 | } |
| 290 | case "item/started": |
| 291 | kind, tool := "", "" |
| 292 | switch n.Item.Type { |
| 293 | case "reasoning": |
| 294 | kind = wire.ActivityThink |
| 295 | mark(&timing.FirstThinkingMs) |
| 296 | case "mcpToolCall": |
| 297 | items[n.Item.ID] = n.Item |
| 298 | kind, tool = wire.ActivityTool, activityName(n.Item.Tool, c.accessToolSet(true).names) |
| 299 | if n.Item.Server != "equipo" { |
| 300 | tool = "other" |
| 301 | } |
| 302 | mark(&timing.FirstToolMs) |
| 303 | } |
| 304 | if kind != "" && kind+"/"+tool != lastActivity { |
| 305 | lastActivity = kind + "/" + tool |
| 306 | activity(kind, tool) |
| 307 | } |
| 308 | case "item/completed": |
| 309 | if n.Item.Type == "agentMessage" && strings.TrimSpace(n.Item.Text) != "" { |
| 310 | final = n.Item.Text |
| 311 | } |
| 312 | delete(items, n.Item.ID) |
| 313 | case "account/rateLimits/updated": |
| 314 | if l, pl, ok := connect.CodexRateLimits(n.RateLimits); ok { |
| 315 | seen = &l |
| 316 | if pl != "" { |
| 317 | plan = pl |
| 318 | } |
| 319 | } |
| 320 | case "thread/tokenUsage/updated": |
| 321 | if thread, turn, total, last, ok := connect.CodexNotice(m.Params); ok { |
| 322 | p.tally.Notice(thread, turn, total, last) |
| 323 | } |
| 324 | case "turn/completed": |
| 325 | var t struct { |
| 326 | ID string `json:"id"` |
| 327 | Status string `json:"status"` |
| 328 | Error json.RawMessage `json:"error"` |
| 329 | } |
| 330 | if json.Unmarshal(n.Turn, &t) != nil || t.ID != turnID { |
| 331 | continue |
| 332 | } |
| 333 | p.tally.End() |
| 334 | if t.Status != "completed" { |
| 335 | proven := c.stop(false) |
| 336 | switch { |
| 337 | case ctx.Err() != nil || t.Status == "interrupted": |
| 338 | return TurnResult{Reason: "cancelled", Usage: usage()} |
| 339 | case connect.CodexFailure(t.Error) == connect.FailQuota || seen != nil && seen.Limited: |
| 340 | l := connect.Limit{Limited: true} |
| 341 | if seen != nil { |
| 342 | l = *seen |
| 343 | l.Limited = true |
| 344 | } |
| 345 | return TurnResult{Reason: "limited", Limit: &l, Plan: plan, Proven: proven, Usage: usage()} |
| 346 | case connect.CodexFailure(t.Error) == connect.FailAuth: |
| 347 | return TurnResult{Reason: "sign_in_again", SignIn: true, Proven: proven, Usage: usage()} |
| 348 | } |
| 349 | return TurnResult{Reason: "provider_failed", Seen: seen, Plan: plan, Usage: usage()} |
| 350 | } |
| 351 | p.turns++ |
| 352 | if c.lane == wire.LaneCoordinator && settles(in.Kind) { |
| 353 | if err := c.settled(in.Kind, explored, catalog); err != nil { |
| 354 | c.log("codex coordinator desk", err) |
| 355 | c.syncOut(p) |
| 356 | return TurnResult{Reason: "desk_unavailable"} |
| 357 | } |
| 358 | } |
| 359 | c.noteHash = noteHash(c.desk.Notebook(notebookContext)) |
| 360 | c.syncOut(p) |
| 361 | if err := c.o.State.saveSession(context.Background(), c.person, c.lane, "codex", c.sessionAccount(), p.thread, in.TurnID); err != nil { |
| 362 | c.log("codex coordinator session", err) |
| 363 | } |
| 364 | idle := c.idleAfterTurn() |
| 365 | c.idle, c.idleAt = time.AfterFunc(idle, c.idleExit), time.Now().Add(idle) |
| 366 | timing.ResultMs = max(time.Since(start).Milliseconds(), 1) |
| 367 | return TurnResult{Text: final, Usage: usage(), Timing: timing, Seen: seen, Plan: plan} |
| 368 | } |
| 369 | } |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | // answer replies to a request the app-server makes: only the lane's own |
| 374 | // Equipo tools are approved. |
| 375 | func (c *codexCoordinator) answer(p *codexProcess, m connect.Message, items map[string]codexItem) { |
| 376 | answerApproval(p.rpc, m, items, c.accessToolSet(true).names) |
| 377 | } |
| 378 | |
| 379 | // answerApproval replies to a request the app-server makes. Only an |
| 380 | // approval to call one of names on the Equipo server, correlated with the |
| 381 | // tool call Codex started, is accepted; every other request (shell, |
| 382 | // patch, questions, anything new) is refused. It reports whether it |
| 383 | // accepted. |
| 384 | func answerApproval(rpc *connect.AppServer, m connect.Message, items map[string]codexItem, names []string) bool { |
| 385 | if m.Method == "mcpServer/elicitation/request" { |
| 386 | server, args, ok := codex.ToolApproval(m.Params) |
| 387 | if ok && server == "equipo" { |
| 388 | for _, it := range items { |
| 389 | if it.Server == "equipo" && slices.Contains(names, it.Tool) && codex.SameArguments(it.Arguments, args) { |
| 390 | _ = rpc.Answer(m.ID, map[string]any{"action": "accept", "content": map[string]any{}}) |
| 391 | return true |
| 392 | } |
| 393 | } |
| 394 | } |
| 395 | _ = rpc.Answer(m.ID, map[string]any{"action": "decline"}) |
| 396 | return false |
| 397 | } |
| 398 | _ = rpc.Refuse(m.ID) |
| 399 | return false |
| 400 | } |
| 401 | |
| 402 | func (c *codexCoordinator) interrupt(p *codexProcess, turn string) { |
| 403 | ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| 404 | defer cancel() |
| 405 | _, _, _ = p.rpc.Call(ctx, "turn/interrupt", map[string]string{"threadId": p.thread, "turnId": turn}) |
| 406 | } |
| 407 | |
| 408 | func (c *codexCoordinator) start(ctx context.Context) (err error) { |
| 409 | o := c.o |
| 410 | direct, err := o.Runner.DirectBinding(c.account) |
| 411 | if err != nil { |
| 412 | return atStep("binding", err) |
| 413 | } |
| 414 | // The refresh's failures are told apart from the copy's own checks. |
| 415 | refresh := o.Refresh |
| 416 | if refresh != nil { |
| 417 | refresh = func(ctx context.Context, b provider.Binding) (provider.Identity, error) { |
| 418 | id, err := o.Refresh(ctx, b) |
| 419 | return id, atStep("refresh", err) |
| 420 | } |
| 421 | } |
| 422 | lease, err := provider.OpenRuntimeCopy(ctx, direct, refresh, o.LockWait) |
| 423 | if err != nil { |
| 424 | return atStep("copy", err) |
| 425 | } |
| 426 | p := &codexProcess{access: c.accessProtocol() >= wire.ProtocolAccess, lease: lease, exited: make(chan struct{})} |
| 427 | defer func() { |
| 428 | if err != nil { |
| 429 | c.cleanup(p) |
| 430 | } |
| 431 | }() |
| 432 | binding := lease.Binding() |
| 433 | var row sessionRow |
| 434 | found := false |
| 435 | if !c.profile.ephemeral { |
| 436 | if row, found, err = o.State.session(ctx, c.person, c.lane, "codex"); err != nil { |
| 437 | return atStep("session", err) |
| 438 | } |
| 439 | } |
| 440 | y1, m1, d1 := row.Updated.UTC().Date() |
| 441 | y2, m2, d2 := time.Now().UTC().Date() |
| 442 | resume := found && row.Account == c.sessionAccount() && y1 == y2 && m1 == m2 && d1 == d2 && validThread(row.SessionID) |
| 443 | if resume { |
| 444 | resume = copyRollouts(c.home, binding.Home, row.SessionID) == nil |
| 445 | } |
| 446 | if !resume { |
| 447 | pruneRollouts(c.home) |
| 448 | } |
| 449 | if p.scratch, err = os.MkdirTemp(o.Runner.ScratchRoot, "policy-"); err != nil { |
| 450 | return atStep("policy_scratch", err) |
| 451 | } |
| 452 | var call ToolReplyFunc |
| 453 | if o.Tools != nil { |
| 454 | call = c.toolReply |
| 455 | } |
| 456 | if p.tool, err = openReplySet(context.Background(), o.Runner.StateDir, c.accessToolSet(call != nil), call); err != nil { |
| 457 | return atStep("tool_socket", err) |
| 458 | } |
| 459 | sel := provider.Selection{ConnectionID: c.account.LocalID, Provider: "codex", Family: c.account.Family, Model: c.account.Model, AccountID: c.account.AccountID} |
| 460 | in, err := runner.PolicyInputs(ctx, o.Runner, sel, binding, c.workspace(), c.profile.action, p.scratch, c.accessProtocol() < wire.ProtocolAccess) |
| 461 | if err != nil { |
| 462 | return atStep("policy_inputs", err) |
| 463 | } |
| 464 | if p.policy, err = provider.BuildPolicy(binding, in); err != nil { |
| 465 | return atStep("policy_build", err) |
| 466 | } |
| 467 | if err = codex.ValidateThinPolicy(binding, p.policy, c.x.Digest, c.x.HostDigest); err != nil { |
| 468 | return atStep("policy_pin", err) |
| 469 | } |
| 470 | if err = lease.CheckCopy(ctx); err != nil { |
| 471 | return atStep("copy_check", err) |
| 472 | } |
| 473 | personKey := sha256.Sum256([]byte(c.person)) |
| 474 | 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} |
| 475 | pctx, cancel := context.WithCancel(context.Background()) |
| 476 | p.cancel = cancel |
| 477 | if p.process, err = o.Manager.StartRecorded(pctx, launch, in.Argv, nil); err != nil { |
| 478 | return atStep("namespace", err) |
| 479 | } |
| 480 | p.rpc = connect.NewAppServer(p.process.Stdout(), p.process.Stdin()) |
| 481 | go func() { _, _ = io.Copy(io.Discard, io.LimitReader(p.process.Stderr(), 1<<20)) }() |
| 482 | go func() { |
| 483 | _, p.exitErr = p.process.Wait(context.Background()) |
| 484 | close(p.exited) |
| 485 | }() |
| 486 | sctx, done := context.WithTimeout(ctx, 30*time.Second) |
| 487 | defer done() |
| 488 | // The pinned version, its home the runtime copy, the expected |
| 489 | // account, and the effective configuration the policy rendered. |
| 490 | raw, _, err := p.rpc.Call(sctx, "initialize", codex.InitializeParams()) |
| 491 | if err == nil { |
| 492 | err = codex.CheckInitialize(raw) |
| 493 | } |
| 494 | if err == nil { |
| 495 | err = p.rpc.Notify("initialized", map[string]any{}) |
| 496 | } |
| 497 | if err == nil { |
| 498 | raw, _, err = p.rpc.Call(sctx, "account/read", map[string]bool{"refreshToken": false}) |
| 499 | } |
| 500 | if err == nil { |
| 501 | var id provider.Identity |
| 502 | if id, err = provider.CodexLoginIdentity(raw); err == nil && id.AccountID != c.account.AccountID { |
| 503 | err = provider.ErrIdentity |
| 504 | } |
| 505 | } |
| 506 | if err == nil { |
| 507 | raw, _, err = p.rpc.Call(sctx, "config/read", map[string]any{"cwd": "/workspace", "includeLayers": true}) |
| 508 | } |
| 509 | if err == nil { |
| 510 | err = codex.CheckConfig(raw, p.policy) |
| 511 | } |
| 512 | if err != nil { |
| 513 | c.proc = p |
| 514 | c.stop(false) |
| 515 | return atStep("handshake", errors.Join(provider.ErrPolicy, err)) |
| 516 | } |
| 517 | p.fresh = !resume |
| 518 | if resume { |
| 519 | raw, _, err = p.rpc.Call(sctx, "thread/resume", codex.ThreadParams(p.policy, row.SessionID)) |
| 520 | if err == nil { |
| 521 | p.thread, err = codex.CheckThread(raw, c.threadModel(), row.SessionID) |
| 522 | } |
| 523 | if errors.Is(err, provider.ErrPolicy) { |
| 524 | c.proc = p |
| 525 | c.stop(false) |
| 526 | return atStep("thread", err) |
| 527 | } |
| 528 | // A thread Codex cannot resume starts afresh, seeded like any new |
| 529 | // session from the notebook and the tail. |
| 530 | p.fresh = err != nil |
| 531 | } |
| 532 | if p.fresh { |
| 533 | raw, _, err = p.rpc.Call(sctx, "thread/start", codex.ThreadParams(p.policy, "")) |
| 534 | if err == nil { |
| 535 | p.thread, err = codex.CheckThread(raw, c.threadModel(), "") |
| 536 | } |
| 537 | if err != nil { |
| 538 | c.proc = p |
| 539 | c.stop(false) |
| 540 | return atStep("thread", errors.Join(provider.ErrPolicy, err)) |
| 541 | } |
| 542 | } |
| 543 | p.tally = connect.NewCodexTally(p.thread, p.fresh) |
| 544 | c.proc = p |
| 545 | c.up.Store(true) |
| 546 | return nil |
| 547 | } |
| 548 | |
| 549 | // threadModel is the model the lane's thread runs: the connection's, or |
| 550 | // for a glance its provider's small model. |
| 551 | func (c *codexCoordinator) threadModel() string { |
| 552 | return provider.LaunchModel(c.profile.action, "codex", c.account.Model) |
| 553 | } |
| 554 | |
| 555 | // stop ends the process; the exit is observed by the containment before |
| 556 | // the copy and scratch are removed. |
| 557 | func (c *codexCoordinator) stop(clean bool) bool { |
| 558 | p := c.proc |
| 559 | if p == nil { |
| 560 | return true |
| 561 | } |
| 562 | proven := p.process == nil |
| 563 | c.proc = nil |
| 564 | c.up.Store(false) |
| 565 | if p.process != nil { |
| 566 | if clean { |
| 567 | p.process.Stdin().Close() |
| 568 | select { |
| 569 | case <-p.exited: |
| 570 | case <-time.After(10 * time.Second): |
| 571 | } |
| 572 | } |
| 573 | p.cancel() |
| 574 | select { |
| 575 | case <-p.exited: |
| 576 | proven = p.exitErr == nil |
| 577 | case <-time.After(30 * time.Second): |
| 578 | c.log("codex coordinator stop", errors.New("exit not observed")) |
| 579 | } |
| 580 | c.syncOut(p) |
| 581 | } |
| 582 | c.cleanup(p) |
| 583 | return proven |
| 584 | } |
| 585 | |
| 586 | func (c *codexCoordinator) cleanup(p *codexProcess) { |
| 587 | if p.cancel != nil { |
| 588 | p.cancel() |
| 589 | } |
| 590 | if p.process != nil { |
| 591 | c.forget(p.process.ID()) |
| 592 | } |
| 593 | if p.tool != nil { |
| 594 | p.tool.Close() |
| 595 | } |
| 596 | if p.lease != nil { |
| 597 | c.log("codex coordinator copy close", p.lease.Close()) |
| 598 | } |
| 599 | if p.scratch != "" { |
| 600 | os.RemoveAll(p.scratch) |
| 601 | } |
| 602 | } |
| 603 | |
| 604 | // syncOut keeps the thread's rollout in the durable session home, so a |
| 605 | // later process can resume it. |
| 606 | func (c *codexCoordinator) syncOut(p *codexProcess) { |
| 607 | if p.thread == "" || p.lease == nil { |
| 608 | return |
| 609 | } |
| 610 | if err := copyRollouts(p.lease.Binding().Home, c.home, p.thread); err != nil && !errors.Is(err, fs.ErrNotExist) { |
| 611 | c.log("codex coordinator rollout", err) |
| 612 | } |
| 613 | } |
| 614 | |
| 615 | // validThread is a Codex thread id (a UUID), never a path. |
| 616 | func validThread(id string) bool { |
| 617 | if len(id) < 8 || len(id) > 64 { |
| 618 | return false |
| 619 | } |
| 620 | for _, r := range id { |
| 621 | if !(r >= '0' && r <= '9' || r >= 'a' && r <= 'f' || r == '-') { |
| 622 | return false |
| 623 | } |
| 624 | } |
| 625 | return true |
| 626 | } |
| 627 | |
| 628 | // copyRollouts copies the thread's rollout files under sessions/ from one |
| 629 | // Codex home to another, keeping their place in the tree; links and |
| 630 | // anything else are skipped. |
| 631 | func copyRollouts(from, to, thread string) error { |
| 632 | if !validThread(thread) { |
| 633 | return fs.ErrInvalid |
| 634 | } |
| 635 | root := filepath.Join(from, "sessions") |
| 636 | found := false |
| 637 | err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { |
| 638 | if err != nil { |
| 639 | return err |
| 640 | } |
| 641 | if !d.Type().IsRegular() || !strings.HasSuffix(d.Name(), "-"+thread+".jsonl") { |
| 642 | return nil |
| 643 | } |
| 644 | rel, err := filepath.Rel(from, path) |
| 645 | if err != nil { |
| 646 | return err |
| 647 | } |
| 648 | found = true |
| 649 | return copyPrivate(path, filepath.Join(to, rel)) |
| 650 | }) |
| 651 | if err == nil && !found { |
| 652 | err = fs.ErrNotExist |
| 653 | } |
| 654 | return err |
| 655 | } |
| 656 | |
| 657 | // pruneRollouts keeps the session home to the thread in use. |
| 658 | func pruneRollouts(home string) { os.RemoveAll(filepath.Join(home, "sessions")) } |
| 659 | |