🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(agent-quota): judge an agent's quota on the accounts its runs are routed to (#23349)
Lobehub Coder9462041c1fea
diff --git a/apps/server/src/routers/lambda/__tests__/agentQuota.deviceAccount.test.ts b/apps/server/src/routers/lambda/__tests__/agentQuota.deviceAccount.test.tsindex 8b856c81c53..8e1ba1cbcfa 100644--- a/apps/server/src/routers/lambda/__tests__/agentQuota.deviceAccount.test.ts+++ b/apps/server/src/routers/lambda/__tests__/agentQuota.deviceAccount.test.ts@@ -39,6 +39,7 @@ vi.mock('@/database/models/agentQuota', () => ({const mockGetDeviceAccount = vi.fn();const mockSetDeviceAccount = vi.fn();const mockSelectForAgent = vi.fn();+const mockResolveAgentAvailability = vi.fn();vi.mock('@/server/services/agentQuota', async (importOriginal) => {const { AccountNotSignedInOnDeviceError } = await importOriginal<typeof AgentQuotaModule>();return {@@ -46,6 +47,7 @@ vi.mock('@/server/services/agentQuota', async (importOriginal) => {AgentQuotaService: vi.fn(function () {return {getDeviceAccount: mockGetDeviceAccount,+ resolveAgentAvailability: mockResolveAgentAvailability,selectForAgent: mockSelectForAgent,setDeviceAccount: mockSetDeviceAccount,};@@ -107,3 +109,32 @@ describe('agentQuota per-device account choice', () => {);});});++describe('agentQuota.resolveAgentAvailability', () => {+ it('judges the agent on the device row the gateway id names', async () => {+ const availability = {+ accountIds: ['acc-1'],+ mode: 'pinned',+ resetsAt: 1_794_985_200_000,+ status: 'exhausted',+ };+ mockResolveAgentAvailability.mockResolvedValue(availability);++ await expect(+ caller().resolveAgentAvailability({ agentId: 'agt-1', deviceId: 'gateway-a' }),+ ).resolves.toEqual(availability);+ // An unknown device is judged as a run without one.+ await caller().resolveAgentAvailability({ agentId: 'agt-1', deviceId: 'gateway-gone' });++ expect(mockResolveAgentAvailability).toHaveBeenNthCalledWith(1, 'agt-1', {+ deviceId: 'row-a',+ modelScope: undefined,+ provider: undefined,+ });+ expect(mockResolveAgentAvailability).toHaveBeenNthCalledWith(2, 'agt-1', {+ deviceId: undefined,+ modelScope: undefined,+ provider: undefined,+ });+ });+});diff --git a/apps/server/src/routers/lambda/agentQuota.ts b/apps/server/src/routers/lambda/agentQuota.tsindex d57155523b0..c8cd39897b0 100644--- a/apps/server/src/routers/lambda/agentQuota.ts+++ b/apps/server/src/routers/lambda/agentQuota.ts@@ -1,4 +1,4 @@-import type { QuotaDeviceAccount } from '@lobechat/types';+import type { QuotaAgentAvailability, QuotaDeviceAccount } from '@lobechat/types';import { TRPCError } from '@trpc/server';import { z } from 'zod';@@ -436,6 +436,30 @@ export const agentQuotaRouter = router({.input(z.object({ accountIds: z.array(z.string()) })).query(async ({ ctx, input }) => ctx.quotaService.resolveAccountLoads(input.accountIds)),+ /**+ * Whether an agent would find quota on the device it runs on, judged on the+ * accounts a run there is routed to (its device pick, a legacy pin, or the+ * pool's candidates). Presence reads this instead of judging the whole pool,+ * which reads "idle" while a device pin is spent.+ */+ resolveAgentAvailability: quotaProcedure+ .input(+ z.object({+ agentId: z.string(),+ /** Gateway id of the device the agent runs on; omitted for a run without one. */+ deviceId: z.string().optional(),+ modelScope: z.string().optional(),+ provider: providerSchema.optional(),+ }),+ )+ .query(async ({ ctx, input }): Promise<QuotaAgentAvailability> =>+ ctx.quotaService.resolveAgentAvailability(input.agentId, {+ deviceId: await deviceRowIdOf(ctx, input.deviceId),+ modelScope: input.modelScope,+ provider: input.provider,+ }),+ ),+selectAccountForAgent: quotaProcedure.input(z.object({diff --git a/apps/server/src/services/agentQuota/__tests__/deviceAccounts.test.ts b/apps/server/src/services/agentQuota/__tests__/deviceAccounts.test.tsindex 63ec63f2d3a..984cd4a363e 100644--- a/apps/server/src/services/agentQuota/__tests__/deviceAccounts.test.ts+++ b/apps/server/src/services/agentQuota/__tests__/deviceAccounts.test.ts@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';import {AgentAccountBindingModel,AgentDeviceAccountBindingModel,+ AgentProviderAccountModel,} from '@/database/models/agentQuota';import { agents, devices, users } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';@@ -237,3 +238,134 @@ describe('AgentQuotaService.planDeviceRouting per device', () => {});});});++describe('AgentQuotaService.resolveAgentAvailability', () => {+ const HOUR = 3_600_000;+ const now = Date.now();+ const resetsAt = now + 2 * HOUR;++ /** An account signed in on `deviceId` whose 5-hour window is at `utilization`. */+ const withSession = (externalAccountId: string, deviceId: string, utilization: number) =>+ service.ingestSnapshot({+ deviceId,+ identity: { email: `${externalAccountId}@example.com`, externalAccountId },+ provider: 'claude-code',+ readings: [+ { capturedAt: now - HOUR, limitType: 'session', resetsAt, scopeKey: '', utilization },+ ],+ });++ // Regression: presence judged the whole pool, so an agent whose device pin+ // was spent read "idle" while every run on that device hit the limit.+ it('judges a device pin alone, even when the rest of the pool has headroom', async () => {+ const spent = await withSession('acc-spent', deviceA, 100);+ const free = await withSession('acc-free', deviceA, 0);+ for (const account of [spent, free])+ await bindings.upsert({ accountId: account.id, agentId, role: QuotaBindingRole.pool });+ await service.setDeviceAccount(agentId, deviceA, spent.id);++ expect(await service.resolveAgentAvailability(agentId, { deviceId: deviceA, now })).toEqual({+ accountIds: [spent.id],+ mode: 'pinned',+ resetsAt,+ status: 'exhausted',+ });+ // The dispatcher routes the run to that same spent account.+ expect(+ await service.planDeviceRouting(agentId, { deviceId: deviceA, now, provider: 'claude-code' }),+ ).toMatchObject({ candidates: [{ externalAccountId: 'acc-spent' }], mode: 'pinned' });+ // Back on Auto, the free account takes the run.+ await service.setDeviceAccount(agentId, deviceA, null);+ expect(+ await service.resolveAgentAvailability(agentId, { deviceId: deviceA, now }),+ ).toMatchObject({ mode: 'balanced', status: 'available' });+ });++ // Regression: Auto mode was narrowed to the logins recorded for the device.+ // That record is partial (a remote device only has the accounts sampled+ // there) and an emptied set read like one never reported, so the verdict+ // flipped while the dispatcher kept offering the same candidates.+ it('judges Auto mode on the candidates the dispatcher sends, whatever logins are recorded', async () => {+ const spent = await withSession('acc-spent', deviceA, 100);+ const free = await withSession('acc-free', deviceB, 0);+ for (const account of [spent, free])+ await bindings.upsert({ accountId: account.id, agentId, role: QuotaBindingRole.pool });+ const expected = {+ accountIds: [spent.id, free.id],+ mode: 'balanced',+ status: 'available',+ };++ // Only the spent account was ever sampled on device A.+ expect(await service.resolveAgentAvailability(agentId, { deviceId: deviceA, now })).toEqual(+ expected,+ );+ expect(+ await service.planDeviceRouting(agentId, { deviceId: deviceA, now, provider: 'claude-code' }),+ ).toMatchObject({ candidates: [{ externalAccountId: 'acc-free' }], mode: 'balanced' });++ // Device A then reports it holds no login at all.+ await service.syncDeviceLogins(deviceA, 'claude-code', []);+ expect(await service.resolveAgentAvailability(agentId, { deviceId: deviceA, now })).toEqual(+ expected,+ );+ });++ it('is exhausted in Auto mode once every candidate is spent, and says when one returns', async () => {+ const early = await withSession('acc-early', deviceA, 100);+ await bindings.upsert({ accountId: early.id, agentId, role: QuotaBindingRole.pool });++ expect(await service.resolveAgentAvailability(agentId, { deviceId: deviceA, now })).toEqual({+ accountIds: [early.id],+ mode: 'balanced',+ resetsAt,+ status: 'exhausted',+ });+ });++ // Regression: an all-disabled Auto pool read "exhausted" with no reset, so+ // presence showed the agent off duty for good, while the dispatcher routes+ // nothing there and the device's default login runs.+ it('does not judge an Auto pool whose accounts are all disabled', async () => {+ const accounts = new AgentProviderAccountModel(serverDB, userId);+ const spent = await withSession('acc-spent', deviceA, 100);+ const free = await withSession('acc-free', deviceA, 0);+ for (const account of [spent, free]) {+ await bindings.upsert({ accountId: account.id, agentId, role: QuotaBindingRole.pool });+ await accounts.update(account.id, { enabled: false });+ }++ expect(+ await service.planDeviceRouting(agentId, { deviceId: deviceA, now, provider: 'claude-code' }),+ ).toBeNull();+ expect(await service.resolveAgentAvailability(agentId, { deviceId: deviceA, now })).toEqual({+ accountIds: [],+ mode: 'balanced',+ status: 'untracked',+ });+ });++ it('still judges a device pin on a disabled account: the run is sent to it', async () => {+ const spent = await withSession('acc-spent', deviceA, 100);+ await bindings.upsert({ accountId: spent.id, agentId, role: QuotaBindingRole.pool });+ await service.setDeviceAccount(agentId, deviceA, spent.id);+ await new AgentProviderAccountModel(serverDB, userId).update(spent.id, { enabled: false });++ expect(+ await service.planDeviceRouting(agentId, { deviceId: deviceA, now, provider: 'claude-code' }),+ ).toMatchObject({ candidates: [{ externalAccountId: 'acc-spent' }], mode: 'pinned' });+ expect(await service.resolveAgentAvailability(agentId, { deviceId: deviceA, now })).toEqual({+ accountIds: [spent.id],+ mode: 'pinned',+ resetsAt,+ status: 'exhausted',+ });+ });++ it('does not judge an agent without accounts', async () => {+ expect(await service.resolveAgentAvailability(agentId, { deviceId: deviceA, now })).toEqual({+ accountIds: [],+ status: 'untracked',+ });+ });+});diff --git a/apps/server/src/services/agentQuota/index.ts b/apps/server/src/services/agentQuota/index.tsindex 68da982043c..96c76af0acf 100644--- a/apps/server/src/services/agentQuota/index.ts+++ b/apps/server/src/services/agentQuota/index.ts@@ -17,9 +17,11 @@ import {type QuotaTokenUsage,rankAccounts,selectAccount,+ summarizeAvailability,windowSecondsForKind,windowsToCalibrationIntervals,} from '@lobechat/heterogeneous-agents/quota';+import type { QuotaAgentAvailability } from '@lobechat/types';import pMap from 'p-map';import type { AccountIdentityInput, SafeAccount } from '@/database/models/agentQuota';@@ -119,6 +121,22 @@ const isForeignKeyViolation = (error: unknown): boolean => {/** Where a pin came from: the run's own device, or the legacy agent-wide pin. */export type AccountPinScope = 'agent' | 'device';+/** An account a device can sign in with, and what the device is told to look for. */+interface RoutableAccount {+ id: string;+ routed: ClaudeCodeRoutedAccount;+}++/** The accounts a device run may use, before quota is weighed; see `planDeviceAccounts`. */+type DeviceAccountPlan =+ | { mode: 'pinned'; pin: RoutableAccount }+ | {+ mode: 'balanced';+ /** A legacy pin picked on another machine: tried first, whatever its load. */+ pinnedElsewhere?: RoutableAccount;+ pool: { account: RoutableAccount; priority: number }[];+ };+export class AgentQuotaService {private accounts: AgentProviderAccountModel;private bindings: AgentAccountBindingModel;@@ -457,8 +475,11 @@ export class AgentQuotaService {const account = byId.get(accountId);const buckets = await this.listLatestReadings(accountId);const scopedWeeklyUtil: Record<string, number> = {};+ const scopedWeeklyResetsAt: Record<string, number | null> = {};let sessionUtil = 0;+ let sessionResetsAt: number | null = null;let weeklyUtil = 0;+ let weeklyResetsAt: number | null = null;let rateLimitedUntil: number | null = null;for (const b of buckets) {@@ -469,13 +490,17 @@ export class AgentQuotaService {if (isSessionLimit(b)) {sessionUtil = utilization;+ sessionResetsAt = b.resetsAt ?? null;// `utilization` is already 0 once the window rolled over, so a// stale 100% cannot bench the account past its own reset.if (utilization >= 100 && b.resetsAt) rateLimitedUntil = b.resetsAt;} else if (isScopedWeeklyLimit(b)) {scopedWeeklyUtil[b.scopeKey] = utilization;- } else if (isWeeklyAllLimit(b)) {- weeklyUtil = Math.max(weeklyUtil, utilization);+ scopedWeeklyResetsAt[b.scopeKey] = b.resetsAt ?? null;+ } else if (isWeeklyAllLimit(b) && utilization >= weeklyUtil) {+ // The fullest weekly window decides when the account frees up.+ weeklyUtil = utilization;+ weeklyResetsAt = b.resetsAt ?? null;}}@@ -488,8 +513,11 @@ export class AgentQuotaService {label: account?.label ?? null,priority: 0,rateLimitedUntil,+ scopedWeeklyResetsAt,scopedWeeklyUtil,+ sessionResetsAt,sessionUtil,+ weeklyResetsAt,weeklyUtil,} satisfies AccountLoadView;}),@@ -612,74 +640,162 @@ export class AgentQuotaService {* The account choice for a run on an execution device, which picks the* login itself (only it knows which accounts it is signed in to): the pin,* or the whole eligible pool best-first. `null` = no routing, and the device- * spawns on its default login as before.- *- * Only `referenced` accounts map to a device login; a run pinned to any- * other account keeps the default login, as on the desktop.- *- * With the run's `deviceId`, that device's own choice is the pin. A legacy- * agent-wide pin stays strict only where its login is recorded; elsewhere- * it was picked on another machine, so it becomes the first Auto candidate- * and the device falls through to the pool (or its default login).+ * spawns on its default login as before. Which accounts count is+ * `planDeviceAccounts`; this only ranks them.*/planDeviceRouting = async (agentId: string,options: Pick<SelectAccountOptions, 'deviceId' | 'modelScope' | 'now' | 'provider'> = {},): Promise<ClaudeCodeAccountRouting | null> => {+ const plan = await this.planDeviceAccounts(agentId, options);+ if (!plan) return null;+ if (plan.mode === 'pinned') return { candidates: [plan.pin.routed], mode: 'pinned' };++ const now = options.now ?? Date.now();+ const loads = await this.poolLoads(plan.pool, now);+ const routedById = new Map(plan.pool.map(({ account }) => [account.id, account.routed]));+ const candidates = rankAccounts(loads, { modelScope: options.modelScope, now }).flatMap(+ (load) => routedById.get(load.accountId) ?? [],+ );+ const elsewhere = plan.pinnedElsewhere?.routed;+ if (elsewhere && !candidates.some((c) => c.externalAccountId === elsewhere.externalAccountId))+ candidates.unshift(elsewhere);++ return candidates.length > 0 ? { candidates, mode: 'balanced' } : null;+ };++ /**+ * Whether a run of `agentId` would find quota on `deviceId`, judged on the+ * accounts `planDeviceAccounts` routes it to — the same ones the dispatcher+ * uses, so presence cannot read "idle" while every run lands on a spent+ * account.+ *+ * Auto mode is judged on the whole candidate list the dispatcher sends, not+ * narrowed to the logins recorded for the device: that record is no+ * inventory. Only a desktop syncs its own full set; a remote device has+ * just the accounts sampled there, and an emptied set reads like one never+ * reported. Which candidate the device can sign in with stays its call.+ */+ resolveAgentAvailability = async (+ agentId: string,+ options: Pick<SelectAccountOptions, 'deviceId' | 'modelScope' | 'now' | 'provider'> = {},+ ): Promise<QuotaAgentAvailability> => {+ const plan = await this.planDeviceAccounts(agentId, options);+ if (!plan) return { accountIds: [], status: 'untracked' };++ // A pin is sent to the device whatever the account's state, so its quota+ // decides; a disabled pool account is out of the rotation the dispatcher+ // ranks (`rankAccounts` drops it).+ const pins = new Set(+ plan.mode === 'pinned'+ ? [plan.pin.id]+ : plan.pinnedElsewhere+ ? [plan.pinnedElsewhere.id]+ : [],+ );+ const candidateIds = [+ ...new Set([+ ...pins,+ ...(plan.mode === 'balanced' ? plan.pool.map(({ account }) => account.id) : []),+ ]),+ ];++ const now = options.now ?? Date.now();+ const loads = (await this.resolveAccountLoads(candidateIds, now))+ .map((load) => (pins.has(load.accountId) ? { ...load, enabled: true } : load))+ .filter((load) => load.enabled);+ // Every account in the rotation is disabled: the dispatcher routes+ // nothing and the device's default login runs.+ if (loads.length === 0) return { accountIds: [], mode: plan.mode, status: 'untracked' };++ const { available, resetsAt } = summarizeAvailability(loads, {+ modelScope: options.modelScope,+ now,+ });++ return {+ accountIds: loads.map((load) => load.accountId),+ mode: plan.mode,+ status: available ? 'available' : 'exhausted',+ ...(resetsAt !== undefined && { resetsAt }),+ };+ };++ /**+ * The accounts a run of `agentId` on `deviceId` may use, before quota is+ * weighed. The dispatcher (`planDeviceRouting`) and the availability read+ * (`resolveAgentAvailability`) both start here, so they cannot disagree:+ *+ * 1. the device's own account choice, strict;+ * 2. a legacy agent-wide pin, strict where its login is recorded (or with no+ * device named); elsewhere it was picked on another machine, so it+ * becomes the first Auto candidate and the device falls through to+ * the pool;+ * 3. the pool.+ *+ * Only `referenced` accounts map to a device login; a pin on any other+ * account keeps the default login, as on the desktop (`null`).+ */+ private planDeviceAccounts = async (+ agentId: string,+ options: Pick<SelectAccountOptions, 'deviceId' | 'provider'>,+ ): Promise<DeviceAccountPlan | null> => {const bindings = await this.enabledBindings(agentId, options.provider);const accounts = new Map((await this.accounts.list()).map((a) => [a.id, a]));- const routed = (accountId: string): ClaudeCodeRoutedAccount | undefined => {+ const routable = (accountId: string): RoutableAccount | undefined => {const account = accounts.get(accountId);if (account?.credentialMode !== QuotaCredentialMode.referenced) return;if (!account.externalAccountId) return;const name = account.label || account.email;- return { externalAccountId: account.externalAccountId, ...(name ? { name } : {}) };+ return {+ id: accountId,+ routed: { externalAccountId: account.externalAccountId, ...(name ? { name } : {}) },+ };};const deviceChoice = await this.deviceChoiceOf(agentId, bindings, options.deviceId);if (deviceChoice) {- const account = routed(deviceChoice);- return account ? { candidates: [account], mode: 'pinned' } : null;+ const pin = routable(deviceChoice);+ return pin ? { mode: 'pinned', pin } : null;}const pinned = bindings.find((b) => b.role === QuotaBindingRole.pinned);- let pinnedElsewhere: ClaudeCodeRoutedAccount | undefined;+ let pinnedElsewhere: RoutableAccount | undefined;if (pinned) {- const account = routed(pinned.accountId);- if (!account) return null;+ const pin = routable(pinned.accountId);+ if (!pin) return null;const strict =!options.deviceId ||(await this.logins.listByAccount(pinned.accountId)).some((login) => login.deviceId === options.deviceId,);- if (strict) return { candidates: [account], mode: 'pinned' };- pinnedElsewhere = account;+ if (strict) return { mode: 'pinned', pin };+ pinnedElsewhere = pin;}- const pool = bindings.filter((b) => b.role === QuotaBindingRole.pool);- if (pool.length === 0)- return pinnedElsewhere ? { candidates: [pinnedElsewhere], mode: 'balanced' } : null;+ const pool = bindings+ .filter((b) => b.role === QuotaBindingRole.pool)+ .flatMap((b) => {+ const account = routable(b.accountId);+ return account ? [{ account, priority: b.priority }] : [];+ });+ if (pool.length === 0 && !pinnedElsewhere) return null;- const now = options.now ?? Date.now();- const priorityById = new Map(pool.map((b) => [b.accountId, b.priority]));+ return { mode: 'balanced', pinnedElsewhere, pool };+ };++ /** Load views of a plan's pool, carrying each binding's priority. */+ private poolLoads = async (+ pool: Extract<DeviceAccountPlan, { mode: 'balanced' }>['pool'],+ now: number,+ ) => {+ if (pool.length === 0) return [];+ const priorityById = new Map(pool.map(({ account, priority }) => [account.id, priority]));const loads = await this.resolveAccountLoads(- pool.map((b) => b.accountId),+ pool.map(({ account }) => account.id),now,);- const candidates = rankAccounts(- loads.map((l) => ({ ...l, priority: priorityById.get(l.accountId) ?? 0 })),- { modelScope: options.modelScope, now },- ).flatMap((load) => routed(load.accountId) ?? []);- if (pinnedElsewhere)- candidates.splice(- 0,- 0,- ...[pinnedElsewhere].filter(- (account) => !candidates.some((c) => c.externalAccountId === account.externalAccountId),- ),- );-- return candidates.length > 0 ? { candidates, mode: 'balanced' } : null;+ return loads.map((l) => ({ ...l, priority: priorityById.get(l.accountId) ?? 0 }));};/**diff --git a/packages/heterogeneous-agents/src/quota/loadBalancer.ts b/packages/heterogeneous-agents/src/quota/loadBalancer.tsindex dd8319c7a9d..0f55855da2e 100644--- a/packages/heterogeneous-agents/src/quota/loadBalancer.ts+++ b/packages/heterogeneous-agents/src/quota/loadBalancer.ts@@ -17,10 +17,16 @@ export interface AccountLoad {priority: number;/** ms epoch until which the account is cooling down after a 429, if any. */rateLimitedUntil?: number | null;+ /** When each scoped weekly window resets (ms epoch), by model display name; `null` = not reported. */+ scopedWeeklyResetsAt?: Record<string, number | null>;/** Scoped weekly utilization by model display name, e.g. `{ Fable: 100 }`. */scopedWeeklyUtil?: Record<string, number>;+ /** When the session (5h) window resets, ms epoch; `null` = not reported. */+ sessionResetsAt?: number | null;/** Session (5h) utilization, 0..100. */sessionUtil?: number;+ /** When the weekly (7d) window resets, ms epoch; `null` = not reported. */+ weeklyResetsAt?: number | null;/** Weekly (7d) utilization, 0..100. */weeklyUtil?: number;}@@ -34,18 +40,27 @@ export interface SelectAccountOptions {/** A limit is treated as exhausted at/above this utilization. */const EXHAUSTED = 100;-const isEligible = (a: AccountLoad, opts: SelectAccountOptions): boolean => {- if (!a.enabled) return false;- if (a.rateLimitedUntil != null && a.rateLimitedUntil > opts.now) return false;- if ((a.weeklyUtil ?? 0) >= EXHAUSTED) return false;- if ((a.sessionUtil ?? 0) >= EXHAUSTED) return false;+/**+ * The limits that keep an enabled account from taking work right now, each as+ * the time it lifts (`null` when the provider gave none). Empty = eligible.+ */+const benchedUntil = (a: AccountLoad, opts: SelectAccountOptions): (number | null)[] => {+ const until: (number | null)[] = [];+ if (a.rateLimitedUntil != null && a.rateLimitedUntil > opts.now) until.push(a.rateLimitedUntil);+ if ((a.weeklyUtil ?? 0) >= EXHAUSTED) until.push(a.weeklyResetsAt ?? null);+ if ((a.sessionUtil ?? 0) >= EXHAUSTED)+ until.push(a.sessionResetsAt ?? a.rateLimitedUntil ?? null);if (opts.modelScope) {const scoped = a.scopedWeeklyUtil?.[opts.modelScope];- if (scoped != null && scoped >= EXHAUSTED) return false;+ if (scoped != null && scoped >= EXHAUSTED)+ until.push(a.scopedWeeklyResetsAt?.[opts.modelScope] ?? null);}- return true;+ return until;};+const isEligible = (a: AccountLoad, opts: SelectAccountOptions): boolean =>+ a.enabled && benchedUntil(a, opts).length === 0;+const scopedHeadroom = (a: AccountLoad, modelScope?: string): number => {if (!modelScope) return 100;const scoped = a.scopedWeeklyUtil?.[modelScope];@@ -85,3 +100,37 @@ export const selectAccount = (candidates: AccountLoad[],opts: SelectAccountOptions,): AccountLoad | null => rankAccounts(candidates, opts)[0] ?? null;++/** Whether a set of accounts can take a run, as the balancer would see it. */+export interface AccountsAvailability {+ /** At least one account is eligible now. */+ available: boolean;+ /**+ * When none is: the earliest moment one comes back (ms epoch). Absent while+ * one is available, and when an account is benched by a limit that gives no+ * reset time — it could come back sooner than any promise made here.+ */+ resetsAt?: number;+}++/**+ * Judge `candidates` with the balancer's own eligibility rule: available when+ * `rankAccounts` would pick one of them, else when the first one frees up. A+ * benched account lifts at the latest reset among the limits that bench it.+ * A disabled account never comes back on its own, so it sets no time.+ */+export const summarizeAvailability = (+ candidates: AccountLoad[],+ opts: SelectAccountOptions,+): AccountsAvailability => {+ const enabled = candidates.filter((a) => a.enabled);+ if (enabled.some((a) => isEligible(a, opts))) return { available: true };++ const liftsAt = enabled.map((a) => {+ const until = benchedUntil(a, opts);+ return until.includes(null) ? null : Math.max(...(until as number[]));+ });+ if (liftsAt.length === 0 || liftsAt.includes(null)) return { available: false };++ return { available: false, resetsAt: Math.min(...(liftsAt as number[])) };+};diff --git a/packages/heterogeneous-agents/src/quota/quota.test.ts b/packages/heterogeneous-agents/src/quota/quota.test.tsindex 937e3f825e0..a9d36260744 100644--- a/packages/heterogeneous-agents/src/quota/quota.test.ts+++ b/packages/heterogeneous-agents/src/quota/quota.test.ts@@ -7,7 +7,7 @@ import {windowsToCalibrationIntervals,} from './calibration';import { computeTurnCostUsd, totalTokens } from './cost';-import { selectAccount } from './loadBalancer';+import { selectAccount, summarizeAvailability } from './loadBalancer';import { buildClaudeQuotaWindows, dropRetiredLimits } from './readings';import type { QuotaLimitReading } from './types';import { CLAUDE_SESSION_WINDOW_SECONDS, windowSecondsForKind } from './types';@@ -436,3 +436,100 @@ describe('selectAccount', () => {expect(pick?.accountId).toBe('p1');});});++describe('summarizeAvailability', () => {+ const base = { enabled: true, priority: 0 };+ const now = 1000;++ it('is available while any account has headroom', () => {+ expect(+ summarizeAvailability(+ [+ { ...base, accountId: 'spent', sessionResetsAt: 9000, sessionUtil: 100 },+ { ...base, accountId: 'free', sessionUtil: 0, weeklyUtil: 56 },+ ],+ { now },+ ),+ ).toEqual({ available: true });+ });++ it('is exhausted when the only candidate is spent, and says when it comes back', () => {+ // A device pin leaves one candidate: its spent 5-hour window decides.+ expect(+ summarizeAvailability(+ [+ {+ ...base,+ accountId: 'pin',+ rateLimitedUntil: 9000,+ sessionResetsAt: 9000,+ sessionUtil: 100,+ },+ ],+ { now },+ ),+ ).toEqual({ available: false, resetsAt: 9000 });+ });++ it('comes back at the earliest account, each at the latest limit benching it', () => {+ expect(+ summarizeAvailability(+ [+ // Both windows spent: back only once the weekly one resets too.+ {+ ...base,+ accountId: 'both',+ sessionResetsAt: 2000,+ sessionUtil: 100,+ weeklyResetsAt: 8000,+ weeklyUtil: 100,+ },+ { ...base, accountId: 'weekly', weeklyResetsAt: 5000, weeklyUtil: 100 },+ ],+ { now },+ ),+ ).toEqual({ available: false, resetsAt: 5000 });+ });++ it('promises no time when a benching limit gives none', () => {+ expect(+ summarizeAvailability(+ [+ { ...base, accountId: 'timed', sessionResetsAt: 2000, sessionUtil: 100 },+ { ...base, accountId: 'untimed', weeklyResetsAt: null, weeklyUtil: 100 },+ ],+ { now },+ ),+ ).toEqual({ available: false });+ });++ it('judges the scoped weekly only for work on that model', () => {+ const fableSpent = [+ {+ ...base,+ accountId: 'a',+ scopedWeeklyResetsAt: { Fable: 7000 },+ scopedWeeklyUtil: { Fable: 100 },+ weeklyUtil: 40,+ },+ ];+ expect(summarizeAvailability(fableSpent, { modelScope: 'Fable', now })).toEqual({+ available: false,+ resetsAt: 7000,+ });+ expect(summarizeAvailability(fableSpent, { now })).toEqual({ available: true });+ });++ it('ignores disabled accounts: they never come back on their own', () => {+ expect(+ summarizeAvailability(+ [+ { ...base, accountId: 'off', enabled: false, weeklyUtil: 0 },+ { ...base, accountId: 'spent', sessionResetsAt: 3000, sessionUtil: 100 },+ ],+ { now },+ ),+ ).toEqual({ available: false, resetsAt: 3000 });+ expect(summarizeAvailability([], { now })).toEqual({ available: false });+ });+});diff --git a/packages/types/src/agentQuota.ts b/packages/types/src/agentQuota.tsindex cfefd14f393..dd11beaf0ae 100644--- a/packages/types/src/agentQuota.ts+++ b/packages/types/src/agentQuota.ts@@ -6,3 +6,27 @@export interface QuotaDeviceAccount {accountId: string | null;}++/**+ * Whether an agent would find quota where it runs, judged on the accounts the+ * dispatcher would route it to there (its device's pick, a legacy pin, or the+ * pool's candidates). Presence reads it; a scheduler can check it before+ * dispatching.+ *+ * - `available`: at least one of those accounts has headroom;+ * - `exhausted`: every one of them is spent;+ * - `untracked`: none of the agent's accounts is routed there, so the run uses+ * the device's default login and its quota is not judged.+ */+export interface QuotaAgentAvailability {+ /** Accounts judged, as the dispatcher would try them; empty when `untracked`. */+ accountIds: string[];+ /** `pinned`: the run must use the one account; `balanced`: it may use any. */+ mode?: 'balanced' | 'pinned';+ /**+ * When `exhausted`: the earliest moment one account comes back (ms epoch).+ * Absent when a limit that benches an account gives no reset time.+ */+ resetsAt?: number;+ status: 'available' | 'exhausted' | 'untracked';+}