Skip to content

🤯 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.

26.7 KB
Raw Blame
import { extractTodosFromMessages, normalizeTodosState } from '@lobechat/agent-runtime';
import { AgentAccountIdentifier } from '@lobechat/builtin-tool-agent-account';
import { AgentBuilderIdentifier } from '@lobechat/builtin-tool-agent-builder';
import { AgentDocumentsIdentifier } from '@lobechat/builtin-tool-agent-documents';
import { AgentManagementIdentifier } from '@lobechat/builtin-tool-agent-management';
import {
  CloudSandboxIdentifier,
  formatSandboxStoragePromptVariables,
  formatUploadedFilesPrompt,
  isPersistentSandboxMode,
} 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 { SkillsIdentifier } from '@lobechat/builtin-tool-skills';
import { WebOnboardingIdentifier } from '@lobechat/builtin-tool-web-onboarding';
import { COMPOSIO_APP_TYPES } from '@lobechat/const';
import {
  type AgentBuilderContext,
  type AgentManagementContext,
  collectDocumentReads,
  type DocumentReferenceItem,
  type GroupAgentBuilderContext,
  type PlanTodoConfig,
  resolveDocumentReferences,
  resolveTopicReferences,
  type RevokedDocumentReads,
  type TopicReferenceItem,
  type WorkspaceContext,
} from '@lobechat/context-engine';
import { agentDisplayName } from '@lobechat/types';
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,
    ),
  );
};

/**
 * Resolve `<refer_document>` tags against the executing agent's documents. A
 * share visitor never reads the creator's documents through a typed tag.
 */
const gatherDocumentReferences = async (
  request: ContextFactRequest,
  providers: ContextFactProviders,
): Promise<DocumentReferenceItem[] | undefined> => {
  // Client-side preprocessing may already have injected the references.
  if (contains(request.messages, ['document_reference_context'])) return undefined;
  if (!contains(request.messages, ['refer_document', 'refer\\_document'])) return undefined;
  const agentId = request.agentId;
  const { findAgentDocument } = providers;
  if (request.shareVisitor || !agentId || !findAgentDocument) return undefined;

  return attempt('documentReferences', () =>
    resolveDocumentReferences(
      request.messages as Array<{ content: string | unknown; role?: string }>,
      (documentId) => findAgentDocument(agentId, documentId),
      // Without the documents tool the agent cannot read an earlier-turn
      // reference on demand, so keep inlining those too.
      { inlineEarlierTurns: !request.enabledToolIds.includes(AgentDocumentsIdentifier) },
    ),
  );
};

/**
 * Documents that earlier turns read and that have since been deleted or
 * disabled. Injection already follows the live bindings; this covers the
 * read results persisted in the conversation. Checked against the agent whose
 * documents the model reads (the edited agent in the agent builder), only when
 * the history holds a document read, and never for a share visitor.
 */
