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
9 changes: 9 additions & 0 deletions changelog/unreleased/aggregation-model-allowlist.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
### English

- Cross-provider model pool saves now validate every member against the provider policy. A disabled model is rejected instead of being stored as a dead route.
- An aggregated logical model is no longer listed in `/v1/models` when provider policy filters out every one of its members.

### 中文

- 保存跨 Provider 模型池时会逐个校验成员是否符合供应商策略。未启用的模型会被拒绝,不会再存成无法路由的死成员。
- 当供应商策略把所有成员都过滤掉时,聚合逻辑模型不再出现在 `/v1/models` 中。
7 changes: 7 additions & 0 deletions changelog/unreleased/provider-model-allowlist.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
### English

- A provider restricted to a selected model list no longer shows `auto`; it stays visible only while that provider keeps the full model catalog.

### 中文

- 限制为勾选模型的供应商不再显示 `auto`;只有保持完整模型目录的供应商才会保留该目录项。
7 changes: 7 additions & 0 deletions changelog/unreleased/provider-policy-settings.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
### English

- Provider-level floors, proxy, system-prompt handling, aliases, enabled models, and check-in time are now stored as one policy per provider/region. The policy is the single source of truth: account reads overlay it at runtime, saving it refreshes the live pool instead of writing the same values back to every account, and new or imported accounts inherit it automatically. Existing provider groups are seeded once at startup from their current account values without rewriting account rows.

### 中文

- 积分/百分比保底、代理、系统提示词处理、别名、可用模型和签到时间改为按供应商/区域保存的统一策略。策略是唯一事实源:账号读取时在运行时叠加,保存策略只刷新池子,不再把同一组值写回每个账号;新建或导入账号会自动继承。已有供应商分组会在启动时用现有账号值一次性生成策略,同样不写账号行。
3 changes: 2 additions & 1 deletion docs/ARCHITECTURE_SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ status: canonical
read-when: 需要快速理解后端分层、请求路径、运行时和 provider 扩展边界时
summary: 面向贡献者和 AI 的精简架构摘要;详细协议、里程碑和本地运维资料不在本文维护。
related: [AGENTS.md, CONTRIBUTING.md, docs/DESIGN.md, docs/REFACTORING.md, docs/NATIVE_PROTOCOL_REQUESTS.md]
last-updated: 2026-11-23
last-updated: 2026-11-24
---

# CLI2API 架构摘要
Expand Down Expand Up @@ -83,6 +83,7 @@ cmd/server
## 持久化和安全边界

- SQLite migration 一旦发布,SQL 字节不可修改;新增 schema 必须追加新的编号 migration。
- 供应商级设置(积分/百分比保底、代理、系统提示词处理、别名、可用模型、签到时间)按 `provider + region` 存在 `app_secrets` 的 `provider_settings_v1` 中。服务启动时只为已有账号的 provider region 补一次缺失策略,之后 `store.Get/List` 在读取时把策略叠加成 effective account,供 runtime、目录、签到和账号视图使用;账号行只作为身份与调度的事实源,历史供应商列即使存在也被策略覆盖。保存供应商策略只能刷新 live pool,不得把同一组值批量写回账号行。跨 Provider 聚合模型写入时也必须用同一策略校验成员模型,不能绕过控制台模型列表保存已禁用模型。
- 控制台密钥、客户端密钥和上游凭证是不同的认证边界,不能混用。
- API 返回中不得暴露原始 token、auth blob、密钥明文、host 路径或凭证 payload。
- 管理接口必须认证;默认只绑定本机,不要直接暴露 host 端口到公网。
Expand Down
153 changes: 153 additions & 0 deletions internal/accounts/provider_policy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
package accounts

import (
"fmt"
"strings"

"github.com/caigee-cmd/cli2api/internal/providers"
)

// ProviderPolicySecret stores the console's provider-wide settings. The value
// is a JSON envelope keyed by ProviderPolicyKey, so every account of the same
// provider and region receives the same routing and safety policy.
const ProviderPolicySecret = "provider_settings_v1"

// ProviderPolicy is the provider-wide counterpart of the per-account settings.
// CreditFloor and PercentFloor are optional: nil inherits the process-global
// floor, while a non-nil value (including zero) overrides it for the provider.
type ProviderPolicy struct {
Provider string `json:"provider"`
Region string `json:"region"`
CreditFloor *float64 `json:"credit_floor"`
PercentFloor *float64 `json:"percent_floor"`
ProxyURL string `json:"proxy_url,omitempty"`
DropSystemPrompt *bool `json:"drop_system_prompt,omitempty"`
ModelAliases map[string]string `json:"model_aliases,omitempty"`
EnabledModels []string `json:"enabled_models,omitempty"`
ModelsRestricted bool `json:"models_restricted,omitempty"`
CheckinTime string `json:"checkin_time,omitempty"`
// CheckinAuto defaults to true when absent so existing policies switch to
// the upstream window + 1 hour without a migration. Manual mode keeps the
// operator's CheckinTime.
CheckinAuto *bool `json:"checkin_auto,omitempty"`
}

