File size: 17,149 Bytes
e48a2d8 | 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 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 | // Package freemodel 免登录免费模型层:把 OpenCode Zen / Kilo 公共网关的免费模型
// 接进本网关的 OpenAI 兼容接口。
//
// 这一层不碰 WorkBuddy 账号池:请求命中 free:<provider>/<model> 时直接转发到上游,
// 不选号、不扣积分、不写 pool 状态。请求整形移植自 dsh-our-free-model 的 o2a 层
// (opencode2api 的 Go 实现的 JS 移植),只保留 chat 线所需的部分。
package freemodel
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"regexp"
"strings"
"sync"
"time"
"github.com/misakano7545/workbuddy2api-panel/internal/extstore"
)
// Prefix 免费模型在 /v1/models 与请求里的前缀。
const Prefix = "free:"
const (
listTimeout = 15 * time.Second
headerTimeout = 120 * time.Second
turnTimeout = 300 * time.Second
maxErrorBytes = 64 << 10
maxBodyRewrite = 64 << 20
)
// Client 免费模型层。
type Client struct {
store *extstore.Store
http *http.Client
refreshMu sync.Mutex
}
// New 构建客户端。store 为空时只读默认值(不会保存)。
func New(store *extstore.Store) *Client {
return &Client{
store: store,
http: newFreeHTTPClient(),
}
}
// Store 返回底层存储。
func (c *Client) Store() *extstore.Store { return c.store }
// FreeModelID 拼出对外模型名。
func FreeModelID(provider, id string) string { return Prefix + provider + "/" + id }
// ParseModel 拆出 provider 与上游 model id。
func ParseModel(model string) (provider, id string, ok bool) {
model = strings.TrimSpace(model)
if !strings.HasPrefix(model, Prefix) {
return "", "", false
}
rest := strings.TrimPrefix(model, Prefix)
provider, id, ok = strings.Cut(rest, "/")
if !ok || provider == "" || id == "" {
return "", "", false
}
if provider != extstore.ProviderOpenCode && provider != extstore.ProviderKilo {
return "", "", false
}
return provider, id, true
}
// Enabled 免费模型层是否可用。
func (c *Client) Enabled() bool {
if c == nil || c.store == nil {
return false
}
return c.store.Snapshot().Free.Enabled
}
// Handles 报告 model 是否属于本层且已启用。
func (c *Client) Handles(model string) bool {
if c == nil || c.store == nil {
return false
}
provider, id, ok := ParseModel(model)
if !ok {
return false
}
return c.store.Snapshot().FreeModelEnabled(provider, id)
}
// Model 一个对外可用的免费模型(带渠道信息)。
type Model struct {
Provider string
ProviderLabel string
ID string
Name string
}
// Models 返回当前已启用(并已发现)的免费模型,供 /v1/models 汇总。
// 只读缓存:清单由启动后的后台刷新与面板「刷新模型清单」维护,避免模型列表
// 接口被上游超时拖住(首次启动 3 秒后就会有清单)。
func (c *Client) Models(ctx context.Context) []Model {
if c == nil || c.store == nil {
return nil
}
snap := c.store.Snapshot()
if !snap.Free.Enabled {
return nil
}
var out []Model
for _, p := range snap.Free.Providers {
if !p.Enabled {
continue
}
for _, m := range p.Models {
if m.Enabled {
out = append(out, Model{Provider: p.Name, ProviderLabel: ProviderLabel(p), ID: m.ID, Name: m.Name})
}
}
}
return out
}
// ProviderLabel 返回渠道显示名(Store 已带 Label,这里只做兜底)。
func ProviderLabel(p extstore.FreeProvider) string {
if strings.TrimSpace(p.Label) != "" {
return p.Label
}
switch p.Type {
case extstore.TypeOpenCode:
return "OpenCode Zen"
case extstore.TypeKilo:
return "Kilo"
}
return p.Name
}
// Refresh 拉取一次上游模型清单并合并进存储。
func (c *Client) Refresh(ctx context.Context, provider string) (int, error) {
if c == nil || c.store == nil {
return 0, fmt.Errorf("free model store not configured")
}
snap := c.store.Snapshot()
p, ok := snap.Provider(provider)
if !ok {
return 0, fmt.Errorf("unknown provider %q", provider)
}
if !p.Enabled {
return 0, fmt.Errorf("provider %s is disabled", provider)
}
c.refreshMu.Lock()
defer c.refreshMu.Unlock()
models, err := c.listModels(ctx, p)
if err != nil {
return 0, err
}
if err := c.store.MergeModels(p.Name, models); err != nil {
return 0, err
}
return len(models), nil
}
// RefreshAll 刷新所有已启用渠道。
func (c *Client) RefreshAll(ctx context.Context) {
if c == nil || c.store == nil {
return
}
snap := c.store.Snapshot()
if !snap.Free.Enabled {
return
}
for _, p := range snap.Free.Providers {
if p.Enabled {
_, _ = c.Refresh(ctx, p.Name)
}
}
}
// RunRefresh 启动后台清单刷新:启动 3 秒后一次,之后每 6 小时一次。
// 上游清单会随改版增删模型;没有它,进程重启后要么空清单、要么永远停在旧快照。
func (c *Client) RunRefresh(ctx context.Context) {
if c == nil || c.store == nil {
return
}
timer := time.NewTimer(3 * time.Second)
defer timer.Stop()
select {
case <-ctx.Done():
return
case <-timer.C:
}
c.RefreshAll(ctx)
ticker := time.NewTicker(6 * time.Hour)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
c.RefreshAll(ctx)
}
}
}
// listModels 拉取一个渠道的模型清单,并按渠道的 FreeFilter 过滤。
func (c *Client) listModels(ctx context.Context, p extstore.FreeProvider) ([]extstore.FreeModel, error) {
ctx, cancel := context.WithTimeout(ctx, listTimeout)
defer cancel()
url := strings.TrimRight(p.BaseURL, "/") + p.ModelsPath
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
req.Header.Set("accept", "application/json")
c.applyProviderHeaders(req, p)
resp, err := c.http.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
raw, err := io.ReadAll(io.LimitReader(resp.Body, 16<<20))
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s listing: HTTP %d: %s", p.Name, resp.StatusCode, truncate(string(raw), 300))
}
var doc struct {
Data []struct {
ID string `json:"id"`
Name string `json:"name"`
IsFree bool `json:"isFree"`
} `json:"data"`
}
if err := json.Unmarshal(raw, &doc); err != nil {
return nil, fmt.Errorf("%s listing: %w", p.Name, err)
}
out := make([]extstore.FreeModel, 0, len(doc.Data))
for _, row := range doc.Data {
if row.ID == "" {
continue
}
if !providerFreeFilter(p, row.ID, row.IsFree) {
continue
}
out = append(out, extstore.FreeModel{ID: row.ID, Name: row.Name, Enabled: true})
}
return out, nil
}
func providerFreeFilter(p extstore.FreeProvider, id string, isFree bool) bool {
switch p.FreeFilter {
case "all":
return true
case "free-suffix":
return isOpenCodeFree(id)
case "is-free":
return isFree
default:
return true
}
}
// applyProviderHeaders 统一设置渠道请求头(清单与对话共用)。
func (c *Client) applyProviderHeaders(req *http.Request, p extstore.FreeProvider) {
switch p.Type {
case extstore.TypeOpenCode:
req.Header.Set("authorization", "Bearer public")
req.Header.Set("user-agent", clientUA)
case extstore.TypeKilo:
req.Header.Set("user-agent", "dsh-our-free-model")
req.Header.Set("http-referer", "https://kilo.ai/")
req.Header.Set("x-title", "Our Free Model")
default:
req.Header.Set("user-agent", "wb2api-freemodel")
}
if p.AuthHeader != "" {
req.Header.Set(p.AuthHeader, p.AuthValue)
}
for k, v := range p.Headers {
if strings.TrimSpace(k) != "" {
req.Header.Set(k, v)
}
}
}
// ── 免费 id 判定 ────────────────────────────────────────────────────────────
var openCodeAlwaysFree = map[string]bool{
"big-pickle": true,
// 这两条在 2026-10-31 的上游改版里下线过;保留判定,上游复活即可用。
"union-alpha": true,
"space-bunny-free": true,
}
// freeIDSegment 与 dsh 的 isFreeLane 同口径:free 必须是独立分段
// (-free / _free / .free / :free,也允许出现在中间),不能是 freedom 这类子串。
var freeIDSegment = regexp.MustCompile(`(?:^|[-_.:])free(?:$|[-_.:])`)
func isOpenCodeFree(id string) bool {
id = strings.TrimSpace(id)
if id == "" {
return false
}
if openCodeAlwaysFree[id] {
return true
}
return freeIDSegment.MatchString(strings.ToLower(id))
}
// ── 请求转发 ────────────────────────────────────────────────────────────────
// ServeChat 处理一条命中免费模型层的 /v1/chat/completions 请求。
// body 是已经读出的原始请求体;exposed 是客户端请求的对外模型名。
func (c *Client) ServeChat(w http.ResponseWriter, r *http.Request, body []byte, exposed string) {
c.ServeChatEcho(w, r, body, exposed, exposed)
}
// ServeChatEcho 同 ServeChat,但响应里的 model 用 echo 覆写(自定义模型映射时
// 客户端请求名与免费模型名不同,响应必须回显客户端自己那个名字)。
func (c *Client) ServeChatEcho(w http.ResponseWriter, r *http.Request, body []byte, exposed, echo string) {
provider, model, ok := ParseModel(exposed)
if !ok {
writeOpenAIError(w, http.StatusBadRequest, "model_not_found", "unknown free model: "+exposed)
return
}
if !c.Handles(exposed) {
writeOpenAIError(w, http.StatusBadRequest, "model_not_found",
"free model is disabled in the panel: "+exposed)
return
}
if strings.TrimSpace(echo) == "" {
echo = exposed
}
snap := c.store.Snapshot()
p, ok := snap.Provider(provider)
if !ok {
writeOpenAIError(w, http.StatusBadRequest, "model_not_found", "unknown free provider: "+provider)
return
}
switch p.Type {
case extstore.TypeOpenCode:
c.serveOpenCodeChat(w, r, p, model, exposed, echo, body)
default:
c.serveOpenAIChat(w, r, p, model, exposed, echo, body)
}
}
// serveOpenAIChat 任意 OpenAI 兼容渠道(Kilo / 自定义公共端点)的透明转发。
func (c *Client) serveOpenAIChat(w http.ResponseWriter, r *http.Request, p extstore.FreeProvider, model, exposed, echo string, body []byte) {
var obj map[string]any
if err := json.Unmarshal(body, &obj); err != nil {
writeOpenAIError(w, http.StatusBadRequest, "invalid_request_error", "invalid JSON body: "+err.Error())
return
}
obj["model"] = model
out, err := json.Marshal(obj)
if err != nil {
writeOpenAIError(w, http.StatusBadRequest, "invalid_request_error", err.Error())
return
}
ctx, cancel := context.WithTimeout(r.Context(), turnTimeout)
defer cancel()
url := strings.TrimRight(p.BaseURL, "/") + p.ChatPath
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(out))
if err != nil {
writeOpenAIError(w, http.StatusBadGateway, "upstream_error", err.Error())
return
}
req.Header.Set("content-type", "application/json")
req.Header.Set("accept", "text/event-stream")
c.applyProviderHeaders(req, p)
resp, err := c.http.Do(req)
if err != nil {
writeOpenAIError(w, http.StatusBadGateway, "upstream_error", "free upstream: "+err.Error())
return
}
defer resp.Body.Close()
// 原样透传内容,只把上游真实模型名改回客户端请求的 free: 名。
copyUpstreamResponseRewritten(w, resp, nil, echo)
}
func (c *Client) serveOpenCodeChat(w http.ResponseWriter, r *http.Request, p extstore.FreeProvider, model, exposed, echo string, body []byte) {
var obj map[string]any
if err := json.Unmarshal(body, &obj); err != nil {
writeOpenAIError(w, http.StatusBadRequest, "invalid_request_error", "invalid JSON body: "+err.Error())
return
}
obj["model"] = model
session := sessionFor(r, obj)
project := projectID(r, session)
renames := applyFingerprint(obj, model, session)
out, err := json.Marshal(obj)
if err != nil {
writeOpenAIError(w, http.StatusBadRequest, "invalid_request_error", err.Error())
return
}
ctx, cancel := context.WithTimeout(r.Context(), turnTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(p.BaseURL, "/")+p.ChatPath, bytes.NewReader(out))
if err != nil {
writeOpenAIError(w, http.StatusBadGateway, "upstream_error", err.Error())
return
}
for k, v := range gatewayHeaders(session, project) {
req.Header.Set(k, v)
}
// 官方指纹头之后允许渠道额外覆盖(自定义 Headers / AuthHeader)。
c.applyProviderHeaders(req, p)
resp, err := c.http.Do(req)
if err != nil {
writeOpenAIError(w, http.StatusBadGateway, "upstream_error", "free upstream: "+err.Error())
return
}
defer resp.Body.Close()
copyUpstreamResponseRewritten(w, resp, renames, echo)
}
// copyUpstreamResponseRewritten 透传 OpenCode 响应,并把工具名/模型名还原。
func copyUpstreamResponseRewritten(w http.ResponseWriter, resp *http.Response, renames *renameMap, exposed string) {
contentType := resp.Header.Get("content-type")
isSSE := strings.Contains(strings.ToLower(contentType), "text/event-stream")
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
raw, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBytes))
w.Header().Set("content-type", "application/json")
w.WriteHeader(resp.StatusCode)
_, _ = w.Write(raw)
return
}
if !isSSE {
raw, err := io.ReadAll(io.LimitReader(resp.Body, maxBodyRewrite))
if err != nil {
writeOpenAIError(w, http.StatusBadGateway, "upstream_error", "read upstream: "+err.Error())
return
}
rewritten := rewriteJSONPayload(raw, renames, exposed)
w.Header().Set("content-type", "application/json")
w.WriteHeader(resp.StatusCode)
_, _ = w.Write(rewritten)
return
}
copyHeaders(w, resp)
w.Header().Set("content-type", "text/event-stream; charset=utf-8")
w.Header().Set("cache-control", "no-cache")
w.Header().Set("x-accel-buffering", "no")
w.WriteHeader(resp.StatusCode)
flusher, _ := w.(http.Flusher)
reader := bufio.NewReaderSize(resp.Body, 64<<10)
for {
line, err := reader.ReadBytes('\n')
if len(line) > 0 {
trimmed := bytes.TrimRight(line, "\r\n")
if bytes.HasPrefix(trimmed, []byte("data:")) {
payload := bytes.TrimSpace(trimmed[len("data:"):])
if len(payload) > 0 && !bytes.Equal(payload, []byte("[DONE]")) {
payload = rewriteJSONPayload(payload, renames, exposed)
}
_, _ = w.Write([]byte("data: "))
_, _ = w.Write(payload)
_, _ = w.Write([]byte("\n\n"))
} else {
_, _ = w.Write(line)
if !bytes.HasSuffix(line, []byte("\n")) {
_, _ = w.Write([]byte("\n"))
}
}
if flusher != nil {
flusher.Flush()
}
}
if err != nil {
if err != io.EOF {
// 流中断:写一条协议内错误帧,客户端不会把它当成正常结束。
_, _ = w.Write([]byte("data: {\"error\":{\"message\":\"free upstream stream interrupted: " +
jsonEscape(err.Error()) + "\",\"type\":\"upstream_error\"}}\n\n"))
if flusher != nil {
flusher.Flush()
}
}
return
}
}
}
func rewriteJSONPayload(raw []byte, renames *renameMap, exposed string) []byte {
var obj map[string]any
if err := json.Unmarshal(raw, &obj); err != nil {
return raw
}
restoreResponse(obj, renames, exposed)
out, err := json.Marshal(obj)
if err != nil {
return raw
}
return out
}
func restoreResponse(obj map[string]any, renames *renameMap, exposed string) {
if exposed != "" {
obj["model"] = exposed
}
if renames == nil {
return
}
choices, _ := obj["choices"].([]any)
for _, rawChoice := range choices {
choice, _ := rawChoice.(map[string]any)
if choice == nil {
continue
}
for _, key := range []string{"delta", "message"} {
holder, _ := choice[key].(map[string]any)
if holder == nil {
continue
}
restoreToolCalls(holder, renames)
if fc, ok := holder["function_call"].(map[string]any); ok {
if name, ok := fc["name"].(string); ok {
fc["name"] = renames.resolve(name)
}
}
}
}
// 非流式的 responses 形状兜底(output 里可能带 function_call)。
restoreToolCalls(obj, renames)
}
func restoreToolCalls(holder map[string]any, renames *renameMap) {
calls, _ := holder["tool_calls"].([]any)
for _, rawCall := range calls {
call, _ := rawCall.(map[string]any)
fn, _ := call["function"].(map[string]any)
if fn == nil {
continue
}
if name, ok := fn["name"].(string); ok {
fn["name"] = renames.resolve(name)
}
}
}
func copyHeaders(w http.ResponseWriter, resp *http.Response) {
for _, key := range []string{"retry-after", "x-request-id"} {
if v := resp.Header.Get(key); v != "" {
w.Header().Set(key, v)
}
}
}
func writeOpenAIError(w http.ResponseWriter, status int, code, msg string) {
w.Header().Set("content-type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(map[string]any{
"error": map[string]any{"message": msg, "type": code, "code": code},
})
}
func truncate(s string, n int) string {
if len(s) <= n {
return s
}
return s[:n]
}
func jsonEscape(s string) string {
b, _ := json.Marshal(s)
if len(b) >= 2 {
return string(b[1 : len(b)-1])
}
return s
}
|