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.

8.3 KB
Raw Blame
import { ActivatorApiName, LobeActivatorIdentifier } from '@lobechat/builtin-tool-activator';
import { AgentDocumentsIdentifier } from '@lobechat/builtin-tool-agent-documents';
import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
import { SkillsIdentifier } from '@lobechat/builtin-tool-skills';
import { AGENT_SHARE_IMPLIED_BUILTIN_IDENTIFIERS } from '@lobechat/builtin-tools';
import {
  hasShareToolGrant,
  resolveShareAllowedSkillIds,
  resolveShareToolGrants,
  type ShareToolGrant,
} from '@lobechat/const';

import { isGovernedByBuiltinAllowlist } from './allowlist';
import { isShareDeviceBuiltin } from './deviceAccess';
import type { AgentShareGate, ShareDataToolPermissions } from './types';

/**
 * Intersect a run's candidate plugin/skill ids with the share whitelist.
 * The whitelist defaults to empty, so an unconfigured share exposes no tools.
 *
 * Identifier-level only: an entry granting just one API
 * (`{ identifier: 'lobe-agent', apis: ['analyzeMedia'] }`) still counts as
 * "this identifier is a
 * candidate" here β€” narrowing the offer down to that specific API happens
 * later, in {@link applyShareGateToToolSet}, once the real manifest is known.
 */
export const filterPluginsByShareGate = (pluginIds: string[], gate: AgentShareGate): string[] => {
  const grants = resolveShareToolGrants(gate.shareConfig.toolGrants);

  // Device builtins (a pinned Computer Use, say) follow the device grant, not
  // the tool picker, exactly as `applyShareGateToToolSet` decides them. The
  // implied builtins need no grant (see `resolveEffectiveShareToolGrants`).
  return pluginIds.filter((id) =>
    isShareDeviceBuiltin(id)
      ? !!gate.canUseDevice
      : AGENT_SHARE_IMPLIED_BUILTIN_IDENTIFIERS.has(id) || hasShareToolGrant(grants, id),
  );
};

/**
 * Intersect a run's candidate SKILL ids with the share's skill grants.
 *
 * Skills are governed by `shareConfig.skillGrants`, not `toolGrants`: a skill
 * grant also authorizes the no-tool path (a pinned skill's body is injected
 * straight into context), so it cannot be expressed as a grant on the
 * `lobe-skills` tool entry. See {@link resolveShareAllowedSkillIds} for the
 * default-closed semantics.
 *
 * Kept next to {@link filterPluginsByShareGate} so the two read as the pair
 * they are; callers must not use the plugin filter for skill ids.
 */
export const filterSkillsByShareGate = (skillIds: string[], gate: AgentShareGate): string[] =>
  resolveShareAllowedSkillIds(skillIds, gate.shareConfig);

/**
 * Builtins whose Share grant is also their runtime opt-in.
 *
 * Agent Documents is a default activatable builtin rather than a profile
 * plugin, so creators have no separate profile switch that could place it in
 * `agentConfig.plugins`. Adding it here only after an explicit Share grant
 * lets the picker act as that opt-in for visitor runs while keeping the
 * default-closed behavior. The final tool-set gate still narrows its APIs.
 *
 * The implied builtins (`lobe-work`) are on in every visitor run with no
 * grant at all: a visitor's Works stay in their own topic (see
 * {@link resolveEffectiveShareToolGrants}).
 */
export const getShareGrantActivatedPluginIds = (gate: AgentShareGate): string[] => {
  const grants = resolveShareToolGrants(gate.shareConfig.toolGrants);

  return [
    ...(hasShareToolGrant(grants, AgentDocumentsIdentifier) ? [AgentDocumentsIdentifier] : []),
    ...AGENT_SHARE_IMPLIED_BUILTIN_IDENTIFIERS,
  ];
};

/**
 * The non-builtin identifiers (MCP servers, Composio and LobeHub Skills
 * connections, installed plugins) a share grants, at any API scope.
 *
 * Tool discovery reads these sources for the creator's whole account, and
 * reading one can decrypt its credentials or call its provider. A share run
 * must only touch what the creator granted, so discovery narrows each source
 * to this set before reading it β€” not just at the final tool-set gate.
 */
export const getShareGrantedExtensionIds = (gate: AgentShareGate): Set<string> =>
  new Set(
    [...resolveShareToolGrants(gate.shareConfig.toolGrants).keys()].filter(
      (identifier) => !isGovernedByBuiltinAllowlist(identifier),
    ),
  );

