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

- Add a configurable credit floor (`CLI2API_CREDIT_FLOOR`, default `0` = disabled) so accounts below the threshold are skipped for paid models while remaining eligible for free models.
- Allow a per-account `credit_floor` override in the account card (save an explicit `0` to disable the floor for that account; leave the override off to inherit the global floor) and through the management API.
- Only enforce the credit floor against quota snapshots reported in `credits`.
- Add an independent percent floor (`CLI2API_PERCENT_FLOOR`, default `0` = disabled, per-account `percent_floor`) for accounts whose quota is reported as a remaining percentage (Devin, Kimi, Zhipu). The two floors never compare across units; entitlement-pack and rate-limit-window accounts keep their existing scheduling behaviour.
- Reject invalid or negative floor values at startup instead of silently disabling the gate.

### 中文

- 新增可配置积分下限(`CLI2API_CREDIT_FLOOR`,默认 `0` 表示关闭):积分低于阈值的账号不再调度计费模型,但仍可调度免费模型。
- 账号卡片与管理 API 支持按账号设置 `credit_floor`(填 0 表示显式关闭该账号保底;关闭覆盖则继承全局阈值)。
- 积分阈值只对以 `credits` 为单位上报的余额生效。
- 新增独立的百分比保底(`CLI2API_PERCENT_FLOOR`,默认 `0` 关闭;按账号 `percent_floor`),适用于以剩余百分比上报余额的账号(Devin、Kimi、智谱);两种单位分别判断、互不做数值换算,权益包与速率窗口账号维持原有调度行为。
- 启动时会拒绝非法或负值配置,避免阈值校验被静默关闭。
2 changes: 2 additions & 0 deletions frontend/src/api/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,8 @@ export type Overview = {
enabled?: boolean
max_inflight?: number
priority?: number
credit_floor?: number | null
percent_floor?: number | null
drop_system_prompt?: boolean
model_aliases?: Record<string, string>
enabled_models?: string[]
Expand Down
75 changes: 74 additions & 1 deletion frontend/src/components/account/EditAccountModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,17 @@ type Props = {
busy: boolean
t: Translate
onClose: () => void
onSave: (input: { name: string; max_inflight: number; priority: number; proxy_url: string; checkin_time?: string; drop_system_prompt?: boolean; model_aliases: Record<string, string>; enabled_models: string[]; set_model_routing: boolean }) => Promise<void>
onSave: (input: { name: string; max_inflight: number; priority: number; credit_floor: number | null; percent_floor: number | null; proxy_url: string; checkin_time?: string; drop_system_prompt?: boolean; model_aliases: Record<string, string>; enabled_models: string[]; set_model_routing: boolean }) => Promise<void>
}

export function EditAccountModal({ account, checkinDefaultTime, checkinTimezone, busy, t, onClose, onSave }: Props) {
const [name, setName] = useState(account?.name || '')
const [maxInFlight, setMaxInFlight] = useState<number>(account?.max_inflight ?? 4)
const [priority, setPriority] = useState<number>(account?.priority ?? 50)
const [creditFloorMode, setCreditFloorMode] = useState<'inherit' | 'custom'>(account?.credit_floor == null ? 'inherit' : 'custom')
const [creditFloor, setCreditFloor] = useState<number>(account?.credit_floor ?? 0)
const [percentFloorMode, setPercentFloorMode] = useState<'inherit' | 'custom'>(account?.percent_floor == null ? 'inherit' : 'custom')
const [percentFloor, setPercentFloor] = useState<number>(account?.percent_floor ?? 0)
const [proxyUrl, setProxyUrl] = useState(account?.proxy_url || '')
const [dropSystemPrompt, setDropSystemPrompt] = useState(Boolean(account?.drop_system_prompt))
const [aliases, setAliases] = useState<Array<{ alias: string; model: string }>>(
Expand Down Expand Up @@ -69,6 +73,14 @@ export function EditAccountModal({ account, checkinDefaultTime, checkinTimezone,
setError(t('priorityInvalid'))
return
}
if (creditFloorMode === 'custom' && (!Number.isFinite(creditFloor) || creditFloor < 0)) {
setError(t('creditFloorInvalid'))
return
}
if (percentFloorMode === 'custom' && (!Number.isFinite(percentFloor) || percentFloor < 0 || percentFloor > 100)) {
setError(t('percentFloorInvalid'))
return
}
if (checkinDefaultTime !== undefined && !inheritCheckinTime && !/^([01]\d|2[0-3]):[0-5]\d$/.test(checkinTime ?? checkinDefaultTime)) {
setError(t('checkinTimeInvalid'))
return
Expand All @@ -79,6 +91,8 @@ export function EditAccountModal({ account, checkinDefaultTime, checkinTimezone,
name: trimmed,
max_inflight: maxInFlight,
priority,
credit_floor: creditFloorMode === 'custom' ? creditFloor : null,
percent_floor: percentFloorMode === 'custom' ? percentFloor : null,
proxy_url: proxyUrl.trim(),
checkin_time: checkinDefaultTime !== undefined ? (inheritCheckinTime ? '' : checkinTime ?? checkinDefaultTime) : undefined,
drop_system_prompt: account?.provider === 'workbuddy' || account?.provider === 'trae' ? dropSystemPrompt : undefined,
Expand Down Expand Up @@ -169,6 +183,65 @@ export function EditAccountModal({ account, checkinDefaultTime, checkinTimezone,
</NumberField.Group>
</NumberField>
</FormRow>
<FormRow label={t('creditFloor')} hint={t('creditFloorHint')} align="start">
<div className="space-y-2">
<CompactSwitch
isSelected={creditFloorMode === 'custom'}
isDisabled={busy}
ariaLabel={t('creditFloorCustom')}
label={t('creditFloorCustom')}
onChange={(selected) => setCreditFloorMode(selected ? 'custom' : 'inherit')}
/>
{creditFloorMode === 'custom' ? (
<NumberField
value={creditFloor}
onChange={(value) => setCreditFloor(value ?? 0)}
minValue={0}
step={1}
isDisabled={busy}
isRequired
>
<NumberField.Group>
<NumberField.DecrementButton />
<NumberField.Input aria-label={t('creditFloor')} />
<NumberField.IncrementButton />
</NumberField.Group>
</NumberField>
) : (
<p className="text-caption text-muted">{t('creditFloorInheritHint')}</p>
)}
</div>
</FormRow>
<FormRow label={t('percentFloor')} hint={t('percentFloorHint')} align="start">
<div className="space-y-2">
<CompactSwitch
isSelected={percentFloorMode === 'custom'}
isDisabled={busy}
ariaLabel={t('percentFloorCustom')}
label={t('percentFloorCustom')}
onChange={(selected) => setPercentFloorMode(selected ? 'custom' : 'inherit')}
/>
{percentFloorMode === 'custom' ? (
<NumberField
value={percentFloor}
onChange={(value) => setPercentFloor(value ?? 0)}
minValue={0}
maxValue={100}
step={1}
isDisabled={busy}
isRequired
>
<NumberField.Group>
<NumberField.DecrementButton />
<NumberField.Input aria-label={t('percentFloor')} />
<NumberField.IncrementButton />
</NumberField.Group>
</NumberField>
) : (
<p className="text-caption text-muted">{t('percentFloorInheritHint')}</p>
)}
</div>
</FormRow>
<FormRow label={t('proxyUrl')} hint={t('proxyUrlHint')}>
<Input
value={proxyUrl}
Expand Down
32 changes: 24 additions & 8 deletions frontend/src/i18n/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -767,15 +767,13 @@ export const messages: Record<Lang, Dict> = {
accountsSigned: '{n} / {total} accounts ready',
addAccount: 'Add account',
batchImport: 'Batch import',
batchImportLoading: 'Importing accounts…',
batchImportLoading: 'Importing WorkBuddy accounts…',
batchImportUnrecognized: 'Could not recognize this credential file format.',
batchImportConfirmTitle: 'Confirm batch import',
batchImportConfirmHint: 'Detected from {file}. Review and confirm before importing.',
batchImportConfirmHintNoFile: 'Review the detected format, then confirm to import.',
batchImportRegion: 'WorkBuddy region',
batchImportKiroRegion: 'Kiro region',
batchImportRegionPickHint: 'Region was unclear — pick CN or Global before importing.',
batchImportKiroRegionPickHint: 'Region was unclear — pick US East or EU Central before importing.',
batchImportRegionMixed: 'This pack mixes CN and Global domains. Split it, or pick one region to force.',
batchImportRegionUnknown: 'Region not detected from domains — please confirm.',
batchImportUnknownFormat: 'Unknown format field; guessed from shape.',
Expand Down Expand Up @@ -871,6 +869,16 @@ export const messages: Record<Lang, Dict> = {
wizardNamePh: 'Account name',
maxInflightHint: 'How many chats this account may run at once. Changing it later restarts the worker.',
priorityHint: 'Higher numbers are preferred when routing later uses this field. Default 50.',
creditFloor: 'Credit floor',
creditFloorHint: 'When enabled, paid models are skipped once the sampled credit balance reaches this value; free models still work. Only accounts reporting credits are affected.',
creditFloorCustom: 'Override global floor for this account',
creditFloorInheritHint: 'Inherits CLI2API_CREDIT_FLOOR. Set 0 here to explicitly disable the floor for this account.',
creditFloorInvalid: 'Credit floor must be zero or a positive number.',
percentFloor: 'Percent floor',
percentFloorHint: 'For accounts reporting remaining percentage (Devin, Kimi, Zhipu): skip paid models once remaining percent reaches this value. Independent of the credit floor; free models still work.',
percentFloorCustom: 'Override global percent floor for this account',
percentFloorInheritHint: 'Inherits CLI2API_PERCENT_FLOOR. Set 0 here to explicitly disable the floor for this account.',
percentFloorInvalid: 'Percent floor must be a number between 0 and 100.',
proxyUrl: 'Proxy URL',
proxyUrlPlaceholder: 'http://127.0.0.1:7890, direct',
proxyUrlHint: 'Blank inherits the global proxy. Use direct or none to bypass proxies for this account. Qoder supports HTTP(S) only; WorkBuddy/Trae also support SOCKS5.',
Expand Down Expand Up @@ -924,7 +932,7 @@ export const messages: Record<Lang, Dict> = {
zhipuKeyRequired: 'Paste the Zhipu API key first.',
wizardPatPh: 'Paste personal access token',
wizardCreateAndLogin: 'Create and sign in',
wizardImportLead: 'Paste a credential JSON export. WorkBuddy hub packages import every account in the file. Kiro accepts a Builder ID, Identity Center, social, or ksk_ JSON.',
wizardImportLead: 'Paste a credential JSON export. WorkBuddy hub packages import every account in the file.',
wizardImportPh: 'Paste credential JSON',
wizardChooseFile: 'Choose file',
wizardBadJson: 'That does not look like a valid credential bundle.',
Expand Down Expand Up @@ -1755,15 +1763,13 @@ export const messages: Record<Lang, Dict> = {
accountsSigned: '{n} / {total} 个账号就绪',
addAccount: '添加账号',
batchImport: '批量导入',
batchImportLoading: '正在导入账号…',
batchImportLoading: '正在导入 WorkBuddy 账号…',
batchImportUnrecognized: '无法识别此凭证文件格式。',
batchImportConfirmTitle: '确认批量导入',
batchImportConfirmHint: '已从 {file} 识别。请核对后再导入。',
batchImportConfirmHintNoFile: '请核对识别结果,确认后再导入。',
batchImportRegion: 'WorkBuddy 区',
batchImportKiroRegion: 'Kiro 地区',
batchImportRegionPickHint: '未能明确识别区,请先选择国内版或国际版。',
batchImportKiroRegionPickHint: '未能明确识别地区,请先选择美东或欧洲中部。',
batchImportRegionMixed: '此包同时含国内与国际域名。请拆分后导入,或强制选择一个区。',
batchImportRegionUnknown: '未从域名识别出区,请确认。',
batchImportUnknownFormat: '未知 format 字段,已按形状猜测。',
Expand Down Expand Up @@ -1859,6 +1865,16 @@ export const messages: Record<Lang, Dict> = {
wizardNamePh: '账号名称',
maxInflightHint: '这个账号同时能跑多少条对话。之后改并发会重启该账号的 worker。',
priorityHint: '数字越大,之后调度会越优先选这个账号。默认 50。',
creditFloor: '积分保底',
creditFloorHint: '开启后,采样到的积分余额降到该值时跳过计费模型,免费模型仍可用;只影响以积分为单位上报余额的账号。',
creditFloorCustom: '为该账号覆盖全局阈值',
creditFloorInheritHint: '继承 CLI2API_CREDIT_FLOOR;填 0 表示显式关闭该账号的保底。',
creditFloorInvalid: '积分保底必须是不小于 0 的数字。',
percentFloor: '百分比保底',
percentFloorHint: '对以剩余百分比上报余额的账号(Devin、Kimi、智谱):剩余百分比降到该值时跳过计费模型;与积分保底互不影响,免费模型仍可用。',
percentFloorCustom: '为该账号覆盖全局百分比阈值',
percentFloorInheritHint: '继承 CLI2API_PERCENT_FLOOR;填 0 表示显式关闭该账号的保底。',
percentFloorInvalid: '百分比保底必须是 0 到 100 之间的数字。',
proxyUrl: '代理地址',
proxyUrlPlaceholder: 'http://127.0.0.1:7890、direct',
proxyUrlHint: '留空继承全局代理;填写 direct 或 none 可让此账号直连。Qoder 仅支持 HTTP(S),WorkBuddy/Trae 额外支持 SOCKS5。',
Expand Down Expand Up @@ -1912,7 +1928,7 @@ export const messages: Record<Lang, Dict> = {
zhipuKeyRequired: '请先粘贴智谱 API Key。',
wizardPatPh: '粘贴个人访问令牌',
wizardCreateAndLogin: '创建并登录',
wizardImportLead: '粘贴凭证 JSON。WorkBuddy hub 导出包会一次性导入其中全部账号。Kiro 接受 Builder ID、Identity Center、社交登录或 ksk_ 的 JSON。',
wizardImportLead: '粘贴凭证 JSON。WorkBuddy hub 导出包会一次性导入其中全部账号。',
wizardImportPh: '粘贴凭证 JSON',
wizardChooseFile: '选择文件',
wizardBadJson: '这看起来不是有效的凭证包。',
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/pages/AccountsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -606,7 +606,7 @@ export function AccountsPage() {
})
}

async function onSaveSettings(id: string, input: { name: string; max_inflight: number; priority: number; proxy_url?: string; checkin_time?: string; drop_system_prompt?: boolean; model_aliases?: Record<string, string>; enabled_models?: string[]; set_model_routing?: boolean }) {
async function onSaveSettings(id: string, input: { name: string; max_inflight: number; priority: number; credit_floor: number | null; percent_floor: number | null; proxy_url?: string; checkin_time?: string; drop_system_prompt?: boolean; model_aliases?: Record<string, string>; enabled_models?: string[]; set_model_routing?: boolean }) {
if (!id) throw new Error(t('accountNameRequired'))
setNameById((current) => ({ ...current, [id]: input.name }))
setInflightById((current) => ({ ...current, [id]: input.max_inflight }))
Expand Down
42 changes: 33 additions & 9 deletions internal/accounts/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,16 @@ type Account struct {
Enabled bool `json:"enabled"`
MaxInFlight int `json:"max_inflight"`
Priority int `json:"priority"`
// CreditFloor is the per-account credit floor override. Nil means "not
// set" and defers to the global CLI2API_CREDIT_FLOOR; a non-nil value
// (including 0, which disables the floor for this account) overrides it.
// No omitempty: an explicit 0 must survive API responses so a caller can
// distinguish "disable this account's floor" from "inherit the global floor".
CreditFloor *float64 `json:"credit_floor"`
// PercentFloor is the per-account floor for percent-denominated quota.
// Nil defers to the global CLI2API_PERCENT_FLOOR; a non-nil value (including
// 0, which disables the percent floor for this account) overrides it.
PercentFloor *float64 `json:"percent_floor"`
// DropSystemPrompt drops caller system prompts before provider-native chat.
DropSystemPrompt bool `json:"drop_system_prompt"`
// ModelAliases maps a client-facing name to this account's real catalog
Expand Down Expand Up @@ -66,6 +76,8 @@ type CreateAccount struct {
Enabled bool
MaxInFlight int
Priority int
CreditFloor *float64
PercentFloor *float64
DropSystemPrompt *bool
WorkBuddyAutoCheckin *bool
WorkBuddyCheckinTime string
Expand All @@ -76,12 +88,22 @@ type CreateAccount struct {
}

type UpdateAccount struct {
AutoCheckin *bool
CheckinTime *string
Name string
Enabled *bool
MaxInFlight *int
Priority *int
AutoCheckin *bool
CheckinTime *string
Name string
Enabled *bool
MaxInFlight *int
Priority *int
// CreditFloor overrides the global floor when non-nil. A nil pointer
// leaves the stored value unchanged on PATCH; a non-nil value (including
// 0, which disables the floor for this account) is stored as the override.
CreditFloor *float64
PercentFloor *float64
// SetCreditFloor/SetPercentFloor let a caller explicitly clear an override
// (store NULL) while leaving PATCH fields absent untouched. Without these,
// a JSON null would be indistinguishable from an omitted field in *float64.
SetCreditFloor bool
SetPercentFloor bool
DropSystemPrompt *bool
WorkBuddyAutoCheckin *bool
WorkBuddyCheckinTime *string
Expand All @@ -108,6 +130,8 @@ type ImportAccount struct {
Enabled bool
MaxInFlight int
Priority int
CreditFloor *float64
PercentFloor *float64
DropSystemPrompt *bool
WorkBuddyAutoCheckin *bool
WorkBuddyCheckinTime string
Expand All @@ -117,9 +141,9 @@ type ImportAccount struct {

type AccountView struct {
Account
Ready bool `json:"ready"`
Hot bool `json:"hot"`
InFlight int `json:"in_flight"`
Ready bool `json:"ready"`
Hot bool `json:"hot"`
InFlight int `json:"in_flight"`
// InFlightSince is RFC3339 when the pool slot went busy (0→1); empty when idle.
InFlightSince string `json:"in_flight_since,omitempty"`
Restarts int `json:"restarts"`
Expand Down
2 changes: 2 additions & 0 deletions internal/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,8 @@ func New(cfg config.Config) *App {
}
pool := manager.Pool()
pool.SetRoutingStrategy(routingStrategy)
pool.SetDefaultCreditFloor(cfg.CreditFloor)
pool.SetDefaultPercentFloor(cfg.PercentFloor)
providerReg := providers.NewRegistry()
workbuddyClient := workbuddy.NewClient(store)
providerReg.Register(workbuddyClient.Adapter())
Expand Down
Loading
Loading