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.

13.6 KB
Raw Blame
import { AuvManifest } from '@lobechat/builtin-tool-auv';
import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';
import { runtimeManagedToolIds } from '@lobechat/builtin-tools';
import type { GenerateToolsParams, LobeToolManifest } from '@lobechat/context-engine';
import {
  type BuiltinToolResolveContext,
  type DeviceExecutionTarget,
  executionTargetToRuntimeMode,
  type LobeAgentChatConfig,
  type LobeBuiltinTool,
  manifestBaseIdentifier,
  resolveToolMode,
  type ToolExecutor,
  type ToolSource,
} from '@lobechat/types';

import { isDeviceToolIdentifier, REMOTE_DEVICE_TOOL_IDENTIFIERS } from './deviceTools';
import type { ToolRuleDeviceAccess, ToolRuleDeviceFacts } from './types';

export interface InvocationToolIdsRequest {
  /** The run's candidate plugin identifiers (pinned, additional, selected, mention-driven). */
  agentPlugins: readonly string[];
  composioIds?: readonly string[];
  connectorIds?: readonly string[];
  disableLocalSystem?: boolean;
  /** An exact toolset (verify agent, goal supervisor): nothing is added. */
  exclusivePluginIds?: readonly string[];
  lobehubSkillIds?: readonly string[];
}

/**
 * The identifiers handed to the tools engine for this run. Beyond the
 * agent's own candidates, every device tool and every connector-family
 * manifest is a candidate β€” the enable rules decide, and a tool that is not
 * a candidate can never be enabled.
 */
export const resolveInvocationToolIds = (request: InvocationToolIdsRequest): string[] => {
  if (request.exclusivePluginIds) return [...request.agentPlugins];
  return [
    ...new Set([
      ...request.agentPlugins,
      ...(request.disableLocalSystem
        ? []
        : [LocalSystemManifest.identifier, AuvManifest.identifier]),
      RemoteDeviceManifest.identifier,
      ...(request.lobehubSkillIds ?? []),
      ...(request.composioIds ?? []),
      ...(request.connectorIds ?? []),
    ]),
  ];
};

/**
 * Build the initial invocation set. Subsequent explicit activations use the full eligible pool.
 *
 * `lobe-web-browsing` stays preloaded whenever search is enabled: it is the
 * highest-frequency tool in general conversations, its slimmed footprint is small,
 * and deferring it forces an extra activation round-trip plus a prompt-cache wipe
 * on providers that lack mid-conversation tool additions. Turning search off still
 * removes it completely via `resolveToolRules` (`runtimeManagedToolIds`).
 */
export const initialToolSelection = (
  toolIds: string[] | undefined,
  chatConfig?: Pick<LobeAgentChatConfig, 'enableAgentMode' | 'toolMode'> | null,
  skipDefaultTools?: boolean,
): Pick<GenerateToolsParams, 'toolIds' | 'excludeDefaultToolIds' | 'skipDefaultTools'> => {
  const deferCapabilities = !skipDefaultTools && resolveToolMode(chatConfig) === 'agent';
  if (!deferCapabilities) {
    return {
      excludeDefaultToolIds: undefined,
      skipDefaultTools: skipDefaultTools || undefined,
      toolIds,
    };
  }
  const deferredRuntimeToolIds = runtimeManagedToolIds.filter(
    (id) => id !== WebBrowsingManifest.identifier,
  );
  return {
    excludeDefaultToolIds: deferredRuntimeToolIds,
    skipDefaultTools: undefined,
    toolIds: toolIds?.filter((id) => !deferredRuntimeToolIds.includes(id)),
  };
};