const gatherRevokedDocumentReads = async (
  request: ContextFactRequest,
  providers: ContextFactProviders,
  agentId: string | undefined,
): Promise<RevokedDocumentReads[] | undefined> => {
  const { findRevokedDocumentReads } = providers;
  if (request.shareVisitor || !agentId || !findRevokedDocumentReads) return undefined;

  // In a group topic, other members' reads are judged against their own
  // bindings; everything else against the agent whose documents the model reads.
  const idsByMember = new Map<string | undefined, Set<string>>();
  for (const read of collectDocumentReads(request.messages)) {
    const member =
      read.agentId && read.agentId !== request.agentId && read.agentId !== agentId
        ? read.agentId
        : undefined;
    const ids = idsByMember.get(member) ?? new Set<string>();
    ids.add(read.documentId);
    idsByMember.set(member, ids);
  }
  if (idsByMember.size === 0) return undefined;

  const sets = await Promise.all(
    [...idsByMember].map(async ([member, ids]): Promise<RevokedDocumentReads> => {
      const sortedIds = [...ids].sort();
      let found: Awaited<ReturnType<typeof findRevokedDocumentReads>>;
      try {
        found = await findRevokedDocumentReads(member ?? agentId, sortedIds);
      } catch (error) {
        log('revokedDocumentReads failed, withholding unverified reads: %O', error);
      }
      // Fail closed: without an answer, a deleted document's old body must not
      // slip through, so every read is withheld until the model reads it again.
      if (!found) {
        return { ...(member && { agentId: member }), documentIds: [], unverifiedIds: sortedIds };
      }
      // Sorted so the filtered prefix stays stable whatever order the host returns.
      return {
        ...(member && { agentId: member }),
        agentDocumentReadIds: [...(found.agentDocumentReadIds ?? [])].sort(),
        documentIds: [...(found.documentIds ?? [])].sort(),
      };
    }),
  );

  const hasRevocations = sets.some(
    (set) =>
      set.documentIds.length > 0 ||
      (set.agentDocumentReadIds?.length ?? 0) > 0 ||
      (set.unverifiedIds?.length ?? 0) > 0,
  );
  return hasRevocations ? sets : 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.discoverableTools?.some((tool) => tool.identifier === 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 reachable = new Set([
    ...request.enabledToolIds,
    ...(request.discoverableTools ?? []).map((tool) => tool.identifier),
  ]);
  const connected: ComposioServiceSummary[] = excludeDisabledComposioServices(
    COMPOSIO_APP_TYPES.filter(
      (tool) => connectedIds.has(tool.identifier) && reachable.has(tool.identifier),
    ),
    disabledIdSet,
  ).map((tool) => ({ identifier: tool.identifier, name: tool.label }));
  const available = resolveAvailableComposioServices(
    COMPOSIO_APP_TYPES,
    connectedIds,
    disabledIdSet,
  );
  return generateComposioServicesList(connected, available);
};

/** Builtins the user removed in this scope; a builder must not pin them. */
const gatherUninstalledBuiltinIds = async (providers: ContextFactProviders) => {
  const ids = await attempt('uninstalledBuiltins', () => providers.listUninstalledBuiltinIds?.());
  return ids ? new Set(ids) : undefined;
};

const gatherAgentBuilderContext = async (
  request: ContextFactRequest,
  providers: ContextFactProviders,
): 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, uninstalled] = await Promise.all([
      attempt('connectedConnectors', () => listConnectedConnectorIds?.(editingAgentId)),
      gatherUninstalledBuiltinIds(providers),
    ]);
    const officialTools = listOfficialTools({
      connectedConnectorIds: new Set(connected ?? []),
      enabledPlugins,
      features: request.features,
      uninstalledBuiltinIds: uninstalled,
    });
    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, uninstalled] = await Promise.all([
      attempt('connectedConnectors', () => listConnectedConnectorIds?.(supervisorAgentId)),
      gatherUninstalledBuiltinIds(providers),
    ]);

    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: new Set(connected ?? []),
        enabledPlugins,
        features: request.features,
        uninstalledBuiltinIds: uninstalled,
      }),
      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.
 * - no delegation facts (`availableAgents` / `mentionedAgents`) inside a
 *   sub-agent run: the executor rejects nested `callAgent` there and the
 *   manifest already hides it, so inviting delegation only sends the model
 *   to a tool call that can never succeed.
 */
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';
  const canDelegate = request.isSubAgent !== true;
  let context: AgentManagementContext | undefined;

  if ((isAutoSkillMode || isEnabled) && providers.listRecentAgents) {
    // Self-management (updateAgent / installPlugin on itself) stays available
    // inside a sub-agent, so its own id is kept; only the delegation list goes.
    const currentAgent = request.agentId
      ? {
          id: request.agentId,
          name: request.agent.name ?? undefined,
          title: request.agent.title ?? undefined,
        }
      : undefined;

    if (canDelegate && request.includeRecentAgents !== false) {
      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,
          name: a.name ?? undefined,
          title: a.title ?? 'Untitled',
        })),
        availableAgentsHasMore: others.length > AVAILABLE_AGENTS_LIMIT,
        ...(currentAgent && { currentAgent }),
      };
    } else if (currentAgent) {
      context = { currentAgent };
    }
  }

  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 (canDelegate && 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);
  // Two tools reach the sandbox, and the optional one is not the common case:
  // `lobe-skills` keeps its shell on even for a run without skills, and when no
  // device is routed its runCommand / execScript open the SAME session in the
  // SAME directory as the cloud-sandbox tool. When a device IS routed and the
  // cloud-sandbox tool is not enabled, `lobe-skills` executes on the device and
  // uses `deviceSystemPrompt` (which has no `{{sandbox_workspace}}`
  // placeholder), so no sandbox lookup is needed.
  const sandboxShellEnabled =
    sandboxEnabled ||
    (!request.activeDeviceId && request.enabledToolIds.includes(SkillsIdentifier));

  const tasks = [
    () =>
      attempt('agentDocuments', () =>
        docsAgentId ? providers.listAgentDocuments?.(docsAgentId) : undefined,
      ),
    () =>
      attempt('agentDocumentChanges', () =>
        docsAgentId ? providers.listAgentDocumentChanges?.(docsAgentId) : undefined,
      ),
    () =>
      attempt('agentAccountContext', async () => {
        const context = await providers.listAgentAccountContext?.(request.agentId);
        // Whether this step can actually read or answer mail is decided by the
        // final tool set (custom / goal / chat modes can exclude the account
        // tool), so the identity block must not promise a tool that is absent.
        return context
          ? {
              ...context,
              toolAvailable: request.enabledToolIds.includes(AgentAccountIdentifier),
            }
          : context;
      }),
    () => gatherAgentBuilderContext(request, providers),
    () => gatherAgentManagementContext(request, providers),
    () => gatherComposioServices(request, providers),
    () => gatherCredentials(request, providers),
    () => gatherDocumentReferences(request, providers),
    () => gatherGroupAgentBuilderContext(request, providers),
    () => gatherOnboardingContext(request, providers),
    () => gatherPlanTodo(request, providers),
    () => gatherRevokedDocumentReads(request, providers, docsAgentId),
    () =>
      attempt('sandboxFiles', () =>
        sandboxEnabled && request.topicId
          ? providers.listSandboxFiles?.(request.topicId)
          : undefined,
      ),
    () =>
      attempt('sandboxPersistence', () =>
        sandboxShellEnabled ? providers.resolveSandboxPersistence?.() : 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,
    agentDocumentChanges,
    agentAccountContext,
    agentBuilderContext,
    agentManagementContext,
    composioServicesList,
    credentials,
    documentReferences,
    groupAgentBuilderContext,
    onboardingContext,
    planTodo,
    revokedDocumentReads,
    sandboxFiles,
    sandboxPersistence,
    topic,
    topicReferences,
    userInfo,
    workspaceContext,
  ] = await tupleSettled(tasks);

  return {
    agentDocumentChanges,
    agentDocuments: agentDocuments?.length ? agentDocuments : undefined,
    revokedDocumentReads,
    step: {
      agentAccountContext,
      agentBuilderContext,
      agentManagementContext,
      documentReferences,
      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_name: agentDisplayName(request.agent) ?? '',
      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) : '',
      // Left out entirely for an ephemeral run so the variable generators'
      // fallback renders the original wording; spelling it out here would mean
      // two copies of the same ephemeral text to keep in step.
      // Also for an ephemeral run whose environment checks repositories out:
      // the model is told where they are (see `formatSandboxRepositoriesPrompt`).
      ...(isPersistentSandboxMode(sandboxPersistence?.mode) ||
      sandboxPersistence?.repositories?.length
        ? formatSandboxStoragePromptVariables(sandboxPersistence)
        : {}),
      topic_id: request.topicId ?? '',
      topic_title: topic?.title ?? '',
      username: userInfo?.username ?? '',
    },
  };
};