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.

39.7 KB
Raw Blame
import type { AgentRuntimeContext } from '@lobechat/agent-runtime';
import { extractActivatedToolIdsFromMessages } from '@lobechat/agent-runtime';
import { ArtboardIdentifier } from '@lobechat/builtin-tool-artboard';
import { ChannelIdentifier } from '@lobechat/builtin-tool-channel';
import { isGoalPrompt } from '@lobechat/builtin-tool-goal';
import { getShellSyntaxGuidance } from '@lobechat/builtin-tool-local-system';
import { TaskIdentifier } from '@lobechat/builtin-tool-task';
import type {
  LobeToolManifest,
  OperationSkillSet,
  ProjectInstructionFile,
} from '@lobechat/context-engine';
import { buildExpertiseContextSnapshot } from '@lobechat/context-engine';
import type { LobeChatDatabase } from '@lobechat/database';
import type {
  EvalMemoryReference,
  LobeAgentAgencyConfig,
  WorkspaceInitResult,
} from '@lobechat/types';
import { getWorkingDirEffectivePath, RequestTrigger } from '@lobechat/types';
import debug from 'debug';

import type { AgentModel } from '@/database/models/agent';
import { DeviceModel } from '@/database/models/device';
import { ExpertiseModel } from '@/database/models/expertise';
import type { MessageModel } from '@/database/models/message';
import type { TopicModel } from '@/database/models/topic';
import { UserPersonaModel } from '@/database/models/userMemory/persona';
import type { ServerUserMemoryConfig } from '@/server/modules/Mecha/ContextEngineering/types';
import type { AgentDocumentsService } from '@/server/services/agentDocuments';
import { AgentEvalMemoryService } from '@/server/services/agentEvalMemory';
import { deviceGateway } from '@/server/services/deviceGateway';
import { FileService } from '@/server/services/file';
import { redisService } from '@/server/services/redis';
import { afterUnscoped } from '@/server/utils/scheduleAfterResponse';

import { applyEvalGateToToolSet } from '../evalGate';
import { pruneRegeneratedBranch } from '../pruneRegeneratedBranch';
import { resolveDeviceWorkingDirectoryConfig } from '../resolveDeviceWorkingDirectory';
import { applyShareGateToToolSet } from '../shareGate';
import type {
  BindTopicWorkingDirectoryParams,
  ExecRunContext,
  InternalExecAgentParams,
  ResolvedWorkspaceInit,
} from '../types';
import { isWorkspaceCacheFresh, upsertWorkspaceScan } from '../workspaceInitCache';
import { buildArtboardCommentsPrompt } from './artboardContext';
import { deferUnusedSkillsTool, type DeferUnusedSkillsToolParams } from './deferUnusedSkillsTool';
import { buildOperationSkillSet, collectSelectedSkillIds } from './operationSkillSet';
import { buildRunProjectContextPrompt } from './projectContext';
import type { ToolDiscoveryResult } from './toolDiscovery';
import type { RunAttachments } from './turnSetup';
import { buildViewedGoalOverview } from './viewedGoalContext';
import { buildViewedTaskContextPrompt } from './viewedTaskContext';

const log = debug('lobe-server:ai-agent-service');

export interface HistoryLoaderInput {
  appContext?: InternalExecAgentParams['appContext'];
  effectiveResume: boolean;
  existingMessageIds: string[];
  parentMessageId?: string;
  resumeParentMessage: Awaited<ReturnType<MessageModel['findById']>>;
  selfMessageIds: Set<string>;
}

/**
 * Build the cached history loader shared by tool discovery (media-availability
 * probe) and the operation-prep message assembly. Loading is deferred and
 * cached so the run pays the query at most once.
 */
