π€― 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(chat): gather the browser's per-step context through the shared rules (#19577)
Arvin Xu1f4d6a7116cd
diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/index.tsindex c92cc77d1ca..3a1b3113c6d 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts@@ -1,5 +1,6 @@import type { AgentState } from '@lobechat/agent-runtime';import { formatWebOnboardingStateMessage } from '@lobechat/builtin-tool-web-onboarding/utils';+import { defaultUninstalledBuiltinTools } from '@lobechat/builtin-tools';import { AGENT_PLAN_FILE_TYPE } from '@lobechat/const';import type { ContextFactProviders, ContextFactRequest } from '@lobechat/mecha';import { getActivePluginIds } from '@lobechat/types';@@ -288,6 +289,26 @@ export const createServerContextFactProviders = ({title: a.title,})),+ // The uninstalled list lives on the user's tool settings, one slot per+ // workspace plus the personal one β the same slot the tool store reads.+ listUninstalledBuiltinIds: async () => {+ const settings = await new UserModel(db, userId).getUserSettings();+ const tool = settings?.tool as+ | {+ uninstalledBuiltinTools?: string[];+ uninstalledBuiltinToolsByWorkspace?: Record<string, string[] | undefined>;+ }+ | null+ | undefined;+ const stored = workspaceId+ ? tool?.uninstalledBuiltinToolsByWorkspace?.[workspaceId]+ : tool?.uninstalledBuiltinTools;+ // Never configured (new account, or a workspace without its own slot)+ // means the default seed β non-recommended builtins start uninstalled β+ // exactly as the browser's tool store resolves it.+ return stored === undefined ? defaultUninstalledBuiltinTools : stored;+ },+listSandboxFiles: async (topicId) =>new FileModel(db, userId).findFilesToInitInSandbox(topicId),diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.tsindex c02c1862949..fc674491cca 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.ts@@ -1,20 +1,21 @@+import { defaultUninstalledBuiltinTools } from '@lobechat/builtin-tools';import { describe, expect, it, vi } from 'vitest';import { createServerContextFactProviders } from './index';-const { findById, getInfoForAIGeneration, loadConnectedComposioIds, pluginQuery } = vi.hoisted(- () => ({+const { findById, getInfoForAIGeneration, getUserSettings, loadConnectedComposioIds, pluginQuery } =+ vi.hoisted(() => ({findById: vi.fn(),getInfoForAIGeneration: vi.fn(),+ getUserSettings: vi.fn(),loadConnectedComposioIds: vi.fn(),pluginQuery: vi.fn(),- }),-);+ }));vi.mock('@/database/models/user', () => ({UserModel: Object.assign(class {- getUserSettings = vi.fn();+ getUserSettings = getUserSettings;},{ getInfoForAIGeneration },),@@ -94,6 +95,47 @@ describe('createServerContextFactProviders', () => {]);});+ it('reads the uninstalled builtin list from the scope the run belongs to', async () => {+ getUserSettings.mockResolvedValue({+ tool: {+ uninstalledBuiltinTools: ['lobe-personal-gone'],+ uninstalledBuiltinToolsByWorkspace: { 'ws-1': ['lobe-ws-gone'] },+ },+ });++ await expect(+ createServerContextFactProviders(source({ origin: { workspaceId: 'ws-1' } }))+ .listUninstalledBuiltinIds!(),+ ).resolves.toEqual(['lobe-ws-gone']);+ await expect(+ createServerContextFactProviders({+ ctx: { serverDB: {}, userId: 'owner-1' } as never,+ state: {} as never,+ }).listUninstalledBuiltinIds!(),+ ).resolves.toEqual(['lobe-personal-gone']);+ });++ it('falls back to the default uninstalled seed when the scope was never configured', async () => {+ getUserSettings.mockResolvedValue({+ tool: { uninstalledBuiltinTools: ['lobe-personal-gone'] },+ });++ // A workspace without its own slot gets the seed, never the personal list.+ await expect(+ createServerContextFactProviders(source({ origin: { workspaceId: 'ws-new' } }))+ .listUninstalledBuiltinIds!(),+ ).resolves.toEqual(defaultUninstalledBuiltinTools);++ getUserSettings.mockResolvedValue({});+ await expect(+ createServerContextFactProviders({+ ctx: { serverDB: {}, userId: 'owner-1' } as never,+ state: {} as never,+ }).listUninstalledBuiltinIds!(),+ ).resolves.toEqual(defaultUninstalledBuiltinTools);+ expect(defaultUninstalledBuiltinTools.length).toBeGreaterThan(0);+ });+it('returns the app origin and the workspace slug when it resolves', async () => {findById.mockResolvedValue({ slug: 'team' });const providers = createServerContextFactProviders(source());diff --git a/apps/server/src/routers/lambda/market/creds.test.ts b/apps/server/src/routers/lambda/market/creds.test.tsindex 8caf701d948..d9d446e221e 100644--- a/apps/server/src/routers/lambda/market/creds.test.ts+++ b/apps/server/src/routers/lambda/market/creds.test.ts@@ -129,6 +129,38 @@ describe('credsRouter is always personal-scoped', () => {});});+describe('credsRouter listForContext follows the runtime scope', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('lists the workspace organization creds for a verified workspace member', async () => {+ const { credsRouter } = await import('./creds');+ const caller = credsRouter.createCaller({+ isWorkspaceMember: true,+ userId: 'user-1',+ workspaceId: 'workspace-1',+ } as any);++ const result = await caller.listForContext();++ expect(mockOrgCredsList).toHaveBeenCalledTimes(1);+ expect(mockPersonalCredsList).not.toHaveBeenCalled();+ expect(result.data.map((c) => c.key)).toEqual(['ORG_SECRET']);+ });++ it('lists personal creds outside a workspace', async () => {+ const { credsRouter } = await import('./creds');+ const caller = credsRouter.createCaller({ isWorkspaceMember: false, userId: 'user-1' } as any);++ const result = await caller.listForContext();++ expect(mockPersonalCredsList).toHaveBeenCalledTimes(1);+ expect(mockOrgCredsList).not.toHaveBeenCalled();+ expect(result.data.map((c) => c.key)).toEqual(['PERSONAL_SECRET']);+ });+});+describe('credsRouter list scopes sharing to the active workspace', () => {beforeEach(() => {vi.clearAllMocks();diff --git a/apps/server/src/routers/lambda/market/creds.ts b/apps/server/src/routers/lambda/market/creds.tsindex 6dda9122363..6c1c939d765 100644--- a/apps/server/src/routers/lambda/market/creds.ts+++ b/apps/server/src/routers/lambda/market/creds.ts@@ -460,6 +460,39 @@ export const credsRouter = router({}),// List OAuth connections (for creating OAuth credentials)+ /**+ * The credentials an agent run may inject, as the runtime's context rules+ * see them: inside a verified workspace the workspace's merged organization+ * view (org-owned creds + members' shared creds), otherwise the caller's+ * personal creds. Unlike `list`, this is scoped on purpose β it mirrors+ * `createServerContextFactProviders.listCredentials` so browser-mode and+ * server-mode runs read the same list.+ */+ listForContext: credsProcedure.query(async ({ ctx }) => {+ const result = ctx.workspaceId+ ? await ctx.marketService.market.organizations.creds({ workspaceId: ctx.workspaceId }).list()+ : await ctx.marketService.market.creds.list();+ const creds = (result.data ?? []) as Array<{+ description?: string;+ key: string;+ name: string;+ ownerDisplayName?: string;+ ownerType?: 'organization' | 'user';+ type: string;+ }>;+ log('listForContext success: %d credentials (workspace=%s)', creds.length, ctx.workspaceId);+ return {+ data: creds.map((cred) => ({+ description: cred.description,+ key: cred.key,+ name: cred.name,+ ownerDisplayName: cred.ownerDisplayName,+ ownerType: cred.ownerType,+ type: cred.type,+ })),+ };+ }),+listOAuthConnections: credsManageProcedure.query(async ({ ctx }) => {log('listOAuthConnections called');diff --git a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.ts b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.tsindex c5d7d9b2322..1b939f6bd49 100644--- a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.ts+++ b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.ts@@ -322,6 +322,33 @@ describe('gatherContextFacts', () => {});});+ it('lists an uninstalled builtin as not installed so the builder does not pin it', async () => {+ const builtinId = listOfficialTools({+ connectedConnectorIds: new Set(),+ enabledPlugins: [],+ features: { composio: false, lobehubSkill: false },+ }).find((t) => t.type === 'builtin')!.identifier;++ const tools = listOfficialTools({+ connectedConnectorIds: new Set(),+ enabledPlugins: [],+ features: { composio: false, lobehubSkill: false },+ uninstalledBuiltinIds: new Set([builtinId]),+ });+ expect(tools.find((t) => t.identifier === builtinId)).toMatchObject({ installed: false });++ const facts = await gatherContextFacts(+ request({ editingAgentId: 'agt_edit', enabledToolIds: ['lobe-agent-builder'] }),+ {+ getAgentDefinition: async () => ({ plugins: [] }),+ listUninstalledBuiltinIds: async () => [builtinId],+ },+ );+ expect(+ facts.step.agentBuilderContext?.officialTools?.find((t) => t.identifier === builtinId),+ ).toMatchObject({ installed: false });+ });+it('describes the workspace only when its slug resolves', async () => {const providers = {getWorkspaceContext: async (id?: string) => ({diff --git a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.tsindex e51a7b4d3b8..31eada57fe6 100644--- a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts+++ b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts@@ -246,6 +246,12 @@ const gatherComposioServices = async (return generateComposioServicesList(connected, available);};+/** Builtins the user removed in this scope; a builder must not pin them. */+const gatherUninstalledBuiltinIds = async (providers: ContextFactProviders) => {+ const ids = await attempt('uninstalledBuiltins', () => providers.listUninstalledBuiltinIds?.());+ return ids ? new Set(ids) : undefined;+};+const gatherAgentBuilderContext = async (request: ContextFactRequest,providers: ContextFactProviders,@@ -263,14 +269,15 @@ const gatherAgentBuilderContext = async (const editing = await getAgentDefinition(editingAgentId);if (!editing) return undefined;const enabledPlugins = editing.plugins ?? [];- const connected = new Set(- (await attempt('connectedConnectors', () => listConnectedConnectorIds?.(editingAgentId))) ??- [],- );+ const [connected, uninstalled] = await Promise.all([+ attempt('connectedConnectors', () => listConnectedConnectorIds?.(editingAgentId)),+ gatherUninstalledBuiltinIds(providers),+ ]);const officialTools = listOfficialTools({- connectedConnectorIds: connected,+ connectedConnectorIds: new Set(connected ?? []),enabledPlugins,features: request.features,+ uninstalledBuiltinIds: uninstalled,});return {config: {@@ -327,11 +334,10 @@ const gatherGroupAgentBuilderContext = async (};}}- const connected = new Set(- (await attempt('connectedConnectors', () =>- listConnectedConnectorIds?.(supervisorAgentId),- )) ?? [],- );+ const [connected, uninstalled] = await Promise.all([+ attempt('connectedConnectors', () => listConnectedConnectorIds?.(supervisorAgentId)),+ gatherUninstalledBuiltinIds(providers),+ ]);return {config: {@@ -348,9 +354,10 @@ const gatherGroupAgentBuilderContext = async (title: member.title || 'Untitled Agent',})),officialTools: listOfficialTools({- connectedConnectorIds: connected,+ connectedConnectorIds: new Set(connected ?? []),enabledPlugins,features: request.features,+ uninstalledBuiltinIds: uninstalled,}),supervisorConfig,};diff --git a/packages/mecha/src/contextEngineering/facts/officialTools.ts b/packages/mecha/src/contextEngineering/facts/officialTools.tsindex 40fb18683c1..648abfe3a2d 100644--- a/packages/mecha/src/contextEngineering/facts/officialTools.ts+++ b/packages/mecha/src/contextEngineering/facts/officialTools.ts@@ -20,15 +20,18 @@ const INTERNAL_TOOLS = new Set([/*** The official tool catalog as the agent / group builder prompt lists it:- * every visible builtin (connectors rendered through their canonical owner),- * then every connector this deployment offers with its connection status.+ * every visible builtin (connectors rendered through their canonical owner)+ * with whether the user still has it installed, then every connector this+ * deployment offers with its connection status.*/export const listOfficialTools = (params: {connectedConnectorIds: Set<string>;enabledPlugins: string[];features: ContextFactRequest['features'];+ /** Builtins the user removed; listed but not installed, so the builder does not pin them. */+ uninstalledBuiltinIds?: Set<string>;}): OfficialToolItem[] => {- const { connectedConnectorIds, enabledPlugins, features } = params;+ const { connectedConnectorIds, enabledPlugins, features, uninstalledBuiltinIds } = params;const catalog = getConnectorCatalog({composio: features.composio,lobehub: features.lobehubSkill,@@ -43,7 +46,7 @@ export const listOfficialTools = (params: {description: tool.manifest?.meta?.description,enabled: enabledPlugins.includes(tool.identifier),identifier: tool.identifier,- installed: true,+ installed: !uninstalledBuiltinIds?.has(tool.identifier),name: tool.manifest?.meta?.title || tool.identifier,type: 'builtin',});diff --git a/packages/mecha/src/contextEngineering/facts/types.ts b/packages/mecha/src/contextEngineering/facts/types.tsindex 565a4cc2cdc..f5c80988fbf 100644--- a/packages/mecha/src/contextEngineering/facts/types.ts+++ b/packages/mecha/src/contextEngineering/facts/types.ts@@ -155,6 +155,8 @@ export interface ContextFactProviders {listTopicMessages?: (topic: TopicFacts,) => Promise<{ content: string; role: string }[] | undefined>;+ /** Builtin tool identifiers the user uninstalled in the current scope. */+ listUninstalledBuiltinIds?: () => Promise<Iterable<string> | undefined>;}export interface GatheredContextFacts {diff --git a/src/services/chat/chat.test.ts b/src/services/chat/chat.test.tsindex 10a9186831a..1d3eb283d9d 100644--- a/src/services/chat/chat.test.ts+++ b/src/services/chat/chat.test.ts@@ -1696,65 +1696,12 @@ describe('ChatService', () => {});describe('agent documents readiness', () => {- it('should ensure agent documents before assistant generation when cache is empty', async () => {+ it('should hand the agent builder run to context engineering without prefetching documents', async () => {const contextEngineeringSpy = vi.spyOn(mechaModule, 'contextEngineering').mockResolvedValue([]);vi.spyOn(chatService, 'getChatCompletion').mockResolvedValue(new Response(''));- vi.spyOn(agentDocumentService, 'getContextDocuments').mockResolvedValue([- {- content: 'Project setup steps',- filename: 'setup.md',- id: 'doc-1',- loadRules: [],- policy: null,- policyLoadFormat: null,- policyLoadPosition: null,- templateId: null,- title: 'Setup',- },- ] as any);-- await chatService.createAssistantMessage({- agentId: 'agent-1',- messages: [{ content: 'Hello', role: 'user' }] as UIChatMessage[],- resolvedAgentConfig: createMockResolvedConfig(),- });-- expect(agentDocumentService.getContextDocuments).toHaveBeenCalledWith({- agentId: 'agent-1',- });- expect(contextEngineeringSpy).toHaveBeenCalledWith(- expect.objectContaining({- agentDocuments: [- expect.objectContaining({- content: 'Project setup steps',- filename: 'setup.md',- id: 'doc-1',- }),- ],- }),- );- });-- it('should resolve agent builder documents from the edited agent', async () => {- const contextEngineeringSpy = vi- .spyOn(mechaModule, 'contextEngineering')- .mockResolvedValue([]);- vi.spyOn(chatService, 'getChatCompletion').mockResolvedValue(new Response(''));- vi.spyOn(agentDocumentService, 'getContextDocuments').mockResolvedValue([- {- content: 'Edited agent setup',- filename: 'builder-target.md',- id: 'doc-1',- loadRules: [],- policy: null,- policyLoadFormat: null,- policyLoadPosition: null,- templateId: null,- title: 'Builder Target',- },- ] as any);+ const getContextDocuments = vi.spyOn(agentDocumentService, 'getContextDocuments');useChatStore.setState({ activeAgentId: 'edited-agent' } as any);@@ -1766,18 +1713,17 @@ describe('ChatService', () => {}),});- expect(agentDocumentService.getContextDocuments).toHaveBeenCalledWith({- agentId: 'edited-agent',- });+ // Which agent's documents to read (the edited one while the builder is+ // active) is decided by the shared context rules inside+ // contextEngineering; the service no longer resolves it up front.+ expect(getContextDocuments).not.toHaveBeenCalled();expect(contextEngineeringSpy).toHaveBeenCalledWith(expect.objectContaining({- agentDocuments: [- expect.objectContaining({- content: 'Edited agent setup',- }),- ],+ agentId: 'builder-agent',+ tools: [AgentBuilderIdentifier],}),);+ expect(contextEngineeringSpy.mock.calls[0][0]).not.toHaveProperty('agentDocuments');});});});diff --git a/src/services/chat/index.ts b/src/services/chat/index.tsindex 19fc60c3b69..00a1b90d86a 100644--- a/src/services/chat/index.ts+++ b/src/services/chat/index.ts@@ -1,11 +1,8 @@-import { AgentBuilderIdentifier } from '@lobechat/builtin-tool-agent-builder';import {- getConnectorCatalog,REQUEST_AGENT_ID_HEADER,REQUEST_TOPIC_ID_HEADER,REQUEST_TRIGGER_HEADER,} from '@lobechat/const';-import { type OfficialToolItem } from '@lobechat/context-engine';import { type FetchSSEOptions } from '@lobechat/fetch-sse';import { fetchSSE, standardizeAnimationStyle } from '@lobechat/fetch-sse';import type { ChatCompletionErrorPayload } from '@lobechat/model-runtime';@@ -28,20 +25,10 @@ import { DEFAULT_AGENT_CONFIG } from '@/const/settings';import { getSearchConfig } from '@/helpers/getSearchConfig';import { isCanUseFC } from '@/helpers/isCanUseFC';import { getAgentStoreState } from '@/store/agent';-import {- agentByIdSelectors,- agentChatConfigSelectors,- agentSelectors,-} from '@/store/agent/selectors';+import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';import { aiModelSelectors, aiProviderSelectors, getAiInfraStoreState } from '@/store/aiInfra';import { getChatStoreState } from '@/store/chat';import { topicSelectors } from '@/store/chat/slices/topic/selectors';-import { getToolStoreState } from '@/store/tool';-import {- builtinToolSelectors,- composioStoreSelectors,- lobehubSkillStoreSelectors,-} from '@/store/tool/selectors';import { getUserStoreState, useUserStore } from '@/store/user';import {settingsSelectors,@@ -123,17 +110,6 @@ interface CreateAssistantMessageStream extends FetchSSEOptions {}class ChatService {- private resolveAgentDocumentsTargetId = (- targetAgentId: string,- enabledToolIds: string[] = [],- ): string | undefined => {- if (enabledToolIds.includes(AgentBuilderIdentifier)) {- return getChatStoreState().activeAgentId || targetAgentId || undefined;- }-- return targetAgentId || undefined;- };-buildAssistantMessageContext = async ({messages,@@ -187,116 +163,9 @@ class ChatService {const enableAgentMode =chatConfig.enableAgentMode !== false && isCanUseFC(payload.model, payload.provider!);- // =================== 1.2 build agent builder context =================== //-- // Check if Agent Builder tool is enabled and build context for it- // Note: When Agent Builder is active, we need to get the context of the agent being edited,- // which is stored in chatStore.activeAgentId, not the targetAgentId (which is the Agent Builder itself)- const isAgentBuilderEnabled = enabledToolIds.includes(AgentBuilderIdentifier);- const documentsAgentId = this.resolveAgentDocumentsTargetId(targetAgentId, enabledToolIds);- let agentBuilderContext;- let agentDocuments = documentsAgentId- ? agentSelectors.getAgentDocumentsById(documentsAgentId)(getAgentStoreState())- : undefined;-- if (documentsAgentId && agentDocuments === undefined) {- try {- agentDocuments = await getAgentStoreState().ensureAgentDocuments(documentsAgentId);- } catch (error) {- // Agent documents are optional on the client; keep generation working if hydration fails.- console.error('[ChatService] Failed to ensure agent documents:', error);- }- }-- if (isAgentBuilderEnabled) {- const activeAgentId = getChatStoreState().activeAgentId || '';- const baseContext =- agentByIdSelectors.getAgentBuilderContextById(activeAgentId)(getAgentStoreState());- const activeAgentConfig =- agentSelectors.getAgentConfigById(activeAgentId)(getAgentStoreState());-- // Build official tools list (builtin tools + Composio tools)- const toolState = getToolStoreState();- const enabledPlugins = activeAgentConfig?.plugins || [];-- const officialTools: OfficialToolItem[] = [];-- const isComposioEnabled = Boolean(- typeof window !== 'undefined' &&- window.global_serverConfigStore?.getState()?.serverConfig?.enableComposio,- );- const isLobehubSkillEnabled = Boolean(- typeof window !== 'undefined' &&- window.global_serverConfigStore?.getState()?.serverConfig?.enableLobehubSkill,- );- const connectorCatalog = getConnectorCatalog({- composio: isComposioEnabled,- lobehub: isLobehubSkillEnabled,- });- const connectorIdentifiers = new Set(- connectorCatalog.map((item) =>- item.type === 'lobehub' ? item.provider.id : item.serverType.identifier,- ),- );-- // Get builtin tools (excluding connectors rendered through their canonical owner)- const builtinTools = builtinToolSelectors.metaList(toolState);-- for (const tool of builtinTools) {- if (connectorIdentifiers.has(tool.identifier)) continue;-- officialTools.push({- description: tool.meta?.description,- enabled: enabledPlugins.includes(tool.identifier),- identifier: tool.identifier,- installed: true,- name: tool.meta?.title || tool.identifier,- type: 'builtin',- });- }-- const allComposioServers = composioStoreSelectors.getServers(toolState);- const allLobehubSkillServers = lobehubSkillStoreSelectors.getServers(toolState);- for (const connector of connectorCatalog) {- if (connector.type === 'composio') {- const { serverType } = connector;- const server = allComposioServers.find(- (item) => item.identifier === serverType.identifier,- );- officialTools.push({- description: `LobeHub Mcp Server: ${serverType.label}`,- enabled: enabledPlugins.includes(serverType.identifier),- identifier: serverType.identifier,- installed: !!server,- name: serverType.label,- type: 'composio',- });- continue;- }-- const { provider } = connector;- const server = allLobehubSkillServers.find((item) => item.identifier === provider.id);- officialTools.push({- description: `LobeHub Skill Provider: ${provider.label}`,- enabled: enabledPlugins.includes(provider.id),- identifier: provider.id,- installed: !!server,- name: provider.label,- type: 'lobehub-skill',- });- }-- agentBuilderContext = {- ...baseContext,- officialTools,- };- }-// Apply context engineering with preprocessing configuration// Note: agentConfig.systemRole is already resolved by resolveAgentConfig for builtin agentsconst modelMessages = await contextEngineering({- agentBuilderContext,- agentDocuments,agentId: targetAgentId,// `agentConfig.plugins` is the raw (pre-filter) field β `plugins` below// is already pinned-only (resolved upstream in agentConfigResolver).diff --git a/src/services/chat/mecha/contextEngineering.test.ts b/src/services/chat/mecha/contextEngineering.test.tsindex 6e9e6936eae..920769160ff 100644--- a/src/services/chat/mecha/contextEngineering.test.ts+++ b/src/services/chat/mecha/contextEngineering.test.ts@@ -1,3 +1,4 @@+import { AgentBuilderIdentifier } from '@lobechat/builtin-tool-agent-builder';import { type UIChatMessage } from '@lobechat/types';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -5,6 +6,7 @@ import * as isCanUseFCModule from '@/helpers/isCanUseFC';import { agentService } from '@/services/agent';import { agentDocumentService } from '@/services/agentDocument';import { useAgentStore } from '@/store/agent';+import { useChatStore } from '@/store/chat';import { useUserStore } from '@/store/user';import * as helpers from '../helper';@@ -79,9 +81,11 @@ beforeEach(() => {useUserStore.setState({ settings: { general: { timezone: 'UTC' } } } as any);useAgentStore.setState({activeAgentId: undefined,+ agentDocumentsMap: {},agentMap: {},availableAgents: undefined,- });+ } as any);+ useChatStore.setState({ activeAgentId: undefined, activeGroupId: undefined } as any);});afterEach(() => {@@ -101,41 +105,43 @@ const getCurrentDateContent = () => {return `Current date: ${year}-${month}-${day} (${tz})`;};-describe('contextEngineering', () => {- it('should not fetch agent documents implicitly when agentId is provided', async () => {- const messages = [{ content: 'Hello', role: 'user' }] as UIChatMessage[];-- await contextEngineering({- agentId: 'agent-1',- messages,- model: 'gpt-4',- provider: 'openai',- });-- expect(agentDocumentService.getDocuments).not.toHaveBeenCalled();- });+const setupDocument = {+ content: 'Project setup steps',+ filename: 'setup.md',+ id: 'doc-1',+ policyLoad: 'always',+ title: 'Setup',+};- it('should use provided agent documents without fetching', async () => {+describe('contextEngineering', () => {+ it('should read the agent documents from the store cache without refetching', async () => {const messages = [{ content: 'Summarize the setup', role: 'user' }] as UIChatMessage[];+ useAgentStore.setState({+ agentDocumentsMap: {+ 'agent-1': [+ {+ content: 'Project setup steps',+ filename: 'setup.md',+ id: 'doc-1',+ // `always` keeps this doc in the inline bucket; without it the+ // default is progressive (metadata-only index, content hidden).+ policyLoad: 'always',+ title: 'Setup',+ },+ ],+ },+ } as any);+ const ensureSpy = vi.spyOn(useAgentStore.getState(), 'ensureAgentDocuments');const output = await contextEngineering({- agentDocuments: [- {- content: 'Project setup steps',- filename: 'setup.md',- id: 'doc-1',- // `always` keeps this doc in the inline bucket; without it the- // default is progressive (metadata-only index, content hidden).- policyLoad: 'always',- title: 'Setup',- },- ],agentId: 'agent-1',messages,model: 'gpt-4',provider: 'openai',});+ // Cache-first: the store answers, the document service is never asked.+ expect(ensureSpy).toHaveBeenCalledWith('agent-1');expect(agentDocumentService.getDocuments).not.toHaveBeenCalled();const documentsMessage = output.find((message) =>@@ -151,16 +157,8 @@ describe('contextEngineering', () => {});it('should suppress agent documents when runtime agent mode is disabled', async () => {+ useAgentStore.setState({ agentDocumentsMap: { 'agent-1': [setupDocument] } } as any);const output = await contextEngineering({- agentDocuments: [- {- content: 'Project setup steps',- filename: 'setup.md',- id: 'doc-1',- policyLoad: 'always',- title: 'Setup',- },- ],agentId: 'agent-1',enableAgentMode: false,messages: [{ content: 'Summarize the setup', role: 'user' }] as UIChatMessage[],@@ -183,23 +181,16 @@ describe('contextEngineering', () => {it('should fall back to stored chat mode when runtime agent mode is omitted', async () => {useAgentStore.setState({activeAgentId: 'agent-1',+ agentDocumentsMap: { 'agent-1': [setupDocument] },agentMap: {'agent-1': {chatConfig: { enableAgentMode: false },},},- });+ } as any);const output = await contextEngineering({- agentDocuments: [- {- content: 'Project setup steps',- filename: 'setup.md',- id: 'doc-1',- policyLoad: 'always',- title: 'Setup',- },- ],+ agentId: 'agent-1',messages: [{ content: 'Summarize the setup', role: 'user' }] as UIChatMessage[],model: 'gpt-4',provider: 'openai',@@ -217,6 +208,31 @@ describe('contextEngineering', () => {expect(documentsMessage).toBeUndefined();});+ it('should read the documents of the edited agent while the agent builder is active', async () => {+ useChatStore.setState({ activeAgentId: 'edited-agent' } as any);+ useAgentStore.setState({+ agentDocumentsMap: {+ 'builder-agent': [{ ...setupDocument, content: 'Builder agent notes', id: 'doc-b' }],+ 'edited-agent': [{ ...setupDocument, content: 'Edited agent setup', id: 'doc-e' }],+ },+ } as any);++ const output = await contextEngineering({+ agentId: 'builder-agent',+ messages: [{ content: 'Improve my agent', role: 'user' }] as UIChatMessage[],+ model: 'gpt-4',+ provider: 'openai',+ tools: [AgentBuilderIdentifier],+ });++ const rendered = output+ .filter((message) => typeof message.content === 'string')+ .map((message) => message.content as string)+ .join('\n');+ expect(rendered).toContain('Edited agent setup');+ expect(rendered).not.toContain('Builder agent notes');+ });+it('should use cached available agents without querying during context engineering', async () => {useAgentStore.setState({availableAgents: [diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.tsindex 6b8323a887a..990ceacdf18 100644--- a/src/services/chat/mecha/contextEngineering.ts+++ b/src/services/chat/mecha/contextEngineering.ts@@ -1,46 +1,17 @@import { LobeActivatorIdentifier } from '@lobechat/builtin-tool-activator';import { AgentBuilderIdentifier } from '@lobechat/builtin-tool-agent-builder';-import { AgentManagementIdentifier } from '@lobechat/builtin-tool-agent-management';-import { formatUploadedFilesPrompt } from '@lobechat/builtin-tool-cloud-sandbox';-import {- type ComposioServiceSummary,- CredsIdentifier,- type CredSummary,- excludeDisabledComposioServices,- generateComposioServicesList,- generateCredsList,- resolveAvailableComposioServices,-} from '@lobechat/builtin-tool-creds';-import { GroupAgentBuilderIdentifier } from '@lobechat/builtin-tool-group-agent-builder';-import { LobeAgentIdentifier } from '@lobechat/builtin-tool-lobe-agent';-import { WebOnboardingIdentifier } from '@lobechat/builtin-tool-web-onboarding';-import {- AGENT_PLAN_FILE_TYPE,- COMPOSIO_APP_TYPES,- getConnectorCatalog,- isDesktop,-} from '@lobechat/const';+import { isDesktop } from '@lobechat/const';import type {- AgentBuilderContext,- AgentContextDocument,AgentGroupConfig,- AgentManagementContext,- GroupAgentBuilderContext,- GroupOfficialToolItem,LobeToolManifest,MemoryContext,- OnboardingContext,OperationSkillSet,- PlanTodoConfig,ToolDiscoveryConfig,UserMemoryData,- WorkspaceContext,} from '@lobechat/context-engine';-import { resolveTopicReferences } from '@lobechat/context-engine';-import { type ContextSnapshot, runContextEngineering } from '@lobechat/mecha';+import { type ContextSnapshot, gatherContextFacts, runContextEngineering } from '@lobechat/mecha';import { historySummaryPrompt } from '@lobechat/prompts';import {- getActivePluginIds,type OpenAIChatMessage,type RuntimeAdditionalContextFragment,type RuntimeInitialContext,@@ -49,33 +20,20 @@ import {} from '@lobechat/types';import debug from 'debug';-import { getActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';+import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { isCanUseFC } from '@/helpers/isCanUseFC';import { HOST_VARIABLE_GENERATORS } from '@/helpers/parserPlaceholder';-import { lambdaClient } from '@/libs/trpc/client';-import {- agentService,- AVAILABLE_AGENTS_CONTEXT_LIMIT,- AVAILABLE_AGENTS_CONTEXT_QUERY_LIMIT,-} from '@/services/agent';-import { notebookService } from '@/services/notebook';import { getAgentStoreState } from '@/store/agent';-import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';+import {+ agentByIdSelectors,+ agentChatConfigSelectors,+ agentSelectors,+} from '@/store/agent/selectors';import { getChatGroupStoreState } from '@/store/agentGroup';import { agentGroupSelectors } from '@/store/agentGroup/selectors';-import { getAiInfraStoreState } from '@/store/aiInfra';import { getChatStoreState } from '@/store/chat';-import { chatSelectors, topicSelectors } from '@/store/chat/selectors';-import { getElectronStoreState } from '@/store/electron';-import { electronSyncSelectors } from '@/store/electron/selectors';import { getToolStoreState } from '@/store/tool';-import {- builtinToolSelectors,- composioStoreSelectors,- lobehubSkillStoreSelectors,- toolSelectors,-} from '@/store/tool/selectors';-import { ComposioServerStatus } from '@/store/tool/slices/composioStore';+import { toolSelectors } from '@/store/tool/selectors';import { useUserStore } from '@/store/user';import { userGeneralSettingsSelectors } from '@/store/user/selectors';@@ -86,6 +44,11 @@ import {isCanUseVideo,isCanUseVision,} from '../helper';+import {+ type BrowserShareVisitor,+ createBrowserContextFactProviders,+ resolveBrowserConnectorFeatures,+} from './contextFactProviders';import { combineUserMemoryData, resolveTopicMemories, resolveUserPersona } from './memoryManager';import { resolveClientSkills } from './skillEngineering';@@ -94,9 +57,6 @@ const log = debug('context-engine:contextEngineering');interface ContextEngineeringContext {/** Agent-materialized presentation contexts for this LLM call */additionalContexts?: readonly RuntimeAdditionalContextFragment[];- /** Agent Builder context for injecting current agent info */- agentBuilderContext?: AgentBuilderContext;- agentDocuments?: AgentContextDocument[];/** The agent ID that will respond (for group context injection) */agentId?: string;/**@@ -133,6 +93,12 @@ interface ContextEngineeringContext {plugins?: string[];provider: string;sessionId?: string;+ /**+ * Present only when the run answers a share visitor. The shared rules then+ * withhold the creator's documents, onboarding profile and workspace links+ * and resolve topic references against the visitor's own conversations.+ */+ shareVisitor?: BrowserShareVisitor;/*** Step context from Agent Runtime* Contains latest XML structure updated each step@@ -158,31 +124,19 @@ export const contextEngineering = async ({enableHistoryCount,historyCount,historySummary,- agentBuilderContext,- agentDocuments,agentId,disabledPluginIds,enableAgentMode,groupId,initialContext,plugins,+ shareVisitor,stepContext,topicId,memoryContext,}: ContextEngineeringContext): Promise<OpenAIChatMessage[]> => {log('tools: %o', tools);- // Check if Agent Builder tool is enabled- const isAgentBuilderEnabled = tools?.includes(AgentBuilderIdentifier) ?? false;- // Check if Group Agent Builder tool is enabled- const isGroupAgentBuilderEnabled = tools?.includes(GroupAgentBuilderIdentifier) ?? false;- // Check if Agent Management tool is enabled- const isAgentManagementEnabled = tools?.includes(AgentManagementIdentifier) ?? false;-- log('isAgentBuilderEnabled: %s', isAgentBuilderEnabled);- log('isGroupAgentBuilderEnabled: %s', isGroupAgentBuilderEnabled);- log('isAgentManagementEnabled: %s', isAgentManagementEnabled);-// Build agent group configuration if groupId is providedlet agentGroup: AgentGroupConfig | undefined;if (groupId) {@@ -225,132 +179,13 @@ export const contextEngineering = async ({}}- // Get agent store state (used for both group agent builder context and file/knowledge base)+ // Agent store state: chat mode, knowledge and identity of the responding agent.const agentStoreState = getAgentStoreState();// Example: preset-task calls omit `enableAgentMode`; preserve explicit chat mode// from stored config instead of letting MessagesEngine treat `undefined` as agent mode.const effectiveEnableAgentMode =enableAgentMode ?? agentChatConfigSelectors.currentChatConfig(agentStoreState).enableAgentMode;- // Build group agent builder context if Group Agent Builder is enabled- // Note: Uses activeGroupId from chatStore to get the group being edited- let groupAgentBuilderContext: GroupAgentBuilderContext | undefined;- if (isGroupAgentBuilderEnabled) {- const activeGroupId = getChatStoreState().activeGroupId;- if (activeGroupId) {- const groupStoreState = getChatGroupStoreState();- const activeGroupDetail = agentGroupSelectors.getGroupById(activeGroupId)(groupStoreState);-- if (activeGroupDetail) {- // Get supervisor agent config if supervisorAgentId exists- let supervisorConfig: GroupAgentBuilderContext['supervisorConfig'];- let enabledPlugins: string[] = [];- if (activeGroupDetail.supervisorAgentId) {- const supervisorAgentConfig = agentSelectors.getAgentConfigById(- activeGroupDetail.supervisorAgentId,- )(agentStoreState);- // Pinned identifiers only β GroupAgentBuilderContext.supervisorConfig.plugins- // is a display/prompt-formatting DTO (still `string[]`) that joins- // entries as plain text, and a disabled plugin isn't "enabled".- enabledPlugins = getActivePluginIds(supervisorAgentConfig.plugins);- supervisorConfig = {- model: supervisorAgentConfig.model,- plugins: enabledPlugins,- provider: supervisorAgentConfig.provider,- };- }-- // Build official tools list (builtin tools + Composio tools)- const toolState = getToolStoreState();- const officialTools: GroupOfficialToolItem[] = [];-- const isComposioEnabled = Boolean(- typeof window !== 'undefined' &&- window.global_serverConfigStore?.getState()?.serverConfig?.enableComposio,- );- const isLobehubSkillEnabled = Boolean(- typeof window !== 'undefined' &&- window.global_serverConfigStore?.getState()?.serverConfig?.enableLobehubSkill,- );- const connectorCatalog = getConnectorCatalog({- composio: isComposioEnabled,- lobehub: isLobehubSkillEnabled,- });- const connectorIdentifiers = new Set(- connectorCatalog.map((item) =>- item.type === 'lobehub' ? item.provider.id : item.serverType.identifier,- ),- );-- // Get builtin tools (excluding connectors rendered through their canonical owner)- const builtinTools = builtinToolSelectors.metaList(toolState);-- for (const tool of builtinTools) {- if (connectorIdentifiers.has(tool.identifier)) continue;-- officialTools.push({- description: tool.meta?.description,- enabled: enabledPlugins.includes(tool.identifier),- identifier: tool.identifier,- installed: true,- name: tool.meta?.title || tool.identifier,- type: 'builtin',- });- }-- const allComposioServers = composioStoreSelectors.getServers(toolState);- const allLobehubSkillServers = lobehubSkillStoreSelectors.getServers(toolState);- for (const connector of connectorCatalog) {- if (connector.type === 'composio') {- const { serverType } = connector;- const server = allComposioServers.find(- (item) => item.identifier === serverType.identifier,- );- officialTools.push({- description: `LobeHub Mcp Server: ${serverType.label}`,- enabled: enabledPlugins.includes(serverType.identifier),- identifier: serverType.identifier,- installed: !!server,- name: serverType.label,- type: 'composio',- });- continue;- }-- const { provider } = connector;- const server = allLobehubSkillServers.find((item) => item.identifier === provider.id);- officialTools.push({- description: `LobeHub Skill Provider: ${provider.label}`,- enabled: enabledPlugins.includes(provider.id),- identifier: provider.id,- installed: !!server,- name: provider.label,- type: 'lobehub-skill',- });- }-- groupAgentBuilderContext = {- config: {- openingMessage: activeGroupDetail.config?.openingMessage || undefined,- openingQuestions: activeGroupDetail.config?.openingQuestions,- systemPrompt: activeGroupDetail.config?.systemPrompt || undefined,- },- groupId: activeGroupId,- groupTitle: activeGroupDetail.title || undefined,- members: activeGroupDetail.agents?.map((agent) => ({- description: agent.description || undefined,- id: agent.id,- isSupervisor: agent.isSupervisor,- title: agent.title || 'Untitled Agent',- })),- officialTools,- supervisorConfig,- };- log('groupAgentBuilderContext built from activeGroupId: %o', groupAgentBuilderContext);- }- }- }-// Get enabled agent files with content and knowledge bases from agent storeconst agentFiles = agentSelectors.currentAgentFiles(agentStoreState);const agentKnowledgeBases = agentSelectors.currentAgentKnowledgeBases(agentStoreState);@@ -372,113 +207,6 @@ export const contextEngineering = async ({userMemoryData = combineUserMemoryData(topicMemories, persona);}- // Resolve plan + todos context (now part of the lobe-agent tool).- // Lobe-agent must be enabled and topicId must be provided.- const isPlanTodoEnabled = tools?.includes(LobeAgentIdentifier) ?? false;- let planTodoConfig: PlanTodoConfig | undefined;-- if (isPlanTodoEnabled && topicId) {- try {- // Fetch plan document for the current topic- const planResult = await notebookService.listDocuments({- topicId,- type: AGENT_PLAN_FILE_TYPE,- });-- if (planResult.data.length > 0) {- const planDoc = planResult.data[0]; // Most recent plan-- // Build plan object for injection- const plan = {- completed: false, // TODO: Add completed field to document if needed- context: planDoc.content ?? undefined,- createdAt: planDoc.createdAt.toISOString(),- description: planDoc.description || '',- goal: planDoc.title || '',- id: planDoc.id,- updatedAt: planDoc.updatedAt.toISOString(),- };-- // Get todos from plan's metadata- const todos = planDoc.metadata?.todos;-- planTodoConfig = {- enabled: true,- plan,- todos,- };-- log('Plan/Todo context resolved: plan=%s, todos=%o', plan.goal, todos?.items?.length ?? 0);- }- } catch (error) {- // Silently fail - plan/todo context is optional- log('Failed to resolve plan/todo context:', error);- }- }-- // Resolve user credentials context for creds tool- // Creds tool must be enabled to fetch credentials- const isCredsEnabled = tools?.includes(CredsIdentifier) ?? false;- let credsList: CredSummary[] | undefined;-- if (isCredsEnabled) {- try {- const credsResult = await lambdaClient.market.creds.list.query();- const userCreds = (credsResult as any)?.data ?? [];- credsList = userCreds.map((cred: any): CredSummary => ({- description: cred.description,- key: cred.key,- name: cred.name,- type: cred.type,- }));- log('Creds context resolved: count=%d', credsList?.length ?? 0);- } catch (error) {- // Silently fail - creds context is optional- log('Failed to resolve creds context:', error);- }- }-- // Build Composio services list for creds context- // Shows which Composio services are connected (authorized) and which are available to connect- let composioServicesList = '';-- const isComposioEnabled =- typeof window !== 'undefined' &&- window.global_serverConfigStore?.getState()?.serverConfig?.enableComposio;-- if (isCredsEnabled && isComposioEnabled) {- try {- const toolState = getToolStoreState();- const allComposioServers = composioStoreSelectors.getServers(toolState);- const disabledIdSet = new Set(disabledPluginIds ?? []);-- // Disabled services are dropped from both lists β not surfaced as- // "connected, use directly" (this agent shouldn't use it) nor as- // "available to connect" (the user's account-level OAuth connection,- // if any, is untouched; this agent just isn't meant to see it).- const connected: ComposioServiceSummary[] = excludeDisabledComposioServices(- allComposioServers.filter((s) => s.status === ComposioServerStatus.ACTIVE),- disabledIdSet,- ).map((s) => ({ identifier: s.identifier, name: s.label }));-- const connectedIds = new Set(connected.map((s) => s.identifier));- const available = resolveAvailableComposioServices(- COMPOSIO_APP_TYPES,- connectedIds,- disabledIdSet,- );-- composioServicesList = generateComposioServicesList(connected, available);- log(- 'Composio services context resolved: connected=%d, available=%d',- connected.length,- available.length,- );- } catch (error) {- log('Failed to resolve Composio services context:', error);- }- }-const userMemoryConfig =enableUserMemories && userMemoryData? {@@ -504,198 +232,47 @@ export const contextEngineering = async ({}}- // Build Agent Management context.- // - availableAgents is injected whenever the user is in auto skill mode (so the- // supervisor can decide to activate agent-management on its own) OR when the tool- // is explicitly enabled.- // - availableProviders / availablePlugins are only built when the tool is explicitly- // enabled, since they're solely needed for createAgent / updateAgent.- let agentManagementContext: AgentManagementContext | undefined;-+ // Which facts this turn needs (plan, references, builder contexts, agent+ // management, credentials, connectors, onboarding, workspace links) is+ // decided by the shared rules; the browser only answers the lookups they+ // ask for, from the stores first.+ const chatStoreState = getChatStoreState();+ const agentConfig = agentId+ ? agentSelectors.getAgentConfigById(agentId)(agentStoreState)+ : undefined;+ const agentMeta = agentId ? agentSelectors.getAgentMetaById(agentId)(agentStoreState) : undefined;+ const agentItem = agentId ? agentByIdSelectors.getAgentById(agentId)(agentStoreState) : undefined;const isInAutoSkillMode =agentChatConfigSelectors.skillActivateMode(agentStoreState) !== 'manual';- const shouldInjectAvailableAgents = isInAutoSkillMode || isAgentManagementEnabled;-- if (shouldInjectAvailableAgents) {- try {- const recentAgents =- agentStoreState.availableAgents ??- (await agentService.queryAgents({ limit: AVAILABLE_AGENTS_CONTEXT_QUERY_LIMIT }));-- // Exclude current agent from `availableAgents`. The model is the current- // agent β its identity/persona is already established by `systemRole`, so- // we don't re-inject it here, and removing self from the list ensures the- // model never sees its own id in the agent-management context (so it- // cannot accidentally call itself via `callAgent`).- const otherAgents = agentId ? recentAgents.filter((a) => a.id !== agentId) : recentAgents;- const hasMoreAgents = otherAgents.length > AVAILABLE_AGENTS_CONTEXT_LIMIT;- const availableAgents = otherAgents.slice(0, AVAILABLE_AGENTS_CONTEXT_LIMIT).map((a) => ({- description: a.description ?? undefined,- id: a.id,- title: a.title ?? 'Untitled',- }));-- agentManagementContext = {- availableAgents,- availableAgentsHasMore: hasMoreAgents,- ...(agentId && {- currentAgent: {- id: agentId,- title: agentSelectors.getAgentMetaById(agentId)(agentStoreState)?.title ?? undefined,- },- }),- };- log('availableAgents fetched: %d agents (hasMore=%s)', availableAgents.length, hasMoreAgents);- } catch (error) {- // Silently fail - availableAgents context is optional- log('Failed to fetch availableAgents: %O', error);- }- }-- if (isAgentManagementEnabled) {- // Get enabled providers and models from aiInfra store- const aiProviderState = getAiInfraStoreState();- const enabledChatModelList = aiProviderState.enabledChatModelList || [];-- // Build availableProviders from enabled chat models (only user-enabled providers)- // Limit to first 5 providers to avoid context bloat- const availableProviders = enabledChatModelList.slice(0, 5).map((provider) => ({- id: provider.id,- models: provider.children.map((model) => ({- abilities: model.abilities,- description: model.description,- id: model.id,- name: model.displayName || model.id,- })),- name: provider.name,- }));-- // Get tool state for plugins- const toolState = getToolStoreState();-- // Build availablePlugins from all plugin sources- const availablePlugins = [];-- // Builtin tools (use allMetaList to include hidden tools like web-browsing, cloud-sandbox, etc.)- // Exclude only truly internal tools (agent-management itself, agent-builder, page-agent)- const allBuiltinTools = builtinToolSelectors.allMetaList(toolState);- const isComposioEnabled = Boolean(- typeof window !== 'undefined' &&- window.global_serverConfigStore?.getState()?.serverConfig?.enableComposio,- );- const isLobehubSkillEnabled = Boolean(- typeof window !== 'undefined' &&- window.global_serverConfigStore?.getState()?.serverConfig?.enableLobehubSkill,- );- const connectorCatalog = getConnectorCatalog({- composio: isComposioEnabled,- lobehub: isLobehubSkillEnabled,- });- const connectorIdentifiers = new Set(- connectorCatalog.map((item) =>- item.type === 'lobehub' ? item.provider.id : item.serverType.identifier,- ),- );- const INTERNAL_TOOLS = new Set([- 'lobe-agent-management', // Don't show agent-management in its own context- 'lobe-agent-builder', // Used for editing current agent, not for creating new agents- 'lobe-group-agent-builder', // Used for editing current group, not for creating new agents- 'lobe-page-agent', // Page-editor specific tool- ]);-- for (const tool of allBuiltinTools) {- if (connectorIdentifiers.has(tool.identifier)) continue;- // Skip internal tools- if (INTERNAL_TOOLS.has(tool.identifier)) continue;-- availablePlugins.push({- description: tool.meta?.description,- identifier: tool.identifier,- name: tool.meta?.title || tool.identifier,- type: 'builtin' as const,- });- }-- for (const connector of connectorCatalog) {- if (connector.type === 'composio') {- const { serverType } = connector;- availablePlugins.push({- description: serverType.description,- identifier: serverType.identifier,- name: serverType.label,- type: 'composio' as const,- });- continue;- }-- const { provider } = connector;- availablePlugins.push({- description: provider.description,- identifier: provider.id,- name: provider.label,- type: 'lobehub-skill' as const,- });- }-- agentManagementContext = {- ...agentManagementContext,- availablePlugins,- availableProviders,- };-- log(- 'agentManagementContext built: %d providers, %d plugins, %d agents',- agentManagementContext.availableProviders?.length ?? 0,- agentManagementContext.availablePlugins?.length ?? 0,- agentManagementContext.availableAgents?.length ?? 0,- );- }-- // Inject mentionedAgents independently of isAgentManagementEnabled.- // When user @mentions an agent, delegation context must always be injected- // even if the agent doesn't have agent-management tool in its config.- const hasMentionedAgents =- initialContext?.mentionedAgents && initialContext.mentionedAgents.length > 0;-- if (hasMentionedAgents) {- agentManagementContext = {- ...agentManagementContext,- mentionedAgents: initialContext!.mentionedAgents,- };- log('mentionedAgents injected: %d agents', initialContext!.mentionedAgents!.length);- }-- // Resolve topic references from messages containing <refer_topic> tags- const topicReferences =- (await resolveTopicReferences(- messages,- async (topicId: string) => {- const topic = topicSelectors.getTopicById(topicId)(getChatStoreState());- return topic ?? null;- },- async (topicId: string) => {- const { messageService } = await import('@/services/message');- const msgs = await messageService.getMessages({ agentId, groupId, topicId });- return msgs.map((m) => ({- content: typeof m.content === 'string' ? m.content : '',- role: m.role,- }));+ const facts = await gatherContextFacts(+ {+ agent: {+ // The current-agent chat config carries the skill activation mode the+ // management rule reads, even when `agentId` is a transient target.+ chatConfig:+ agentConfig?.chatConfig ?? agentChatConfigSelectors.currentChatConfig(agentStoreState),+ description: agentMeta?.description,+ slug: agentItem?.slug,+ title: agentMeta?.title,},- )) ?? [];-- // Build onboarding context if this is the web-onboarding agent.- // Single combined trpc call β server runs state/soul/persona DB queries in parallel.- let onboardingContext: OnboardingContext | undefined;- const isOnboardingAgent = tools?.includes(WebOnboardingIdentifier);- if (isOnboardingAgent) {- try {- const { userService } = await import('@/services/user');- onboardingContext = await userService.getOnboardingAgentContext();- log('Built onboarding context');- } catch (error) {- log('Failed to build onboarding context: %O', error);- }- }+ agentId,+ disabledPluginIds,+ // The Profile panel edits `activeAgentId` / `activeGroupId`, not the+ // builder agent that is answering.+ editingAgentId: tools?.includes(AgentBuilderIdentifier)+ ? chatStoreState.activeAgentId || agentId+ : undefined,+ editingGroupId: chatStoreState.activeGroupId || undefined,+ enabledToolIds: tools ?? [],+ features: resolveBrowserConnectorFeatures(),+ mentionedAgents: initialContext?.mentionedAgents,+ messages,+ shareVisitor,+ topicId,+ workspaceId: getActiveWorkspaceId() ?? undefined,+ },+ createBrowserContextFactProviders({ agentId, groupId, shareVisitor }),+ );// Resolve enabled skills (await: pinned DB skills fetch their content on demand).// In auto mode: expose all installed skills so the AI can discover and activate them.@@ -711,32 +288,22 @@ export const contextEngineering = async ({}}- // The agent's identity lives on the agent row (name/title), not in the- // prompt text β inject it so the model can answer "who are you?" with the- // name the user gave it instead of the product/model name.- const agentIdentityMeta = agentId- ? agentSelectors.getAgentMetaById(agentId)(agentStoreState)- : undefined;-- // Where the run lives (app origin + active workspace slug) so the model- // writes in-app links that resolve to the right scope. Mirrors the server- // runtime's `resolveWorkspaceContext`.- const workspaceContext = resolveClientWorkspaceContext();-- // Create MessagesEngine with injected dependencies// One timezone for every date the prompt renders β the core's temporal- // placeholders, the system-date line and the host's own `session_date` β- // so a run near midnight cannot carry two different dates.+ // placeholders (including `session_date`) and the system-date line β so a+ // run near midnight cannot carry two different dates.const userTimezone = userGeneralSettingsSelectors.currentTimezone(useUserStore.getState());// Everything gathered above is host-specific; shaping it into engine// parameters is shared with the server through `@lobechat/mecha`.const snapshot: ContextSnapshot = {agent: {- documents: agentDocuments,+ documents: facts.agentDocuments,enableHistoryCount,historyCount,- identity: { name: agentIdentityMeta?.name, title: agentIdentityMeta?.title },+ // The agent's identity lives on the agent row (name/title), not in the+ // prompt text β inject it so the model can answer "who are you?" with+ // the name the user gave it instead of the product/model name.+ identity: { name: agentMeta?.name, title: agentMeta?.title },inputTemplate,knowledge: { fileContents, knowledgeBases },systemRole,@@ -762,15 +329,7 @@ export const contextEngineering = async ({messages,stepContext,},- step: {- ...(isAgentBuilderEnabled && { agentBuilderContext }),- ...(isGroupAgentBuilderEnabled && { groupAgentBuilderContext }),- agentManagementContext,- onboardingContext,- planTodo: planTodoConfig,- topicReferences,- workspaceContext,- },+ step: facts.step,tools: {enabledSkills,enabledToolIds: tools,@@ -780,53 +339,17 @@ export const contextEngineering = async ({selectedTools: initialContext?.selectedTools,toolDiscoveryConfig,},- // Browser-resolved placeholders. The store-backed generators stay lazy so a- // placeholder that never renders costs nothing. Temporal placeholders are- // not among them: the core renders those in the user's timezone, the same- // way on every host.+ // Placeholders resolved by the shared rules (credentials, connectors,+ // sandbox files, agent / topic identity) plus the browser's own lazy+ // store-backed generators. Temporal placeholders are not among them: the+ // core renders those in the user's timezone, the same way on every host.variables: {+ ...facts.variables,...HOST_VARIABLE_GENERATORS,- // NOTICE: required by builtin-tool-creds/src/systemRole.ts- CREDS_LIST: () => (credsList ? generateCredsList(credsList) : ''),- // NOTICE: required by builtin-tool-creds/src/systemRole.ts (Composio integrations)- COMPOSIO_SERVICES_LIST: () => composioServicesList,- // NOTICE: required by builtin-tool-creds/src/systemRole.ts (session_context)- session_date: () =>- new Intl.DateTimeFormat('en-US', {- day: 'numeric',- month: 'long',- timeZone: userTimezone,- weekday: 'long',- year: 'numeric',- }).format(new Date()),- sandbox_enabled: () => String(tools?.includes('lobe-cloud-sandbox') ?? false),- // NOTICE: required by builtin-tool-cloud-sandbox/src/systemRole.ts β- // lists the topic files synced into the sandbox upload dir. Read lazily- // from the chat store so we only pay the cost when the placeholder renders.- sandbox_uploaded_files: () =>- tools?.includes('lobe-cloud-sandbox')- ? formatUploadedFilesPrompt(chatSelectors.currentUserFiles(getChatStoreState()))- : '',- // NOTICE(@nekomeowww): required by builtin-tool-memory/src/systemRole.ts+ // NOTICE(@nekomeowww): required by builtin-tool-memory/src/systemRole.ts β+ // the browser knows the effective effort (agent override, else the user+ // setting), which the agent row alone cannot tell.memory_effort: () => (userMemoryConfig ? (memoryContext?.effort ?? '') : ''),- // Current agent + topic identity β referenced by the LobeHub builtin- // skill (packages/builtin-skills/src/lobehub/content.ts) so the model- // can run `lh agent run -a {{agent_id}}` etc without first having to- // search for itself. Read lazily from stores so we only pay the cost- // when the placeholder actually appears in a rendered message.- agent_id: () => agentId ?? '',- agent_title: () =>- agentId ? (agentSelectors.getAgentMetaById(agentId)(agentStoreState)?.title ?? '') : '',- agent_description: () =>- agentId- ? (agentSelectors.getAgentMetaById(agentId)(agentStoreState)?.description ?? '')- : '',- topic_id: () => topicId ?? '',- topic_title: () => {- if (!topicId) return '';- const topic = topicSelectors.getTopicById(topicId)(getChatStoreState());- return topic?.title ?? '';- },},world: {group: agentGroup,@@ -850,18 +373,3 @@ export const contextEngineering = async ({return processed;};--const resolveClientAppOrigin = (): string | undefined => {- if (isDesktop) return electronSyncSelectors.remoteServerUrl(getElectronStoreState()) || undefined;- if (typeof window === 'undefined') return undefined;- return window.location.origin || undefined;-};--const resolveClientWorkspaceContext = (): WorkspaceContext | undefined => {- const appUrl = resolveClientAppOrigin();- const slug = getActiveWorkspaceSlug();-- if (!appUrl && !slug) return undefined;-- return { appUrl, ...(slug && { workspace: { slug } }) };-};diff --git a/src/services/chat/mecha/contextFactProviders.test.ts b/src/services/chat/mecha/contextFactProviders.test.tsnew file mode 100644index 00000000000..524503d29df--- /dev/null+++ b/src/services/chat/mecha/contextFactProviders.test.ts@@ -0,0 +1,171 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { lambdaClient } from '@/libs/trpc/client';+import { agentService } from '@/services/agent';+import { useAgentStore } from '@/store/agent';+import { useChatStore } from '@/store/chat';+import { useToolStore } from '@/store/tool';+import { ComposioServerStatus } from '@/store/tool/slices/composioStore';++import {+ createBrowserContextFactProviders,+ resolveBrowserConnectorFeatures,+} from './contextFactProviders';++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: { market: { creds: { listForContext: { query: vi.fn() } } } },+}));++vi.mock('@/services/agent', () => ({+ agentService: { queryAgents: vi.fn() },+}));++beforeEach(() => {+ useAgentStore.setState({ agentDocumentsMap: {}, availableAgents: undefined } as any);+ useToolStore.setState({+ composioServers: [],+ installedPlugins: [],+ lobehubSkillServers: [],+ uninstalledBuiltinTools: [],+ } as any);+});++afterEach(() => {+ vi.clearAllMocks();+});++describe('createBrowserContextFactProviders', () => {+ it('reports no connector features when the server config store is not mounted', () => {+ expect(resolveBrowserConnectorFeatures()).toEqual({ composio: false, lobehubSkill: false });+ });++ it('reuses the prefetched agent list and only queries when it is missing', async () => {+ const providers = createBrowserContextFactProviders();+ vi.mocked(agentService.queryAgents).mockResolvedValue([{ id: 'agent-2' }] as any);++ useAgentStore.setState({ availableAgents: [{ id: 'agent-1' }] } as any);+ await expect(providers.listRecentAgents!(12)).resolves.toEqual([{ id: 'agent-1' }]);+ expect(agentService.queryAgents).not.toHaveBeenCalled();++ useAgentStore.setState({ availableAgents: undefined } as any);+ await expect(providers.listRecentAgents!(12)).resolves.toEqual([{ id: 'agent-2' }]);+ expect(agentService.queryAgents).toHaveBeenCalledWith({ limit: 12 });+ });++ it('treats only active Composio connections and every installed LobeHub skill provider as connected', async () => {+ useToolStore.setState({+ composioServers: [+ { identifier: 'gmail', status: ComposioServerStatus.ACTIVE },+ { identifier: 'slack', status: ComposioServerStatus.PENDING_AUTH },+ ],+ lobehubSkillServers: [{ identifier: 'linear', isConnected: false }],+ } as any);++ const connected = await createBrowserContextFactProviders().listConnectedConnectorIds!();++ expect(new Set(connected)).toEqual(new Set(['gmail', 'linear']));+ });++ it('reports the builtins the user uninstalled', async () => {+ useToolStore.setState({ uninstalledBuiltinTools: ['lobe-gone'] } as any);++ await expect(createBrowserContextFactProviders().listUninstalledBuiltinIds!()).resolves.toEqual(+ ['lobe-gone'],+ );+ });++ it('answers agent documents from the store cache first', async () => {+ useAgentStore.setState({+ agentDocumentsMap: { 'agent-1': [{ content: 'cached', id: 'doc-1' }] },+ } as any);++ await expect(+ createBrowserContextFactProviders().listAgentDocuments!('agent-1'),+ ).resolves.toEqual([{ content: 'cached', id: 'doc-1' }]);+ });++ it('hydrates agent documents through the store when the cache is empty', async () => {+ const { agentDocumentService } = await import('@/services/agentDocument');+ const getContextDocuments = vi+ .spyOn(agentDocumentService, 'getContextDocuments')+ .mockResolvedValue([+ {+ content: 'Project setup steps',+ filename: 'setup.md',+ id: 'doc-1',+ loadRules: [],+ policy: null,+ policyLoadFormat: null,+ policyLoadPosition: null,+ templateId: null,+ title: 'Setup',+ },+ ] as any);++ const documents = await createBrowserContextFactProviders().listAgentDocuments!('agent-1');++ expect(getContextDocuments).toHaveBeenCalledWith({ agentId: 'agent-1' });+ expect(documents).toEqual([+ expect.objectContaining({+ content: 'Project setup steps',+ filename: 'setup.md',+ id: 'doc-1',+ }),+ ]);+ });++ it('lets the server scope the credential list to the verified workspace', async () => {+ vi.mocked(lambdaClient.market.creds.listForContext.query).mockResolvedValue({+ data: [{ key: 'ORG_SECRET', name: 'Org', ownerType: 'organization', type: 'kv-env' }],+ } as any);++ const creds = await createBrowserContextFactProviders().listCredentials!({+ workspaceId: 'ws-1',+ });++ expect(creds?.map((c) => c.key)).toEqual(['ORG_SECRET']);+ });++ it('attributes a cached topic to the share visitor so the visibility rule can admit it', async () => {+ useChatStore.setState({+ topicDataMap: {+ agt_1: { items: [{ historySummary: 'sum', id: 'tpc_1', title: 'Mine' }] },+ },+ } as any);+ const visitor = { agentId: 'agt_1', shareId: 'share_1', visitorUserId: 'visitor_1' };++ const cached = await createBrowserContextFactProviders().findTopic!('tpc_1');+ expect(cached).toMatchObject({ id: 'tpc_1', senderId: undefined });++ const asVisitor = await createBrowserContextFactProviders({ shareVisitor: visitor }).findTopic!(+ 'tpc_1',+ );+ expect(asVisitor).toMatchObject({ agentId: 'agt_1', id: 'tpc_1', senderId: 'visitor_1' });++ const { messageService } = await import('@/services/message');+ const getMessages = vi.spyOn(messageService, 'getMessages').mockResolvedValue([]);+ await createBrowserContextFactProviders({ shareVisitor: visitor }).listTopicMessages!({+ id: 'tpc_1',+ });+ expect(getMessages).toHaveBeenCalledWith(expect.objectContaining({ agentShareId: 'share_1' }));+ });++ it('scopes referenced-topic reads to the executing agent and group', async () => {+ const { messageService } = await import('@/services/message');+ const getMessages = vi+ .spyOn(messageService, 'getMessages')+ .mockResolvedValue([{ content: 'hi', role: 'user' }] as any);++ const messages = await createBrowserContextFactProviders({+ agentId: 'agent-1',+ groupId: 'group-1',+ }).listTopicMessages!({ id: 'tpc_1' });++ expect(getMessages).toHaveBeenCalledWith({+ agentId: 'agent-1',+ groupId: 'group-1',+ topicId: 'tpc_1',+ });+ expect(messages).toEqual([{ content: 'hi', role: 'user' }]);+ });+});diff --git a/src/services/chat/mecha/contextFactProviders.ts b/src/services/chat/mecha/contextFactProviders.tsnew file mode 100644index 00000000000..c6becbfb8e9--- /dev/null+++ b/src/services/chat/mecha/contextFactProviders.ts@@ -0,0 +1,243 @@+import { AGENT_PLAN_FILE_TYPE, isDesktop } from '@lobechat/const';+import type { ContextFactProviders, ContextFactRequest, CredentialSummary } from '@lobechat/mecha';+import { type AgentShareVisitorContext, getActivePluginIds } from '@lobechat/types';++import { getActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';+import { lambdaClient } from '@/libs/trpc/client';+import { agentService } from '@/services/agent';+import { messageService } from '@/services/message';+import { notebookService } from '@/services/notebook';+import { userService } from '@/services/user';+import { getAgentStoreState } from '@/store/agent';+import { agentSelectors } from '@/store/agent/selectors';+import { getChatGroupStoreState } from '@/store/agentGroup';+import { agentGroupSelectors } from '@/store/agentGroup/selectors';+import { getAiInfraStoreState } from '@/store/aiInfra';+import { getChatStoreState } from '@/store/chat';+import { chatSelectors, topicSelectors } from '@/store/chat/selectors';+import { getElectronStoreState } from '@/store/electron';+import { electronSyncSelectors } from '@/store/electron/selectors';+import { getServerConfigStoreState } from '@/store/serverConfig';+import { serverConfigSelectors } from '@/store/serverConfig/selectors';+import { getToolStoreState } from '@/store/tool';+import {+ composioStoreSelectors,+ lobehubSkillStoreSelectors,+ pluginSelectors,+} from '@/store/tool/selectors';+import { ComposioServerStatus } from '@/store/tool/slices/composioStore';+import { getUserStoreState } from '@/store/user';+import { userGeneralSettingsSelectors, userProfileSelectors } from '@/store/user/selectors';++export interface BrowserContextFactSource {+ /** Executing agent, used to scope referenced-topic reads. */+ agentId?: string;+ groupId?: string;+ /** Present only when the browser answers a share visitor. */+ shareVisitor?: BrowserShareVisitor;+}++/**+ * The visitor context a browser caller can supply. `shareId` routes+ * referenced-topic reads through the share-authorized message endpoint.+ */+export type BrowserShareVisitor = Pick<AgentShareVisitorContext, 'agentId' | 'visitorUserId'> & {+ shareId?: string;+};++/** The topic row fields the store carries beyond the `ChatTopic` type. */+interface StoredTopicOwnership {+ agentId?: string | null;+ groupId?: string | null;+ senderId?: string | null;+}++/** Which connector families this deployment offers, as the server config reports. */+export const resolveBrowserConnectorFeatures = (): ContextFactRequest['features'] => {+ const serverConfig = getServerConfigStoreState();+ if (!serverConfig) return { composio: false, lobehubSkill: false };+ return {+ composio: serverConfigSelectors.enableComposio(serverConfig),+ lobehubSkill: serverConfigSelectors.enableLobehubSkill(serverConfig),+ };+};++const resolveClientAppOrigin = (): string | undefined => {+ if (isDesktop) return electronSyncSelectors.remoteServerUrl(getElectronStoreState()) || undefined;+ if (typeof window === 'undefined') return undefined;+ return window.location.origin || undefined;+};++const toIsoString = (value: Date | string | null | undefined): string =>+ value instanceof Date ? value.toISOString() : (value ?? '');++/**+ * How the browser fetches the facts the shared context rules ask for. Every+ * method reads the stores first and only goes to the network for what the+ * stores do not hold; which facts a turn needs is decided by+ * `gatherContextFacts` in `@lobechat/mecha`, the same way as on the server.+ */+export const createBrowserContextFactProviders = ({+ agentId,+ groupId,+ shareVisitor,+}: BrowserContextFactSource = {}): ContextFactProviders => ({+ findTopic: async (topicId) => {+ const topic = topicSelectors.getTopicById(topicId)(getChatStoreState());+ if (!topic) return null;+ const stored = topic as typeof topic & StoredTopicOwnership;+ return {+ // A visitor's store only ever holds topics the server already scoped to+ // this visitor and the shared agent (`shareChat.getTopics` queries by+ // sender + agent), so a cached topic without explicit ownership columns+ // is the visitor's own β the shared visibility rule must see it as such.+ agentId: stored.agentId ?? shareVisitor?.agentId,+ groupId: stored.groupId,+ historySummary: topic.historySummary,+ id: topic.id,+ senderId: stored.senderId ?? shareVisitor?.visitorUserId,+ title: topic.title,+ };+ },++ getAgentDefinition: async (targetAgentId) => {+ const state = getAgentStoreState();+ const config = agentSelectors.getAgentConfigById(targetAgentId)(state);+ const meta = agentSelectors.getAgentMetaById(targetAgentId)(state);+ if (!config) return null;+ return {+ avatar: meta?.avatar,+ backgroundColor: meta?.backgroundColor,+ chatConfig: config.chatConfig,+ description: meta?.description,+ model: config.model,+ name: meta?.name,+ openingMessage: config.openingMessage,+ openingQuestions: config.openingQuestions,+ params: config.params as Record<string, unknown> | undefined,+ plugins: getActivePluginIds(config.plugins),+ provider: config.provider,+ systemRole: config.systemRole,+ tags: meta?.tags,+ title: meta?.title,+ };+ },++ getGroup: async (targetGroupId) => {+ const group = agentGroupSelectors.getGroupById(targetGroupId)(getChatGroupStoreState());+ if (!group) return null;+ return {+ config: group.config,+ content: group.content,+ members: (group.agents ?? []).map((member) => ({+ agentId: member.id,+ description: member.description,+ role: member.isSupervisor ? 'supervisor' : 'participant',+ title: member.title,+ })),+ title: group.title,+ };+ },++ // Single combined trpc call β the server runs state/soul/persona queries in parallel.+ getOnboardingContext: () => userService.getOnboardingAgentContext(),++ getPlanDocument: async (topicId) => {+ const { data } = await notebookService.listDocuments({ topicId, type: AGENT_PLAN_FILE_TYPE });+ const planDocument = data[0];+ if (!planDocument) return null;+ return {+ content: planDocument.content,+ createdAt: toIsoString(planDocument.createdAt),+ description: planDocument.description,+ id: planDocument.id,+ metadata: planDocument.metadata as { todos?: unknown } | null,+ title: planDocument.title,+ updatedAt: toIsoString(planDocument.updatedAt),+ };+ },++ getUserInfo: async () => {+ const userState = getUserStoreState();+ return {+ language: userGeneralSettingsSelectors.responseLanguage(userState),+ username: userProfileSelectors.displayUserName(userState),+ };+ },++ getWorkspaceContext: async () => ({+ appUrl: resolveClientAppOrigin(),+ slug: getActiveWorkspaceSlug() ?? undefined,+ }),++ // Cache-first: the store dedupes in-flight hydration per agent.+ listAgentDocuments: (targetAgentId) => getAgentStoreState().ensureAgentDocuments(targetAgentId),++ listConnectedConnectorIds: async () => {+ const toolState = getToolStoreState();+ const connected = new Set<string>();+ for (const server of composioStoreSelectors.getServers(toolState)) {+ if (server.status === ComposioServerStatus.ACTIVE) connected.add(server.identifier);+ }+ for (const server of lobehubSkillStoreSelectors.getServers(toolState)) {+ connected.add(server.identifier);+ }+ return connected;+ },++ // The server resolves the scope from the verified workspace header: the+ // workspace's shared organization creds inside a workspace, personal+ // creds otherwise β the same rule the server runtime applies.+ listCredentials: async () => {+ const result = await lambdaClient.market.creds.listForContext.query();+ return result.data as CredentialSummary[];+ },++ listCustomPlugins: async () =>+ pluginSelectors.installedCustomPluginMetaList(getToolStoreState()).map((plugin) => ({+ description: plugin.description,+ identifier: plugin.identifier,+ name: plugin.title || plugin.identifier,+ type: 'custom' as const,+ })),++ listEnabledProviders: async () =>+ (getAiInfraStoreState().enabledChatModelList || []).map((provider) => ({+ id: provider.id,+ models: provider.children.map((model) => ({+ abilities: model.abilities,+ description: model.description,+ id: model.id,+ name: model.displayName || model.id,+ })),+ name: provider.name,+ })),++ // The prefetched list is reused when present so sending never waits on it.+ listRecentAgents: async (limit) =>+ getAgentStoreState().availableAgents ?? (await agentService.queryAgents({ limit })),++ // Non-recommended builtins are uninstalled by default; the builder must+ // not present them as installed and pin unusable identifiers.+ listUninstalledBuiltinIds: async () => getToolStoreState().uninstalledBuiltinTools,++ listSandboxFiles: async () =>+ chatSelectors+ .currentUserFiles(getChatStoreState())+ .map((file) => ({ name: file.name, size: file.size })),++ listTopicMessages: async (topic) => {+ const msgs = await messageService.getMessages({+ agentId,+ // Share rows belong to the creator; a visitor must read through the+ // share-authorized endpoint or the owner-scoped query comes back empty.+ agentShareId: shareVisitor?.shareId,+ groupId,+ topicId: topic.id,+ });+ return msgs.map((m) => ({+ content: typeof m.content === 'string' ? m.content : '',+ role: m.role,+ }));+ },+});