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.

30.7 KB
Raw Blame
import { AcceptanceEvidenceManifest } from '@lobechat/builtin-tool-acceptance-evidence';
import { LobeActivatorManifest } from '@lobechat/builtin-tool-activator';
import { AgentAccountManifest } from '@lobechat/builtin-tool-agent-account';
import { AgentBuilderManifest } from '@lobechat/builtin-tool-agent-builder';
import {
  AgentDocumentsManifest,
  resolveAgentDocumentsRestrictedManifest,
} from '@lobechat/builtin-tool-agent-documents';
import {
  AgentManagementManifest,
  resolveAgentManagementManifest,
} from '@lobechat/builtin-tool-agent-management';
import {
  agentSignalFeedbackIntentManifest,
  agentSignalReflectionManifest,
  agentSignalReviewManifest,
  agentSignalSkillManagementManifest,
} from '@lobechat/builtin-tool-agent-signal';
import { ArtboardManifest } from '@lobechat/builtin-tool-artboard';
import { AttachmentsManifest } from '@lobechat/builtin-tool-attachments';
import { AuvManifest } from '@lobechat/builtin-tool-auv';
import { BriefManifest } from '@lobechat/builtin-tool-brief';
import { BrowserManifest } from '@lobechat/builtin-tool-browser';
import { CalculatorManifest } from '@lobechat/builtin-tool-calculator/manifest';
import { CanvasManifest } from '@lobechat/builtin-tool-canvas';
import { ChannelManifest } from '@lobechat/builtin-tool-channel';
import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
import { CredsManifest } from '@lobechat/builtin-tool-creds';
import { DashboardManifest } from '@lobechat/builtin-tool-dashboard';
import {
  GoalManifest,
  GoalReportManifest,
  GoalSupervisorManifest,
} from '@lobechat/builtin-tool-goal';
import { GroupAgentBuilderManifest } from '@lobechat/builtin-tool-group-agent-builder';
import { GroupManagementManifest } from '@lobechat/builtin-tool-group-management';
import { ImageGenerationManifest } from '@lobechat/builtin-tool-image-generation';
import { KnowledgeBaseManifest } from '@lobechat/builtin-tool-knowledge-base';
import { LobeAgentManifest, resolveLobeAgentManifest } from '@lobechat/builtin-tool-lobe-agent';
import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
import { McpEventsManifest } from '@lobechat/builtin-tool-mcp-events';
import { MemoryManifest, resolveMemoryRestrictedManifest } from '@lobechat/builtin-tool-memory';
import { MessageManifest, resolveMessageManifest } from '@lobechat/builtin-tool-message';
import { PageAgentManifest } from '@lobechat/builtin-tool-page-agent';
import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
import { selfFeedbackIntentManifest } from '@lobechat/builtin-tool-self-iteration';
import { SkillMaintainerManifest } from '@lobechat/builtin-tool-skill-maintainer';
import { SkillStoreManifest } from '@lobechat/builtin-tool-skill-store';
import {
  resolveSkillsManifest,
  resolveSkillsRestrictedManifest,
  SkillsManifest,
} from '@lobechat/builtin-tool-skills';
import { TaskManifest } from '@lobechat/builtin-tool-task';
import { UserInteractionManifest } from '@lobechat/builtin-tool-user-interaction';
import { VerifyToolManifest } from '@lobechat/builtin-tool-verify';
import { VideoGenerationManifest } from '@lobechat/builtin-tool-video-generation';
import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';
import { WebOnboardingManifest } from '@lobechat/builtin-tool-web-onboarding';
import { WebhookManifest } from '@lobechat/builtin-tool-webhook';
import { WorkManifest } from '@lobechat/builtin-tool-work';
import { isDesktop, RECOMMENDED_SKILLS, RecommendedSkillType } from '@lobechat/const';
import {
  type AgentPluginEntry,
  getDisabledPluginIds,
  type LobeAgentChatConfig,
  type LobeBuiltinTool,
  resolveToolMode,
} from '@lobechat/types';

import { resolveCloudSandboxInPageScope } from './pageScope';