export interface DiscoveryPoolRequest {
  /** Builtin tools after the device walls, with their `discoverable` flag. */
  builtinTools: readonly Pick<
    LobeBuiltinTool,
    'discoverable' | 'identifier' | 'manifest' | 'resolveManifest'
  >[];
  /** Disabled-filtered Composio manifests. */
  composio?: readonly LobeToolManifest[];
  /** Gateway device facts; absent without a gateway. */
  device?: Pick<ToolRuleDeviceFacts, 'supportedTools'>;
  deviceAccess?: ToolRuleDeviceAccess;
  /**
   * The run may still reach a device: routed, or device-targeted but not
   * routed yet (the picker is exactly what resolves that). Taken from the
   * execution plan's kind, not from the target β€” an `auto` run with several
   * online machines is unrouted and still needs the picker.
   */
  deviceCapable?: boolean;
  disabledPluginIds?: readonly string[];
  disableLocalSystem?: boolean;
  /** The manifests the engine enabled for the invocation set. */
  enabledManifests: ReadonlyMap<string, LobeToolManifest>;
  exclusivePluginIds?: readonly string[];
  executionTarget: DeviceExecutionTarget;
  /**
   * Installed plugins the run may DISCOVER but must never enable by itself β€”
   * the three-state plugin config's `auto` mode (installed, not pinned, not
   * disabled). They are seeded last and only for identifiers nothing else in
   * the pool already covers, so an enabled manifest, a discoverable builtin
   * or a connector family keeps this run's manifest and routing. Nothing here
   * reaches the enable rules: `enabledToolIds` stays pinned-only, and the
   * activator is the only way one of these becomes callable.
   */
  installedManifests?: readonly LobeToolManifest[];
  /** Disabled-filtered LobeHub skill manifests. */
  lobehubSkills?: readonly LobeToolManifest[];
  /**
   * Runtime context for context-aware builtin manifests β€” the same one the
   * tools engine resolved the enabled set with. A discoverable builtin is
   * activated mid-run from THIS map, so it must be trimmed for the run too
   * (e.g. agent-management drops `callAgent` inside a sub-agent run).
   */
  manifestContext?: BuiltinToolResolveContext;
  /** The page agent edits the open page through the conversation sandbox. */
  pageScope?: boolean;
}

export interface DiscoveryPool {
  /** The single guard every ingest into the pool goes through. */
  /**
   * `baseIdentifier` is a connector row's connector (`manifest.connector`): its
   * tool set follows the connector's exclusive and disabled entries.
   */
  isManifestIngestAllowed: (identifier: string, baseIdentifier?: string) => boolean;
  /** What the activator may discover and enable mid-run. */
  manifestMap: Record<string, LobeToolManifest>;
  /** Which family a discovered tool executes through. */
  sourceMap: Record<string, ToolSource>;
}

/**
 * The pool the activator may resolve tools from mid-run: the enabled
 * manifests, every discoverable builtin the walls allow, the connector
 * families, and the installed plugins the run may activate but not enable on
 * its own. Device and sandbox tools only appear when the run can reach
 * them β€” explicit activation bypasses the enable rules, so what is not
 * reachable must not be discoverable at all.
 */
