// Package fakepi is a stand-in for the pinned Pi 1.5.2 in RPC mode // (`pi --mode rpc`), reproducing what Equipo relies on from its protocol // as recorded from the real Pi (internal/runner/provider/pi/testdata): // get_state; prompt with its response, then agent_start, turn_start, // message_start/update/end with usage {input (uncached), output, // cacheRead, cacheWrite, reasoning, totalTokens, cost}, tool_execution_start // and _end by toolCallId, turn_end, agent_end {willRetry} and // agent_settled; abort; extension_ui_request / extension_ui_response for // a call Equipo's extension does not allow; MCP tools named // mcp____ through the stdio server in // $PI_CODING_AGENT_DIR/mcp.json; and a session file under --session-dir, // resumed with --session-id. // // The fake plays Equipo's extension itself: a call to a tool not in // EQUIPO_PI_TOOLS, or a read outside EQUIPO_PI_CONFINE, is asked of the // client and blocked unless it answers confirmed. // // Test binaries call Main when they are started as "pi" (or the Pi CLI's // file name). Prompt words steer a run: "[Equipo: engineering]" applies // each "edit:||" and calls submit_candidate; // "[Equipo: review]" calls submit_review (approve, or changes_requested // for each "review:changes:||"); "[Equipo: question]" // answers; "read:" reads a file (asked when outside the // confinement); "keyrefused" fails as a 401, "modelgone" as a 404 (model_not_found), "ratelimited" as a 429 after // Pi's three retries, "nousage" ends with no message_end, "endnousage" ends properly with no usage, "sleep:" // pauses mid-reply, "flood:" replies with n bytes, "answeredby:" reports that model as the one // that answered, "thenby:" reports it for every request after the first, "unknown-event" emits a record of a type Equipo does // not know. package fakepi import ( "bufio" "crypto/rand" "encoding/json" "fmt" "io" "os" "os/exec" "path/filepath" "regexp" "strconv" "strings" "sync" "time" ) // Version is the pinned Pi the fake stands in for. const Version = "1.5.2" var ( editWord = regexp.MustCompile(`edit:([^|\n]+)\|([^|\n]*)\|([^\n]*)`) reviewChanges = regexp.MustCompile(`review:changes:([^|\n]+)\|([0-9]+)\|([^\n;]*)`) readWord = regexp.MustCompile(`read:([^\s"\\]+)`) sleepWord = regexp.MustCompile(`sleep:([0-9]+)`) answeredWord = regexp.MustCompile(`answeredby:([^\s"\\]+)`) thenWord = regexp.MustCompile(`thenby:([^\s"\\]+)`) floodWord = regexp.MustCompile(`flood:([0-9]+)`) ) type fake struct { out io.Writer outMu sync.Mutex provider, model string sessionDir, id string tools map[string]bool confine, cwd string messages int mcpIn io.Writer mcpOut *bufio.Reader callID int answers chan answer aborted chan struct{} abortOnce sync.Once running sync.Mutex // done closes when the newest run ends. done chan struct{} uiID int // answered is the model the provider says answered ("" the selected); // then, the model that answers every request after a run's first. answered, then string replies int } type answer struct { ID string Confirmed bool Cancelled bool } // Main runs the fake with argv after the program name. func Main(args []string, stdin io.Reader, stdout, stderr io.Writer) int { f := &fake{out: stdout, tools: map[string]bool{}, answers: make(chan answer, 8)} mode := "" for i := 0; i < len(args); i++ { next := func() string { if i+1 < len(args) { i++ return args[i] } return "" } switch args[i] { case "--version", "-v": fmt.Fprintln(stdout, Version) return 0 case "--mode": mode = next() case "--provider": f.provider = next() case "--model": f.model = next() case "--session-dir": f.sessionDir = next() case "--session-id": f.id = next() case "--tools", "-e", "--extension": next() } } if mode != "rpc" || f.model == "" || f.provider == "" || f.sessionDir == "" { fmt.Fprintln(stderr, "fakepi: needs --mode rpc, --provider, --model and --session-dir") return 2 } for _, t := range strings.Split(os.Getenv("EQUIPO_PI_TOOLS"), ",") { if t != "" { f.tools[t] = true } } f.confine = os.Getenv("EQUIPO_PI_CONFINE") f.cwd, _ = os.Getwd() if f.id == "" { f.id = uuid() } else { f.messages = f.countSession() } s := bufio.NewScanner(stdin) s.Buffer(make([]byte, 0, 64<<10), 16<<20) var runs sync.WaitGroup for s.Scan() { var cmd struct { ID, Type, Message string Confirmed, Cancelled bool } if json.Unmarshal(s.Bytes(), &cmd) != nil { f.send(map[string]any{"type": "response", "command": "parse", "success": false, "error": "Failed to parse command"}) continue } switch cmd.Type { case "get_state": f.respond(cmd.ID, "get_state", map[string]any{"model": map[string]any{"id": f.model, "provider": f.provider, "api": "openai-completions"}, "sessionId": f.id, "sessionFile": f.sessionFile(), "isStreaming": false, "messageCount": f.messages}) case "prompt": f.respond(cmd.ID, "prompt", map[string]any{"disposition": "started"}) f.aborted = make(chan struct{}) f.abortOnce = sync.Once{} runs.Add(1) done := make(chan struct{}) f.done = done go func(text string) { defer runs.Done(); defer close(done); f.run(text) }(cmd.Message) case "abort": if f.aborted != nil { f.abortOnce.Do(func() { close(f.aborted) }) } // Pi answers an abort once the run has ended. go func(id string, done chan struct{}) { if done != nil { <-done } f.respond(id, "abort", nil) }(cmd.ID, f.done) case "extension_ui_response": f.answers <- answer{ID: cmd.ID, Confirmed: cmd.Confirmed, Cancelled: cmd.Cancelled} case "get_session_stats": f.respond(cmd.ID, "get_session_stats", map[string]any{"sessionId": f.id, "userMessages": f.messages}) default: f.send(map[string]any{"id": cmd.ID, "type": "response", "command": cmd.Type, "success": false, "error": "unknown command"}) } } runs.Wait() return 0 } func (f *fake) send(v any) { raw, _ := json.Marshal(v) f.outMu.Lock() defer f.outMu.Unlock() f.out.Write(append(raw, '\n')) } func (f *fake) respond(id, command string, data any) { r := map[string]any{"type": "response", "command": command, "success": true} if id != "" { r["id"] = id } if data != nil { r["data"] = data } f.send(r) } func uuid() string { var b [16]byte rand.Read(b[:]) return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:]) } func (f *fake) sessionFile() string { matches, _ := filepath.Glob(filepath.Join(f.sessionDir, "*_"+f.id+".jsonl")) if len(matches) > 0 { return matches[0] } return filepath.Join(f.sessionDir, time.Now().UTC().Format("2006-01-02T15-04-05-000Z")+"_"+f.id+".jsonl") } func (f *fake) countSession() int { raw, err := os.ReadFile(f.sessionFile()) if err != nil { return 0 } return strings.Count(string(raw), `"role":"user"`) } func (f *fake) record(role, text string) { os.MkdirAll(f.sessionDir, 0700) file, err := os.OpenFile(f.sessionFile(), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600) if err != nil { return } defer file.Close() raw, _ := json.Marshal(map[string]any{"type": "message", "message": map[string]any{"role": role, "content": text}}) file.Write(append(raw, '\n')) } func (f *fake) assistant(stop string, usage bool, content []any, errorMessage string) map[string]any { model := f.model if f.answered != "" { model = f.answered } if f.then != "" && f.replies > 0 { model = f.then } f.replies++ m := map[string]any{"role": "assistant", "content": content, "api": "openai-completions", "provider": f.provider, "model": model, "stopReason": stop} u := map[string]any{"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0, "reasoning": 0, "totalTokens": 0, "cost": map[string]any{"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0, "total": 0, "totalFromProvider": false}} if usage { u["input"], u["output"], u["cacheRead"], u["totalTokens"] = 100, 10, 20, 130 } m["usage"] = u if errorMessage != "" { m["errorMessage"] = errorMessage } return m } func (f *fake) stopped() bool { select { case <-f.aborted: return true default: return false } } // run plays one prompt to its end. func (f *fake) run(prompt string) { f.running.Lock() defer f.running.Unlock() if m := answeredWord.FindStringSubmatch(prompt); m != nil { f.answered = m[1] } if m := thenWord.FindStringSubmatch(prompt); m != nil { f.then, f.replies = m[1], 0 } f.messages++ f.record("user", prompt) f.send(map[string]any{"type": "agent_start"}) f.send(map[string]any{"type": "turn_start"}) f.send(map[string]any{"type": "message_start", "message": map[string]any{"role": "user", "content": []any{map[string]string{"type": "text", "text": prompt}}}}) f.send(map[string]any{"type": "message_end", "message": map[string]any{"role": "user", "content": []any{map[string]string{"type": "text", "text": prompt}}}}) end := func(stop, errorMessage string, retry bool) { msg := f.assistant(stop, false, []any{}, errorMessage) f.send(map[string]any{"type": "message_start", "message": msg}) f.send(map[string]any{"type": "message_end", "message": msg}) f.send(map[string]any{"type": "turn_end", "message": msg, "toolResults": []any{}}) f.send(map[string]any{"type": "agent_end", "messages": []any{msg}, "willRetry": retry}) } switch { case strings.Contains(prompt, "keyrefused"): end("error", `401: {"message":"Invalid API key"}`, false) f.send(map[string]any{"type": "agent_settled", "aborted": false}) return case strings.Contains(prompt, "modelgone"): end("error", `404: {"error":{"code":"model_not_found"}}`, false) f.send(map[string]any{"type": "agent_settled", "aborted": false}) return case strings.Contains(prompt, "ratelimited"): for i := 1; i <= 3; i++ { end("error", `429: {"message":"Too many requests"}`, true) f.send(map[string]any{"type": "auto_retry_start", "attempt": i, "maxAttempts": 3, "delayMs": 1, "errorMessage": "429"}) } end("error", `429: {"message":"Too many requests"}`, false) f.send(map[string]any{"type": "auto_retry_end", "success": false, "attempt": 3, "finalError": "429"}) f.send(map[string]any{"type": "agent_settled", "aborted": false}) return case strings.Contains(prompt, "endnousage"): // The run ends properly, with no assistant message and so no usage. f.send(map[string]any{"type": "turn_end", "toolResults": []any{}}) f.send(map[string]any{"type": "agent_end", "messages": []any{}, "willRetry": false}) f.send(map[string]any{"type": "agent_settled", "aborted": false}) return case strings.Contains(prompt, "nousage"): // The process ends mid-run, with no message_end and no agent_end. os.Exit(3) } if strings.Contains(prompt, "unknown-event") { f.send(map[string]any{"type": "fake_unknown_event", "detail": "not for Equipo"}) } var notes []string call := 0 tool := func(name string, args map[string]any) (string, bool) { call++ id := fmt.Sprintf("call_%d", call) rawArgs, _ := json.Marshal(args) msg := f.assistant("toolUse", true, []any{map[string]any{"type": "toolCall", "id": id, "name": name, "arguments": args}}, "") f.send(map[string]any{"type": "message_start", "message": f.assistant("toolUse", false, []any{}, "")}) f.send(map[string]any{"type": "message_end", "message": msg}) f.send(map[string]any{"type": "tool_execution_start", "toolCallId": id, "toolName": name, "args": json.RawMessage(rawArgs)}) text, isError := f.execute(id, name, args) f.send(map[string]any{"type": "tool_execution_end", "toolCallId": id, "toolName": name, "result": map[string]any{"content": []any{map[string]string{"type": "text", "text": text}}}, "isError": isError}) f.send(map[string]any{"type": "turn_end", "message": msg, "toolResults": []any{}}) f.send(map[string]any{"type": "turn_start"}) return text, isError } for _, m := range readWord.FindAllStringSubmatch(prompt, -1) { text, isError := tool("read", map[string]any{"path": m[1]}) if isError { notes = append(notes, "[read "+m[1]+" refused: "+text+"]") } else { notes = append(notes, "[read "+m[1]+": "+strings.TrimSpace(text)+"]") } if f.stopped() { f.aborted2() return } } reply := "ok" switch { case strings.HasPrefix(prompt, "[Equipo: engineering]"): for _, m := range editWord.FindAllStringSubmatch(prompt, -1) { path := m[1] raw, err := os.ReadFile(path) if err == nil { _, isError := tool("edit", map[string]any{"path": path, "oldText": m[2], "newText": m[3]}) if !isError { err = os.WriteFile(path, []byte(strings.Replace(string(raw), m[2], m[3], 1)), 0644) } } if err == nil { notes = append(notes, fmt.Sprintf("Replaced %q with %q in %s.", m[2], m[3], path)) } } if text, isError := tool("mcp__equipo__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, " ") case strings.HasPrefix(prompt, "[Equipo: Copy]"): _, data, _ := strings.Cut(prompt, "\n") var input struct { Strings []struct { Key string `json:"key"` Text string `json:"text"` } `json:"strings"` } if json.Unmarshal([]byte(data), &input) != nil { reply = "Invalid copy fixture" break } words := []map[string]any{} for _, s := range input.Strings { text := s.Text if text == "New words" { text = "Save changes" } if strings.Contains(prompt, "copy-lone-percent") { text += "%" } words = append(words, map[string]any{"key": s.Key, "text": text, "action": "accept", "flag": "Check wording in context."}) } text, bad := tool("mcp__equipo__submit_review", map[string]any{"version": 1, "strings": words}) reply = "Copy reviewed. " + text if bad { reply += " refused" } case strings.HasPrefix(prompt, "[Equipo: review]"): verdict, headline, summary, findings := "approve", "Approved.", "The change does what the task asks.", []map[string]any{} for _, m := range reviewChanges.FindAllStringSubmatch(prompt, -1) { 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 Pi)" + strings.Join(notes, " ") if text, isError := tool("mcp__equipo__submit_review", map[string]any{"verdict": verdict, "headline": headline, "summary": summary + " (from Pi)", "findings": findings}); isError { reply += " [submit_review failed: " + text + "]" } case strings.HasPrefix(prompt, "[Equipo: question]"): reply = fmt.Sprintf("Answered from my session (message %d).", f.messages) + strings.Join(notes, " ") default: reply = "ok " + strings.Join(notes, " ") } if strings.Contains(prompt, "echokey") { // What a step that reads its environment could say: the key, in // the reply (split across deltas) and in the verdict it records. key := os.Getenv("TENSORX_API_KEY") reply = "the key is " + key + " and that is all" if strings.HasPrefix(prompt, "[Equipo: review]") { tool("mcp__equipo__submit_review", map[string]any{"verdict": "approve", "headline": "Key " + key, "summary": "I read " + key, "findings": []map[string]any{}}) } } if m := floodWord.FindStringSubmatch(prompt); m != nil { n, _ := strconv.Atoi(m[1]) reply = strings.Repeat("f", n) } if m := sleepWord.FindStringSubmatch(prompt); m != nil { ms, _ := strconv.Atoi(m[1]) select { case <-time.After(time.Duration(ms) * time.Millisecond): case <-f.aborted: } } if f.stopped() { f.aborted2() return } half := len(reply) / 2 start := f.assistant("stop", false, []any{}, "") f.send(map[string]any{"type": "message_start", "message": start}) for _, part := range []string{reply[:half], reply[half:]} { f.send(map[string]any{"type": "message_update", "usage": start["usage"], "assistantMessageEvent": map[string]any{"type": "text_delta", "contentIndex": 0, "delta": part}}) } msg := f.assistant("stop", true, []any{map[string]string{"type": "text", "text": reply}}, "") if strings.HasPrefix(prompt, "[Equipo: Copy]") { if strings.Contains(prompt, "copy-usage-overrun") { msg["usage"].(map[string]any)["input"] = 50000 } if strings.Contains(prompt, "copy-usage-missing") { delete(msg, "usage") } } f.send(map[string]any{"type": "message_end", "message": msg}) f.record("assistant", reply) f.send(map[string]any{"type": "turn_end", "message": msg, "toolResults": []any{}}) f.send(map[string]any{"type": "agent_end", "messages": []any{msg}, "willRetry": false}) f.send(map[string]any{"type": "agent_settled", "aborted": false}) } func (f *fake) aborted2() { msg := f.assistant("aborted", false, []any{}, "This operation was aborted") f.send(map[string]any{"type": "message_start", "message": msg}) f.send(map[string]any{"type": "message_end", "message": msg}) f.send(map[string]any{"type": "turn_end", "message": msg, "toolResults": []any{}}) f.send(map[string]any{"type": "agent_end", "messages": []any{msg}, "willRetry": false}) f.send(map[string]any{"type": "agent_settled", "aborted": true}) } // allowed plays Equipo's extension: a tool it pins, and for a read-only // role a read inside the confinement. func (f *fake) allowed(name string, args map[string]any) bool { if !f.tools[name] { return false } if f.confine == "" || name != "read" && name != "grep" && name != "find" && name != "ls" { return true } p, _ := args["path"].(string) if p == "" { p = "." } if !filepath.IsAbs(p) { p = filepath.Join(f.cwd, p) } if real, err := filepath.EvalSymlinks(p); err == nil { p = real } p = filepath.Clean(p) return p == f.confine || strings.HasPrefix(p, f.confine+"/") } // execute runs one tool call: asked of the client first when the // extension would not allow it. func (f *fake) execute(id, name string, args map[string]any) (string, bool) { if !f.allowed(name, args) { f.uiID++ uid := fmt.Sprintf("ui-%d", f.uiID) message, _ := json.Marshal(map[string]any{"id": id, "tool": name, "args": args}) f.send(map[string]any{"type": "extension_ui_request", "id": uid, "method": "confirm", "title": "equipo:tool_call", "message": string(message)}) var a answer select { case a = <-f.answers: case <-f.aborted: select { case a = <-f.answers: case <-time.After(5 * time.Second): } } if a.ID != uid || !a.Confirmed { return "Equipo did not allow this call.", true } } if server, tool, ok := strings.Cut(strings.TrimPrefix(name, "mcp__"), "__"); ok && strings.HasPrefix(name, "mcp__") { if server != "equipo" { return "unknown server", true } return f.callTool(tool, args) } switch name { case "read": p, _ := args["path"].(string) raw, err := os.ReadFile(p) if err != nil { return err.Error(), true } return string(raw), false case "edit": return "Edited.", false } return "unknown tool", true } func (f *fake) callTool(name string, input map[string]any) (string, bool) { if f.mcpIn == nil { if msg := f.connectMCP(); msg != "" { return msg, true } } f.callID++ raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 100 + f.callID, "method": "tools/call", "params": map[string]any{"name": name, "arguments": input}}) if _, err := f.mcpIn.Write(append(raw, '\n')); err != nil { return "MCP write failed", true } line, err := f.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 mcp.json in Pi's config // directory. func (f *fake) connectMCP() string { raw, err := os.ReadFile(filepath.Join(os.Getenv("PI_CODING_AGENT_DIR"), "mcp.json")) var cfg struct { MCPServers map[string]struct { Command string Args []string } `json:"mcpServers"` } if err != nil || json.Unmarshal(raw, &cfg) != nil || cfg.MCPServers["equipo"].Command == "" { return "no MCP server configured" } eq := cfg.MCPServers["equipo"] cmd := exec.Command(eq.Command, eq.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-pi", "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" } f.mcpIn, f.mcpOut = in, r return "" }