/**
 * Whether the share grants `lobe-cloud-sandbox` (at any API scope). Drives
 * `resolveExecutionPlan`'s `sandboxFallback`: a visitor can never reach the
 * creator's device, so this grant is only meaningful if the plan resolves to
 * the sandbox instead of collapsing to `none`.
 */
export const shareGateGrantsCloudSandbox = (gate: AgentShareGate): boolean =>
  hasShareToolGrant(
    resolveShareToolGrants(gate.shareConfig.toolGrants),
    CloudSandboxManifest.identifier,
  );

/**
 * Strip agent files / knowledge bases from a share visitor's resolved agent
 * config. Mutates in place β€” `agentConfig` is threaded through the whole
 * orchestration by reference (tool discovery, knowledge flags, context builder
 * snapshot), so a filtered copy would silently diverge.
 *
 * ADAPTATION vs the original design: the share config no longer carries a
 * `filePermissionConfig` field, so there is no grant a creator could set that
 * would expose their agent files or knowledge bases to a visitor. The gate is
 * therefore unconditional rather than conditional β€” the fail-closed reading of
 * "no configured permission". Re-introducing a file grant means restoring the
 * config field AND relaxing this function together.
 */
export const applyShareGateToAgentConfig = (agentConfig: {
  files?: unknown[] | null;
  knowledgeBases?: unknown[] | null;
}): void => {
  agentConfig.files = [];
  agentConfig.knowledgeBases = [];
};

/**
 * Whether this share authorizes any skill at all β€” the condition under which
 * the `lobe-skills` tool itself becomes available to a visitor.
 *
 * Skills are NOT picked in the tool picker, so no creator ever writes a
 * `lobe-skills` entry into `toolGrants`; the skill list IS the opt-in, the same
 * way {@link getShareGrantActivatedPluginIds} lets the Documents grant double as
 * that tool's runtime opt-in. Without this, a share could list skills the
 * visitor's model has no tool to load.
 */
export const hasShareSkillAuthorization = (permissions: ShareDataToolPermissions): boolean =>
  (permissions.skillGrants?.length ?? 0) > 0;

/**
 * `resolveShareToolGrants` plus the grants that are implied rather than picked.
 *
 * - `lobe-skills`, whose opt-in lives in `skillGrants` (see
 *   {@link hasShareSkillAuthorization}). The synthetic grant is toolset-level
 *   (`'all'`) on purpose: narrowing the Skills tool down to its two
 *   visitor-safe APIs is {@link DATA_TOOL_ACCESS_RULES}' job, and expressing it
 *   twice would let the two lists drift.
 * - `lobe-activator`, implied by ANY tool grant or by the device grant
 *   (`canUseDevice`): Computer Use is discoverable, not enabled by default,
 *   so a device-only share needs it to turn that tool on. It is a runtime capability,
 *   not a tool the owner picks, and it can only surface manifests the gated
 *   tool set already holds. Whether a run actually keeps it (only while a
 *   granted tool is left to activate) is decided at assembly in
 *   `applyShareGateToToolSet`. Always written as `activateTools` only, so a
 *   stored or hand-edited `lobe-activator` entry can never widen it to the
 *   runtime's unlisted `activateSkill` method.
 * - `lobe-work` (every {@link AGENT_SHARE_IMPLIED_BUILTIN_IDENTIFIERS} entry),
 *   on in every visitor run: it registers what the visitor run produced as
 *   Works fenced to the visitor topic, never the creator's lists. Added
 *   after the activator check, so it alone never implies the activator: it is
 *   enabled directly (`getShareGrantActivatedPluginIds`), not activated.
 *
 * Every gate that asks "did the creator grant this identifier" must go through
 * here, or the tool passes one layer and is rejected by the next.
 */
export const resolveEffectiveShareToolGrants = (
  permissions: ShareDataToolPermissions,
): Map<string, ShareToolGrant> => {
  const grants = resolveShareToolGrants(permissions.toolGrants);

  grants.delete(LobeActivatorIdentifier);
  if (grants.size > 0 || permissions.canUseDevice) {
    grants.set(LobeActivatorIdentifier, new Set([ActivatorApiName.activateTools]));
  }

  if (hasShareSkillAuthorization(permissions)) grants.set(SkillsIdentifier, 'all');

  for (const identifier of AGENT_SHARE_IMPLIED_BUILTIN_IDENTIFIERS) grants.set(identifier, 'all');

  return grants;
};