package fakeopencode import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "encoding/json" "encoding/pem" "fmt" "io" "math/big" "net" "net/http" "os" "path/filepath" "strings" "sync" "sync/atomic" "testing" "time" ) // TestKey is the key tests deliver; the fake Go refuses any other with a // 401. const TestKey = "sk-go-equipo-test-key-0123456789" // Go is an OpenAI-compatible OpenCode Go on 127.0.0.1, serving TLS as // opencode.ai under a test authority, at Go's paths: the model list at // /inference/go/v1/models and chat completions at // /inference/go/openai/v1/chat/completions. A user message "CALL // " is answered with that tool call, a tool result with "done // after the tool: ...", Equipo's step prompts with their tool call, and // anything else with "ok done"; every answer carries usage as Go's does: // cost 0 within the plan, and the opencode block with billing_source, // allowance, list_cost and tokens. It records what it was sent. type Go struct { // Addr is where it listens; CA is its authority's certificate (PEM). Addr, CA string // OmitToolReplyUsage, when set, sends no usage with the answer to a // tool result: one request of a turn without its figure. OmitToolReplyUsage atomic.Bool mu sync.Mutex requests []Request } // Request is one request as the fake Go saw it. type Request struct { Method, Path, Auth, Model string Stream bool MaxTokens int Tools []string System string Messages int // Last is the request's last message, LastRole its role (a tool // result's is "tool"). Last, LastRole string } // Seen is every request so far. func (g *Go) Seen() []Request { g.mu.Lock() defer g.mu.Unlock() return append([]Request(nil), g.requests...) } // Models are the models the fake Go lists. var Models = []string{"glm-5.3", "kimi-k3", "beam-free"} // StartGo starts the fake Go and routes the test relay's opencode.ai to // it (EQUIPO_TEST_EGRESS_UPSTREAM, test builds only). func StartGo(t testing.TB) *Go { t.Helper() caKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) 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} caDER, err := x509.CreateCertificate(rand.Reader, caTmpl, caTmpl, &caKey.PublicKey, caKey) if err != nil { t.Fatal(err) } ca, _ := x509.ParseCertificate(caDER) key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) 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}} leafDER, err := x509.CreateCertificate(rand.Reader, leaf, ca, &key.PublicKey, caKey) if err != nil { t.Fatal(err) } caFile := filepath.Join(t.TempDir(), "ca.pem") if err := os.WriteFile(caFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caDER}), 0600); err != nil { t.Fatal(err) } g := &Go{CA: caFile} srv := &http.Server{Handler: http.HandlerFunc(g.serve), TLSConfig: &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{leafDER}, PrivateKey: key}}}} ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } g.Addr = ln.Addr().String() go srv.ServeTLS(ln, "", "") t.Cleanup(func() { srv.Close() }) if prev := os.Getenv("EQUIPO_TEST_EGRESS_UPSTREAM"); prev != "" { t.Setenv("EQUIPO_TEST_EGRESS_UPSTREAM", prev+",opencode.ai="+g.Addr) } else { t.Setenv("EQUIPO_TEST_EGRESS_UPSTREAM", "opencode.ai="+g.Addr) } return g } // steps turns Equipo's step prompts into the calls a model would make. func steps(text string) string { switch { case strings.HasPrefix(text, "[Equipo: review]"): return `CALL equipo_submit_review {"verdict":"approve","headline":"Approved.","summary":"The change does what the task asks. (from OpenCode Go)","findings":[]}` case strings.HasPrefix(text, "[Equipo: engineering]"): return `CALL equipo_submit_candidate {}` } return text } func goUsage(model string) map[string]any { return map[string]any{"prompt_tokens": 100, "completion_tokens": 7, "total_tokens": 107, "prompt_tokens_details": map[string]any{"cached_tokens": 40}, "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}}} } func (g *Go) serve(w http.ResponseWriter, r *http.Request) { auth := r.Header.Get("Authorization") // Every request is recorded before it is routed, whatever its path: // a test sees stray traffic on the one allowed host. g.mu.Lock() g.requests = append(g.requests, Request{Method: r.Method, Path: r.URL.Path, Auth: auth}) at := len(g.requests) - 1 g.mu.Unlock() if r.Method == http.MethodGet && r.URL.Path == "/inference/go/v1/models" { if auth != "Bearer "+TestKey { w.WriteHeader(401) return } var data []map[string]string for _, m := range Models { data = append(data, map[string]string{"id": m, "object": "model"}) } json.NewEncoder(w).Encode(map[string]any{"object": "list", "data": data}) return } if r.Method != http.MethodPost || r.URL.Path != "/inference/go/openai/v1/chat/completions" { http.NotFound(w, r) return } var req struct { Model string `json:"model"` Stream bool `json:"stream"` MaxTokens int `json:"max_tokens"` Messages []struct { Role string `json:"role"` Content json.RawMessage `json:"content"` } `json:"messages"` Tools []struct { Function struct{ Name string } `json:"function"` } `json:"tools"` } if json.NewDecoder(io.LimitReader(r.Body, 8<<20)).Decode(&req) != nil { http.Error(w, "bad", 400) return } rec := Request{Method: r.Method, Path: r.URL.Path, Auth: auth, Model: req.Model, Stream: req.Stream, MaxTokens: req.MaxTokens, Messages: len(req.Messages)} for _, tool := range req.Tools { rec.Tools = append(rec.Tools, tool.Function.Name) } text, role := "", "" for i, m := range req.Messages { var s string if json.Unmarshal(m.Content, &s) != nil { var parts []struct{ Text string } json.Unmarshal(m.Content, &parts) for _, p := range parts { s += p.Text } } if m.Role == "system" || m.Role == "developer" { rec.System += s } if i == len(req.Messages)-1 { text, role = s, m.Role } } rec.Last, rec.LastRole = text, role g.mu.Lock() g.requests[at] = rec g.mu.Unlock() if auth != "Bearer "+TestKey { w.Header().Set("Content-Type", "application/json") w.WriteHeader(401) io.WriteString(w, `{"error":{"message":"Invalid API key"}}`) return } if !req.Stream { // The one-token probe. 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)}) return } w.Header().Set("Content-Type", "text/event-stream") chunk := func(v any) { raw, _ := json.Marshal(v) fmt.Fprintf(w, "data: %s\n\n", raw) if fl, ok := w.(http.Flusher); ok { fl.Flush() } } base := func(k string, v any) map[string]any { return map[string]any{"id": "c1", "object": "chat.completion.chunk", "created": 1, "model": req.Model, k: v} } if role == "user" { text = steps(text) } if role == "user" && strings.HasPrefix(text, "CALL ") { parts := strings.SplitN(text, " ", 3) if len(parts) < 3 { parts = append(parts, "{}") } 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]}}}}}})) chunk(base("choices", []any{map[string]any{"index": 0, "delta": map[string]any{}, "finish_reason": "tool_calls"}})) } else { reply := "ok done" if role == "tool" { reply = "done after the tool: " + strings.ReplaceAll(clip(text, 2000), "\n", " ") } chunk(base("choices", []any{map[string]any{"index": 0, "delta": map[string]any{"role": "assistant", "content": reply}}})) chunk(base("choices", []any{map[string]any{"index": 0, "delta": map[string]any{}, "finish_reason": "stop"}})) } if !(role == "tool" && g.OmitToolReplyUsage.Load()) { u := base("choices", []any{}) u["usage"] = goUsage(req.Model) chunk(u) } io.WriteString(w, "data: [DONE]\n\n") } func clip(s string, n int) string { if len(s) <= n { return s } return s[:n] }