// Package fakecodex is a stand-in for the pinned Codex 0.165.0 CLI's // app-server, reproducing what Equipo relies on from its JSON-RPC // protocol (the schemas under internal/runner/provider/codex/testdata and // `codex app-server generate-json-schema`): initialize; account/read with // and without a refresh; config/read echoing the -c session flags as the // effective configuration; the device-code sign-in (account/login/start // with chatgptDeviceCode, account/login/completed); account/rateLimits; // thread/start and thread/resume with a rollout under // $CODEX_HOME/sessions; turn/start with agentMessage deltas, items, // thread/tokenUsage/updated and turn/completed; turn/interrupt; and MCP // tool calls through the configured stdio server after an // mcpServer/elicitation/request approval. // // Test binaries call Main when they are started as "codex". The device // sign-in completes when /.fake-device.json appears: // {"email": ..., "plan": ...} approves, {"refuse": true} is OpenAI // refusing (device login not enabled). Prompt words in the newest // message steer a turn: "tool:[:]" as in fakeclaude, // "limit:" (the account at that email has spent its limit: both // windows at 100% and the turn fails usageLimitExceeded), "sleep:" // pauses mid-reply, "fail" fails the turn. // // Steps: a prompt starting "[Equipo: engineering]" is an Engineering step. // It shows a command, applies each "edit:||" to the file // in its working directory (the namespace's /workspace) as a fileChange // item, calls submit_candidate through MCP and replies with a // "Headline: ..." line and a summary. A prompt starting "[Equipo: // review]" is a Review step: it calls submit_review (approve, or // changes_requested for each "review:changes:||"). // "steplimit:" and "reviewlimit:" refuse such a step on // quota as "limit:" does a turn. package fakecodex import ( "bufio" "crypto/rand" "encoding/json" "fmt" "io" "os" "os/exec" "path/filepath" "regexp" "strconv" "strings" "sync" "time" "amadan.net/oficina/equipo/internal/fakeclaude" ) // Version is the pinned CLI version the fake reports. const Version = "0.165.0" // Main runs the fake with argv after the program name. func Main(args []string, stdin io.Reader, stdout, stderr io.Writer) int { if len(args) == 1 && args[0] == "--version" { fmt.Fprintln(stdout, "codex-cli "+Version) return 0 } if len(args) > 0 && args[len(args)-1] == "--help" { return 0 } if len(args) == 0 || args[0] != "app-server" { fmt.Fprintln(stderr, "fakecodex: only app-server is faked") return 2 } settings := map[string]any{} for i := 1; i < len(args); i++ { if args[i] == "-c" && i+1 < len(args) { i++ k, v, ok := strings.Cut(args[i], "=") if !ok { return 2 } val, rest, err := parseTOML(v) if err != nil || strings.TrimSpace(rest) != "" { fmt.Fprintln(stderr, "fakecodex: bad -c value for", k) return 2 } settings[k] = val } } s := &server{out: json.NewEncoder(stdout), settings: settings, home: os.Getenv("CODEX_HOME"), answers: map[string]chan json.RawMessage{}} return s.serve(stdin) } type server struct { wmu sync.Mutex out *json.Encoder settings map[string]any home string mu sync.Mutex thread string turn string interrupt chan struct{} answers map[string]chan json.RawMessage reqID int total tokens mcpIn io.Writer mcpOut *bufio.Reader callID int } func (s *server) send(v any) { s.wmu.Lock() defer s.wmu.Unlock() _ = s.out.Encode(v) } func (s *server) notify(method string, params any) { s.send(map[string]any{"method": method, "params": params}) } func (s *server) reply(id json.RawMessage, result any) { s.send(map[string]any{"id": id, "result": result}) } func (s *server) fail(id json.RawMessage, message string) { s.send(map[string]any{"id": id, "error": map[string]any{"code": -32600, "message": message}}) } // request asks the client something and waits for its answer. func (s *server) request(method string, params any) json.RawMessage { s.mu.Lock() s.reqID++ id := strconv.Quote("s" + strconv.Itoa(s.reqID)) ch := make(chan json.RawMessage, 1) s.answers[id] = ch s.mu.Unlock() s.send(map[string]any{"id": json.RawMessage(id), "method": method, "params": params}) select { case raw := <-ch: return raw case <-time.After(30 * time.Second): return nil } } func uuid() string { var b [16]byte _, _ = rand.Read(b[:]) b[6] = (b[6] & 15) | 112 b[8] = (b[8] & 63) | 128 return fmt.Sprintf("%x-%x-%x-%x-%x", b[:4], b[4:6], b[6:8], b[8:10], b[10:]) } type authFile struct { Email string `json:"email"` Plan string `json:"plan"` } func (s *server) auth() (authFile, bool) { var a authFile raw, err := os.ReadFile(filepath.Join(s.home, "auth.json")) return a, err == nil && json.Unmarshal(raw, &a) == nil && a.Email != "" } // WriteAuth signs a fake home in, as `codex login` leaves auth.json. func WriteAuth(home, email, plan string) error { raw, _ := json.Marshal(map[string]any{"email": email, "plan": plan, "tokens": map[string]string{"id_token": "fake", "access_token": "fake", "refresh_token": "fake"}}) tmp := filepath.Join(home, ".auth.json.fake") if err := os.WriteFile(tmp, raw, 0600); err != nil { return err } return os.Rename(tmp, filepath.Join(home, "auth.json")) } func (s *server) serve(stdin io.Reader) int { scan := bufio.NewScanner(stdin) scan.Buffer(make([]byte, 0, 64<<10), 4<<20) for scan.Scan() { var m struct { ID json.RawMessage `json:"id"` Method string `json:"method"` Params json.RawMessage `json:"params"` Result json.RawMessage `json:"result"` Error json.RawMessage `json:"error"` } if json.Unmarshal(scan.Bytes(), &m) != nil { return 1 } if m.Method == "" { s.mu.Lock() ch := s.answers[string(m.ID)] delete(s.answers, string(m.ID)) s.mu.Unlock() if ch != nil { if len(m.Error) > 0 { ch <- json.RawMessage(`{"refused":true}`) } else { ch <- m.Result } } continue } if len(m.ID) == 0 { continue } s.handle(m.ID, m.Method, m.Params) } return 0 } func (s *server) handle(id json.RawMessage, method string, params json.RawMessage) { switch method { case "initialize": s.reply(id, map[string]any{"userAgent": "equipo/" + Version + " (fake; linux)", "codexHome": s.home, "platformFamily": "unix", "platformOs": "linux"}) case "account/read": var p struct { Refresh bool `json:"refreshToken"` } _ = json.Unmarshal(params, &p) if _, err := os.Stat(filepath.Join(s.home, ".fake-revoked")); err == nil && p.Refresh { s.fail(id, "refresh_token_invalidated") return } a, ok := s.auth() if !ok { s.reply(id, map[string]any{"account": nil, "requiresOpenaiAuth": true}) return } s.reply(id, map[string]any{"account": map[string]any{"type": "chatgpt", "email": a.Email, "planType": a.Plan}, "requiresOpenaiAuth": true}) case "config/read": origins := map[string]any{} for k := range s.settings { origins[k] = map[string]any{"name": map[string]string{"type": "sessionFlags"}, "version": "fake-1"} } 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}) case "account/login/start": var p struct { Type string `json:"type"` } if json.Unmarshal(params, &p) != nil || p.Type != "chatgptDeviceCode" { s.fail(id, "unsupported login type") return } login := uuid() s.reply(id, map[string]any{"type": "chatgptDeviceCode", "loginId": login, "verificationUrl": "https://auth.openai.com/codex/device", "userCode": "FAKE-" + strings.ToUpper(login[:4])}) go s.deviceLogin(login) case "account/login/cancel": s.reply(id, map[string]any{"status": "canceled"}) case "account/rateLimits/read": s.reply(id, map[string]any{"rateLimits": s.limits(false)}) case "thread/start", "thread/resume": var p struct { ThreadID string `json:"threadId"` } _ = json.Unmarshal(params, &p) thread := uuid() if method == "thread/resume" { if s.rollout(p.ThreadID) == "" { s.fail(id, "no rollout found for thread id "+p.ThreadID) return } thread = p.ThreadID } s.mu.Lock() s.thread = thread s.mu.Unlock() model, _ := s.settings["model"].(string) 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"}}) s.total = tokens{} if method == "thread/resume" { // The resumed thread's last turn's usage, sent again. if last, turn, ok := s.loadTotal(thread); ok { s.total = last s.usage(thread, turn, last, last) } } case "turn/start": var p struct { ThreadID string `json:"threadId"` Input []struct { Type string `json:"type"` Text string `json:"text"` Path string `json:"path"` } `json:"input"` } s.mu.Lock() thread := s.thread s.mu.Unlock() if json.Unmarshal(params, &p) != nil || p.ThreadID != thread || len(p.Input) < 1 || p.Input[0].Type != "text" { s.fail(id, "bad turn") return } // localImage inputs: the app-server reads each path itself, inside // the namespace, as the pinned version does. seen := "" for _, in := range p.Input[1:] { data, err := os.ReadFile(in.Path) if in.Type != "localImage" || err != nil { s.fail(id, "bad image input") return } media := "image/png" switch { case len(data) > 2 && data[0] == 0xff && data[1] == 0xd8: media = "image/jpeg" case strings.HasPrefix(string(data), "GIF8"): media = "image/gif" case len(data) > 12 && string(data[8:12]) == "WEBP": media = "image/webp" } seen += " [localImage " + in.Path + " " + fakeclaude.DescribeImage(media, data) + "]" } p.Input[0].Text += "\x00" + seen turn := uuid() stop := make(chan struct{}) s.mu.Lock() s.turn, s.interrupt = turn, stop s.mu.Unlock() s.reply(id, map[string]any{"turn": map[string]any{"id": turn, "status": "inProgress", "items": []any{}}}) go s.runTurn(thread, turn, p.Input[0].Text, stop) case "turn/interrupt": s.mu.Lock() if s.interrupt != nil { close(s.interrupt) s.interrupt = nil } s.mu.Unlock() s.reply(id, map[string]any{}) default: s.fail(id, "method not faked: "+method) } } // deviceLogin waits for the person's approval (a file the test writes // beside the new home) and completes the sign-in. func (s *server) deviceLogin(login string) { path := filepath.Join(filepath.Dir(s.home), ".fake-device.json") for deadline := time.Now().Add(2 * time.Minute); time.Now().Before(deadline); time.Sleep(100 * time.Millisecond) { raw, err := os.ReadFile(path) if err != nil { continue } var v struct { Email, Plan string Refuse bool } if json.Unmarshal(raw, &v) != nil { continue } if v.Refuse { s.notify("account/login/completed", map[string]any{"loginId": login, "success": false, "error": "Enable device code authorization for Codex in ChatGPT Security Settings"}) return } if WriteAuth(s.home, v.Email, v.Plan) != nil { return } s.notify("account/login/completed", map[string]any{"loginId": login, "success": true, "error": nil}) s.notify("account/updated", map[string]any{"authMode": "chatgpt", "planType": v.Plan}) return } } func (s *server) limits(spent bool) map[string]any { used := 10 if spent { used = 100 } a, _ := s.auth() 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} } // rollout is the thread's rollout file, or "". func (s *server) rollout(thread string) string { matches, _ := filepath.Glob(filepath.Join(s.home, "sessions", "*", "*", "*", "rollout-*-"+thread+".jsonl")) if len(matches) == 1 { return matches[0] } return "" } func (s *server) record(thread, prompt, reply string) int { path := s.rollout(thread) if path == "" { now := time.Now().UTC() 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") _ = os.MkdirAll(filepath.Dir(path), 0700) } f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600) if err == nil { for _, line := range []map[string]string{{"type": "user", "text": prompt}, {"type": "agent", "text": reply}} { raw, _ := json.Marshal(line) f.Write(append(raw, '\n')) } f.Close() } raw, _ := os.ReadFile(path) return strings.Count(string(raw), `"type":"agent"`) } var ( toolWord = regexp.MustCompile(`tool:([a-z_]+)(?::([^\n]*))?`) limitWord = regexp.MustCompile(`\blimit:([^\s|]+@[^\s|]+[a-z])`) stepLimitWord = regexp.MustCompile(`\bsteplimit:([^\s|]+@[^\s|]+[a-z])`) reviewLimitWord = regexp.MustCompile(`\breviewlimit:([^\s|]+@[^\s|]+[a-z])`) sleepWord = regexp.MustCompile(`\bsleep:([0-9]+)`) pauseWord = regexp.MustCompile(`\bpause:([0-9]+)`) editWord = regexp.MustCompile(`edit:([^|\n]+)\|([^|\n]*)\|([^\n]*)`) reviewChanges = regexp.MustCompile(`review:changes:([^|\n]+)\|([0-9]+)\|([^\n;]*)`) ) func (s *server) runTurn(thread, turn, prompt string, stop chan struct{}) { prompt, seen, _ := strings.Cut(prompt, "\x00") newest := prompt if _, after, ok := strings.Cut(prompt, "Newest message:\n"); ok { newest = after } // Words a failed turn left unanswered ride before it, as context. if _, after, ok := strings.Cut(newest, "The person's newest message:\n"); ok { newest = after } done := func(status string, turnErr any) { s.notify("turn/completed", map[string]any{"threadId": thread, "turn": map[string]any{"id": turn, "status": status, "items": []any{}, "error": turnErr}}) } interrupted := func() bool { select { case <-stop: done("interrupted", nil) return true default: return false } } s.notify("turn/started", map[string]any{"threadId": thread, "turn": map[string]any{"id": turn, "status": "inProgress", "items": []any{}}}) a, _ := s.auth() engineering, review := strings.HasPrefix(prompt, "[Equipo: engineering]"), strings.HasPrefix(prompt, "[Equipo: review]") spent := func(word *regexp.Regexp, text string) bool { m := word.FindStringSubmatch(text) return m != nil && m[1] == a.Email } if spent(limitWord, newest) || engineering && spent(stepLimitWord, prompt) || review && spent(reviewLimitWord, prompt) { s.notify("account/rateLimits/updated", map[string]any{"rateLimits": s.limits(true)}) e := map[string]any{"message": "You've hit your usage limit.", "codexErrorInfo": "usageLimitExceeded", "additionalDetails": nil} s.notify("error", map[string]any{"threadId": thread, "turnId": turn, "willRetry": false, "error": e}) done("failed", e) return } if engineering || review { s.step(thread, turn, prompt, review, done) return } // A glance: one short line from the small model, no tools. earlier := false if path := s.rollout(thread); path != "" { raw, _ := os.ReadFile(path) earlier = strings.Contains(string(raw), `"type":"agent"`) } if line, pause, fail, ok := fakeclaude.Glance(prompt, earlier); ok { select { case <-stop: case <-time.After(pause): } if interrupted() { return } if fail { done("failed", map[string]any{"message": "stream disconnected", "codexErrorInfo": "other"}) return } msg := "msg_" + turn[:8] s.notify("item/completed", map[string]any{"threadId": thread, "turnId": turn, "item": map[string]any{"id": msg, "type": "agentMessage", "text": line}}) s.record(thread, prompt, line) done("completed", nil) return } reply := "" for i, m := range toolWord.FindAllStringSubmatch(newest, -1) { text, _ := s.mcpTool(thread, turn, fmt.Sprintf("mcp_%s_%d", turn[:8], i), m[1], fakeclaude.ToolInput(m[1], m[2])) reply += fmt.Sprintf(" [%s: %s]", m[1], text) if interrupted() { return } } turns := 0 if path := s.rollout(thread); path != "" { raw, _ := os.ReadFile(path) turns = strings.Count(string(raw), `"type":"agent"`) } context := "fresh" if turns > 0 { context = "resumed" } text := fmt.Sprintf("Hello from the fake Codex coordinator. Turn %d, %s thread.", turns+1, context) + reply + seen if strings.Contains(prompt, "Conversation so far") { text += " I see the earlier conversation." } if strings.Contains(prompt, "=== Your notebook") { text += " (notebook in context)" } pause := time.Duration(0) if m := sleepWord.FindStringSubmatch(newest); m != nil { ms, _ := strconv.Atoi(m[1]) pause = time.Duration(ms) * time.Millisecond } // Two requests' worth: half before the pause, the rest at the end. half := tokens{Input: len(prompt) / 8, Cached: len(prompt) / 16, Output: len(text) / 8, Reasoning: 3} full := tokens{Input: len(prompt) / 4, Cached: len(prompt) / 8, Output: len(text) / 4, Reasoning: 7} rest := tokens{full.Input - half.Input, full.Cached - half.Cached, full.Output - half.Output, full.Reasoning - half.Reasoning} // pause: waits before the first words, as the fake Claude does. if m := pauseWord.FindStringSubmatch(newest); m != nil { ms, _ := strconv.Atoi(m[1]) select { case <-stop: case <-time.After(time.Duration(ms) * time.Millisecond): } } msg := "msg_" + turn[:8] s.notify("item/started", map[string]any{"threadId": thread, "turnId": turn, "item": map[string]any{"id": msg, "type": "agentMessage", "text": ""}}) words := strings.SplitAfter(text, " ") third := max(len(words)/3, 1) for i := 0; i < len(words); i += third { chunk := strings.Join(words[i:min(i+third, len(words))], "") s.notify("item/agentMessage/delta", map[string]any{"threadId": thread, "turnId": turn, "itemId": msg, "delta": chunk}) if i == 0 { // The first request's usage, as the pinned app-server sends it // mid-turn: a cancelled turn has figures too. s.usage(thread, turn, s.total.plus(half), half) } if pause > 0 && i == 0 { select { case <-stop: case <-time.After(pause): } } if interrupted() { return } } if strings.Contains(newest, "fail") { done("failed", map[string]any{"message": "stream disconnected", "codexErrorInfo": "other"}) return } s.notify("item/completed", map[string]any{"threadId": thread, "turnId": turn, "item": map[string]any{"id": msg, "type": "agentMessage", "text": text}}) s.record(thread, prompt, text) // The second notice for the turn, with the thread's running total (as // the pinned app-server sends them), resent once. s.usage(thread, turn, s.total.plus(full), rest) s.usage(thread, turn, s.total.plus(full), rest) s.total = s.total.plus(full) s.saveTotal(thread, turn) s.notify("account/rateLimits/updated", map[string]any{"rateLimits": s.limits(false)}) done("completed", nil) } // mcpTool calls an Equipo tool as Codex does: the item starts, the // client is asked to approve the call, and only an accepted call reaches // the MCP server. func (s *server) mcpTool(thread, turn, item, name string, input map[string]any) (string, bool) { args, _ := json.Marshal(input) started := map[string]any{"id": item, "type": "mcpToolCall", "server": "equipo", "tool": name, "arguments": json.RawMessage(args), "status": "inProgress"} s.notify("item/started", map[string]any{"threadId": thread, "turnId": turn, "item": started}) 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{}}}) var v struct { Action string `json:"action"` } _ = json.Unmarshal(answer, &v) text, isError := "user declined the tool call", true if v.Action == "accept" { text, isError = s.callTool(name, input) } status := "completed" if isError { status = "failed" } 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}}) return text, isError } // step plays an Engineering or Review step in the working directory. func (s *server) step(thread, turn, prompt string, review bool, done func(string, any)) { prompt = fakeclaude.StepMarkerText(prompt) item := func(kind string, i int) string { return fmt.Sprintf("%s_%s_%d", kind, turn[:8], i) } var notes []string reply := "" if !review { edits := fakeclaude.DistinctStepMarkers(editWord, prompt) if len(edits) > 0 { cmd := map[string]any{"id": item("cmd", 0), "type": "commandExecution", "command": "cat " + edits[0][1], "cwd": "/workspace", "status": "inProgress"} s.notify("item/started", map[string]any{"threadId": thread, "turnId": turn, "item": cmd}) cmd["status"] = "completed" s.notify("item/completed", map[string]any{"threadId": thread, "turnId": turn, "item": cmd}) } for i, m := range edits { 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"} s.notify("item/started", map[string]any{"threadId": thread, "turnId": turn, "item": change}) raw, err := os.ReadFile(m[1]) if err == nil { err = os.WriteFile(m[1], []byte(strings.Replace(string(raw), m[2], m[3], 1)), 0644) } change["status"] = "completed" note := fmt.Sprintf("Replaced %q with %q in %s.", m[2], m[3], m[1]) if err != nil { change["status"], note = "failed", "Could not change "+m[1]+"." } s.notify("item/completed", map[string]any{"threadId": thread, "turnId": turn, "item": change}) notes = append(notes, note) } if text, isError := s.mcpTool(thread, turn, item("mcp", 0), "submit_candidate", map[string]any{}); isError { notes = append(notes, "[submit_candidate failed: "+text+"]") } reply = "Headline: Made the change the task asks for.\n\n" + strings.Join(notes, " ") if len(edits) == 0 { reply = "Headline: Nothing needed changing.\n\nI looked and changed nothing." } } else { verdict, headline, summary, findings := "approve", "Approved.", "The change does what the task asks.", []map[string]any{} for _, m := range fakeclaude.DistinctStepMarkers(reviewChanges, prompt) { line, _ := strconv.Atoi(m[2]) verdict, headline, summary = "changes_requested", "Asked for one more change.", "One thing needs changing." findings = append(findings, map[string]any{"path": m[1], "line": line, "text": m[3]}) } reply = summary + " (from Codex)" 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 { reply += " [submit_review failed: " + text + "]" } } msg := item("msg", 0) s.notify("item/started", map[string]any{"threadId": thread, "turnId": turn, "item": map[string]any{"id": msg, "type": "agentMessage", "text": ""}}) s.notify("item/agentMessage/delta", map[string]any{"threadId": thread, "turnId": turn, "itemId": msg, "delta": reply}) s.notify("item/completed", map[string]any{"threadId": thread, "turnId": turn, "item": map[string]any{"id": msg, "type": "agentMessage", "text": reply}}) used := tokens{Input: len(prompt) / 4, Cached: len(prompt) / 8, Output: len(reply) / 4, Reasoning: 5} s.total = s.total.plus(used) s.usage(thread, turn, s.total, used) s.notify("account/rateLimits/updated", map[string]any{"rateLimits": s.limits(false)}) done("completed", nil) } type tokens struct{ Input, Cached, Output, Reasoning int } func (a tokens) plus(b tokens) tokens { return tokens{a.Input + b.Input, a.Cached + b.Cached, a.Output + b.Output, a.Reasoning + b.Reasoning} } func (a tokens) breakdown() map[string]any { 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} } func (s *server) usage(thread, turn string, total, last tokens) { s.notify("thread/tokenUsage/updated", map[string]any{"threadId": thread, "turnId": turn, "tokenUsage": map[string]any{"last": last.breakdown(), "total": total.breakdown(), "modelContextWindow": 272000}}) } func (s *server) saveTotal(thread, turn string) { if path := s.rollout(thread); path != "" { if f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0600); err == nil { raw, _ := json.Marshal(map[string]any{"type": "usage", "turn": turn, "total": s.total}) f.Write(append(raw, '\n')) f.Close() } } } func (s *server) loadTotal(thread string) (tokens, string, bool) { raw, err := os.ReadFile(s.rollout(thread)) if err != nil { return tokens{}, "", false } var out tokens turn, ok := "", false for _, line := range strings.Split(string(raw), "\n") { var v struct { Type, Turn string Total tokens } if json.Unmarshal([]byte(line), &v) == nil && v.Type == "usage" { out, turn, ok = v.Total, v.Turn, true } } return out, turn, ok } // callTool calls an Equipo tool through the configured MCP server, // starting it on first use. func (s *server) callTool(name string, input map[string]any) (string, bool) { if s.mcpIn == nil { if msg := s.connectMCP(); msg != "" { return msg, true } } s.callID++ raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 100 + s.callID, "method": "tools/call", "params": map[string]any{"name": name, "arguments": input}}) if _, err := s.mcpIn.Write(append(raw, '\n')); err != nil { return "MCP write failed", true } line, err := s.mcpOut.ReadBytes('\n') var reply struct { Result struct { Content []struct { Text string `json:"text"` } `json:"content"` IsError bool `json:"isError"` } `json:"result"` Error *struct{} `json:"error"` } if err != nil || json.Unmarshal(line, &reply) != nil || reply.Error != nil || len(reply.Result.Content) == 0 { return "MCP call failed", true } return reply.Result.Content[0].Text, reply.Result.IsError } // connectMCP starts the equipo server from the session flags and checks // its tool list against enabled_tools, as Codex filters it. func (s *server) connectMCP() string { servers, _ := s.settings["mcp_servers"].(map[string]any) eq, _ := servers["equipo"].(map[string]any) command, _ := eq["command"].(string) var args []string if list, ok := eq["args"].([]any); ok { for _, a := range list { if v, ok := a.(string); ok { args = append(args, v) } } } if command == "" { return "no MCP server configured" } cmd := exec.Command(command, args...) in, _ := cmd.StdinPipe() out, _ := cmd.StdoutPipe() if cmd.Start() != nil { return "MCP server did not start" } r := bufio.NewReader(out) call := func(id int, method string, params any) json.RawMessage { raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": id, "method": method, "params": params}) if _, err := in.Write(append(raw, '\n')); err != nil { return nil } line, err := r.ReadBytes('\n') var reply struct { Result json.RawMessage `json:"result"` } if err != nil || json.Unmarshal(line, &reply) != nil { return nil } return reply.Result } 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 { return "MCP initialize failed" } note, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "method": "notifications/initialized"}) in.Write(append(note, '\n')) if call(2, "tools/list", map[string]any{}) == nil { return "MCP tools/list failed" } s.mcpIn, s.mcpOut = in, r return "" } // parseTOML reads one value of the inline TOML the launcher renders: // basic strings, integers, booleans, arrays and inline tables with // quoted keys. It returns the value and the unread rest. func parseTOML(v string) (any, string, error) { v = strings.TrimLeft(v, " ") switch { case v == "": return nil, v, fmt.Errorf("empty") case v[0] == '"': end := 1 for ; end < len(v); end++ { if v[end] == '\\' { end++ continue } if v[end] == '"' { break } } if end >= len(v) { return nil, v, fmt.Errorf("unterminated string") } s, err := strconv.Unquote(v[:end+1]) return s, v[end+1:], err case strings.HasPrefix(v, "true"): return true, v[4:], nil case strings.HasPrefix(v, "false"): return false, v[5:], nil case v[0] == '[': out := []any{} rest := strings.TrimLeft(v[1:], " ") for !strings.HasPrefix(rest, "]") { val, r, err := parseTOML(rest) if err != nil { return nil, v, err } out = append(out, val) rest = strings.TrimLeft(strings.TrimPrefix(strings.TrimLeft(r, " "), ","), " ") } return out, rest[1:], nil case v[0] == '{': out := map[string]any{} rest := strings.TrimLeft(v[1:], " ") for !strings.HasPrefix(rest, "}") { key, r, err := parseTOML(rest) k, ok := key.(string) if err != nil || !ok { return nil, v, fmt.Errorf("bad key") } r = strings.TrimLeft(r, " ") if !strings.HasPrefix(r, "=") { return nil, v, fmt.Errorf("missing =") } val, r2, err := parseTOML(r[1:]) if err != nil { return nil, v, err } out[k] = val rest = strings.TrimLeft(strings.TrimPrefix(strings.TrimLeft(r2, " "), ","), " ") } return out, rest[1:], nil } end := strings.IndexAny(v, ",]} ") if end < 0 { end = len(v) } n, err := strconv.ParseInt(v[:end], 10, 64) return n, v[end:], err }