| 1 | package openai |
| 2 | |
| 3 | import ( |
| 4 | "net/url" |
| 5 | "strings" |
| 6 | ) |
| 7 | |
| 8 | const ( |
| 9 | tokenRhythmOrigin = "https://tokenrhythm.studio" |
| 10 | tokenRhythmHost = "tokenrhythm.studio" |
| 11 | tokenRhythmChatPath = "/v1/chat/completions" |
| 12 | tokenRhythmModelsPath = "/v1/models" |
| 13 | ) |
| 14 | |
| 15 | // canonicalTokenRhythmEndpoint rewrites known official Token Rhythm URLs. |
| 16 | // Official /v1 routes are already complete; unknown or unsafe URLs stay untouched. |
| 17 | func canonicalTokenRhythmEndpoint(raw, canonicalPath string) (string, bool) { |
| 18 | raw = strings.TrimSpace(raw) |
| 19 | if raw == "" { |
| 20 | return "", false |
| 21 | } |
| 22 | if strings.ContainsAny(raw, "?#") { |
| 23 | return "", false |
| 24 | } |
| 25 | u, err := url.Parse(raw) |
| 26 | if err != nil || u.Scheme != "https" || u.Host == "" || u.Opaque != "" { |
| 27 | return "", false |
| 28 | } |
| 29 | if !strings.EqualFold(u.Hostname(), tokenRhythmHost) { |
| 30 | return "", false |
| 31 | } |
| 32 | if port := u.Port(); port != "" && port != "443" { |
| 33 | return "", false |
| 34 | } |
| 35 | if u.User != nil || u.RawPath != "" { |
| 36 | return "", false |
| 37 | } |
| 38 | if !tokenRhythmKnownPath(u.Path) { |
| 39 | return "", false |
| 40 | } |
| 41 | return tokenRhythmOrigin + canonicalPath, true |
| 42 | } |
| 43 | |
| 44 | func canonicalTokenRhythmChatURL(raw string) (string, bool) { |
| 45 | return canonicalTokenRhythmEndpoint(raw, tokenRhythmChatPath) |
| 46 | } |
| 47 | |
| 48 | // CanonicalTokenRhythmModelsURL rewrites known official Token Rhythm URLs to GET /v1/models. |
| 49 | func CanonicalTokenRhythmModelsURL(raw string) (string, bool) { |
| 50 | return canonicalTokenRhythmEndpoint(raw, tokenRhythmModelsPath) |
| 51 | } |
| 52 | |
| 53 | func tokenRhythmKnownPath(path string) bool { |
| 54 | if path != "/" { |
| 55 | path = strings.TrimSuffix(path, "/") |
| 56 | } |
| 57 | switch path { |
| 58 | case "", "/", "/v1", "/v1/v1": |
| 59 | return true |
| 60 | } |
| 61 | for _, leaf := range []string{"/chat/completions", "/models"} { |
| 62 | for _, prefix := range []string{"", "/v1", "/v1/v1"} { |
| 63 | if path == prefix+leaf || path == prefix+leaf+leaf { |
| 64 | return true |
| 65 | } |
| 66 | } |
| 67 | } |
| 68 | return false |
| 69 | } |
| 70 |