/**
 * Default candidates evaluated by the tool enable rules.
 * Shared between frontend (createAgentToolsEngine) and server (createServerAgentToolsEngine).
 */
export const defaultToolIds = [
  LobeActivatorManifest.identifier,
  SkillsManifest.identifier,
  WebBrowsingManifest.identifier,
  KnowledgeBaseManifest.identifier,
  AttachmentsManifest.identifier,
  MemoryManifest.identifier,
  LocalSystemManifest.identifier,
  BrowserManifest.identifier,
  CloudSandboxManifest.identifier,
  AgentDocumentsManifest.identifier,
  TaskManifest.identifier,
  // A runtime media fallback can enable this candidate even without a user pin.
  LobeAgentManifest.identifier,
  CanvasManifest.identifier,
];

/**
 * Builtins enabled by default in Agent mode. The activator loads other tools
 * on demand, and Skills loads skill instructions and carries the sandbox
 * shell. A run with no skill to offer keeps only that shell until a skill
 * arrives (`planSkillsToolDeferral` in `@lobechat/mecha`).
 */
export const alwaysOnToolIds = [LobeActivatorManifest.identifier, SkillsManifest.identifier];

/** Ignore stale picker preferences for fixed infrastructure in ordinary Agent mode.
 * Only use for saved user choices, never for a share allowlist or runtime exclusion. */
export const getUserDisabledToolIds = (
  plugins: AgentPluginEntry[] | undefined,
  chatConfig?: Pick<LobeAgentChatConfig, 'toolMode' | 'enableAgentMode'> | null,
) => {
  const disabled = getDisabledPluginIds(plugins);
  return resolveToolMode(chatConfig) === 'agent'
    ? disabled.filter((id) => !alwaysOnToolIds.includes(id))
    : disabled;
};

/**
 * Tool IDs allowed when the agent runs in chat mode
 * (`chatConfig.enableAgentMode === false`). Each one still passes through
 * its own runtime gate (e.g. knowledge base requires `hasEnabledKnowledgeBases`,
 * memory requires the global memory setting, web-browsing requires search
 * enabled, image/video generation require an explicit pin). This list is the
 * strict outer whitelist.
 *
 * In chat mode, both the server `createServerAgentToolsEngine` and the
 * frontend `createAgentToolsEngine` build their rules from ONLY these
 * identifiers, drop user plugins / `alwaysOnToolIds` entirely (except
 * image/video generation, which are re-enabled only when pinned), and disable
 * `allowExplicitActivation` so the activator can't smuggle other tools in.
 */
export const chatModeAllowedToolIds = [
  AttachmentsManifest.identifier,
  KnowledgeBaseManifest.identifier,
  MemoryManifest.identifier,
  WebBrowsingManifest.identifier,
  ImageGenerationManifest.identifier,
  VideoGenerationManifest.identifier,
];

/**
 * Tool IDs that make up the group supervisor's orchestration toolset:
 * dispatching members (speak / broadcast / delegate / executeAgentTask).
 *
 * These ship only with the builtin `group-supervisor` agent, but a group can
 * run a user's own agent as supervisor (`execGroupAgent` passes the configured
 * supervisor agentId, not the builtin slug). Such a run is verified as the
 * group's supervisor, and the tools engine uses this list β€” the single source
 * of truth β€” to both add these tools to the agent-mode candidate set and enable
 * them. Without it the supervisor has no way to dispatch members and degrades
 * to a single-agent monologue.
 *
 * NOTE: `lobe-group-agent-builder` (member CRUD: searchAgent / inviteAgent /
 * createAgent) is deliberately excluded β€” it has no server runtime registered
 * (`apps/server/.../serverRuntimes`), so advertising it on a server-side
 * supervisor run would throw `Builtin tool "lobe-group-agent-builder" is not
 * implemented` the moment the model called it. Add it back here once a server
 * runtime exists.
 */
export const groupSupervisorToolIds = [GroupManagementManifest.identifier];

