π€― 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(mecha): decide which context facts a step needs in the shared core (#19576)
Arvin Xu237392c46838
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.tsindex 989912a997c..f8cb33beb61 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts@@ -2227,7 +2227,9 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {state,);- return mockChat.mock.calls[0][0].messages.find(+ // The shared context rules may prepend an agent-management block as its+ // own user turn; the TODO state rides on the actual user message.+ return mockChat.mock.calls[0][0].messages.findLast((message: { role?: string }) => message.role === 'user',)?.content as string;};@@ -2262,8 +2264,9 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {expect(content).toContain('New task');expect(content).not.toContain('Old task');+ // The plan document is still read for the plan block, but history wins+ // for the TODO state.expect(content).not.toContain('Stale metadata task');- expect(mockFindPlanDocuments).not.toHaveBeenCalled();});it.each([{ items: [], updatedAt: 'canonical-clear' }, []])(@@ -2288,7 +2291,6 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {expect(content).not.toContain('<todo_context>');expect(content).not.toContain('Stale metadata task');- expect(mockFindPlanDocuments).not.toHaveBeenCalled();},);diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.tsindex 54c9138f053..ba0b6687145 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts@@ -1,4 +1,5 @@import type { AgentState, CallLLMPayload } from '@lobechat/agent-runtime';+import { gatherContextFacts } from '@lobechat/mecha';import type { ChatStreamPayload } from '@lobechat/model-runtime';import { SpanStatusCode } from '@lobechat/observability-otel/api';import {@@ -8,7 +9,10 @@ import {} from '@lobechat/observability-otel/modules/agent-runtime';import { serverMessagesEngine } from '@/server/modules/Mecha/ContextEngineering';-import { gatherServerContextFacts } from '@/server/modules/Mecha/ContextEngineering/providers';+import {+ createServerContextFactProviders,+ resolveServerConnectorFeatures,+} from '@/server/modules/Mecha/ContextEngineering/providers';import type { RuntimeExecutorContext } from '../context';import { resolveRuntimeHistoryCount } from '../executorHelpers';@@ -72,26 +76,32 @@ export const buildServerCallLlmContext = async ({const agentId = state.origin?.agentId;const topicId = ctx.topicId ?? state.origin?.topicId;- const facts = await gatherServerContextFacts({- activeDeviceId,- agentId,- ctx,- enabledToolIds: resolved.enabledToolIds,- executionTarget,- messagesForContext,- state,- topicId,- workspaceId: state.origin?.workspaceId ?? ctx.workspaceId,- });-- const sessionDate = new Intl.DateTimeFormat('en-US', {- day: 'numeric',- month: 'long',- timeZone: state.world?.userTimezone || 'UTC',- weekday: 'long',- year: 'numeric',- }).format(new Date());- const memoryEffort = String(agentConfig.chatConfig?.memory?.effort ?? '');+ // Which facts this turn needs is decided by the shared rules; the server+ // only answers the lookups they ask for.+ const facts = await gatherContextFacts(+ {+ activeDeviceId,+ agent: {+ chatConfig: agentConfig.chatConfig,+ description: agentConfig.description,+ slug: agentConfig.slug,+ title: agentConfig.title,+ },+ agentId,+ disabledPluginIds: state.world?.disabledPluginIds,+ editingAgentId: state.metadata?.editingAgentId as string | undefined,+ editingGroupId: state.metadata?.editingGroupId as string | undefined,+ enabledToolIds: resolved.enabledToolIds,+ executionTarget,+ features: resolveServerConnectorFeatures(),+ mentionedAgents: (state as any).initialContext?.initialContext?.mentionedAgents,+ messages: messagesForContext,+ shareVisitor: state.principal?.actor?.shareVisitor ?? ctx.agentShareVisitor,+ topicId,+ workspaceId: state.origin?.workspaceId ?? ctx.workspaceId,+ },+ createServerContextFactProviders({ ctx, state }),+ );const contextEngineInput = {additionalContexts: llmPayload.additionalContexts,@@ -101,19 +111,13 @@ export const buildServerCallLlmContext = async ({agentIdentity: { name: agentConfig.name ?? undefined, title: agentConfig.title ?? undefined },...(facts.step.agentBuilderContext && { agentBuilderContext: facts.step.agentBuilderContext }),agentGroup: state.world?.group,- agentManagementContext: (state as any).initialContext?.initialContext?.mentionedAgents?.length- ? {- mentionedAgents: (state as any).initialContext.initialContext.mentionedAgents,- }- : undefined,+ agentManagementContext: facts.step.agentManagementContext,additionalVariables: {...state.binding?.device?.systemInfo,...facts.variables,// Only override the generator's 'en-US' locale fallback when the user info// fetch actually resolved a language β an empty string would render blank.- ...(facts.variables.language && { locale: facts.variables.language }),- memory_effort: memoryEffort,- session_date: sessionDate,+ ...(facts.variables.language && { locale: facts.variables.language as string }),},userTimezone: state.world?.userTimezone,capabilities,diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/__tests__/gatherServerContextFacts.test.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/__tests__/gatherServerContextFacts.test.tsdeleted file mode 100644index ee19dd361b9..00000000000--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/__tests__/gatherServerContextFacts.test.ts+++ /dev/null@@ -1,122 +0,0 @@-import { describe, expect, it, vi } from 'vitest';--import { gatherServerContextFacts, PROVIDER_CONCURRENCY } from '../index';-import { resolveSandboxVariables } from '../sandboxVariables';-import type { ServerContextFactInput } from '../types';--const mocks = vi.hoisted(() => {- const names = [- 'resolveAgentBuilderContextFacts',- 'resolveAgentDocumentFacts',- 'resolveComposioServicesVariable',- 'resolveCredsListVariable',- 'resolveGroupAgentBuilderContextFacts',- 'resolveLobehubSkillVariables',- 'resolveOnboardingContextFacts',- 'resolvePlanTodoFacts',- 'resolveTopicReferenceFacts',- 'resolveUserInfoVariables',- 'resolveWorkspaceContextFacts',- ] as const;- return Object.fromEntries(names.map((name) => [name, vi.fn()])) as Record<- (typeof names)[number],- ReturnType<typeof vi.fn>- >;-});--vi.mock('../agentBuilderContext', () => ({- resolveAgentBuilderContextFacts: mocks.resolveAgentBuilderContextFacts,-}));-vi.mock('../agentDocuments', () => ({- resolveAgentDocumentFacts: mocks.resolveAgentDocumentFacts,-}));-vi.mock('../composioServices', () => ({- resolveComposioServicesVariable: mocks.resolveComposioServicesVariable,-}));-vi.mock('../credsList', () => ({ resolveCredsListVariable: mocks.resolveCredsListVariable }));-vi.mock('../groupAgentBuilderContext', () => ({- resolveGroupAgentBuilderContextFacts: mocks.resolveGroupAgentBuilderContextFacts,-}));-vi.mock('../lobehubSkillVariables', () => ({- resolveLobehubSkillVariables: mocks.resolveLobehubSkillVariables,-}));-vi.mock('../onboardingContext', () => ({- resolveOnboardingContextFacts: mocks.resolveOnboardingContextFacts,-}));-vi.mock('../planTodo', () => ({ resolvePlanTodoFacts: mocks.resolvePlanTodoFacts }));-vi.mock('../topicReferences', () => ({- resolveTopicReferenceFacts: mocks.resolveTopicReferenceFacts,-}));-vi.mock('../userInfoVariables', () => ({- resolveUserInfoVariables: mocks.resolveUserInfoVariables,-}));-vi.mock('../workspaceContext', () => ({- resolveWorkspaceContextFacts: mocks.resolveWorkspaceContextFacts,-}));--const input = (overrides: Partial<ServerContextFactInput> = {}): ServerContextFactInput => ({- ctx: {} as never,- enabledToolIds: [],- messagesForContext: [],- state: {} as never,- ...overrides,-});--describe('gatherServerContextFacts', () => {- it('overlaps the providers but never runs more than the cap at once', async () => {- let inFlight = 0;- let maxInFlight = 0;- const slow = (value: unknown) => async () => {- inFlight += 1;- maxInFlight = Math.max(maxInFlight, inFlight);- await new Promise((resolve) => setTimeout(resolve, 5));- inFlight -= 1;- return value;- };- for (const mock of Object.values(mocks)) mock.mockImplementation(slow(undefined));- mocks.resolveAgentDocumentFacts.mockImplementation(slow([{ id: 'd1' }]));- mocks.resolveCredsListVariable.mockImplementation(slow('creds'));- mocks.resolveTopicReferenceFacts.mockImplementation(slow([{ id: 't1' }]));- mocks.resolveLobehubSkillVariables.mockImplementation(- slow({ agent_id: 'agt_1', topic_title: 'T' }),- );- mocks.resolveUserInfoVariables.mockImplementation(- slow({ language: 'zh-CN', username: 'arvin' }),- );-- const facts = await gatherServerContextFacts(input());-- // Eleven slow providers (the sandbox one is real and returns at once),- // eight at a time: bounded, but still overlapping.- expect(maxInFlight).toBe(PROVIDER_CONCURRENCY);- expect(facts.agentDocuments).toEqual([{ id: 'd1' }]);- expect(facts.step.topicReferences).toEqual([{ id: 't1' }]);- expect(facts.variables).toMatchObject({- CREDS_LIST: 'creds',- agent_id: 'agt_1',- language: 'zh-CN',- sandbox_enabled: 'false',- topic_title: 'T',- username: 'arvin',- });- });-});--describe('resolveSandboxVariables', () => {- it('reports the sandbox reachable when no device is routed or the target is auto', async () => {- const base = input({ ctx: { serverDB: undefined } as never });-- await expect(- resolveSandboxVariables({ ...base, executionTarget: 'none' }),- ).resolves.toMatchObject({ creds_sandbox_reachable: 'true', sandbox_enabled: 'false' });- await expect(- resolveSandboxVariables({ ...base, activeDeviceId: 'dev-1', executionTarget: 'auto' }),- ).resolves.toMatchObject({ creds_sandbox_reachable: 'true' });- await expect(- resolveSandboxVariables({ ...base, activeDeviceId: 'dev-1', executionTarget: 'device' }),- ).resolves.toMatchObject({ creds_sandbox_reachable: 'false' });- await expect(- resolveSandboxVariables({ ...base, enabledToolIds: ['lobe-cloud-sandbox'] }),- ).resolves.toMatchObject({ sandbox_enabled: 'true', sandbox_uploaded_files: '' });- });-});diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/agentBuilderContext.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/agentBuilderContext.tsdeleted file mode 100644index aaac90dcb71..00000000000--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/agentBuilderContext.ts+++ /dev/null@@ -1,66 +0,0 @@-import type { AgentBuilderContext } from '@lobechat/context-engine';-import { getActivePluginIds } from '@lobechat/types';--import { AgentModel } from '@/database/models/agent';-import { log } from '@/server/modules/AgentRuntime/executorHelpers';--import { listOfficialTools } from './officialTools';-import type { ServerContextFactInput } from './types';--/**- * The agent currently being edited in the Profile panel, so the builder- * agent knows what it is editing. Keyed off `metadata.editingAgentId`, which- * the client stamps when it opens the panel.- */-export const resolveAgentBuilderContextFacts = async ({- ctx,- state,-}: ServerContextFactInput): Promise<AgentBuilderContext | undefined> => {- const editingAgentId = state.metadata?.editingAgentId as string | undefined;- if (!editingAgentId || !ctx.serverDB || !ctx.userId) return undefined;- try {- const editingConfig = (await new AgentModel(- ctx.serverDB,- ctx.userId,- ctx.workspaceId,- ).getAgentConfigById(editingAgentId)) as Record<string, any> | null;- if (!editingConfig) return undefined;-- const enabledPlugins: string[] = getActivePluginIds(- Array.isArray(editingConfig.plugins) ? editingConfig.plugins : undefined,- );- const officialTools = await listOfficialTools({- agentId: editingAgentId,- db: ctx.serverDB,- enabledPlugins,- label: 'agentBuilderContext',- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });-- return {- config: {- chatConfig: editingConfig.chatConfig ?? undefined,- model: editingConfig.model ?? undefined,- openingMessage: editingConfig.openingMessage ?? undefined,- openingQuestions: editingConfig.openingQuestions ?? undefined,- params: editingConfig.params ?? undefined,- plugins: enabledPlugins,- provider: editingConfig.provider ?? undefined,- systemRole: editingConfig.systemRole ?? undefined,- },- meta: {- avatar: editingConfig.avatar ?? undefined,- backgroundColor: editingConfig.backgroundColor ?? undefined,- description: editingConfig.description ?? undefined,- name: editingConfig.name ?? undefined,- tags: editingConfig.tags ?? undefined,- title: editingConfig.title ?? undefined,- },- ...(officialTools.length > 0 && { officialTools }),- };- } catch (error) {- log('Failed to build agentBuilderContext for editing agent %s: %O', editingAgentId, error);- return undefined;- }-};diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/agentDocuments.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/agentDocuments.tsdeleted file mode 100644index 1838e67372f..00000000000--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/agentDocuments.ts+++ /dev/null@@ -1,36 +0,0 @@-import type { AgentContextDocument } from '@lobechat/context-engine';--import { log } from '@/server/modules/AgentRuntime/executorHelpers';-import { AgentDocumentsService } from '@/server/services/agentDocuments';-import { toAgentContextDocuments } from '@/utils/agentDocumentContextMapping';--import type { ServerContextFactInput } from './types';--/**- * The agent's context documents. A share visitor run never sees the creator's- * documents: `applyShareGateToAgentConfig` already blanks `agentConfig.files` /- * `knowledgeBases`, but this source is fetched independently of agentConfig,- * so it needs its own gate. Fail closed unconditionally: the share config has- * no setting that could grant file access.- */-export const resolveAgentDocumentFacts = async ({- agentId,- ctx,- workspaceId,-}: ServerContextFactInput): Promise<AgentContextDocument[] | undefined> => {- if (!agentId || !ctx.serverDB || !ctx.userId || ctx.agentShareVisitor) return undefined;- try {- const docs = await new AgentDocumentsService(- ctx.serverDB,- ctx.userId,- workspaceId,- ).getAgentContextDocuments(agentId);- if (docs.length === 0) return undefined;- const documents = toAgentContextDocuments(docs);- log('Resolved %d agent documents for agent %s', documents.length, agentId);- return documents;- } catch (error) {- log('Failed to resolve agent documents for agent %s: %O', agentId, error);- return undefined;- }-};diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/composioServices.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/composioServices.tsdeleted file mode 100644index bc985d4f324..00000000000--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/composioServices.ts+++ /dev/null@@ -1,64 +0,0 @@-import {- type ComposioServiceSummary,- excludeDisabledComposioServices,- generateComposioServicesList,- resolveAvailableComposioServices,-} from '@lobechat/builtin-tool-creds';-import { COMPOSIO_APP_TYPES } from '@lobechat/const';-import { getDisabledPluginIds } from '@lobechat/types';--import { composioEnv } from '@/config/composio';-import { AgentModel } from '@/database/models/agent';-import { loadConnectedComposioIds } from '@/server/modules/AgentRuntime/adapters/composioConnectedIds';-import { log } from '@/server/modules/AgentRuntime/executorHelpers';--import type { ServerContextFactInput } from './types';--/**- * `{{COMPOSIO_SERVICES_LIST}}` β connected vs. available Composio services.- * Connected = ACTIVE connections across BOTH the legacy plugin projection AND- * the connector table (agent-scoped connections live only in the latter).- * Disabled services are dropped from both lists β not surfaced as "connected,- * use directly" nor as "available to connect".- */-export const resolveComposioServicesVariable = async ({- agentId,- ctx,-}: ServerContextFactInput): Promise<string> => {- if (!ctx.serverDB || !ctx.userId || !composioEnv.COMPOSIO_API_KEY) return '';- try {- const connectedIds = await loadConnectedComposioIds(- ctx.serverDB,- ctx.userId,- ctx.workspaceId,- agentId,- );- let disabledIdSet = new Set<string>();- if (agentId) {- const agentConfig = await new AgentModel(- ctx.serverDB,- ctx.userId,- ctx.workspaceId,- ).getAgentConfigById(agentId);- disabledIdSet = new Set(getDisabledPluginIds(agentConfig?.plugins ?? undefined));- }- const connected: ComposioServiceSummary[] = excludeDisabledComposioServices(- COMPOSIO_APP_TYPES.filter((tool) => connectedIds.has(tool.identifier)),- disabledIdSet,- ).map((tool) => ({ identifier: tool.identifier, name: tool.label }));- const available = resolveAvailableComposioServices(- COMPOSIO_APP_TYPES,- connectedIds,- disabledIdSet,- );- log(- 'Fetched Composio services for {{COMPOSIO_SERVICES_LIST}}: connected=%d, available=%d',- connected.length,- available.length,- );- return generateComposioServicesList(connected, available);- } catch (error) {- log('Failed to fetch Composio services for {{COMPOSIO_SERVICES_LIST}} substitution: %O', error);- return '';- }-};diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/credsList.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/credsList.tsdeleted file mode 100644index 81c88dd2877..00000000000--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/credsList.ts+++ /dev/null@@ -1,55 +0,0 @@-import { type CredSummary, generateCredsList } from '@lobechat/builtin-tool-creds';--import { UserModel } from '@/database/models/user';-import { log } from '@/server/modules/AgentRuntime/executorHelpers';-import { MarketService } from '@/server/services/market';--import type { ServerContextFactInput } from './types';--/**- * `{{CREDS_LIST}}` β the credentials the model may inject into a sandbox.- * Inside a workspace, the agent must only see the workspace's shared- * organization credentials β personal creds are not visible there.- */-export const resolveCredsListVariable = async ({- ctx,-}: ServerContextFactInput): Promise<string> => {- if (!ctx.userId) return '';- try {- // Read market accessToken from DB so the server-side runtime can- // authenticate with the Market API instead of falling back to an- // anonymous trustedClientToken (which 401s on creds endpoints).- let marketAccessToken: string | undefined;- if (ctx.serverDB) {- try {- const settings = await new UserModel(ctx.serverDB, ctx.userId).getUserSettings();- marketAccessToken = (settings?.market as any)?.accessToken;- } catch {- // non-fatal β MarketService will fall back to trustedClientToken- }- }-- const marketService = new MarketService({- accessToken: marketAccessToken,- userInfo: { userId: ctx.userId },- });- const credsResult = ctx.workspaceId- ? await marketService.market.organizations.creds({ workspaceId: ctx.workspaceId }).list()- : await marketService.market.creds.list();- const userCreds = (credsResult as any)?.data ?? [];- log('Fetched %d creds for {{CREDS_LIST}} substitution', userCreds.length);- return generateCredsList(- userCreds.map((cred: any): CredSummary => ({- description: cred.description,- key: cred.key,- name: cred.name,- ownerDisplayName: cred.ownerDisplayName,- ownerType: cred.ownerType,- type: cred.type,- })),- );- } catch (error) {- log('Failed to fetch creds for {{CREDS_LIST}} substitution: %O', error);- return '';- }-};diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/groupAgentBuilderContext.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/groupAgentBuilderContext.tsdeleted file mode 100644index cd9f7b18fb8..00000000000--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/groupAgentBuilderContext.ts+++ /dev/null@@ -1,85 +0,0 @@-import type { GroupAgentBuilderContext } from '@lobechat/context-engine';-import { getActivePluginIds } from '@lobechat/types';--import { AgentModel } from '@/database/models/agent';-import { ChatGroupModel } from '@/database/models/chatGroup';-import { log } from '@/server/modules/AgentRuntime/executorHelpers';--import { listOfficialTools } from './officialTools';-import type { ServerContextFactInput } from './types';--/**- * The group currently being edited in the group Profile panel β mirrors the- * agent builder context. Without it the model has no idea which group it is- * editing, so it cannot address members by id (updateAgentPrompt) and falls- * back to telling the user to wire the group up by hand.- */-export const resolveGroupAgentBuilderContextFacts = async ({- ctx,- state,-}: ServerContextFactInput): Promise<GroupAgentBuilderContext | undefined> => {- const editingGroupId = state.metadata?.editingGroupId as string | undefined;- if (!editingGroupId || !ctx.serverDB || !ctx.userId) return undefined;- try {- const chatGroupModel = new ChatGroupModel(ctx.serverDB, ctx.userId, ctx.workspaceId);- const [group, roster] = await Promise.all([- chatGroupModel.findById(editingGroupId),- chatGroupModel.getGroupAgentsWithMeta(editingGroupId),- ]);- if (!group) return undefined;-- const supervisorAgentId = roster.find((member) => member.role === 'supervisor')?.agentId;-- let supervisorConfig: GroupAgentBuilderContext['supervisorConfig'];- let enabledPlugins: string[] = [];- if (supervisorAgentId) {- const supervisor = await new AgentModel(- ctx.serverDB,- ctx.userId,- ctx.workspaceId,- ).getAgentConfigById(supervisorAgentId);- if (supervisor) {- // Pinned identifiers only β `supervisorConfig.plugins` is a prompt- // formatting DTO and a disabled plugin isn't "enabled".- enabledPlugins = getActivePluginIds(- Array.isArray(supervisor.plugins) ? supervisor.plugins : undefined,- );- supervisorConfig = {- model: supervisor.model ?? undefined,- plugins: enabledPlugins,- provider: supervisor.provider ?? undefined,- };- }- }-- const officialTools = await listOfficialTools({- agentId: supervisorAgentId,- db: ctx.serverDB,- enabledPlugins,- label: 'groupAgentBuilderContext',- userId: ctx.userId,- workspaceId: ctx.workspaceId,- });-- return {- config: {- openingMessage: group.config?.openingMessage || undefined,- openingQuestions: group.config?.openingQuestions ?? undefined,- systemPrompt: group.content || undefined,- },- groupId: editingGroupId,- groupTitle: group.title || undefined,- members: roster.map((member) => ({- description: member.description ?? undefined,- id: member.agentId,- isSupervisor: member.role === 'supervisor',- title: member.title || 'Untitled Agent',- })),- officialTools,- supervisorConfig,- };- } catch (error) {- log('Failed to build groupAgentBuilderContext for group %s: %O', editingGroupId, error);- return undefined;- }-};diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/index.tsindex 5a821b0b07d..c92cc77d1ca 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts@@ -1,94 +1,311 @@-import pMap from 'p-map';--import { resolveAgentBuilderContextFacts } from './agentBuilderContext';-import { resolveAgentDocumentFacts } from './agentDocuments';-import { resolveComposioServicesVariable } from './composioServices';-import { resolveCredsListVariable } from './credsList';-import { resolveGroupAgentBuilderContextFacts } from './groupAgentBuilderContext';-import { resolveLobehubSkillVariables } from './lobehubSkillVariables';-import { resolveOnboardingContextFacts } from './onboardingContext';-import { resolvePlanTodoFacts } from './planTodo';-import { resolveSandboxVariables } from './sandboxVariables';-import { resolveTopicReferenceFacts } from './topicReferences';-import type { ServerContextFactInput } from './types';-import { resolveUserInfoVariables } from './userInfoVariables';-import { resolveWorkspaceContextFacts } from './workspaceContext';--export type { ServerContextFactInput } from './types';+import type { AgentState } from '@lobechat/agent-runtime';+import { formatWebOnboardingStateMessage } from '@lobechat/builtin-tool-web-onboarding/utils';+import { AGENT_PLAN_FILE_TYPE } from '@lobechat/const';+import type { ContextFactProviders, ContextFactRequest } from '@lobechat/mecha';+import { getActivePluginIds } from '@lobechat/types';-/**- * How many lookups run at once. Most providers hit Postgres through the same- * pool, and a few reach external services (market, Composio); capping the- * fan-out keeps one step from grabbing a dozen connections at once.- */-export const PROVIDER_CONCURRENCY = 8;+import { loadModels } from '@/business/client/model-bank/loadModels';+import { composioEnv } from '@/config/composio';+import { AgentModel } from '@/database/models/agent';+import { AiModelModel } from '@/database/models/aiModel';+import { ChatGroupModel } from '@/database/models/chatGroup';+import { FileModel } from '@/database/models/file';+import { MessageModel } from '@/database/models/message';+import { PluginModel } from '@/database/models/plugin';+import { TopicModel } from '@/database/models/topic';+import { TopicDocumentModel } from '@/database/models/topicDocument';+import { UserModel } from '@/database/models/user';+import { UserPersonaModel } from '@/database/models/userMemory/persona';+import { WorkspaceModel } from '@/database/models/workspace';+import { appEnv } from '@/envs/app';+import { loadConnectedComposioIds } from '@/server/modules/AgentRuntime/adapters/composioConnectedIds';+import type { RuntimeExecutorContext } from '@/server/modules/AgentRuntime/context';+import { buildPostProcessUrl, log } from '@/server/modules/AgentRuntime/executorHelpers';+import { AgentDocumentsService } from '@/server/services/agentDocuments';+import { MarketService } from '@/server/services/market';+import { OnboardingService } from '@/server/services/onboarding';+import { toAgentContextDocuments } from '@/utils/agentDocumentContextMapping';-type Settled<T extends readonly (() => Promise<unknown>)[]> = {- [K in keyof T]: Awaited<ReturnType<T[K]>>;-};+export interface ServerContextFactSource {+ ctx: RuntimeExecutorContext;+ state: AgentState;+}-/** `Promise.all` over thunks with a concurrency cap, keeping each position's type. */-const runBounded = <T extends readonly (() => Promise<unknown>)[]>(- tasks: T,- concurrency: number,-): Promise<Settled<T>> => pMap(tasks, (task) => task(), { concurrency }) as Promise<Settled<T>>;+/** Which connector families this deployment offers (mirrors the global config). */+export const resolveServerConnectorFeatures = (): ContextFactRequest['features'] => ({+ composio: !!composioEnv.COMPOSIO_API_KEY,+ lobehubSkill: !!(appEnv.MARKET_TRUSTED_CLIENT_SECRET && appEnv.MARKET_TRUSTED_CLIENT_ID),+});++const toIsoString = (value: Date | string | null | undefined): string =>+ value instanceof Date ? value.toISOString() : (value ?? '');++const getAppUrl = (): string | undefined => {+ try {+ return appEnv.APP_URL;+ } catch {+ return process.env.APP_URL;+ }+};/**- * Everything the server gathers per step for the context snapshot, grouped- * the way the snapshot consumes it. Each provider is independent and- * best-effort, so they run concurrently (bounded by- * {@link PROVIDER_CONCURRENCY}): a step pays for the slowest lookup, not the- * sum of them.+ * How the server fetches the facts the shared context rules ask for. Every+ * method is a plain lookup against the database, the market service or the+ * run's own tool set; which facts a turn needs, and what a share visitor may+ * see, is decided by `gatherContextFacts` in `@lobechat/mecha`.*/-export const gatherServerContextFacts = async (input: ServerContextFactInput) => {- const [- agentBuilderContext,- agentDocuments,- composioServicesList,- credsList,- groupAgentBuilderContext,- lobehubSkill,- onboardingContext,- planTodo,- sandbox,- topicReferences,- userInfo,- workspaceContext,- ] = await runBounded(- [- () => resolveAgentBuilderContextFacts(input),- () => resolveAgentDocumentFacts(input),- () => resolveComposioServicesVariable(input),- () => resolveCredsListVariable(input),- () => resolveGroupAgentBuilderContextFacts(input),- () => resolveLobehubSkillVariables(input),- () => resolveOnboardingContextFacts(input),- () => resolvePlanTodoFacts(input),- () => resolveSandboxVariables(input),- () => resolveTopicReferenceFacts(input),- () => resolveUserInfoVariables(input),- () => resolveWorkspaceContextFacts(input),- ] as const,- PROVIDER_CONCURRENCY,- );+export const createServerContextFactProviders = ({+ ctx,+ state,+}: ServerContextFactSource): ContextFactProviders => {+ const { serverDB, userId } = ctx;+ if (!serverDB || !userId) return {};+ const db = serverDB;+ const workspaceId = state.origin?.workspaceId ?? ctx.workspaceId;return {- agentDocuments,- step: {- agentBuilderContext,- groupAgentBuilderContext,- onboardingContext,- planTodo,- topicReferences,- workspaceContext,+ findTopic: async (topicId) => {+ const topic = await new TopicModel(db, userId, ctx.workspaceId).findById(topicId);+ if (!topic) return null;+ return {+ agentId: topic.agentId,+ groupId: topic.groupId,+ historySummary: topic.historySummary,+ id: topic.id,+ senderId: topic.senderId,+ title: topic.title,+ };+ },++ getAgentDefinition: async (agentId) => {+ const config = (await new AgentModel(db, userId, ctx.workspaceId).getAgentConfigById(+ agentId,+ )) as Record<string, any> | null;+ if (!config) return null;+ return {+ ...config,+ plugins: getActivePluginIds(Array.isArray(config.plugins) ? config.plugins : undefined),+ };},- variables: {- ...lobehubSkill,- ...sandbox,- COMPOSIO_SERVICES_LIST: composioServicesList,- CREDS_LIST: credsList,- language: userInfo.language,- username: userInfo.username,++ getGroup: async (groupId) => {+ const chatGroupModel = new ChatGroupModel(db, userId, ctx.workspaceId);+ const [group, roster] = await Promise.all([+ chatGroupModel.findById(groupId),+ chatGroupModel.getGroupAgentsWithMeta(groupId),+ ]);+ if (!group) return null;+ return {+ config: group.config,+ content: group.content,+ members: roster.map((member) => ({+ agentId: member.agentId,+ description: member.description,+ role: member.role === 'supervisor' ? 'supervisor' : 'participant',+ title: member.title,+ })),+ title: group.title,+ };+ },++ getOnboardingContext: async () => {+ const onboardingService = new OnboardingService(db, userId);+ const docService = new AgentDocumentsService(db, userId, workspaceId);+ const personaModel = new UserPersonaModel(db, userId);++ const [onboardingState, soulDoc, persona, userInfo] = await Promise.all([+ onboardingService.getState(),+ onboardingService+ .getInboxAgentId()+ .then((inboxAgentId) =>+ inboxAgentId ? docService.getDocumentByFilename(inboxAgentId, 'SOUL.md') : null,+ )+ .catch((error) => {+ log('Failed to fetch SOUL.md for onboarding context: %O', error);+ return null;+ }),+ personaModel.getLatestPersonaDocument().catch((error) => {+ log('Failed to fetch user persona for onboarding context: %O', error);+ return null;+ }),+ onboardingService.getInitialUserInfo().catch((error) => {+ log('Failed to fetch initial user info for onboarding context: %O', error);+ return undefined;+ }),+ ]);++ return {+ discoveryUserMessageCount: onboardingState.discoveryUserMessageCount,+ personaContent: persona?.persona ?? null,+ phaseGuidance: formatWebOnboardingStateMessage(onboardingState),+ remainingDiscoveryExchanges: onboardingState.remainingDiscoveryExchanges,+ soulContent: soulDoc?.content ?? null,+ userInfo,+ };+ },++ getPlanDocument: async (topicId) => {+ const [planDocument] = await new TopicDocumentModel(db, userId, workspaceId).findByTopicId(+ topicId,+ { type: AGENT_PLAN_FILE_TYPE },+ );+ 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 (targetUserId) => {+ const info = await UserModel.getInfoForAIGeneration(db, targetUserId ?? userId);+ return { language: info.responseLanguage, username: info.userName };+ },++ getWorkspaceContext: async (targetWorkspaceId) => {+ const appUrl = getAppUrl();+ if (!targetWorkspaceId) return { appUrl };+ const workspace = await new WorkspaceModel(db, userId).findById(targetWorkspaceId);+ if (!workspace?.slug)+ log('Workspace %s has no slug; skipping workspace context', targetWorkspaceId);+ return { appUrl, slug: workspace?.slug ?? undefined };+ },++ listAgentDocuments: async (agentId) => {+ const docs = await new AgentDocumentsService(+ db,+ userId,+ workspaceId,+ ).getAgentContextDocuments(agentId);+ return toAgentContextDocuments(docs);+ },++ // Connected = ACTIVE Composio connections across BOTH the legacy plugin+ // projection AND the connector table, plus the LobeHub skill providers+ // discovered for this run (their manifests are only fetched for connected+ // providers, so presence in the tool set is the connection).+ listConnectedConnectorIds: async (agentId) => {+ const connected = await loadConnectedComposioIds(db, userId, ctx.workspaceId, agentId);+ const sourceMap = state.operationToolSet?.sourceMap ?? state.toolSourceMap ?? {};+ for (const [identifier, source] of Object.entries(sourceMap)) {+ if (source === 'lobehubSkill') connected.add(identifier);+ }+ return connected;+ },++ listCredentials: async ({ workspaceId: scopeWorkspaceId }) => {+ // Read market accessToken from DB so the server-side runtime can+ // authenticate with the Market API instead of falling back to an+ // anonymous trustedClientToken (which 401s on creds endpoints).+ let marketAccessToken: string | undefined;+ try {+ const settings = await new UserModel(db, userId).getUserSettings();+ marketAccessToken = (settings?.market as any)?.accessToken;+ } catch {+ // non-fatal β MarketService will fall back to trustedClientToken+ }+ const marketService = new MarketService({+ accessToken: marketAccessToken,+ userInfo: { userId },+ });+ // Inside a workspace, the agent must only see the workspace's shared+ // organization credentials β personal creds are not visible there.+ const result = scopeWorkspaceId+ ? await marketService.market.organizations.creds({ workspaceId: scopeWorkspaceId }).list()+ : await marketService.market.creds.list();+ const creds = (result as any)?.data ?? [];+ log('Fetched %d creds for {{CREDS_LIST}} substitution', creds.length);+ return creds.map((cred: any) => ({+ description: cred.description,+ key: cred.key,+ name: cred.name,+ ownerDisplayName: cred.ownerDisplayName,+ ownerType: cred.ownerType,+ type: cred.type,+ }));+ },++ // Custom MCP connectors the user installed, beyond the shared catalog.+ // Read from the installed-plugins table: the run's tool source map only+ // classifies skill / Composio / client tools, so it cannot tell a custom+ // connector apart, and a connector the agent has not pinned yet must+ // still be offered to createAgent / updateAgent.+ listCustomPlugins: async () => {+ const installed = await new PluginModel(db, userId, ctx.workspaceId).query();+ return installed+ .filter((plugin) => plugin.type === 'customPlugin')+ .map((plugin) => ({+ description: plugin.manifest?.meta?.description,+ identifier: plugin.identifier,+ name: plugin.manifest?.meta?.title || plugin.identifier,+ type: 'custom' as const,+ }));+ },++ listEnabledProviders: async () => {+ const [allUserModels, builtinModels] = await Promise.all([+ new AiModelModel(db, userId).getAllModels(),+ loadModels(),+ ]);+ const providerMap = new Map<+ string,+ {+ id: string;+ models: { abilities?: any; description?: string; id: string; name: string }[];+ name: string;+ }+ >();+ for (const userModel of allUserModels) {+ if (!userModel.enabled || userModel.type !== 'chat') continue;+ const modelInfo = builtinModels.find(+ (m) => m.id === userModel.id && m.providerId === userModel.providerId,+ );+ if (!providerMap.has(userModel.providerId)) {+ providerMap.set(userModel.providerId, {+ id: userModel.providerId,+ models: [],+ name: userModel.providerId,+ });+ }+ providerMap.get(userModel.providerId)!.models.push({+ abilities: userModel.abilities || modelInfo?.abilities,+ description: modelInfo?.description,+ id: userModel.id,+ name: userModel.displayName || modelInfo?.displayName || userModel.id,+ });+ }+ return [...providerMap.values()];+ },++ listRecentAgents: async (limit) =>+ (await new AgentModel(db, userId, ctx.workspaceId).queryAgents({ limit })).map((a) => ({+ description: a.description,+ id: a.id,+ title: a.title,+ })),++ listSandboxFiles: async (topicId) =>+ new FileModel(db, userId).findFilesToInitInSandbox(topicId),++ listTopicMessages: async (topic) => {+ const messages = await new MessageModel(db, userId, ctx.workspaceId).query(+ {+ agentId: topic.agentId ?? undefined,+ groupId: topic.groupId ?? undefined,+ topicId: topic.id,+ },+ // The shared rules already proved a visitor may see this topic, so+ // the creator-facing agent-share exclusion must not apply here.+ { allowShareVisitor: true, postProcessUrl: buildPostProcessUrl(ctx) },+ );+ return messages.map((message) => ({+ content: typeof message.content === 'string' ? message.content : '',+ role: message.role,+ }));},};};diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/lobehubSkillVariables.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/lobehubSkillVariables.tsdeleted file mode 100644index d660bec5c62..00000000000--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/lobehubSkillVariables.ts+++ /dev/null@@ -1,38 +0,0 @@-import { TopicModel } from '@/database/models/topic';-import { log } from '@/server/modules/AgentRuntime/executorHelpers';--import type { ServerContextFactInput } from './types';--/**- * Placeholders for the LobeHub builtin skill- * (`packages/builtin-skills/src/lobehub/content.ts`) so it can render- * `{{agent_id}}` / `{{agent_title}}` / `{{topic_id}}` etc. into the model's- * prompt without a separate context injector. The topic title is read fresh- * each step because auto-titling can rename the topic mid-run.- */-export const resolveLobehubSkillVariables = async ({- agentId,- ctx,- state,- topicId,-}: ServerContextFactInput): Promise<Record<string, string>> => {- let topicTitle = '';- if (topicId && ctx.serverDB && ctx.userId) {- try {- const topic = await new TopicModel(ctx.serverDB, ctx.userId, ctx.workspaceId).findById(- topicId,- );- topicTitle = topic?.title ?? '';- } catch (error) {- log('Failed to load topic title for lobehub skill placeholders: %O', error);- }- }-- return {- agent_description: state.world?.agent?.description ?? '',- agent_id: agentId ?? '',- agent_title: state.world?.agent?.title ?? '',- topic_id: topicId ?? '',- topic_title: topicTitle,- };-};diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/officialTools.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/officialTools.tsdeleted file mode 100644index cd7d8e3e490..00000000000--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/officialTools.ts+++ /dev/null@@ -1,61 +0,0 @@-import { builtinTools } from '@lobechat/builtin-tools';-import { COMPOSIO_APP_TYPES } from '@lobechat/const';-import type { OfficialToolItem } from '@lobechat/context-engine';-import type { LobeChatDatabase } from '@lobechat/database';--import { composioEnv } from '@/config/composio';-import { loadConnectedComposioIds } from '@/server/modules/AgentRuntime/adapters/composioConnectedIds';-import { log } from '@/server/modules/AgentRuntime/executorHelpers';--/**- * The official tool catalog as an agent / group builder prompt lists it:- * every visible builtin, then (when Composio is configured) every Composio- * service with its connection status for the given agent. Agent-scoped- * connections aren't in the plugin table β the connector table is unioned so- * the builder marks them installed too.- */-export const listOfficialTools = async (params: {- agentId?: string;- db: LobeChatDatabase;- enabledPlugins: string[];- label: string;- userId: string;- workspaceId?: string;-}): Promise<OfficialToolItem[]> => {- const { agentId, db, enabledPlugins, label, userId, workspaceId } = params;- const composioIdentifiers = new Set(COMPOSIO_APP_TYPES.map((tool) => tool.identifier));- const officialTools: OfficialToolItem[] = [];-- for (const tool of builtinTools) {- if (tool.hidden) continue;- if (composioIdentifiers.has(tool.identifier)) continue;- officialTools.push({- description: tool.manifest?.meta?.description,- enabled: enabledPlugins.includes(tool.identifier),- identifier: tool.identifier,- installed: true,- name: tool.manifest?.meta?.title || tool.identifier,- type: 'builtin',- });- }-- if (composioEnv.COMPOSIO_API_KEY) {- try {- const connectedComposioIds = await loadConnectedComposioIds(db, userId, workspaceId, agentId);- for (const tool of COMPOSIO_APP_TYPES) {- officialTools.push({- description: `LobeHub Mcp Server: ${tool.label}`,- enabled: enabledPlugins.includes(tool.identifier),- identifier: tool.identifier,- installed: connectedComposioIds.has(tool.identifier),- name: tool.label,- type: 'composio',- });- }- } catch (composioError) {- log('Failed to load Composio status for %s: %O', label, composioError);- }- }-- return officialTools;-};diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/onboardingContext.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/onboardingContext.tsdeleted file mode 100644index fa884842383..00000000000--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/onboardingContext.ts+++ /dev/null@@ -1,85 +0,0 @@-import { formatWebOnboardingStateMessage } from '@lobechat/builtin-tool-web-onboarding/utils';-import type { OnboardingContext } from '@lobechat/context-engine';--import { UserPersonaModel } from '@/database/models/userMemory/persona';-import { log } from '@/server/modules/AgentRuntime/executorHelpers';-import { AgentDocumentsService } from '@/server/services/agentDocuments';-import { OnboardingService } from '@/server/services/onboarding';--import type { ServerContextFactInput } from './types';--/**- * Persona, SOUL document and initial user info for the onboarding agent.- *- * Personal profile data with no share permission that could ever grant it, so- * a share visitor run never builds it. Two paths reach here: the builtin- * `web-onboarding` agent, and any shared agent whose enabled tools include- * `lobe-web-onboarding`. Gating on `ctx.agentShareVisitor` closes both.- */-export const resolveOnboardingContextFacts = async ({- agentId,- ctx,- enabledToolIds,- messagesForContext,- state,- workspaceId,-}: ServerContextFactInput): Promise<OnboardingContext | undefined> => {- const isOnboardingAgent =- state.world?.agent?.slug === 'web-onboarding' || enabledToolIds.includes('lobe-web-onboarding');- if (!isOnboardingAgent || ctx.agentShareVisitor || !ctx.serverDB || !ctx.userId) {- return undefined;- }-- const alreadyHasOnboardingContext = (- messagesForContext as Array<{ content: string | unknown }>- ).some((message) => {- if (typeof message.content !== 'string') return false;-- return (- message.content.includes('<onboarding_context>') ||- message.content.includes('<current_soul_document>') ||- message.content.includes('<current_user_persona>')- );- });- if (alreadyHasOnboardingContext) return undefined;-- try {- const onboardingService = new OnboardingService(ctx.serverDB, ctx.userId);- const docService = new AgentDocumentsService(ctx.serverDB, ctx.userId, workspaceId);- const personaModel = new UserPersonaModel(ctx.serverDB, ctx.userId);-- const [onboardingState, soulDoc, persona, userInfo] = await Promise.all([- onboardingService.getState(),- onboardingService- .getInboxAgentId()- .then((inboxAgentId) =>- inboxAgentId ? docService.getDocumentByFilename(inboxAgentId, 'SOUL.md') : null,- )- .catch((error) => {- log('Failed to fetch SOUL.md for onboarding context: %O', error);- return null;- }),- personaModel.getLatestPersonaDocument().catch((error) => {- log('Failed to fetch user persona for onboarding context: %O', error);- return null;- }),- onboardingService.getInitialUserInfo().catch((error) => {- log('Failed to fetch initial user info for onboarding context: %O', error);- return undefined;- }),- ]);-- log('Built onboarding context for agent %s, phase: %s', agentId, onboardingState.phase);- return {- discoveryUserMessageCount: onboardingState.discoveryUserMessageCount,- personaContent: persona?.persona ?? null,- phaseGuidance: formatWebOnboardingStateMessage(onboardingState),- remainingDiscoveryExchanges: onboardingState.remainingDiscoveryExchanges,- soulContent: soulDoc?.content ?? null,- userInfo,- };- } catch (error) {- log('Failed to build onboarding context: %O', error);- return undefined;- }-};diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/planTodo.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/planTodo.tsdeleted file mode 100644index 20d5d7a4481..00000000000--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/planTodo.ts+++ /dev/null@@ -1,44 +0,0 @@-import { extractTodosFromMessages, normalizeTodosState } from '@lobechat/agent-runtime';-import { AGENT_PLAN_FILE_TYPE } from '@lobechat/const';-import type { PlanTodoConfig } from '@lobechat/context-engine';--import { TopicDocumentModel } from '@/database/models/topicDocument';-import { log } from '@/server/modules/AgentRuntime/executorHelpers';--import type { ServerContextFactInput } from './types';--/**- * The current TODO state. Message history is the source of truth; the plan- * document is only a best-effort mirror consulted when history carries no- * TODO state yet and the run has `lobe-agent`.- */-export const resolvePlanTodoFacts = async ({- ctx,- enabledToolIds,- messagesForContext,- topicId,- workspaceId,-}: ServerContextFactInput): Promise<PlanTodoConfig | undefined> => {- const messageTodos = extractTodosFromMessages(messagesForContext);- if (messageTodos !== undefined) return { enabled: true, todos: messageTodos };-- if (!enabledToolIds.includes('lobe-agent') || !topicId || !ctx.serverDB || !ctx.userId) {- return undefined;- }- try {- const [planDocument] = await new TopicDocumentModel(- ctx.serverDB,- ctx.userId,- workspaceId,- ).findByTopicId(topicId, { type: AGENT_PLAN_FILE_TYPE });- if (!planDocument) return undefined;- const todos = normalizeTodosState(- planDocument.metadata?.todos,- planDocument.updatedAt.toISOString(),- );- return todos === undefined ? undefined : { enabled: true, todos };- } catch (error) {- log('Failed to resolve plan TODO context for topic %s: %O', topicId, error);- return undefined;- }-};diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/sandboxVariables.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/sandboxVariables.tsdeleted file mode 100644index 71773a3e8b1..00000000000--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/sandboxVariables.ts+++ /dev/null@@ -1,52 +0,0 @@-import { formatUploadedFilesPrompt } from '@lobechat/builtin-tool-cloud-sandbox';--import { FileModel } from '@/database/models/file';-import { log } from '@/server/modules/AgentRuntime/executorHelpers';--import type { ServerContextFactInput } from './types';--export interface SandboxVariables {- creds_sandbox_reachable: string;- sandbox_enabled: string;- sandbox_uploaded_files: string;-}--/**- * Cloud-sandbox placeholders.- *- * `sandbox_enabled` tracks whether the dedicated Cloud Sandbox tool is- * offered β true for target 'sandbox', and (so the model can choose sandbox- * vs. an auto-routed device per call) for 'auto' too, regardless of whether a- * device ended up routed. It's still not the full answer for- * `injectCredsToSandbox` reachability: `lobe-skills`' `runCommand` /- * `execScript` ALSO silently fall back to that same cloud sandbox session- * whenever no device is actively routed, for targets where the dedicated tool- * isn't offered at all (e.g. the common no-device 'none' web/agent session).- * So a credential is reachable whenever EITHER condition holds: the dedicated- * tool is exposed for 'auto' (independent of device routing), or no device is- * routed (independent of target).- */-export const resolveSandboxVariables = async ({- activeDeviceId,- ctx,- enabledToolIds,- executionTarget,- topicId,-}: ServerContextFactInput): Promise<SandboxVariables> => {- const sandboxEnabled = enabledToolIds.includes('lobe-cloud-sandbox');- let uploadedFiles = '';- if (sandboxEnabled && ctx.serverDB && ctx.userId && topicId) {- try {- const files = await new FileModel(ctx.serverDB, ctx.userId).findFilesToInitInSandbox(topicId);- uploadedFiles = formatUploadedFilesPrompt(files);- } catch (error) {- log('Failed to resolve files for {{sandbox_uploaded_files}} substitution: %O', error);- }- }-- return {- creds_sandbox_reachable: String(!activeDeviceId || executionTarget === 'auto'),- sandbox_enabled: String(sandboxEnabled),- sandbox_uploaded_files: uploadedFiles,- };-};diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.tsnew file mode 100644index 00000000000..c02c1862949--- /dev/null+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/serverContextFactProviders.test.ts@@ -0,0 +1,114 @@+import { describe, expect, it, vi } from 'vitest';++import { createServerContextFactProviders } from './index';++const { findById, getInfoForAIGeneration, loadConnectedComposioIds, pluginQuery } = vi.hoisted(+ () => ({+ findById: vi.fn(),+ getInfoForAIGeneration: vi.fn(),+ loadConnectedComposioIds: vi.fn(),+ pluginQuery: vi.fn(),+ }),+);++vi.mock('@/database/models/user', () => ({+ UserModel: Object.assign(+ class {+ getUserSettings = vi.fn();+ },+ { getInfoForAIGeneration },+ ),+}));+vi.mock('@/database/models/plugin', () => ({+ PluginModel: class {+ query = pluginQuery;+ },+}));+vi.mock('@/database/models/workspace', () => ({+ WorkspaceModel: class {+ findById = findById;+ },+}));+vi.mock('@/server/modules/AgentRuntime/adapters/composioConnectedIds', () => ({+ loadConnectedComposioIds,+}));+vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'https://app.test' } }));++const source = (state: Record<string, unknown> = {}) => ({+ ctx: { serverDB: {}, userId: 'owner-1', workspaceId: 'ws-1' } as never,+ state: state as never,+});++describe('createServerContextFactProviders', () => {+ it('answers nothing without a database or user', () => {+ expect(createServerContextFactProviders({ ctx: {} as never, state: {} as never })).toEqual({});+ });++ it('reads user info for the user the rules name, defaulting to the run owner', async () => {+ getInfoForAIGeneration.mockResolvedValue({ responseLanguage: 'ja-JP', userName: 'v' });+ const providers = createServerContextFactProviders(source());++ await expect(providers.getUserInfo!('visitor-1')).resolves.toEqual({+ language: 'ja-JP',+ username: 'v',+ });+ expect(getInfoForAIGeneration).toHaveBeenLastCalledWith(expect.anything(), 'visitor-1');++ await providers.getUserInfo!(undefined);+ expect(getInfoForAIGeneration).toHaveBeenLastCalledWith(expect.anything(), 'owner-1');+ });++ it('unions connected Composio services with the runβs LobeHub skill providers', async () => {+ loadConnectedComposioIds.mockResolvedValue(new Set(['gmail']));+ const providers = createServerContextFactProviders(+ source({+ operationToolSet: {+ sourceMap: {+ 'gmail': 'composio',+ 'lobehub-skill-x': 'lobehubSkill',+ 'weather': 'builtin',+ },+ },+ }),+ );++ const ids = new Set(await providers.listConnectedConnectorIds!('agt_1'));+ expect(ids).toEqual(new Set(['gmail', 'lobehub-skill-x']));+ });++ it('offers every installed custom MCP connector, pinned or not, and nothing else', async () => {+ pluginQuery.mockResolvedValue([+ {+ identifier: 'my-mcp',+ manifest: { meta: { description: 'Local files', title: 'My MCP' } },+ type: 'customPlugin',+ },+ { identifier: 'market-plugin', manifest: { meta: { title: 'Market' } }, type: 'plugin' },+ ]);++ await expect(+ createServerContextFactProviders(source({ operationToolSet: { sourceMap: {} } }))+ .listCustomPlugins!(),+ ).resolves.toEqual([+ { description: 'Local files', identifier: 'my-mcp', name: 'My MCP', type: 'custom' },+ ]);+ });++ it('returns the app origin and the workspace slug when it resolves', async () => {+ findById.mockResolvedValue({ slug: 'team' });+ const providers = createServerContextFactProviders(source());++ await expect(providers.getWorkspaceContext!(undefined)).resolves.toEqual({+ appUrl: 'https://app.test',+ });+ await expect(providers.getWorkspaceContext!('ws-1')).resolves.toEqual({+ appUrl: 'https://app.test',+ slug: 'team',+ });+ findById.mockResolvedValue({ slug: null });+ await expect(providers.getWorkspaceContext!('ws-1')).resolves.toEqual({+ appUrl: 'https://app.test',+ slug: undefined,+ });+ });+});diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/topicReferences.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/topicReferences.tsdeleted file mode 100644index 8c32f6e2b76..00000000000--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/topicReferences.ts+++ /dev/null@@ -1,74 +0,0 @@-import { resolveTopicReferences, type TopicReferenceItem } from '@lobechat/context-engine';--import { MessageModel } from '@/database/models/message';-import { TopicModel } from '@/database/models/topic';-import { buildPostProcessUrl } from '@/server/modules/AgentRuntime/executorHelpers';--import type { ServerContextFactInput } from './types';--/**- * Summaries for the topics a `<refer_topic>` tag points at. Skipped when the- * messages already carry an injected `topic_reference_context` (client-side- * preprocessing) to avoid double injection.- */-export const resolveTopicReferenceFacts = async ({- ctx,- messagesForContext,-}: ServerContextFactInput): Promise<TopicReferenceItem[] | undefined> => {- const alreadyHasTopicRefs = (messagesForContext as Array<{ content: string | unknown }>).some(- (message) =>- typeof message.content === 'string' && message.content.includes('topic_reference_context'),- );- if (alreadyHasTopicRefs || !ctx.serverDB || !ctx.userId) return undefined;-- const topicModel = new TopicModel(ctx.serverDB, ctx.userId, ctx.workspaceId);- const messageModel = new MessageModel(ctx.serverDB, ctx.userId, ctx.workspaceId);- const agentShareVisitor = ctx.agentShareVisitor;- // Topic references are limited to the visitor's own topics in shared runs.- // `TopicModel`'s built-in ownership scoping is not sufficient here β the- // rows are owned by the CREATOR, so every one of the creator's private- // topics would otherwise be addressable by a `<refer_topic>` tag the- // visitor typed. Match the visitor/agent pairing of the active share- // instead: a visitor topic is tied to its share purely through- // `(agentId, senderId)`, since `agent_shares` is 1:1 per agent.- //- // Known gap: a topic created before the owner paused the share still- // matches `(agentId, senderId)` for a returning visitor, because topics- // carry no share-instance column. Such a topic is the SAME visitor's own- // prior conversation with the SAME agent, so this leaks nothing across- // identities β it only means old context can resurface once the share is- // turned back on.- const isTopicVisibleToRun = (- topic: { agentId?: string | null; senderId?: string | null } | null | undefined,- ): boolean => {- if (!agentShareVisitor) return true;- return (- topic?.senderId === agentShareVisitor.visitorUserId &&- topic?.agentId === agentShareVisitor.agentId- );- };-- return resolveTopicReferences(- messagesForContext as Array<{ content: string | unknown }>,- async (topicId) => {- const topic = await topicModel.findById(topicId);- return isTopicVisibleToRun(topic) ? topic : null;- },- async (topicId) => {- const topic = await topicModel.findById(topicId);- if (!isTopicVisibleToRun(topic)) return [];-- return messageModel.query(- {- agentId: topic?.agentId ?? undefined,- groupId: topic?.groupId ?? undefined,- topicId,- },- // `isTopicVisibleToRun` above already proved this referenced topic is- // the SAME visitor's own conversation with the SAME agent, so the- // creator-facing agent-share exclusion must not apply here.- { allowShareVisitor: true, postProcessUrl: buildPostProcessUrl(ctx) },- );- },- );-};diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/types.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/types.tsdeleted file mode 100644index 3c6fa4b03c1..00000000000--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/types.ts+++ /dev/null@@ -1,31 +0,0 @@-import type { AgentState } from '@lobechat/agent-runtime';-import type { UIChatMessage } from '@lobechat/types';--import type { RuntimeExecutorContext } from '@/server/modules/AgentRuntime/context';--/**- * What every server-side fact provider may read.- *- * Providers turn the run's state plus the server's data sources into one fact- * for the context snapshot. They are independent of each other, best-effort- * (a failed lookup logs and yields `undefined`, never blocks the LLM call) and- * run concurrently, so none may depend on another's result.- */-export interface ServerContextFactInput {- /** Device routed for this step, if any (single-track device gate applied). */- activeDeviceId?: string;- /** Executing agent row id (`origin.agentId`). */- agentId?: string;- ctx: RuntimeExecutorContext;- /** Tool ids enabled for this step, after resolution. */- enabledToolIds: string[];- /** Effective execution target off the plan, when resolved. */- executionTarget?: string;- /** Conversation as the engine will see it (history hints already applied). */- messagesForContext: UIChatMessage[];- state: AgentState;- /** Topic the turn belongs to (`ctx.topicId` wins over `origin.topicId`). */- topicId?: string;- /** Workspace scoping for DB models (`origin.workspaceId` wins over `ctx.workspaceId`). */- workspaceId?: string;-}diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/userInfoVariables.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/userInfoVariables.tsdeleted file mode 100644index a8a03fdf1bb..00000000000--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/userInfoVariables.ts+++ /dev/null@@ -1,30 +0,0 @@-import { UserModel } from '@/database/models/user';-import { log } from '@/server/modules/AgentRuntime/executorHelpers';--import type { ServerContextFactInput } from './types';--export interface UserInfoVariables {- language: string;- username: string;-}--/**- * `{{username}}` / `{{language}}` render back to whoever is actually- * conversing. In a share-visitor run `ctx.userId` is the CREATOR (the agent- * still executes under their identity), so resolving from it would leak the- * creator's own name / locale into a link visitor's turn. Resolve from the- * visitor's own user id instead whenever this is a share-visitor run.- */-export const resolveUserInfoVariables = async ({- ctx,-}: ServerContextFactInput): Promise<UserInfoVariables> => {- const userInfoUserId = ctx.agentShareVisitor?.visitorUserId ?? ctx.userId;- if (!ctx.serverDB || !userInfoUserId) return { language: '', username: '' };- try {- const userInfo = await UserModel.getInfoForAIGeneration(ctx.serverDB, userInfoUserId);- return { language: userInfo.responseLanguage, username: userInfo.userName };- } catch (error) {- log('Failed to fetch user info for {{username}}/{{language}} substitution: %O', error);- return { language: '', username: '' };- }-};diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/workspaceContext.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/workspaceContext.tsdeleted file mode 100644index ca45a725380..00000000000--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/workspaceContext.ts+++ /dev/null@@ -1,54 +0,0 @@-import type { WorkspaceContext } from '@lobechat/context-engine';--import { WorkspaceModel } from '@/database/models/workspace';-import { appEnv } from '@/envs/app';-import { log } from '@/server/modules/AgentRuntime/executorHelpers';--import type { ServerContextFactInput } from './types';--const getAppUrl = (): string | undefined => {- try {- return appEnv.APP_URL;- } catch {- return process.env.APP_URL;- }-};--/**- * Where the run lives β app origin + workspace slug β so the model can write- * in-app links that resolve to the right scope. Without this the model has no- * idea it is inside a team workspace and composes personal-space (or- * training-data) URLs. Best-effort: a failed lookup skips the block.- */-export const resolveWorkspaceContextFacts = async ({- ctx,- workspaceId,-}: ServerContextFactInput): Promise<WorkspaceContext | undefined> => {- // A share visitor converses under the CREATOR's identity: the creator's- // routes (workspace or personal) are not the visitor's, so never describe- // that scope to them β skip the block entirely, whatever the run's scope.- if (ctx.agentShareVisitor) return undefined;-- const appUrl = getAppUrl();-- // Personal space: the origin alone is enough to anchor links.- if (!workspaceId) return appUrl ? { appUrl } : undefined;-- // Workspace run whose slug cannot be resolved: injecting origin-only would- // wrongly tell the model it is in the personal space, so inject nothing- // (the pre-fix behaviour) rather than a false statement.- if (!ctx.serverDB || !ctx.userId) return undefined;-- try {- const workspace = await new WorkspaceModel(ctx.serverDB, ctx.userId).findById(workspaceId);- if (!workspace?.slug) {- log('Workspace %s has no slug; skipping workspace context', workspaceId);- return undefined;- }-- return { appUrl, workspace: { slug: workspace.slug } };- } catch (error) {- log('Failed to resolve workspace context for %s: %O', workspaceId, error);- return undefined;- }-};diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex 53c3483396b..ccf138df921 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -885,6 +885,7 @@ export class AgentRuntimeService {maxSteps,userMemory,deviceSystemInfo,+ disabledPluginIds,operationSkillSet,parentOperationId,signal,@@ -1074,6 +1075,7 @@ export class AgentRuntimeService {channel: { botPlatform: botPlatformContext, discord: discordContext },}),connectorOwnershipNote,+ disabledPluginIds,eval: evalContext,group: agentGroup,projectInstructions,diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.tsindex f1534e3a213..41245b8a0d4 100644--- a/apps/server/src/services/agentRuntime/types.ts+++ b/apps/server/src/services/agentRuntime/types.ts@@ -487,6 +487,8 @@ export interface OperationCreationParams {deviceAccessPolicy?: { canUseDevice: boolean; reason: DeviceAccessReason };/** Device system info for placeholder variable replacement in Local System systemRole */deviceSystemInfo?: Record<string, string>;+ /** Tri-state disabled plugin identifiers, kept on `state.world` for the context rules. */+ disabledPluginIds?: string[];/** Discord context for injecting channel/guild info into agent system message */discordContext?: any;/** Whether ContextEngine may inject the operation expertise snapshot. */diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex c1d1a998283..c99068b499b 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -1325,6 +1325,7 @@ export class AiAgentService {botContext,botPlatformContext,clientIp,+ disabledPluginIds,discordContext,discovery,enableExpertise,diff --git a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts b/apps/server/src/services/aiAgent/pipeline/operationPrep.tsindex 9515a5f2edc..1458d29a952 100644--- a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts+++ b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts@@ -2,8 +2,7 @@ import type { AgentRuntimeContext } from '@lobechat/agent-runtime';import { extractActivatedToolIdsFromMessages } from '@lobechat/agent-runtime';import { builtinSkills } from '@lobechat/builtin-skills';import { getShellSyntaxGuidance } from '@lobechat/builtin-tool-local-system';-import { builtinTools } from '@lobechat/builtin-tools';-import type { AgentManagementContext, ProjectInstructionFile } from '@lobechat/context-engine';+import type { ProjectInstructionFile } from '@lobechat/context-engine';import { buildExpertiseContextSnapshot, SkillEngine } from '@lobechat/context-engine';import type { LobeChatDatabase } from '@lobechat/database';import { buildTaskManagerDefaultsPrompt, resourcesTreePrompt } from '@lobechat/prompts';@@ -17,7 +16,6 @@ import debug from 'debug';import type { AgentModel } from '@/database/models/agent';import { AgentSkillModel } from '@/database/models/agentSkill';-import { AiModelModel } from '@/database/models/aiModel';import { DeviceModel } from '@/database/models/device';import { ExpertiseModel } from '@/database/models/expertise';import { GoalGraphModel } from '@/database/models/goalGraph';@@ -443,156 +441,9 @@ export const prepareOperation = async (const deviceSystemInfo = await fetchDeviceSystemInfoForTemplate(activeDeviceId);- // 9.5. Build Agent Management context- // - availableAgents is injected whenever the user is in auto 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.- const isAgentManagementEnabled = toolsResult.enabledToolIds?.includes('lobe-agent-management');- const isInAutoSkillMode = agentConfig.chatConfig?.skillActivateMode !== 'manual';- const shouldInjectAvailableAgents = isInAutoSkillMode || isAgentManagementEnabled;- let agentManagementContext: AgentManagementContext | undefined;-- if (shouldInjectAvailableAgents) {- // Query user's most recently updated agents.- // Over-fetch by 2: +1 reserved for the current agent (filtered out below- // so the model has no exposure to its own id and cannot self-delegate)- // and +1 to detect overflow for the `hasMore` flag.- const AVAILABLE_AGENTS_LIMIT = 10;- const recentAgents = await deps.agentModel.queryAgents({- limit: AVAILABLE_AGENTS_LIMIT + 2,- });-- // Exclude the current agent from `availableAgents` β the model is the current- // agent. Its persona/identity 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 can't- // accidentally call itself via `callAgent`).- const otherAgents = recentAgents.filter((a) => a.id !== resolvedAgentId);- const hasMoreAgents = otherAgents.length > AVAILABLE_AGENTS_LIMIT;- const availableAgents = otherAgents.slice(0, AVAILABLE_AGENTS_LIMIT).map((a) => ({- description: a.description ?? undefined,- id: a.id,- title: a.title ?? 'Untitled',- }));-- agentManagementContext = {- availableAgents,- availableAgentsHasMore: hasMoreAgents,- ...(resolvedAgentId && {- currentAgent: {- id: resolvedAgentId,- title: agentConfig.title ?? undefined,- },- }),- };- }-- if (isAgentManagementEnabled) {- // Query user's enabled models from database- const aiModelModel = new AiModelModel(deps.db, deps.userId);- const allUserModels = await aiModelModel.getAllModels();-- // Filter only enabled chat models and group by provider- const providerMap = new Map<- string,- {- id: string;- models: Array<{ abilities?: any; description?: string; id: string; name: string }>;- name: string;- }- >();-- for (const userModel of allUserModels) {- // Only include enabled chat models- if (!userModel.enabled || userModel.type !== 'chat') continue;-- // Get model info from builtin metadata for full metadata.- const modelInfo = builtinModels.find(- (m) => m.id === userModel.id && m.providerId === userModel.providerId,- );-- if (!providerMap.has(userModel.providerId)) {- providerMap.set(userModel.providerId, {- id: userModel.providerId,- models: [],- name: userModel.providerId, // TODO: Map to friendly provider name- });- }-- const modelProvider = providerMap.get(userModel.providerId)!;- modelProvider.models.push({- abilities: userModel.abilities || modelInfo?.abilities,- description: modelInfo?.description,- id: userModel.id,- name: userModel.displayName || modelInfo?.displayName || userModel.id,- });- }-- // Build availablePlugins from all plugin sources- // Exclude only truly internal tools (agent-management itself, agent-builder, page-agent)- 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- ]);-- const availablePlugins = [- // All builtin tools (including hidden ones like web-browsing, cloud-sandbox)- ...builtinTools- .filter((tool) => !INTERNAL_TOOLS.has(tool.identifier))- .map((tool) => ({- description: tool.manifest.meta?.description,- identifier: tool.identifier,- name: tool.manifest.meta?.title || tool.identifier,- type: 'builtin' as const,- })),- // Lobehub Skills- ...lobehubSkillManifests.map((manifest) => ({- description: manifest.meta?.description,- identifier: manifest.identifier,- name: manifest.meta?.title || manifest.identifier,- type: 'lobehub-skill' as const,- })),- // Composio tools- ...composioManifests.map((manifest) => ({- description: manifest.meta?.description,- identifier: manifest.identifier,- name: manifest.meta?.title || manifest.identifier,- type: 'composio' as const,- })),- // Custom connectors (user-added MCP servers)- ...connectorManifests.map((manifest) => ({- description: manifest.meta?.description,- identifier: manifest.identifier,- name: manifest.meta?.title || manifest.identifier,- type: 'custom' as const,- })),- ];-- // Merge models / plugins into the (already-initialized) agentManagementContext.- // availableAgents was populated above by `shouldInjectAvailableAgents`, which is- // always true when isAgentManagementEnabled.- agentManagementContext = {- ...agentManagementContext!,- availablePlugins,- // Limit to first 5 providers to avoid context bloat- availableProviders: Array.from(providerMap.values()).slice(0, 5),- };-- log(- 'execAgent: built agentManagementContext with %d providers, %d plugins, %d agents',- agentManagementContext.availableProviders!.length,- agentManagementContext.availablePlugins!.length,- agentManagementContext.availableAgents?.length ?? 0,- );- } else if (agentManagementContext) {- log(- 'execAgent: injected availableAgents only (auto mode, agent-management tool not enabled): %d agents',- agentManagementContext.availableAgents?.length ?? 0,- );- }+ // 9.5. The agent-management context (available agents / providers / plugins)+ // is gathered per step by the shared context rules (`@lobechat/mecha`),+ // together with the @-mentioned agents persisted on `initialContext` below.await throwIfExecutionAborted('tool preparation');@@ -800,8 +651,8 @@ export const prepareOperation = async (// Persist the @-mentioned agents into the runtime initialContext so the// context engine injects the delegation context on every step (survives the- // queue-mode dispatch). `callLlm` bridges this into `agentManagementContext`- // for the AgentManagementContextInjector β mirrors the client runtime.+ // queue-mode dispatch). The shared context rules fold them into the+ // agent-management context on every step β mirrors the client runtime.if (hasMentionedAgents) {initialContext = {...initialContext,diff --git a/apps/server/src/services/aiAgent/pipeline/startOperation.ts b/apps/server/src/services/aiAgent/pipeline/startOperation.tsindex 8aca9e206f8..44c5b6f4275 100644--- a/apps/server/src/services/aiAgent/pipeline/startOperation.ts+++ b/apps/server/src/services/aiAgent/pipeline/startOperation.ts@@ -32,6 +32,8 @@ export interface StartOperationInput {botContext?: InternalExecAgentParams['botContext'];botPlatformContext?: InternalExecAgentParams['botPlatformContext'];clientIp?: string;+ /** Tri-state disabled plugin identifiers, kept on the world slot for the context rules. */+ disabledPluginIds?: string[];discordContext?: any;discovery: ToolDiscoveryResult;enableExpertise: boolean;@@ -95,6 +97,7 @@ export const startOperation = async (botContext,botPlatformContext,clientIp,+ disabledPluginIds,discordContext,discovery,enableExpertise,@@ -174,6 +177,7 @@ export const startOperation = async (: undefined,deviceSystemInfo:Object.keys(prep.deviceSystemInfo).length > 0 ? prep.deviceSystemInfo : undefined,+ disabledPluginIds,executionPlan: discovery.executionPlan,searchDecision: discovery.searchDecision,userTimezone,diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.tsindex 1e9e54a5adc..995ce3e3e60 100644--- a/packages/agent-runtime/src/types/state.ts+++ b/packages/agent-runtime/src/types/state.ts@@ -215,6 +215,12 @@ export interface AgentWorldSnapshot {};/** Borrowed-connector attribution rendered into the system message. */connectorOwnershipNote?: string;+ /**+ * Plugin identifiers the agent explicitly disabled (tri-state entries).+ * `agent.plugins` is already collapsed to pinned ids, so the disabled set+ * is kept apart for the rules that must hide those tools from the model.+ */+ disabledPluginIds?: string[];/** Evaluation prompt data for eval runs. */eval?: EvalContext;/** Multi-agent group roster (or bot-conversation fallback). */diff --git a/packages/mecha/package.json b/packages/mecha/package.jsonindex 65ebcd8c15f..530b9d122bc 100644--- a/packages/mecha/package.json+++ b/packages/mecha/package.json@@ -8,14 +8,25 @@"test:coverage": "vitest --coverage --silent='passed-only'"},"dependencies": {+ "@lobechat/agent-runtime": "workspace:*","@lobechat/builtin-agents": "workspace:*",+ "@lobechat/builtin-tool-agent-builder": "workspace:*",+ "@lobechat/builtin-tool-agent-management": "workspace:*",+ "@lobechat/builtin-tool-cloud-sandbox": "workspace:*",+ "@lobechat/builtin-tool-creds": "workspace:*",+ "@lobechat/builtin-tool-group-agent-builder": "workspace:*",+ "@lobechat/builtin-tool-lobe-agent": "workspace:*","@lobechat/builtin-tool-local-system": "workspace:*","@lobechat/builtin-tool-page-agent": "workspace:*","@lobechat/builtin-tool-task": "workspace:*",+ "@lobechat/builtin-tool-web-onboarding": "workspace:*",+ "@lobechat/builtin-tools": "workspace:*",+ "@lobechat/const": "workspace:*","@lobechat/context-engine": "workspace:*","@lobechat/prompts": "workspace:*","@lobechat/types": "workspace:*","debug": "^4.4.3",- "immer": "^10.1.3"+ "immer": "^10.1.3",+ "p-map": "^7.0.6"}}diff --git a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.ts b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.tsnew file mode 100644index 00000000000..c5d7d9b2322--- /dev/null+++ b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.test.ts@@ -0,0 +1,346 @@+import { getConnectorCatalog } from '@lobechat/const';+import { describe, expect, it, vi } from 'vitest';++import { gatherContextFacts } from './gatherContextFacts';+import { listOfficialTools } from './officialTools';+import type { ContextFactProviders, ContextFactRequest } from './types';++const request = (overrides: Partial<ContextFactRequest> = {}): ContextFactRequest => ({+ agent: { chatConfig: {} as never, description: 'helps', slug: null, title: 'Helper' },+ agentId: 'agt_1',+ enabledToolIds: [],+ features: { composio: true, lobehubSkill: true },+ messages: [],+ topicId: 'tpc_1',+ ...overrides,+});++const message = (content: string) =>+ ({ content, createdAt: 0, id: 'm', role: 'user', updatedAt: 0 }) as never;++describe('gatherContextFacts', () => {+ it('yields no facts and never throws when the host provides nothing', async () => {+ const facts = await gatherContextFacts(request(), {});++ expect(facts.agentDocuments).toBeUndefined();+ expect(Object.values(facts.step).every((v) => v === undefined)).toBe(true);+ expect(facts.variables).toMatchObject({+ CREDS_LIST: '',+ agent_id: 'agt_1',+ agent_title: 'Helper',+ creds_sandbox_reachable: 'true',+ sandbox_enabled: 'false',+ topic_id: 'tpc_1',+ });+ });++ it('treats a failing provider as a missing fact', async () => {+ const facts = await gatherContextFacts(request(), {+ findTopic: async () => {+ throw new Error('db down');+ },+ getUserInfo: async () => ({ language: 'zh-CN', username: 'arvin' }),+ });++ expect(facts.variables.topic_title).toBe('');+ expect(facts.variables.username).toBe('arvin');+ });++ describe('plan / todo', () => {+ const providers: ContextFactProviders = {+ getPlanDocument: async () => ({+ content: 'ctx',+ createdAt: '2026-01-01T00:00:00.000Z',+ description: 'desc',+ id: 'plan_1',+ metadata: { todos: { items: [{ status: 'todo', text: 'from doc' }] } },+ title: 'Ship it',+ updatedAt: '2026-01-02T00:00:00.000Z',+ }),+ };++ it('injects the plan block from the document and its todos when history has none', async () => {+ const facts = await gatherContextFacts(+ request({ enabledToolIds: ['lobe-agent'] }),+ providers,+ );++ expect(facts.step.planTodo?.plan).toMatchObject({ goal: 'Ship it', description: 'desc' });+ expect(facts.step.planTodo?.todos?.items.map((t) => t.text)).toEqual(['from doc']);+ });++ it('keeps the plan block but takes todos from history when history has them', async () => {+ const facts = await gatherContextFacts(+ request({+ enabledToolIds: ['lobe-agent'],+ messages: [+ {+ content: 'done',+ createdAt: 0,+ id: 't',+ pluginState: { todos: { items: [{ status: 'todo', text: 'from history' }] } },+ role: 'tool',+ updatedAt: 0,+ } as never,+ ],+ }),+ providers,+ );++ expect(facts.step.planTodo?.plan?.goal).toBe('Ship it');+ expect(facts.step.planTodo?.todos?.items.map((t) => t.text)).toEqual(['from history']);+ });++ it('does not read the plan document without lobe-agent', async () => {+ const getPlanDocument = vi.fn(providers.getPlanDocument);+ const facts = await gatherContextFacts(request(), { getPlanDocument });++ expect(getPlanDocument).not.toHaveBeenCalled();+ expect(facts.step.planTodo).toBeUndefined();+ });+ });++ describe('credentials and Composio', () => {+ it('lists credentials for the run scope only when the creds tool is enabled', async () => {+ const listCredentials = vi.fn(async () => [+ { key: 'k', name: 'GitHub', type: 'kv-env' as const },+ ]);++ const off = await gatherContextFacts(request(), { listCredentials });+ expect(listCredentials).not.toHaveBeenCalled();+ expect(off.variables.CREDS_LIST).toBe('');++ const on = await gatherContextFacts(+ request({ enabledToolIds: ['lobe-creds'], workspaceId: 'ws_1' }),+ { listCredentials },+ );+ expect(listCredentials).toHaveBeenCalledWith({ workspaceId: 'ws_1' });+ expect(on.variables.CREDS_LIST).toContain('GitHub');+ });++ it('drops disabled Composio services from both lists and needs the creds tool', async () => {+ const listConnectedConnectorIds = vi.fn(async () => ['gmail', 'slack']);++ const off = await gatherContextFacts(request(), { listConnectedConnectorIds });+ expect(listConnectedConnectorIds).not.toHaveBeenCalled();+ expect(off.variables.COMPOSIO_SERVICES_LIST).toBe('');++ const on = await gatherContextFacts(+ request({ disabledPluginIds: ['slack'], enabledToolIds: ['lobe-creds'] }),+ { listConnectedConnectorIds },+ );+ const list = on.variables.COMPOSIO_SERVICES_LIST as string;+ expect(list).toContain('gmail');+ expect(list).not.toContain('slack');+ });+ });++ describe('share visitor gates', () => {+ const visitor = { agentId: 'agt_1', visitorUserId: 'visitor_1' };++ it('hides documents, onboarding and workspace context from a visitor', async () => {+ const facts = await gatherContextFacts(+ request({+ agent: { slug: 'web-onboarding' },+ enabledToolIds: ['lobe-web-onboarding'],+ shareVisitor: visitor,+ workspaceId: 'ws_1',+ }),+ {+ getOnboardingContext: async () => ({ phaseGuidance: 'go' }) as never,+ getWorkspaceContext: async () => ({ appUrl: 'https://x', slug: 'team' }),+ listAgentDocuments: async () => [{ id: 'd1' }] as never,+ },+ );++ expect(facts.agentDocuments).toBeUndefined();+ expect(facts.step.onboardingContext).toBeUndefined();+ expect(facts.step.workspaceContext).toBeUndefined();+ });++ it('only resolves topic references the visitor started with the shared agent', async () => {+ const findTopic = async (topicId: string) =>+ topicId === 'mine'+ ? { agentId: 'agt_1', historySummary: 'my summary', id: 'mine', senderId: 'visitor_1' }+ : {+ agentId: 'agt_1',+ historySummary: 'creator secret',+ id: 'theirs',+ senderId: 'creator',+ };++ const facts = await gatherContextFacts(+ request({+ messages: [+ message(+ '<refer_topic id="mine">a</refer_topic> <refer_topic id="theirs">b</refer_topic>',+ ),+ ],+ shareVisitor: visitor,+ }),+ { findTopic },+ );++ const summaries = facts.step.topicReferences?.map((r) => r.summary) ?? [];+ expect(summaries).toContain('my summary');+ expect(summaries).not.toContain('creator secret');+ });++ it('never enumerates the ownerβs agents, providers or plugins for a visitor', async () => {+ const listRecentAgents = vi.fn(async () => [{ id: 'agt_2', title: 'Owner private' }]);+ const listEnabledProviders = vi.fn(async () => [{ id: 'openai', models: [], name: 'x' }]);+ const listCustomPlugins = vi.fn(async () => []);++ const facts = await gatherContextFacts(+ request({+ // Auto skill mode and even a leaked tool id must not open the door.+ enabledToolIds: ['lobe-agent-management'],+ mentionedAgents: [{ id: 'agt_3', title: 'Mentioned' }] as never,+ shareVisitor: visitor,+ }),+ { listCustomPlugins, listEnabledProviders, listRecentAgents },+ );++ expect(listRecentAgents).not.toHaveBeenCalled();+ expect(listEnabledProviders).not.toHaveBeenCalled();+ expect(listCustomPlugins).not.toHaveBeenCalled();+ expect(facts.step.agentManagementContext).toEqual({+ mentionedAgents: [{ id: 'agt_3', title: 'Mentioned' }],+ });+ });++ it('reads user info for the visitor, not the owner', async () => {+ const getUserInfo = vi.fn(async () => ({ language: 'ja-JP', username: 'v' }));+ await gatherContextFacts(request({ shareVisitor: visitor }), { getUserInfo });+ expect(getUserInfo).toHaveBeenCalledWith('visitor_1');++ await gatherContextFacts(request(), { getUserInfo });+ expect(getUserInfo).toHaveBeenLastCalledWith(undefined);+ });+ });++ it('skips topic references and onboarding already present in the messages', async () => {+ const findTopic = vi.fn();+ const getOnboardingContext = vi.fn();+ await gatherContextFacts(+ request({+ enabledToolIds: ['lobe-web-onboarding'],+ messages: [+ message(+ '<topic_reference_context>β¦</topic_reference_context> <onboarding_context>β¦</onboarding_context>',+ ),+ ],+ }),+ { findTopic, getOnboardingContext },+ );+ // The current topic is still looked up for its title; no referenced topic is.+ expect(findTopic.mock.calls.map(([id]) => id)).toEqual(['tpc_1']);+ expect(getOnboardingContext).not.toHaveBeenCalled();+ });++ it('reads the documents of the agent being edited while the builder is active', async () => {+ const listAgentDocuments = vi.fn(async (id: string) => [{ id: `doc-of-${id}` }] as never);++ const plain = await gatherContextFacts(request({ editingAgentId: 'agt_edit' }), {+ listAgentDocuments,+ });+ expect(plain.agentDocuments).toEqual([{ id: 'doc-of-agt_1' }]);++ const building = await gatherContextFacts(+ request({ editingAgentId: 'agt_edit', enabledToolIds: ['lobe-agent-builder'] }),+ { listAgentDocuments },+ );+ expect(building.agentDocuments).toEqual([{ id: 'doc-of-agt_edit' }]);+ });++ describe('agent management', () => {+ const recent = Array.from({ length: 12 }, (_, i) => ({ id: `agt_${i}`, title: `A${i}` }));++ it('lists available agents in auto skill mode without the tool, excluding itself', async () => {+ const facts = await gatherContextFacts(request(), { listRecentAgents: async () => recent });++ const ctx = facts.step.agentManagementContext!;+ expect(ctx.availableAgents?.map((a) => a.id)).not.toContain('agt_1');+ expect(ctx.availableAgents).toHaveLength(10);+ expect(ctx.availableAgentsHasMore).toBe(true);+ expect(ctx.currentAgent).toEqual({ id: 'agt_1', title: 'Helper' });+ expect(ctx.availablePlugins).toBeUndefined();+ });++ it('adds providers and the plugin catalog only when the tool is enabled', async () => {+ const facts = await gatherContextFacts(+ request({+ agent: { chatConfig: { skillActivateMode: 'manual' } as never },+ enabledToolIds: ['lobe-agent-management'],+ }),+ {+ listCustomPlugins: async () => [{ identifier: 'my-mcp', name: 'Mine', type: 'custom' }],+ listEnabledProviders: async () => [{ id: 'openai', models: [], name: 'OpenAI' }],+ listRecentAgents: async () => recent,+ },+ );++ const ctx = facts.step.agentManagementContext!;+ expect(ctx.availableProviders).toEqual([{ id: 'openai', models: [], name: 'OpenAI' }]);+ const types = new Set(ctx.availablePlugins?.map((p) => p.type));+ expect(types).toEqual(new Set(['builtin', 'composio', 'lobehub-skill', 'custom']));+ expect(ctx.availablePlugins?.map((p) => p.identifier)).not.toContain('lobe-agent-builder');+ });++ it('carries mentioned agents even without the tool or auto mode', async () => {+ const facts = await gatherContextFacts(+ request({+ agent: { chatConfig: { skillActivateMode: 'manual' } as never },+ mentionedAgents: [{ id: 'agt_9', title: 'Nine' }] as never,+ }),+ {},+ );+ expect(facts.step.agentManagementContext).toEqual({+ mentionedAgents: [{ id: 'agt_9', title: 'Nine' }],+ });+ });+ });++ it('lists LobeHub skill connectors in the official tool catalog with their status', () => {+ const [lobehubProvider] = getConnectorCatalog({ composio: false, lobehub: true });+ const lobehubId = lobehubProvider.type === 'lobehub' ? lobehubProvider.provider.id : '';+ const tools = listOfficialTools({+ connectedConnectorIds: new Set(['gmail', lobehubId]),+ enabledPlugins: ['gmail'],+ features: { composio: true, lobehubSkill: true },+ });++ const types = new Set(tools.map((t) => t.type));+ expect(types).toEqual(new Set(['builtin', 'composio', 'lobehub-skill']));+ expect(tools.find((t) => t.identifier === 'gmail')).toMatchObject({+ enabled: true,+ installed: true,+ });+ expect(tools.find((t) => t.identifier === lobehubId)).toMatchObject({+ installed: true,+ type: 'lobehub-skill',+ });+ });++ it('describes the workspace only when its slug resolves', async () => {+ const providers = {+ getWorkspaceContext: async (id?: string) => ({+ appUrl: 'https://x',+ slug: id ? undefined : undefined,+ }),+ };+ const personal = await gatherContextFacts(request({ workspaceId: undefined }), providers);+ expect(personal.step.workspaceContext).toEqual({ appUrl: 'https://x' });++ const unresolved = await gatherContextFacts(request({ workspaceId: 'ws_1' }), providers);+ expect(unresolved.step.workspaceContext).toBeUndefined();++ const resolved = await gatherContextFacts(request({ workspaceId: 'ws_1' }), {+ getWorkspaceContext: async () => ({ appUrl: 'https://x', slug: 'team' }),+ });+ expect(resolved.step.workspaceContext).toEqual({+ appUrl: 'https://x',+ workspace: { slug: 'team' },+ });+ });+});diff --git a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.tsnew file mode 100644index 00000000000..e51a7b4d3b8--- /dev/null+++ b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts@@ -0,0 +1,508 @@+import { extractTodosFromMessages, normalizeTodosState } from '@lobechat/agent-runtime';+import { AgentBuilderIdentifier } from '@lobechat/builtin-tool-agent-builder';+import { AgentManagementIdentifier } from '@lobechat/builtin-tool-agent-management';+import {+ CloudSandboxIdentifier,+ formatUploadedFilesPrompt,+} from '@lobechat/builtin-tool-cloud-sandbox';+import {+ type ComposioServiceSummary,+ CredsIdentifier,+ 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 { COMPOSIO_APP_TYPES } from '@lobechat/const';+import {+ type AgentBuilderContext,+ type AgentManagementContext,+ type GroupAgentBuilderContext,+ type PlanTodoConfig,+ resolveTopicReferences,+ type TopicReferenceItem,+ type WorkspaceContext,+} from '@lobechat/context-engine';+import debug from 'debug';+import pMap from 'p-map';++import { listAvailablePlugins, listOfficialTools } from './officialTools';+import type {+ ContextFactProviders,+ ContextFactRequest,+ GatheredContextFacts,+ TopicFacts,+} from './types';++const log = debug('mecha:contextFacts');++/** How many recent agents the management context lists before saying "and more". */+export const AVAILABLE_AGENTS_LIMIT = 10;+/** Providers listed in the management context. */+const AVAILABLE_PROVIDERS_LIMIT = 5;+/** How many provider lookups run at once. */+export const FACT_CONCURRENCY = 8;++const messageContents = (messages: ContextFactRequest['messages']) =>+ messages.map((message) => message.content).filter((c): c is string => typeof c === 'string');++const contains = (messages: ContextFactRequest['messages'], markers: string[]) =>+ messageContents(messages).some((content) => markers.some((marker) => content.includes(marker)));++/**+ * Run a provider; a missing or failing provider is "no fact", never a failed+ * turn. Accepts an optional-chained call (`providers.x?.(...)`) directly.+ */+const attempt = async <T>(+ label: string,+ run: () => Promise<T | null | undefined> | T | null | undefined,+): Promise<T | undefined> => {+ try {+ return (await run()) ?? undefined;+ } catch (error) {+ log('%s failed (non-fatal): %O', label, error);+ return undefined;+ }+};++const tupleSettled = <T extends readonly (() => Promise<unknown>)[]>(tasks: T) =>+ pMap(tasks, (task) => task(), { concurrency: FACT_CONCURRENCY }) as Promise<{+ [K in keyof T]: Awaited<ReturnType<T[K]>>;+ }>;++/**+ * A share visitor may only reference their own conversations with the shared+ * agent. Topic rows are owned by the CREATOR, so ownership scoping alone would+ * expose every private topic to a `<refer_topic>` tag the visitor typed; match+ * the visitor / agent pairing of the active share instead.+ */+const isTopicVisibleToRun = (+ request: ContextFactRequest,+ topic: TopicFacts | null | undefined,+): boolean => {+ const visitor = request.shareVisitor;+ if (!visitor) return true;+ return topic?.senderId === visitor.visitorUserId && topic?.agentId === visitor.agentId;+};++const gatherTopicReferences = async (+ request: ContextFactRequest,+ providers: ContextFactProviders,+): Promise<TopicReferenceItem[] | undefined> => {+ // Client-side preprocessing may already have injected the references.+ if (contains(request.messages, ['topic_reference_context'])) return undefined;+ if (!providers.findTopic) return undefined;+ const { findTopic, listTopicMessages } = providers;++ return attempt('topicReferences', () =>+ resolveTopicReferences(+ request.messages as Array<{ content: string | unknown }>,+ async (topicId) => {+ const topic = await findTopic(topicId);+ return isTopicVisibleToRun(request, topic) ? (topic ?? null) : null;+ },+ listTopicMessages+ ? async (topicId) => {+ const topic = await findTopic(topicId);+ if (!topic || !isTopicVisibleToRun(request, topic)) return [];+ return (await listTopicMessages(topic)) ?? [];+ }+ : undefined,+ ),+ );+};++/**+ * The agent whose documents the model reads: the one being edited while the+ * agent builder is active, otherwise the executing agent. Never for a share+ * visitor β the share config has no setting that could grant file access.+ */+const documentsAgentId = (request: ContextFactRequest) => {+ if (request.shareVisitor) return undefined;+ if (request.enabledToolIds.includes(AgentBuilderIdentifier) && request.editingAgentId) {+ return request.editingAgentId;+ }+ return request.agentId;+};++const gatherOnboardingContext = async (+ request: ContextFactRequest,+ providers: ContextFactProviders,+) => {+ const isOnboardingAgent =+ request.agent.slug === 'web-onboarding' ||+ request.enabledToolIds.includes(WebOnboardingIdentifier);+ // Persona / SOUL / initial user info are personal profile data with no+ // share permission that could ever grant them.+ if (!isOnboardingAgent || request.shareVisitor || !providers.getOnboardingContext)+ return undefined;+ if (+ contains(request.messages, [+ '<onboarding_context>',+ '<current_soul_document>',+ '<current_user_persona>',+ ])+ ) {+ return undefined;+ }+ return attempt('onboardingContext', providers.getOnboardingContext);+};++const gatherWorkspaceContext = async (+ request: ContextFactRequest,+ providers: ContextFactProviders,+): Promise<WorkspaceContext | undefined> => {+ // A share visitor converses under the CREATOR's identity: the creator's+ // routes are not the visitor's, so never describe that scope to them.+ if (request.shareVisitor || !providers.getWorkspaceContext) return undefined;+ const { getWorkspaceContext } = providers;+ return attempt('workspaceContext', async () => {+ const resolved = await getWorkspaceContext(request.workspaceId);+ if (!resolved) return undefined;+ // Personal space: the origin alone anchors links.+ if (!request.workspaceId) return resolved.appUrl ? { appUrl: resolved.appUrl } : undefined;+ // A workspace run whose slug cannot be resolved must not be described as+ // the personal space; inject nothing rather than a false statement.+ if (!resolved.slug) return undefined;+ return { appUrl: resolved.appUrl, workspace: { slug: resolved.slug } };+ });+};++const gatherPlanTodo = async (+ request: ContextFactRequest,+ providers: ContextFactProviders,+): Promise<PlanTodoConfig | undefined> => {+ // Message history is the source of truth for the TODO state; the plan+ // document is a best-effort mirror the run keeps with `lobe-agent`.+ const messageTodos = extractTodosFromMessages(request.messages);+ const canReadPlan =+ request.enabledToolIds.includes(LobeAgentIdentifier) &&+ !!request.topicId &&+ !!providers.getPlanDocument;+ const planDoc = canReadPlan+ ? await attempt('planDocument', () => providers.getPlanDocument?.(request.topicId!))+ : undefined;++ const todos =+ messageTodos ??+ (planDoc ? normalizeTodosState(planDoc.metadata?.todos, planDoc.updatedAt) : undefined);++ if (!planDoc && todos === undefined) return undefined;+ return {+ enabled: true,+ ...(planDoc && {+ plan: {+ completed: false,+ context: planDoc.content ?? undefined,+ createdAt: planDoc.createdAt,+ description: planDoc.description ?? '',+ goal: planDoc.title ?? '',+ id: planDoc.id,+ updatedAt: planDoc.updatedAt,+ },+ }),+ todos,+ };+};++const gatherCredentials = async (request: ContextFactRequest, providers: ContextFactProviders) => {+ // Only a run that can inject credentials needs the list.+ if (!request.enabledToolIds.includes(CredsIdentifier) || !providers.listCredentials)+ return undefined;+ const { listCredentials } = providers;+ return attempt('credentials', () => listCredentials({ workspaceId: request.workspaceId }));+};++const gatherComposioServices = async (+ request: ContextFactRequest,+ providers: ContextFactProviders,+): Promise<string> => {+ if (+ !request.enabledToolIds.includes(CredsIdentifier) ||+ !request.features.composio ||+ !providers.listConnectedConnectorIds+ ) {+ return '';+ }+ const { listConnectedConnectorIds } = providers;+ const connectedIds = new Set(+ (await attempt('connectedConnectors', () => listConnectedConnectorIds(request.agentId))) ?? [],+ );+ // Disabled services are dropped from both lists β neither "connected, use+ // directly" nor "available to connect" β the agent isn't meant to see them.+ const disabledIdSet = new Set(request.disabledPluginIds ?? []);+ const connected: ComposioServiceSummary[] = excludeDisabledComposioServices(+ COMPOSIO_APP_TYPES.filter((tool) => connectedIds.has(tool.identifier)),+ disabledIdSet,+ ).map((tool) => ({ identifier: tool.identifier, name: tool.label }));+ const available = resolveAvailableComposioServices(+ COMPOSIO_APP_TYPES,+ connectedIds,+ disabledIdSet,+ );+ return generateComposioServicesList(connected, available);+};++const gatherAgentBuilderContext = async (+ request: ContextFactRequest,+ providers: ContextFactProviders,+): Promise<AgentBuilderContext | undefined> => {+ const { editingAgentId } = request;+ if (+ !request.enabledToolIds.includes(AgentBuilderIdentifier) ||+ !editingAgentId ||+ !providers.getAgentDefinition+ ) {+ return undefined;+ }+ const { getAgentDefinition, listConnectedConnectorIds } = providers;+ return attempt('agentBuilderContext', async () => {+ const editing = await getAgentDefinition(editingAgentId);+ if (!editing) return undefined;+ const enabledPlugins = editing.plugins ?? [];+ const connected = new Set(+ (await attempt('connectedConnectors', () => listConnectedConnectorIds?.(editingAgentId))) ??+ [],+ );+ const officialTools = listOfficialTools({+ connectedConnectorIds: connected,+ enabledPlugins,+ features: request.features,+ });+ return {+ config: {+ chatConfig: editing.chatConfig ?? undefined,+ model: editing.model ?? undefined,+ openingMessage: editing.openingMessage ?? undefined,+ openingQuestions: editing.openingQuestions ?? undefined,+ params: editing.params ?? undefined,+ plugins: enabledPlugins,+ provider: editing.provider ?? undefined,+ systemRole: editing.systemRole ?? undefined,+ },+ meta: {+ avatar: editing.avatar ?? undefined,+ backgroundColor: editing.backgroundColor ?? undefined,+ description: editing.description ?? undefined,+ name: editing.name ?? undefined,+ tags: editing.tags ?? undefined,+ title: editing.title ?? undefined,+ },+ ...(officialTools.length > 0 && { officialTools }),+ };+ });+};++const gatherGroupAgentBuilderContext = async (+ request: ContextFactRequest,+ providers: ContextFactProviders,+): Promise<GroupAgentBuilderContext | undefined> => {+ const { editingGroupId } = request;+ if (+ !request.enabledToolIds.includes(GroupAgentBuilderIdentifier) ||+ !editingGroupId ||+ !providers.getGroup+ ) {+ return undefined;+ }+ const { getAgentDefinition, getGroup, listConnectedConnectorIds } = providers;+ return attempt('groupAgentBuilderContext', async () => {+ const group = await getGroup(editingGroupId);+ if (!group) return undefined;+ const supervisorAgentId = group.members.find((m) => m.role === 'supervisor')?.agentId;++ let supervisorConfig: GroupAgentBuilderContext['supervisorConfig'];+ let enabledPlugins: string[] = [];+ if (supervisorAgentId && getAgentDefinition) {+ const supervisor = await getAgentDefinition(supervisorAgentId);+ if (supervisor) {+ enabledPlugins = supervisor.plugins ?? [];+ supervisorConfig = {+ model: supervisor.model ?? undefined,+ plugins: enabledPlugins,+ provider: supervisor.provider ?? undefined,+ };+ }+ }+ const connected = new Set(+ (await attempt('connectedConnectors', () =>+ listConnectedConnectorIds?.(supervisorAgentId),+ )) ?? [],+ );++ return {+ config: {+ openingMessage: group.config?.openingMessage || undefined,+ openingQuestions: group.config?.openingQuestions ?? undefined,+ systemPrompt: group.content || undefined,+ },+ groupId: editingGroupId,+ groupTitle: group.title || undefined,+ members: group.members.map((member) => ({+ description: member.description ?? undefined,+ id: member.agentId,+ isSupervisor: member.role === 'supervisor',+ title: member.title || 'Untitled Agent',+ })),+ officialTools: listOfficialTools({+ connectedConnectorIds: connected,+ enabledPlugins,+ features: request.features,+ }),+ supervisorConfig,+ };+ });+};++/**+ * - `availableAgents` whenever the agent is in auto skill mode (so it can+ * decide to activate agent management on its own) or the tool is enabled.+ * - providers / plugins only when the tool is enabled: they only serve+ * createAgent / updateAgent.+ * - `mentionedAgents` always: an @-mention must carry delegation context even+ * when the agent has no agent-management tool.+ * - nothing owner-scoped for a share visitor: the creator's other agents,+ * providers and plugins are theirs, and the share gate has already removed+ * the tool that could act on them.+ */+const gatherAgentManagementContext = async (+ request: ContextFactRequest,+ providers: ContextFactProviders,+): Promise<AgentManagementContext | undefined> => {+ const isVisitor = !!request.shareVisitor;+ const isEnabled = !isVisitor && request.enabledToolIds.includes(AgentManagementIdentifier);+ const isAutoSkillMode = !isVisitor && request.agent.chatConfig?.skillActivateMode !== 'manual';+ let context: AgentManagementContext | undefined;++ if ((isAutoSkillMode || isEnabled) && providers.listRecentAgents) {+ const { listRecentAgents } = providers;+ const recent =+ (await attempt('recentAgents', () => listRecentAgents(AVAILABLE_AGENTS_LIMIT + 2))) ?? [];+ // The model is the current agent: its identity is already established by+ // the system role, and it must never see its own id (it cannot call itself).+ const others = request.agentId ? recent.filter((a) => a.id !== request.agentId) : recent;+ context = {+ availableAgents: others.slice(0, AVAILABLE_AGENTS_LIMIT).map((a) => ({+ description: a.description ?? undefined,+ id: a.id,+ title: a.title ?? 'Untitled',+ })),+ availableAgentsHasMore: others.length > AVAILABLE_AGENTS_LIMIT,+ ...(request.agentId && {+ currentAgent: { id: request.agentId, title: request.agent.title ?? undefined },+ }),+ };+ }++ if (isEnabled) {+ const [enabledProviders, customPlugins] = await Promise.all([+ attempt('enabledProviders', () => providers.listEnabledProviders?.()),+ attempt('customPlugins', () => providers.listCustomPlugins?.()),+ ]);+ context = {+ ...context,+ availablePlugins: [...listAvailablePlugins(request.features), ...(customPlugins ?? [])],+ availableProviders: (enabledProviders ?? []).slice(0, AVAILABLE_PROVIDERS_LIMIT),+ };+ }++ if (request.mentionedAgents?.length) {+ context = { ...context, mentionedAgents: request.mentionedAgents };+ }++ return context;+};++/**+ * Decide which facts this turn needs, fetch them through the host's providers+ * and place them where the context snapshot consumes them. The rules β which+ * tool gates a fact, what a share visitor may see, what counts as already+ * injected β live here and only here; hosts implement fetching.+ */+export const gatherContextFacts = async (+ request: ContextFactRequest,+ providers: ContextFactProviders,+): Promise<GatheredContextFacts> => {+ const docsAgentId = documentsAgentId(request);+ const sandboxEnabled = request.enabledToolIds.includes(CloudSandboxIdentifier);++ const tasks = [+ () =>+ attempt('agentDocuments', () =>+ docsAgentId ? providers.listAgentDocuments?.(docsAgentId) : undefined,+ ),+ () => gatherAgentBuilderContext(request, providers),+ () => gatherAgentManagementContext(request, providers),+ () => gatherComposioServices(request, providers),+ () => gatherCredentials(request, providers),+ () => gatherGroupAgentBuilderContext(request, providers),+ () => gatherOnboardingContext(request, providers),+ () => gatherPlanTodo(request, providers),+ () =>+ attempt('sandboxFiles', () =>+ sandboxEnabled && request.topicId+ ? providers.listSandboxFiles?.(request.topicId)+ : undefined,+ ),+ () =>+ attempt('topic', () =>+ request.topicId ? providers.findTopic?.(request.topicId) : undefined,+ ),+ () => gatherTopicReferences(request, providers),+ () => attempt('userInfo', () => providers.getUserInfo?.(request.shareVisitor?.visitorUserId)),+ () => gatherWorkspaceContext(request, providers),+ ] as const;++ const [+ agentDocuments,+ agentBuilderContext,+ agentManagementContext,+ composioServicesList,+ credentials,+ groupAgentBuilderContext,+ onboardingContext,+ planTodo,+ sandboxFiles,+ topic,+ topicReferences,+ userInfo,+ workspaceContext,+ ] = await tupleSettled(tasks);++ return {+ agentDocuments: agentDocuments?.length ? agentDocuments : undefined,+ step: {+ agentBuilderContext,+ agentManagementContext,+ groupAgentBuilderContext,+ onboardingContext,+ planTodo,+ topicReferences,+ workspaceContext,+ },+ variables: {+ COMPOSIO_SERVICES_LIST: composioServicesList,+ CREDS_LIST: credentials ? generateCredsList(credentials) : '',+ agent_description: request.agent.description ?? '',+ agent_id: request.agentId ?? '',+ agent_title: request.agent.title ?? '',+ // A credential is reachable whenever the dedicated sandbox tool is+ // exposed for 'auto' (independent of device routing) or no device is+ // routed (independent of target): `runCommand` / `execScript` fall back+ // to the cloud sandbox session whenever no device is actively routed.+ creds_sandbox_reachable: String(+ !request.activeDeviceId || request.executionTarget === 'auto',+ ),+ language: userInfo?.language ?? '',+ memory_effort: String(request.agent.chatConfig?.memory?.effort ?? ''),+ sandbox_enabled: String(sandboxEnabled),+ sandbox_uploaded_files: sandboxFiles ? formatUploadedFilesPrompt(sandboxFiles) : '',+ topic_id: request.topicId ?? '',+ topic_title: topic?.title ?? '',+ username: userInfo?.username ?? '',+ },+ };+};diff --git a/packages/mecha/src/contextEngineering/facts/index.ts b/packages/mecha/src/contextEngineering/facts/index.tsnew file mode 100644index 00000000000..8c4cb812f28--- /dev/null+++ b/packages/mecha/src/contextEngineering/facts/index.ts@@ -0,0 +1,3 @@+export { AVAILABLE_AGENTS_LIMIT, FACT_CONCURRENCY, gatherContextFacts } from './gatherContextFacts';+export { listAvailablePlugins, listOfficialTools } from './officialTools';+export type * from './types';diff --git a/packages/mecha/src/contextEngineering/facts/officialTools.ts b/packages/mecha/src/contextEngineering/facts/officialTools.tsnew file mode 100644index 00000000000..40fb18683c1--- /dev/null+++ b/packages/mecha/src/contextEngineering/facts/officialTools.ts@@ -0,0 +1,121 @@+import { builtinTools } from '@lobechat/builtin-tools';+import { type ConnectorCatalogItem, getConnectorCatalog } from '@lobechat/const';+import type { AvailablePluginInfo, OfficialToolItem } from '@lobechat/context-engine';++import type { ContextFactRequest } from './types';++const connectorIdentifier = (item: ConnectorCatalogItem) =>+ item.type === 'lobehub' ? item.provider.id : item.serverType.identifier;++/**+ * Tools that only make sense for the agent they ship with; never offered as+ * something to create a new agent with.+ */+const INTERNAL_TOOLS = new Set([+ 'lobe-agent-management',+ 'lobe-agent-builder',+ 'lobe-group-agent-builder',+ 'lobe-page-agent',+]);++/**+ * 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.+ */+export const listOfficialTools = (params: {+ connectedConnectorIds: Set<string>;+ enabledPlugins: string[];+ features: ContextFactRequest['features'];+}): OfficialToolItem[] => {+ const { connectedConnectorIds, enabledPlugins, features } = params;+ const catalog = getConnectorCatalog({+ composio: features.composio,+ lobehub: features.lobehubSkill,+ });+ const connectorIdentifiers = new Set(catalog.map(connectorIdentifier));+ const officialTools: OfficialToolItem[] = [];++ for (const tool of builtinTools) {+ if (tool.hidden) continue;+ if (connectorIdentifiers.has(tool.identifier)) continue;+ officialTools.push({+ description: tool.manifest?.meta?.description,+ enabled: enabledPlugins.includes(tool.identifier),+ identifier: tool.identifier,+ installed: true,+ name: tool.manifest?.meta?.title || tool.identifier,+ type: 'builtin',+ });+ }++ for (const item of catalog) {+ if (item.type === 'composio') {+ officialTools.push({+ description: `LobeHub Mcp Server: ${item.serverType.label}`,+ enabled: enabledPlugins.includes(item.serverType.identifier),+ identifier: item.serverType.identifier,+ installed: connectedConnectorIds.has(item.serverType.identifier),+ name: item.serverType.label,+ type: 'composio',+ });+ continue;+ }+ officialTools.push({+ description: `LobeHub Skill Provider: ${item.provider.label}`,+ enabled: enabledPlugins.includes(item.provider.id),+ identifier: item.provider.id,+ installed: connectedConnectorIds.has(item.provider.id),+ name: item.provider.label,+ type: 'lobehub-skill',+ });+ }++ return officialTools;+};++/**+ * Plugins the agent-management tool may attach to a new agent: every builtin+ * except the internal ones (hidden builtins included β web browsing and the+ * sandbox are real capabilities), plus the connector catalog.+ */+export const listAvailablePlugins = (+ features: ContextFactRequest['features'],+): AvailablePluginInfo[] => {+ const catalog = getConnectorCatalog({+ composio: features.composio,+ lobehub: features.lobehubSkill,+ });+ const connectorIdentifiers = new Set(catalog.map(connectorIdentifier));+ const plugins: AvailablePluginInfo[] = [];++ for (const tool of builtinTools) {+ if (connectorIdentifiers.has(tool.identifier) || INTERNAL_TOOLS.has(tool.identifier)) continue;+ plugins.push({+ description: tool.manifest?.meta?.description,+ identifier: tool.identifier,+ name: tool.manifest?.meta?.title || tool.identifier,+ type: 'builtin',+ });+ }++ for (const item of catalog) {+ if (item.type === 'composio') {+ plugins.push({+ description: item.serverType.description,+ identifier: item.serverType.identifier,+ name: item.serverType.label,+ type: 'composio',+ });+ continue;+ }+ plugins.push({+ description: item.provider.description,+ identifier: item.provider.id,+ name: item.provider.label,+ type: 'lobehub-skill',+ });+ }++ return plugins;+};diff --git a/packages/mecha/src/contextEngineering/facts/types.ts b/packages/mecha/src/contextEngineering/facts/types.tsnew file mode 100644index 00000000000..565a4cc2cdc--- /dev/null+++ b/packages/mecha/src/contextEngineering/facts/types.ts@@ -0,0 +1,164 @@+import type { CredSummary } from '@lobechat/builtin-tool-creds';+import type {+ AgentContextDocument,+ AgentManagementContext,+ AvailablePluginInfo,+ AvailableProviderInfo,+ OnboardingContext,+} from '@lobechat/context-engine';+import type {+ AgentShareVisitorContext,+ LobeAgentChatConfig,+ RuntimeMentionedAgent,+ UIChatMessage,+} from '@lobechat/types';++import type { ContextStepSnapshot, ContextVariables } from '../types';++/** A credential the model may inject into a sandbox, as the creds prompt lists it. */+export type CredentialSummary = CredSummary;++/** The subset of an agent row the builder and management contexts read. */+export interface AgentDefinitionFacts {+ avatar?: string | null;+ backgroundColor?: string | null;+ chatConfig?: LobeAgentChatConfig | null;+ description?: string | null;+ model?: string | null;+ name?: string | null;+ openingMessage?: string | null;+ openingQuestions?: string[] | null;+ params?: Record<string, unknown> | null;+ /** Pinned plugin identifiers only (disabled entries excluded). */+ plugins?: string[] | null;+ provider?: string | null;+ systemRole?: string | null;+ tags?: string[] | null;+ title?: string | null;+}++export interface GroupFacts {+ config?: { openingMessage?: string | null; openingQuestions?: string[] | null } | null;+ /** The group's shared prompt / description. */+ content?: string | null;+ members: {+ agentId: string;+ description?: string | null;+ role: 'supervisor' | 'participant';+ title?: string | null;+ }[];+ title?: string | null;+}++export interface TopicFacts {+ agentId?: string | null;+ groupId?: string | null;+ historySummary?: string | null;+ id: string;+ /** Who started the topic; share-visitor topics are keyed by this. */+ senderId?: string | null;+ title?: string | null;+}++export interface PlanDocumentFacts {+ content?: string | null;+ createdAt: string;+ description?: string | null;+ id: string;+ metadata?: { todos?: unknown } | null;+ title?: string | null;+ updatedAt: string;+}++/**+ * Everything the gathering rules read about the run. Assembled by the host+ * from the runtime state (server) or the stores (browser); the rules never+ * read a store or a database themselves.+ */+export interface ContextFactRequest {+ /** Device routed for this step, after the single-track device gate. */+ activeDeviceId?: string;+ agent: {+ chatConfig?: LobeAgentChatConfig | null;+ description?: string | null;+ slug?: string | null;+ title?: string | null;+ };+ /** Executing agent row id. */+ agentId?: string;+ /** Plugin identifiers the agent explicitly disabled (tri-state entries). */+ disabledPluginIds?: string[];+ /** Agent being edited in the Profile panel, when the agent builder is active. */+ editingAgentId?: string;+ /** Group being edited in the group Profile panel, when the group builder is active. */+ editingGroupId?: string;+ /** Tool ids enabled for this step, after resolution. */+ enabledToolIds: string[];+ /** Effective execution target off the plan, when resolved. */+ executionTarget?: string;+ /** Which connector families this deployment offers. */+ features: { composio: boolean; lobehubSkill: boolean };+ /** Agents the user @-mentioned in the turn. */+ mentionedAgents?: RuntimeMentionedAgent[];+ /** Conversation as the engine will see it (history hints already applied). */+ messages: UIChatMessage[];+ /** Present only on a shared-agent visitor run. */+ shareVisitor?: Pick<AgentShareVisitorContext, 'agentId' | 'visitorUserId'>;+ topicId?: string;+ workspaceId?: string;+}++/**+ * How a host fetches facts. Every method is optional: a host that cannot+ * answer one (a CLI without a market account, a browser without a+ * connector catalog) simply leaves the fact out. Providers are called with+ * the rules already applied β a provider is only invoked when the run+ * needs that fact β and may throw; the gatherer treats a failure as "no+ * fact" and never blocks the turn.+ */+export interface ContextFactProviders {+ /** A topic by id, or null when the caller may not see it. */+ findTopic?: (topicId: string) => Promise<TopicFacts | null | undefined>;+ /** The agent row the builder or group builder is editing. */+ getAgentDefinition?: (agentId: string) => Promise<AgentDefinitionFacts | null | undefined>;+ getGroup?: (groupId: string) => Promise<GroupFacts | null | undefined>;+ /** Persona / SOUL / initial user info for the onboarding agent. */+ getOnboardingContext?: () => Promise<OnboardingContext | null | undefined>;+ /** The topic's plan document, when one exists. */+ getPlanDocument?: (topicId: string) => Promise<PlanDocumentFacts | null | undefined>;+ /**+ * Name and reply language of whoever is conversing. `userId` is the share+ * visitor on a shared-agent run, otherwise undefined for the run's own user.+ */+ getUserInfo?: (userId?: string) => Promise<{ language?: string; username?: string } | undefined>;+ /** Origin and slug that in-app links should resolve against. */+ getWorkspaceContext?: (+ workspaceId?: string,+ ) => Promise<{ appUrl?: string; slug?: string } | undefined>;+ /** Context documents attached to an agent. */+ listAgentDocuments?: (agentId: string) => Promise<AgentContextDocument[] | undefined>;+ /** Connector identifiers (Composio services, LobeHub skill providers) connected for the agent. */+ listConnectedConnectorIds?: (agentId?: string) => Promise<Iterable<string> | undefined>;+ /** Credentials visible in the given scope (workspace-shared inside a workspace). */+ listCredentials?: (scope: { workspaceId?: string }) => Promise<CredentialSummary[] | undefined>;+ /** Plugins beyond the shared catalog (custom connectors) the user may enable. */+ listCustomPlugins?: () => Promise<AvailablePluginInfo[] | undefined>;+ /** Providers and models the user enabled, for the agent-management context. */+ listEnabledProviders?: () => Promise<AvailableProviderInfo[] | undefined>;+ /** Recently used agents, most recent first. */+ listRecentAgents?: (+ limit: number,+ ) => Promise<{ description?: string | null; id: string; title?: string | null }[] | undefined>;+ /** Files synced into the topic's sandbox upload dir. */+ listSandboxFiles?: (topicId: string) => Promise<{ name: string; size?: number }[] | undefined>;+ /** Messages of a referenced topic, oldest first. */+ listTopicMessages?: (+ topic: TopicFacts,+ ) => Promise<{ content: string; role: string }[] | undefined>;+}++export interface GatheredContextFacts {+ agentDocuments?: AgentContextDocument[];+ step: ContextStepSnapshot & { agentManagementContext?: AgentManagementContext };+ variables: ContextVariables;+}diff --git a/packages/mecha/src/contextEngineering/index.ts b/packages/mecha/src/contextEngineering/index.tsindex f2bae540f5b..f2590fcc8bd 100644--- a/packages/mecha/src/contextEngineering/index.ts+++ b/packages/mecha/src/contextEngineering/index.ts@@ -17,6 +17,7 @@ export const runContextEngineering = async (};export { buildMessagesEngineParams } from './buildMessagesEngineParams';+export * from './facts';export type * from './types';export {createVariableGenerators,diff --git a/packages/mecha/src/contextEngineering/variableGenerators.ts b/packages/mecha/src/contextEngineering/variableGenerators.tsindex eb8a74a1c37..6d35627e09c 100644--- a/packages/mecha/src/contextEngineering/variableGenerators.ts+++ b/packages/mecha/src/contextEngineering/variableGenerators.ts@@ -62,6 +62,16 @@ export const createVariableGenerators = ({weekday: () => new Date().toLocaleDateString('en-US', { timeZone: tz, weekday: 'long' }),year: () => timeParts().year,+ // The creds tool's session context renders the calendar date.+ session_date: () =>+ new Intl.DateTimeFormat('en-US', {+ day: 'numeric',+ month: 'long',+ timeZone: tz,+ weekday: 'long',+ year: 'numeric',+ }).format(new Date()),+// --- model ---model: () => model ?? '',provider: () => provider ?? '',diff --git a/packages/mecha/vitest.config.mts b/packages/mecha/vitest.config.mtsindex 940870a78e9..9436de26e58 100644--- a/packages/mecha/vitest.config.mts+++ b/packages/mecha/vitest.config.mts@@ -1,6 +1,16 @@import { defineConfig } from 'vitest/config';export default defineConfig({+ plugins: [+ {+ name: 'raw-md',+ // Builtin tool packages import their README / docs as text; the rules+ // here never read them, so resolve them to an empty module.+ transform(_, id) {+ if (id.endsWith('.md')) return { code: 'export default ""', map: null };+ },+ },+ ],test: {coverage: {reporter: ['text', 'json', 'lcov', 'text-summary'],