func (policy ProviderPolicy) CheckinScheduleAuto() bool {
return policy.CheckinAuto == nil || *policy.CheckinAuto
}

func ProviderPolicyKey(provider, region string) string {
return NormalizeProviderFamily(provider) + ":" + NormalizeRegion(region)
}

// NormalizeProviderPolicy canonicalizes the provider/region pair and validates
// the same routing, floor, proxy, and check-in rules used for accounts.
func NormalizeProviderPolicy(policy ProviderPolicy) (ProviderPolicy, error) {
descriptor, parsedRegion, err := providers.Resolve(policy.Provider, policy.Region)
if err != nil {
return ProviderPolicy{}, err
}
policy.Provider = descriptor.ID
policy.Region = parsedRegion.ID
if policy.CreditFloor != nil && *policy.CreditFloor < 0 {
return ProviderPolicy{}, fmt.Errorf("credit_floor must be >= 0")
}
if policy.PercentFloor != nil && (*policy.PercentFloor < 0 || *policy.PercentFloor > 100) {
return ProviderPolicy{}, fmt.Errorf("percent_floor must be between 0 and 100")
}
policy.ProxyURL = strings.TrimSpace(policy.ProxyURL)
if err := ValidateAccountProxy(policy.Provider, policy.Region, policy.ProxyURL); err != nil {
return ProviderPolicy{}, err
}
aliases, enabled, err := NormalizeAccountRouting(policy.ModelAliases, policy.EnabledModels)
if err != nil {
return ProviderPolicy{}, err
}
policy.ModelAliases = aliases
policy.EnabledModels = enabled
policy.ModelsRestricted = len(enabled) > 0
if policy.CheckinTime = strings.TrimSpace(policy.CheckinTime); policy.CheckinTime != "" {
policy.CheckinTime, err = NormalizeCheckinTime(policy.CheckinTime)
if err != nil {
return ProviderPolicy{}, err
}
if _, supported := providers.CheckinFor(policy.Provider, policy.Region); !supported {
return ProviderPolicy{}, fmt.Errorf("check-in is not available for this provider and region")
}
}
return policy, nil
}

// ApplyProviderPolicy overlays an account with its provider-scoped settings in
// memory. The account keeps its own name, concurrency, priority, credential,
// and enabled state; only fields owned by the provider policy change. This is
// never written back to SQLite: the provider policy stays the source of truth.
func ApplyProviderPolicy(account *Account, policy ProviderPolicy) {
if account == nil {
return
}
account.CreditFloor = cloneFloat(policy.CreditFloor)
account.PercentFloor = cloneFloat(policy.PercentFloor)
account.ProxyURL = strings.TrimSpace(policy.ProxyURL)
account.DropSystemPrompt = DefaultDropSystemPrompt(account.Provider, policy.DropSystemPrompt)
account.ModelAliases = cloneAliases(policy.ModelAliases)
account.EnabledModels = cloneStrings(policy.EnabledModels)
account.ModelsRestricted = len(policy.EnabledModels) > 0
// The effective check-in time is resolved for provider+region, not copied
// into account storage. Auto mode ignores the stored clock and uses the
// upstream window + 1 hour; manual mode keeps the operator's value. The old
// provider-only secret could not distinguish Qoder global/CN or WorkBuddy
// CN/global.
if policy.CheckinScheduleAuto() {
account.CheckinTime = ""
} else {
account.CheckinTime = strings.TrimSpace(policy.CheckinTime)
}
if account.Provider == "workbuddy" {
account.WorkBuddyCheckinTime = account.CheckinTime
}
}

// StripProviderOwnedSettings removes fields owned by a provider policy from an
// account PATCH. Identity, concurrency, priority, enabled state, and automatic
// check-in opt-in stay account-scoped.
func StripProviderOwnedSettings(input UpdateAccount) UpdateAccount {
input.CreditFloor = nil
input.SetCreditFloor = false
input.PercentFloor = nil
input.SetPercentFloor = false
input.ProxyURL = nil
input.DropSystemPrompt = nil
input.ModelAliases = nil
input.EnabledModels = nil
input.SetModelRouting = false
input.CheckinTime = nil
input.WorkBuddyCheckinTime = nil
return input
}

func cloneFloat(value *float64) *float64 {
if value == nil {
return nil
}
copied := *value
return &copied
}