/**
 * Tool IDs whose enabled state is decided by runtime / system conditions
 * (e.g. cloud runtime, agent has documents attached, knowledge base configured,
 * desktop gateway available), NOT by the user's plugin selection.
 *
 * The chat-input Tools popover deliberately hides these β€” even in manual
 * skill-activate mode β€” so users don't see a toggle that they can't actually
 * affect (the rules in `AgentToolsEngine.createEnableChecker` would force them
 * back on regardless of UI state).
 *
 * If you change this list, keep it in sync with the `rules` map in
 * `src/server/modules/Mecha/AgentToolsEngine/index.ts` and the matching frontend
 * `src/helpers/toolEngineering/index.ts`.
 */
export const runtimeManagedToolIds = [
  McpEventsManifest.identifier,
  AttachmentsManifest.identifier,
  // Enabled by a runtime rule (`hasIdentityAccount`) rather than by user
  // selection: the identity/inbox state reaches the model as context, so this
  // tool only exists for an agent that actually owns an account.
  AgentAccountManifest.identifier,
  BrowserManifest.identifier,
  CloudSandboxManifest.identifier,
  KnowledgeBaseManifest.identifier,
  LocalSystemManifest.identifier,
  MemoryManifest.identifier,
  RemoteDeviceManifest.identifier,
  WebBrowsingManifest.identifier,
];

/**
 * Master allowlist of builtin tool identifiers a share visitor's run may ever
 * touch, at BOTH the tool-set-assembly layer (server
 * `applyShareGateToToolSet`) and the dispatch layer (server
 * `isShareBlockedDataToolCall`) β€” see
 * `apps/server/src/services/aiAgent/shareGate/`. Also the single source of
 * truth for the agent-owner-facing share settings tool picker, which must
 * show a builtin tool as unavailable-to-visitors rather than let the owner
 * select (and the UI silently confirm) a grant the server gate can never
 * honor.
 *
 * Exported from `@lobechat/builtin-tools` β€” not `apps/server` β€” specifically
 * so the client settings UI can import the exact same Set the server gate
 * enforces, instead of hand-copying identifiers that could drift. This
 * package is already the shared boundary for cross-cutting builtin-tool
 * identifier lists consumed by both the frontend (`createAgentToolsEngine`)
 * and the server (`createServerAgentToolsEngine`) β€” see `defaultToolIds` /
 * `chatModeAllowedToolIds` / `runtimeManagedToolIds` above.
 *
 * DEFAULT-DENY, not default-allow-minus-a-blocklist. A share visitor's run
 * executes with the CREATOR's full credentials, and every builtin runtime
 * defaults to creator-scoped β€” it is written for the creator's own
 * conversation, where "the caller" and "the data owner" are the same person.
 * A share visitor breaks that assumption (caller β‰  data owner), and nothing
 * about a builtin tool's manifest or registration signals whether its
 * runtime happens to re-derive its scope from a model-suppliable argument
 * (unsafe for a visitor) or purely from server-side context like
 * `context.agentId` / `context.operationId` (safe). Under this allowlist, a
 * newly registered builtin tool β€” or a newly added API on an already-allowed
 * one β€” is exposed to a share visitor ONLY once someone explicitly adds it
 * here with file:line evidence for why its runtime cannot resolve to the
 * creator's data outside what this specific share/agent grants.
 *
 * Every entry was verified against its actual server runtime
 * (`apps/server/src/services/toolExecution/serverRuntimes/*`), not just its
 * manifest. For the rationale behind every DENIED identifier
 * (`lobe-agent-management`, `lobe-task`, `lobe-creds`, `lobe-message`,
 * `lobe-skill-store`, `lobe-agent-builder`,
 * `lobe-group-agent-builder`, `lobe-group-management`, `agent-signal-review`,
 * `lobe-user-interaction`,
 * `lobe-local-system`, `lobe-browser`, `lobe-remote-device`, and the hidden system-only self-iteration tools),
 * see the denied-builtins section of
 * `apps/server/src/services/aiAgent/shareGate/README.md`.
 */