export const createHistoryMessagesLoader = (
  deps: {
    db: LobeChatDatabase;
    isShareVisitorRun: boolean;
    messageModel: MessageModel;
    userId: string;
    workspaceId?: string;
  },
  input: HistoryLoaderInput,
): (() => Promise<any[]>) => {
  const {
    appContext,
    effectiveResume,
    existingMessageIds,
    parentMessageId,
    resumeParentMessage,
    selfMessageIds,
  } = input;

  // Resolve file URLs before visual tool activation checks and context build.
  const fileService = new FileService(deps.db, deps.userId, deps.workspaceId);
  const postProcessUrl = (path: string | null, file: { id?: string | null }) =>
    fileService.getFileAccessUrl({ id: file.id, url: path });
  let historyMessagesCache: any[] | undefined;
  // The run's own topic was resolved and authorized upstream (a share visitor
  // run reaches here through `findVisitorTopicOrThrow`), and it executes under
  // the CREATOR's identity β€” so an AUTHORIZED share run must opt out of
  // `query()`'s creator-facing agent-share exclusion or the agent loses its
  // history. A non-share run must NOT get this opt-out: `turnSetup`'s
  // visitor-topic guard rejects a non-share run whose `appContext.topicId`
  // resolves to a visitor topic, but this loader is cheap defense-in-depth in
  // case that guard is ever bypassed or a future call site skips it β€” without
  // it, a non-share run pointed at a leaked visitor topicId would still load
  // the visitor's transcript into the owner's model context.
  const historyQueryOptions = { allowShareVisitor: deps.isShareVisitorRun, postProcessUrl };
  // Group runs must scope the query by `groupId`: without it `query()` falls
  // into its standard branch (`groupId IS NULL`) and returns none of the group
  // conversation, so a group supervisor's run starts with no history and loses
  // everything derived from it (e.g. cross-operation tool-activation restore).

  return async () => {
    if (historyMessagesCache) return historyMessagesCache;

    if (existingMessageIds.length > 0) {
      const messages = await deps.messageModel.query(
        {
          groupId: appContext?.groupId ?? undefined,
          sessionId: appContext?.sessionId,
          threadId: appContext?.threadId,
          topicId: appContext?.topicId ?? undefined,
        },
        historyQueryOptions,
      );
      const idSet = new Set(existingMessageIds);
      historyMessagesCache = messages.filter((msg) => idSet.has(msg.id));
    } else if (appContext?.topicId) {
      // Follow-up message in existing topic: load all history for context.
      // Exclude the turn we just persisted above (`selfMessageIds`) β€” history
      // must be the PRIOR turns only; the current prompt is appended separately
      // as the in-memory `userMessage`, so leaving it in would double-count it.
      const messages = await deps.messageModel.query(
        {
          groupId: appContext?.groupId ?? undefined,
          sessionId: appContext?.sessionId,
          threadId: appContext?.threadId,
          topicId: appContext?.topicId,
        },
        historyQueryOptions,
      );
      historyMessagesCache = messages.filter((msg) => !selfMessageIds.has(msg.id));
    } else {
      historyMessagesCache = [];
    }

    // ── Regenerate: drop the anchor user message's existing answer branch ──
    // In gateway/server runtime mode the client only sends `parentMessageId`
    // (the user message being regenerated) and lets the server rebuild the
    // context. The topic query above still returns the anchor's *previous*
    // assistant branch (the answer being replaced) and β€” when a middle turn is
    // regenerated β€” the later turns that continued from it. Leaving them in
    // makes the model see an already-answered turn and "continue" it instead of
    // producing a fresh answer (`[U1, A1]` β†’ continue rather than `[U1]` β†’ A2).
    //
    // The branch must be pruned even after `/compact`: compaction hides the
    // grouped messages and `query` returns a synthetic `compressedGroup` node
    // that carries neither `parentId` nor (for compaction) the group's
    // `parentMessageId`, so ancestry can't be walked from `query` output alone.
    // We load the raw message tree (including hidden/compacted messages) and
    // compute the anchor's descendants from it, then drop both regular
    // descendant messages and any group node whose members fall in that branch.
    //
    // Scoped to a `user`-role anchor: the human-approval resume path anchors on
    // a tool message and must keep the in-flight turn (including parallel-tool
    // sibling messages) intact, so it is intentionally left untouched.
    if (
      historyMessagesCache &&
      effectiveResume &&
      parentMessageId &&
      resumeParentMessage?.role === 'user' &&
      appContext?.topicId
    ) {
      const tree = await deps.messageModel.queryTopicMessageTree({
        threadId: appContext.threadId,
        topicId: appContext.topicId,
      });
      historyMessagesCache = pruneRegeneratedBranch(historyMessagesCache, tree, parentMessageId);
    }

    return historyMessagesCache;
  };
};

export interface OperationPrepDeps {
  agentDocumentsService: AgentDocumentsService;
  agentModel: AgentModel;
  bindTopicWorkingDirectory: (params: BindTopicWorkingDirectoryParams) => Promise<void>;
  db: LobeChatDatabase;
  topicModel: TopicModel;
  userId: string;
  workspaceId?: string;
}

export interface OperationPrepInput {
  botPlatformContext?: InternalExecAgentParams['botPlatformContext'];
  /** Tri-state disabled plugin identifiers β€” excluded from the skill pool. */
  disabledPluginIds: string[];
  discovery: ToolDiscoveryResult;
  ephemeralUserMessage?: string;
  /** The only tools an eval attempt may see or call (case environment + infrastructure). */
  evalAllowedTools?: string[];
  /** Isolated Memory scope of an eval trial; persona is read from it, never the caller. */
  evalMemory?: EvalMemoryReference;
  /** Exact toolset requested by the caller (e.g. verify agent, goal supervisor). */
  exclusivePluginIds?: string[];
  globalMemoryEnabled: boolean;
  hasMentionedAgents: boolean;
  loadHistoryMessages: () => Promise<any[]>;
  mentionedAgents?: InternalExecAgentParams['mentionedAgents'];
  /** Deterministic continuation id or the freshly minted `op_…` id. */
  operationId: string;
  runAttachments: RunAttachments;
  runFromHistory: boolean;
  /** Skills this turn's request selected; earlier turns' come from history. */
  selectedSkillIds?: string[];
  /** The Task this run executes; the skills it names are trusted for this run. */
  taskId?: string;
  throwIfExecutionAborted: (stage: string) => Promise<void>;
}