func cloneAliases(value map[string]string) map[string]string {
if len(value) == 0 {
return nil
}
out := make(map[string]string, len(value))
for key, item := range value {
out[key] = item
}
return out
}

func cloneStrings(value []string) []string {
if len(value) == 0 {
return nil
}
return append([]string(nil), value...)
}
7 changes: 7 additions & 0 deletions internal/accounts/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ type AccountStore interface {
Create(ctx context.Context, input CreateAccount) (Account, error)
Get(ctx context.Context, id string) (Account, error)
List(ctx context.Context) ([]Account, error)
// ListRaw returns the stored account rows without overlaying provider
// policies. Console code uses it to compare the old effective policy with a
// new one; runtime and account views must keep using List/Get.
ListRaw(ctx context.Context) ([]Account, error)
Update(ctx context.Context, id string, input UpdateAccount) error
Delete(ctx context.Context, id string) error
SaveCredential(ctx context.Context, accountID, authType string, credential NativeCredential) error
Expand All @@ -55,6 +59,9 @@ type AccountStore interface {
GetSecret(ctx context.Context, name string) (string, bool, error)
SetSecret(ctx context.Context, name, value string) error
SetSecretOrEmpty(ctx context.Context, name, value string) error
ListProviderPolicies(ctx context.Context) ([]ProviderPolicy, error)
GetProviderPolicy(ctx context.Context, provider, region string) (ProviderPolicy, bool, error)
SaveProviderPolicy(ctx context.Context, policy ProviderPolicy) error
WorkBuddyCheckinTimeDefault(ctx context.Context) string
GetModelContext(ctx context.Context, modelID string) (int, bool, error)
SetModelContext(ctx context.Context, modelID string, contextLength int) error
Expand Down
5 changes: 5 additions & 0 deletions internal/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,11 @@ func New(cfg config.Config) *App {
TemplatePath: cfg.PlainTemplatePath, ProxyAPIKey: proxyAPIKey, ProxyURL: proxyURL,
MaxLogWriters: io.MultiWriter(os.Stderr, ring),
}, store, nil)
// Existing provider-region groups migrate to provider policies before the
// runtime starts, so workers see the same unified values on first boot.
if err := appsvc.NewProviderSettings(manager).SeedMissing(context.Background()); err != nil {
log.Printf("[provider-settings] seed existing groups: %v", err)
}
if err := manager.Start(context.Background()); err != nil {
panic(err)
}
Expand Down
59 changes: 59 additions & 0 deletions internal/app/provider_policy_seed_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package app_test

import (
"context"
"path/filepath"
"testing"

"github.com/caigee-cmd/cli2api/internal/accounts"
"github.com/caigee-cmd/cli2api/internal/app"
"github.com/caigee-cmd/cli2api/internal/config"
sqlstore "github.com/caigee-cmd/cli2api/internal/store"
)

func TestAppSeedsProviderPolicyForExistingAccountWithoutRewritingIt(t *testing.T) {
ctx := context.Background()
dataDir := t.TempDir()
store, err := sqlstore.OpenStore(filepath.Join(dataDir, "qoder.db"))
if err != nil {
t.Fatal(err)
}
account, err := store.Create(ctx, accounts.CreateAccount{
Name: "existing", Provider: "trae", Region: "cn", Enabled: false,
ProxyURL: "http://user:secret@example.test:8080",
})
if err != nil {
_ = store.Close()
t.Fatal(err)
}
if err := store.Close(); err != nil {
t.Fatal(err)
}

a := app.New(config.Config{ProxyAPIKey: "key", QoderHome: t.TempDir(), DataDir: dataDir, RuntimeDir: t.TempDir()})
defer a.Close()

policy, found, err := a.Manager.Store().GetProviderPolicy(ctx, "trae", "cn")
if err != nil || !found {
t.Fatalf("seeded policy: found=%v err=%v", found, err)
}
if policy.ProxyURL != "http://user:secret@example.test:8080" {
t.Fatalf("seeded policy proxy = %q", policy.ProxyURL)
}

raw, err := a.Manager.Store().ListRaw(ctx)
if err != nil {
t.Fatal(err)
}
if len(raw) != 1 || raw[0].ID != account.ID || raw[0].ProxyURL != "http://user:secret@example.test:8080" {
t.Fatalf("startup seed rewrote account row: %#v", raw)
}

effective, err := a.Manager.Store().Get(ctx, account.ID)
if err != nil {
t.Fatal(err)
}
if effective.ProxyURL != "http://user:secret@example.test:8080" {
t.Fatalf("effective account proxy = %q", effective.ProxyURL)
}
}
Loading
Loading