Skip to content

🀯 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.

✨ feat(agent): add an availability layer for dispatch and contact status (#23438)

Arvin Xu35b4ff610c5b
diff --git a/apps/server/src/modules/Redis/keys.ts b/apps/server/src/modules/Redis/keys.ts
index cd3e56be670..4cb81649684 100644
--- a/apps/server/src/modules/Redis/keys.ts
+++ b/apps/server/src/modules/Redis/keys.ts
@@ -15,6 +15,11 @@
* When using `createRedisWithPrefix`, pass one of these as the prefix parameter.
*/
export const RedisKeyNamespace = {
+ /**
+ * Whether Agents can take work: device presence per principal pool and each agent's quota
+ * verdict per caller, read by the dispatch layer and the contact card's status.
+ */
+ AGENT_AVAILABILITY: 'agent-availability',
/**
* Agent Signal keys β€” the same `agent-signal` keyspace the Agent Signal runtime
* stores (receipts, dedupe, policy state) already use.
@@ -97,6 +102,20 @@ export const RedisKeyNamespace = {
* ```
*/
export const RedisKeys = {
+ /** Agent availability scope β€” see {@link RedisKeyNamespace.AGENT_AVAILABILITY}. */
+ agentAvailability: {
+ /**
+ * One device's presence (connected, managed phase) as one principal pool sees it.
+ * Full key: agent-availability:device:v1:{pool}:{deviceId}
+ */
+ device: (pool: string, deviceId: string): string => `device:v1:${pool}:${deviceId}`,
+ /**
+ * Whether one agent's quota is spent where it runs, as one caller sees its accounts.
+ * Full key: agent-availability:quota:v1:{userId}:{pool}:{agentId}:{deviceId|none}
+ */
+ quota: (userId: string, pool: string, agentId: string, deviceId?: string): string =>
+ `quota:v1:${userId}:${pool}:${agentId}:${deviceId ?? 'none'}`,
+ },
inboundWebhook: {
wake: (id: string) => `wake:v1:${id}`,
check: (id: string) => `check:v1:${id}`,
@@ -405,6 +424,7 @@ export const RedisKeys = {
* land under another scope's prefix. Every scope must be mapped.
*/
export const RedisKeyScopeNamespace = {
+ agentAvailability: RedisKeyNamespace.AGENT_AVAILABILITY,
inboundWebhook: RedisKeyNamespace.INBOUND_WEBHOOK,
agentIdentity: RedisKeyNamespace.AGENT_IDENTITY,
agentRun: RedisKeyNamespace.AGENT_RUN,
diff --git a/apps/server/src/routers/lambda/agentAvailability.ts b/apps/server/src/routers/lambda/agentAvailability.ts
new file mode 100644
index 00000000000..7c4201b8420
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentAvailability.ts
@@ -0,0 +1,32 @@
+import type { AgentAvailability } from '@lobechat/types';
+import { z } from 'zod';
+
+import { authedProcedure, router } from '@/libs/trpc/lambda';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { AgentAvailabilityService } from '@/server/services/agentAvailability';
+
+const availabilityProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts;
+ return opts.next({
+ ctx: {
+ availabilityService: new AgentAvailabilityService(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ ),
+ },
+ });
+});
+
+export const agentAvailabilityRouter = router({
+ /**
+ * Whether each agent can take work right now, in one read: its status, the queued and
+ * running Channel replies it has, when an off-duty agent's quota comes back, and whether
+ * routing may hand it an unaddressed message. Agents the caller cannot see are absent.
+ */
+ getAvailability: availabilityProcedure
+ .input(z.object({ agentIds: z.array(z.string()).max(200) }))
+ .query(async ({ ctx, input }): Promise<Record<string, AgentAvailability>> =>
+ ctx.availabilityService.getAvailability(input.agentIds),
+ ),
+});
diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.ts
index df77861a4c7..f4ee4d8020f 100644
--- a/apps/server/src/routers/lambda/index.ts
+++ b/apps/server/src/routers/lambda/index.ts
@@ -26,6 +26,7 @@ import { acceptanceRouter } from './acceptance';
import { acceptanceCommentRouter } from './acceptanceComment';
import { agentRouter } from './agent';
import { agentAccountRouter } from './agentAccount';
+import { agentAvailabilityRouter } from './agentAvailability';
import { agentBotProviderRouter } from './agentBotProvider';
import { agentBotWakeRouter } from './agentBotWake';
import { agentDocumentRouter } from './agentDocument';
@@ -161,6 +162,7 @@ export const lambdaRouter = router({
aiAgent: aiAgentRouter,
aiChat: aiChatRouter,
aiModel: aiModelRouter,
+ agentAvailability: agentAvailabilityRouter,
agentQuota: agentQuotaRouter,
agentShare: agentShareRouter,
aiProvider: aiProviderRouter,
diff --git a/apps/server/src/services/agentAvailability/index.test.ts b/apps/server/src/services/agentAvailability/index.test.ts
new file mode 100644
index 00000000000..43b603439dc
--- /dev/null
+++ b/apps/server/src/services/agentAvailability/index.test.ts
@@ -0,0 +1,167 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentAvailabilityService } from './index';
+
+const mocks = vi.hoisted(() => ({
+ deviceByAgent: {} as Record<string, string>,
+ online: [] as { deviceId: string; online: boolean }[],
+ quota: {} as Record<string, { resetsAt?: number; status: string }>,
+ quotaCalls: [] as { agentId: string; deviceId?: string; provider?: string }[],
+ /** Agents that run Claude Code through bound accounts. */
+ routed: [] as string[],
+ visible: [] as string[],
+}));
+
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: class {
+ queryAgencyRoutingByIds = async (ids: string[]) =>
+ ids
+ .filter((id) => mocks.visible.includes(id))
+ .map((id) => ({
+ agencyConfig: mocks.routed.includes(id)
+ ? { heterogeneousProvider: { type: 'claude-code' } }
+ : id === 'own-login'
+ ? { heterogeneousProvider: { env: { ANTHROPIC_API_KEY: 'sk' }, type: 'claude-code' } }
+ : null,
+ id,
+ }));
+ },
+}));
+vi.mock('@/database/models/device', () => ({ DeviceModel: class {} }));
+vi.mock('@/server/services/agentQuota/resolveDeviceRowId', () => ({
+ resolveDeviceRowId: async (_model: unknown, _ws: unknown, deviceId: string) => `row-${deviceId}`,
+}));
+vi.mock('@/server/routers/lambda/deviceBoundAgents', () => ({
+ loadAgentDeviceBindings: async ({ agentIds }: { agentIds: string[] }) =>
+ Object.fromEntries(
+ agentIds.flatMap((id) => (mocks.deviceByAgent[id] ? [[id, mocks.deviceByAgent[id]]] : [])),
+ ),
+}));
+vi.mock('@/server/services/agentQuota', () => ({
+ AgentQuotaService: class {
+ resolveAgentAvailability = async (
+ agentId: string,
+ options: { deviceId?: string; provider?: string },
+ ) => {
+ mocks.quotaCalls.push({ agentId, deviceId: options.deviceId, provider: options.provider });
+ return mocks.quota[agentId] ?? { accountIds: [], status: 'untracked' };
+ };
+ },
+}));
+vi.mock('@/server/services/deviceGateway/scopedDevices', () => ({
+ getScopedOnlineDevices: async () => mocks.online,
+}));
+vi.mock('@/business/server/managedDevice', () => ({
+ managedDeviceProvider: { isAvailable: async () => false, listStates: async () => ({}) },
+}));
+vi.mock('@/server/services/redis', () => ({
+ redisService: {
+ agentAvailability: {
+ readDevices: async (_pool: string, ids: string[]) => ids.map(() => undefined),
+ readQuotas: async (_user: string, _pool: string, keys: unknown[]) =>
+ keys.map(() => undefined),
+ rememberDevices: async () => {},
+ rememberQuotas: async () => {},
+ },
+ },
+}));
+
+const jobCounts: { agentId: string; value: number }[] = [];
+const db = {
+ select: () => ({
+ from: () => ({
+ innerJoin: () => ({ where: () => ({ groupBy: async () => jobCounts }) }),
+ }),
+ }),
+} as never;
+
+const now = 1_000_000;
+const service = () => new AgentAvailabilityService(db, 'user-1');
+
+beforeEach(() => {
+ mocks.deviceByAgent = {};
+ mocks.online = [];
+ mocks.quota = {};
+ mocks.quotaCalls = [];
+ mocks.routed = [];
+ mocks.visible = [];
+ jobCounts.length = 0;
+});
+
+describe('AgentAvailabilityService', () => {
+ it('answers only for agents the caller can see', async () => {
+ mocks.visible = ['mine'];
+ mocks.routed = ['mine', 'someone-elses'];
+ mocks.deviceByAgent = { 'mine': 'd1', 'someone-elses': 'd2' };
+ mocks.online = [{ deviceId: 'd1', online: true }];
+ jobCounts.push({ agentId: 'mine', value: 1 });
+
+ const result = await service().getAvailability(['mine', 'someone-elses'], now);
+
+ expect(Object.keys(result)).toEqual(['mine']);
+ expect(result.mine).toMatchObject({ activeJobs: 1, dispatchable: true, status: 'working' });
+ expect(mocks.quotaCalls.map((call) => call.agentId)).toEqual(['mine']);
+ });
+
+ it('judges quota on the device row the agent runs on', async () => {
+ mocks.visible = ['a1'];
+ mocks.routed = ['a1'];
+ mocks.deviceByAgent = { a1: 'd1' };
+ mocks.online = [{ deviceId: 'd1', online: true }];
+ mocks.quota = { a1: { resetsAt: now + 60_000, status: 'exhausted' } };
+
+ const result = await service().getAvailability(['a1'], now);
+
+ expect(mocks.quotaCalls).toEqual([
+ { agentId: 'a1', deviceId: 'row-d1', provider: 'claude-code' },
+ ]);
+ expect(result.a1).toMatchObject({
+ dispatchable: false,
+ resetsAt: now + 60_000,
+ status: 'offDuty',
+ });
+ });
+
+ it('never judges an agent whose runs skip bound accounts', async () => {
+ mocks.visible = ['own-login', 'native'];
+ mocks.quota = {
+ 'native': { status: 'exhausted' },
+ 'own-login': { status: 'exhausted' },
+ };
+
+ const result = await service().getAvailability(['own-login', 'native'], now);
+
+ expect(mocks.quotaCalls).toEqual([]);
+ expect(result['own-login']).toMatchObject({ dispatchable: true, status: 'online' });
+ expect(result.native).toMatchObject({ dispatchable: true, status: 'online' });
+ });
+
+ it('never judges a Claude Code agent that runs in the Cloud Sandbox', async () => {
+ mocks.visible = ['sandbox'];
+ mocks.routed = ['sandbox'];
+ mocks.quota = { sandbox: { status: 'exhausted' } };
+
+ const result = await service().getAvailability(['sandbox'], now);
+
+ expect(mocks.quotaCalls).toEqual([]);
+ expect(result.sandbox).toMatchObject({ dispatchable: true, status: 'online' });
+ });
+
+ it('keeps an agent with untracked quota on duty', async () => {
+ mocks.visible = ['a1'];
+ mocks.routed = ['a1'];
+
+ const result = await service().getAvailability(['a1'], now);
+
+ expect(result.a1).toMatchObject({ dispatchable: true, status: 'online' });
+ });
+
+ it('reads an agent whose device is not connected as offline and not dispatchable', async () => {
+ mocks.visible = ['a1'];
+ mocks.deviceByAgent = { a1: 'd1' };
+
+ const result = await service().getAvailability(['a1'], now);
+
+ expect(result.a1).toMatchObject({ dispatchable: false, status: 'offline' });
+ });
+});
diff --git a/apps/server/src/services/agentAvailability/index.ts b/apps/server/src/services/agentAvailability/index.ts
new file mode 100644
index 00000000000..0578cba4893
--- /dev/null
+++ b/apps/server/src/services/agentAvailability/index.ts
@@ -0,0 +1,269 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import { claudeCodeAgentEnvPicksLogin } from '@lobechat/heterogeneous-agents/quota';
+import type { AgentAvailability, LobeAgentAgencyConfig, ManagedDevicePhase } from '@lobechat/types';
+import debug from 'debug';
+import { and, count, eq, inArray } from 'drizzle-orm';
+import pMap from 'p-map';
+
+import { agentDispatchPolicy } from '@/business/server/agentDispatchPolicy';
+import { managedDeviceProvider } from '@/business/server/managedDevice';
+import { AgentModel } from '@/database/models/agent';
+import { DeviceModel } from '@/database/models/device';
+import { channelJobs, channelMembers } from '@/database/schemas';
+import { loadAgentDeviceBindings } from '@/server/routers/lambda/deviceBoundAgents';
+import { AgentQuotaService } from '@/server/services/agentQuota';
+import { resolveDeviceRowId } from '@/server/services/agentQuota/resolveDeviceRowId';
+import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';
+import { redisService } from '@/server/services/redis';
+import type {
+ CachedAgentQuota,
+ CachedDevicePresence,
+} from '@/server/services/redis/agentAvailability';
+
+import { resolveAgentAvailability } from './resolve';
+
+const log = debug('lobe-server:agent-availability');
+
+/**
+ * Whether a device run of this agent is routed through its bound accounts, as device dispatch
+ * decides it (`resolveClaudeAccountRouting`): only Claude Code is, and not when the agent's env
+ * picks its own login (an API key, a config dir). Any other agent is never judged by quota.
+ */
+const routesThroughQuota = (agencyConfig?: LobeAgentAgencyConfig | null) => {
+ const provider = agencyConfig?.heterogeneousProvider;
+ return provider?.type === 'claude-code' && !claudeCodeAgentEnvPicksLogin(provider.env);
+};
+
+/** How long a status read waits for managed device phases; past it they read as unknown. */
+const MANAGED_PHASES_TIMEOUT_MS = 3000;
+
+const withTimeout = async <T>(work: Promise<T>, ms: number, fallback: T): Promise<T> => {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ return await Promise.race([
+ work,
+ new Promise<T>((resolve) => {
+ timer = setTimeout(() => resolve(fallback), ms);
+ }),
+ ]);
+ } catch {
+ return fallback;
+ } finally {
+ clearTimeout(timer);
+ }
+};
+
+/**
+ * Whether Agents can take work right now, for one caller. The one place that combines device
+ * presence, managed device phases, quota and queued work: Channel routing and the contact card
+ * both read it, so what a card shows is what dispatch decides on.
+ *
+ * Device presence and quota loads are served from Redis (`redisService.agentAvailability`), one
+ * key per device in the caller's pool and one per account; a miss does the live read and
+ * remembers it. Queued work is read from the database every time: it moves with each dispatch.
+ */
+export class AgentAvailabilityService {
+ private readonly db: LobeChatDatabase;
+ private readonly userId: string;
+ private readonly workspaceId?: string;
+
+ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ this.db = db;
+ this.userId = userId;
+ this.workspaceId = workspaceId;
+ }
+
+ /** Availability of each agent the caller can see; others are absent. */
+ getAvailability = async (
+ agentIds: string[],
+ now: number = Date.now(),
+ ): Promise<Record<string, AgentAvailability>> => {
+ const requested = [...new Set(agentIds)];
+ if (requested.length === 0) return {};
+
+ // Only agents the caller can see: every read below trusts these ids.
+ const visible = await new AgentModel(
+ this.db,
+ this.userId,
+ this.workspaceId,
+ ).queryAgencyRoutingByIds(requested);
+ const ids = visible.map((agent) => agent.id);
+ if (ids.length === 0) return {};
+
+ const deviceByAgent = await loadAgentDeviceBindings({
+ agentIds: ids,
+ db: this.db,
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ });
+ const [devices, quotas, activeJobs] = await Promise.all([
+ this.readDevices([...new Set(Object.values(deviceByAgent))]),
+ this.readQuotas(
+ // Account routing runs only for a run dispatched to a device; a Cloud Sandbox run uses
+ // its own vault credential, so bindings kept from a device setup do not bench it.
+ visible
+ .filter((agent) => deviceByAgent[agent.id] && routesThroughQuota(agent.agencyConfig))
+ .map((agent) => agent.id),
+ deviceByAgent,
+ now,
+ ),
+ this.countActiveJobs(ids),
+ ]);
+
+ const result: Record<string, AgentAvailability> = {};
+ for (const agentId of ids) {
+ const deviceId = deviceByAgent[agentId];
+ const availability = resolveAgentAvailability({
+ activeJobs: activeJobs.get(agentId) ?? 0,
+ device: deviceId ? devices.get(deviceId) : undefined,
+ deviceId,
+ quota: quotas.get(agentId),
+ });
+ result[agentId] = {
+ ...availability,
+ dispatchable: agentDispatchPolicy.canTakeUnaddressed(availability),
+ };
+ }
+ return result;
+ };
+
+ /**
+ * The principal pool a device's presence is read in: the caller's own, or the caller within
+ * the workspace. Per caller even in a workspace: the scoped device list leaves out another
+ * member's private devices, so one member's view must never answer for another's.
+ */
+ private get pool() {
+ return this.workspaceId ? `ws:${this.workspaceId}:user:${this.userId}` : `user:${this.userId}`;
+ }
+
+ private readDevices = async (deviceIds: string[]) => {
+ const presence = new Map<string, CachedDevicePresence>();
+ if (deviceIds.length === 0) return presence;
+
+ const cached = await redisService.agentAvailability.readDevices(this.pool, deviceIds);
+ deviceIds.forEach((deviceId, i) => {
+ if (cached[i]) presence.set(deviceId, cached[i]);
+ });
+ if (presence.size === deviceIds.length) return presence;
+
+ // One miss reads the whole pool: the gateway and the provider answer per pool anyway, and
+ // remembering every device spares the next caller.
+ const [pool, phases] = await Promise.all([
+ getScopedOnlineDevices(this.db, this.userId, this.workspaceId).catch((error) => {
+ log('device pool read failed: %O', error);
+ return [];
+ }),
+ this.readManagedPhases(),
+ ]);
+ const live = new Map<string, CachedDevicePresence>();
+ for (const device of pool)
+ live.set(device.deviceId, { managedPhase: phases[device.deviceId], online: device.online });
+ for (const [deviceId, managedPhase] of Object.entries(phases))
+ if (!live.has(deviceId)) live.set(deviceId, { managedPhase, online: false });
+
+ void redisService.agentAvailability.rememberDevices(this.pool, live);
+ for (const deviceId of deviceIds) {
+ const value = live.get(deviceId);
+ if (value && !presence.has(deviceId)) presence.set(deviceId, value);
+ }
+ return presence;
+ };
+
+ private readManagedPhases = async (): Promise<Record<string, ManagedDevicePhase>> => {
+ if (!(await managedDeviceProvider.isAvailable().catch(() => false))) return {};
+ return withTimeout(
+ managedDeviceProvider.listStates({ userId: this.userId, workspaceId: this.workspaceId }),
+ MANAGED_PHASES_TIMEOUT_MS,
+ {},
+ );
+ };
+
+ /**
+ * Whether each agent would find quota where it runs, as `AgentQuotaService.resolveAgentAvailability`
+ * judges it: on the accounts a run there is routed to (the device's choice, a strict legacy
+ * pin, or the pool), and only those the caller can see. The answer is remembered per caller,
+ * agent and device, so one member's view never answers for another's.
+ */
+ private readQuotas = async (
+ agentIds: string[],
+ deviceByAgent: Record<string, string>,
+ now: number,
+ ): Promise<Map<string, CachedAgentQuota>> => {
+ const keyOf = (agentId: string) => ({ agentId, deviceId: deviceByAgent[agentId] });
+ const cached = await redisService.agentAvailability.readQuotas(
+ this.userId,
+ this.pool,
+ agentIds.map(keyOf),
+ );
+ const quotas = new Map<string, CachedAgentQuota>();
+ const missing: string[] = [];
+ agentIds.forEach((agentId, i) => {
+ if (cached[i]) quotas.set(agentId, cached[i]);
+ else missing.push(agentId);
+ });
+ if (missing.length === 0) return quotas;
+
+ const quotaService = new AgentQuotaService(this.db, this.userId, this.workspaceId);
+ const deviceModel = new DeviceModel(this.db, this.userId, this.workspaceId);
+ const rowIds = new Map<string, Promise<string | undefined>>();
+ const rowIdOf = (deviceId: string) => {
+ let id = rowIds.get(deviceId);
+ if (!id) {
+ id = resolveDeviceRowId(deviceModel, this.workspaceId, deviceId);
+ rowIds.set(deviceId, id);
+ }
+ return id;
+ };
+
+ const live = await pMap(
+ missing,
+ async (agentId): Promise<[string, CachedAgentQuota] | undefined> => {
+ const deviceId = deviceByAgent[agentId];
+ try {
+ const quota = await quotaService.resolveAgentAvailability(agentId, {
+ deviceId: deviceId ? await rowIdOf(deviceId) : undefined,
+ now,
+ provider: 'claude-code',
+ });
+ return [
+ agentId,
+ {
+ exhausted: quota.status === 'exhausted',
+ ...(quota.resetsAt !== undefined && { resetsAt: quota.resetsAt }),
+ },
+ ];
+ } catch (error) {
+ // Quota is a nice-to-have: a failed read only means "off duty" was not ruled in.
+ log('quota read failed for %s: %O', agentId, error);
+ }
+ },
+ { concurrency: 5 },
+ );
+
+ const fresh = live.filter((entry): entry is [string, CachedAgentQuota] => !!entry);
+ void redisService.agentAvailability.rememberQuotas(
+ this.userId,
+ this.pool,
+ fresh.map(([agentId, quota]) => ({ ...keyOf(agentId), quota })),
+ now,
+ );
+ for (const [agentId, quota] of fresh) quotas.set(agentId, quota);
+ return quotas;
+ };
+
+ /** Channel replies each agent has queued or running, across every Channel. */
+ private countActiveJobs = async (agentIds: string[]) => {
+ const rows = await this.db
+ .select({ agentId: channelMembers.agentId, value: count() })
+ .from(channelJobs)
+ .innerJoin(channelMembers, eq(channelMembers.id, channelJobs.memberId))
+ .where(
+ and(
+ inArray(channelMembers.agentId, agentIds),
+ inArray(channelJobs.status, ['queued', 'running']),
+ ),
+ )
+ .groupBy(channelMembers.agentId);
+ return new Map(rows.flatMap((row) => (row.agentId ? [[row.agentId, row.value]] : [])));
+ };
+}
diff --git a/apps/server/src/services/agentAvailability/resolve.test.ts b/apps/server/src/services/agentAvailability/resolve.test.ts
new file mode 100644
index 00000000000..1b757913b09
--- /dev/null
+++ b/apps/server/src/services/agentAvailability/resolve.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveAgentAvailability } from './resolve';
+
+const spent = { exhausted: true, resetsAt: 1_060_000 };
+const fresh = { exhausted: false };
+
+describe('resolveAgentAvailability', () => {
+ const base = { activeJobs: 0 };
+
+ it('reads a cloud agent with nothing running as online', () => {
+ expect(resolveAgentAvailability(base)).toEqual({ activeJobs: 0, status: 'online' });
+ });
+
+ it('reads a connected device with nothing running as idle', () => {
+ expect(
+ resolveAgentAvailability({ ...base, device: { online: true }, deviceId: 'd1' }).status,
+ ).toBe('idle');
+ });
+
+ it.each([
+ [undefined, 'offline'],
+ ['failed', 'offline'],
+ ['suspended', 'sleeping'],
+ ['suspending', 'sleeping'],
+ ['waking', 'waking'],
+ ['pending', 'waking'],
+ ] as const)('reads a disconnected device in phase %s as %s', (managedPhase, status) => {
+ expect(
+ resolveAgentAvailability({
+ ...base,
+ device: { managedPhase, online: false },
+ deviceId: 'd1',
+ }).status,
+ ).toBe(status);
+ });
+
+ it('reads a device missing from the pool as offline', () => {
+ expect(resolveAgentAvailability({ ...base, deviceId: 'd1' }).status).toBe('offline');
+ });
+
+ it('reads an agent with queued or running replies as working', () => {
+ expect(resolveAgentAvailability({ ...base, activeJobs: 2, quota: fresh })).toEqual({
+ activeJobs: 2,
+ status: 'working',
+ });
+ });
+
+ it('reads an agent out of quota as off duty, even while a run finishes', () => {
+ expect(resolveAgentAvailability({ ...base, activeJobs: 1, quota: spent })).toEqual({
+ activeJobs: 1,
+ resetsAt: 1_060_000,
+ status: 'offDuty',
+ });
+ });
+
+ it('does not rule off duty in when the quota could not be read', () => {
+ expect(resolveAgentAvailability(base).status).toBe('online');
+ });
+
+ it('lets an offline device hide the quota', () => {
+ expect(resolveAgentAvailability({ ...base, deviceId: 'd1', quota: spent }).status).toBe(
+ 'offline',
+ );
+ });
+});
diff --git a/apps/server/src/services/agentAvailability/resolve.ts b/apps/server/src/services/agentAvailability/resolve.ts
new file mode 100644
index 00000000000..aeb761b3e2f
--- /dev/null
+++ b/apps/server/src/services/agentAvailability/resolve.ts
@@ -0,0 +1,57 @@
+import type {
+ AgentAvailability,
+ AgentAvailabilityStatus,
+ ManagedDevicePhase,
+} from '@lobechat/types';
+
+/** Whether an agent's quota is spent where it runs; see `AgentQuotaService.resolveAgentAvailability`. */
+export interface AvailabilityQuota {
+ exhausted: boolean;
+ /** When the first account comes back (ms), if a limit says so. */
+ resetsAt?: number;
+}
+
+/**
+ * What a disconnected device is doing. A managed cloud device that is not
+ * connected is usually asleep, not gone; one that failed or is being deleted
+ * will not come back.
+ */
+const offlineStatus = (phase?: ManagedDevicePhase): AgentAvailabilityStatus => {
+ switch (phase) {
+ case 'suspended':
+ case 'suspending': {
+ return 'sleeping';
+ }
+ case 'pending':
+ case 'running':
+ case 'waking': {
+ return 'waking';
+ }
+ default: {
+ return 'offline';
+ }
+ }
+};
+
+export const resolveAgentAvailability = ({
+ activeJobs,
+ device,
+ deviceId,
+ quota,
+}: {
+ activeJobs: number;
+ /** The bound device's presence, or `undefined` when the pool does not have it. */
+ device?: { managedPhase?: ManagedDevicePhase; online: boolean };
+ /** The device the Agent runs on for the caller; absent for a cloud Agent. */
+ deviceId?: string;
+ /** Absent when it could not be read: "off duty" is then not ruled in. */
+ quota?: AvailabilityQuota;
+}): Omit<AgentAvailability, 'dispatchable'> => {
+ if (deviceId && !device?.online)
+ return { activeJobs, status: offlineStatus(device?.managedPhase) };
+ // Off duty before working: a run already in flight keeps going, but no new work should land.
+ if (quota?.exhausted) return { activeJobs, resetsAt: quota.resetsAt, status: 'offDuty' };
+ if (activeJobs > 0) return { activeJobs, status: 'working' };
+
+ return { activeJobs, status: deviceId ? 'idle' : 'online' };
+};
diff --git a/apps/server/src/services/redis/README.md b/apps/server/src/services/redis/README.md
index c3416c2cb82..95e81dc5feb 100644
--- a/apps/server/src/services/redis/README.md
+++ b/apps/server/src/services/redis/README.md
@@ -3,6 +3,10 @@
Import `redisService` from `@/server/services/redis`. Domains expose business operations;
callers do not choose a provider, prefix, key, SET options or claim lifetime.
+- `agentAvailability`: what the dispatch layer reads to tell whether an Agent can take work β€”
+ device presence per principal pool (30 seconds) and each agent's quota verdict per caller, agent
+ and device (a minute, or until a spent agent's reset, at most ten minutes). Batched reads; a miss or no Redis reads
+ as unknown and the caller does the live read.
- `deviceSystemInfo.remember`: principal/device scoped answers, three minute default freshness;
callers may request a freshness bound through the existing gateway API.
- `skillTools.remember`: connection scoped tool lists, ten minutes; empty/failed results are not cached.
diff --git a/apps/server/src/services/redis/agentAvailability.ts b/apps/server/src/services/redis/agentAvailability.ts
new file mode 100644
index 00000000000..8fc3d55eda4
--- /dev/null
+++ b/apps/server/src/services/redis/agentAvailability.ts
@@ -0,0 +1,111 @@
+import type { ManagedDevicePhase } from '@lobechat/types';
+
+import { RedisKeys } from '@/server/modules/Redis';
+
+import { getRedisServiceClient } from './client';
+
+/** A device as one principal pool sees it. */
+export interface CachedDevicePresence {
+ managedPhase?: ManagedDevicePhase;
+ online: boolean;
+}
+
+/** Whether one agent's quota is spent where it runs. */
+export interface CachedAgentQuota {
+ exhausted: boolean;
+ resetsAt?: number;
+}
+
+/** Which agent, on which device, a quota verdict is about. */
+export interface AgentQuotaKey {
+ agentId: string;
+ deviceId?: string;
+}
+
+/** Presence moves with a socket, so a remembered answer stays short. */
+const DEVICE_TTL_MS = 30 * 1000;
+/** Quota readings arrive with runs; a minute keeps a refill from going unnoticed for long. */
+const QUOTA_TTL_MS = 60 * 1000;
+/**
+ * A spent agent stays spent until its reset, but an account added or re-enabled meanwhile
+ * would put it back on duty, so never trust that for longer than this.
+ */
+const QUOTA_EXHAUSTED_MAX_TTL_MS = 10 * 60 * 1000;
+
+const parse = <T>(raw: string | null): T | undefined => {
+ if (raw === null) return;
+ try {
+ return JSON.parse(raw) as T;
+ } catch {
+ return;
+ }
+};
+
+/** Read many keys at once; a missing key, or no Redis, reads as `undefined`. */
+const readMany = async <T>(keys: string[]): Promise<(T | undefined)[]> => {
+ const redis = await getRedisServiceClient('agentAvailability');
+ if (!redis || keys.length === 0) return keys.map(() => undefined);
+ try {
+ return (await redis.mget(...keys)).map((raw) => parse<T>(raw));
+ } catch {
+ return keys.map(() => undefined);
+ }
+};
+
+/** Fire-and-forget: the caller already has its answer. */
+const writeMany = async (entries: { key: string; ttlMs: number; value: unknown }[]) => {
+ const redis = await getRedisServiceClient('agentAvailability');
+ if (!redis || entries.length === 0) return;
+ const pipeline = redis.pipeline();
+ for (const { key, ttlMs, value } of entries)
+ pipeline.set(key, JSON.stringify(value), { px: Math.max(1, Math.round(ttlMs)) });
+ await pipeline.exec().catch(() => undefined);
+};
+
+const quotaTtlMs = (quota: CachedAgentQuota, now: number) =>
+ quota.exhausted && quota.resetsAt !== undefined && quota.resetsAt > now
+ ? Math.min(quota.resetsAt - now, QUOTA_EXHAUSTED_MAX_TTL_MS)
+ : QUOTA_TTL_MS;
+
+export const agentAvailability = {
+ /** Remembered presence of `deviceIds` in one principal pool, `undefined` where unknown. */
+ readDevices: (pool: string, deviceIds: string[]) =>
+ readMany<CachedDevicePresence>(
+ deviceIds.map((deviceId) => RedisKeys.agentAvailability.device(pool, deviceId)),
+ ),
+
+ rememberDevices: (pool: string, devices: Map<string, CachedDevicePresence>) =>
+ writeMany(
+ [...devices].map(([deviceId, value]) => ({
+ key: RedisKeys.agentAvailability.device(pool, deviceId),
+ ttlMs: DEVICE_TTL_MS,
+ value,
+ })),
+ ),
+
+ /** Remembered quota verdicts, as `userId` sees them in `pool`; `undefined` where unknown. */
+ readQuotas: (userId: string, pool: string, keys: AgentQuotaKey[]) =>
+ readMany<CachedAgentQuota>(
+ keys.map(({ agentId, deviceId }) =>
+ RedisKeys.agentAvailability.quota(userId, pool, agentId, deviceId),
+ ),
+ ),
+
+ /**
+ * Remember quota verdicts. A spent agent is kept until its reset (bounded), so the key
+ * expiring is the quota coming back.
+ */
+ rememberQuotas: (
+ userId: string,
+ pool: string,
+ entries: (AgentQuotaKey & { quota: CachedAgentQuota })[],
+ now = Date.now(),
+ ) =>
+ writeMany(
+ entries.map(({ agentId, deviceId, quota }) => ({
+ key: RedisKeys.agentAvailability.quota(userId, pool, agentId, deviceId),
+ ttlMs: quotaTtlMs(quota, now),
+ value: quota,
+ })),
+ ),
+};
diff --git a/apps/server/src/services/redis/index.ts b/apps/server/src/services/redis/index.ts
index 9c213d8735f..5d7562fe218 100644
--- a/apps/server/src/services/redis/index.ts
+++ b/apps/server/src/services/redis/index.ts
@@ -1,3 +1,4 @@
+import { agentAvailability } from './agentAvailability';
import { agentDocumentIndex } from './agentDocumentIndex';
import { agentIdentity } from './agentIdentity';
import { agentRunSlots } from './agentRunSlots';
@@ -22,6 +23,7 @@ import { workspaceRescan } from './workspaceRescan';
/** Business Redis API. Providers, keys and expiry policy stay inside each domain. */
export const redisService = {
+ agentAvailability,
agentDocumentIndex,
agentIdentity,
agentRunSlots,
diff --git a/packages/business-server/src/agentDispatchPolicy.test.ts b/packages/business-server/src/agentDispatchPolicy.test.ts
new file mode 100644
index 00000000000..e134d7c6a13
--- /dev/null
+++ b/packages/business-server/src/agentDispatchPolicy.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from 'vitest';
+
+import { agentDispatchPolicy } from './agentDispatchPolicy';
+
+describe('agentDispatchPolicy (open source)', () => {
+ it.each([
+ ['online', true],
+ ['idle', true],
+ ['working', true],
+ ['sleeping', true],
+ ['waking', true],
+ ['offline', false],
+ ['offDuty', false],
+ ] as const)('%s β†’ %s', (status, expected) => {
+ expect(agentDispatchPolicy.canTakeUnaddressed({ activeJobs: 5, status })).toBe(expected);
+ });
+});
diff --git a/packages/business-server/src/agentDispatchPolicy.ts b/packages/business-server/src/agentDispatchPolicy.ts
new file mode 100644
index 00000000000..61fa6d1890d
--- /dev/null
+++ b/packages/business-server/src/agentDispatchPolicy.ts
@@ -0,0 +1,20 @@
+import type { AgentAvailability } from '@lobechat/types';
+
+/**
+ * Which Agents an unaddressed Channel message may be routed to. An explicit
+ * @mention never asks the policy: it is a direct assignment.
+ *
+ * The open-source build keeps it simple: any Agent that can still run takes
+ * work, however much it already has queued. A deployment with a resource
+ * scheduler (balance, load) overrides this module through its own
+ * `@/business/server/...` mapping.
+ */
+export interface AgentDispatchPolicy {
+ canTakeUnaddressed: (availability: Omit<AgentAvailability, 'dispatchable'>) => boolean;
+}
+
+export const agentDispatchPolicy: AgentDispatchPolicy = {
+ // Offline: nothing reaches it. Off duty: its runs would fail on quota.
+ // Sleeping and waking devices take work; the message wakes them.
+ canTakeUnaddressed: ({ status }) => status !== 'offline' && status !== 'offDuty',
+};
diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.ts
index 961fe4ca6c2..fbb4d42faa6 100644
--- a/packages/const/src/apiKeyScope.ts
+++ b/packages/const/src/apiKeyScope.ts
@@ -188,6 +188,8 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRule
// is separated onto `agent:credential:write` via
// `TRPC_PROCEDURE_EXTRA_SCOPES` below.
agentAccount: rw('agent:read', 'agent:write'),
+ // read-only status of the caller's agents: presence, queued replies, quota reset time
+ agentAvailability: rw('agent:read', null),
// bot channel wiring carries channel credentials
agentBotProvider: 'blocked',
// a bot's wake records: channel message previews and the owner's marks, read through the same
diff --git a/packages/types/src/agentAvailability.ts b/packages/types/src/agentAvailability.ts
new file mode 100644
index 00000000000..4e25022a35b
--- /dev/null
+++ b/packages/types/src/agentAvailability.ts
@@ -0,0 +1,27 @@
+/**
+ * Whether an Agent can take work right now, as the dispatch layer sees it:
+ *
+ * - `offline`: it runs on a device that is not connected, so nothing reaches it;
+ * - `sleeping`: its managed cloud device is asleep; a message wakes it, so it
+ * still takes work, only the first reply is slower;
+ * - `waking`: its managed cloud device is starting up;
+ * - `offDuty`: every account it can run on has used up its quota;
+ * - `working`: it has a Channel reply queued or running;
+ * - `idle`: its device is connected and nothing is running;
+ * - `online`: a cloud Agent with nothing running β€” it needs no device to answer.
+ *
+ * Checked in that order: a device that is not connected hides everything else, and an Agent
+ * out of quota reads off duty even while a run already in flight finishes.
+ */
+export type AgentAvailabilityStatus =
+ 'idle' | 'offDuty' | 'offline' | 'online' | 'sleeping' | 'waking' | 'working';
+
+export interface AgentAvailability {
+ /** Channel replies the Agent has queued or running, across every Channel. */
+ activeJobs: number;
+ /** Whether an unaddressed message may be routed to it, per the deployment's dispatch policy. */
+ dispatchable: boolean;
+ /** When an off-duty Agent's quota comes back (ms), if every account says so. */
+ resetsAt?: number;
+ status: AgentAvailabilityStatus;
+}
diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts
index cd846974719..9b5741c0c77 100644
--- a/packages/types/src/index.ts
+++ b/packages/types/src/index.ts
@@ -1,5 +1,6 @@
export * from './agent';
export * from './agentAccount';
+export * from './agentAvailability';
export * from './agentExecution';
export * from './agentGroup';
export * from './agentHook';