export interface OperationPrepResult {
  activatableToolIds: string[];
  allMessages: any[];
  /** Full manifests of tools this run starts narrowed (`OperationToolSet.deferredManifestMap`). */
  deferredManifestMap?: Record<string, LobeToolManifest>;
  deviceSystemInfo: Record<string, string>;
  expertise?: Awaited<ReturnType<typeof buildExpertiseContextSnapshot>>;
  initialContext: AgentRuntimeContext;
  operationSkillSet?: OperationSkillSet;
  /**
   * A project's root instruction files. Run context, not agent config β€” it
   * travels on the operation like `expertise` does, and the context engine
   * injects it.
   */
  projectInstructions?: ProjectInstructionFile[];
  userMemory?: ServerUserMemoryConfig;
}

/**
 * Resolve the "workspace init" scan (project skills + AGENTS.md) for a run
 * bound to a device's project directory. Reads the cache on
 * `devices.workingDirs[].workspace`, reusing it within the workspace-init TTL;
 * otherwise re-scans the device in one round-trip and writes the result back.
 *
 * Gated on `activeDeviceId` β€” without an online device there is nothing to
 * scan and no current working directory to key the cache on. The web UI reads
 * the same persisted `workingDirs` directly, so it can still render a last-known
 * scan even while the device is offline.
 */