export const AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS = new Set<string>([
  CalculatorManifest.identifier,
  WebBrowsingManifest.identifier,
  ImageGenerationManifest.identifier,
  // Like image generation: a visitor run spends the creator's quota, so it still needs the
  // owner's explicit share tool grant, and its charges carry the share `spendOrigin`.
  VideoGenerationManifest.identifier,
  VerifyToolManifest.identifier,
  AcceptanceEvidenceManifest.identifier,
  LobeAgentManifest.identifier,
  // `lobe-cloud-sandbox`: allowed because a share-visitor run gets its own
  // fresh per-topic sandbox session, not the creator's. The `lh` CLI JWT
  // shim that would otherwise mint a creator-scoped token inside the shell
  // is skipped for visitor runs (see `cloudSandbox.ts` /
  // `preprocessLhCommand.ts`), and `lobe-creds` stays denied so
  // `~/.creds/env` is never written into that session either. See the
  // allowed-builtins section of `shareGate/README.md` for the full rationale.
  CloudSandboxManifest.identifier,
  // Data-bearing tools whose whole-identifier grant AND per-API write/always-
  // blocked surface is further narrowed server-side by
  // `DATA_TOOL_ACCESS_RULES` in `shareGate/dataToolRules.ts` β€” being on this allowlist only
  // lets them survive to that narrower gate, it does not itself grant read or
  // write access.
  KnowledgeBaseManifest.identifier,
  MemoryManifest.identifier,
  AgentDocumentsManifest.identifier,
  // `lobe-activator`: never picked in the owner's tool picker β€” it is implied
  // (scoped to `activateTools`) by any tool grant and kept only while the
  // gated set still holds a granted tool to activate. It can only surface
  // manifests from that already-gated set, and its skill fallback re-checks
  // `shareConfig.skillGrants`. See the allowed-builtins section of
  // `shareGate/README.md`.
  LobeActivatorManifest.identifier,
  // `lobe-skills`: a skill-driven agent is broken the moment it is shared
  // without this, since skills are loaded on demand through this tool. It is
  // allowed only in the narrow shape `DATA_TOOL_ACCESS_RULES` gives it β€”
  // `activateSkill` / `readReference` on skills the creator explicitly listed
  // in `shareConfig.skillGrants`, enforced again at load time in the server
  // runtime so the model cannot name a skill outside that list. Every other
  // API of the tool is blocked. See the allowed-builtins section of
  // `shareGate/README.md`.
  SkillsManifest.identifier,
  // `lobe-work`: on in every visitor run without a creator grant (see
  // {@link AGENT_SHARE_IMPLIED_BUILTIN_IDENTIFIERS}). Its runtime takes the run
  // (operation, topic, tool call) from the execution context only, writes under
  // the share scope pinned to the visitor topic (`resolveRunWorkAccessScope`),
  // and changes or deletes only Works this conversation created. Collection images
  // must be the creator's images the visitor conversation produced or showed
  // in a tool result (`resolveAgentWorkCollectionItems`).
  // See the allowed-builtins section of `shareGate/README.md`.
  WorkManifest.identifier,
]);

/**
 * Builtins every share visitor run gets without an owner grant: the server
 * implies their grant (`resolveEffectiveShareToolGrants`) and enables them
 * (`getShareGrantActivatedPluginIds`). The owner share-settings picker leaves
 * them out, since a toggle there would change nothing.
 */
export const AGENT_SHARE_IMPLIED_BUILTIN_IDENTIFIERS = new Set<string>([WorkManifest.identifier]);

/**
 * Subset of {@link AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS} whose server-side
 * data grant is UNCONDITIONALLY `none` β€” surviving the master allowlist only
 * to be blocked outright by `DATA_TOOL_ACCESS_RULES` in
 * `apps/server/src/services/aiAgent/shareGate/dataToolRules.ts`, for every API and no matter
 * what the share config says. There is no knowledge-base or agent-file grant
 * in `AgentShareConfig` at all (see `applyShareGateToAgentConfig`), so a
 * visitor run can never reach the knowledge-base store. Agent Documents is
 * separately narrowed to share-scoped authoring APIs.
 *
 * Memory is deliberately NOT here: its grant is conditional on
 * `allowReadMemory`, so the owner enabling that switch does change what a
 * visitor run can do.
 *
 * Exists so the owner-facing share settings tool picker can render these as
 * permanently unavailable instead of offering a toggle the server will always
 * ignore. `shareGate/dispatch.test.ts` asserts this set stays exactly the set of
 * identifiers `isShareBlockedDataToolCall` blocks under maximal permissions,
 * so relaxing a grant server-side without updating this list fails there
 * rather than silently lying in the UI.
 */
