π€― 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
β»οΈ refactor(server): resolve the run agent config through the shared mecha rules (#19525)
Arvin Xucaefd70f7fad
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.tsindex 0679f0d0615..3d1d234645b 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts@@ -469,6 +469,12 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {expect(callArgs.agentConfig.systemRole).toBe(customSystemRole);});+ // Regular agents get no builtin runtime prompt. They do get the user's reply+ // language appended β the same rule the client runtime applies, now shared+ // through `@lobechat/mecha`.+ const REPLY_LANGUAGE_ONLY =+ 'Preferred reply language: en-US. Use this language unless the user explicitly asks to switch.';+it('should not apply runtime config for non-builtin agents', async () => {mockGetAgentConfig.mockResolvedValue({chatConfig: {},@@ -486,8 +492,8 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {});const callArgs = mockCreateOperation.mock.calls[0][0];- // Should remain empty - no runtime config applied- expect(callArgs.agentConfig.systemRole).toBe('');+ // No runtime prompt applied β only the reply-language instruction.+ expect(callArgs.agentConfig.systemRole).toBe(REPLY_LANGUAGE_ONLY);});it('should not apply runtime config for agents without slug', async () => {@@ -506,7 +512,7 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {});const callArgs = mockCreateOperation.mock.calls[0][0];- expect(callArgs.agentConfig.systemRole).toBe('');+ expect(callArgs.agentConfig.systemRole).toBe(REPLY_LANGUAGE_ONLY);});it('should persist request trigger metadata on the created user message', async () => {diff --git a/apps/server/src/services/aiAgent/__tests__/resolveRunAgentConfig.test.ts b/apps/server/src/services/aiAgent/__tests__/resolveRunAgentConfig.test.tsnew file mode 100644index 00000000000..b29ca331645--- /dev/null+++ b/apps/server/src/services/aiAgent/__tests__/resolveRunAgentConfig.test.ts@@ -0,0 +1,126 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { resolveRunAgentConfig } from '../pipeline/resolveRunAgentConfig';++const { getInfoForAIGeneration, getPreference, isResourceAuthorOrAdmin } = vi.hoisted(() => ({+ getInfoForAIGeneration: vi.fn(),+ getPreference: vi.fn(),+ isResourceAuthorOrAdmin: vi.fn(),+}));++vi.mock('@/database/models/workspaceUserSettings', () => ({+ WorkspaceUserSettingsModel: class {+ getPreference = getPreference;+ },+}));++vi.mock('@/database/models/user', () => ({+ UserModel: { getInfoForAIGeneration },+}));++vi.mock('@/server/services/resourcePermission', () => ({+ isResourceAuthorOrAdmin,+}));++const deps = {+ db: {} as never,+ userId: 'member-1',+ workspaceId: 'ws-1',+};++const webOnboardingRow = () =>+ ({+ agencyConfig: undefined,+ chatConfig: {},+ id: 'agent-web-onboarding',+ model: 'gpt-4',+ plugins: [],+ provider: 'openai',+ slug: 'web-onboarding',+ systemRole: '',+ userId: 'author-1',+ visibility: 'public',+ workspaceId: 'ws-1',+ }) as never;++describe('resolveRunAgentConfig', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getPreference.mockResolvedValue({});+ isResourceAuthorOrAdmin.mockResolvedValue(false);+ getInfoForAIGeneration.mockResolvedValue({ responseLanguage: 'en-US' });+ });++ it('keeps a builtin runtime execution target over a saved member device override', async () => {+ // A workspace member pinned this agent to their local device β¦+ getPreference.mockResolvedValue({+ agentDeviceOverrides: {+ 'agent-web-onboarding': { boundDeviceId: 'dev-1', executionTarget: 'local' },+ },+ });++ const { agentConfig } = await resolveRunAgentConfig(+ { ...deps, resolveAgentConfigOrThrow: async () => webOnboardingRow() },+ { identifier: 'agent-web-onboarding', throwIfExecutionAborted: async () => {} },+ );++ // β¦ but the onboarding runtime disables execution outright, and the+ // runtime policy is merged on top of the member preference, not under it.+ expect(agentConfig.agencyConfig?.executionTarget).toBe('none');+ });++ it('reads the reply language for the share visitor, not the owner, on a shared-agent run', async () => {+ getInfoForAIGeneration.mockImplementation(async (_db: unknown, userId: string) => ({+ responseLanguage: userId === 'visitor-1' ? 'ja-JP' : 'en-US',+ }));++ const { agentConfig } = await resolveRunAgentConfig(+ {+ ...deps,+ resolveAgentConfigOrThrow: async () =>+ ({ ...(webOnboardingRow() as object), id: 'agent-regular', slug: null }) as never,+ },+ {+ identifier: 'agent-regular',+ shareVisitorUserId: 'visitor-1',+ throwIfExecutionAborted: async () => {},+ },+ );++ expect(getInfoForAIGeneration).toHaveBeenCalledWith(expect.anything(), 'visitor-1');+ expect(agentConfig.systemRole).toContain('Preferred reply language: ja-JP');+ });++ it('reads the reply language for the caller on an ordinary run', async () => {+ await resolveRunAgentConfig(+ {+ ...deps,+ resolveAgentConfigOrThrow: async () =>+ ({ ...(webOnboardingRow() as object), id: 'agent-regular', slug: null }) as never,+ },+ { identifier: 'agent-regular', throwIfExecutionAborted: async () => {} },+ );++ expect(getInfoForAIGeneration).toHaveBeenCalledWith(expect.anything(), 'member-1');+ });++ it('applies a saved member device override to a regular workspace agent', async () => {+ getPreference.mockResolvedValue({+ agentDeviceOverrides: {+ 'agent-regular': { boundDeviceId: 'dev-1', executionTarget: 'local' },+ },+ });++ const { agentConfig, memberDeviceOverride } = await resolveRunAgentConfig(+ {+ ...deps,+ resolveAgentConfigOrThrow: async () =>+ ({ ...(webOnboardingRow() as object), id: 'agent-regular', slug: null }) as never,+ },+ { identifier: 'agent-regular', throwIfExecutionAborted: async () => {} },+ );++ expect(memberDeviceOverride).toEqual({ boundDeviceId: 'dev-1', executionTarget: 'local' });+ expect(agentConfig.agencyConfig?.executionTarget).toBe('local');+ });+});diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 9925be4a359..c1d1a998283 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -834,6 +834,7 @@ export class AiAgentService {instructions,modelOverride,providerOverride,+ shareVisitorUserId: shareGate?.visitorUserId,throwIfExecutionAborted,toolModeOverride,},diff --git a/apps/server/src/services/aiAgent/pipeline/resolveRunAgentConfig.ts b/apps/server/src/services/aiAgent/pipeline/resolveRunAgentConfig.tsindex e94ade73aa2..e9fc64c54f3 100644--- a/apps/server/src/services/aiAgent/pipeline/resolveRunAgentConfig.ts+++ b/apps/server/src/services/aiAgent/pipeline/resolveRunAgentConfig.ts@@ -1,20 +1,8 @@-import {- BUILTIN_AGENT_SLUGS,- getAgentRuntimeConfig,- isCollaborativeBuiltinAgentRow,-} from '@lobechat/builtin-agents';-import { LobeAgentIdentifier } from '@lobechat/builtin-tool-lobe-agent';-import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';-import { TaskIdentifier } from '@lobechat/builtin-tool-task';import { resolveSubAgentChatConfig } from '@lobechat/const';import type { LobeChatDatabase } from '@lobechat/database';-import type { AgentModelOverride, LobeAgentAgencyConfig } from '@lobechat/types';-import {- getActivePluginIds,- getDisabledPluginIds,- resolveAgentAgencyConfig,- resolveAgentModelConfig,-} from '@lobechat/types';+import { type AgentConfigSnapshot, resolveAgentConfig } from '@lobechat/mecha';+import type { AgentModelOverride, LobeAgentAgencyConfig, MessageMapScope } from '@lobechat/types';+import { getDisabledPluginIds, resolveAgentAgencyConfig } from '@lobechat/types';import debug from 'debug';import { UserModel } from '@/database/models/user';@@ -41,6 +29,12 @@ export interface ResolveRunAgentConfigInput {instructions?: string;modelOverride?: string;providerOverride?: string;+ /**+ * The share visitor actually driving a shared-agent run. The service is+ * constructed as the share owner, so caller-scoped facts (the reply+ * language appended to the system role) must be read for this user instead.+ */+ shareVisitorUserId?: string;throwIfExecutionAborted: (stage: string) => Promise<void>;toolModeOverride?: InternalExecAgentParams['toolModeOverride'];}@@ -68,16 +62,98 @@ export interface ResolvedRunAgentConfig {resolvedAgentId: string;}+interface WorkspaceMemberOverrides {+ device?: Pick<LobeAgentAgencyConfig, 'boundDeviceId' | 'executionTarget'>;+ mode?: boolean;+ model?: AgentModelOverride;+}++/**+ * This caller's workspace-scoped execution / model / mode preferences for the+ * agent. They live in the dedicated per-(workspace, user) settings row and+ * never mutate the shared Agent config. Losing them is non-fatal: execution+ * falls back to the shared row.+ */+const loadWorkspaceMemberOverrides = async (+ deps: ResolveRunAgentConfigDeps,+ agentId: string,+): Promise<WorkspaceMemberOverrides> => {+ if (!deps.workspaceId) return {};+ try {+ const preference = await new WorkspaceUserSettingsModel(+ deps.db,+ deps.userId,+ deps.workspaceId,+ ).getPreference();+ return {+ device: preference.agentDeviceOverrides?.[agentId],+ mode: preference.agentModeOverrides?.[agentId],+ model: preference.agentModelOverrides?.[agentId],+ };+ } catch (error) {+ log('execAgent: failed to load caller workspace_user_settings preferences: %O', error);+ return {};+ }+};++/**+ * Author-or-admin, NOT the configuration flag: this value decides whether the+ * run ignores the member's own model / device / mode overrides, and a+ * collaborative builtin must keep honoring them β the client runtime resolves+ * the same distinction from authorship. Permission lookup failure is+ * fail-closed: applying member policy is safer than accidentally granting+ * shared-config semantics.+ */+const resolveCanManage = async (+ deps: ResolveRunAgentConfigDeps,+ agentConfig: AgentConfigWithId,+ agentWorkspaceId: string | undefined,+ isPublicWorkspaceAgent: boolean,+): Promise<boolean> => {+ if (agentConfig.userId === deps.userId) return true;+ if (!isPublicWorkspaceAgent || !agentWorkspaceId) return false;+ try {+ return await isResourceAuthorOrAdmin({+ db: deps.db,+ meta: {+ userId: agentConfig.userId,+ visibility: agentConfig.visibility ?? 'public',+ workspaceId: agentWorkspaceId,+ },+ resourceType: 'agent',+ userId: deps.userId,+ workspaceId: agentWorkspaceId,+ });+ } catch (error) {+ log('execAgent: failed to resolve Agent management access: %O', error);+ return false;+ }+};++const loadUserLocale = async (+ deps: ResolveRunAgentConfigDeps,+ userId: string,+): Promise<string | undefined> => {+ try {+ const userInfo = await UserModel.getInfoForAIGeneration(deps.db, userId);+ return userInfo.responseLanguage;+ } catch (error) {+ log('execAgent: failed to load user locale for agent config resolution: %O', error);+ return undefined;+ }+};+/*** Stages 1β2.5 of {@link AiAgentService.execAgent}: resolve the effective agent* configuration for this run.*- * Covers: config fetch (id or slug), per-(workspace, user) member overrides- * (device / model / mode), author-or-admin management access, agency-config- * resolution, callSubAgent chatConfig patches, the IM `/mode` override, the- * persistence-attribution agent ids, final model resolution, builtin-agent- * runtime merge, page/task scope injection, sub-agent tool stripping, and the- * per-call `instructions` systemRole append.+ * Gathers what the shared rules need from the server's own sources (the agent+ * row, the caller's workspace member overrides, author-or-admin access, the+ * user's reply language), runs `resolveAgentConfig` from `@lobechat/mecha` β+ * the same rules the client runtime applies β and then layers the per-call+ * intents only a run knows about: the member device override, callSubAgent+ * chatConfig patches, the IM `/mode` override, the persistence-attribution+ * agent ids and the per-call `instructions` systemRole append.*/export const resolveRunAgentConfig = async (deps: ResolveRunAgentConfigDeps,@@ -90,86 +166,81 @@ export const resolveRunAgentConfig = async (instructions,modelOverride,providerOverride,+ shareVisitorUserId,throwIfExecutionAborted,toolModeOverride,} = input;- // 1. Get agent configuration with default config merged (supports both id and slug)- const agentConfig = await deps.resolveAgentConfigOrThrow(identifier);-- // Use actual agent ID from config for subsequent operations- const resolvedAgentId = agentConfig.id;- let memberDeviceOverride:- Pick<LobeAgentAgencyConfig, 'boundDeviceId' | 'executionTarget'> | undefined;- let memberModelOverride: AgentModelOverride | undefined;- let memberModeOverride: boolean | undefined;-- // Layer this caller's workspace-scoped execution and model preferences over- // the shared Agent row. Device selection keeps its existing fallback rules;- // public Workspace Agents allow member choice by default unless the author- // explicitly fixes the model. Both overrides live in the dedicated per-- // (workspace, user) settings row and never mutate shared Agent config.- if (deps.workspaceId) {- try {- const workspaceUserSettings = new WorkspaceUserSettingsModel(- deps.db,- deps.userId,- deps.workspaceId,- );- const preference = await workspaceUserSettings.getPreference();- memberDeviceOverride = preference.agentDeviceOverrides?.[resolvedAgentId];- memberModelOverride = preference.agentModelOverrides?.[resolvedAgentId];- memberModeOverride = preference.agentModeOverrides?.[resolvedAgentId];- } catch (error) {- // Losing preferences is non-fatal: execution falls back to the shared- // Agent row.- log('execAgent: failed to load caller workspace_user_settings preferences: %O', error);- }- }-- let canManageAgent = agentConfig.userId === deps.userId;- const agentWorkspaceId = agentConfig.workspaceId ?? deps.workspaceId;- const isPublicWorkspaceAgent = !!agentWorkspaceId && agentConfig.visibility !== 'private';- if (isPublicWorkspaceAgent && !canManageAgent) {- try {- // Author-or-admin, NOT the configuration flag: this value decides whether- // the run ignores the member's own model / device / mode overrides, and a- // collaborative builtin must keep honoring them β the client runtime- // (`agentConfigResolver`) resolves the same distinction from authorship.- canManageAgent = await isResourceAuthorOrAdmin({- db: deps.db,- meta: {- userId: agentConfig.userId,- visibility: agentConfig.visibility ?? 'public',- workspaceId: agentWorkspaceId,- },- resourceType: 'agent',- userId: deps.userId,- workspaceId: agentWorkspaceId,- });- } catch (error) {- // Permission lookup failure is fail-closed: applying member policy is- // safer than accidentally granting shared-config semantics.- log('execAgent: failed to resolve Agent management access: %O', error);- }- }+ // --- gather the snapshot ---+ const row = await deps.resolveAgentConfigOrThrow(identifier);+ const resolvedAgentId = row.id;+ const agentWorkspaceId = row.workspaceId ?? deps.workspaceId;+ const isPublicWorkspaceAgent = !!agentWorkspaceId && row.visibility !== 'private';++ const [overrides, canManageAgent, userLocale] = await Promise.all([+ loadWorkspaceMemberOverrides(deps, resolvedAgentId),+ resolveCanManage(deps, row, agentWorkspaceId, isPublicWorkspaceAgent),+ // A share visitor replies in their own language, not the owner's.+ loadUserLocale(deps, shareVisitorUserId ?? deps.userId),+ ]);++ // The caller's device preference layers onto the shared row BEFORE the+ // shared rules run, so a builtin runtime that pins its own execution target+ // (the onboarding agents set `executionTarget: 'none'`) still wins over a+ // saved member override when its `agencyConfig` is merged on top.+ row.agencyConfig = resolveAgentAgencyConfig(row.agencyConfig, overrides.device, {+ canManage: canManageAgent,+ visibility: row.visibility,+ workspaceId: agentWorkspaceId,+ });++ const snapshot: AgentConfigSnapshot = {+ agent: {+ name: row.name ?? null,+ slug: row.slug,+ title: row.title ?? null,+ userId: row.userId,+ virtual: (row as { virtual?: boolean | null }).virtual,+ visibility: row.visibility,+ workspaceId: agentWorkspaceId ?? null,+ },+ agentConfig: row,+ canManage: canManageAgent,+ chatConfig: row.chatConfig,+ memberModeOverride: overrides.mode,+ memberModelOverride: overrides.model,+ slug: row.slug ?? undefined,+ userLocale,+ };- agentConfig.agencyConfig = resolveAgentAgencyConfig(- agentConfig.agencyConfig,- memberDeviceOverride,+ // --- shared rules ---+ const resolved = resolveAgentConfig({- canManage: canManageAgent,- visibility: agentConfig.visibility,- workspaceId: agentWorkspaceId,+ agentId: resolvedAgentId,+ groupId: appContext?.groupId ?? undefined,+ isSubAgent: appContext?.isSubAgent,+ modelOverride: {+ ...(modelOverride ? { model: modelOverride } : {}),+ ...(providerOverride ? { provider: providerOverride } : {}),+ },+ scope: (appContext?.scope ?? undefined) as MessageMapScope | undefined,},+ snapshot,);- if (!canManageAgent && memberModeOverride !== undefined) {- agentConfig.chatConfig = {- ...agentConfig.chatConfig,- enableAgentMode: memberModeOverride,- };- }+ // Capture disabled identifiers off the row before the resolved config+ // collapses plugins to pinned ids: they later filter the auto-discovery+ // candidate pool so a disabled plugin can't be rediscovered.+ const disabledPluginIds = getDisabledPluginIds(row.plugins);++ // One mutable object from here on β later stages append to `systemRole` and+ // `createOperation` must see those writes.+ const agentConfig: AgentConfigWithId = Object.assign(row, resolved.agentConfig, {+ chatConfig: resolved.chatConfig,+ plugins: resolved.plugins,+ });++ // --- per-call intents the shared rules do not know ---// callSubAgent thinking / reasoning-effort overrides. A virtual sub-agent// executes the same agent row, so `agentConfig.chatConfig` here IS the// parent's chatConfig β merging the `agencyConfig.subagent.chatConfig`@@ -217,33 +288,6 @@ export const resolveRunAgentConfig = async (const conversationAgentId = appContext?.conversationAgentId ?? persistAgentId;const assistantAgentId = appContext?.conversationAgentId ? resolvedAgentId : persistAgentId;- // Resolve the final model once, keeping per-call task / sub-agent overrides- // above the caller's personal workspace choice and the shared Agent default.- // The callSubAgent spawn site resolves the sub-agent default and passes it- // explicitly, so this path never has to special-case sub-agents.- const effectiveModel = resolveAgentModelConfig(- {- ...agentConfig,- canManage: canManageAgent,- // A collaborative builtin is Workspace infrastructure with no author and- // no config page, so its model is personal for every caller β being its- // creator or an admin must not pin the whole Workspace to one model.- // Device / mode overrides keep the ordinary author rule above.- personalModelSelection: isCollaborativeBuiltinAgentRow({- ...agentConfig,- workspaceId: agentWorkspaceId,- }),- workspaceId: agentWorkspaceId,- },- memberModelOverride,- {- ...(modelOverride ? { model: modelOverride } : {}),- ...(providerOverride ? { provider: providerOverride } : {}),- },- );- agentConfig.model = effectiveModel.model;- agentConfig.provider = effectiveModel.provider;-log('execAgent: got agent config for %s (id: %s), model: %s, provider: %s',identifier,@@ -252,115 +296,6 @@ export const resolveRunAgentConfig = async (agentConfig.provider,);- // Capture disabled identifiers before collapsing to pinned-only ids below- // β everything from here on (builtin runtime merge, page/task/sub-agent- // injection, the `agentPlugins` build further down) expects a plain- // pinned-id string[], matching pre-tri-state behavior. Operating on a- // local `string[]` (rather than repeatedly re-reading/writing- // `agentConfig.plugins`, whose declared type is the wider- // `AgentPluginEntry[]`) keeps this whole block free of per-line casts;- // `agentConfig.plugins` is written back once, at the end.- // `disabledPluginIds` is consumed later to filter the auto-discovery- // candidate pool (installedPlugins) so disabled plugins can't be- // rediscovered/activated by the auto activator.- const disabledPluginIds = getDisabledPluginIds(agentConfig.plugins);- let activePluginIds: string[] = getActivePluginIds(agentConfig.plugins);-- // 2. Merge builtin agent runtime config (systemRole, plugins)- // The DB only stores persist config. Runtime config (e.g. inbox systemRole) is generated dynamically.- const agentSlug = agentConfig.slug;- const builtinSlugs = Object.values(BUILTIN_AGENT_SLUGS) as string[];- if (agentSlug && builtinSlugs.includes(agentSlug)) {- let userLocale: string | undefined;- try {- const userInfo = await UserModel.getInfoForAIGeneration(deps.db, deps.userId);- userLocale = userInfo.responseLanguage;- } catch (error) {- log('execAgent: failed to load user locale for builtin runtime config: %O', error);- }-- const runtimeConfig = getAgentRuntimeConfig(agentSlug, {- // The renameable default assistant must introduce itself by the name the- // user gave it, not the hardcoded product default.- agentName: agentConfig.name ?? undefined,- agentTitle: agentConfig.title ?? undefined,- model: agentConfig.model,- plugins: activePluginIds,- userLocale,- });- if (runtimeConfig) {- // Runtime systemRole takes effect only if DB has no user-customized systemRole- if (!agentConfig.systemRole && runtimeConfig.systemRole) {- agentConfig.systemRole = runtimeConfig.systemRole;- log('execAgent: merged builtin agent runtime systemRole for slug=%s', agentSlug);- }- // Runtime plugins merged (runtime plugins take priority if provided)- if (runtimeConfig.plugins && runtimeConfig.plugins.length > 0) {- activePluginIds = runtimeConfig.plugins;- log('execAgent: merged builtin agent runtime plugins for slug=%s', agentSlug);- }- if (runtimeConfig.agencyConfig) {- agentConfig.agencyConfig = {- ...agentConfig.agencyConfig,- ...runtimeConfig.agencyConfig,- };- log('execAgent: merged builtin agent runtime agencyConfig for slug=%s', agentSlug);- }- }- }-- if (appContext?.scope !== 'page') {- activePluginIds = activePluginIds.filter((id) => id !== PageAgentIdentifier);- }-- if (appContext?.scope === 'page' && agentSlug !== BUILTIN_AGENT_SLUGS.pageAgent) {- const pageAgentRuntime = getAgentRuntimeConfig(BUILTIN_AGENT_SLUGS.pageAgent, {- model: agentConfig.model,- plugins: activePluginIds,- });- const pageAgentSystemRole = pageAgentRuntime?.systemRole || '';-- if (pageAgentSystemRole) {- agentConfig.systemRole = agentConfig.systemRole- ? `${agentConfig.systemRole}\n\n${pageAgentSystemRole}`- : pageAgentSystemRole;- }-- activePluginIds = activePluginIds.includes(PageAgentIdentifier)- ? activePluginIds- : [PageAgentIdentifier, ...activePluginIds];- agentConfig.chatConfig = {- ...agentConfig.chatConfig,- enableHistoryCount: false,- };- log('execAgent: injected page-agent runtime for page scope');- }-- if (appContext?.scope === 'task' && agentSlug !== BUILTIN_AGENT_SLUGS.taskAgent) {- const taskAgentRuntime = getAgentRuntimeConfig(BUILTIN_AGENT_SLUGS.taskAgent, {- model: agentConfig.model,- plugins: activePluginIds,- });- const taskAgentSystemRole = taskAgentRuntime?.systemRole || '';-- if (taskAgentSystemRole) {- agentConfig.systemRole = agentConfig.systemRole- ? `${agentConfig.systemRole}\n\n${taskAgentSystemRole}`- : taskAgentSystemRole;- }-- activePluginIds = activePluginIds.includes(TaskIdentifier)- ? activePluginIds- : [TaskIdentifier, ...activePluginIds];- log('execAgent: injected task-agent runtime for task scope');- }-- if (appContext?.isSubAgent) {- activePluginIds = activePluginIds.filter((id) => id !== LobeAgentIdentifier);- }-- agentConfig.plugins = activePluginIds;-await throwIfExecutionAborted('agent configuration');// 2.5. Append additional instructions to agent's systemRole@@ -373,13 +308,13 @@ export const resolveRunAgentConfig = async (return {agentConfig,- agentSlug,+ agentSlug: row.slug,assistantAgentId,canManageAgent,conversationAgentId,disabledPluginIds,isPublicWorkspaceAgent,- memberDeviceOverride,+ memberDeviceOverride: overrides.device,persistAgentId,resolvedAgentId,};diff --git a/packages/builtin-agents/src/agents/inbox/index.ts b/packages/builtin-agents/src/agents/inbox/index.tsindex d58b26ca561..49383f1748d 100644--- a/packages/builtin-agents/src/agents/inbox/index.ts+++ b/packages/builtin-agents/src/agents/inbox/index.ts@@ -14,7 +14,10 @@ export const INBOX: BuiltinAgentDefinition = {avatar: '/avatars/lobe-ai.png',runtime: (ctx) => ({plugins: [AgentDocumentsIdentifier, UserInteractionIdentifier, ...(ctx.plugins || [])],- systemRole: createSystemRole(ctx.userLocale, { name: ctx.agentName, title: ctx.agentTitle }),+ // A user-customized prompt wins; the runtime one is only the default.+ systemRole:+ ctx.storedSystemRole ||+ createSystemRole(ctx.userLocale, { name: ctx.agentName, title: ctx.agentTitle }),}),slug: BUILTIN_AGENT_SLUGS.inbox,diff --git a/packages/builtin-agents/src/types.ts b/packages/builtin-agents/src/types.tsindex 29439ec6705..71058975715 100644--- a/packages/builtin-agents/src/types.ts+++ b/packages/builtin-agents/src/types.ts@@ -82,6 +82,15 @@ export interface RuntimeContext {/** Plugins enabled for the agent */plugins?: string[];+ /**+ * The system role stored on the agent row, when the user customized it.+ * Builtins whose runtime prompt is only a default the user may edit (the+ * renameable inbox assistant) honor it; builtins whose prompt is the+ * feature itself (page / task / supervisor) ignore it or embed it via+ * their own context.+ */+ storedSystemRole?: string;+/** Target agent config for AgentBuilder */targetAgentConfig?: LobeAgentConfig;diff --git a/packages/mecha/src/resolveAgentConfig.test.ts b/packages/mecha/src/resolveAgentConfig.test.tsindex 4ce45d0e072..6b2d9487728 100644--- a/packages/mecha/src/resolveAgentConfig.test.ts+++ b/packages/mecha/src/resolveAgentConfig.test.ts@@ -140,4 +140,42 @@ describe('resolveAgentConfig without a host', () => {// A manager reads the shared row, so their own member pick stays dormant.expect(resolved.chatConfig.enableAgentMode).toBeUndefined();});++ it('lets a per-call model override outrank the member pick and the shared default', () => {+ const resolved = resolveAgentConfig(+ { agentId: 'agt_1', modelOverride: { model: 'pinned-model' } },+ snapshot({+ agent: { visibility: 'public', workspaceId: 'ws_1' },+ canManage: false,+ memberModelOverride: { model: 'member-model', provider: 'anthropic' },+ }),+ );++ // Model is pinned by the call; provider still comes from the member pick.+ expect(resolved.agentConfig.model).toBe('pinned-model');+ expect(resolved.agentConfig.provider).toBe('anthropic');+ });++ it('keeps a user-customized system role on a builtin row over the runtime one', () => {+ const customized = resolveAgentConfig(+ { agentId: 'agt_inbox' },+ snapshot({+ agentConfig: { model: 'gpt-5', provider: 'openai', systemRole: 'Mine.' } as never,+ slug: 'inbox',+ }),+ );+ expect(customized.isBuiltinAgent).toBe(true);+ expect(customized.agentConfig.systemRole).toBe('Mine.');++ const empty = resolveAgentConfig(+ { agentId: 'agt_inbox' },+ snapshot({+ agentConfig: { model: 'gpt-5', provider: 'openai', systemRole: '' } as never,+ slug: 'inbox',+ }),+ );+ // The row has no system role, so the runtime one fills it in.+ expect(empty.agentConfig.systemRole).toBeTruthy();+ expect(empty.agentConfig.systemRole).not.toBe('');+ });});diff --git a/packages/mecha/src/resolveAgentConfig.ts b/packages/mecha/src/resolveAgentConfig.tsindex f99a4985d36..77e96fab3be 100644--- a/packages/mecha/src/resolveAgentConfig.ts+++ b/packages/mecha/src/resolveAgentConfig.ts@@ -164,8 +164,14 @@ export interface AgentConfigResolverContext {*/isSubAgent?: boolean;- /** Current model being used (for template variables) */+ /** Current model being used (for template variables); defaults to the resolved model. */model?: string;+ /**+ * Per-call model / provider pinned by the caller (task or sub-agent spawn,+ * an explicit request override). Outranks the member's personal choice and+ * the shared default.+ */+ modelOverride?: Partial<AgentModelOverride> | null;/** Plugins enabled for the agent */plugins?: string[];@@ -225,8 +231,15 @@ export const resolveAgentConfig = (ctx: AgentConfigResolverContext,snapshot: AgentConfigSnapshot,): ResolvedAgentConfig => {- const { agentId, model, documentContent, plugins, targetAgentConfig, isSubAgent, disableTools } =- ctx;+ const {+ agentId,+ documentContent,+ plugins,+ targetAgentConfig,+ isSubAgent,+ disableTools,+ modelOverride,+ } = ctx;log('resolveAgentConfig called with agentId: %s, scope: %s, isSubAgent: %s, disableTools: %s',@@ -294,8 +307,11 @@ export const resolveAgentConfig = (workspaceId: agent?.workspaceId,},memberModelOverride,+ modelOverride,),};+ // Runtime templates render `{{model}}` for the model the run will actually use.+ const model = ctx.model ?? agentConfig.model;const sharedChatConfig = snapshot.chatConfig;const chatConfig =memberModeOverride === undefined@@ -509,11 +525,13 @@ export const resolveAgentConfig = (isDev: snapshot.isDev ?? false,model,plugins: plugins || basePlugins,+ storedSystemRole: agentConfig.systemRole || undefined,targetAgentConfig,userLocale: snapshot.userLocale,});- // Merge runtime systemRole into agent config+ // The runtime prompt is the authority for a builtin; a builtin that treats+ // it as a user-editable default reads `storedSystemRole` itself (inbox).let resolvedSystemRole = runtimeConfig?.systemRole ?? agentConfig.systemRole;// Merge plugins: runtime plugins take priority, fallback to base plugins