const resolveWorkspaceInit = async (
  deps: OperationPrepDeps,
  params: {
    activeDeviceId: string | undefined;
    agencyConfig?: LobeAgentAgencyConfig;
    /**
     * The device is not online yet (a managed cloud device that is waking).
     * The bound directory still resolves from the persisted rows, but the
     * device is never scanned: only a cached scan is served.
     */
    deviceWaking?: boolean;
    topicId: string;
  },
): Promise<ResolvedWorkspaceInit> => {
  const empty: WorkspaceInitResult = { instructions: [], skills: [] };
  const { activeDeviceId, agencyConfig, deviceWaking, topicId } = params;
  if (!activeDeviceId) return { workspace: empty };

  try {
    // The active device may be personal (userId-scoped) or workspace-owned
    // (workspace-scoped) β€” look up both pools so the bound cwd, project
    // skills, and AGENTS/CLAUDE instructions still resolve for a workspace
    // device. Mirrors the dispatch-side lookup (see `deviceModelForCwd`).
    const deviceModel = new DeviceModel(deps.db, deps.userId, deps.workspaceId);
    const personalDevice = await deviceModel.findByDeviceId(activeDeviceId);
    const workspaceDevice = personalDevice
      ? undefined
      : await deviceModel.findWorkspaceDeviceById(activeDeviceId);
    const device = personalDevice ?? workspaceDevice;
    if (!device) return { workspace: empty };

    // For a workspace-owned device, route the gateway RPC to the
    // `workspace:<id>` principal and persist the scan via the workspace
    // update path β€” otherwise the scan goes through the personal pool
    // (empty result) and the writeback misses the row.
    const deviceWorkspaceId = workspaceDevice ? deps.workspaceId : undefined;

    // The bound project root we scan β€” resolved via the shared precedence
    // helper so it cannot drift from hetero dispatch / topic backfill. Read
    // from the persisted `device.defaultCwd` (not a live device query, which
    // only reports the daemon's process.cwd = `/`); also returned to the
    // caller so the system prompt's {{workingDirectory}} reflects the same
    // bound directory the workspace scan used.
    const topic = await deps.topicModel.findById(topicId);
    const topicWorkingDirectory = topic?.metadata?.workingDirectory;
    const boundCwdConfig = resolveDeviceWorkingDirectoryConfig({
      deviceDefaultCwd: device.defaultCwd,
      deviceId: activeDeviceId,
      devicePlatform: device.platform,
      // A directory that is one of the topic's repos is not a path on this
      // machine β€” skip it (see the resolver) and scan what the device has.
      repos: topic?.metadata?.repos,
      topicDeviceId: topic?.metadata?.boundDeviceId,
      topicWorkingDirectory,
      topicWorkingDirectoryConfig: topic?.metadata?.workingDirectoryConfig,
      workingDirByDevice: agencyConfig?.workingDirByDevice,
    });
    const boundCwd = getWorkingDirEffectivePath(boundCwdConfig);
    if (!boundCwd) {
      // Device-level skills do not require a project. Do not substitute the
      // device's home or daemon cwd, bind a directory, or cache this result as
      // a workingDirs entry (those entries also authorize file-operation roots).
      if (deviceWaking) return { workspace: empty };
      const scanned = await deviceGateway.initWorkspace({
        deviceId: activeDeviceId,
        userId: deps.userId,
        workspaceId: deviceWorkspaceId,
      });
      return { workspace: scanned ?? empty };
    }
    const resolved = {
      boundCwd,
      boundCwdConfig,
      topicDeviceId: topic?.metadata?.boundDeviceId,
      topicWorkingDirectory,
    };

    const workingDirs = device.workingDirs ?? [];
    const cached = workingDirs.find(
      (dir) => dir.path === boundCwd || getWorkingDirEffectivePath(dir) === boundCwd,
    );

    if (deviceWaking) return { ...resolved, workspace: cached?.workspace ?? empty };

    if (isWorkspaceCacheFresh(cached, Date.now()) && cached?.workspace) {
      log('execAgent: reusing cached workspace init for %s', boundCwd);
      return { ...resolved, workspace: cached.workspace };
    }

    // Scan the directory on the device and persist the result back onto
    // `workingDirs` (update in place or prepend a new MRU entry), keeping the
    // JSONB payload bounded. Workspace devices are owned by the workspace, not
    // a userId β€” use the workspace-scoped update path so the writeback lands.
    //
    // Update the MATCHED entry's path, not `boundCwd`: the lookup above can
    // match a source entry by its effective (worktree) path, so a selected
    // worktree reaches here with `boundCwd` = the worktree path while the
    // recorded entry is keyed by the source path. Upserting on `boundCwd`
    // would prepend a bare worktree recent and lose the source/worktree
    // metadata the picker relies on; upsert on the matched source path instead.
    const scanAndPersist = async (): Promise<WorkspaceInitResult | undefined> => {
      const scanned = await deviceGateway.initWorkspace({
        deviceId: activeDeviceId,
        scope: boundCwd,
        userId: deps.userId,
        workspaceId: deviceWorkspaceId,
      });
      if (!scanned) return undefined;

      // Re-read the row before writing: the scan runs for up to 30s, and the
      // user (or another refresh) may have edited `workingDirs` in the
      // meantime. Merging the fresh scan into the CURRENT list keeps those
      // edits instead of overwriting them with the pre-scan snapshot.
      const latest = deviceWorkspaceId
        ? await deviceModel.findWorkspaceDeviceById(activeDeviceId)
        : await deviceModel.findByDeviceId(activeDeviceId);
      const current = latest?.workingDirs ?? workingDirs;

      // The entry this scan refreshes was removed mid-scan. Writing it back
      // would resurrect it β€” and `workingDirs` is the allowlist for device
      // file-operation roots β€” so keep the answer for this turn only.
      if (cached && !current.some((dir) => dir.path === cached.path)) {
        log('execAgent: %s was removed during the scan; skip the writeback', cached.path);
        return scanned;
      }

      const updated = upsertWorkspaceScan(current, cached?.path ?? boundCwd, scanned, Date.now());
      if (deviceWorkspaceId) {
        await deviceModel.updateWorkspaceDevice(activeDeviceId, { workingDirs: updated });
      } else {
        await deviceModel.update(activeDeviceId, { workingDirs: updated });
      }
      log('execAgent: scanned and cached workspace init for %s', boundCwd);
      return scanned;
    };

    // A stale scan still describes the project well enough for this turn:
    // project skills and AGENTS.md change on the order of commits, not sends.
    // Serve it now and refresh after the response, so the user does not wait
    // on a directory walk over the device's WebSocket (up to 30s) just
    // because an hour passed. A directory never scanned still scans inline β€”
    // there is nothing to serve instead.
    //
    // Unscoped on purpose: a sub-agent or group-member run reaches here from
    // inside a step's scheduled-work scope, whose step-boundary flush has a
    // short budget β€” a rescan of this length would stall it. The refresh is
    // not part of the step's settlement, so it goes straight to the host.
    //
    // Claimed before scanning: concurrent sends, sub-agents and group members
    // that read the same stale entry would each schedule their own 30s walk
    // and the same writeback. One of them wins the claim for the length of a
    // scan; the others leave the refresh to it.
    if (cached?.workspace) {
      log('execAgent: serving stale workspace init for %s, refreshing in background', boundCwd);
      afterUnscoped(async () => {
        try {
          if (
            !(await redisService.workspaceRescan.claim({
              userId: deps.userId,
              workspaceId: deviceWorkspaceId,
              deviceId: activeDeviceId,
              cwd: boundCwd,
            }))
          ) {
            log('execAgent: workspace rescan for %s already in flight, skipping', boundCwd);
            return;
          }
          await scanAndPersist();
        } catch (error) {
          log('execAgent: background workspace rescan failed for %s: %O', boundCwd, error);
        }
      });
      return { ...resolved, workspace: cached.workspace };
    }

    const scanned = await scanAndPersist();
    // Scan failed (offline mid-run / parse error) and there is no cache to
    // fall back to: the run proceeds without project skills + instructions.
    return { ...resolved, workspace: scanned ?? empty };
  } catch (error) {
    log('execAgent: resolveWorkspaceInit failed: %O', error);
    return { workspace: empty };
  }
};