export const AGENT_SHARE_NO_DATA_GRANT_BUILTIN_IDENTIFIERS = new Set<string>([
  KnowledgeBaseManifest.identifier,
]);

const builtinToolRegistry: LobeBuiltinTool[] = [
  {
    discoverable: false,
    hidden: true,
    identifier: AcceptanceEvidenceManifest.identifier,
    manifest: AcceptanceEvidenceManifest,
    type: 'builtin',
  },
  {
    discoverable: false,
    hidden: true,
    identifier: VerifyToolManifest.identifier,
    manifest: VerifyToolManifest,
    type: 'builtin',
  },
  {
    discoverable: false,
    hidden: true,
    identifier: LobeActivatorManifest.identifier,
    manifest: LobeActivatorManifest,
    type: 'builtin',
  },
  {
    discoverable: false,
    hidden: true,
    identifier: SkillsManifest.identifier,
    manifest: SkillsManifest,
    // Context-aware: prefixes exec-class API descriptions with the run's
    // actual execution environment (cloud sandbox as fallback / offline
    // degradation), so the model never assumes they run on the user's machine.
    resolveManifest: resolveSkillsManifest,
    // Agent Share projection: only `activateSkill` / `readReference` survive
    // the gate, so the full five-API systemRole is replaced with one that
    // describes just those two.
    resolveRestrictedManifest: resolveSkillsRestrictedManifest,
    type: 'builtin',
  },
  {
    identifier: SkillStoreManifest.identifier,
    manifest: SkillStoreManifest,
    type: 'builtin',
  },
  {
    discoverable: false,
    hidden: true,
    identifier: SkillMaintainerManifest.identifier,
    manifest: SkillMaintainerManifest,
    type: 'builtin',
  },
  {
    discoverable: false,
    hidden: true,
    identifier: selfFeedbackIntentManifest.identifier,
    manifest: selfFeedbackIntentManifest,
    type: 'builtin',
  },
  {
    discoverable: false,
    hidden: true,
    identifier: agentSignalReviewManifest.identifier,
    manifest: agentSignalReviewManifest,
    type: 'builtin',
  },
  {
    discoverable: false,
    hidden: true,
    identifier: agentSignalReflectionManifest.identifier,
    manifest: agentSignalReflectionManifest,
    type: 'builtin',
  },
  {
    discoverable: false,
    hidden: true,
    identifier: agentSignalFeedbackIntentManifest.identifier,
    manifest: agentSignalFeedbackIntentManifest,
    type: 'builtin',
  },
  {
    discoverable: false,
    hidden: true,
    identifier: agentSignalSkillManagementManifest.identifier,
    manifest: agentSignalSkillManagementManifest,
    type: 'builtin',
  },
  {
    discoverable: isDesktop,
    hidden: true,
    identifier: BrowserManifest.identifier,
    manifest: BrowserManifest,
    type: 'builtin',
  },
  {
    discoverable: isDesktop,
    hidden: true,
    identifier: AuvManifest.identifier,
    manifest: AuvManifest,
    type: 'builtin',
  },
  {
    discoverable: isDesktop,
    hidden: true,
    identifier: LocalSystemManifest.identifier,
    manifest: LocalSystemManifest,
    type: 'builtin',
  },
  {
    hidden: true,
    identifier: MemoryManifest.identifier,
    manifest: MemoryManifest,
    resolveRestrictedManifest: resolveMemoryRestrictedManifest,
    type: 'builtin',
  },
  {
    hidden: true,
    identifier: WebBrowsingManifest.identifier,
    manifest: WebBrowsingManifest,
    type: 'builtin',
  },
  {
    hidden: true,
    identifier: CloudSandboxManifest.identifier,
    manifest: CloudSandboxManifest,
    resolveManifest: resolveCloudSandboxInPageScope(CloudSandboxManifest),
    type: 'builtin',
  },
  {
    identifier: AgentDocumentsManifest.identifier,
    manifest: AgentDocumentsManifest,
    resolveRestrictedManifest: resolveAgentDocumentsRestrictedManifest,
    type: 'builtin',
  },
  {
    identifier: CredsManifest.identifier,
    manifest: CredsManifest,
    type: 'builtin',
  },
  {
    // Runtime-managed: enabled only when the agent owns an account, so it is
    // not a user-facing row and not an always-on tool.
    hidden: true,
    identifier: AgentAccountManifest.identifier,
    manifest: AgentAccountManifest,
    type: 'builtin',
  },
  {
    hidden: true,
    identifier: McpEventsManifest.identifier,
    manifest: McpEventsManifest,
    type: 'builtin',
  },
  {
    // On demand: hidden from the Tools popover and absent from the defaults, but discoverable, so
    // the activator enables it when the user asks about this agent's webhooks. The `webhook`
    // flag removes it from the pool (`featureGates.ts`); share visitors never reach it (not in
    // AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS: it creates entry points that run as the creator).
    hidden: true,
    identifier: WebhookManifest.identifier,
    manifest: WebhookManifest,
    type: 'builtin',
  },
  {
    // On demand: hidden and absent from the defaults, but discoverable, so the activator enables
    // it when the agent has a collection or a published link to show. A share visitor's run gets it
    // without a creator grant (see `shareGate/grants.ts`): its Works stay in the visitor's topic.
    hidden: true,
    identifier: WorkManifest.identifier,
    manifest: WorkManifest,
    type: 'builtin',
  },
  {
    hidden: true,
    identifier: KnowledgeBaseManifest.identifier,
    manifest: KnowledgeBaseManifest,
    type: 'builtin',
  },
  {
    discoverable: false,
    hidden: true,
    identifier: AttachmentsManifest.identifier,
    manifest: AttachmentsManifest,
    type: 'builtin',
  },
  {
    // Opt-in image generation: chat mode no longer auto-injects it, so the
    // Tools popover must expose a pin/disable control.
    identifier: ImageGenerationManifest.identifier,
    manifest: ImageGenerationManifest,
    type: 'builtin',
  },
  {
    // Opt-in video generation: exposed in the Tools popover so users can pin it.
    identifier: VideoGenerationManifest.identifier,
    manifest: VideoGenerationManifest,
    type: 'builtin',
  },
  {
    discoverable: false,
    hidden: true,
    identifier: PageAgentManifest.identifier,
    manifest: PageAgentManifest,
    type: 'builtin',
  },
  {
    discoverable: false,
    hidden: true,
    identifier: AgentBuilderManifest.identifier,
    manifest: AgentBuilderManifest,
    type: 'builtin',
  },
  {
    discoverable: false,
    hidden: true,
    identifier: GroupAgentBuilderManifest.identifier,
    manifest: GroupAgentBuilderManifest,
    type: 'builtin',
  },
  {
    discoverable: false,
    hidden: true,
    identifier: GroupManagementManifest.identifier,
    manifest: GroupManagementManifest,
    type: 'builtin',
  },
  {
    hidden: true,
    identifier: AgentManagementManifest.identifier,
    manifest: AgentManagementManifest,
    // Context-aware: hides the `callAgent` API inside sub-agent runs.
    resolveManifest: resolveAgentManagementManifest,
    type: 'builtin',
  },
  {
    identifier: CalculatorManifest.identifier,
    manifest: CalculatorManifest,
    type: 'builtin',
  },
  {
    discoverable: false,
    hidden: true,
    identifier: ChannelManifest.identifier,
    manifest: ChannelManifest,
    type: 'builtin',
  },
  {
    identifier: MessageManifest.identifier,
    manifest: MessageManifest,
    // Context-aware: drops APIs the current IM platform can't fulfil (e.g.
    // WeChat has no `readMessages`), trimming both the tool list and systemRole.
    resolveManifest: resolveMessageManifest,
    type: 'builtin',
  },
  {
    hidden: true,
    identifier: RemoteDeviceManifest.identifier,
    manifest: RemoteDeviceManifest,
    type: 'builtin',
  },
  {
    discoverable: false,
    hidden: true,
    identifier: WebOnboardingManifest.identifier,
    manifest: WebOnboardingManifest,
    type: 'builtin',
  },
  {
    discoverable: false,
    hidden: true,
    identifier: UserInteractionManifest.identifier,
    manifest: UserInteractionManifest,
    type: 'builtin',
  },
  {
    discoverable: false,
    hidden: true,
    identifier: GoalSupervisorManifest.identifier,
    manifest: GoalSupervisorManifest,
    type: 'builtin',
  },
  {
    discoverable: false,
    hidden: true,
    identifier: GoalReportManifest.identifier,
    manifest: GoalReportManifest,
    type: 'builtin',
  },
  {
    // Hidden from the Tools popover (a goal starts from `/goal`), but
    // discoverable so the activator can enable it when the user asks for a goal
    // in plain words or wants a rejected goal proposal redone.
    hidden: true,
    identifier: GoalManifest.identifier,
    manifest: GoalManifest,
    type: 'builtin',
  },
  {
    identifier: TaskManifest.identifier,
    manifest: TaskManifest,
    type: 'builtin',
  },
  {
    identifier: CanvasManifest.identifier,
    manifest: CanvasManifest,
    type: 'builtin',
  },
  {
    // Server tool discovery adds it to project conversations only; it has no
    // client executor, so it must never be pinned or discovered.
    discoverable: false,
    hidden: true,
    identifier: ArtboardManifest.identifier,
    manifest: ArtboardManifest,
    type: 'builtin',
  },
  {
    // Opt-in: pin it in the Tools popover, or the activator enables it when a
    // user asks for monitoring β€” not a default so ordinary turns stay lean.
    identifier: DashboardManifest.identifier,
    manifest: DashboardManifest,
    type: 'builtin',
  },
  {
    discoverable: false,
    hidden: true,
    identifier: BriefManifest.identifier,
    manifest: BriefManifest,
    type: 'builtin',
  },
  {
    identifier: LobeAgentManifest.identifier,
    manifest: LobeAgentManifest,
    // Context-aware: hides the `callSubAgent` API inside group / sub-agent runs.
    resolveManifest: resolveLobeAgentManifest,
    type: 'builtin',
  },
];

