| 1 | package fakepi |
| 2 | |
| 3 | import ( |
| 4 | "crypto/ecdsa" |
| 5 | "crypto/elliptic" |
| 6 | "crypto/rand" |
| 7 | "crypto/tls" |
| 8 | "crypto/x509" |
| 9 | "crypto/x509/pkix" |
| 10 | "encoding/json" |
| 11 | "encoding/pem" |
| 12 | "fmt" |
| 13 | "io" |
| 14 | "math/big" |
| 15 | "net" |
| 16 | "net/http" |
| 17 | "os" |
| 18 | "path/filepath" |
| 19 | "strings" |
| 20 | "sync" |
| 21 | "testing" |
| 22 | "time" |
| 23 | ) |
| 24 | |
| 25 | // TestKey is the key tests deliver to a real Pi; TensorX refuses any |
| 26 | // other with a 401. |
| 27 | const TestKey = "tx-equipo-test-key-0123456789" |
| 28 | |
| 29 | // steps turns Equipo's step prompts into the calls a model would make: |
| 30 | // a Review step submits an approval, an Engineering step its candidate. |
| 31 | func steps(text string) string { |
| 32 | switch { |
| 33 | case strings.HasPrefix(text, "[Equipo: review]"): |
| 34 | return `CALL mcp__equipo__submit_review {"verdict":"approve","headline":"Approved.","summary":"The change does what the task asks. (from TensorX)","findings":[]}` |
| 35 | case strings.HasPrefix(text, "[Equipo: engineering]"): |
| 36 | return `CALL mcp__equipo__submit_candidate {}` |
| 37 | } |
| 38 | return text |
| 39 | } |
| 40 | |
| 41 | // TensorX is an OpenAI-compatible provider on 127.0.0.1, serving TLS |
| 42 | // as api.tensorx.ai under a test authority. It answers a user message |
| 43 | // "CALL <tool> <json>" with that tool call, a tool result with "done", |
| 44 | // and anything else with "ok done", each with usage; it records what it |
| 45 | // was sent. |
| 46 | type TensorX struct { |
| 47 | // Addr is where it listens; CA is its authority's certificate (PEM). |
| 48 | Addr, CA string |
| 49 | mu sync.Mutex |
| 50 | requests []Request |
| 51 | } |
| 52 | |
| 53 | type Request struct { |
| 54 | Auth, Model string |
| 55 | Tools []string |
| 56 | System string |
| 57 | Messages int |
| 58 | // ToolText is the tool result the request answers, if any. |
| 59 | ToolText string |
| 60 | } |
| 61 | |
| 62 | // Seen is every request so far. |
| 63 | func (f *TensorX) Seen() []Request { |
| 64 | f.mu.Lock() |
| 65 | defer f.mu.Unlock() |
| 66 | return append([]Request(nil), f.requests...) |
| 67 | } |
| 68 | |
| 69 | func StartTensorX(t testing.TB) *TensorX { |
| 70 | t.Helper() |
| 71 | caKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| 72 | caTmpl := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "equipo test authority"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign} |
| 73 | caDER, err := x509.CreateCertificate(rand.Reader, caTmpl, caTmpl, &caKey.PublicKey, caKey) |
| 74 | if err != nil { |
| 75 | t.Fatal(err) |
| 76 | } |
| 77 | ca, _ := x509.ParseCertificate(caDER) |
| 78 | key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| 79 | leaf := &x509.Certificate{SerialNumber: big.NewInt(2), Subject: pkix.Name{CommonName: "api.tensorx.ai"}, DNSNames: []string{"api.tensorx.ai"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}} |
| 80 | leafDER, err := x509.CreateCertificate(rand.Reader, leaf, ca, &key.PublicKey, caKey) |
| 81 | if err != nil { |
| 82 | t.Fatal(err) |
| 83 | } |
| 84 | caFile := filepath.Join(t.TempDir(), "ca.pem") |
| 85 | if err := os.WriteFile(caFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caDER}), 0600); err != nil { |
| 86 | t.Fatal(err) |
| 87 | } |
| 88 | f := &TensorX{CA: caFile} |
| 89 | srv := &http.Server{Handler: http.HandlerFunc(f.serve), TLSConfig: &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{leafDER}, PrivateKey: key}}}} |
| 90 | ln, err := net.Listen("tcp", "127.0.0.1:0") |
| 91 | if err != nil { |
| 92 | t.Fatal(err) |
| 93 | } |
| 94 | f.Addr = ln.Addr().String() |
| 95 | go srv.ServeTLS(ln, "", "") |
| 96 | t.Cleanup(func() { srv.Close() }) |
| 97 | t.Setenv("EQUIPO_TEST_EGRESS_UPSTREAM", "api.tensorx.ai="+f.Addr) |
| 98 | return f |
| 99 | } |
| 100 | |
| 101 | func (f *TensorX) serve(w http.ResponseWriter, r *http.Request) { |
| 102 | if r.URL.Path != "/v1/chat/completions" { |
| 103 | http.NotFound(w, r) |
| 104 | return |
| 105 | } |
| 106 | var req struct { |
| 107 | Model string `json:"model"` |
| 108 | Messages []struct { |
| 109 | Role string `json:"role"` |
| 110 | Content json.RawMessage `json:"content"` |
| 111 | } `json:"messages"` |
| 112 | Tools []struct { |
| 113 | Function struct{ Name string } `json:"function"` |
| 114 | } `json:"tools"` |
| 115 | } |
| 116 | if json.NewDecoder(io.LimitReader(r.Body, 8<<20)).Decode(&req) != nil { |
| 117 | http.Error(w, "bad", 400) |
| 118 | return |
| 119 | } |
| 120 | rec := Request{Auth: r.Header.Get("Authorization"), Model: req.Model, Messages: len(req.Messages)} |
| 121 | for _, tool := range req.Tools { |
| 122 | rec.Tools = append(rec.Tools, tool.Function.Name) |
| 123 | } |
| 124 | for _, m := range req.Messages { |
| 125 | if m.Role == "system" || m.Role == "developer" { |
| 126 | rec.System += string(m.Content) |
| 127 | } |
| 128 | } |
| 129 | f.mu.Lock() |
| 130 | f.requests = append(f.requests, rec) |
| 131 | f.mu.Unlock() |
| 132 | if rec.Auth != "Bearer "+TestKey { |
| 133 | w.Header().Set("Content-Type", "application/json") |
| 134 | w.WriteHeader(401) |
| 135 | io.WriteString(w, `{"error":{"message":"Invalid API key"}}`) |
| 136 | return |
| 137 | } |
| 138 | text := "" |
| 139 | role := "" |
| 140 | if n := len(req.Messages); n > 0 { |
| 141 | role = req.Messages[n-1].Role |
| 142 | var s string |
| 143 | if json.Unmarshal(req.Messages[n-1].Content, &s) != nil { |
| 144 | var parts []struct{ Text string } |
| 145 | json.Unmarshal(req.Messages[n-1].Content, &parts) |
| 146 | for _, p := range parts { |
| 147 | s += p.Text |
| 148 | } |
| 149 | } |
| 150 | text = s |
| 151 | } |
| 152 | w.Header().Set("Content-Type", "text/event-stream") |
| 153 | chunk := func(v any) { |
| 154 | raw, _ := json.Marshal(v) |
| 155 | fmt.Fprintf(w, "data: %s\n\n", raw) |
| 156 | if fl, ok := w.(http.Flusher); ok { |
| 157 | fl.Flush() |
| 158 | } |
| 159 | } |
| 160 | base := map[string]any{"id": "c1", "object": "chat.completion.chunk", "created": 1, "model": req.Model} |
| 161 | with := func(k string, v any) map[string]any { |
| 162 | out := map[string]any{} |
| 163 | for a, b := range base { |
| 164 | out[a] = b |
| 165 | } |
| 166 | out[k] = v |
| 167 | return out |
| 168 | } |
| 169 | if role == "tool" { |
| 170 | f.mu.Lock() |
| 171 | f.requests[len(f.requests)-1].ToolText = text |
| 172 | f.mu.Unlock() |
| 173 | } |
| 174 | if role == "user" { |
| 175 | text = steps(text) |
| 176 | } |
| 177 | if role == "user" && (strings.HasPrefix(text, "CALL ") || strings.HasPrefix(text, "BATCH ")) { |
| 178 | var calls []struct { |
| 179 | Name string `json:"name"` |
| 180 | Arguments json.RawMessage `json:"arguments"` |
| 181 | } |
| 182 | if strings.HasPrefix(text, "BATCH ") { |
| 183 | _ = json.Unmarshal([]byte(strings.TrimPrefix(text, "BATCH ")), &calls) |
| 184 | } else { |
| 185 | parts := strings.SplitN(text, " ", 3) |
| 186 | calls = append(calls, struct { |
| 187 | Name string `json:"name"` |
| 188 | Arguments json.RawMessage `json:"arguments"` |
| 189 | }{parts[1], json.RawMessage(parts[2])}) |
| 190 | } |
| 191 | var batch []any |
| 192 | for i, c := range calls { |
| 193 | batch = append(batch, map[string]any{"index": i, "id": fmt.Sprintf("call_%d", i+1), "type": "function", "function": map[string]any{"name": c.Name, "arguments": string(c.Arguments)}}) |
| 194 | } |
| 195 | chunk(with("choices", []any{map[string]any{"index": 0, "delta": map[string]any{"role": "assistant", "tool_calls": batch}}})) |
| 196 | chunk(with("choices", []any{map[string]any{"index": 0, "delta": map[string]any{}, "finish_reason": "tool_calls"}})) |
| 197 | } else { |
| 198 | reply := "ok done" |
| 199 | if role == "tool" { |
| 200 | reply = "done after the tool: " + strings.ReplaceAll(text, "\n", " ") |
| 201 | } |
| 202 | chunk(with("choices", []any{map[string]any{"index": 0, "delta": map[string]any{"role": "assistant", "content": reply}}})) |
| 203 | chunk(with("choices", []any{map[string]any{"index": 0, "delta": map[string]any{}, "finish_reason": "stop"}})) |
| 204 | } |
| 205 | chunk(with("choices", []any{})) |
| 206 | usage := with("choices", []any{}) |
| 207 | usage["usage"] = map[string]any{"prompt_tokens": 100, "completion_tokens": 7, "total_tokens": 107, "prompt_tokens_details": map[string]any{"cached_tokens": 40}} |
| 208 | chunk(usage) |
| 209 | io.WriteString(w, "data: [DONE]\n\n") |
| 210 | } |
| 211 | |