/**
 * Stages 9.4–18 of {@link AiAgentService.execAgent}: assemble everything
 * `createOperation` consumes beyond the tool set β€” device system info for
 * prompt placeholders, the agent-management context, user persona memory, the
 * message history + in-memory user message, the base initial runtime context
 * (active document / task manager / mentioned agents), the workspace-init scan
 * (bound cwd + project instructions), the OperationSkillSet, and the learned
 * expertise snapshot.
 *
 * Side effects, all order-preserving with the pre-extraction code: writes the
 * bound cwd onto the returned `deviceSystemInfo`, pins the topic working
 * directory, and merges attachment warnings into `botPlatformContext`. The
 * project instructions come back on the result instead.
 */
export const prepareOperation = async (
  deps: OperationPrepDeps,
  ctx: ExecRunContext,
  input: OperationPrepInput,
): Promise<OperationPrepResult> => {
  /** Filled by the workspace branch below; returned as run context. */
  let projectInstructions: ProjectInstructionFile[] | undefined;
  const {
    agentConfig,
    appContext,
    assistantMessageId,
    model,
    parentMessageId,
    prompt,
    provider,
    resolvedAgentId,
    shareGate,
    topicId,
    userMessageId,
    userMessageMetadata,
  } = ctx;
  const {
    botPlatformContext,
    disabledPluginIds,
    discovery,
    ephemeralUserMessage,
    globalMemoryEnabled,
    hasMentionedAgents,
    loadHistoryMessages,
    mentionedAgents,
    operationId,
    runAttachments,
    runFromHistory,
    throwIfExecutionAborted,
  } = input;
  const {
    activeDeviceId,
    activeDeviceScope,
    agentPlugins,
    executionPlan,
    onlineDevices,
    toolsEngine,
    toolsResult,
    tools,
  } = discovery;

  // 9.4. Fetch device system info for placeholder variable replacement.
  //
  // Decoupled from activeDeviceId routing: pulled into a helper
  // so the device whose info populates the template (`{{hostname}}`,
  // `{{workingDirectory}}`, etc.) is a separate decision from the device
  // that tool calls route to. Today they're aligned β€” but future policy
  // changes (e.g., showing last-known info for an offline bound device)
  // belong in this helper, not in the activeDeviceId resolution block.
  const fetchDeviceSystemInfoForTemplate = async (
    deviceId: string | undefined,
  ): Promise<Record<string, string>> => {
    if (!deviceId) return {};
    try {
      // Tool discovery already asked this device for the same answer earlier
      // in the send window, so the run's fact reader serves it from there
      // (it also owns the personal / workspace scoping of the lookup).
      const systemInfo = await ctx.runFacts.deviceSystemInfo(deviceId, activeDeviceScope);
      if (!systemInfo) return {};
      const device = onlineDevices.find((d) => d.deviceId === deviceId);
      log('execAgent: fetched device system info for %s', deviceId);
      // Devices that don't report defaultShell run an older client whose
      // runner still hardcodes cmd.exe on Windows β€” describe that honestly
      // instead of the new PowerShell default.
      const defaultShell =
        systemInfo.defaultShell ?? (device?.platform === 'win32' ? 'cmd.exe' : '/bin/sh');
      // Optional folders the device could not resolve must stay absent so the
      // template falls back to '(not reported)' instead of rendering undefined.
      const reported = {
        arch: systemInfo.arch,
        defaultShell,
        desktopPath: systemInfo.desktopPath,
        documentsPath: systemInfo.documentsPath,
        downloadsPath: systemInfo.downloadsPath,
        homePath: systemInfo.homePath,
        hostname: device?.hostname ?? 'unknown',
        musicPath: systemInfo.musicPath,
        picturesPath: systemInfo.picturesPath,
        platform: device?.platform ?? 'unknown',
        // Keep the syntax guidance consistent with the shell named above β€”
        // the system role references both placeholders in one sentence.
        shellSyntaxGuidance: getShellSyntaxGuidance(defaultShell),
        userDataPath: systemInfo.userDataPath,
        videosPath: systemInfo.videosPath,
        // `workingDirectory` is intentionally NOT taken from the live device
        // query β€” it only reports the daemon's process.cwd() (= `/` for a
        // Finder/Dock-launched app). The bound directory is resolved from the
        // persisted device row in resolveWorkspaceInit and written onto
        // deviceSystemInfo.workingDirectory at the call site below.
      };
      return Object.fromEntries(
        Object.entries(reported).filter(([, value]) => value !== undefined),
      ) as Record<string, string>;
    } catch (error) {
      log('execAgent: failed to fetch device system info: %O', error);
      return {};
    }
  };

  const deviceSystemInfo = await fetchDeviceSystemInfoForTemplate(activeDeviceId);

  // 9.5. The agent-management context (available agents / providers / plugins)
  // is gathered per step by the shared context rules (`@lobechat/mecha`),
  // together with the @-mentioned agents persisted on `initialContext` below.

  await throwIfExecutionAborted('tool preparation');

  // 10. Fetch user persona for memory injection (reuses globalMemoryEnabled from step 8)
  let userMemory: ServerUserMemoryConfig | undefined;

  // An eval attempt reads its persona from its own Memory entries (the case
  // fixture's), never the caller's. Checking the reference sits outside the
  // best-effort persona fetch: a foreign reference must fail the attempt.
  const evalPersona = input.evalMemory
    ? await new AgentEvalMemoryService(deps.db, deps.userId, deps.workspaceId).getPersonaDocument(
        input.evalMemory,
        { threadId: appContext?.threadId, topicId },
      )
    : undefined;

  if (globalMemoryEnabled) {
    try {
      const persona = input.evalMemory
        ? evalPersona
        : await new UserPersonaModel(deps.db, deps.userId).getLatestPersonaDocument();

      if (persona?.persona) {
        userMemory = {
          fetchedAt: Date.now(),
          memories: {
            contexts: [],
            experiences: [],
            persona: {
              narrative: persona.persona,
              tagline: persona.tagline,
            },
            preferences: [],
          },
        };
        log('execAgent: fetched user persona (version: %d)', persona.version);
      }
    } catch (error) {
      log('execAgent: failed to fetch user persona: %O', error);
    }
  }

  // 11. Get existing messages if provided.
  const historyMessages = await loadHistoryMessages();

  await throwIfExecutionAborted('message history loading');

  // 12. Surface Phase 2 warnings (attachment ingestion/parsing errors) from the
  // shared turn-setup block to the context engine, alongside Phase 1 warnings
  // already on botPlatformContext. The DB user/assistant rows + Agent Signal
  // enqueue all happened in that shared block, before the hetero fork.
  if (runAttachments.warnings.length > 0 && botPlatformContext) {
    const existing = (botPlatformContext as any).warnings as string[] | undefined;
    (botPlatformContext as any).warnings = [...(existing ?? []), ...runAttachments.warnings];
  }

  // Build the in-memory user message for the LLM context (separate from the DB
  // row created above).
  // - imageList: vision models render these as image_url parts
  // - videoList: video-capable models render these as video parts
  // - audioList: audio-capable models render these as audio parts
  // - fileList: MessageContentProcessor injects content via filesPrompts() XML
  // - metadata: the row's persisted metadata, so injectors that read attached
  //   content (selections, local file snapshots) see this turn as they will
  //   see it in history
  const userMessage = {
    audioList: runAttachments.audioList,
    content: ephemeralUserMessage ?? prompt,
    fileList: runAttachments.fileList,
    id: userMessageId,
    imageList: runAttachments.imageList,
    ...(userMessageMetadata && { metadata: userMessageMetadata }),
    role: 'user' as const,
    videoList: runAttachments.videoList,
  };

  // Combine history messages with the user message. An ephemeral message is
  // injected into the LLM context even under runFromHistory (suppressUserMessage)
  // β€” it drives this turn but was never persisted (id is undefined).
  const allMessages =
    runFromHistory && !ephemeralUserMessage ? historyMessages : [...historyMessages, userMessage];

  // Re-check historical activations against this run's tool-mode and model
  // gates. manifestMap is intentionally broader for discovery and must not
  // by itself authorize a tool in chat/custom mode or without function calls.
  const historicalActivatedToolIds = extractActivatedToolIdsFromMessages(allMessages) ?? [];
  const activatableToolIds =
    toolsEngine && historicalActivatedToolIds.length > 0
      ? toolsEngine.generateToolsDetailed({
          context: { isExplicitActivation: true },
          model,
          provider,
          skipDefaultTools: true,
          toolIds: historicalActivatedToolIds,
        }).enabledToolIds
      : [];

  // Final share-gate allowlist enforcement β€” run once here, after every
  // manifest/default/dynamic-activation source (installed plugins, LobeHub
  // Skills, Composio, real-MCP connectors, always-on builtin defaults) has
  // been merged into `toolManifestMap` / `toolsResult.enabledToolIds` /
  // `tools` / `activatableToolIds` by `toolDiscovery` and the historical
  // re-activation pass above. `filterPluginsByShareGate` in `toolDiscovery`
  // only trimmed the initial candidate id list β€” it does not stop
  // `lobe-activator` from dynamically activating (and `ToolExecutionService`
  // from executing, with the CREATOR's credentials) a creator-connected tool
  // that was never in `shareConfig.toolGrants`. Mutates the discovery maps
  // in place, so the `toolSet` handed to `createOperation` is the pruned one.
  if (shareGate) {
    applyShareGateToToolSet(
      {
        activatableToolIds,
        enabledToolIds: toolsResult.enabledToolIds,
        executorMap: discovery.toolExecutorMap,
        manifestMap: discovery.toolManifestMap,
        sourceMap: discovery.toolSourceMap,
        tools,
      },
      shareGate,
    );
  }

  // Eval attempts stay inside the case's environment the same way: whatever
  // discovery merged in (always-on builtins, every plugin the account holds
  // for other cases) is pruned to the attempt's allowlist here, so neither the
  // first step nor a later `lobe-activator` call can reach past it.
  if (input.evalAllowedTools) {
    applyEvalGateToToolSet(
      {
        activatableToolIds,
        enabledToolIds: toolsResult.enabledToolIds,
        executorMap: discovery.toolExecutorMap,
        manifestMap: discovery.toolManifestMap,
        sourceMap: discovery.toolSourceMap,
        tools,
      },
      input.evalAllowedTools,
    );
  }

  log('execAgent: prepared evalContext for executor');

  await throwIfExecutionAborted('operation preparation');

  // 16. Create initial context
  let initialContext: AgentRuntimeContext = {
    payload: {
      // Pass assistant message ID so agent runtime knows which message to update
      assistantMessageId,
      isFirstMessage: true,
      message:
        runFromHistory && !ephemeralUserMessage
          ? [{ content: '' }]
          : [{ content: ephemeralUserMessage ?? prompt }],
      // Pass user message ID as parentMessageId for reference
      parentMessageId: parentMessageId ?? userMessageId ?? '',
      // Include tools for initial LLM call
      tools,
    },
    phase: 'user_input' as const,
    session: {
      messageCount: allMessages.length,
      sessionId: operationId,
      status: 'idle' as const,
      stepCount: 0,
    },
  };

  if (appContext?.scope !== 'page' && appContext?.documentId) {
    // Server is authoritative β€” `(agentId, documentId)` is a unique binding
    // so a single indexed lookup both validates any caller-supplied
    // `agentDocumentId` hint and resolves the row id when one was not
    // provided (covers docs opened outside the active topic, e.g. skills
    // and web docs).
    try {
      const row = await deps.agentDocumentsService.findRowByDocumentId(
        resolvedAgentId,
        appContext.documentId,
      );

      initialContext = {
        ...initialContext,
        initialContext: {
          activeTopicDocument: {
            ...(row?.id ? { agentDocumentId: row.id } : {}),
            documentId: appContext.documentId,
            ...(row?.title ? { title: row.title } : {}),
          },
        },
      };
    } catch (error) {
      log('execAgent: failed to resolve active topic document context: %O', error);
      initialContext = {
        ...initialContext,
        initialContext: {
          activeTopicDocument: {
            documentId: appContext.documentId,
          },
        },
      };
    }
  }

  // Page-scoped context (the viewed task or goal) and the project the run is in.
  // Delegation rules name the task tool, so they follow its presence in the final set.
  const [taskManagerPrompt, goalOverview, projectOverview, artboardComments] = await Promise.all([
    buildViewedTaskContextPrompt(deps, appContext, input.taskId),
    buildViewedGoalOverview(deps, appContext),
    buildRunProjectContextPrompt(deps, appContext?.projectId, resolvedAgentId, {
      channelMessaging: !!toolsResult.enabledToolIds?.includes(ChannelIdentifier),
      coordinationRules: !!toolsResult.enabledToolIds?.includes(TaskIdentifier),
    }),
    toolsResult.enabledToolIds?.includes(ArtboardIdentifier)
      ? buildArtboardCommentsPrompt(deps, appContext?.projectId, topicId)
      : undefined,
  ]);
  const projectPrompt =
    [projectOverview, artboardComments].filter(Boolean).join('\n\n') || undefined;
  if (taskManagerPrompt || goalOverview || projectPrompt) {
    initialContext = {
      ...initialContext,
      initialContext: {
        ...initialContext.initialContext,
        ...(goalOverview && { goalOverview }),
        ...(projectPrompt && { projectContext: { contextPrompt: projectPrompt } }),
        ...(taskManagerPrompt && { taskManager: { contextPrompt: taskManagerPrompt } }),
      },
    };
  }

  // Persist the @-mentioned agents into the runtime initialContext so the
  // context engine injects the delegation context on every step (survives the
  // queue-mode dispatch). The shared context rules fold them into the
  // agent-management context on every step β€” mirrors the client runtime.
  if (hasMentionedAgents) {
    initialContext = {
      ...initialContext,
      initialContext: {
        ...initialContext.initialContext,
        mentionedAgents,
      },
    };
  }

  // On device runs, workspace init discovers home-directory skills. A bound directory
  // also contributes project skills + AGENTS.md up to the repository root;
  // those combined scans are cached on `devices.workingDirs` within the TTL.
  // Without a bound directory, only home skill directories are scanned.
  // Skills surface in `<available_skills>` (metadata only β€” SKILL.md bodies are read lazily at
  // activation via `local-system` readFile, which `serverRuntimes/skills.ts`
  // re-gates on `activeDeviceId`). Only `location` (the absolute SKILL.md
  // path) flows through; the directory tree is enumerated lazily, keeping the
  // op-param payload small.
  // A waking managed device is not bound yet (see `resolveDevicePlan`), but
  // its directory is known from the persisted rows, and the run will reach it.
  const wakingDeviceId =
    executionPlan?.kind === 'device-wakeable' ? executionPlan.deviceId : undefined;
  const workspaceInit = await resolveWorkspaceInit(deps, {
    activeDeviceId: activeDeviceId ?? wakingDeviceId,
    agencyConfig: agentConfig.agencyConfig ?? undefined,
    deviceWaking: !activeDeviceId && !!wakingDeviceId,
    topicId,
  });

  // Feed the bound directory (resolved from the persisted device row) into
  // the local-system tool's {{workingDirectory}} placeholder β€” the channel
  // the model uses to know where it is and reach for absolute paths β€” and,
  // downstream, the runCommand cwd / search scope (RuntimeExecutors reads
  // state.binding.device.systemInfo.workingDirectory). Resume-safe via the
  // existing deviceSystemInfo plumbing (computeDeviceContext).
  if (workspaceInit.boundCwd) {
    deviceSystemInfo.workingDirectory = workspaceInit.boundCwd;
  }

  // Bind the topic to that very directory. A native (non-hetero) agent
  // routed to a device used to resolve its cwd here for the prompt and the
  // tools, but never write it back β€” so its topics stayed unbound while the
  // run itself executed in the right place. Awaited (not fire-and-forget):
  // the tool layer reads the topic's cwd on the same run.
  await deps.bindTopicWorkingDirectory({
    config: workspaceInit.boundCwdConfig,
    currentDeviceId: workspaceInit.topicDeviceId,
    currentWorkingDirectory: workspaceInit.topicWorkingDirectory,
    deviceId: activeDeviceId ?? wakingDeviceId,
    topicId,
  });

  // Collected for the context engine, which assembles the system message and
  // injects these directly after the persona β€” where this code used to
  // concatenate them. Returning them rather than stamping `agentConfig` keeps
  // run context off the agent's configuration.
  if (workspaceInit.workspace.instructions.length) {
    projectInstructions = workspaceInit.workspace.instructions.map(({ content, path, source }) => ({
      content,
      path,
      source,
    }));
    log(
      'execAgent: injected %d project instruction file(s): %s',
      workspaceInit.workspace.instructions.length,
      workspaceInit.workspace.instructions.map((i) => i.source).join(', '),
    );
  }

  // 18. Build OperationSkillSet via SkillEngine (see `buildOperationSkillSet`).
  const operationSkillSet = await buildOperationSkillSet(deps, {
    activeDeviceId,
    agentConfig,
    agentPlugins,
    autoSkillIds: ctx.autoSkillIds,
    implicitBuiltinSkillIds: discovery.implicitBuiltinSkillIds,
    disabledPluginIds,
    executionPlan,
    prompt,
    resolvedAgentId,
    selectedSkillIds: collectSelectedSkillIds(historyMessages, input.selectedSkillIds),
    shareGate,
    taskId: input.taskId,
    workspaceInit,
  });

  // 18b. A run with no skill to offer starts without the skill APIs of
  // `lobe-skills`; its sandbox shell and `exportFile` stay. The full manifest
  // waits in `deferredManifestMap` until a skill is installed mid-run.
  const skillsToolSet: DeferUnusedSkillsToolParams['toolSet'] = {
    activatableToolIds,
    enabledToolIds: toolsResult.enabledToolIds,
    executorMap: discovery.toolExecutorMap,
    manifestMap: discovery.toolManifestMap,
    sourceMap: discovery.toolSourceMap,
    tools,
  };
  if (
    deferUnusedSkillsTool({
      agentChatConfig: agentConfig.chatConfig,
      allMessages,
      evalAllowedTools: input.evalAllowedTools,
      exclusivePluginIds: input.exclusivePluginIds,
      isGoalTurn: isGoalPrompt(prompt),
      isShareRun: Boolean(shareGate),
      operationSkillSet,
      toolSet: skillsToolSet,
    })
  ) {
    log('execAgent: deferred the skill APIs of lobe-skills (no skill available or used)');
  }

  // Resolve learned expertise once so every step in this operation uses the exact same snapshot.
  // ContextEngine owns the Lab-controlled injection decision via enableExpertise.
  const expertiseAgentId = appContext?.agentSignal?.agentId ?? resolvedAgentId;
  let expertise;
  // Learned expertise is the caller's account state. An eval attempt sees only
  // what its case declares, so it is left out (its write side, Agent Signal,
  // is suppressed on eval turns as well).
  if (ctx.trigger !== RequestTrigger.Eval) {
    try {
      const expertiseModel = new ExpertiseModel(deps.db, deps.userId, deps.workspaceId);
      expertise = await buildExpertiseContextSnapshot(expertiseModel, expertiseAgentId);
    } catch (error) {
      console.error('Failed to build expertise snapshot for agent:', expertiseAgentId, error);
    }
  }

  return {
    activatableToolIds,
    allMessages,
    deferredManifestMap: skillsToolSet.deferredManifestMap,
    deviceSystemInfo,
    expertise,
    initialContext,
    operationSkillSet,
    projectInstructions,
    userMemory,
  };
};