File size: 11,847 Bytes
1766992
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
// Copyright (c) 2025-2026 libaxuan
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

package handlers

import (
	"github.com/libaxuan/cursor2api-go/config"
	"github.com/libaxuan/cursor2api-go/middleware"
	"github.com/libaxuan/cursor2api-go/models"
	"github.com/libaxuan/cursor2api-go/services"
	"github.com/libaxuan/cursor2api-go/utils"
	"net/http"
	"os"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

// Handler 处理器结构
type Handler struct {
	config        *config.Config
	cursorService *services.CursorService
	docsContent   []byte
	responseStore *services.ResponseStore
}

// NewHandler 创建新的处理器
func NewHandler(cfg *config.Config) *Handler {
	cursorService := services.NewCursorService(cfg)

	// 预加载文档内容
	docsPath := "static/docs.html"
	var docsContent []byte

	if data, err := os.ReadFile(docsPath); err == nil {
		docsContent = data
	} else {
		// 如果文件不存在,使用默认的简单HTML页面
		simpleHTML := `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cursor2API - Go Version</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 800px;
            margin: 50px auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            border-bottom: 2px solid #007bff;
            padding-bottom: 10px;
        }
        .info {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin: 20px 0;
            border-left: 4px solid #007bff;
        }
        code {
            background: #e9ecef;
            padding: 2px 6px;
            border-radius: 4px;
            font-family: 'Courier New', monospace;
        }
        .endpoint {
            background: #e3f2fd;
            padding: 10px;
            margin: 10px 0;
            border-radius: 5px;
            border-left: 3px solid #2196f3;
        }
        .status-ok {
            color: #28a745;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🚀 Cursor2API - Go Version</h1>
        
        <div class="info">
            <p><strong>Status:</strong> <span class="status-ok">✅ Running</span></p>
            <p><strong>Version:</strong> Go Implementation</p>
            <p><strong>Description:</strong> OpenAI-compatible chat completions proxy for Cursor AI</p>
        </div>
        
        <div class="info">
            <h3>📡 Available Endpoints:</h3>
            <div class="endpoint">
                <strong>GET</strong> <code>/v1/models</code><br>
                <small>List available AI models</small>
            </div>
            <div class="endpoint">
                <strong>POST</strong> <code>/v1/chat/completions</code><br>
                <small>Create chat completion (supports streaming and tool calls)</small>
            </div>
            <div class="endpoint">
                <strong>POST</strong> <code>/v1/responses</code><br>
                <small>Create response (Responses API compatible)</small>
            </div>
            <div class="endpoint">
                <strong>GET</strong> <code>/health</code><br>
                <small>Health check endpoint</small>
            </div>
        </div>
        
        <div class="info">
            <h3>🔐 Authentication:</h3>
            <p>Use Bearer token authentication:</p>
            <code>Authorization: Bearer YOUR_API_KEY</code>
            <p><small>Default API key: <code>0000</code> (change via API_KEY environment variable)</small></p>
        </div>
        
        <div class="info">
            <h3>💻 Example Usage:</h3>
            <pre><code>curl -X POST http://localhost:8002/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer 0000" \
  -d '{
    "model": "claude-sonnet-4.6-thinking",
    "messages": [
      {"role": "user", "content": "Plan first, then decide whether a tool is needed."}
    ],
    "stream": true
  }'</code></pre>
        </div>
        
        <div class="info">
            <p><strong>Repository:</strong> <a href="https://github.com/cursor2api/cursor2api-go">cursor2api-go</a></p>
            <p><strong>Documentation:</strong> OpenAI API compatible</p>
        </div>
    </div>
</body>
</html>`
		docsContent = []byte(simpleHTML)
	}

	return &Handler{
		config:        cfg,
		cursorService: cursorService,
		docsContent:   docsContent,
		responseStore: services.NewResponseStore(0, 0),
	}

}

// ListModels 列出可用模型
func (h *Handler) ListModels(c *gin.Context) {
	modelNames := h.config.GetModels()
	modelList := make([]models.Model, 0, len(modelNames))

	for _, modelID := range modelNames {
		// 获取模型配置信息
		modelConfig, exists := models.GetModelConfig(modelID)

		model := models.Model{
			ID:      modelID,
			Object:  "model",
			Created: time.Now().Unix(),
			OwnedBy: "cursor2api",
		}

		// 如果找到模型配置,添加max_tokens和context_window信息
		if exists {
			model.MaxTokens = modelConfig.MaxTokens
			model.ContextWindow = modelConfig.ContextWindow
		}

		modelList = append(modelList, model)
	}

	response := models.ModelsResponse{
		Object: "list",
		Data:   modelList,
	}

	c.JSON(http.StatusOK, response)
}

// ChatCompletions 处理聊天完成请求
func (h *Handler) ChatCompletions(c *gin.Context) {
	var request models.ChatCompletionRequest
	if err := c.ShouldBindJSON(&request); err != nil {
		logrus.WithError(err).Error("Failed to bind request")
		c.JSON(http.StatusBadRequest, models.NewErrorResponse(
			"Invalid request format",
			"invalid_request_error",
			"invalid_json",
		))
		return
	}

	// 验证模型
	if !h.config.IsValidModel(request.Model) {
		c.JSON(http.StatusBadRequest, models.NewErrorResponse(
			"Invalid model specified",
			"invalid_request_error",
			"model_not_found",
		))
		return
	}

	// 验证消息
	if len(request.Messages) == 0 {
		c.JSON(http.StatusBadRequest, models.NewErrorResponse(
			"Messages cannot be empty",
			"invalid_request_error",
			"missing_messages",
		))
		return
	}

	// 验证并调整max_tokens参数
	request.MaxTokens = models.ValidateMaxTokens(request.Model, request.MaxTokens)

	// 调用Cursor服务
	// 根据是否流式返回不同响应
	if request.Stream {
		chatGenerator, err := h.cursorService.ChatCompletion(c.Request.Context(), &request)
		if err != nil {
			logrus.WithError(err).Error("Failed to create chat completion")
			middleware.HandleError(c, err)
			return
		}
		utils.SafeStreamWrapper(utils.StreamChatCompletion, c, chatGenerator, request.Model)
	} else {
		resp, err := h.cursorService.ChatCompletionNonStream(c.Request.Context(), &request)
		if err != nil {
			logrus.WithError(err).Error("Failed to create non-stream chat completion")
			middleware.HandleError(c, err)
			return
		}
		c.JSON(http.StatusOK, resp)
	}
}

// Responses 处理 Responses API 请求
func (h *Handler) Responses(c *gin.Context) {
	var request models.ResponseRequest
	if err := c.ShouldBindJSON(&request); err != nil {
		logrus.WithError(err).Error("Failed to bind response request")
		c.JSON(http.StatusBadRequest, models.NewErrorResponse(
			"Invalid request format",
			"invalid_request_error",
			"invalid_json",
		))
		return
	}

	// 验证模型
	if !h.config.IsValidModel(request.Model) {
		c.JSON(http.StatusBadRequest, models.NewErrorResponse(
			"Invalid model specified",
			"invalid_request_error",
			"model_not_found",
		))
		return
	}

	var previousMessages []models.Message
	previousID := ""
	if request.PreviousResponseID != nil {
		previousID = strings.TrimSpace(*request.PreviousResponseID)
	}
	if previousID != "" {
		stored, ok := h.responseStore.Get(previousID)
		if !ok {
			c.JSON(http.StatusBadRequest, models.NewErrorResponse(
				"previous_response_id not found; include prior output items in input instead",
				"invalid_request_error",
				"previous_response_id",
			))
			return
		}
		previousMessages = stored
	}

	chatRequest, adapter, err := services.BuildChatCompletionRequestFromResponse(&request)
	if err != nil {
		c.JSON(http.StatusBadRequest, models.NewErrorResponse(
			err.Error(),
			"invalid_request_error",
			"invalid_input",
		))
		return
	}

	chatRequest.MaxTokens = models.ValidateMaxTokens(chatRequest.Model, chatRequest.MaxTokens)
	if len(previousMessages) > 0 {
		chatRequest.Messages = mergeStoredMessages(chatRequest.Messages, previousMessages)
	}

	if chatRequest.Stream {
		chatGenerator, err := h.cursorService.ChatCompletion(c.Request.Context(), chatRequest)
		if err != nil {
			logrus.WithError(err).Error("Failed to create response stream")
			middleware.HandleError(c, err)
			return
		}
		responseID := utils.GenerateResponseID()
		accumulator := newStreamAccumulator()
		wrapped := teeChatGenerator(c.Request.Context(), chatGenerator, accumulator)
		utils.SafeStreamWrapper(func(ctx *gin.Context, gen <-chan interface{}, model string) {
			services.StreamResponse(ctx, gen, &request, adapter, responseID)
		}, c, wrapped, chatRequest.Model)
		if h.responseStore != nil && accumulator.okToStore() {
			assistant := accumulator.message()
			conversation := buildConversationForStore(chatRequest.Messages, assistant)
			h.responseStore.Put(responseID, conversation)
		}
		return
	}

	resp, err := h.cursorService.ChatCompletionNonStream(c.Request.Context(), chatRequest)
	if err != nil {
		logrus.WithError(err).Error("Failed to create non-stream response")
		middleware.HandleError(c, err)
		return
	}

	if len(resp.Choices) == 0 {
		c.JSON(http.StatusInternalServerError, models.NewErrorResponse(
			"Empty response from upstream",
			"internal_error",
			"empty_response",
		))
		return
	}
	output, outputText := services.BuildResponseOutputFromMessage(resp.Choices[0].Message, adapter)
	usage := services.BuildResponseUsage(resp.Usage)
	response := services.BuildCompletedResponse(&request, output, outputText, usage)
	if h.responseStore != nil {
		conversation := buildConversationForStore(chatRequest.Messages, resp.Choices[0].Message)
		h.responseStore.Put(response.ID, conversation)
	}
	c.JSON(http.StatusOK, response)
}

// ServeDocs 服务API文档页面
func (h *Handler) ServeDocs(c *gin.Context) {
	c.Data(http.StatusOK, "text/html; charset=utf-8", h.docsContent)
}

// Health 健康检查
func (h *Handler) Health(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"status":    "ok",
		"timestamp": time.Now().Unix(),
		"version":   "go-1.0.0",
	})
}