export const resolveDiscoveryPool = (request: DiscoveryPoolRequest): DiscoveryPool => {
  const { device, deviceAccess, executionTarget } = request;
  const hasDeviceProxy = !!device;
  const disabled = new Set(request.disabledPluginIds ?? []);
  const exclusive = request.exclusivePluginIds ? new Set(request.exclusivePluginIds) : undefined;
  const canUseDevice = deviceAccess?.canUseDevice ?? true;
  const deviceLocked = deviceAccess?.deviceLocked ?? false;

  // A device-LOCKED run keeps local-system but must not expose the picker:
  // leaving it discoverable would let explicit activation re-surface the
  // device list mid-run. Enforced at the ingest layer so no later source
  // can re-add an identifier the walls removed.
  const isManifestIngestAllowed = (identifier: string, baseIdentifier = identifier): boolean => {
    if (exclusive && !exclusive.has(identifier) && !exclusive.has(baseIdentifier)) return false;
    if (disabled.has(identifier) || disabled.has(baseIdentifier)) return false;
    if (
      hasDeviceProxy &&
      identifier === AuvManifest.identifier &&
      !device.supportedTools?.includes(identifier)
    )
      return false;
    if (!canUseDevice && isDeviceToolIdentifier(identifier)) return false;
    if (deviceLocked && REMOTE_DEVICE_TOOL_IDENTIFIERS.has(identifier)) return false;
    return true;
  };

  const manifestMap: Record<string, LobeToolManifest> = {};
  const sourceMap: Record<string, ToolSource> = {};

  // Seed with the invocation set (candidates βˆͺ defaults the engine enabled).
  request.enabledManifests.forEach((manifest, id) => {
    if (isManifestIngestAllowed(id, manifestBaseIdentifier(manifest))) manifestMap[id] = manifest;
  });

  const runtimeMode = executionTargetToRuntimeMode(executionTarget);
  const deviceCapable = request.deviceCapable ?? false;
  // Auto mode lets the model choose the sandbox or the routed device per
  // call, so the sandbox stays discoverable there too.
  const cloudSandboxAllowed =
    runtimeMode === 'cloud' || executionTarget === 'auto' || !!request.pageScope;
  if (!cloudSandboxAllowed) delete manifestMap[CloudSandboxManifest.identifier];
  // A `none` / `sandbox` run behind a gateway must not expose device tools:
  // "no device" means NO device, not "no device yet". Without a gateway the
  // desktop client owns the tool gate and routes in-process.
  const stripDeviceTools = hasDeviceProxy && !deviceCapable;
  if (stripDeviceTools) {
    delete manifestMap[AuvManifest.identifier];
    delete manifestMap[RemoteDeviceManifest.identifier];
    delete manifestMap[LocalSystemManifest.identifier];
  }

  // Discoverable builtins the activator may enable later (e.g. creds, task);
  // `discoverable: false` keeps infrastructure tools out of the listing.
  for (const tool of request.builtinTools) {
    if (!isManifestIngestAllowed(tool.identifier)) continue;
    if (tool.identifier === CloudSandboxManifest.identifier && !cloudSandboxAllowed) continue;
    if (stripDeviceTools && isDeviceToolIdentifier(tool.identifier)) continue;
    if (tool.discoverable === false || manifestMap[tool.identifier]) continue;
    const manifest =
      request.manifestContext && tool.resolveManifest
        ? tool.resolveManifest(request.manifestContext)
        : tool.manifest;
    // A resolver returning `null` opts the tool out of this run entirely.
    if (manifest) manifestMap[tool.identifier] = manifest as LobeToolManifest;
  }

  // Local-system and Computer Use are only `discoverable` on the desktop, so
  // a gateway server injects them explicitly for a `local` target.
  for (const manifest of [LocalSystemManifest, AuvManifest]) {
    if (
      !request.disableLocalSystem &&
      isManifestIngestAllowed(manifest.identifier) &&
      hasDeviceProxy &&
      runtimeMode === 'local' &&
      !manifestMap[manifest.identifier]
    ) {
      manifestMap[manifest.identifier] = manifest as LobeToolManifest;
    }
  }

  // Connector families, with the source the runtime executes them through.
  const ingestFamily = (manifests: readonly LobeToolManifest[], source: ToolSource) => {
    for (const manifest of manifests) {
      if (!isManifestIngestAllowed(manifest.identifier, manifestBaseIdentifier(manifest))) continue;
      if (!manifestMap[manifest.identifier]) manifestMap[manifest.identifier] = manifest;
      sourceMap[manifest.identifier] = source;
    }
  };
  ingestFamily(request.lobehubSkills ?? [], 'lobehubSkill');
  ingestFamily(request.composio ?? [], 'composio');

  // Installed-but-not-pinned plugins (`auto` in the agent's three-state
  // plugin config): discoverable exactly like the client runtime lists them
  // from `installedPlugins`, yet never part of the run's enabled set β€” the
  // activator is what turns one into a callable tool. Seeded last and only
  // where nothing above already answered for the identifier, so a pinned
  // manifest, a discoverable builtin or a connector family always wins.
  for (const manifest of request.installedManifests ?? []) {
    const identifier = manifest?.identifier;
    if (!identifier) continue;
    if (manifestMap[identifier]) continue;
    if (!isManifestIngestAllowed(identifier)) continue;
    manifestMap[identifier] = manifest;
    // Every installed plugin executes through the MCP path, matching the
    // client's own labelling of them.
    sourceMap[identifier] = 'mcp';
  }

  return { isManifestIngestAllowed, manifestMap, sourceMap };
};

export interface ClientExecutorsRequest {
  /** A device gateway exists; tool calls tunnel to a registered device. */
  hasDeviceProxy: boolean;
  manifestMap: Readonly<Record<string, LobeToolManifest>>;
  /** Connectors and installed plugins that run over stdio (a local process). */
  stdioIdentifiers?: readonly string[];
}

/**
 * Tools that must run on the user's machine (local-system, stdio MCP) are
 * marked for direct client dispatch only in the standalone deployment: with a
 * gateway every caller converges on the device-gateway path and the executor
 * stays unset so the remote-device proxy resolves the route.
 *
 * A stdio entry is recognised by being *part of this run's pool*, not by being
 * enabled. The activator can turn a discoverable-but-unpinned plugin into a
 * callable tool mid-run, and `ToolResolver.applyActivation` adds it without
 * re-running this pass β€” an id left out here would be dispatched to the server
 * and run the user's local MCP command there instead of on their machine.
 * Marking the whole pool up front costs nothing: an executor entry for a tool
 * nobody calls is inert, and a share run prunes what it does not grant.
 */
export const resolveClientExecutors = (
  request: ClientExecutorsRequest,
): Record<string, ToolExecutor> => {
  const executorMap: Record<string, ToolExecutor> = {};
  if (request.hasDeviceProxy) return executorMap;
  for (const [id, manifest] of Object.entries(request.manifestMap)) {
    if ((manifest as { executors?: string[] })?.executors?.includes('client'))
      executorMap[id] = 'client';
  }
  for (const id of request.stdioIdentifiers ?? []) {
    if (request.manifestMap[id]) executorMap[id] = 'client';
  }
  return executorMap;
};