| 1 | // Package fakecodex is a stand-in for the pinned Codex 0.165.0 CLI's |
| 2 | // app-server, reproducing what Equipo relies on from its JSON-RPC |
| 3 | // protocol (the schemas under internal/runner/provider/codex/testdata and |
| 4 | // `codex app-server generate-json-schema`): initialize; account/read with |
| 5 | // and without a refresh; config/read echoing the -c session flags as the |
| 6 | // effective configuration; the device-code sign-in (account/login/start |
| 7 | // with chatgptDeviceCode, account/login/completed); account/rateLimits; |
| 8 | // thread/start and thread/resume with a rollout under |
| 9 | // $CODEX_HOME/sessions; turn/start with agentMessage deltas, items, |
| 10 | // thread/tokenUsage/updated and turn/completed; turn/interrupt; and MCP |
| 11 | // tool calls through the configured stdio server after an |
| 12 | // mcpServer/elicitation/request approval. |
| 13 | // |
| 14 | // Test binaries call Main when they are started as "codex". The device |
| 15 | // sign-in completes when <dirname $CODEX_HOME>/.fake-device.json appears: |
| 16 | // {"email": ..., "plan": ...} approves, {"refuse": true} is OpenAI |
| 17 | // refusing (device login not enabled). Prompt words in the newest |
| 18 | // message steer a turn: "tool:<name>[:<arg>]" as in fakeclaude, |
| 19 | // "limit:<email>" (the account at that email has spent its limit: both |
| 20 | // windows at 100% and the turn fails usageLimitExceeded), "sleep:<ms>" |
| 21 | // pauses mid-reply, "fail" fails the turn. |
| 22 | // |
| 23 | // Steps: a prompt starting "[Equipo: engineering]" is an Engineering step. |
| 24 | // It shows a command, applies each "edit:<path>|<old>|<new>" to the file |
| 25 | // in its working directory (the namespace's /workspace) as a fileChange |
| 26 | // item, calls submit_candidate through MCP and replies with a |
| 27 | // "Headline: ..." line and a summary. A prompt starting "[Equipo: |
| 28 | // review]" is a Review step: it calls submit_review (approve, or |
| 29 | // changes_requested for each "review:changes:<path>|<line>|<text>"). |
| 30 | // "steplimit:<email>" and "reviewlimit:<email>" refuse such a step on |
| 31 | // quota as "limit:<email>" does a turn. |
| 32 | package fakecodex |
| 33 | |
| 34 | import ( |
| 35 | "bufio" |
| 36 | "crypto/rand" |
| 37 | "encoding/json" |
| 38 | "fmt" |
| 39 | "io" |
| 40 | "os" |
| 41 | "os/exec" |
| 42 | "path/filepath" |
| 43 | "regexp" |
| 44 | "strconv" |
| 45 | "strings" |
| 46 | "sync" |
| 47 | "time" |
| 48 | |
| 49 | "amadan.net/oficina/equipo/internal/fakeclaude" |
| 50 | ) |
| 51 | |
| 52 | // Version is the pinned CLI version the fake reports. |
| 53 | const Version = "0.165.0" |
| 54 | |
| 55 | // Main runs the fake with argv after the program name. |
| 56 | func Main(args []string, stdin io.Reader, stdout, stderr io.Writer) int { |
| 57 | if len(args) == 1 && args[0] == "--version" { |
| 58 | fmt.Fprintln(stdout, "codex-cli "+Version) |
| 59 | return 0 |
| 60 | } |
| 61 | if len(args) > 0 && args[len(args)-1] == "--help" { |
| 62 | return 0 |
| 63 | } |
| 64 | if len(args) == 0 || args[0] != "app-server" { |
| 65 | fmt.Fprintln(stderr, "fakecodex: only app-server is faked") |
| 66 | return 2 |
| 67 | } |
| 68 | settings := map[string]any{} |
| 69 | for i := 1; i < len(args); i++ { |
| 70 | if args[i] == "-c" && i+1 < len(args) { |
| 71 | i++ |
| 72 | k, v, ok := strings.Cut(args[i], "=") |
| 73 | if !ok { |
| 74 | return 2 |
| 75 | } |
| 76 | val, rest, err := parseTOML(v) |
| 77 | if err != nil || strings.TrimSpace(rest) != "" { |
| 78 | fmt.Fprintln(stderr, "fakecodex: bad -c value for", k) |
| 79 | return 2 |
| 80 | } |
| 81 | settings[k] = val |
| 82 | } |
| 83 | } |
| 84 | s := &server{out: json.NewEncoder(stdout), settings: settings, home: os.Getenv("CODEX_HOME"), answers: map[string]chan json.RawMessage{}} |
| 85 | return s.serve(stdin) |
| 86 | } |
| 87 | |
| 88 | type server struct { |
| 89 | wmu sync.Mutex |
| 90 | out *json.Encoder |
| 91 | settings map[string]any |
| 92 | home string |
| 93 | |
| 94 | mu sync.Mutex |
| 95 | thread string |
| 96 | turn string |
| 97 | interrupt chan struct{} |
| 98 | answers map[string]chan json.RawMessage |
| 99 | reqID int |
| 100 | |
| 101 | total tokens |
| 102 | |
| 103 | mcpIn io.Writer |
| 104 | mcpOut *bufio.Reader |
| 105 | callID int |
| 106 | } |
| 107 | |
| 108 | func (s *server) send(v any) { |
| 109 | s.wmu.Lock() |
| 110 | defer s.wmu.Unlock() |
| 111 | _ = s.out.Encode(v) |
| 112 | } |
| 113 | |
| 114 | func (s *server) notify(method string, params any) { |
| 115 | s.send(map[string]any{"method": method, "params": params}) |
| 116 | } |
| 117 | |
| 118 | func (s *server) reply(id json.RawMessage, result any) { |
| 119 | s.send(map[string]any{"id": id, "result": result}) |
| 120 | } |
| 121 | |
| 122 | func (s *server) fail(id json.RawMessage, message string) { |
| 123 | s.send(map[string]any{"id": id, "error": map[string]any{"code": -32600, "message": message}}) |
| 124 | } |
| 125 | |
| 126 | // request asks the client something and waits for its answer. |
| 127 | func (s *server) request(method string, params any) json.RawMessage { |
| 128 | s.mu.Lock() |
| 129 | s.reqID++ |
| 130 | id := strconv.Quote("s" + strconv.Itoa(s.reqID)) |
| 131 | ch := make(chan json.RawMessage, 1) |
| 132 | s.answers[id] = ch |
| 133 | s.mu.Unlock() |
| 134 | s.send(map[string]any{"id": json.RawMessage(id), "method": method, "params": params}) |
| 135 | select { |
| 136 | case raw := <-ch: |
| 137 | return raw |
| 138 | case <-time.After(30 * time.Second): |
| 139 | return nil |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | func uuid() string { |
| 144 | var b [16]byte |
| 145 | _, _ = rand.Read(b[:]) |
| 146 | b[6] = (b[6] & 15) | 112 |
| 147 | b[8] = (b[8] & 63) | 128 |
| 148 | return fmt.Sprintf("%x-%x-%x-%x-%x", b[:4], b[4:6], b[6:8], b[8:10], b[10:]) |
| 149 | } |
| 150 | |
| 151 | type authFile struct { |
| 152 | Email string `json:"email"` |
| 153 | Plan string `json:"plan"` |
| 154 | } |
| 155 | |
| 156 | func (s *server) auth() (authFile, bool) { |
| 157 | var a authFile |
| 158 | raw, err := os.ReadFile(filepath.Join(s.home, "auth.json")) |
| 159 | return a, err == nil && json.Unmarshal(raw, &a) == nil && a.Email != "" |
| 160 | } |
| 161 | |
| 162 | // WriteAuth signs a fake home in, as `codex login` leaves auth.json. |
| 163 | func WriteAuth(home, email, plan string) error { |
| 164 | raw, _ := json.Marshal(map[string]any{"email": email, "plan": plan, "tokens": map[string]string{"id_token": "fake", "access_token": "fake", "refresh_token": "fake"}}) |
| 165 | tmp := filepath.Join(home, ".auth.json.fake") |
| 166 | if err := os.WriteFile(tmp, raw, 0600); err != nil { |
| 167 | return err |
| 168 | } |
| 169 | return os.Rename(tmp, filepath.Join(home, "auth.json")) |
| 170 | } |
| 171 | |
| 172 | func (s *server) serve(stdin io.Reader) int { |
| 173 | scan := bufio.NewScanner(stdin) |
| 174 | scan.Buffer(make([]byte, 0, 64<<10), 4<<20) |
| 175 | for scan.Scan() { |
| 176 | var m struct { |
| 177 | ID json.RawMessage `json:"id"` |
| 178 | Method string `json:"method"` |
| 179 | Params json.RawMessage `json:"params"` |
| 180 | Result json.RawMessage `json:"result"` |
| 181 | Error json.RawMessage `json:"error"` |
| 182 | } |
| 183 | if json.Unmarshal(scan.Bytes(), &m) != nil { |
| 184 | return 1 |
| 185 | } |
| 186 | if m.Method == "" { |
| 187 | s.mu.Lock() |
| 188 | ch := s.answers[string(m.ID)] |
| 189 | delete(s.answers, string(m.ID)) |
| 190 | s.mu.Unlock() |
| 191 | if ch != nil { |
| 192 | if len(m.Error) > 0 { |
| 193 | ch <- json.RawMessage(`{"refused":true}`) |
| 194 | } else { |
| 195 | ch <- m.Result |
| 196 | } |
| 197 | } |
| 198 | continue |
| 199 | } |
| 200 | if len(m.ID) == 0 { |
| 201 | continue |
| 202 | } |
| 203 | s.handle(m.ID, m.Method, m.Params) |
| 204 | } |
| 205 | return 0 |
| 206 | } |
| 207 | |
| 208 | func (s *server) handle(id json.RawMessage, method string, params json.RawMessage) { |
| 209 | switch method { |
| 210 | case "initialize": |
| 211 | s.reply(id, map[string]any{"userAgent": "equipo/" + Version + " (fake; linux)", "codexHome": s.home, "platformFamily": "unix", "platformOs": "linux"}) |
| 212 | case "account/read": |
| 213 | var p struct { |
| 214 | Refresh bool `json:"refreshToken"` |
| 215 | } |
| 216 | _ = json.Unmarshal(params, &p) |
| 217 | if _, err := os.Stat(filepath.Join(s.home, ".fake-revoked")); err == nil && p.Refresh { |
| 218 | s.fail(id, "refresh_token_invalidated") |
| 219 | return |
| 220 | } |
| 221 | a, ok := s.auth() |
| 222 | if !ok { |
| 223 | s.reply(id, map[string]any{"account": nil, "requiresOpenaiAuth": true}) |
| 224 | return |
| 225 | } |
| 226 | s.reply(id, map[string]any{"account": map[string]any{"type": "chatgpt", "email": a.Email, "planType": a.Plan}, "requiresOpenaiAuth": true}) |
| 227 | case "config/read": |
| 228 | origins := map[string]any{} |
| 229 | for k := range s.settings { |
| 230 | origins[k] = map[string]any{"name": map[string]string{"type": "sessionFlags"}, "version": "fake-1"} |
| 231 | } |
| 232 | s.reply(id, map[string]any{"config": s.settings, "layers": []any{map[string]any{"name": map[string]string{"type": "sessionFlags"}, "version": "fake-1", "config": s.settings, "disabledReason": nil}}, "origins": origins}) |
| 233 | case "account/login/start": |
| 234 | var p struct { |
| 235 | Type string `json:"type"` |
| 236 | } |
| 237 | if json.Unmarshal(params, &p) != nil || p.Type != "chatgptDeviceCode" { |
| 238 | s.fail(id, "unsupported login type") |
| 239 | return |
| 240 | } |
| 241 | login := uuid() |
| 242 | s.reply(id, map[string]any{"type": "chatgptDeviceCode", "loginId": login, "verificationUrl": "https://auth.openai.com/codex/device", "userCode": "FAKE-" + strings.ToUpper(login[:4])}) |
| 243 | go s.deviceLogin(login) |
| 244 | case "account/login/cancel": |
| 245 | s.reply(id, map[string]any{"status": "canceled"}) |
| 246 | case "account/rateLimits/read": |
| 247 | s.reply(id, map[string]any{"rateLimits": s.limits(false)}) |
| 248 | case "thread/start", "thread/resume": |
| 249 | var p struct { |
| 250 | ThreadID string `json:"threadId"` |
| 251 | } |
| 252 | _ = json.Unmarshal(params, &p) |
| 253 | thread := uuid() |
| 254 | if method == "thread/resume" { |
| 255 | if s.rollout(p.ThreadID) == "" { |
| 256 | s.fail(id, "no rollout found for thread id "+p.ThreadID) |
| 257 | return |
| 258 | } |
| 259 | thread = p.ThreadID |
| 260 | } |
| 261 | s.mu.Lock() |
| 262 | s.thread = thread |
| 263 | s.mu.Unlock() |
| 264 | model, _ := s.settings["model"].(string) |
| 265 | s.reply(id, map[string]any{"thread": map[string]any{"id": thread}, "model": model, "modelProvider": "openai", "cwd": "/workspace", "approvalPolicy": "on-request", "approvalsReviewer": "user", "activePermissionProfile": map[string]any{"id": "equipo", "extends": nil}, "runtimeWorkspaceRoots": []string{"/workspace"}}) |
| 266 | s.total = tokens{} |
| 267 | if method == "thread/resume" { |
| 268 | // The resumed thread's last turn's usage, sent again. |
| 269 | if last, turn, ok := s.loadTotal(thread); ok { |
| 270 | s.total = last |
| 271 | s.usage(thread, turn, last, last) |
| 272 | } |
| 273 | } |
| 274 | case "turn/start": |
| 275 | var p struct { |
| 276 | ThreadID string `json:"threadId"` |
| 277 | Input []struct { |
| 278 | Type string `json:"type"` |
| 279 | Text string `json:"text"` |
| 280 | Path string `json:"path"` |
| 281 | } `json:"input"` |
| 282 | } |
| 283 | s.mu.Lock() |
| 284 | thread := s.thread |
| 285 | s.mu.Unlock() |
| 286 | if json.Unmarshal(params, &p) != nil || p.ThreadID != thread || len(p.Input) < 1 || p.Input[0].Type != "text" { |
| 287 | s.fail(id, "bad turn") |
| 288 | return |
| 289 | } |
| 290 | // localImage inputs: the app-server reads each path itself, inside |
| 291 | // the namespace, as the pinned version does. |
| 292 | seen := "" |
| 293 | for _, in := range p.Input[1:] { |
| 294 | data, err := os.ReadFile(in.Path) |
| 295 | if in.Type != "localImage" || err != nil { |
| 296 | s.fail(id, "bad image input") |
| 297 | return |
| 298 | } |
| 299 | media := "image/png" |
| 300 | switch { |
| 301 | case len(data) > 2 && data[0] == 0xff && data[1] == 0xd8: |
| 302 | media = "image/jpeg" |
| 303 | case strings.HasPrefix(string(data), "GIF8"): |
| 304 | media = "image/gif" |
| 305 | case len(data) > 12 && string(data[8:12]) == "WEBP": |
| 306 | media = "image/webp" |
| 307 | } |
| 308 | seen += " [localImage " + in.Path + " " + fakeclaude.DescribeImage(media, data) + "]" |
| 309 | } |
| 310 | p.Input[0].Text += "\x00" + seen |
| 311 | turn := uuid() |
| 312 | stop := make(chan struct{}) |
| 313 | s.mu.Lock() |
| 314 | s.turn, s.interrupt = turn, stop |
| 315 | s.mu.Unlock() |
| 316 | s.reply(id, map[string]any{"turn": map[string]any{"id": turn, "status": "inProgress", "items": []any{}}}) |
| 317 | go s.runTurn(thread, turn, p.Input[0].Text, stop) |
| 318 | case "turn/interrupt": |
| 319 | s.mu.Lock() |
| 320 | if s.interrupt != nil { |
| 321 | close(s.interrupt) |
| 322 | s.interrupt = nil |
| 323 | } |
| 324 | s.mu.Unlock() |
| 325 | s.reply(id, map[string]any{}) |
| 326 | default: |
| 327 | s.fail(id, "method not faked: "+method) |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | // deviceLogin waits for the person's approval (a file the test writes |
| 332 | // beside the new home) and completes the sign-in. |
| 333 | func (s *server) deviceLogin(login string) { |
| 334 | path := filepath.Join(filepath.Dir(s.home), ".fake-device.json") |
| 335 | for deadline := time.Now().Add(2 * time.Minute); time.Now().Before(deadline); time.Sleep(100 * time.Millisecond) { |
| 336 | raw, err := os.ReadFile(path) |
| 337 | if err != nil { |
| 338 | continue |
| 339 | } |
| 340 | var v struct { |
| 341 | Email, Plan string |
| 342 | Refuse bool |
| 343 | } |
| 344 | if json.Unmarshal(raw, &v) != nil { |
| 345 | continue |
| 346 | } |
| 347 | if v.Refuse { |
| 348 | s.notify("account/login/completed", map[string]any{"loginId": login, "success": false, "error": "Enable device code authorization for Codex in ChatGPT Security Settings"}) |
| 349 | return |
| 350 | } |
| 351 | if WriteAuth(s.home, v.Email, v.Plan) != nil { |
| 352 | return |
| 353 | } |
| 354 | s.notify("account/login/completed", map[string]any{"loginId": login, "success": true, "error": nil}) |
| 355 | s.notify("account/updated", map[string]any{"authMode": "chatgpt", "planType": v.Plan}) |
| 356 | return |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | func (s *server) limits(spent bool) map[string]any { |
| 361 | used := 10 |
| 362 | if spent { |
| 363 | used = 100 |
| 364 | } |
| 365 | a, _ := s.auth() |
| 366 | return map[string]any{"primary": map[string]any{"usedPercent": used, "windowDurationMins": 300, "resetsAt": time.Now().Add(3 * time.Hour).Truncate(time.Hour).Unix()}, "secondary": map[string]any{"usedPercent": used, "windowDurationMins": 10080, "resetsAt": time.Now().Add(70 * time.Hour).Truncate(time.Hour).Unix()}, "planType": a.Plan, "limitId": nil, "limitName": nil, "rateLimitReachedType": nil} |
| 367 | } |
| 368 | |
| 369 | // rollout is the thread's rollout file, or "". |
| 370 | func (s *server) rollout(thread string) string { |
| 371 | matches, _ := filepath.Glob(filepath.Join(s.home, "sessions", "*", "*", "*", "rollout-*-"+thread+".jsonl")) |
| 372 | if len(matches) == 1 { |
| 373 | return matches[0] |
| 374 | } |
| 375 | return "" |
| 376 | } |
| 377 | |
| 378 | func (s *server) record(thread, prompt, reply string) int { |
| 379 | path := s.rollout(thread) |
| 380 | if path == "" { |
| 381 | now := time.Now().UTC() |
| 382 | path = filepath.Join(s.home, "sessions", now.Format("2006"), now.Format("01"), now.Format("02"), "rollout-"+now.Format("2006-01-02T15-04-05")+"-"+thread+".jsonl") |
| 383 | _ = os.MkdirAll(filepath.Dir(path), 0700) |
| 384 | } |
| 385 | f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600) |
| 386 | if err == nil { |
| 387 | for _, line := range []map[string]string{{"type": "user", "text": prompt}, {"type": "agent", "text": reply}} { |
| 388 | raw, _ := json.Marshal(line) |
| 389 | f.Write(append(raw, '\n')) |
| 390 | } |
| 391 | f.Close() |
| 392 | } |
| 393 | raw, _ := os.ReadFile(path) |
| 394 | return strings.Count(string(raw), `"type":"agent"`) |
| 395 | } |
| 396 | |
| 397 | var ( |
| 398 | toolWord = regexp.MustCompile(`tool:([a-z_]+)(?::([^\n]*))?`) |
| 399 | limitWord = regexp.MustCompile(`\blimit:([^\s|]+@[^\s|]+[a-z])`) |
| 400 | stepLimitWord = regexp.MustCompile(`\bsteplimit:([^\s|]+@[^\s|]+[a-z])`) |
| 401 | reviewLimitWord = regexp.MustCompile(`\breviewlimit:([^\s|]+@[^\s|]+[a-z])`) |
| 402 | sleepWord = regexp.MustCompile(`\bsleep:([0-9]+)`) |
| 403 | pauseWord = regexp.MustCompile(`\bpause:([0-9]+)`) |
| 404 | editWord = regexp.MustCompile(`edit:([^|\n]+)\|([^|\n]*)\|([^\n]*)`) |
| 405 | reviewChanges = regexp.MustCompile(`review:changes:([^|\n]+)\|([0-9]+)\|([^\n;]*)`) |
| 406 | ) |
| 407 | |
| 408 | func (s *server) runTurn(thread, turn, prompt string, stop chan struct{}) { |
| 409 | prompt, seen, _ := strings.Cut(prompt, "\x00") |
| 410 | newest := prompt |
| 411 | if _, after, ok := strings.Cut(prompt, "Newest message:\n"); ok { |
| 412 | newest = after |
| 413 | } |
| 414 | // Words a failed turn left unanswered ride before it, as context. |
| 415 | if _, after, ok := strings.Cut(newest, "The person's newest message:\n"); ok { |
| 416 | newest = after |
| 417 | } |
| 418 | done := func(status string, turnErr any) { |
| 419 | s.notify("turn/completed", map[string]any{"threadId": thread, "turn": map[string]any{"id": turn, "status": status, "items": []any{}, "error": turnErr}}) |
| 420 | } |
| 421 | interrupted := func() bool { |
| 422 | select { |
| 423 | case <-stop: |
| 424 | done("interrupted", nil) |
| 425 | return true |
| 426 | default: |
| 427 | return false |
| 428 | } |
| 429 | } |
| 430 | s.notify("turn/started", map[string]any{"threadId": thread, "turn": map[string]any{"id": turn, "status": "inProgress", "items": []any{}}}) |
| 431 | a, _ := s.auth() |
| 432 | engineering, review := strings.HasPrefix(prompt, "[Equipo: engineering]"), strings.HasPrefix(prompt, "[Equipo: review]") |
| 433 | spent := func(word *regexp.Regexp, text string) bool { |
| 434 | m := word.FindStringSubmatch(text) |
| 435 | return m != nil && m[1] == a.Email |
| 436 | } |
| 437 | if spent(limitWord, newest) || engineering && spent(stepLimitWord, prompt) || review && spent(reviewLimitWord, prompt) { |
| 438 | s.notify("account/rateLimits/updated", map[string]any{"rateLimits": s.limits(true)}) |
| 439 | e := map[string]any{"message": "You've hit your usage limit.", "codexErrorInfo": "usageLimitExceeded", "additionalDetails": nil} |
| 440 | s.notify("error", map[string]any{"threadId": thread, "turnId": turn, "willRetry": false, "error": e}) |
| 441 | done("failed", e) |
| 442 | return |
| 443 | } |
| 444 | if engineering || review { |
| 445 | s.step(thread, turn, prompt, review, done) |
| 446 | return |
| 447 | } |
| 448 | // A glance: one short line from the small model, no tools. |
| 449 | earlier := false |
| 450 | if path := s.rollout(thread); path != "" { |
| 451 | raw, _ := os.ReadFile(path) |
| 452 | earlier = strings.Contains(string(raw), `"type":"agent"`) |
| 453 | } |
| 454 | if line, pause, fail, ok := fakeclaude.Glance(prompt, earlier); ok { |
| 455 | select { |
| 456 | case <-stop: |
| 457 | case <-time.After(pause): |
| 458 | } |
| 459 | if interrupted() { |
| 460 | return |
| 461 | } |
| 462 | if fail { |
| 463 | done("failed", map[string]any{"message": "stream disconnected", "codexErrorInfo": "other"}) |
| 464 | return |
| 465 | } |
| 466 | msg := "msg_" + turn[:8] |
| 467 | s.notify("item/completed", map[string]any{"threadId": thread, "turnId": turn, "item": map[string]any{"id": msg, "type": "agentMessage", "text": line}}) |
| 468 | s.record(thread, prompt, line) |
| 469 | done("completed", nil) |
| 470 | return |
| 471 | } |
| 472 | reply := "" |
| 473 | for i, m := range toolWord.FindAllStringSubmatch(newest, -1) { |
| 474 | text, _ := s.mcpTool(thread, turn, fmt.Sprintf("mcp_%s_%d", turn[:8], i), m[1], fakeclaude.ToolInput(m[1], m[2])) |
| 475 | reply += fmt.Sprintf(" [%s: %s]", m[1], text) |
| 476 | if interrupted() { |
| 477 | return |
| 478 | } |
| 479 | } |
| 480 | turns := 0 |
| 481 | if path := s.rollout(thread); path != "" { |
| 482 | raw, _ := os.ReadFile(path) |
| 483 | turns = strings.Count(string(raw), `"type":"agent"`) |
| 484 | } |
| 485 | context := "fresh" |
| 486 | if turns > 0 { |
| 487 | context = "resumed" |
| 488 | } |
| 489 | text := fmt.Sprintf("Hello from the fake Codex coordinator. Turn %d, %s thread.", turns+1, context) + reply + seen |
| 490 | if strings.Contains(prompt, "Conversation so far") { |
| 491 | text += " I see the earlier conversation." |
| 492 | } |
| 493 | if strings.Contains(prompt, "=== Your notebook") { |
| 494 | text += " (notebook in context)" |
| 495 | } |
| 496 | pause := time.Duration(0) |
| 497 | if m := sleepWord.FindStringSubmatch(newest); m != nil { |
| 498 | ms, _ := strconv.Atoi(m[1]) |
| 499 | pause = time.Duration(ms) * time.Millisecond |
| 500 | } |
| 501 | // Two requests' worth: half before the pause, the rest at the end. |
| 502 | half := tokens{Input: len(prompt) / 8, Cached: len(prompt) / 16, Output: len(text) / 8, Reasoning: 3} |
| 503 | full := tokens{Input: len(prompt) / 4, Cached: len(prompt) / 8, Output: len(text) / 4, Reasoning: 7} |
| 504 | rest := tokens{full.Input - half.Input, full.Cached - half.Cached, full.Output - half.Output, full.Reasoning - half.Reasoning} |
| 505 | // pause: waits before the first words, as the fake Claude does. |
| 506 | if m := pauseWord.FindStringSubmatch(newest); m != nil { |
| 507 | ms, _ := strconv.Atoi(m[1]) |
| 508 | select { |
| 509 | case <-stop: |
| 510 | case <-time.After(time.Duration(ms) * time.Millisecond): |
| 511 | } |
| 512 | } |
| 513 | msg := "msg_" + turn[:8] |
| 514 | s.notify("item/started", map[string]any{"threadId": thread, "turnId": turn, "item": map[string]any{"id": msg, "type": "agentMessage", "text": ""}}) |
| 515 | words := strings.SplitAfter(text, " ") |
| 516 | third := max(len(words)/3, 1) |
| 517 | for i := 0; i < len(words); i += third { |
| 518 | chunk := strings.Join(words[i:min(i+third, len(words))], "") |
| 519 | s.notify("item/agentMessage/delta", map[string]any{"threadId": thread, "turnId": turn, "itemId": msg, "delta": chunk}) |
| 520 | if i == 0 { |
| 521 | // The first request's usage, as the pinned app-server sends it |
| 522 | // mid-turn: a cancelled turn has figures too. |
| 523 | s.usage(thread, turn, s.total.plus(half), half) |
| 524 | } |
| 525 | if pause > 0 && i == 0 { |
| 526 | select { |
| 527 | case <-stop: |
| 528 | case <-time.After(pause): |
| 529 | } |
| 530 | } |
| 531 | if interrupted() { |
| 532 | return |
| 533 | } |
| 534 | } |
| 535 | if strings.Contains(newest, "fail") { |
| 536 | done("failed", map[string]any{"message": "stream disconnected", "codexErrorInfo": "other"}) |
| 537 | return |
| 538 | } |
| 539 | s.notify("item/completed", map[string]any{"threadId": thread, "turnId": turn, "item": map[string]any{"id": msg, "type": "agentMessage", "text": text}}) |
| 540 | s.record(thread, prompt, text) |
| 541 | // The second notice for the turn, with the thread's running total (as |
| 542 | // the pinned app-server sends them), resent once. |
| 543 | s.usage(thread, turn, s.total.plus(full), rest) |
| 544 | s.usage(thread, turn, s.total.plus(full), rest) |
| 545 | s.total = s.total.plus(full) |
| 546 | s.saveTotal(thread, turn) |
| 547 | s.notify("account/rateLimits/updated", map[string]any{"rateLimits": s.limits(false)}) |
| 548 | done("completed", nil) |
| 549 | } |
| 550 | |
| 551 | // mcpTool calls an Equipo tool as Codex does: the item starts, the |
| 552 | // client is asked to approve the call, and only an accepted call reaches |
| 553 | // the MCP server. |
| 554 | func (s *server) mcpTool(thread, turn, item, name string, input map[string]any) (string, bool) { |
| 555 | args, _ := json.Marshal(input) |
| 556 | started := map[string]any{"id": item, "type": "mcpToolCall", "server": "equipo", "tool": name, "arguments": json.RawMessage(args), "status": "inProgress"} |
| 557 | s.notify("item/started", map[string]any{"threadId": thread, "turnId": turn, "item": started}) |
| 558 | answer := s.request("mcpServer/elicitation/request", map[string]any{"threadId": thread, "turnId": turn, "serverName": "equipo", "mode": "form", "message": "Allow the equipo MCP server to run tool " + name + "?", "_meta": map[string]any{"codex_approval_kind": "mcp_tool_call", "tool_params": json.RawMessage(args)}, "requestedSchema": map[string]any{"type": "object", "properties": map[string]any{}}}) |
| 559 | var v struct { |
| 560 | Action string `json:"action"` |
| 561 | } |
| 562 | _ = json.Unmarshal(answer, &v) |
| 563 | text, isError := "user declined the tool call", true |
| 564 | if v.Action == "accept" { |
| 565 | text, isError = s.callTool(name, input) |
| 566 | } |
| 567 | status := "completed" |
| 568 | if isError { |
| 569 | status = "failed" |
| 570 | } |
| 571 | s.notify("item/completed", map[string]any{"threadId": thread, "turnId": turn, "item": map[string]any{"id": item, "type": "mcpToolCall", "server": "equipo", "tool": name, "arguments": json.RawMessage(args), "status": status, "result": map[string]any{"content": []any{map[string]string{"type": "text", "text": text}}}, "error": nil}}) |
| 572 | return text, isError |
| 573 | } |
| 574 | |
| 575 | // step plays an Engineering or Review step in the working directory. |
| 576 | func (s *server) step(thread, turn, prompt string, review bool, done func(string, any)) { |
| 577 | prompt = fakeclaude.StepMarkerText(prompt) |
| 578 | item := func(kind string, i int) string { return fmt.Sprintf("%s_%s_%d", kind, turn[:8], i) } |
| 579 | var notes []string |
| 580 | reply := "" |
| 581 | if !review { |
| 582 | edits := fakeclaude.DistinctStepMarkers(editWord, prompt) |
| 583 | if len(edits) > 0 { |
| 584 | cmd := map[string]any{"id": item("cmd", 0), "type": "commandExecution", "command": "cat " + edits[0][1], "cwd": "/workspace", "status": "inProgress"} |
| 585 | s.notify("item/started", map[string]any{"threadId": thread, "turnId": turn, "item": cmd}) |
| 586 | cmd["status"] = "completed" |
| 587 | s.notify("item/completed", map[string]any{"threadId": thread, "turnId": turn, "item": cmd}) |
| 588 | } |
| 589 | for i, m := range edits { |
| 590 | change := map[string]any{"id": item("patch", i), "type": "fileChange", "changes": []any{map[string]any{"path": filepath.Join("/workspace", filepath.Clean("/"+m[1])), "kind": map[string]string{"type": "update"}, "diff": ""}}, "status": "inProgress"} |
| 591 | s.notify("item/started", map[string]any{"threadId": thread, "turnId": turn, "item": change}) |
| 592 | raw, err := os.ReadFile(m[1]) |
| 593 | if err == nil { |
| 594 | err = os.WriteFile(m[1], []byte(strings.Replace(string(raw), m[2], m[3], 1)), 0644) |
| 595 | } |
| 596 | change["status"] = "completed" |
| 597 | note := fmt.Sprintf("Replaced %q with %q in %s.", m[2], m[3], m[1]) |
| 598 | if err != nil { |
| 599 | change["status"], note = "failed", "Could not change "+m[1]+"." |
| 600 | } |
| 601 | s.notify("item/completed", map[string]any{"threadId": thread, "turnId": turn, "item": change}) |
| 602 | notes = append(notes, note) |
| 603 | } |
| 604 | if text, isError := s.mcpTool(thread, turn, item("mcp", 0), "submit_candidate", map[string]any{}); isError { |
| 605 | notes = append(notes, "[submit_candidate failed: "+text+"]") |
| 606 | } |
| 607 | reply = "Headline: Made the change the task asks for.\n\n" + strings.Join(notes, " ") |
| 608 | if len(edits) == 0 { |
| 609 | reply = "Headline: Nothing needed changing.\n\nI looked and changed nothing." |
| 610 | } |
| 611 | } else { |
| 612 | verdict, headline, summary, findings := "approve", "Approved.", "The change does what the task asks.", []map[string]any{} |
| 613 | for _, m := range fakeclaude.DistinctStepMarkers(reviewChanges, prompt) { |
| 614 | line, _ := strconv.Atoi(m[2]) |
| 615 | verdict, headline, summary = "changes_requested", "Asked for one more change.", "One thing needs changing." |
| 616 | findings = append(findings, map[string]any{"path": m[1], "line": line, "text": m[3]}) |
| 617 | } |
| 618 | reply = summary + " (from Codex)" |
| 619 | if text, isError := s.mcpTool(thread, turn, item("mcp", 0), "submit_review", map[string]any{"verdict": verdict, "headline": headline, "summary": summary + " (from Codex)", "findings": findings}); isError { |
| 620 | reply += " [submit_review failed: " + text + "]" |
| 621 | } |
| 622 | } |
| 623 | msg := item("msg", 0) |
| 624 | s.notify("item/started", map[string]any{"threadId": thread, "turnId": turn, "item": map[string]any{"id": msg, "type": "agentMessage", "text": ""}}) |
| 625 | s.notify("item/agentMessage/delta", map[string]any{"threadId": thread, "turnId": turn, "itemId": msg, "delta": reply}) |
| 626 | s.notify("item/completed", map[string]any{"threadId": thread, "turnId": turn, "item": map[string]any{"id": msg, "type": "agentMessage", "text": reply}}) |
| 627 | used := tokens{Input: len(prompt) / 4, Cached: len(prompt) / 8, Output: len(reply) / 4, Reasoning: 5} |
| 628 | s.total = s.total.plus(used) |
| 629 | s.usage(thread, turn, s.total, used) |
| 630 | s.notify("account/rateLimits/updated", map[string]any{"rateLimits": s.limits(false)}) |
| 631 | done("completed", nil) |
| 632 | } |
| 633 | |
| 634 | type tokens struct{ Input, Cached, Output, Reasoning int } |
| 635 | |
| 636 | func (a tokens) plus(b tokens) tokens { |
| 637 | return tokens{a.Input + b.Input, a.Cached + b.Cached, a.Output + b.Output, a.Reasoning + b.Reasoning} |
| 638 | } |
| 639 | |
| 640 | func (a tokens) breakdown() map[string]any { |
| 641 | return map[string]any{"inputTokens": a.Input, "cachedInputTokens": a.Cached, "cacheWriteInputTokens": 0, "outputTokens": a.Output, "reasoningOutputTokens": a.Reasoning, "totalTokens": a.Input + a.Output + a.Reasoning} |
| 642 | } |
| 643 | |
| 644 | func (s *server) usage(thread, turn string, total, last tokens) { |
| 645 | s.notify("thread/tokenUsage/updated", map[string]any{"threadId": thread, "turnId": turn, "tokenUsage": map[string]any{"last": last.breakdown(), "total": total.breakdown(), "modelContextWindow": 272000}}) |
| 646 | } |
| 647 | |
| 648 | func (s *server) saveTotal(thread, turn string) { |
| 649 | if path := s.rollout(thread); path != "" { |
| 650 | if f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0600); err == nil { |
| 651 | raw, _ := json.Marshal(map[string]any{"type": "usage", "turn": turn, "total": s.total}) |
| 652 | f.Write(append(raw, '\n')) |
| 653 | f.Close() |
| 654 | } |
| 655 | } |
| 656 | } |
| 657 | |
| 658 | func (s *server) loadTotal(thread string) (tokens, string, bool) { |
| 659 | raw, err := os.ReadFile(s.rollout(thread)) |
| 660 | if err != nil { |
| 661 | return tokens{}, "", false |
| 662 | } |
| 663 | var out tokens |
| 664 | turn, ok := "", false |
| 665 | for _, line := range strings.Split(string(raw), "\n") { |
| 666 | var v struct { |
| 667 | Type, Turn string |
| 668 | Total tokens |
| 669 | } |
| 670 | if json.Unmarshal([]byte(line), &v) == nil && v.Type == "usage" { |
| 671 | out, turn, ok = v.Total, v.Turn, true |
| 672 | } |
| 673 | } |
| 674 | return out, turn, ok |
| 675 | } |
| 676 | |
| 677 | // callTool calls an Equipo tool through the configured MCP server, |
| 678 | // starting it on first use. |
| 679 | func (s *server) callTool(name string, input map[string]any) (string, bool) { |
| 680 | if s.mcpIn == nil { |
| 681 | if msg := s.connectMCP(); msg != "" { |
| 682 | return msg, true |
| 683 | } |
| 684 | } |
| 685 | s.callID++ |
| 686 | raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 100 + s.callID, "method": "tools/call", "params": map[string]any{"name": name, "arguments": input}}) |
| 687 | if _, err := s.mcpIn.Write(append(raw, '\n')); err != nil { |
| 688 | return "MCP write failed", true |
| 689 | } |
| 690 | line, err := s.mcpOut.ReadBytes('\n') |
| 691 | var reply struct { |
| 692 | Result struct { |
| 693 | Content []struct { |
| 694 | Text string `json:"text"` |
| 695 | } `json:"content"` |
| 696 | IsError bool `json:"isError"` |
| 697 | } `json:"result"` |
| 698 | Error *struct{} `json:"error"` |
| 699 | } |
| 700 | if err != nil || json.Unmarshal(line, &reply) != nil || reply.Error != nil || len(reply.Result.Content) == 0 { |
| 701 | return "MCP call failed", true |
| 702 | } |
| 703 | return reply.Result.Content[0].Text, reply.Result.IsError |
| 704 | } |
| 705 | |
| 706 | // connectMCP starts the equipo server from the session flags and checks |
| 707 | // its tool list against enabled_tools, as Codex filters it. |
| 708 | func (s *server) connectMCP() string { |
| 709 | servers, _ := s.settings["mcp_servers"].(map[string]any) |
| 710 | eq, _ := servers["equipo"].(map[string]any) |
| 711 | command, _ := eq["command"].(string) |
| 712 | var args []string |
| 713 | if list, ok := eq["args"].([]any); ok { |
| 714 | for _, a := range list { |
| 715 | if v, ok := a.(string); ok { |
| 716 | args = append(args, v) |
| 717 | } |
| 718 | } |
| 719 | } |
| 720 | if command == "" { |
| 721 | return "no MCP server configured" |
| 722 | } |
| 723 | cmd := exec.Command(command, args...) |
| 724 | in, _ := cmd.StdinPipe() |
| 725 | out, _ := cmd.StdoutPipe() |
| 726 | if cmd.Start() != nil { |
| 727 | return "MCP server did not start" |
| 728 | } |
| 729 | r := bufio.NewReader(out) |
| 730 | call := func(id int, method string, params any) json.RawMessage { |
| 731 | raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": id, "method": method, "params": params}) |
| 732 | if _, err := in.Write(append(raw, '\n')); err != nil { |
| 733 | return nil |
| 734 | } |
| 735 | line, err := r.ReadBytes('\n') |
| 736 | var reply struct { |
| 737 | Result json.RawMessage `json:"result"` |
| 738 | } |
| 739 | if err != nil || json.Unmarshal(line, &reply) != nil { |
| 740 | return nil |
| 741 | } |
| 742 | return reply.Result |
| 743 | } |
| 744 | if call(1, "initialize", map[string]any{"protocolVersion": "2025-06-18", "capabilities": map[string]any{}, "clientInfo": map[string]string{"name": "fake-codex", "version": Version}}) == nil { |
| 745 | return "MCP initialize failed" |
| 746 | } |
| 747 | note, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "method": "notifications/initialized"}) |
| 748 | in.Write(append(note, '\n')) |
| 749 | if call(2, "tools/list", map[string]any{}) == nil { |
| 750 | return "MCP tools/list failed" |
| 751 | } |
| 752 | s.mcpIn, s.mcpOut = in, r |
| 753 | return "" |
| 754 | } |
| 755 | |
| 756 | // parseTOML reads one value of the inline TOML the launcher renders: |
| 757 | // basic strings, integers, booleans, arrays and inline tables with |
| 758 | // quoted keys. It returns the value and the unread rest. |
| 759 | func parseTOML(v string) (any, string, error) { |
| 760 | v = strings.TrimLeft(v, " ") |
| 761 | switch { |
| 762 | case v == "": |
| 763 | return nil, v, fmt.Errorf("empty") |
| 764 | case v[0] == '"': |
| 765 | end := 1 |
| 766 | for ; end < len(v); end++ { |
| 767 | if v[end] == '\\' { |
| 768 | end++ |
| 769 | continue |
| 770 | } |
| 771 | if v[end] == '"' { |
| 772 | break |
| 773 | } |
| 774 | } |
| 775 | if end >= len(v) { |
| 776 | return nil, v, fmt.Errorf("unterminated string") |
| 777 | } |
| 778 | s, err := strconv.Unquote(v[:end+1]) |
| 779 | return s, v[end+1:], err |
| 780 | case strings.HasPrefix(v, "true"): |
| 781 | return true, v[4:], nil |
| 782 | case strings.HasPrefix(v, "false"): |
| 783 | return false, v[5:], nil |
| 784 | case v[0] == '[': |
| 785 | out := []any{} |
| 786 | rest := strings.TrimLeft(v[1:], " ") |
| 787 | for !strings.HasPrefix(rest, "]") { |
| 788 | val, r, err := parseTOML(rest) |
| 789 | if err != nil { |
| 790 | return nil, v, err |
| 791 | } |
| 792 | out = append(out, val) |
| 793 | rest = strings.TrimLeft(strings.TrimPrefix(strings.TrimLeft(r, " "), ","), " ") |
| 794 | } |
| 795 | return out, rest[1:], nil |
| 796 | case v[0] == '{': |
| 797 | out := map[string]any{} |
| 798 | rest := strings.TrimLeft(v[1:], " ") |
| 799 | for !strings.HasPrefix(rest, "}") { |
| 800 | key, r, err := parseTOML(rest) |
| 801 | k, ok := key.(string) |
| 802 | if err != nil || !ok { |
| 803 | return nil, v, fmt.Errorf("bad key") |
| 804 | } |
| 805 | r = strings.TrimLeft(r, " ") |
| 806 | if !strings.HasPrefix(r, "=") { |
| 807 | return nil, v, fmt.Errorf("missing =") |
| 808 | } |
| 809 | val, r2, err := parseTOML(r[1:]) |
| 810 | if err != nil { |
| 811 | return nil, v, err |
| 812 | } |
| 813 | out[k] = val |
| 814 | rest = strings.TrimLeft(strings.TrimPrefix(strings.TrimLeft(r2, " "), ","), " ") |
| 815 | } |
| 816 | return out, rest[1:], nil |
| 817 | } |
| 818 | end := strings.IndexAny(v, ",]} ") |
| 819 | if end < 0 { |
| 820 | end = len(v) |
| 821 | } |
| 822 | n, err := strconv.ParseInt(v[:end], 10, 64) |
| 823 | return n, v[end:], err |
| 824 | } |
| 825 | |