/**
 * Hoist each tool's `manifest.meta` identity (title / avatar / description / tags)
 * onto the top level, so context-free consumers (UI lists, discovery, settings,
 * token estimation) read `tool.title` / `tool.avatar` directly instead of reaching
 * into `manifest.meta`. This keeps identity stable and decoupled from `manifest`,
 * which may be produced per-turn by a context-aware `resolveManifest`.
 *
 * Optional chaining is defensive: this runs at module load, and tests routinely
 * mock individual builtin-tool packages (a stubbed manifest may lack `meta`). In
 * production every builtin manifest has a `meta`, so the hoisted fields are real.
 */
export const builtinTools: LobeBuiltinTool[] = builtinToolRegistry.map((tool) => ({
  ...tool,
  avatar: tool.manifest?.meta?.avatar,
  description: tool.manifest?.meta?.description,
  tags: tool.manifest?.meta?.tags,
  title: tool.manifest?.meta?.title,
}));

// A saved pin on a user-selectable tool predates on-demand loading. Runtime additions
// (mentions, media fallback, exact toolsets) are not user preferences and bypass this filter.
export const onDemandBuiltinToolIds = builtinTools
  .filter(
    (tool) =>
      (tool.discoverable !== false || tool.identifier === AuvManifest.identifier) &&
      !alwaysOnToolIds.includes(tool.identifier) &&
      !runtimeManagedToolIds.includes(tool.identifier),
  )
  .map((tool) => tool.identifier);
