Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions changelog/unreleased/freemilk-provider.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
### English

- Add an experimental FreeMilk provider. Sign in with Google; the model list comes from the account, and chat uses the hosted free models.

### 中文

- 新增实验性 FreeMilk 供应商。使用 Google 登录,模型列表从账号获取,聊天走托管的免费模型。
Binary file added frontend/src/assets/freemilk-mark.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 3 additions & 1 deletion frontend/src/components/AddAccountModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ const labelKeys: Record<string, string> = {
'minimaxcode-global': 'accountTypeMiniMaxCodeGlobal',
'opencode-go': 'accountTypeOpenCode',
'opencode-zen': 'accountTypeOpenCode',
'freemilk-global': 'accountTypeFreeMilk',
}

const hintKeys: Record<string, string> = {
Expand All @@ -100,6 +101,7 @@ const hintKeys: Record<string, string> = {
'minimaxcode-global': 'accountTypeMiniMaxCodeGlobalHint',
'opencode-go': 'accountTypeOpenCodeGoHint',
'opencode-zen': 'accountTypeOpenCodeZenHint',
'freemilk-global': 'accountTypeFreeMilkHint',
}

async function loadProviderOptions(): Promise<ProviderOption[]> {
Expand Down Expand Up @@ -217,7 +219,7 @@ export function AddAccountModal({ isOpen, onClose, onAdded }: Props) {
// Command Code has no browser login (a pasted user_… key is the only auth),
// so the wizard opens on the PAT tab instead of the browser tab.
const hasBrowserLogin = activeOption?.descriptor.capabilities?.browser_login !== false
const showCallbackPaste = activeOption?.provider === 'trae' || activeOption?.provider === 'devin' || activeOption?.provider === 'codex' || activeOption?.provider === 'codearts'
const showCallbackPaste = activeOption?.provider === 'trae' || activeOption?.provider === 'devin' || activeOption?.provider === 'codex' || activeOption?.provider === 'codearts' || activeOption?.provider === 'freemilk'
const busy = phase === 'busy' || phase === 'polling'
const settingsLocked = Boolean(createdId.current) || busy
const isDone = phase === 'done'
Expand Down
20 changes: 20 additions & 0 deletions frontend/src/components/FreeMilkMark.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import freemilkMark from '@/assets/freemilk-mark.png'

type Props = {
size?: number
className?: string
}

// FreeMilk brand mark, taken from the Mac app icon.
export function FreeMilkMark({ size = 16, className = '' }: Props) {
return (
<img
src={freemilkMark}
alt=""
width={size}
height={size}
className={`block shrink-0 rounded-[22%] ${className}`.trim()}
draggable={false}
/>
)
}
4 changes: 4 additions & 0 deletions frontend/src/components/ProviderMark.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { CommandMark } from '@/components/CommandMark'
import { CodeArtsMark } from '@/components/CodeArtsMark'
import { CodexMark } from '@/components/CodexMark'
import { DevinMark } from '@/components/DevinMark'
import { FreeMilkMark } from '@/components/FreeMilkMark'
import { DoubaoworkMark } from '@/components/DoubaoworkMark'
import { KiroMark } from '@/components/KiroMark'
import { KimiMark } from '@/components/KimiMark'
Expand Down Expand Up @@ -65,5 +66,8 @@ export function ProviderMark({ provider, size = 16, className = '' }: Props) {
if (id === 'opencode') {
return <OpenCodeMark size={size} className={className} />
}
if (id === 'freemilk') {
return <FreeMilkMark size={size} className={className} />
}
return <QoderMark size={size} className={className} />
}
4 changes: 4 additions & 0 deletions frontend/src/i18n/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1052,6 +1052,8 @@ export const messages: Record<Lang, Dict> = {
accountTypeOpenCodeGoHint: 'Experimental. Paste an OpenCode API key. This account calls the Go subscription gateway.',
accountTypeOpenCodeZen: 'OpenCode Zen',
accountTypeOpenCodeZenHint: 'Experimental. Paste an OpenCode API key. This account calls the Zen pay-as-you-go gateway.',
accountTypeFreeMilk: 'FreeMilk',
accountTypeFreeMilkHint: 'Experimental. Sign in with Google. Chat uses the hosted free models.',
accountTypeCodexGlobal: 'Codex',
accountTypeCodexGlobalHint: 'OpenAI Codex via Codex CLI OAuth, Sign in with ChatGPT, or an imported credential',
accountTypeZhipuCN: 'Zhipu GLM',
Expand Down Expand Up @@ -2311,6 +2313,8 @@ export const messages: Record<Lang, Dict> = {
accountTypeOpenCodeGoHint: '实验性。粘贴 OpenCode API Key。此账号走 Go 订阅网关。',
accountTypeOpenCodeZen: 'OpenCode Zen',
accountTypeOpenCodeZenHint: '实验性。粘贴 OpenCode API Key。此账号走 Zen 按量网关。',
accountTypeFreeMilk: 'FreeMilk',
accountTypeFreeMilkHint: '实验性。使用 Google 登录。聊天走托管的免费模型。',
accountTypeCodexGlobal: 'Codex',
accountTypeCodexGlobalHint: 'OpenAI Codex:Codex CLI OAuth、Sign in with ChatGPT,或导入凭证',
accountTypeZhipuCN: '智谱 GLM',
Expand Down
8 changes: 8 additions & 0 deletions frontend/src/lib/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ export function isOpenCodeProvider(provider?: string) {
return String(provider || '').toLowerCase() === 'opencode'
}

export function isFreeMilkProvider(provider?: string) {
return String(provider || '').toLowerCase() === 'freemilk'
}

export function isMetaProvider(provider?: string) {
const value = String(provider || '').toLowerCase()
return value === 'meta' || value === 'muse'
Expand All @@ -68,6 +72,7 @@ export function accountProviderFamilyLabel(
if (isDoubaoworkProvider(providerID)) return 'Doubao Work'
if (isMiniMaxCodeProvider(providerID)) return 'MiniMax Code'
if (isOpenCodeProvider(providerID)) return 'OpenCode'
if (isFreeMilkProvider(providerID)) return 'FreeMilk'
if (isMetaProvider(providerID)) return 'Muse (Meta)'
if (isQoderProvider(providerID)) return 'Qoder'
return provider || t('account')
Expand Down Expand Up @@ -113,6 +118,9 @@ export function accountProviderLabel(
if (isOpenCodeProvider(providerID)) {
return regionID === 'zen' ? t('accountTypeOpenCodeZen') : t('accountTypeOpenCodeGo')
}
if (isFreeMilkProvider(providerID)) {
return t('accountTypeFreeMilk')
}
if (isMetaProvider(providerID)) {
return t('accountTypeMetaGlobal')
}
Expand Down
2 changes: 2 additions & 0 deletions internal/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (
"github.com/caigee-cmd/cli2api/internal/providers/command"
"github.com/caigee-cmd/cli2api/internal/providers/devin"
"github.com/caigee-cmd/cli2api/internal/providers/doubaowork"
"github.com/caigee-cmd/cli2api/internal/providers/freemilk"
"github.com/caigee-cmd/cli2api/internal/providers/kimi"
"github.com/caigee-cmd/cli2api/internal/providers/kiro"
"github.com/caigee-cmd/cli2api/internal/providers/meta"
Expand Down Expand Up @@ -145,6 +146,7 @@ func New(cfg config.Config) *App {
providerReg.Register(meta.NewClient(store).Adapter())
providerReg.Register(doubaowork.NewClient(store).Adapter())
providerReg.Register(opencode.NewClient(store).Adapter())
providerReg.Register(freemilk.NewClient(store).Adapter())
qoderClient := qoder.NewClient()
qoderClient.Bind(manager.AccountURL, manager.ProxyAPIKey)
qoderClient.SetDirect(qoder.NewDirect(store, func(ctx context.Context, accountID string) (string, error) {
Expand Down
214 changes: 214 additions & 0 deletions internal/providers/freemilk/api.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
package freemilk

import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
)

type tokenResponse struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
ExpiresIn int `json:"expires_in"`
TokenType string `json:"token_type"`
}

type accountProfile struct {
ID string `json:"id"`
Email string `json:"email"`
Name string `json:"name"`
}

type balanceResponse struct {
InitialFreeBalance float64 `json:"initial_free_balance"`
PeriodicFreeBalance float64 `json:"periodic_free_balance"`
SubscriptionBalance float64 `json:"subscription_balance"`
PurchasedBalance float64 `json:"purchased_balance"`
DailyAllowance float64 `json:"daily_allowance"`
NextRefillAt string `json:"next_refill_at"`
Limits []limitRow `json:"limits"`
}

type limitRow struct {
Key string `json:"key"`
Name string `json:"name"`
Used float64
}

func (c *Client) exchangeGoogle(ctx context.Context, client *http.Client, identityToken, deviceID string) (Credential, error) {
body := map[string]string{"identity_token": identityToken}
var token tokenResponse
if err := c.postJSON(ctx, client, deviceID, "", "/auth/google", body, &token); err != nil {
return Credential{}, err
}
return credentialFromToken(token, deviceID), nil
}

func (c *Client) refresh(ctx context.Context, client *http.Client, credential Credential) (Credential, error) {
if strings.TrimSpace(credential.RefreshToken) == "" {
return Credential{}, fmt.Errorf("freemilk refresh token missing")
}
body := map[string]string{"refresh_token": credential.RefreshToken}
var token tokenResponse
if err := c.postJSON(ctx, client, credential.DeviceID, "", "/auth/refresh", body, &token); err != nil {
return Credential{}, err
}
next := credentialFromToken(token, credential.DeviceID)
if next.RefreshToken == "" {
next.RefreshToken = credential.RefreshToken
}
next.UserID = credential.UserID
next.Email = credential.Email
next.Name = credential.Name
return next, nil
}

func (c *Client) profile(ctx context.Context, client *http.Client, credential Credential) (accountProfile, error) {
var profile accountProfile
if err := c.getJSON(ctx, client, credential, "/auth/me", &profile); err != nil {
return accountProfile{}, err
}
return profile, nil
}

func (c *Client) balance(ctx context.Context, client *http.Client, credential Credential) (balanceResponse, error) {
var balance balanceResponse
if err := c.getJSON(ctx, client, credential, "/auth/me/balance", &balance); err != nil {
return balanceResponse{}, err
}
return balance, nil
}

func credentialFromToken(token tokenResponse, deviceID string) Credential {
credential := Credential{
Format: CredentialFormat,
AccessToken: strings.TrimSpace(token.AccessToken),
RefreshToken: strings.TrimSpace(token.RefreshToken),
DeviceID: deviceID,
}
if token.ExpiresIn > 0 {
credential.ExpiresAt = time.Now().Add(time.Duration(token.ExpiresIn) * time.Second)
}
return credential
}

func (c *Client) postJSON(ctx context.Context, client *http.Client, deviceID, accessToken, path string, body, out any) error {
payload, err := json.Marshal(body)
if err != nil {
return err
}
request, err := http.NewRequestWithContext(ctx, http.MethodPost, c.apiBase+path, bytes.NewReader(payload))
if err != nil {
return err
}
request.Header.Set("Content-Type", "application/json")
applyAccountHeaders(request, deviceID, accessToken)
return doJSON(client, request, out)
}

func (c *Client) getJSON(ctx context.Context, client *http.Client, credential Credential, path string, out any) error {
request, err := http.NewRequestWithContext(ctx, http.MethodGet, c.apiBase+path, nil)
if err != nil {
return err
}
applyAccountHeaders(request, credential.DeviceID, credential.AccessToken)
return doJSON(client, request, out)
}

func applyAccountHeaders(request *http.Request, deviceID, accessToken string) {
request.Header.Set("Accept", "application/json")
request.Header.Set("Accept-Language", "en-US,en;q=0.9")
request.Header.Set("User-Agent", UserAgent)
request.Header.Set("X-Client-Type", ClientType)
request.Header.Set("X-App-Version", AppVersion)
if deviceID != "" {
request.Header.Set("X-Device-Id", deviceID)
}
if strings.TrimSpace(accessToken) != "" {
request.Header.Set("Authorization", "Bearer "+strings.TrimSpace(accessToken))
}
}

func doJSON(client *http.Client, request *http.Request, out any) error {
response, err := client.Do(request)
if err != nil {
return err
}
defer response.Body.Close()
payload, err := io.ReadAll(io.LimitReader(response.Body, 1<<20))
if err != nil {
return err
}
if response.StatusCode >= 300 {
return &upstreamError{Status: response.StatusCode, Body: string(payload)}
}
if out == nil || len(bytes.TrimSpace(payload)) == 0 {
return nil
}
if err := json.Unmarshal(payload, out); err != nil {
return fmt.Errorf("freemilk response is not json")
}
return nil
}

type upstreamError struct {
Status int
Body string
}

func (e *upstreamError) Error() string {
message := errorMessage(e.Body)
if message == "" {
return fmt.Sprintf("freemilk upstream status %d", e.Status)
}
return message
}

type hostedModelResponse struct {
ID string `json:"id"`
Name string `json:"name"`
Mode string `json:"mode"`
APIFormat string `json:"api_format"`
Tier string `json:"tier"`
ContextWindow int `json:"context_window"`
AcceptsImages bool `json:"accepts_images"`
IsDefault bool `json:"is_default"`
Limit string `json:"limit"`
}

type hostedCatalogResponse struct {
Models []hostedModelResponse `json:"models"`
}

func (c *Client) hostedCatalog(ctx context.Context, client *http.Client, credential Credential) ([]hostedModel, error) {
var catalog hostedCatalogResponse
if err := c.getJSON(ctx, client, credential, "/auth/models", &catalog); err != nil {
return nil, err
}
out := make([]hostedModel, 0, len(catalog.Models))
for _, model := range catalog.Models {
if strings.TrimSpace(model.ID) == "" || strings.TrimSpace(model.Mode) == "" {
continue
}
out = append(out, hostedModel{
ID: model.ID,
Name: firstNonEmpty(model.Name, model.ID),
Mode: model.Mode,
Format: model.APIFormat,
ContextWindow: model.ContextWindow,
Images: model.AcceptsImages,
Free: model.Tier != "premium",
Premium: model.Tier == "premium",
Reasoning: model.APIFormat == "chat_completions",
})
}
if len(out) == 0 {
return nil, fmt.Errorf("freemilk model catalog is empty")
}
return out, nil
}
Loading
Loading