🤯 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
import { type BuiltinAgentSlug } from '@lobechat/builtin-agents';
import { BUILTIN_AGENTS } from '@lobechat/builtin-agents';
import { DEFAULT_PROVIDER } from '@lobechat/business-const';
import { DEFAULT_MODEL, isAgentShareModelRestrictionExempt } from '@lobechat/const';
import { type LobeChatDatabase } from '@lobechat/database';
import {
type AgentItem,
type CreateAgentConfig,
isLiveAgentShareVisibility,
type LobeAgentChatConfig,
type LobeAgentConfig,
} from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import debug from 'debug';
import { type PartialDeep } from 'type-fest';
import { AGENT_SHARE_ALLOWED_PROVIDERS } from '@/business/agent-share';
import { AgentModel } from '@/database/models/agent';
import { AgentShareModel } from '@/database/models/agentShare';
import { ResourcePermissionModel } from '@/database/models/resourcePermission';
import { SessionModel } from '@/database/models/session';
import { UserModel } from '@/database/models/user';
import { DEFAULT_RESOURCE_ACCESS_LEVELS } from '@/database/schemas';
import { mergeAgentDefaultConfig } from '@/database/utils/agentConfig';
import { normalizeInboxAgentAvatar, normalizeInboxAgentTitle } from '@/database/utils/inboxAgent';
import { getRedisConfig } from '@/envs/redis';
import { getServerDefaultAgentConfig } from '@/server/globalConfig';
import {
getJSONFromRedis,
initializeRedisWithPrefix,
isRedisEnabled,
RedisKeyNamespace,
RedisKeys,
} from '@/server/modules/Redis';
import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';
import { merge } from '@/utils/merge';
import { type UpdateAgentResult } from './type';
const log = debug('lobe-agent:service');
/**
* Whether a config patch can change what a shared agent's model restriction sees: the model
* selection itself, or the driver that exempts it. Clearing a Claude Code driver turns the
* stored selection back into a native one, so it is checked under the same lock.
*/
const touchesShareModel = (value: PartialDeep<AgentItem>): boolean =>
'model' in value ||
'provider' in value ||
value.agencyConfig === null ||
(!!value.agencyConfig && 'heterogeneousProvider' in value.agencyConfig);
/**
* Agent config with required id field.
* Used when returning agent config from database (id is always present).
*/
export type AgentConfigWithId = LobeAgentConfig &
Partial<Pick<AgentItem, 'createdAt'>> &
Pick<AgentItem, 'id' | 'slug' | 'userId' | 'visibility' | 'workspaceId'> & {
/**
* Raw callSubAgent chatConfig override, stamped by execAgent alongside the
* merged chatConfig. The LLM context hints need it to re-apply explicit
* sub-agent reasoning choices over the user's model-instance defaults.
*/
subAgentChatConfigOverride?: Partial<LobeAgentChatConfig>;
};
interface AgentWelcomeData {
openQuestions: string[];
welcomeMessage: string;
}
/**
* Agent Service
*
* Encapsulates "mutation + query" logic for agent operations.
* After performing update operations, returns the updated agent data.
*/
export class AgentService {
private readonly userId: string;
private readonly db: LobeChatDatabase;
private readonly agentModel: AgentModel;
private readonly userModel: UserModel;
private readonly workspaceId?: string;
constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
this.userId = userId;
this.db = db;
this.workspaceId = workspaceId;
this.agentModel = new AgentModel(db, userId, workspaceId);
this.userModel = new UserModel(db, userId);
}
/** Shared creation policy for Agent clients and the native Session adapter. */
async createAgent(input: {
config?: CreateAgentConfig & { pinned?: boolean };
groupId?: string;
visibility?: 'private' | 'public';
}) {
const folderVisibility = input.groupId
? await this.agentModel.getAssignableSessionGroupVisibility(input.groupId)
: undefined;
const visibility = input.visibility;
if (folderVisibility && visibility && visibility !== folderVisibility) {
throw new TRPCError({
code: 'BAD_REQUEST',
message: `A ${visibility} agent cannot be created in a ${folderVisibility} folder`,
});
}
const agent = await this.agentModel.create({
...input.config,
sessionGroupId: input.groupId,
...(visibility || folderVisibility ? { visibility: visibility ?? folderVisibility } : {}),
});
if (this.workspaceId && agent.visibility !== 'private') {
await new ResourcePermissionModel(this.db, this.workspaceId).setAccessLevel(
'agent',
agent.id,
DEFAULT_RESOURCE_ACCESS_LEVELS.agent,
this.userId,
);
}
return { agentId: agent.id };
}
/**
* Validate the effective selection at configuration boundaries, including inherited defaults.
*
* Returns the resolved selection to pin, or `undefined` when there is nothing to check.
* A locally executed CLI agent (Claude Code, Codex, …) is exempt (`isAgentShareModelRestrictionExempt`): it runs on the
* creator's device and calls none of `provider`'s models. The decision reads the effective
* driver, the stored one merged with the patch, so switching back to LobeHub
* (`heterogeneousProvider: null`) is checked as usual, and a real provider saved next to the
* driver is checked too, since clearing the driver would make it the native selection.
*/
async assertShareModelAllowed(agentId: string, patch: PartialDeep<AgentItem> = {}) {
if (!AGENT_SHARE_ALLOWED_PROVIDERS) return;
const agent = await this.agentModel.getAgentConfigById(agentId);
if (!agent) throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });
// Same deep merge as `AgentModel.updateConfig`, so a partial driver edit (`env` only) keeps
// the stored `type`. `agencyConfig: null` clears the whole block and must not fall back to it.
const effectiveAgencyConfig =
'agencyConfig' in patch
? patch.agencyConfig === null
? null
: merge(agent.agencyConfig ?? {}, patch.agencyConfig)
: agent.agencyConfig;
const provider = 'provider' in patch ? patch.provider : agent.provider;
if (
isAgentShareModelRestrictionExempt({
agencyConfig: effectiveAgencyConfig as AgentItem['agencyConfig'],
provider,
})
)
return;
// Moving between two heterogeneous drivers clears the old one first and writes the new
// one second. The cleared row keeps only the runtime stamp, which names no chat provider.
if (
!effectiveAgencyConfig?.heterogeneousProvider &&
isAgentShareModelRestrictionExempt({ agencyConfig: agent.agencyConfig, provider })
)
return;
const selection = await this.resolveModelSelection({ ...agent, ...patch });
if (!AGENT_SHARE_ALLOWED_PROVIDERS.includes(selection.provider)) {
throw new TRPCError({
code: 'BAD_REQUEST',
message: `Shared agents only support models from: ${AGENT_SHARE_ALLOWED_PROVIDERS.join(', ')}. Switch providers or turn off sharing first.`,
});
}
return selection;
}
/** Serialize provider changes and publication on the existing shared-agent row lock. */
async withShareModelLock<T>(
agentId: string,
action: (service: AgentService, shares: AgentShareModel) => Promise<T>,
): Promise<T> {
if (!AGENT_SHARE_ALLOWED_PROVIDERS) {
return action(this, new AgentShareModel(this.db, this.userId, this.workspaceId));
}
return this.db.transaction(async (transaction) => {
const tx = transaction as LobeChatDatabase;
if (
!(await AgentShareModel.lockScopedAgentRow(tx, agentId, {
userId: this.userId,
workspaceId: this.workspaceId,
}))
) {
throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });
}
if (this.workspaceId) {
await assertCanPerformResourceAction({
action: 'manage',
db: tx,
resourceId: agentId,
resourceType: 'agent',
userId: this.userId,
workspaceId: this.workspaceId,
});
}
return action(
new AgentService(tx, this.userId, this.workspaceId),
new AgentShareModel(tx, this.userId, this.workspaceId),
);
});
}
/** Pin inherited defaults so later account changes cannot alter a published model. */
async prepareShareModel(agentId: string) {
const selection = await this.assertShareModelAllowed(agentId);
if (selection) await this.agentModel.updateConfig(agentId, selection);
}
async createInbox() {
const sessionModel = new SessionModel(this.db, this.userId, this.workspaceId);
const defaultAgentConfig = getServerDefaultAgentConfig();
await sessionModel.createInbox(defaultAgentConfig);
}
/**
* Get a builtin agent by slug, creating it if it doesn't exist.
* This is a generic interface for all builtin agents (page-copilot, inbox, etc.)
*
* The returned agent config is merged with:
* 1. DEFAULT_AGENT_CONFIG (hardcoded defaults)
* 2. Server's globalDefaultAgentConfig (from environment variable DEFAULT_AGENT_CONFIG)
* 3. The actual agent config from database
* 4. Avatar from builtin-agents package definition (if available)
*
* This ensures the frontend always receives a complete config with model/provider.
*/
async getBuiltinAgent(slug: string) {
// Fetch agent and defaultAgentConfig in parallel
const [agent, defaultAgentConfig] = await Promise.all([
this.agentModel.getBuiltinAgent(slug),
this.userModel.getUserSettingsDefaultAgentConfig(),
]);
const mergedConfig = this.mergeDefaultConfig(agent, defaultAgentConfig);
if (!mergedConfig) return null;
return this.applyBuiltinIdentity(mergedConfig, slug);
}
/**
* Builtin agent rows are provisioned without avatar/title (see
* `AgentModel.getBuiltinAgent`) — their identity lives in the builtin-agents
* package definition, and in branding constants for the inbox. Every read
* path that returns an agent snapshot must re-apply that identity: the
* client treats `fetchAgentConfig` responses as authoritative full snapshots
* and replaces its cached entry, so a snapshot missing the avatar clobbers a
* previously correct one and the UI falls back to the default robot avatar.
*/
private applyBuiltinIdentity<T extends LobeAgentConfig>(config: T, fallbackSlug?: string): T {
const slug = (config as { slug?: string | null }).slug ?? fallbackSlug;
const identity = { slug };
const normalizedConfig = {
...config,
avatar: normalizeInboxAgentAvatar(config.avatar, identity),
title: normalizeInboxAgentTitle(config.title, identity),
};
// Use builtin avatar as fallback only when DB has no custom avatar
const builtinAgent = slug ? BUILTIN_AGENTS[slug as BuiltinAgentSlug] : undefined;
if (builtinAgent?.avatar && !normalizedConfig.avatar) {
return { ...normalizedConfig, avatar: builtinAgent.avatar };
}
return normalizedConfig;
}
/**
* Get agent config by ID or slug with default config merged.
* Supports both agentId and slug lookup.
*
* The returned agent config is merged with:
* 1. DEFAULT_AGENT_CONFIG (hardcoded defaults)
* 2. Server's globalDefaultAgentConfig (from environment variable DEFAULT_AGENT_CONFIG)
* 3. User's defaultAgentConfig (from user settings)
* 4. The actual agent config from database
*/
async getAgentConfig(idOrSlug: string): Promise<AgentConfigWithId | null> {
const [agent, defaultAgentConfig] = await Promise.all([
this.agentModel.getAgentConfig(idOrSlug),
this.userModel.getUserSettingsDefaultAgentConfig(),
]);
const config = this.mergeDefaultConfig(agent, defaultAgentConfig) as AgentConfigWithId | null;
if (!config) return null;
return this.applyBuiltinIdentity(config);
}
/**
* Get agent config by ID with default config merged.
*
* The returned agent config is merged with:
* 1. DEFAULT_AGENT_CONFIG (hardcoded defaults)
* 2. Server's globalDefaultAgentConfig (from environment variable DEFAULT_AGENT_CONFIG)
* 3. User's defaultAgentConfig (from user settings)
* 4. The actual agent config from database
* 5. AI-generated welcome data from Redis (if available)
*/
async getAgentConfigById(agentId: string) {
const [agent, defaultAgentConfig, welcomeData] = await Promise.all([
this.agentModel.getAgentConfigById(agentId),
this.userModel.getUserSettingsDefaultAgentConfig(),
this.getAgentWelcomeFromRedis(agentId),
]);
const config = this.mergeDefaultConfig(agent, defaultAgentConfig);
if (!config) return null;
const normalizedConfig = this.applyBuiltinIdentity(config);
// Merge AI-generated welcome data if available
if (welcomeData) {
return {
...normalizedConfig,
openingMessage: welcomeData.welcomeMessage,
openingQuestions: welcomeData.openQuestions,
};
}
return normalizedConfig;
}
/**
* The model and provider a run of this agent actually uses: the same
* `DEFAULT_AGENT_CONFIG` → server default → user default → agent layering
* as {@link getAgentConfig}, narrowed to those two fields. For read paths
* that only need to know which model will answer (deriving what media a
* share visitor may attach, for instance) without loading the agent's
* knowledge and documents.
*/
async resolveModelSelection(agent: {
model?: string | null;
provider?: string | null;
}): Promise<{ model: string; provider: string }> {
const defaultAgentConfig = await this.userModel.getUserSettingsDefaultAgentConfig();
const merged = this.mergeDefaultConfig(
{ model: agent.model, provider: agent.provider },
defaultAgentConfig,
)!;
// `LobeAgentConfig` types both as optional even though `DEFAULT_AGENT_CONFIG`
// always supplies them; the fallbacks are those same constants.
return { model: merged.model ?? DEFAULT_MODEL, provider: merged.provider ?? DEFAULT_PROVIDER };
}
/**
* Get AI-generated welcome data from Redis
* Returns null if Redis is disabled or data doesn't exist
*/
private async getAgentWelcomeFromRedis(agentId: string): Promise<AgentWelcomeData | null> {
try {
const redisConfig = getRedisConfig();
if (!isRedisEnabled(redisConfig)) return null;
const redis = await initializeRedisWithPrefix(redisConfig, RedisKeyNamespace.AI_GENERATION);
return getJSONFromRedis<AgentWelcomeData>(
redis,
RedisKeys.aiGeneration.agentWelcome(agentId),
);
} catch (error) {
// Log error for observability but don't break agent retrieval
log('Failed to get agent welcome from Redis for agent %s: %O', agentId, error);
return null;
}
}
/**
* Merge default config with agent config.
* Returns null if agent is null/undefined.
*
* Merge order (later values override earlier):
* 1. DEFAULT_AGENT_CONFIG - hardcoded defaults
* 2. serverDefaultAgentConfig - from environment variable
* 3. userDefaultAgentConfig - from user settings (defaultAgent.config)
* 4. agent - actual agent config from database
*
* Workspace exception: a workspace is a shared resource, so its agents must
* NOT inherit any individual member's *personal* default model. Otherwise a
* shared agent persisted with an empty model (e.g. the workspace inbox)
* resolves to whoever opens it — the creator's personal default leaks in and
* the workspace looks "initialized" with their model. For workspace-scoped
* reads we skip the user layer and fall back to the system default instead.
*/
private mergeDefaultConfig(
agent: any,
defaultAgentConfig: Awaited<ReturnType<UserModel['getUserSettingsDefaultAgentConfig']>>,
): LobeAgentConfig | null {
if (!agent) return null;
return mergeAgentDefaultConfig(agent, {
serverDefault: getServerDefaultAgentConfig(),
userDefault: defaultAgentConfig,
workspaceId: this.workspaceId,
});
}
/**
* Update agent config and return the updated data
* Pattern: update + query
*
* This method combines config update and querying into a single operation,
* reducing the need for separate refresh calls and improving performance.
*/
async updateAgentConfig(
agentId: string,
value: PartialDeep<AgentItem>,
replaceWorkingDirDeviceIds?: string[],
): Promise<UpdateAgentResult> {
if (AGENT_SHARE_ALLOWED_PROVIDERS && !this.workspaceId && touchesShareModel(value)) {
return this.withShareModelLock(agentId, (service) =>
service.saveAgentConfig(agentId, value, replaceWorkingDirDeviceIds),
);
}
return this.saveAgentConfig(agentId, value, replaceWorkingDirDeviceIds);
}
private async saveAgentConfig(
agentId: string,
value: PartialDeep<AgentItem>,
replaceWorkingDirDeviceIds?: string[],
): Promise<UpdateAgentResult> {
// The prompt editor prefers editorData over systemRole, so a systemRole-only
// write must drop the old rich document or the editor shows stale content.
if ('systemRole' in value && !('editorData' in value)) {
value = { ...value, editorData: null } as PartialDeep<AgentItem>;
}
if (AGENT_SHARE_ALLOWED_PROVIDERS && touchesShareModel(value)) {
const share = await new AgentShareModel(this.db, this.userId, this.workspaceId).getByAgentId(
agentId,
);
if (isLiveAgentShareVisibility(share?.visibility)) {
const selection = await this.assertShareModelAllowed(agentId, value);
value = { ...value, ...selection };
}
}
// 1. Execute update
await this.agentModel.updateConfig(agentId, value as any, replaceWorkingDirDeviceIds);
// 2. Query and return updated data (with default config merged)
const agent = await this.getAgentConfigById(agentId);
if (!agent) throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });
return { agent: agent as any, success: true };
}
}