const onDemandBuiltinIds = new Set(onDemandBuiltinToolIds);

/** An old library uninstall stays in effect until the agent explicitly chooses the tool. */
export const getLegacyDisabledBuiltinToolIds = (
  uninstalled: readonly string[],
  overrides: readonly string[],
) => uninstalled.filter((id) => isOnDemandBuiltinTool(id) && !overrides.includes(id));

/** Agent mode discovers installed builtins by default. Other modes keep their configured toolset. */
export const getUnavailableBuiltinToolIds = (
  available: Iterable<string>,
  chatConfig?: Pick<LobeAgentChatConfig, 'toolMode' | 'enableAgentMode'> | null,
  uninstalled: readonly string[] = [],
  overrides: readonly string[] = [],
) => {
  const legacyDisabled = getLegacyDisabledBuiltinToolIds(uninstalled, overrides);
  if (resolveToolMode(chatConfig) === 'agent') return legacyDisabled;

  const allowed = new Set(available);
  return onDemandBuiltinToolIds.filter((id) => !allowed.has(id) || legacyDisabled.includes(id));
};
export const isOnDemandBuiltinTool = (identifier: string) => onDemandBuiltinIds.has(identifier);

const recommendedBuiltinIds = new Set(
  RECOMMENDED_SKILLS.filter((s) => s.type === RecommendedSkillType.Builtin).map((s) => s.id),
);

