π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β»οΈ refactor(server): split the per-step context gathering into fact providers (#19574)
Arvin Xufbd47003da55
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.tsindex ae933ccff62..54c9138f053 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts@@ -1,26 +1,4 @@import type { AgentState, CallLLMPayload } from '@lobechat/agent-runtime';-import { extractTodosFromMessages, normalizeTodosState } from '@lobechat/agent-runtime';-import {- type ComposioServiceSummary,- type CredSummary,- excludeDisabledComposioServices,- generateComposioServicesList,- generateCredsList,- resolveAvailableComposioServices,-} from '@lobechat/builtin-tool-creds';-import { builtinTools } from '@lobechat/builtin-tools';-import { AGENT_PLAN_FILE_TYPE, COMPOSIO_APP_TYPES } from '@lobechat/const';-import type {- AgentBuilderContext,- AgentContextDocument,- GroupAgentBuilderContext,- GroupOfficialToolItem,- OfficialToolItem,- OnboardingContext,- PlanTodoConfig,- WorkspaceContext,-} from '@lobechat/context-engine';-import { resolveTopicReferences } from '@lobechat/context-engine';import type { ChatStreamPayload } from '@lobechat/model-runtime';import { SpanStatusCode } from '@lobechat/observability-otel/api';import {@@ -28,28 +6,12 @@ import {CONTEXT_ENGINEERING_SPAN_NAME,tracer as agentRuntimeTracer,} from '@lobechat/observability-otel/modules/agent-runtime';-import { getActivePluginIds, getDisabledPluginIds } from '@lobechat/types';-import { composioEnv } from '@/config/composio';-import { AgentModel } from '@/database/models/agent';-import { ChatGroupModel } from '@/database/models/chatGroup';-import { FileModel } from '@/database/models/file';-import { MessageModel as MessageModelClass } from '@/database/models/message';-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 { serverMessagesEngine } from '@/server/modules/Mecha/ContextEngineering';-import { AgentDocumentsService } from '@/server/services/agentDocuments';-import { MarketService } from '@/server/services/market';-import { OnboardingService } from '@/server/services/onboarding';-import { toAgentContextDocuments } from '@/utils/agentDocumentContextMapping';+import { gatherServerContextFacts } from '@/server/modules/Mecha/ContextEngineering/providers';import type { RuntimeExecutorContext } from '../context';-import { buildPostProcessUrl, log, resolveRuntimeHistoryCount } from '../executorHelpers';-import { loadConnectedComposioIds } from './composioConnectedIds';+import { resolveRuntimeHistoryCount } from '../executorHelpers';import {resolveServerCallLlmContextHints,type ServerCallLlmContextHints,@@ -108,253 +70,20 @@ export const buildServerCallLlmContext = async ({shouldReplayAssistantReasoning,} = contextHints;- // Extract <refer_topic> tags from messages and fetch summaries.- // Skip if messages already contain injected topic_reference_context- // (e.g., from client-side contextEngineering preprocessing) to avoid double injection.- let topicReferences;- 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) {- const topicModel = new TopicModel(ctx.serverDB, ctx.userId, ctx.workspaceId);- const messageModel = new MessageModelClass(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- );- };- topicReferences = await 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) },- );- },- );- }-- // Fetch agent documents for context injection.- // A share visitor run never sees the creator's agent context 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.- const agentDocumentsAllowedForShare = !ctx.agentShareVisitor;- let agentDocuments: AgentContextDocument[] | undefined;const agentId = state.origin?.agentId;- if (agentId && ctx.serverDB && ctx.userId && agentDocumentsAllowedForShare) {- try {- const agentDocService = new AgentDocumentsService(- ctx.serverDB,- ctx.userId,- state.origin?.workspaceId ?? ctx.workspaceId,- );- const docs = await agentDocService.getAgentContextDocuments(agentId);- if (docs.length > 0) {- agentDocuments = toAgentContextDocuments(docs);- log('Resolved %d agent documents for agent %s', agentDocuments.length, agentId);- }- } catch (error) {- log('Failed to resolve agent documents for agent %s: %O', agentId, error);- }- }-- // Detect onboarding agent and build context injection.- let onboardingContext: OnboardingContext | undefined;- const isOnboardingAgent =- agentConfig?.slug === 'web-onboarding' ||- resolved.enabledToolIds.includes('lobe-web-onboarding');- 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>')- );+ 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,});- // Onboarding context is the creator's own persona, SOUL document and initial- // user info β 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.- const onboardingContextAllowedForShare = !ctx.agentShareVisitor;-- if (- isOnboardingAgent &&- onboardingContextAllowedForShare &&- !alreadyHasOnboardingContext &&- ctx.serverDB &&- ctx.userId- ) {- try {- const { formatWebOnboardingStateMessage } =- await import('@lobechat/builtin-tool-web-onboarding/utils');- const onboardingService = new OnboardingService(ctx.serverDB, ctx.userId);- const docService = new AgentDocumentsService(- ctx.serverDB,- ctx.userId,- state.origin?.workspaceId ?? ctx.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;- }),- ]);-- onboardingContext = {- discoveryUserMessageCount: onboardingState.discoveryUserMessageCount,- personaContent: persona?.persona ?? null,- phaseGuidance: formatWebOnboardingStateMessage(onboardingState),- remainingDiscoveryExchanges: onboardingState.remainingDiscoveryExchanges,- soulContent: soulDoc?.content ?? null,- userInfo,- };- log('Built onboarding context for agent %s, phase: %s', agentId, onboardingState.phase);- } catch (error) {- log('Failed to build onboarding context: %O', error);- }- }-- // Build additional placeholder variables 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 needing a separate context injector.- const lobehubSkillAgentId = state.origin?.agentId;- const lobehubSkillTopicId = ctx.topicId ?? state.origin?.topicId;- const lobehubSkillAgentMeta = state.world?.agent as- { description?: string | null; title?: string | null } | undefined;-- let lobehubSkillTopicTitle = '';- if (lobehubSkillTopicId && ctx.serverDB && ctx.userId) {- try {- const topicModelForLobehub = new TopicModel(ctx.serverDB, ctx.userId, ctx.workspaceId);- const topicRecord = await topicModelForLobehub.findById(lobehubSkillTopicId);- lobehubSkillTopicTitle = topicRecord?.title ?? '';- } catch (error) {- log('Failed to load topic title for lobehub skill placeholders: %O', error);- }- }-- const lobehubSkillVariables: Record<string, string> = {- agent_description: lobehubSkillAgentMeta?.description ?? '',- agent_id: lobehubSkillAgentId ?? '',- agent_title: lobehubSkillAgentMeta?.title ?? '',- topic_id: lobehubSkillTopicId ?? '',- topic_title: lobehubSkillTopicTitle,- };-- // Tool-specific template variable resolution. The client-side- // contextEngineering.ts resolves these via Zustand stores and lambdaClient.- // In execAgent (server/bot) mode we must fetch from DB directly.- //- // `{{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 here 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.- let serverUsername = '';- let serverLanguage = '';- const userInfoUserId = ctx.agentShareVisitor?.visitorUserId ?? ctx.userId;- if (ctx.serverDB && userInfoUserId) {- try {- const userInfo = await UserModel.getInfoForAIGeneration(ctx.serverDB, userInfoUserId);- serverUsername = userInfo.userName;- serverLanguage = userInfo.responseLanguage;- } catch (error) {- log('Failed to fetch user info for {{username}}/{{language}} substitution: %O', error);- }- }-- // Where the run lives β app origin + workspace slug β so the model can- // write in-app links that resolve to the right scope. `workspaceId` is only- // threaded through for DB scoping otherwise, so 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 and- // never blocks the LLM call.- const workspaceContext = await resolveWorkspaceContext(ctx, state);-- const sandboxEnabled = String(resolved.enabledToolIds.includes('lobe-cloud-sandbox'));- // `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).- const credsSandboxReachable = String(!activeDeviceId || executionTarget === 'auto');- let sandboxUploadedFiles = '';- if (sandboxEnabled === 'true' && ctx.serverDB && ctx.userId && lobehubSkillTopicId) {- try {- const { formatUploadedFilesPrompt } = await import('@lobechat/builtin-tool-cloud-sandbox');- const fileModel = new FileModel(ctx.serverDB, ctx.userId);- const uploadedFiles = await fileModel.findFilesToInitInSandbox(lobehubSkillTopicId);- sandboxUploadedFiles = formatUploadedFilesPrompt(uploadedFiles);- } catch (error) {- log('Failed to resolve files for {{sandbox_uploaded_files}} substitution: %O', error);- }- }-const sessionDate = new Intl.DateTimeFormat('en-US', {day: 'numeric',month: 'long',@@ -362,313 +91,15 @@ export const buildServerCallLlmContext = async ({weekday: 'long',year: 'numeric',}).format(new Date());-const memoryEffort = String(agentConfig.chatConfig?.memory?.effort ?? '');- const messageTodos = extractTodosFromMessages(messagesForContext);- let planTodo: PlanTodoConfig | undefined =- messageTodos !== undefined ? { enabled: true, todos: messageTodos } : undefined;-- if (- messageTodos === undefined &&- resolved.enabledToolIds.includes('lobe-agent') &&- lobehubSkillTopicId &&- ctx.serverDB &&- ctx.userId- ) {- try {- const topicDocumentModel = new TopicDocumentModel(- ctx.serverDB,- ctx.userId,- state.origin?.workspaceId ?? ctx.workspaceId,- );- const [planDocument] = await topicDocumentModel.findByTopicId(lobehubSkillTopicId, {- type: AGENT_PLAN_FILE_TYPE,- });- if (planDocument) {- const todos = normalizeTodosState(- planDocument.metadata?.todos,- planDocument.updatedAt.toISOString(),- );- if (todos !== undefined) planTodo = { enabled: true, todos };- }- } catch (error) {- log('Failed to resolve plan TODO context for topic %s: %O', lobehubSkillTopicId, error);- }- }-- let credsListStr = '';- if (ctx.userId) {- 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 userModel = new UserModel(ctx.serverDB, ctx.userId);- const settings = await userModel.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 },- });- // Inside a workspace, the agent must only see the workspace's shared- // organization credentials β personal creds are not visible here.- const credsResult = ctx.workspaceId- ? await marketService.market.organizations.creds({ workspaceId: ctx.workspaceId }).list()- : await marketService.market.creds.list();- const userCreds = (credsResult as any)?.data ?? [];- credsListStr = generateCredsList(- userCreds.map((cred: any): CredSummary => ({- description: cred.description,- key: cred.key,- name: cred.name,- ownerDisplayName: cred.ownerDisplayName,- ownerType: cred.ownerType,- type: cred.type,- })),- );- log('Fetched %d creds for {{CREDS_LIST}} substitution', userCreds.length);- } catch (error) {- log('Failed to fetch creds for {{CREDS_LIST}} substitution: %O', error);- }- }-- let composioServicesListStr = '';- if (ctx.serverDB && ctx.userId && !!composioEnv.COMPOSIO_API_KEY) {- try {- // Connected = ACTIVE Composio connections across BOTH the legacy plugin- // projection AND the connector table (agent-scoped connections live only- // in the latter β see loadConnectedComposioIds).- const connectedIds = await loadConnectedComposioIds(- ctx.serverDB,- ctx.userId,- ctx.workspaceId,- agentId,- );- // Disabled services are dropped from both lists β not surfaced as- // "connected, use directly" nor as "available to connect".- let disabledIdSet = new Set<string>();- if (agentId) {- const agentModel = new AgentModel(ctx.serverDB, ctx.userId, ctx.workspaceId);- const agentConfig = await agentModel.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,- );- composioServicesListStr = generateComposioServicesList(connected, available);- log(- 'Fetched Composio services for {{COMPOSIO_SERVICES_LIST}}: connected=%d, available=%d',- connected.length,- available.length,- );- } catch (error) {- log(- 'Failed to fetch Composio services for {{COMPOSIO_SERVICES_LIST}} substitution: %O',- error,- );- }- }-- let agentBuilderContext: AgentBuilderContext | undefined;- const editingAgentId = state.metadata?.editingAgentId;- if (editingAgentId && ctx.serverDB && ctx.userId) {- try {- const editingAgentModel = new AgentModel(ctx.serverDB, ctx.userId, ctx.workspaceId);- const editingConfig = (await editingAgentModel.getAgentConfigById(editingAgentId)) as Record<- string,- any- > | null;- if (editingConfig) {- const enabledPlugins: string[] = getActivePluginIds(- Array.isArray(editingConfig.plugins) ? editingConfig.plugins : undefined,- );- 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 {- // Agent-scoped connections aren't in the plugin table β union the- // connector table so the builder marks them installed too.- const connectedComposioIds = await loadConnectedComposioIds(- ctx.serverDB,- ctx.userId,- ctx.workspaceId,- editingAgentId,- );- 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 agentBuilderContext: %O', composioError);- }- }-- agentBuilderContext = {- 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);- }- }-- // Group Agent Builder β mirrors the block above for the group Profile panel.- // Without this 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 β built-in group agents were missing from the member list.- let groupAgentBuilderContext: GroupAgentBuilderContext | undefined;- const editingGroupId = state.metadata?.editingGroupId;- if (editingGroupId && ctx.serverDB && ctx.userId) {- 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) {- const supervisorAgentId = roster.find((member) => member.role === 'supervisor')?.agentId;-- let supervisorConfig: GroupAgentBuilderContext['supervisorConfig'];- let enabledPlugins: string[] = [];- if (supervisorAgentId) {- const supervisorModel = new AgentModel(ctx.serverDB, ctx.userId, ctx.workspaceId);- const supervisor = await supervisorModel.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 composioIdentifiers = new Set(COMPOSIO_APP_TYPES.map((tool) => tool.identifier));- const groupOfficialTools: GroupOfficialToolItem[] = [];-- for (const tool of builtinTools) {- if (tool.hidden) continue;- if (composioIdentifiers.has(tool.identifier)) continue;- groupOfficialTools.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(- ctx.serverDB,- ctx.userId,- ctx.workspaceId,- supervisorAgentId,- );- for (const tool of COMPOSIO_APP_TYPES) {- groupOfficialTools.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 groupAgentBuilderContext: %O', composioError);- }- }-- groupAgentBuilderContext = {- 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: groupOfficialTools,- supervisorConfig,- };- }- } catch (error) {- log('Failed to build groupAgentBuilderContext for group %s: %O', editingGroupId, error);- }- }-const contextEngineInput = {additionalContexts: llmPayload.additionalContexts,- agentDocuments,+ agentDocuments: facts.agentDocuments,// Identity lives on the agent row, not in the prompt text β inject it so// the model introduces itself by the user-given name.agentIdentity: { name: agentConfig.name ?? undefined, title: agentConfig.title ?? undefined },- ...(agentBuilderContext && { agentBuilderContext }),+ ...(facts.step.agentBuilderContext && { agentBuilderContext: facts.step.agentBuilderContext }),agentGroup: state.world?.group,agentManagementContext: (state as any).initialContext?.initialContext?.mentionedAgents?.length? {@@ -677,31 +108,26 @@ export const buildServerCallLlmContext = async ({: undefined,additionalVariables: {...state.binding?.device?.systemInfo,- ...lobehubSkillVariables,- COMPOSIO_SERVICES_LIST: composioServicesListStr,- CREDS_LIST: credsListStr,- creds_sandbox_reachable: credsSandboxReachable,- language: serverLanguage,+ ...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.- ...(serverLanguage && { locale: serverLanguage }),+ ...(facts.variables.language && { locale: facts.variables.language }),memory_effort: memoryEffort,- sandbox_enabled: sandboxEnabled,- sandbox_uploaded_files: sandboxUploadedFiles,session_date: sessionDate,- username: serverUsername,},userTimezone: state.world?.userTimezone,capabilities,botPlatformContext: state.world?.channel?.botPlatform,- ...(workspaceContext && { workspaceContext }),+ ...(facts.step.workspaceContext && { workspaceContext: facts.step.workspaceContext }),discordContext: state.world?.channel?.discord,enableExpertise: state.enableExpertise,enableHistoryCount: agentConfig.chatConfig?.enableHistoryCount ?? undefined,evalContext: state.world?.eval,expertise: state.expertise,forceFinish: state.forceFinish,- ...(groupAgentBuilderContext && { groupAgentBuilderContext }),+ ...(facts.step.groupAgentBuilderContext && {+ groupAgentBuilderContext: facts.step.groupAgentBuilderContext,+ }),historyCount: resolveRuntimeHistoryCount(agentConfig.chatConfig?.historyCount),initialContext: (state as any).initialContext?.initialContext,knowledge: {@@ -724,7 +150,7 @@ export const buildServerCallLlmContext = async ({modelDisplayName,modelKnowledgeCutoff,provider,- ...(planTodo && { planTodo }),+ ...(facts.step.planTodo && { planTodo: facts.step.planTodo }),connectorOwnershipNote: state.world?.connectorOwnershipNote,projectInstructions: state.world?.projectInstructions,systemRole: agentConfig.systemRole ?? undefined,@@ -738,8 +164,8 @@ export const buildServerCallLlmContext = async ({skillsConfig: { enabledSkills: resolvedSkills.enabledSkills },}),enableAgentMode: agentConfig.chatConfig?.enableAgentMode,- ...(topicReferences && { topicReferences }),- ...(onboardingContext && { onboardingContext }),+ ...(facts.step.topicReferences && { topicReferences: facts.step.topicReferences }),+ ...(facts.step.onboardingContext && { onboardingContext: facts.step.onboardingContext }),};const processedMessages = await agentRuntimeTracer.startActiveSpan(@@ -807,45 +233,3 @@ export const buildServerCallLlmContext = async ({shouldReplayAssistantReasoning,};};--const getAppUrl = (): string | undefined => {- try {- return appEnv.APP_URL;- } catch {- return process.env.APP_URL;- }-};--const resolveWorkspaceContext = async (- ctx: RuntimeExecutorContext,- state: AgentState,-): 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();- const workspaceId = state.origin?.workspaceId ?? ctx.workspaceId;-- // 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/modules/Mecha/ContextEngineering/providers/__tests__/gatherServerContextFacts.test.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/__tests__/gatherServerContextFacts.test.tsnew file mode 100644index 00000000000..ee19dd361b9--- /dev/null+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/__tests__/gatherServerContextFacts.test.ts@@ -0,0 +1,122 @@+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.tsnew file mode 100644index 00000000000..aaac90dcb71--- /dev/null+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/agentBuilderContext.ts@@ -0,0 +1,66 @@+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.tsnew file mode 100644index 00000000000..1838e67372f--- /dev/null+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/agentDocuments.ts@@ -0,0 +1,36 @@+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.tsnew file mode 100644index 00000000000..bc985d4f324--- /dev/null+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/composioServices.ts@@ -0,0 +1,64 @@+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.tsnew file mode 100644index 00000000000..81c88dd2877--- /dev/null+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/credsList.ts@@ -0,0 +1,55 @@+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.tsnew file mode 100644index 00000000000..cd9f7b18fb8--- /dev/null+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/groupAgentBuilderContext.ts@@ -0,0 +1,85 @@+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.tsnew file mode 100644index 00000000000..5a821b0b07d--- /dev/null+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts@@ -0,0 +1,94 @@+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';++/**+ * 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;++type Settled<T extends readonly (() => Promise<unknown>)[]> = {+ [K in keyof T]: Awaited<ReturnType<T[K]>>;+};++/** `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>>;++/**+ * 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.+ */+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,+ );++ return {+ agentDocuments,+ step: {+ agentBuilderContext,+ groupAgentBuilderContext,+ onboardingContext,+ planTodo,+ topicReferences,+ workspaceContext,+ },+ variables: {+ ...lobehubSkill,+ ...sandbox,+ COMPOSIO_SERVICES_LIST: composioServicesList,+ CREDS_LIST: credsList,+ language: userInfo.language,+ username: userInfo.username,+ },+ };+};diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/lobehubSkillVariables.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/lobehubSkillVariables.tsnew file mode 100644index 00000000000..d660bec5c62--- /dev/null+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/lobehubSkillVariables.ts@@ -0,0 +1,38 @@+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.tsnew file mode 100644index 00000000000..cd7d8e3e490--- /dev/null+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/officialTools.ts@@ -0,0 +1,61 @@+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.tsnew file mode 100644index 00000000000..fa884842383--- /dev/null+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/onboardingContext.ts@@ -0,0 +1,85 @@+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.tsnew file mode 100644index 00000000000..20d5d7a4481--- /dev/null+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/planTodo.ts@@ -0,0 +1,44 @@+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.tsnew file mode 100644index 00000000000..71773a3e8b1--- /dev/null+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/sandboxVariables.ts@@ -0,0 +1,52 @@+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/topicReferences.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/topicReferences.tsnew file mode 100644index 00000000000..8c32f6e2b76--- /dev/null+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/topicReferences.ts@@ -0,0 +1,74 @@+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.tsnew file mode 100644index 00000000000..3c6fa4b03c1--- /dev/null+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/types.ts@@ -0,0 +1,31 @@+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.tsnew file mode 100644index 00000000000..a8a03fdf1bb--- /dev/null+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/userInfoVariables.ts@@ -0,0 +1,30 @@+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.tsnew file mode 100644index 00000000000..ca45a725380--- /dev/null+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/workspaceContext.ts@@ -0,0 +1,54 @@+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;+ }+};