| 1 | package fakeopencode |
| 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 | "sync/atomic" |
| 22 | "testing" |
| 23 | "time" |
| 24 | ) |
| 25 | |
| 26 | // TestKey is the key tests deliver; the fake Go refuses any other with a |
| 27 | // 401. |
| 28 | const TestKey = "sk-go-equipo-test-key-0123456789" |
| 29 | |
| 30 | // Go is an OpenAI-compatible OpenCode Go on 127.0.0.1, serving TLS as |
| 31 | // opencode.ai under a test authority, at Go's paths: the model list at |
| 32 | // /inference/go/v1/models and chat completions at |
| 33 | // /inference/go/openai/v1/chat/completions. A user message "CALL <tool> |
| 34 | // <json>" is answered with that tool call, a tool result with "done |
| 35 | // after the tool: ...", Equipo's step prompts with their tool call, and |
| 36 | // anything else with "ok done"; every answer carries usage as Go's does: |
| 37 | // cost 0 within the plan, and the opencode block with billing_source, |
| 38 | // allowance, list_cost and tokens. It records what it was sent. |
| 39 | type Go struct { |
| 40 | // Addr is where it listens; CA is its authority's certificate (PEM). |
| 41 | Addr, CA string |
| 42 | // OmitToolReplyUsage, when set, sends no usage with the answer to a |
| 43 | // tool result: one request of a turn without its figure. |
| 44 | OmitToolReplyUsage atomic.Bool |
| 45 | mu sync.Mutex |
| 46 | requests []Request |
| 47 | } |
| 48 | |
| 49 | // Request is one request as the fake Go saw it. |
| 50 | type Request struct { |
| 51 | Method, Path, Auth, Model string |
| 52 | Stream bool |
| 53 | MaxTokens int |
| 54 | Tools []string |
| 55 | System string |
| 56 | Messages int |
| 57 | // Last is the request's last message, LastRole its role (a tool |
| 58 | // result's is "tool"). |
| 59 | Last, LastRole string |
| 60 | } |
| 61 | |
| 62 | // Seen is every request so far. |
| 63 | func (g *Go) Seen() []Request { |
| 64 | g.mu.Lock() |
| 65 | defer g.mu.Unlock() |
| 66 | return append([]Request(nil), g.requests...) |
| 67 | } |
| 68 | |
| 69 | // Models are the models the fake Go lists. |
| 70 | var Models = []string{"glm-5.3", "kimi-k3", "beam-free"} |
| 71 | |
| 72 | // StartGo starts the fake Go and routes the test relay's opencode.ai to |
| 73 | // it (EQUIPO_TEST_EGRESS_UPSTREAM, test builds only). |
| 74 | func StartGo(t testing.TB) *Go { |
| 75 | t.Helper() |
| 76 | caKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| 77 | 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} |
| 78 | caDER, err := x509.CreateCertificate(rand.Reader, caTmpl, caTmpl, &caKey.PublicKey, caKey) |
| 79 | if err != nil { |
| 80 | t.Fatal(err) |
| 81 | } |
| 82 | ca, _ := x509.ParseCertificate(caDER) |
| 83 | key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| 84 | leaf := &x509.Certificate{SerialNumber: big.NewInt(2), Subject: pkix.Name{CommonName: "opencode.ai"}, DNSNames: []string{"opencode.ai"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}} |
| 85 | leafDER, err := x509.CreateCertificate(rand.Reader, leaf, ca, &key.PublicKey, caKey) |
| 86 | if err != nil { |
| 87 | t.Fatal(err) |
| 88 | } |
| 89 | caFile := filepath.Join(t.TempDir(), "ca.pem") |
| 90 | if err := os.WriteFile(caFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caDER}), 0600); err != nil { |
| 91 | t.Fatal(err) |
| 92 | } |
| 93 | g := &Go{CA: caFile} |
| 94 | srv := &http.Server{Handler: http.HandlerFunc(g.serve), TLSConfig: &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{leafDER}, PrivateKey: key}}}} |
| 95 | ln, err := net.Listen("tcp", "127.0.0.1:0") |
| 96 | if err != nil { |
| 97 | t.Fatal(err) |
| 98 | } |
| 99 | g.Addr = ln.Addr().String() |
| 100 | go srv.ServeTLS(ln, "", "") |
| 101 | t.Cleanup(func() { srv.Close() }) |
| 102 | if prev := os.Getenv("EQUIPO_TEST_EGRESS_UPSTREAM"); prev != "" { |
| 103 | t.Setenv("EQUIPO_TEST_EGRESS_UPSTREAM", prev+",opencode.ai="+g.Addr) |
| 104 | } else { |
| 105 | t.Setenv("EQUIPO_TEST_EGRESS_UPSTREAM", "opencode.ai="+g.Addr) |
| 106 | } |
| 107 | return g |
| 108 | } |
| 109 | |
| 110 | // steps turns Equipo's step prompts into the calls a model would make. |
| 111 | func steps(text string) string { |
| 112 | switch { |
| 113 | case strings.HasPrefix(text, "[Equipo: review]"): |
| 114 | return `CALL equipo_submit_review {"verdict":"approve","headline":"Approved.","summary":"The change does what the task asks. (from OpenCode Go)","findings":[]}` |
| 115 | case strings.HasPrefix(text, "[Equipo: engineering]"): |
| 116 | return `CALL equipo_submit_candidate {}` |
| 117 | } |
| 118 | return text |
| 119 | } |
| 120 | |
| 121 | func goUsage(model string) map[string]any { |
| 122 | return map[string]any{"prompt_tokens": 100, "completion_tokens": 7, "total_tokens": 107, "prompt_tokens_details": map[string]any{"cached_tokens": 40}, |
| 123 | "cost": 0, "opencode": map[string]any{"billing_source": "go", "allowance": 0.00123, "list_cost": 0.00123, "tokens": map[string]any{"input": 60, "output": 7, "reasoning": 0, "cache_read": 40, "cache_write_5m": 0, "cache_write_1h": 0}}} |
| 124 | } |
| 125 | |
| 126 | func (g *Go) serve(w http.ResponseWriter, r *http.Request) { |
| 127 | auth := r.Header.Get("Authorization") |
| 128 | // Every request is recorded before it is routed, whatever its path: |
| 129 | // a test sees stray traffic on the one allowed host. |
| 130 | g.mu.Lock() |
| 131 | g.requests = append(g.requests, Request{Method: r.Method, Path: r.URL.Path, Auth: auth}) |
| 132 | at := len(g.requests) - 1 |
| 133 | g.mu.Unlock() |
| 134 | if r.Method == http.MethodGet && r.URL.Path == "/inference/go/v1/models" { |
| 135 | if auth != "Bearer "+TestKey { |
| 136 | w.WriteHeader(401) |
| 137 | return |
| 138 | } |
| 139 | var data []map[string]string |
| 140 | for _, m := range Models { |
| 141 | data = append(data, map[string]string{"id": m, "object": "model"}) |
| 142 | } |
| 143 | json.NewEncoder(w).Encode(map[string]any{"object": "list", "data": data}) |
| 144 | return |
| 145 | } |
| 146 | if r.Method != http.MethodPost || r.URL.Path != "/inference/go/openai/v1/chat/completions" { |
| 147 | http.NotFound(w, r) |
| 148 | return |
| 149 | } |
| 150 | var req struct { |
| 151 | Model string `json:"model"` |
| 152 | Stream bool `json:"stream"` |
| 153 | MaxTokens int `json:"max_tokens"` |
| 154 | Messages []struct { |
| 155 | Role string `json:"role"` |
| 156 | Content json.RawMessage `json:"content"` |
| 157 | } `json:"messages"` |
| 158 | Tools []struct { |
| 159 | Function struct{ Name string } `json:"function"` |
| 160 | } `json:"tools"` |
| 161 | } |
| 162 | if json.NewDecoder(io.LimitReader(r.Body, 8<<20)).Decode(&req) != nil { |
| 163 | http.Error(w, "bad", 400) |
| 164 | return |
| 165 | } |
| 166 | rec := Request{Method: r.Method, Path: r.URL.Path, Auth: auth, Model: req.Model, Stream: req.Stream, MaxTokens: req.MaxTokens, Messages: len(req.Messages)} |
| 167 | for _, tool := range req.Tools { |
| 168 | rec.Tools = append(rec.Tools, tool.Function.Name) |
| 169 | } |
| 170 | text, role := "", "" |
| 171 | for i, m := range req.Messages { |
| 172 | var s string |
| 173 | if json.Unmarshal(m.Content, &s) != nil { |
| 174 | var parts []struct{ Text string } |
| 175 | json.Unmarshal(m.Content, &parts) |
| 176 | for _, p := range parts { |
| 177 | s += p.Text |
| 178 | } |
| 179 | } |
| 180 | if m.Role == "system" || m.Role == "developer" { |
| 181 | rec.System += s |
| 182 | } |
| 183 | if i == len(req.Messages)-1 { |
| 184 | text, role = s, m.Role |
| 185 | } |
| 186 | } |
| 187 | rec.Last, rec.LastRole = text, role |
| 188 | g.mu.Lock() |
| 189 | g.requests[at] = rec |
| 190 | g.mu.Unlock() |
| 191 | if auth != "Bearer "+TestKey { |
| 192 | w.Header().Set("Content-Type", "application/json") |
| 193 | w.WriteHeader(401) |
| 194 | io.WriteString(w, `{"error":{"message":"Invalid API key"}}`) |
| 195 | return |
| 196 | } |
| 197 | if !req.Stream { |
| 198 | // The one-token probe. |
| 199 | json.NewEncoder(w).Encode(map[string]any{"id": "c1", "object": "chat.completion", "model": req.Model, "choices": []any{map[string]any{"index": 0, "message": map[string]any{"role": "assistant", "content": "ok"}, "finish_reason": "length"}}, "usage": goUsage(req.Model)}) |
| 200 | return |
| 201 | } |
| 202 | w.Header().Set("Content-Type", "text/event-stream") |
| 203 | chunk := func(v any) { |
| 204 | raw, _ := json.Marshal(v) |
| 205 | fmt.Fprintf(w, "data: %s\n\n", raw) |
| 206 | if fl, ok := w.(http.Flusher); ok { |
| 207 | fl.Flush() |
| 208 | } |
| 209 | } |
| 210 | base := func(k string, v any) map[string]any { |
| 211 | return map[string]any{"id": "c1", "object": "chat.completion.chunk", "created": 1, "model": req.Model, k: v} |
| 212 | } |
| 213 | if role == "user" { |
| 214 | text = steps(text) |
| 215 | } |
| 216 | if role == "user" && strings.HasPrefix(text, "CALL ") { |
| 217 | parts := strings.SplitN(text, " ", 3) |
| 218 | if len(parts) < 3 { |
| 219 | parts = append(parts, "{}") |
| 220 | } |
| 221 | chunk(base("choices", []any{map[string]any{"index": 0, "delta": map[string]any{"role": "assistant", "tool_calls": []any{map[string]any{"index": 0, "id": fmt.Sprintf("call_%d", time.Now().UnixNano()), "type": "function", "function": map[string]any{"name": parts[1], "arguments": parts[2]}}}}}})) |
| 222 | chunk(base("choices", []any{map[string]any{"index": 0, "delta": map[string]any{}, "finish_reason": "tool_calls"}})) |
| 223 | } else { |
| 224 | reply := "ok done" |
| 225 | if role == "tool" { |
| 226 | reply = "done after the tool: " + strings.ReplaceAll(clip(text, 2000), "\n", " ") |
| 227 | } |
| 228 | chunk(base("choices", []any{map[string]any{"index": 0, "delta": map[string]any{"role": "assistant", "content": reply}}})) |
| 229 | chunk(base("choices", []any{map[string]any{"index": 0, "delta": map[string]any{}, "finish_reason": "stop"}})) |
| 230 | } |
| 231 | if !(role == "tool" && g.OmitToolReplyUsage.Load()) { |
| 232 | u := base("choices", []any{}) |
| 233 | u["usage"] = goUsage(req.Model) |
| 234 | chunk(u) |
| 235 | } |
| 236 | io.WriteString(w, "data: [DONE]\n\n") |
| 237 | } |
| 238 | |
| 239 | func clip(s string, n int) string { |
| 240 | if len(s) <= n { |
| 241 | return s |
| 242 | } |
| 243 | return s[:n] |
| 244 | } |
| 245 | |