| 1 | // Package fakepi is a stand-in for the pinned Pi 1.5.2 in RPC mode |
| 2 | // (`pi --mode rpc`), reproducing what Equipo relies on from its protocol |
| 3 | // as recorded from the real Pi (internal/runner/provider/pi/testdata): |
| 4 | // get_state; prompt with its response, then agent_start, turn_start, |
| 5 | // message_start/update/end with usage {input (uncached), output, |
| 6 | // cacheRead, cacheWrite, reasoning, totalTokens, cost}, tool_execution_start |
| 7 | // and _end by toolCallId, turn_end, agent_end {willRetry} and |
| 8 | // agent_settled; abort; extension_ui_request / extension_ui_response for |
| 9 | // a call Equipo's extension does not allow; MCP tools named |
| 10 | // mcp__<server>__<tool> through the stdio server in |
| 11 | // $PI_CODING_AGENT_DIR/mcp.json; and a session file under --session-dir, |
| 12 | // resumed with --session-id. |
| 13 | // |
| 14 | // The fake plays Equipo's extension itself: a call to a tool not in |
| 15 | // EQUIPO_PI_TOOLS, or a read outside EQUIPO_PI_CONFINE, is asked of the |
| 16 | // client and blocked unless it answers confirmed. |
| 17 | // |
| 18 | // Test binaries call Main when they are started as "pi" (or the Pi CLI's |
| 19 | // file name). Prompt words steer a run: "[Equipo: engineering]" applies |
| 20 | // each "edit:<path>|<old>|<new>" and calls submit_candidate; |
| 21 | // "[Equipo: review]" calls submit_review (approve, or changes_requested |
| 22 | // for each "review:changes:<path>|<line>|<text>"); "[Equipo: question]" |
| 23 | // answers; "read:<path>" reads a file (asked when outside the |
| 24 | // confinement); "keyrefused" fails as a 401, "modelgone" as a 404 (model_not_found), "ratelimited" as a 429 after |
| 25 | // Pi's three retries, "nousage" ends with no message_end, "endnousage" ends properly with no usage, "sleep:<ms>" |
| 26 | // pauses mid-reply, "flood:<n>" replies with n bytes, "answeredby:<model>" reports that model as the one |
| 27 | // that answered, "thenby:<model>" reports it for every request after the first, "unknown-event" emits a record of a type Equipo does |
| 28 | // not know. |
| 29 | package fakepi |
| 30 | |
| 31 | import ( |
| 32 | "bufio" |
| 33 | "crypto/rand" |
| 34 | "encoding/json" |
| 35 | "fmt" |
| 36 | "io" |
| 37 | "os" |
| 38 | "os/exec" |
| 39 | "path/filepath" |
| 40 | "regexp" |
| 41 | "strconv" |
| 42 | "strings" |
| 43 | "sync" |
| 44 | "time" |
| 45 | ) |
| 46 | |
| 47 | // Version is the pinned Pi the fake stands in for. |
| 48 | const Version = "1.5.2" |
| 49 | |
| 50 | var ( |
| 51 | editWord = regexp.MustCompile(`edit:([^|\n]+)\|([^|\n]*)\|([^\n]*)`) |
| 52 | reviewChanges = regexp.MustCompile(`review:changes:([^|\n]+)\|([0-9]+)\|([^\n;]*)`) |
| 53 | readWord = regexp.MustCompile(`read:([^\s"\\]+)`) |
| 54 | sleepWord = regexp.MustCompile(`sleep:([0-9]+)`) |
| 55 | answeredWord = regexp.MustCompile(`answeredby:([^\s"\\]+)`) |
| 56 | thenWord = regexp.MustCompile(`thenby:([^\s"\\]+)`) |
| 57 | floodWord = regexp.MustCompile(`flood:([0-9]+)`) |
| 58 | ) |
| 59 | |
| 60 | type fake struct { |
| 61 | out io.Writer |
| 62 | outMu sync.Mutex |
| 63 | provider, model string |
| 64 | sessionDir, id string |
| 65 | tools map[string]bool |
| 66 | confine, cwd string |
| 67 | messages int |
| 68 | mcpIn io.Writer |
| 69 | mcpOut *bufio.Reader |
| 70 | callID int |
| 71 | answers chan answer |
| 72 | aborted chan struct{} |
| 73 | abortOnce sync.Once |
| 74 | running sync.Mutex |
| 75 | // done closes when the newest run ends. |
| 76 | done chan struct{} |
| 77 | uiID int |
| 78 | // answered is the model the provider says answered ("" the selected); |
| 79 | // then, the model that answers every request after a run's first. |
| 80 | answered, then string |
| 81 | replies int |
| 82 | } |
| 83 | |
| 84 | type answer struct { |
| 85 | ID string |
| 86 | Confirmed bool |
| 87 | Cancelled bool |
| 88 | } |
| 89 | |
| 90 | // Main runs the fake with argv after the program name. |
| 91 | func Main(args []string, stdin io.Reader, stdout, stderr io.Writer) int { |
| 92 | f := &fake{out: stdout, tools: map[string]bool{}, answers: make(chan answer, 8)} |
| 93 | mode := "" |
| 94 | for i := 0; i < len(args); i++ { |
| 95 | next := func() string { |
| 96 | if i+1 < len(args) { |
| 97 | i++ |
| 98 | return args[i] |
| 99 | } |
| 100 | return "" |
| 101 | } |
| 102 | switch args[i] { |
| 103 | case "--version", "-v": |
| 104 | fmt.Fprintln(stdout, Version) |
| 105 | return 0 |
| 106 | case "--mode": |
| 107 | mode = next() |
| 108 | case "--provider": |
| 109 | f.provider = next() |
| 110 | case "--model": |
| 111 | f.model = next() |
| 112 | case "--session-dir": |
| 113 | f.sessionDir = next() |
| 114 | case "--session-id": |
| 115 | f.id = next() |
| 116 | case "--tools", "-e", "--extension": |
| 117 | next() |
| 118 | } |
| 119 | } |
| 120 | if mode != "rpc" || f.model == "" || f.provider == "" || f.sessionDir == "" { |
| 121 | fmt.Fprintln(stderr, "fakepi: needs --mode rpc, --provider, --model and --session-dir") |
| 122 | return 2 |
| 123 | } |
| 124 | for _, t := range strings.Split(os.Getenv("EQUIPO_PI_TOOLS"), ",") { |
| 125 | if t != "" { |
| 126 | f.tools[t] = true |
| 127 | } |
| 128 | } |
| 129 | f.confine = os.Getenv("EQUIPO_PI_CONFINE") |
| 130 | f.cwd, _ = os.Getwd() |
| 131 | if f.id == "" { |
| 132 | f.id = uuid() |
| 133 | } else { |
| 134 | f.messages = f.countSession() |
| 135 | } |
| 136 | s := bufio.NewScanner(stdin) |
| 137 | s.Buffer(make([]byte, 0, 64<<10), 16<<20) |
| 138 | var runs sync.WaitGroup |
| 139 | for s.Scan() { |
| 140 | var cmd struct { |
| 141 | ID, Type, Message string |
| 142 | Confirmed, Cancelled bool |
| 143 | } |
| 144 | if json.Unmarshal(s.Bytes(), &cmd) != nil { |
| 145 | f.send(map[string]any{"type": "response", "command": "parse", "success": false, "error": "Failed to parse command"}) |
| 146 | continue |
| 147 | } |
| 148 | switch cmd.Type { |
| 149 | case "get_state": |
| 150 | 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}) |
| 151 | case "prompt": |
| 152 | f.respond(cmd.ID, "prompt", map[string]any{"disposition": "started"}) |
| 153 | f.aborted = make(chan struct{}) |
| 154 | f.abortOnce = sync.Once{} |
| 155 | runs.Add(1) |
| 156 | done := make(chan struct{}) |
| 157 | f.done = done |
| 158 | go func(text string) { defer runs.Done(); defer close(done); f.run(text) }(cmd.Message) |
| 159 | case "abort": |
| 160 | if f.aborted != nil { |
| 161 | f.abortOnce.Do(func() { close(f.aborted) }) |
| 162 | } |
| 163 | // Pi answers an abort once the run has ended. |
| 164 | go func(id string, done chan struct{}) { |
| 165 | if done != nil { |
| 166 | <-done |
| 167 | } |
| 168 | f.respond(id, "abort", nil) |
| 169 | }(cmd.ID, f.done) |
| 170 | case "extension_ui_response": |
| 171 | f.answers <- answer{ID: cmd.ID, Confirmed: cmd.Confirmed, Cancelled: cmd.Cancelled} |
| 172 | case "get_session_stats": |
| 173 | f.respond(cmd.ID, "get_session_stats", map[string]any{"sessionId": f.id, "userMessages": f.messages}) |
| 174 | default: |
| 175 | f.send(map[string]any{"id": cmd.ID, "type": "response", "command": cmd.Type, "success": false, "error": "unknown command"}) |
| 176 | } |
| 177 | } |
| 178 | runs.Wait() |
| 179 | return 0 |
| 180 | } |
| 181 | |
| 182 | func (f *fake) send(v any) { |
| 183 | raw, _ := json.Marshal(v) |
| 184 | f.outMu.Lock() |
| 185 | defer f.outMu.Unlock() |
| 186 | f.out.Write(append(raw, '\n')) |
| 187 | } |
| 188 | |
| 189 | func (f *fake) respond(id, command string, data any) { |
| 190 | r := map[string]any{"type": "response", "command": command, "success": true} |
| 191 | if id != "" { |
| 192 | r["id"] = id |
| 193 | } |
| 194 | if data != nil { |
| 195 | r["data"] = data |
| 196 | } |
| 197 | f.send(r) |
| 198 | } |
| 199 | |
| 200 | func uuid() string { |
| 201 | var b [16]byte |
| 202 | rand.Read(b[:]) |
| 203 | return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:]) |
| 204 | } |
| 205 | |
| 206 | func (f *fake) sessionFile() string { |
| 207 | matches, _ := filepath.Glob(filepath.Join(f.sessionDir, "*_"+f.id+".jsonl")) |
| 208 | if len(matches) > 0 { |
| 209 | return matches[0] |
| 210 | } |
| 211 | return filepath.Join(f.sessionDir, time.Now().UTC().Format("2006-01-02T15-04-05-000Z")+"_"+f.id+".jsonl") |
| 212 | } |
| 213 | |
| 214 | func (f *fake) countSession() int { |
| 215 | raw, err := os.ReadFile(f.sessionFile()) |
| 216 | if err != nil { |
| 217 | return 0 |
| 218 | } |
| 219 | return strings.Count(string(raw), `"role":"user"`) |
| 220 | } |
| 221 | |
| 222 | func (f *fake) record(role, text string) { |
| 223 | os.MkdirAll(f.sessionDir, 0700) |
| 224 | file, err := os.OpenFile(f.sessionFile(), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600) |
| 225 | if err != nil { |
| 226 | return |
| 227 | } |
| 228 | defer file.Close() |
| 229 | raw, _ := json.Marshal(map[string]any{"type": "message", "message": map[string]any{"role": role, "content": text}}) |
| 230 | file.Write(append(raw, '\n')) |
| 231 | } |
| 232 | |
| 233 | func (f *fake) assistant(stop string, usage bool, content []any, errorMessage string) map[string]any { |
| 234 | model := f.model |
| 235 | if f.answered != "" { |
| 236 | model = f.answered |
| 237 | } |
| 238 | if f.then != "" && f.replies > 0 { |
| 239 | model = f.then |
| 240 | } |
| 241 | f.replies++ |
| 242 | m := map[string]any{"role": "assistant", "content": content, "api": "openai-completions", "provider": f.provider, "model": model, "stopReason": stop} |
| 243 | 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}} |
| 244 | if usage { |
| 245 | u["input"], u["output"], u["cacheRead"], u["totalTokens"] = 100, 10, 20, 130 |
| 246 | } |
| 247 | m["usage"] = u |
| 248 | if errorMessage != "" { |
| 249 | m["errorMessage"] = errorMessage |
| 250 | } |
| 251 | return m |
| 252 | } |
| 253 | |
| 254 | func (f *fake) stopped() bool { |
| 255 | select { |
| 256 | case <-f.aborted: |
| 257 | return true |
| 258 | default: |
| 259 | return false |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | // run plays one prompt to its end. |
| 264 | func (f *fake) run(prompt string) { |
| 265 | f.running.Lock() |
| 266 | defer f.running.Unlock() |
| 267 | if m := answeredWord.FindStringSubmatch(prompt); m != nil { |
| 268 | f.answered = m[1] |
| 269 | } |
| 270 | if m := thenWord.FindStringSubmatch(prompt); m != nil { |
| 271 | f.then, f.replies = m[1], 0 |
| 272 | } |
| 273 | f.messages++ |
| 274 | f.record("user", prompt) |
| 275 | f.send(map[string]any{"type": "agent_start"}) |
| 276 | f.send(map[string]any{"type": "turn_start"}) |
| 277 | f.send(map[string]any{"type": "message_start", "message": map[string]any{"role": "user", "content": []any{map[string]string{"type": "text", "text": prompt}}}}) |
| 278 | f.send(map[string]any{"type": "message_end", "message": map[string]any{"role": "user", "content": []any{map[string]string{"type": "text", "text": prompt}}}}) |
| 279 | end := func(stop, errorMessage string, retry bool) { |
| 280 | msg := f.assistant(stop, false, []any{}, errorMessage) |
| 281 | f.send(map[string]any{"type": "message_start", "message": msg}) |
| 282 | f.send(map[string]any{"type": "message_end", "message": msg}) |
| 283 | f.send(map[string]any{"type": "turn_end", "message": msg, "toolResults": []any{}}) |
| 284 | f.send(map[string]any{"type": "agent_end", "messages": []any{msg}, "willRetry": retry}) |
| 285 | } |
| 286 | switch { |
| 287 | case strings.Contains(prompt, "keyrefused"): |
| 288 | end("error", `401: {"message":"Invalid API key"}`, false) |
| 289 | f.send(map[string]any{"type": "agent_settled", "aborted": false}) |
| 290 | return |
| 291 | case strings.Contains(prompt, "modelgone"): |
| 292 | end("error", `404: {"error":{"code":"model_not_found"}}`, false) |
| 293 | f.send(map[string]any{"type": "agent_settled", "aborted": false}) |
| 294 | return |
| 295 | case strings.Contains(prompt, "ratelimited"): |
| 296 | for i := 1; i <= 3; i++ { |
| 297 | end("error", `429: {"message":"Too many requests"}`, true) |
| 298 | f.send(map[string]any{"type": "auto_retry_start", "attempt": i, "maxAttempts": 3, "delayMs": 1, "errorMessage": "429"}) |
| 299 | } |
| 300 | end("error", `429: {"message":"Too many requests"}`, false) |
| 301 | f.send(map[string]any{"type": "auto_retry_end", "success": false, "attempt": 3, "finalError": "429"}) |
| 302 | f.send(map[string]any{"type": "agent_settled", "aborted": false}) |
| 303 | return |
| 304 | case strings.Contains(prompt, "endnousage"): |
| 305 | // The run ends properly, with no assistant message and so no usage. |
| 306 | f.send(map[string]any{"type": "turn_end", "toolResults": []any{}}) |
| 307 | f.send(map[string]any{"type": "agent_end", "messages": []any{}, "willRetry": false}) |
| 308 | f.send(map[string]any{"type": "agent_settled", "aborted": false}) |
| 309 | return |
| 310 | case strings.Contains(prompt, "nousage"): |
| 311 | // The process ends mid-run, with no message_end and no agent_end. |
| 312 | os.Exit(3) |
| 313 | } |
| 314 | if strings.Contains(prompt, "unknown-event") { |
| 315 | f.send(map[string]any{"type": "fake_unknown_event", "detail": "not for Equipo"}) |
| 316 | } |
| 317 | var notes []string |
| 318 | call := 0 |
| 319 | tool := func(name string, args map[string]any) (string, bool) { |
| 320 | call++ |
| 321 | id := fmt.Sprintf("call_%d", call) |
| 322 | rawArgs, _ := json.Marshal(args) |
| 323 | msg := f.assistant("toolUse", true, []any{map[string]any{"type": "toolCall", "id": id, "name": name, "arguments": args}}, "") |
| 324 | f.send(map[string]any{"type": "message_start", "message": f.assistant("toolUse", false, []any{}, "")}) |
| 325 | f.send(map[string]any{"type": "message_end", "message": msg}) |
| 326 | f.send(map[string]any{"type": "tool_execution_start", "toolCallId": id, "toolName": name, "args": json.RawMessage(rawArgs)}) |
| 327 | text, isError := f.execute(id, name, args) |
| 328 | 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}) |
| 329 | f.send(map[string]any{"type": "turn_end", "message": msg, "toolResults": []any{}}) |
| 330 | f.send(map[string]any{"type": "turn_start"}) |
| 331 | return text, isError |
| 332 | } |
| 333 | for _, m := range readWord.FindAllStringSubmatch(prompt, -1) { |
| 334 | text, isError := tool("read", map[string]any{"path": m[1]}) |
| 335 | if isError { |
| 336 | notes = append(notes, "[read "+m[1]+" refused: "+text+"]") |
| 337 | } else { |
| 338 | notes = append(notes, "[read "+m[1]+": "+strings.TrimSpace(text)+"]") |
| 339 | } |
| 340 | if f.stopped() { |
| 341 | f.aborted2() |
| 342 | return |
| 343 | } |
| 344 | } |
| 345 | reply := "ok" |
| 346 | switch { |
| 347 | case strings.HasPrefix(prompt, "[Equipo: engineering]"): |
| 348 | for _, m := range editWord.FindAllStringSubmatch(prompt, -1) { |
| 349 | path := m[1] |
| 350 | raw, err := os.ReadFile(path) |
| 351 | if err == nil { |
| 352 | _, isError := tool("edit", map[string]any{"path": path, "oldText": m[2], "newText": m[3]}) |
| 353 | if !isError { |
| 354 | err = os.WriteFile(path, []byte(strings.Replace(string(raw), m[2], m[3], 1)), 0644) |
| 355 | } |
| 356 | } |
| 357 | if err == nil { |
| 358 | notes = append(notes, fmt.Sprintf("Replaced %q with %q in %s.", m[2], m[3], path)) |
| 359 | } |
| 360 | } |
| 361 | if text, isError := tool("mcp__equipo__submit_candidate", map[string]any{}); isError { |
| 362 | notes = append(notes, "[submit_candidate failed: "+text+"]") |
| 363 | } |
| 364 | reply = "Headline: Made the change the task asks for.\n\n" + strings.Join(notes, " ") |
| 365 | case strings.HasPrefix(prompt, "[Equipo: Copy]"): |
| 366 | _, data, _ := strings.Cut(prompt, "\n") |
| 367 | var input struct { |
| 368 | Strings []struct { |
| 369 | Key string `json:"key"` |
| 370 | Text string `json:"text"` |
| 371 | } `json:"strings"` |
| 372 | } |
| 373 | if json.Unmarshal([]byte(data), &input) != nil { |
| 374 | reply = "Invalid copy fixture" |
| 375 | break |
| 376 | } |
| 377 | words := []map[string]any{} |
| 378 | for _, s := range input.Strings { |
| 379 | text := s.Text |
| 380 | if text == "New words" { |
| 381 | text = "Save changes" |
| 382 | } |
| 383 | if strings.Contains(prompt, "copy-lone-percent") { |
| 384 | text += "%" |
| 385 | } |
| 386 | words = append(words, map[string]any{"key": s.Key, "text": text, "action": "accept", "flag": "Check wording in context."}) |
| 387 | } |
| 388 | text, bad := tool("mcp__equipo__submit_review", map[string]any{"version": 1, "strings": words}) |
| 389 | reply = "Copy reviewed. " + text |
| 390 | if bad { |
| 391 | reply += " refused" |
| 392 | } |
| 393 | case strings.HasPrefix(prompt, "[Equipo: review]"): |
| 394 | verdict, headline, summary, findings := "approve", "Approved.", "The change does what the task asks.", []map[string]any{} |
| 395 | for _, m := range reviewChanges.FindAllStringSubmatch(prompt, -1) { |
| 396 | line, _ := strconv.Atoi(m[2]) |
| 397 | verdict, headline, summary = "changes_requested", "Asked for one more change.", "One thing needs changing." |
| 398 | findings = append(findings, map[string]any{"path": m[1], "line": line, "text": m[3]}) |
| 399 | } |
| 400 | reply = summary + " (from Pi)" + strings.Join(notes, " ") |
| 401 | if text, isError := tool("mcp__equipo__submit_review", map[string]any{"verdict": verdict, "headline": headline, "summary": summary + " (from Pi)", "findings": findings}); isError { |
| 402 | reply += " [submit_review failed: " + text + "]" |
| 403 | } |
| 404 | case strings.HasPrefix(prompt, "[Equipo: question]"): |
| 405 | reply = fmt.Sprintf("Answered from my session (message %d).", f.messages) + strings.Join(notes, " ") |
| 406 | default: |
| 407 | reply = "ok " + strings.Join(notes, " ") |
| 408 | } |
| 409 | if strings.Contains(prompt, "echokey") { |
| 410 | // What a step that reads its environment could say: the key, in |
| 411 | // the reply (split across deltas) and in the verdict it records. |
| 412 | key := os.Getenv("TENSORX_API_KEY") |
| 413 | reply = "the key is " + key + " and that is all" |
| 414 | if strings.HasPrefix(prompt, "[Equipo: review]") { |
| 415 | tool("mcp__equipo__submit_review", map[string]any{"verdict": "approve", "headline": "Key " + key, "summary": "I read " + key, "findings": []map[string]any{}}) |
| 416 | } |
| 417 | } |
| 418 | if m := floodWord.FindStringSubmatch(prompt); m != nil { |
| 419 | n, _ := strconv.Atoi(m[1]) |
| 420 | reply = strings.Repeat("f", n) |
| 421 | } |
| 422 | if m := sleepWord.FindStringSubmatch(prompt); m != nil { |
| 423 | ms, _ := strconv.Atoi(m[1]) |
| 424 | select { |
| 425 | case <-time.After(time.Duration(ms) * time.Millisecond): |
| 426 | case <-f.aborted: |
| 427 | } |
| 428 | } |
| 429 | if f.stopped() { |
| 430 | f.aborted2() |
| 431 | return |
| 432 | } |
| 433 | half := len(reply) / 2 |
| 434 | start := f.assistant("stop", false, []any{}, "") |
| 435 | f.send(map[string]any{"type": "message_start", "message": start}) |
| 436 | for _, part := range []string{reply[:half], reply[half:]} { |
| 437 | f.send(map[string]any{"type": "message_update", "usage": start["usage"], "assistantMessageEvent": map[string]any{"type": "text_delta", "contentIndex": 0, "delta": part}}) |
| 438 | } |
| 439 | msg := f.assistant("stop", true, []any{map[string]string{"type": "text", "text": reply}}, "") |
| 440 | if strings.HasPrefix(prompt, "[Equipo: Copy]") { |
| 441 | if strings.Contains(prompt, "copy-usage-overrun") { |
| 442 | msg["usage"].(map[string]any)["input"] = 50000 |
| 443 | } |
| 444 | if strings.Contains(prompt, "copy-usage-missing") { |
| 445 | delete(msg, "usage") |
| 446 | } |
| 447 | } |
| 448 | f.send(map[string]any{"type": "message_end", "message": msg}) |
| 449 | f.record("assistant", reply) |
| 450 | f.send(map[string]any{"type": "turn_end", "message": msg, "toolResults": []any{}}) |
| 451 | f.send(map[string]any{"type": "agent_end", "messages": []any{msg}, "willRetry": false}) |
| 452 | f.send(map[string]any{"type": "agent_settled", "aborted": false}) |
| 453 | } |
| 454 | |
| 455 | func (f *fake) aborted2() { |
| 456 | msg := f.assistant("aborted", false, []any{}, "This operation was aborted") |
| 457 | f.send(map[string]any{"type": "message_start", "message": msg}) |
| 458 | f.send(map[string]any{"type": "message_end", "message": msg}) |
| 459 | f.send(map[string]any{"type": "turn_end", "message": msg, "toolResults": []any{}}) |
| 460 | f.send(map[string]any{"type": "agent_end", "messages": []any{msg}, "willRetry": false}) |
| 461 | f.send(map[string]any{"type": "agent_settled", "aborted": true}) |
| 462 | } |
| 463 | |
| 464 | // allowed plays Equipo's extension: a tool it pins, and for a read-only |
| 465 | // role a read inside the confinement. |
| 466 | func (f *fake) allowed(name string, args map[string]any) bool { |
| 467 | if !f.tools[name] { |
| 468 | return false |
| 469 | } |
| 470 | if f.confine == "" || name != "read" && name != "grep" && name != "find" && name != "ls" { |
| 471 | return true |
| 472 | } |
| 473 | p, _ := args["path"].(string) |
| 474 | if p == "" { |
| 475 | p = "." |
| 476 | } |
| 477 | if !filepath.IsAbs(p) { |
| 478 | p = filepath.Join(f.cwd, p) |
| 479 | } |
| 480 | if real, err := filepath.EvalSymlinks(p); err == nil { |
| 481 | p = real |
| 482 | } |
| 483 | p = filepath.Clean(p) |
| 484 | return p == f.confine || strings.HasPrefix(p, f.confine+"/") |
| 485 | } |
| 486 | |
| 487 | // execute runs one tool call: asked of the client first when the |
| 488 | // extension would not allow it. |
| 489 | func (f *fake) execute(id, name string, args map[string]any) (string, bool) { |
| 490 | if !f.allowed(name, args) { |
| 491 | f.uiID++ |
| 492 | uid := fmt.Sprintf("ui-%d", f.uiID) |
| 493 | message, _ := json.Marshal(map[string]any{"id": id, "tool": name, "args": args}) |
| 494 | f.send(map[string]any{"type": "extension_ui_request", "id": uid, "method": "confirm", "title": "equipo:tool_call", "message": string(message)}) |
| 495 | var a answer |
| 496 | select { |
| 497 | case a = <-f.answers: |
| 498 | case <-f.aborted: |
| 499 | select { |
| 500 | case a = <-f.answers: |
| 501 | case <-time.After(5 * time.Second): |
| 502 | } |
| 503 | } |
| 504 | if a.ID != uid || !a.Confirmed { |
| 505 | return "Equipo did not allow this call.", true |
| 506 | } |
| 507 | } |
| 508 | if server, tool, ok := strings.Cut(strings.TrimPrefix(name, "mcp__"), "__"); ok && strings.HasPrefix(name, "mcp__") { |
| 509 | if server != "equipo" { |
| 510 | return "unknown server", true |
| 511 | } |
| 512 | return f.callTool(tool, args) |
| 513 | } |
| 514 | switch name { |
| 515 | case "read": |
| 516 | p, _ := args["path"].(string) |
| 517 | raw, err := os.ReadFile(p) |
| 518 | if err != nil { |
| 519 | return err.Error(), true |
| 520 | } |
| 521 | return string(raw), false |
| 522 | case "edit": |
| 523 | return "Edited.", false |
| 524 | } |
| 525 | return "unknown tool", true |
| 526 | } |
| 527 | |
| 528 | func (f *fake) callTool(name string, input map[string]any) (string, bool) { |
| 529 | if f.mcpIn == nil { |
| 530 | if msg := f.connectMCP(); msg != "" { |
| 531 | return msg, true |
| 532 | } |
| 533 | } |
| 534 | f.callID++ |
| 535 | raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 100 + f.callID, "method": "tools/call", "params": map[string]any{"name": name, "arguments": input}}) |
| 536 | if _, err := f.mcpIn.Write(append(raw, '\n')); err != nil { |
| 537 | return "MCP write failed", true |
| 538 | } |
| 539 | line, err := f.mcpOut.ReadBytes('\n') |
| 540 | var reply struct { |
| 541 | Result struct { |
| 542 | Content []struct { |
| 543 | Text string `json:"text"` |
| 544 | } `json:"content"` |
| 545 | IsError bool `json:"isError"` |
| 546 | } `json:"result"` |
| 547 | Error *struct{} `json:"error"` |
| 548 | } |
| 549 | if err != nil || json.Unmarshal(line, &reply) != nil || reply.Error != nil || len(reply.Result.Content) == 0 { |
| 550 | return "MCP call failed", true |
| 551 | } |
| 552 | return reply.Result.Content[0].Text, reply.Result.IsError |
| 553 | } |
| 554 | |
| 555 | // connectMCP starts the equipo server from mcp.json in Pi's config |
| 556 | // directory. |
| 557 | func (f *fake) connectMCP() string { |
| 558 | raw, err := os.ReadFile(filepath.Join(os.Getenv("PI_CODING_AGENT_DIR"), "mcp.json")) |
| 559 | var cfg struct { |
| 560 | MCPServers map[string]struct { |
| 561 | Command string |
| 562 | Args []string |
| 563 | } `json:"mcpServers"` |
| 564 | } |
| 565 | if err != nil || json.Unmarshal(raw, &cfg) != nil || cfg.MCPServers["equipo"].Command == "" { |
| 566 | return "no MCP server configured" |
| 567 | } |
| 568 | eq := cfg.MCPServers["equipo"] |
| 569 | cmd := exec.Command(eq.Command, eq.Args...) |
| 570 | in, _ := cmd.StdinPipe() |
| 571 | out, _ := cmd.StdoutPipe() |
| 572 | if cmd.Start() != nil { |
| 573 | return "MCP server did not start" |
| 574 | } |
| 575 | r := bufio.NewReader(out) |
| 576 | call := func(id int, method string, params any) json.RawMessage { |
| 577 | raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": id, "method": method, "params": params}) |
| 578 | if _, err := in.Write(append(raw, '\n')); err != nil { |
| 579 | return nil |
| 580 | } |
| 581 | line, err := r.ReadBytes('\n') |
| 582 | var reply struct { |
| 583 | Result json.RawMessage `json:"result"` |
| 584 | } |
| 585 | if err != nil || json.Unmarshal(line, &reply) != nil { |
| 586 | return nil |
| 587 | } |
| 588 | return reply.Result |
| 589 | } |
| 590 | 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 { |
| 591 | return "MCP initialize failed" |
| 592 | } |
| 593 | note, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "method": "notifications/initialized"}) |
| 594 | in.Write(append(note, '\n')) |
| 595 | if call(2, "tools/list", map[string]any{}) == nil { |
| 596 | return "MCP tools/list failed" |
| 597 | } |
| 598 | f.mcpIn, f.mcpOut = in, r |
| 599 | return "" |
| 600 | } |
| 601 | |