/**
 * Non-selectable, non-recommended tools that require installation from the Skill Store.
 * These tools default to uninstalled and must be explicitly installed by the user from the Skill Store.
 */
export const defaultUninstalledBuiltinTools = builtinTools
  .filter(
    (t) =>
      !t.hidden && !isOnDemandBuiltinTool(t.identifier) && !recommendedBuiltinIds.has(t.identifier),
  )
  .map((t) => t.identifier);

/**
 * Minimal view of `settings.tool` covering just the builtin-tool install slots.
 * Typed locally so the helpers accept the loosened shape returned by
 * `getUserState()` while still spreading the rest of `tool` through at runtime.
 */
export interface UninstalledBuiltinToolsScope {
  uninstalledBuiltinTools?: string[];
  uninstalledBuiltinToolsByWorkspace?: Record<string, string[] | undefined>;
}

/**
 * Resolve the uninstalled-builtin-tools list for the active scope.
 *
 * - Personal context (`workspaceId == null`) β†’ the user's personal list.
 * - Workspace context β†’ the per-workspace list; a workspace with no stored
 *   entry falls back to the default seed (a clean default state), never the
 *   user's personal customization.
 *
 * `undefined` (never configured) maps to the default seed in both scopes.
 */
export const resolveUninstalledBuiltinTools = (
  tool: UninstalledBuiltinToolsScope | null | undefined,
  workspaceId?: string | null,
): string[] => {
  const stored = workspaceId
    ? tool?.uninstalledBuiltinToolsByWorkspace?.[workspaceId]
    : tool?.uninstalledBuiltinTools;

  return stored === undefined ? defaultUninstalledBuiltinTools : stored;
};

const builtinIdentifierSet = new Set(builtinTools.map((tool) => tool.identifier));

/**
 * Whether `identifier` belongs to the population
 * {@link AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS} governs β€” the real builtin
 * tool registry above, the same source the server gate
 * (`hasServerRuntime`/`BuiltinToolsExecutor`) resolves against. MCP servers,
 * market plugins, and custom plugins never appear in this registry, so they
 * fall outside this allowlist's jurisdiction entirely.
 */
export const isBuiltinToolIdentifier = (identifier: string): boolean =>
  builtinIdentifierSet.has(identifier);

/**
 * Whether `identifier` would survive the agent-share builtin-tool gate: true
 * for anything outside this allowlist's jurisdiction (MCP/market/custom
 * plugins β€” left entirely to the owner's `enabledToolIds` picker), and for a
 * governed builtin identifier, true only when it is explicitly listed in
 * {@link AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS}.
 *
 * Shared by the server gate (`apps/server/src/services/aiAgent/shareGate/`) and the owner-facing tool picker
 * so both sides agree on exactly which builtin tools a share visitor's run
 * can ever reach.
 */
export const isAgentShareAllowedBuiltinIdentifier = (identifier: string): boolean =>
  !isBuiltinToolIdentifier(identifier) || AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS.has(identifier);