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.

♻️ refactor(mecha): decide the tool rules of a run in the shared core (#19604)

Arvin Xu1f311b14b28b
diff --git a/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts b/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts
index e3b21494192..e3dcc3b3d34 100644
--- a/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts
+++ b/apps/server/src/modules/Mecha/AgentToolsEngine/index.ts
@@ -9,44 +9,15 @@
* - Gets model capabilities from provided function
* - No dependency on frontend stores (useToolStore, useAgentStore, etc.)
*/
-import { AuvManifest } from '@lobechat/builtin-tool-auv';
-import { BrowserManifest } from '@lobechat/builtin-tool-browser';
-import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
-import { ImageGenerationManifest } from '@lobechat/builtin-tool-image-generation';
-import { KnowledgeBaseManifest } from '@lobechat/builtin-tool-knowledge-base';
-import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
-import { MemoryManifest } from '@lobechat/builtin-tool-memory';
-import { MessageManifest } from '@lobechat/builtin-tool-message';
-import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
-import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';
-import {
- alwaysOnToolIds,
- builtinTools,
- chatModeAllowedToolIds,
- defaultToolIds,
- groupSupervisorToolIds,
-} from '@lobechat/builtin-tools';
+import { builtinTools } from '@lobechat/builtin-tools';
import { createEnableChecker, type LobeToolManifest } from '@lobechat/context-engine';
import { ToolsEngine } from '@lobechat/context-engine';
-import {
- type BuiltinToolManifest,
- getActivePluginIds,
- type RuntimeEnvMode,
- type RuntimePlatform,
-} from '@lobechat/types';
+import { resolveToolRules } from '@lobechat/mecha';
+import { type BuiltinToolManifest, type RuntimePlatform } from '@lobechat/types';
import debug from 'debug';
-import {
- executionTargetToRuntimeMode,
- isDeviceLockedPlan,
- resolveExecutionTarget,
- resolveToolMode,
-} from '@/helpers/executionTarget';
-import {
- buildAllowedBuiltinTools,
- DEVICE_TOOL_IDENTIFIERS,
- REMOTE_DEVICE_TOOL_IDENTIFIERS,
-} from '@/server/services/aiAgent/deviceToolRegistry';
+import { isDeviceLockedPlan, resolveExecutionTarget } from '@/helpers/executionTarget';
+import { buildAllowedBuiltinTools } from '@/server/services/aiAgent/deviceToolRegistry';
import {
type ServerAgentToolsContext,
@@ -217,193 +188,89 @@ export const createServerAgentToolsEngine = (
} = params;
// Tools that need a user-side execution target (local-system, stdio MCP)
- // run on a device registered with the device-gateway. Desktop, CLI, and
- // bot/IM callers all converge on this single path; the previous Phase 6.4
- // `clientRuntime === 'desktop'` short-circuit (Agent Gateway WS dispatch
- // back to the caller) is removed.
+ // run on a device registered with the device-gateway. Desktop, CLI and
+ // bot/IM callers all converge on this single path.
const hasDeviceProxy = !!deviceContext?.gatewayConfigured;
-
// A server configured with a device-gateway is serving desktop-class users
- // (the unset-target default resolves to `local`); otherwise the caller is
- // treated as web.
+ // (the unset-target default resolves to `local`); otherwise web.
const platform: RuntimePlatform = hasDeviceProxy ? 'desktop' : 'web';
-
- // Tool gate derived from the run's resolved execution plan (sandbox β†’ cloud
- // tools, local β†’ local-system tools, device β†’ gateway). Callers that don't
- // resolve a plan (focused sub-agent engines) fall back to deriving the
- // effective target from agencyConfig.
+ // Prefer the run's resolved plan; callers without one (focused sub-agent
+ // engines) derive the effective target from agencyConfig.
const executionTarget =
executionPlan?.target ??
resolveExecutionTarget(agentConfig.agencyConfig, {
clientExecutionAvailable: platform === 'desktop',
});
- const runtimeMode: RuntimeEnvMode = executionTargetToRuntimeMode(executionTarget);
- // Device tools (local-system, remote-device proxy) only exist for
- // device-capable targets. `none` means NO device β€” the proxy that could
- // activate one mid-run must not be offered either; `sandbox` and devices
- // are mutually exclusive.
- const deviceCapable = executionTarget === 'local' || executionTarget === 'device';
- // The run is locked to ONE device (routed, or explicitly bound but
- // offline): there is no device decision left, so the remote-device picker
- // must not exist β€” physically, not just rule-disabled, because
- // `allowExplicitActivation` lets activator-driven activation bypass the
- // rule gates. Prefer the resolved plan; callers without one (focused
- // sub-agent engines) fall back to the raw device context with the same
- // semantics.
const deviceLocked = executionPlan
? isDeviceLockedPlan(executionPlan)
: !!deviceContext?.autoActivated || !!deviceContext?.boundDeviceId;
- const searchMode = agentConfig.chatConfig?.searchMode ?? 'auto';
- const isSearchEnabled = useApplicationBuiltinSearchTool ?? searchMode !== 'off';
- // Chat mode no longer auto-injects image generation. Opt in by pinning the
- // tool; native imageOutput models never receive the fallback.
- const pinnedPluginIds = getActivePluginIds(agentConfig.plugins);
- const imageGenerationCapable =
- context.isModelSupportToolUse(model, provider) && !modelAbilities?.imageOutput;
- const imageGenerationEnabled =
- imageGenerationCapable && pinnedPluginIds.includes(ImageGenerationManifest.identifier);
- // Tool mode: explicit `toolMode` wins; otherwise derive from `enableAgentMode`
- // (undefined = agent). `custom` = toolset is exactly the agent's plugins.
- const toolMode = resolveToolMode(agentConfig.chatConfig ?? undefined);
- const isChatMode = toolMode === 'chat';
- const isCustomMode = toolMode === 'custom';
+ // The rules β€” mode, per-tool enablement, defaults and the device walls β€”
+ // are shared with the browser through `@lobechat/mecha`; this engine only
+ // assembles the server's facts.
+ const resolved = resolveToolRules({
+ agent: { chatConfig: agentConfig.chatConfig, plugins: agentConfig.plugins },
+ // Gateway facts exist only behind a gateway: without one nothing can
+ // dispatch to a device, so the picker never exists. The policy / plan
+ // walls apply either way.
+ device: hasDeviceProxy
+ ? {
+ autoActivated: deviceContext?.autoActivated,
+ deviceOnline: deviceContext?.deviceOnline,
+ supportedTools: deviceContext?.supportedTools ?? [],
+ }
+ : undefined,
+ deviceAccess: { canUseDevice, deviceLocked },
+ disableLocalSystem,
+ disabledPluginIds,
+ executionTarget,
+ hasEnabledKnowledgeBases,
+ isBotConversation,
+ isGroupSupervisor,
+ // Local tools reach a machine only through an online, auto-activated
+ // device on the gateway; access policy is enforced upstream by the plan.
+ localExecutionReady:
+ hasDeviceProxy && !!deviceContext?.deviceOnline && !!deviceContext?.autoActivated,
+ memoryEnabled: globalMemoryEnabled,
+ model: {
+ canUseFC: context.isModelSupportToolUse(model, provider),
+ hasImageOutput: !!modelAbilities?.imageOutput,
+ },
+ useApplicationBuiltinSearchTool,
+ });
log(
- 'Creating agent tools engine model=%s provider=%s searchMode=%s platform=%s runtimeMode=%s additionalManifests=%d hasDeviceProxy=%s canUseDevice=%s isChatMode=%s',
+ 'Creating agent tools engine model=%s provider=%s platform=%s runtimeMode=%s toolMode=%s additionalManifests=%d hasDeviceProxy=%s canUseDevice=%s',
model,
provider,
- searchMode,
platform,
- runtimeMode,
+ resolved.runtimeMode,
+ resolved.toolMode,
additionalManifests?.length ?? 0,
hasDeviceProxy,
canUseDevice,
- isChatMode,
);
- // Chat mode: strict outer whitelist. Drop alwaysOn tools and every other
- // runtime-managed rule. Each entry still passes through its own gate (KB /
- // memory / search). Image generation is opt-in via a pinned plugin β€” no
- // automatic injection. `allowExplicitActivation` is off so the activator
- // can't smuggle anything else in.
- const chatModeRules = {
- [ImageGenerationManifest.identifier]: imageGenerationEnabled,
- [KnowledgeBaseManifest.identifier]: hasEnabledKnowledgeBases,
- [MemoryManifest.identifier]: globalMemoryEnabled,
- [WebBrowsingManifest.identifier]: isSearchEnabled,
- };
-
- // Custom mode: the tool set is EXACTLY the agent's declared plugins β€” no
- // alwaysOn tools, no default/runtime-managed injection, no activator. Used by
- // focused builtin sub-agents (e.g. the verify agent, which mounts only its
- // writeback tool) that need a precise, self-configured toolset.
- const customModeRules = Object.fromEntries((agentConfig.plugins ?? []).map((id) => [id, true]));
-
- const agentModeRules = {
- // User-selected plugins
- ...Object.fromEntries((agentConfig.plugins ?? []).map((id) => [id, true])),
- // Always-on builtin tools
- ...Object.fromEntries(alwaysOnToolIds.map((id) => [id, true])),
- // System-level rules (may override user selection for specific tools)
- // Auto mode lets the model choose per call whether to run in the cloud
- // sandbox or on the auto-routed device β€” `injectCredsToSandbox` has no
- // device branch and always targets the sandbox regardless of routing β€”
- // so the dedicated Cloud Sandbox tool is offered here too, not only when
- // the target is literally 'sandbox'.
- [CloudSandboxManifest.identifier]: runtimeMode === 'cloud' || executionTarget === 'auto',
- [KnowledgeBaseManifest.identifier]: hasEnabledKnowledgeBases,
- // Local-system: the user must have opted into local runtime
- // (`runtimeMode === 'local'`) AND have an online, auto-activated device
- // registered with the device-gateway. Access policy (external bot
- // senders) is enforced upstream: `resolveExecutionPlan` degrades denied
- // targets to `none`, and `buildAllowedBuiltinTools` +
- // `excludeIdentifiers` physically drop the manifest for
- // `canUseDevice=false` turns.
- [LocalSystemManifest.identifier]:
- !disableLocalSystem &&
- runtimeMode === 'local' &&
- hasDeviceProxy &&
- !!deviceContext?.deviceOnline &&
- !!deviceContext?.autoActivated,
- // Browser drives the device's in-app browser β€” same device gate as
- // local-system: local runtime routed to an online, auto-activated device.
- [BrowserManifest.identifier]:
- runtimeMode === 'local' &&
- hasDeviceProxy &&
- !!deviceContext?.deviceOnline &&
- !!deviceContext?.autoActivated,
- [MemoryManifest.identifier]: globalMemoryEnabled,
- // Only auto-enable in bot conversations; otherwise let user's plugin selection take effect
- ...(isBotConversation && { [MessageManifest.identifier]: true }),
- // Group supervisor: enable the orchestration toolset (see
- // `groupSupervisorToolIds`). The same list also feeds the candidate set
- // below, so the bundle has a single source of truth.
- ...(isGroupSupervisor && Object.fromEntries(groupSupervisorToolIds.map((id) => [id, true]))),
- // Remote-device proxy: shown only for device-capable targets when the
- // server has a proxy AND the run is not already locked to a device
- // (routed, or explicitly bound but offline β€” a bound-offline run stays
- // unrouted until that device comes back, rather than silently hopping
- // elsewhere). This rule is defense-in-depth: the authoritative wall is
- // physical (`buildAllowedBuiltinTools` + `excludeIdentifiers` below drop
- // the manifest for locked turns), since explicit activation bypasses
- // rules. External bot senders never reach it either way: the plan
- // degrades denied targets to `none` (β†’ not deviceCapable) and the
- // physical walls drop it for `canUseDevice=false` turns.
- [RemoteDeviceManifest.identifier]: deviceCapable && hasDeviceProxy && !deviceLocked,
- [WebBrowsingManifest.identifier]: isSearchEnabled,
- };
-
- const excludedIdentifiers = new Set(disabledPluginIds);
- if (hasDeviceProxy && !deviceContext?.supportedTools?.includes(AuvManifest.identifier))
- excludedIdentifiers.add(AuvManifest.identifier);
- if (!canUseDevice) {
- for (const identifier of DEVICE_TOOL_IDENTIFIERS) excludedIdentifiers.add(identifier);
- } else if (deviceLocked) {
- for (const identifier of REMOTE_DEVICE_TOOL_IDENTIFIERS) excludedIdentifiers.add(identifier);
- }
-
return createServerToolsEngine(context, {
- // Pass additional manifests (e.g., LobeHub Skills)
additionalManifests,
- // Physically drop device-tool manifests for turns whose access policy
- // denies them. Without this filter, `lobe-activator`'s explicit
- // activation could resolve the manifest and bypass the rule-layer
- // gates below ().
+ // Physically drop device-tool manifests the walls deny: explicit
+ // activation could otherwise resolve them past the rule gates.
builtinTools: buildAllowedBuiltinTools({
canUseDevice,
deviceLocked,
disableLocalSystem,
supportedDeviceTools: hasDeviceProxy ? (deviceContext?.supportedTools ?? []) : undefined,
}),
- // Add default tools based on configuration. Custom mode = exactly the
- // agent's plugins; chat mode = strict allow-list; agent mode = full defaults.
- // Agent mode: the supervisor's orchestration tools are neither in the
- // agent's plugins nor in `defaultToolIds`, so add them to the candidate set
- // here (the `agentModeRules` above then enable them). Enabling a tool that
- // isn't a candidate is a no-op β€” the checker only filters
- // `union(toolIds, defaultToolIds)`.
- defaultToolIds: isCustomMode
- ? (agentConfig.plugins ?? [])
- : isChatMode
- ? chatModeAllowedToolIds
- : [...defaultToolIds, ...(isGroupSupervisor ? groupSupervisorToolIds : [])],
- // Post-merge wall: a plugin or Skill/Composio manifest claiming a
- // device identifier survives `buildAllowedBuiltinTools` (which only
- // filters the builtin source). Excluding the identifiers here drops
- // them from the combined `manifestSchemas` so the activator cannot
- // resolve them regardless of which manifest source declared them.
- // Locked turns exclude the remote-device picker only (local-system
- // stays for the routed device).
- excludeIdentifiers: excludedIdentifiers.size > 0 ? excludedIdentifiers : undefined,
- // Conversation context for context-aware builtin manifests (scope /
- // isSubAgent), e.g. hiding lobe-agent's callSubAgent in sub-agent / group runs.
+ defaultToolIds: resolved.defaultToolIds,
+ // Post-merge wall: a plugin or Skill/Composio manifest claiming a device
+ // identifier survives the builtin filter; excluding it here drops it from
+ // every source.
+ excludeIdentifiers:
+ resolved.excludedIdentifiers.size > 0 ? resolved.excludedIdentifiers : undefined,
manifestContext,
enableChecker: createEnableChecker({
- // Allow lobe-activator to dynamically enable tools at runtime (e.g., lobe-creds, lobe-task).
- // Only in agent mode; chat/custom modes can't let the activator bypass their fixed set.
- allowExplicitActivation: toolMode === 'agent',
- rules: isCustomMode ? customModeRules : isChatMode ? chatModeRules : agentModeRules,
+ allowExplicitActivation: resolved.allowExplicitActivation,
+ rules: resolved.rules,
}),
});
};
diff --git a/apps/server/src/services/aiAgent/deviceToolRegistry.ts b/apps/server/src/services/aiAgent/deviceToolRegistry.ts
index 239dd10ef28..a3c2ebc7026 100644
--- a/apps/server/src/services/aiAgent/deviceToolRegistry.ts
+++ b/apps/server/src/services/aiAgent/deviceToolRegistry.ts
@@ -19,100 +19,27 @@
* because the manifest was still resolvable in the engine even when
* the rule-layer gate denied it).
*/
-import { AuvManifest } from '@lobechat/builtin-tool-auv';
-import { BrowserManifest } from '@lobechat/builtin-tool-browser';
-import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
-import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
import { builtinTools } from '@lobechat/builtin-tools';
+import {
+ DEVICE_TOOL_IDENTIFIERS,
+ DEVICE_TOOL_MANIFESTS,
+ type DeviceToolWallParams,
+ filterAllowedBuiltinTools,
+ isDeviceToolIdentifier,
+ REMOTE_DEVICE_TOOL_IDENTIFIERS,
+} from '@lobechat/mecha';
-export const DEVICE_TOOL_MANIFESTS = [
- LocalSystemManifest,
- RemoteDeviceManifest,
- BrowserManifest,
- AuvManifest,
-] as const;
-
-export const DEVICE_TOOL_IDENTIFIERS: ReadonlySet<string> = new Set(
- DEVICE_TOOL_MANIFESTS.map((m) => m.identifier),
-);
-
-/**
- * The remote-device picker alone β€” the exclusion set for device-LOCKED runs,
- * which keep local-system for the routed device but must not see the picker.
- */
-export const REMOTE_DEVICE_TOOL_IDENTIFIERS: ReadonlySet<string> = new Set([
- RemoteDeviceManifest.identifier,
-]);
-
-export const isDeviceToolIdentifier = (identifier: string): boolean =>
- DEVICE_TOOL_IDENTIFIERS.has(identifier);
-
-export interface AllowedBuiltinToolsParams {
- /**
- * Output of `resolveDeviceAccessPolicy`. When `false`, BOTH device tools
- * (local-system and remote-device) are stripped from the returned list β€”
- * this is the hard wall that keeps external bot senders from reaching the
- * owner's machine even via `lobe-activator`'s `isExplicitActivation`
- * bypass at the engine's enableChecker layer.
- */
- canUseDevice: boolean;
- /**
- * The run is locked to a specific device β€” routed, or explicitly bound but
- * offline (see `isDeviceLockedPlan`). Strips `lobe-remote-device` ONLY:
- * with no device decision left, the picker must not exist (offering
- * `activateDevice` invites redundant activation or hopping to a machine
- * the user never chose), while local-system stays for the routed device.
- * Physical counterpart of the `!deviceLocked` rule gate in
- * `AgentToolsEngine` β€” without it, the activator's `isExplicitActivation`
- * bypass can re-surface the device list mid-run.
- */
- deviceLocked?: boolean;
- /**
- * User-level kill switch for local-system specifically. Independent of
- * `canUseDevice` β€” an owner may want first-party local-system disabled
- * (privacy, sandbox tests) while remote-device stays available.
- * `undefined` is treated as `false` so callers that thread the
- * `disableLocalSystem?: boolean` param through don't need to coerce.
- */
- disableLocalSystem?: boolean;
- /** Gateway callers pass reported capabilities or [] for older clients; omitted for standalone client execution. */
- supportedDeviceTools?: readonly string[];
-}
+// The registry and the walls live in `@lobechat/mecha` so both hosts agree
+// on which builtin tools are device tools; re-exported for the server callers.
+export {
+ DEVICE_TOOL_IDENTIFIERS,
+ DEVICE_TOOL_MANIFESTS,
+ isDeviceToolIdentifier,
+ REMOTE_DEVICE_TOOL_IDENTIFIERS,
+};
-/**
- * Physically filter the `builtinTools` array based on per-turn device
- * access. Callers MUST use this in place of iterating `builtinTools`
- * directly when the resulting manifests will reach a place the activator
- * (or the rendered `<available_tools>` block) can see.
- *
- * Defense-in-depth note: the rule-layer gates in `AgentToolsEngine` are
- * kept as a secondary line of defense, but they are bypassed by
- * `allowExplicitActivation` (B2), so the **physical** filter
- * here is the only reliable enforcement point.
- */
-export const buildAllowedBuiltinTools = (params: AllowedBuiltinToolsParams) => {
- const { canUseDevice, deviceLocked, disableLocalSystem, supportedDeviceTools } = params;
+export type AllowedBuiltinToolsParams = DeviceToolWallParams;
- return builtinTools.filter((tool) => {
- if (
- tool.identifier === AuvManifest.identifier &&
- supportedDeviceTools !== undefined &&
- !supportedDeviceTools.includes(tool.identifier)
- )
- return false;
- if (
- disableLocalSystem &&
- (tool.identifier === LocalSystemManifest.identifier ||
- tool.identifier === AuvManifest.identifier)
- ) {
- return false;
- }
- if (!canUseDevice && DEVICE_TOOL_IDENTIFIERS.has(tool.identifier)) {
- return false;
- }
- if (deviceLocked && REMOTE_DEVICE_TOOL_IDENTIFIERS.has(tool.identifier)) {
- return false;
- }
- return true;
- });
-};
+/** The bundled builtin tools that may exist for this run, after the device walls. */
+export const buildAllowedBuiltinTools = (params: AllowedBuiltinToolsParams) =>
+ filterAllowedBuiltinTools(builtinTools, params);
diff --git a/packages/mecha/package.json b/packages/mecha/package.json
index 399b8926b00..06a629e190b 100644
--- a/packages/mecha/package.json
+++ b/packages/mecha/package.json
@@ -11,14 +11,22 @@
"@lobechat/agent-runtime": "workspace:*",
"@lobechat/builtin-agents": "workspace:*",
"@lobechat/builtin-tool-agent-builder": "workspace:*",
+ "@lobechat/builtin-tool-auv": "workspace:*",
+ "@lobechat/builtin-tool-browser": "workspace:*",
"@lobechat/builtin-tool-agent-management": "workspace:*",
"@lobechat/builtin-tool-cloud-sandbox": "workspace:*",
"@lobechat/builtin-tool-creds": "workspace:*",
"@lobechat/builtin-tool-group-agent-builder": "workspace:*",
+ "@lobechat/builtin-tool-image-generation": "workspace:*",
+ "@lobechat/builtin-tool-knowledge-base": "workspace:*",
"@lobechat/builtin-tool-lobe-agent": "workspace:*",
"@lobechat/builtin-tool-local-system": "workspace:*",
+ "@lobechat/builtin-tool-memory": "workspace:*",
+ "@lobechat/builtin-tool-message": "workspace:*",
"@lobechat/builtin-tool-page-agent": "workspace:*",
+ "@lobechat/builtin-tool-remote-device": "workspace:*",
"@lobechat/builtin-tool-task": "workspace:*",
+ "@lobechat/builtin-tool-web-browsing": "workspace:*",
"@lobechat/builtin-tool-web-onboarding": "workspace:*",
"@lobechat/builtin-tools": "workspace:*",
"@lobechat/business-const": "workspace:*",
diff --git a/packages/mecha/src/index.ts b/packages/mecha/src/index.ts
index 23100f876f5..75eb5ee0397 100644
--- a/packages/mecha/src/index.ts
+++ b/packages/mecha/src/index.ts
@@ -6,3 +6,4 @@ export type {
ResolvedAgentConfig,
} from './resolveAgentConfig';
export { resolveAgentConfig } from './resolveAgentConfig';
+export * from './toolSet';
diff --git a/packages/mecha/src/toolSet/deviceTools.ts b/packages/mecha/src/toolSet/deviceTools.ts
new file mode 100644
index 00000000000..6848cd68622
--- /dev/null
+++ b/packages/mecha/src/toolSet/deviceTools.ts
@@ -0,0 +1,66 @@
+import { AuvManifest } from '@lobechat/builtin-tool-auv';
+import { BrowserManifest } from '@lobechat/builtin-tool-browser';
+import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
+import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
+import type { LobeBuiltinTool } from '@lobechat/types';
+
+/** Builtin tools that only exist for a run with a device (local machine or routed device). */
+export const DEVICE_TOOL_MANIFESTS = [
+ LocalSystemManifest,
+ RemoteDeviceManifest,
+ BrowserManifest,
+ AuvManifest,
+] as const;
+
+export const DEVICE_TOOL_IDENTIFIERS: ReadonlySet<string> = new Set(
+ DEVICE_TOOL_MANIFESTS.map((m) => m.identifier),
+);
+
+/** The picker that activates a device mid-run; pointless once the run is locked to one. */
+export const REMOTE_DEVICE_TOOL_IDENTIFIERS: ReadonlySet<string> = new Set([
+ RemoteDeviceManifest.identifier,
+]);
+
+export const isDeviceToolIdentifier = (identifier: string): boolean =>
+ DEVICE_TOOL_IDENTIFIERS.has(identifier);
+
+export interface DeviceToolWallParams {
+ /** The run's access policy allows a device at all (external bot senders do not). */
+ canUseDevice: boolean;
+ /** The run is committed to one device (routed, or bound but offline). */
+ deviceLocked?: boolean;
+ disableLocalSystem?: boolean;
+ /**
+ * Tools the routed device reports supporting. `undefined` means no device
+ * gateway is involved, so the opt-in check does not apply.
+ */
+ supportedDeviceTools?: readonly string[];
+}
+
+/**
+ * Whether a builtin tool may physically exist in this run's manifest pool.
+ * This is a wall, not a rule: explicit activation bypasses the enable rules,
+ * so a tool the policy denies must not be resolvable at all.
+ */
+export const isBuiltinToolAllowed = (identifier: string, params: DeviceToolWallParams): boolean => {
+ const { canUseDevice, deviceLocked, disableLocalSystem, supportedDeviceTools } = params;
+ if (
+ identifier === AuvManifest.identifier &&
+ supportedDeviceTools !== undefined &&
+ !supportedDeviceTools.includes(identifier)
+ )
+ return false;
+ if (
+ disableLocalSystem &&
+ (identifier === LocalSystemManifest.identifier || identifier === AuvManifest.identifier)
+ )
+ return false;
+ if (!canUseDevice && DEVICE_TOOL_IDENTIFIERS.has(identifier)) return false;
+ if (deviceLocked && REMOTE_DEVICE_TOOL_IDENTIFIERS.has(identifier)) return false;
+ return true;
+};
+
+export const filterAllowedBuiltinTools = <T extends Pick<LobeBuiltinTool, 'identifier'>>(
+ tools: readonly T[],
+ params: DeviceToolWallParams,
+): T[] => tools.filter((tool) => isBuiltinToolAllowed(tool.identifier, params));
diff --git a/packages/mecha/src/toolSet/index.ts b/packages/mecha/src/toolSet/index.ts
new file mode 100644
index 00000000000..ec35113017f
--- /dev/null
+++ b/packages/mecha/src/toolSet/index.ts
@@ -0,0 +1,3 @@
+export * from './deviceTools';
+export { deviceToolWallParams, resolveToolRules } from './resolveToolRules';
+export type * from './types';
diff --git a/packages/mecha/src/toolSet/resolveToolRules.test.ts b/packages/mecha/src/toolSet/resolveToolRules.test.ts
new file mode 100644
index 00000000000..4a543a0a8ab
--- /dev/null
+++ b/packages/mecha/src/toolSet/resolveToolRules.test.ts
@@ -0,0 +1,208 @@
+import { AuvManifest } from '@lobechat/builtin-tool-auv';
+import { groupSupervisorToolIds } from '@lobechat/builtin-tools';
+import { describe, expect, it } from 'vitest';
+
+import { filterAllowedBuiltinTools } from './deviceTools';
+import { resolveToolRules } from './resolveToolRules';
+import type { ToolRuleRequest } from './types';
+
+const request = (overrides: Partial<ToolRuleRequest> = {}): ToolRuleRequest => ({
+ agent: { chatConfig: {}, plugins: ['my-plugin'] },
+ executionTarget: 'sandbox',
+ localExecutionReady: false,
+ model: { canUseFC: true },
+ ...overrides,
+});
+
+describe('resolveToolRules', () => {
+ it('derives the three modes from the chat config, never from the model', () => {
+ expect(resolveToolRules(request()).toolMode).toBe('agent');
+ expect(
+ resolveToolRules(request({ agent: { chatConfig: { enableAgentMode: false }, plugins: [] } }))
+ .toolMode,
+ ).toBe('chat');
+ expect(
+ resolveToolRules(request({ agent: { chatConfig: { toolMode: 'custom' }, plugins: [] } }))
+ .toolMode,
+ ).toBe('custom');
+ // A model without function calling keeps the stored mode; the tools
+ // engine marks the tools incompatible instead.
+ expect(resolveToolRules(request({ model: { canUseFC: false } })).toolMode).toBe('agent');
+ });
+
+ it('chat mode is a strict whitelist with no activator and no always-on tools', () => {
+ const resolved = resolveToolRules(
+ request({
+ agent: { chatConfig: { enableAgentMode: false }, plugins: ['my-plugin'] },
+ hasEnabledKnowledgeBases: true,
+ }),
+ );
+ expect(resolved.allowExplicitActivation).toBe(false);
+ expect(resolved.rules['my-plugin']).toBeUndefined();
+ expect(resolved.rules['lobe-agent']).toBeUndefined();
+ expect(resolved.rules['lobe-knowledge-base']).toBe(true);
+ expect(resolved.rules['lobe-web-browsing']).toBe(true);
+ expect(resolved.defaultToolIds).not.toContain('lobe-agent');
+ });
+
+ it('custom mode is exactly the pinned plugins', () => {
+ const resolved = resolveToolRules(
+ request({ agent: { chatConfig: { toolMode: 'custom' }, plugins: ['a', 'b'] } }),
+ );
+ expect(resolved.rules).toEqual({ a: true, b: true });
+ expect(resolved.defaultToolIds).toEqual(['a', 'b']);
+ expect(resolved.allowExplicitActivation).toBe(false);
+ });
+
+ it('agent mode enables pinned, runtime and always-on tools and opens the activator', () => {
+ const resolved = resolveToolRules(
+ request({ isGroupSupervisor: true, runtimePluginIds: ['scope-plugin'] }),
+ );
+ expect(resolved.allowExplicitActivation).toBe(true);
+ expect(resolved.rules['my-plugin']).toBe(true);
+ expect(resolved.rules['scope-plugin']).toBe(true);
+ expect(resolved.rules['lobe-agent']).toBe(true);
+ for (const id of groupSupervisorToolIds) {
+ expect(resolved.rules[id]).toBe(true);
+ expect(resolved.defaultToolIds).toContain(id);
+ }
+ });
+
+ it('offers image generation only when pinned on a tool-calling model without native output', () => {
+ const pinned = { chatConfig: { enableAgentMode: false }, plugins: ['lobe-image-generation'] };
+ expect(resolveToolRules(request({ agent: pinned })).rules['lobe-image-generation']).toBe(true);
+ expect(
+ resolveToolRules(request({ agent: pinned, model: { canUseFC: true, hasImageOutput: true } }))
+ .rules['lobe-image-generation'],
+ ).toBe(false);
+ expect(
+ resolveToolRules(request({ agent: pinned, model: { canUseFC: false } })).rules[
+ 'lobe-image-generation'
+ ],
+ ).toBe(false);
+ });
+
+ it('gates the sandbox, local and device tools on the execution target', () => {
+ const sandbox = resolveToolRules(request({ executionTarget: 'sandbox' }));
+ expect(sandbox.rules['lobe-cloud-sandbox']).toBe(true);
+ expect(sandbox.rules['lobe-local-system']).toBe(false);
+
+ const auto = resolveToolRules(request({ executionTarget: 'auto' }));
+ expect(auto.rules['lobe-cloud-sandbox']).toBe(true);
+
+ const localNotReady = resolveToolRules(request({ executionTarget: 'local' }));
+ expect(localNotReady.rules['lobe-local-system']).toBe(false);
+ expect(localNotReady.rules['lobe-browser']).toBe(false);
+
+ const localReady = resolveToolRules(
+ request({ executionTarget: 'local', localExecutionReady: true }),
+ );
+ expect(localReady.rules['lobe-local-system']).toBe(true);
+ expect(localReady.rules['lobe-browser']).toBe(true);
+ expect(localReady.rules['lobe-cloud-sandbox']).toBe(false);
+
+ const disabledLocal = resolveToolRules(
+ request({ disableLocalSystem: true, executionTarget: 'local', localExecutionReady: true }),
+ );
+ expect(disabledLocal.rules['lobe-local-system']).toBe(false);
+ });
+
+ it('offers the device picker only behind a gateway while a device decision remains', () => {
+ // A persisted `device` target on a server without a gateway: the policy
+ // allows a device, but nothing could dispatch to one.
+ const noGateway = resolveToolRules(
+ request({
+ deviceAccess: { canUseDevice: true, deviceLocked: false },
+ executionTarget: 'device',
+ }),
+ );
+ expect(noGateway.rules['lobe-remote-device']).toBe(false);
+ expect(noGateway.excludedIdentifiers).toEqual(new Set());
+
+ const open = resolveToolRules(
+ request({
+ device: { supportedTools: [AuvManifest.identifier] },
+ deviceAccess: { canUseDevice: true, deviceLocked: false },
+ executionTarget: 'device',
+ }),
+ );
+ expect(open.rules['lobe-remote-device']).toBe(true);
+
+ const locked = resolveToolRules(
+ request({
+ device: { supportedTools: [AuvManifest.identifier] },
+ deviceAccess: { canUseDevice: true, deviceLocked: true },
+ executionTarget: 'device',
+ }),
+ );
+ expect(locked.rules['lobe-remote-device']).toBe(false);
+ expect(locked.excludedIdentifiers.has('lobe-remote-device')).toBe(true);
+ expect(locked.excludedIdentifiers.has('lobe-local-system')).toBe(false);
+ });
+
+ it('walls every device tool off for a run whose policy denies devices, gateway or not', () => {
+ const denied = resolveToolRules(
+ request({
+ deviceAccess: { canUseDevice: false, deviceLocked: false },
+ disabledPluginIds: ['my-plugin'],
+ executionTarget: 'none',
+ }),
+ );
+ expect(denied.excludedIdentifiers).toEqual(
+ new Set([
+ 'my-plugin',
+ 'lobe-local-system',
+ 'lobe-remote-device',
+ 'lobe-browser',
+ AuvManifest.identifier,
+ ]),
+ );
+ // Computer Use also disappears when the routed device does not support it.
+ const unsupported = resolveToolRules(
+ request({
+ device: {},
+ deviceAccess: { canUseDevice: true, deviceLocked: false },
+ executionTarget: 'local',
+ }),
+ );
+ expect(unsupported.excludedIdentifiers.has(AuvManifest.identifier)).toBe(true);
+ });
+
+ it('enables the message tool in bot conversations and search per the decision', () => {
+ const bot = resolveToolRules(
+ request({ isBotConversation: true, useApplicationBuiltinSearchTool: false }),
+ );
+ expect(bot.rules['lobe-message']).toBe(true);
+ expect(bot.rules['lobe-web-browsing']).toBe(false);
+ const off = resolveToolRules(request({ agent: { chatConfig: { searchMode: 'off' } } }));
+ expect(off.rules['lobe-web-browsing']).toBe(false);
+ });
+});
+
+describe('filterAllowedBuiltinTools', () => {
+ const tools = [
+ { identifier: 'lobe-local-system' },
+ { identifier: 'lobe-remote-device' },
+ { identifier: AuvManifest.identifier },
+ { identifier: 'lobe-web-browsing' },
+ ];
+ it('keeps non-device tools and drops device tools per the walls', () => {
+ const ids = (params: Parameters<typeof filterAllowedBuiltinTools>[1]) =>
+ filterAllowedBuiltinTools(tools, params).map((t) => t.identifier);
+ expect(ids({ canUseDevice: false, deviceLocked: false })).toEqual(['lobe-web-browsing']);
+ expect(ids({ canUseDevice: true, deviceLocked: true })).toEqual([
+ 'lobe-local-system',
+ AuvManifest.identifier,
+ 'lobe-web-browsing',
+ ]);
+ expect(ids({ canUseDevice: true, deviceLocked: false, supportedDeviceTools: [] })).toEqual([
+ 'lobe-local-system',
+ 'lobe-remote-device',
+ 'lobe-web-browsing',
+ ]);
+ expect(ids({ canUseDevice: true, deviceLocked: false, disableLocalSystem: true })).toEqual([
+ 'lobe-remote-device',
+ 'lobe-web-browsing',
+ ]);
+ });
+});
diff --git a/packages/mecha/src/toolSet/resolveToolRules.ts b/packages/mecha/src/toolSet/resolveToolRules.ts
new file mode 100644
index 00000000000..9ad824cd7c7
--- /dev/null
+++ b/packages/mecha/src/toolSet/resolveToolRules.ts
@@ -0,0 +1,136 @@
+import { AuvManifest } from '@lobechat/builtin-tool-auv';
+import { BrowserManifest } from '@lobechat/builtin-tool-browser';
+import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
+import { ImageGenerationManifest } from '@lobechat/builtin-tool-image-generation';
+import { KnowledgeBaseManifest } from '@lobechat/builtin-tool-knowledge-base';
+import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
+import { MemoryManifest } from '@lobechat/builtin-tool-memory';
+import { MessageManifest } from '@lobechat/builtin-tool-message';
+import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
+import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';
+import {
+ alwaysOnToolIds,
+ chatModeAllowedToolIds,
+ defaultToolIds,
+ groupSupervisorToolIds,
+} from '@lobechat/builtin-tools';
+import { executionTargetToRuntimeMode, resolveToolMode } from '@lobechat/types';
+
+import {
+ DEVICE_TOOL_IDENTIFIERS,
+ type DeviceToolWallParams,
+ REMOTE_DEVICE_TOOL_IDENTIFIERS,
+} from './deviceTools';
+import type { ResolvedToolRules, ToolRuleRequest } from './types';
+
+const enableAll = (ids: readonly string[]) => Object.fromEntries(ids.map((id) => [id, true]));
+
+/** The wall parameters for a run's device facts; no device means no walls. */
+export const deviceToolWallParams = (request: ToolRuleRequest): DeviceToolWallParams | undefined =>
+ request.deviceAccess
+ ? {
+ canUseDevice: request.deviceAccess.canUseDevice,
+ deviceLocked: request.deviceAccess.deviceLocked,
+ disableLocalSystem: request.disableLocalSystem,
+ // Only a gateway device can report what it supports.
+ supportedDeviceTools: request.device ? (request.device.supportedTools ?? []) : undefined,
+ }
+ : undefined;
+
+/**
+ * Decide which tools a run may enable, which it gets by default, and which
+ * must not exist in its manifest pool. The mode (chat / custom / agent) and
+ * every per-tool rule live here for both hosts; hosts only assemble the facts
+ * and feed the result to the tools engine's enable checker.
+ */
+export const resolveToolRules = (request: ToolRuleRequest): ResolvedToolRules => {
+ const { agent, device, deviceAccess, executionTarget, model } = request;
+ const pinnedPluginIds = agent.plugins ?? [];
+ const toolMode = resolveToolMode(agent.chatConfig);
+ const runtimeMode = executionTargetToRuntimeMode(executionTarget);
+ // Device tools only exist for device-capable targets: `none` means no
+ // device, and `sandbox` and devices are mutually exclusive.
+ const deviceCapable = executionTarget === 'local' || executionTarget === 'device';
+ const deviceLocked = deviceAccess?.deviceLocked ?? false;
+
+ const searchMode = agent.chatConfig?.searchMode ?? 'auto';
+ const isSearchEnabled = request.useApplicationBuiltinSearchTool ?? searchMode !== 'off';
+ const kbEnabled = request.hasEnabledKnowledgeBases ?? false;
+ const memoryEnabled = request.memoryEnabled ?? false;
+ // Image generation is never auto-injected: the user opts in by pinning the
+ // tool, and a model with native image output never gets the fallback.
+ const imageGenerationEnabled =
+ model.canUseFC &&
+ !model.hasImageOutput &&
+ pinnedPluginIds.includes(ImageGenerationManifest.identifier);
+ // Local tools need a `local` target that can actually reach a machine.
+ const localToolsEnabled =
+ !request.disableLocalSystem && runtimeMode === 'local' && request.localExecutionReady;
+
+ // Chat mode: a strict outer whitelist. No always-on tools, no runtime
+ // injection, no activator β€” each entry still passes its own gate.
+ const chatModeRules = {
+ [ImageGenerationManifest.identifier]: imageGenerationEnabled,
+ [KnowledgeBaseManifest.identifier]: kbEnabled,
+ [MemoryManifest.identifier]: memoryEnabled,
+ [WebBrowsingManifest.identifier]: isSearchEnabled,
+ };
+ // Custom mode: the tool set is EXACTLY the agent's declared plugins, for
+ // focused builtin sub-agents that configure themselves precisely.
+ const customModeRules = enableAll(pinnedPluginIds);
+ const agentModeRules = {
+ ...enableAll(request.runtimePluginIds ?? []),
+ ...enableAll(pinnedPluginIds),
+ ...enableAll(alwaysOnToolIds),
+ // System rules may override the user's selection for specific tools.
+ // Auto mode lets the model pick the sandbox or the routed device per
+ // call, so the dedicated sandbox tool is offered there too.
+ [CloudSandboxManifest.identifier]: runtimeMode === 'cloud' || executionTarget === 'auto',
+ [KnowledgeBaseManifest.identifier]: kbEnabled,
+ [LocalSystemManifest.identifier]: localToolsEnabled,
+ // The in-app browser drives the same machine as local-system.
+ [BrowserManifest.identifier]: runtimeMode === 'local' && request.localExecutionReady,
+ [MemoryManifest.identifier]: memoryEnabled,
+ ...(request.isBotConversation && { [MessageManifest.identifier]: true }),
+ ...(request.isGroupSupervisor && enableAll(groupSupervisorToolIds)),
+ // The device picker: only for device-capable targets behind a gateway,
+ // and only while the run still has a device decision to make. The wall
+ // below is the authoritative gate; this rule is defense in depth.
+ [RemoteDeviceManifest.identifier]: deviceCapable && !!device && !deviceLocked,
+ [WebBrowsingManifest.identifier]: isSearchEnabled,
+ };
+
+ // Walls follow the policy and the plan, with or without a gateway; the
+ // Computer Use opt-in is a gateway device's own report.
+ const excludedIdentifiers = new Set(request.disabledPluginIds ?? []);
+ if (device && !device.supportedTools?.includes(AuvManifest.identifier))
+ excludedIdentifiers.add(AuvManifest.identifier);
+ if (deviceAccess) {
+ if (!deviceAccess.canUseDevice) {
+ for (const identifier of DEVICE_TOOL_IDENTIFIERS) excludedIdentifiers.add(identifier);
+ } else if (deviceLocked) {
+ for (const identifier of REMOTE_DEVICE_TOOL_IDENTIFIERS) excludedIdentifiers.add(identifier);
+ }
+ }
+
+ return {
+ allowExplicitActivation: toolMode === 'agent',
+ defaultToolIds:
+ toolMode === 'custom'
+ ? [...pinnedPluginIds]
+ : toolMode === 'chat'
+ ? [...chatModeAllowedToolIds]
+ : [...defaultToolIds, ...(request.isGroupSupervisor ? groupSupervisorToolIds : [])],
+ deviceCapable,
+ deviceLocked,
+ excludedIdentifiers,
+ rules:
+ toolMode === 'custom'
+ ? customModeRules
+ : toolMode === 'chat'
+ ? chatModeRules
+ : agentModeRules,
+ runtimeMode,
+ toolMode,
+ };
+};
diff --git a/packages/mecha/src/toolSet/types.ts b/packages/mecha/src/toolSet/types.ts
new file mode 100644
index 00000000000..78d487292db
--- /dev/null
+++ b/packages/mecha/src/toolSet/types.ts
@@ -0,0 +1,98 @@
+import type { DeviceExecutionTarget, LobeAgentChatConfig, RuntimeEnvMode } from '@lobechat/types';
+
+/**
+ * What the run knows about its device through a device gateway. Present only
+ * when a gateway exists: without one no device can be dispatched, so the
+ * picker never exists regardless of the target.
+ */
+export interface ToolRuleDeviceFacts {
+ /** A device was auto-routed for this run. */
+ autoActivated?: boolean;
+ deviceOnline?: boolean;
+ /** Tools the routed device reports supporting (Computer Use opts in). */
+ supportedTools?: readonly string[];
+}
+
+/** The run's device policy and plan, independent of whether a gateway exists. */
+export interface ToolRuleDeviceAccess {
+ /** The run's access policy allows a device at all (external senders do not). */
+ canUseDevice: boolean;
+ /** The run is committed to one device (routed, or bound but offline). */
+ deviceLocked: boolean;
+}
+
+/** Everything the tool rules read about the run. Assembled by the host. */
+export interface ToolRuleRequest {
+ agent: {
+ chatConfig?: Pick<LobeAgentChatConfig, 'enableAgentMode' | 'searchMode' | 'toolMode'> | null;
+ /** Pinned plugin identifiers (tri-state entries already collapsed). */
+ plugins?: readonly string[] | null;
+ };
+ /**
+ * Gateway device facts. A host without a gateway (the browser runtime, a
+ * self-hosted server without one) leaves this out: the device picker never
+ * exists and Computer Use is not gated on device support.
+ */
+ device?: ToolRuleDeviceFacts;
+ /**
+ * Device policy and plan. A host that resolves an execution plan supplies
+ * it so the walls apply even without a gateway; the browser runtime leaves
+ * it out and applies no walls.
+ */
+ deviceAccess?: ToolRuleDeviceAccess;
+ /** Plugin identifiers the agent explicitly disabled. */
+ disabledPluginIds?: readonly string[];
+ /**
+ * The host cannot run `local-system` / `auv` for this run regardless of the
+ * target (external senders, no local executor).
+ */
+ disableLocalSystem?: boolean;
+ /** The run's effective execution target, resolved by the host. */
+ executionTarget: DeviceExecutionTarget;
+ hasEnabledKnowledgeBases?: boolean;
+ isBotConversation?: boolean;
+ /** Verified against the persisted roster, never a client claim. */
+ isGroupSupervisor?: boolean;
+ /**
+ * Local tools can actually run for a `local` target: the routed device is
+ * online and auto-activated (gateway), or the host itself is the local
+ * machine (desktop client runtime).
+ */
+ localExecutionReady: boolean;
+ /** Memory tool on, as the host resolved it (agent override, else user setting). */
+ memoryEnabled?: boolean;
+ model: {
+ /** The model can call functions; unknown counts as yes. */
+ canUseFC: boolean;
+ /** The model produces images natively, so the fallback tool is never offered. */
+ hasImageOutput?: boolean;
+ };
+ /**
+ * Plugin identifiers the runtime resolved beyond the agent's own (sub-agent,
+ * group or page scope); enabled like pinned plugins in agent mode.
+ */
+ runtimePluginIds?: readonly string[];
+ /** The application's web-browsing tool should serve search for this model. */
+ useApplicationBuiltinSearchTool?: boolean;
+}
+
+export type ToolMode = 'agent' | 'chat' | 'custom';
+
+export interface ResolvedToolRules {
+ /** Only agent mode lets the activator enable tools beyond the rules. */
+ allowExplicitActivation: boolean;
+ /** Candidate tools added to the request's own ids before the rules run. */
+ defaultToolIds: string[];
+ /** Device tools may only exist for device-capable targets. */
+ deviceCapable: boolean;
+ deviceLocked: boolean;
+ /**
+ * Identifiers that must not exist in the manifest pool at all, from any
+ * source: the agent's disabled plugins plus the device walls.
+ */
+ excludedIdentifiers: Set<string>;
+ /** Per-tool enablement for the enable checker; absent means disabled. */
+ rules: Record<string, boolean>;
+ runtimeMode: RuntimeEnvMode;
+ toolMode: ToolMode;
+}
diff --git a/packages/types/src/agent/executionTargetRules.ts b/packages/types/src/agent/executionTargetRules.ts
new file mode 100644
index 00000000000..18aca4616d9
--- /dev/null
+++ b/packages/types/src/agent/executionTargetRules.ts
@@ -0,0 +1,45 @@
+import type { DeviceExecutionTarget, ExecutionPlan } from './agencyConfig';
+import type { RuntimeEnvMode } from './agentConfig';
+import type { LobeAgentChatConfig } from './chatConfig';
+
+/**
+ * Tool-resolution mode: an explicit `toolMode` wins; otherwise derive from
+ * `enableAgentMode` (undefined = agent). `custom` = the toolset is exactly the
+ * agent's plugins. Every host must derive chat mode through this so the tool
+ * engine, the context engine and the execution plan agree on what chat mode is.
+ */
+export const resolveToolMode = (
+ chatConfig: Pick<LobeAgentChatConfig, 'enableAgentMode' | 'toolMode'> | undefined | null,
+): 'agent' | 'chat' | 'custom' =>
+ chatConfig?.toolMode ?? (chatConfig?.enableAgentMode === false ? 'chat' : 'agent');
+
+/** The runtime-mode tool gate (`cloud` / `local` / `none`) of an execution target. */
+export const executionTargetToRuntimeMode = (target: DeviceExecutionTarget): RuntimeEnvMode => {
+ switch (target) {
+ case 'local': {
+ return 'local';
+ }
+ case 'sandbox': {
+ return 'cloud';
+ }
+ default: {
+ return 'none';
+ }
+ }
+};
+
+export const isDeviceCapablePlan = (plan: ExecutionPlan): boolean =>
+ plan.kind === 'device' || plan.kind === 'device-unrouted';
+
+/**
+ * The run is committed to ONE device: either already routed (`device`, which
+ * includes the opt-in `auto` single-online activation) or locked to an
+ * explicit binding that is currently offline (`bound-device-offline` waits for
+ * that machine rather than hopping elsewhere). A locked run has no device
+ * decision left, so the remote-device picker must not exist for it β€” not even
+ * as an activator-discoverable manifest, since explicit activation bypasses
+ * the rule-layer gates.
+ */
+export const isDeviceLockedPlan = (plan: ExecutionPlan): boolean =>
+ plan.kind === 'device' ||
+ (plan.kind === 'device-unrouted' && plan.reason === 'bound-device-offline');
diff --git a/packages/types/src/agent/index.ts b/packages/types/src/agent/index.ts
index b40e1d2c3e2..8cfc4b7170c 100644
--- a/packages/types/src/agent/index.ts
+++ b/packages/types/src/agent/index.ts
@@ -4,6 +4,7 @@ export * from './agentIntervention';
export * from './chatConfig';
export * from './displayName';
export * from './document';
+export * from './executionTargetRules';
export type * from './graph';
export * from './heteroCliArgs';
export * from './heterogeneousAgent';
diff --git a/src/helpers/executionTarget.ts b/src/helpers/executionTarget.ts
index d5911467729..8392fdd5927 100644
--- a/src/helpers/executionTarget.ts
+++ b/src/helpers/executionTarget.ts
@@ -7,7 +7,18 @@ import type {
LobeAgentChatConfig,
RuntimeEnvMode,
} from '@lobechat/types';
-import { RequestTrigger } from '@lobechat/types';
+import {
+ executionTargetToRuntimeMode,
+ isDeviceCapablePlan,
+ isDeviceLockedPlan,
+ RequestTrigger,
+ resolveToolMode,
+} from '@lobechat/types';
+
+// The pure mode / plan predicates live in `@lobechat/types` so the shared
+// tool rules in `@lobechat/mecha` can use them; re-exported here for the
+// existing host consumers.
+export { executionTargetToRuntimeMode, isDeviceCapablePlan, isDeviceLockedPlan, resolveToolMode };
/**
* Whether a workspace config still needs the shared-row safety coercion.
@@ -19,19 +30,6 @@ export const resolveWorkspaceScoped = (
deviceOverride: AgentDeviceOverride | null | undefined,
): boolean => isWorkspaceAgent && deviceOverride?.executionTarget === undefined;
-/**
- * The agent's tool mode β€” explicit `chatConfig.toolMode` wins; otherwise derive
- * from `enableAgentMode` (undefined = agent). `chat` = no execution
- * environment (plain chat); `custom` = toolset is exactly the agent's plugins.
- *
- * Single source of truth so client (selectors), server tools engine, and
- * `resolveExecutionPlan` all agree on what counts as chat mode.
- */
-export const resolveToolMode = (
- chatConfig: LobeAgentChatConfig | undefined,
-): 'agent' | 'chat' | 'custom' =>
- chatConfig?.toolMode ?? (chatConfig?.enableAgentMode === false ? 'chat' : 'agent');
-
export interface ResolveExecutionTargetOptions {
/**
* Whether tools can run on the user's own client/device in this environment β€”
@@ -269,27 +267,6 @@ export const canExecutionTargetReadLocalPaths = (
target === 'local' ||
(target === 'device' && !!currentDeviceId && agencyConfig?.boundDeviceId === currentDeviceId);
-/**
- * Derive the `runtimeMode` tool gate from the unified execution target:
- * `local` β†’ local-system tools, `sandbox` β†’ cloud sandbox, `device`/`auto` β†’
- * gateway routing, `none` β†’ no run tools (plain chat). `device`/`auto`/`none`
- * all gate to `'none'` β€” device tools are routed via `resolveExecutionPlan`,
- * not via runtimeMode.
- */
-export const executionTargetToRuntimeMode = (target: DeviceExecutionTarget): RuntimeEnvMode => {
- switch (target) {
- case 'local': {
- return 'local';
- }
- case 'sandbox': {
- return 'cloud';
- }
- default: {
- return 'none';
- }
- }
-};
-
/**
* The effective `runtimeMode` (server tool gate) from the unified execution
* target.
@@ -327,25 +304,6 @@ export const executionPlanToManifestExecutionEnv = (
? 'local'
: plan.kind;
-/** Device tools (local-system / remote-device proxy) only exist in device-capable sessions. */
-export const isDeviceCapablePlan = (plan: ExecutionPlan): boolean =>
- plan.kind === 'device' || plan.kind === 'device-unrouted';
-
-/**
- * The run is committed to ONE device: either already routed (`device`, which
- * includes the opt-in `auto` single-online activation) or locked to an
- * explicit binding that is currently offline (`bound-device-offline` waits for
- * that machine rather than hopping elsewhere). A locked run has no device
- * decision left, so the remote-device picker must not exist for it β€” not even
- * as an activator-discoverable manifest, since `allowExplicitActivation`
- * bypasses the rule-layer gates. The picker exists only in the complement:
- * unrouted runs that still need a selection (`no-bound-device` /
- * `ambiguous-online-devices` / `no-online-device`).
- */
-export const isDeviceLockedPlan = (plan: ExecutionPlan): boolean =>
- plan.kind === 'device' ||
- (plan.kind === 'device-unrouted' && plan.reason === 'bound-device-offline');
-
export interface ResolveExecutionPlanParams {
agencyConfig: LobeAgentAgencyConfig | undefined;
/**
diff --git a/src/helpers/toolEngineering/index.test.ts b/src/helpers/toolEngineering/index.test.ts
index e0b283cab7c..3ff9600729b 100644
--- a/src/helpers/toolEngineering/index.test.ts
+++ b/src/helpers/toolEngineering/index.test.ts
@@ -181,10 +181,13 @@ vi.mock('@/store/agent/selectors', () => ({
},
agentChatConfigSelectors: {
currentChatConfig: () => mockCurrentChatConfig,
- isCloudSandboxEnabled: () => false,
- isLocalSystemEnabled: () => desktopEnv.enabled,
isMemoryToolEnabled: () => false,
},
+ chatConfigByIdSelectors: {
+ // A local target only resolves on the desktop; elsewhere the run has no
+ // execution environment.
+ getExecutionTargetById: () => () => (desktopEnv.enabled ? 'local' : 'none'),
+ },
}));
vi.mock('@/store/aiInfra', () => ({
@@ -485,7 +488,7 @@ describe('toolEngineering', () => {
expect(result.enabledToolIds).not.toContain('lobe-agent');
});
- it('should use chat-mode defaults when the model does not support function calling', () => {
+ it('should keep agent-mode defaults and mark every tool incompatible when the model cannot call functions', () => {
mockIsCanUseFC = false;
const toolsEngine = createAgentToolsEngine({
@@ -499,8 +502,11 @@ describe('toolEngineering', () => {
toolIds: [],
});
+ // The stored mode is not demoted to chat mode for a non-FC model (same
+ // rule as the server runtime); the engine reports the incompatibility
+ // per tool instead.
expect(result.enabledToolIds).toEqual([]);
- expect(result.filteredTools).not.toContainEqual({
+ expect(result.filteredTools).toContainEqual({
id: 'lobe-agent',
reason: 'incompatible',
});
diff --git a/src/helpers/toolEngineering/index.ts b/src/helpers/toolEngineering/index.ts
index 117f7844c08..aef2c05169c 100644
--- a/src/helpers/toolEngineering/index.ts
+++ b/src/helpers/toolEngineering/index.ts
@@ -2,16 +2,9 @@
* Tools Engineering - Unified tools processing using ToolsEngine
*/
import { AuvManifest } from '@lobechat/builtin-tool-auv';
-import { BrowserManifest } from '@lobechat/builtin-tool-browser';
-import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
-import { ImageGenerationManifest } from '@lobechat/builtin-tool-image-generation';
-import { KnowledgeBaseManifest } from '@lobechat/builtin-tool-knowledge-base';
-import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
-import { MemoryManifest } from '@lobechat/builtin-tool-memory';
-import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';
-import { alwaysOnToolIds, chatModeAllowedToolIds, defaultToolIds } from '@lobechat/builtin-tools';
import { createEnableChecker, type PluginEnableChecker } from '@lobechat/context-engine';
import { ToolsEngine } from '@lobechat/context-engine';
+import { resolveToolRules } from '@lobechat/mecha';
import {
type BuiltinToolManifest,
type BuiltinToolResolveContext,
@@ -25,7 +18,11 @@ import { applyToolNameMaxLength } from '@/helpers/applyToolNameMaxLength';
import { isToolAvailableInCurrentEnv } from '@/helpers/toolAvailability';
import { patchManifestWithPermissions } from '@/libs/mcp/patchManifestPermissions';
import { getAgentStoreState } from '@/store/agent';
-import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';
+import {
+ agentChatConfigSelectors,
+ agentSelectors,
+ chatConfigByIdSelectors,
+} from '@/store/agent/selectors';
import { aiModelSelectors, getAiInfraStoreState } from '@/store/aiInfra';
import { getToolStoreState } from '@/store/tool';
import {
@@ -221,67 +218,44 @@ export const createAgentToolsEngine = (
) => {
const searchConfig = getSearchConfig(workingModel.model, workingModel.provider);
const agentState = getAgentStoreState();
- // `currentAgentPlugins` already resolves to pinned-only identifiers β€” disabled
- // entries never reach the tools-engine whitelist.
- const userPlugins = agentSelectors.currentAgentPlugins(agentState);
- const disabledPluginIds = agentSelectors.currentAgentDisabledPlugins(agentState);
- const isChatMode =
- agentChatConfigSelectors.currentChatConfig(agentState).enableAgentMode === false ||
- !isCanUseFC(workingModel.model, workingModel.provider);
-
- // Each entry below still respects its own runtime gate; in chat mode this
- // is the entire whitelist. `allowExplicitActivation` and user plugins /
- // `alwaysOnToolIds` are deliberately omitted in chat mode so the activator
- // can't smuggle additional tools in.
- const kbEnabled = agentSelectors.hasEnabledKnowledgeBases(agentState);
- const memoryEnabled =
- agentChatConfigSelectors.currentChatConfig(agentState).memory?.enabled ??
- settingsSelectors.memoryEnabled(useUserStore.getState());
- const webBrowsingEnabled = searchConfig.useApplicationBuiltinSearchTool;
- // Chat mode no longer auto-injects image generation (token cost + unwanted
- // tool calls). Users opt in by pinning `lobe-image-generation`. Models with
- // native imageOutput still skip the fallback tool entirely.
- const imageGenerationCapable =
- isCanUseFC(workingModel.model, workingModel.provider) &&
- !aiModelSelectors.isModelSupportImageOutput(
- workingModel.model,
- workingModel.provider,
- )(getAiInfraStoreState());
- const imageGenerationEnabled =
- imageGenerationCapable && userPlugins.includes(ImageGenerationManifest.identifier);
+ const activeAgentId = agentState.activeAgentId || '';
+ const chatConfig = agentChatConfigSelectors.currentChatConfig(agentState);
- const chatModeRules = {
- [ImageGenerationManifest.identifier]: imageGenerationEnabled,
- [KnowledgeBaseManifest.identifier]: kbEnabled,
- [MemoryManifest.identifier]: memoryEnabled,
- [WebBrowsingManifest.identifier]: webBrowsingEnabled,
- };
-
- const agentModeRules = {
- // Runtime-resolved plugins (from agentConfigResolver for the effective agent,
- // may include sub-agent/group/page scope plugins not on the active agent)
- ...(pluginIds && Object.fromEntries(pluginIds.map((id) => [id, true]))),
- // User-selected plugins (from the active agent)
- ...Object.fromEntries(userPlugins.map((id) => [id, true])),
- // Always-on builtin tools
- ...Object.fromEntries(alwaysOnToolIds.map((id) => [id, true])),
- // System-level rules (may override user selection for specific tools)
- // Browser rides the same local-runtime gate as local-system because the
- // control IPC only exists in the desktop main process.
- [BrowserManifest.identifier]: agentChatConfigSelectors.isLocalSystemEnabled(agentState),
- [CloudSandboxManifest.identifier]: agentChatConfigSelectors.isCloudSandboxEnabled(agentState),
- [KnowledgeBaseManifest.identifier]: kbEnabled,
- [LocalSystemManifest.identifier]: agentChatConfigSelectors.isLocalSystemEnabled(agentState),
- [MemoryManifest.identifier]: memoryEnabled,
- [WebBrowsingManifest.identifier]: webBrowsingEnabled,
- };
+ // The rules β€” mode, per-tool enablement and defaults β€” are shared with the
+ // server runtime through `@lobechat/mecha`; the browser only assembles its
+ // facts. It has no device gateway, so no device walls apply here and the
+ // remaining platform gate stays in `platformFilter` below.
+ const resolved = resolveToolRules({
+ agent: {
+ chatConfig,
+ // `currentAgentPlugins` already resolves to pinned-only identifiers.
+ plugins: agentSelectors.currentAgentPlugins(agentState),
+ },
+ disabledPluginIds: agentSelectors.currentAgentDisabledPlugins(agentState),
+ executionTarget: chatConfigByIdSelectors.getExecutionTargetById(activeAgentId)(agentState),
+ hasEnabledKnowledgeBases: agentSelectors.hasEnabledKnowledgeBases(agentState),
+ // A `local` target only resolves on the desktop, where the host itself is
+ // the machine: local tools are always reachable there.
+ localExecutionReady: true,
+ memoryEnabled:
+ chatConfig.memory?.enabled ?? settingsSelectors.memoryEnabled(useUserStore.getState()),
+ model: {
+ canUseFC: isCanUseFC(workingModel.model, workingModel.provider),
+ hasImageOutput: aiModelSelectors.isModelSupportImageOutput(
+ workingModel.model,
+ workingModel.provider,
+ )(getAiInfraStoreState()),
+ },
+ runtimePluginIds: pluginIds,
+ useApplicationBuiltinSearchTool: searchConfig.useApplicationBuiltinSearchTool,
+ });
return createToolsEngine({
- defaultToolIds: isChatMode ? chatModeAllowedToolIds : defaultToolIds,
- disabledPluginIds,
+ defaultToolIds: resolved.defaultToolIds,
+ disabledPluginIds: [...resolved.excludedIdentifiers],
manifestContext,
enableChecker: createEnableChecker({
- allowExplicitActivation: !isChatMode,
+ allowExplicitActivation: resolved.allowExplicitActivation,
platformFilter: ({ pluginId }) => {
const toolStoreState = getToolStoreState();
const installedPlugin = pluginSelectors.getInstalledPluginById(pluginId)(toolStoreState);
@@ -296,7 +270,7 @@ export const createAgentToolsEngine = (
return undefined; // fall through to rules
},
- rules: isChatMode ? chatModeRules : agentModeRules,
+ rules: resolved.rules,
}),
});
};
diff --git a/src/store/agent/selectors/chatConfigByIdSelectors.ts b/src/store/agent/selectors/chatConfigByIdSelectors.ts
index 476f9b59a66..8d83e51ef69 100644
--- a/src/store/agent/selectors/chatConfigByIdSelectors.ts
+++ b/src/store/agent/selectors/chatConfigByIdSelectors.ts
@@ -3,9 +3,17 @@ import {
DEFAULT_AGENT_SEARCH_FC_MODEL,
isDesktop,
} from '@lobechat/const';
-import { type LobeAgentChatConfig, type RuntimeEnvMode } from '@lobechat/types';
+import {
+ type DeviceExecutionTarget,
+ type LobeAgentChatConfig,
+ type RuntimeEnvMode,
+} from '@lobechat/types';
-import { resolveRuntimeMode, resolveToolMode } from '@/helpers/executionTarget';
+import {
+ executionTargetToRuntimeMode,
+ resolveExecutionTarget,
+ resolveToolMode,
+} from '@/helpers/executionTarget';
import { resolveGatewayModeEnabled } from '@/helpers/gatewayMode';
import { type AgentStoreState } from '@/store/agent/initialState';
@@ -69,24 +77,27 @@ const isLocalSystemEnabledById = (agentId: string) => (s: AgentStoreState) =>
* `agencyConfig.executionTarget` (sandbox β†’ cloud, local β†’ local, device β†’
* none).
*/
+/**
+ * The agent's effective execution target. On web a bound `local` target only
+ * surfaces as `device` (not `sandbox`) when Gateway mode is effectively
+ * enabled and can route to the device; the gate derives from this selector's
+ * own state so it re-evaluates on `disableGatewayMode` changes. Workspace
+ * agents never execute on the current member's own client β€” their stored
+ * `local` coerces away (see `workspaceScoped`).
+ */
+const getExecutionTargetById =
+ (agentId: string) =>
+ (s: AgentStoreState): DeviceExecutionTarget =>
+ resolveExecutionTarget(agentSelectors.getAgentConfigById(agentId)(s)?.agencyConfig, {
+ clientExecutionAvailable: isDesktop,
+ deviceRoutingAvailable: resolveGatewayModeEnabled(s, agentId),
+ workspaceScoped: !!s.agentMap[agentId]?.workspaceId,
+ });
+
const getRuntimeModeById =
(agentId: string) =>
- (s: AgentStoreState): RuntimeEnvMode => {
- const config = agentSelectors.getAgentConfigById(agentId)(s);
-
- // On web a bound `local` target only surfaces as `device` (not `sandbox`)
- // when Gateway mode is effectively enabled and can route to the device
- //. Derive the gate from this selector's own state `s` so it
- // re-evaluates on `disableGatewayMode` changes without a second global read.
- // Workspace agents never execute on the current member's own client β€”
- // their default/stored `local` coerces away (see `workspaceScoped`).
- return resolveRuntimeMode(
- config?.agencyConfig,
- isDesktop,
- resolveGatewayModeEnabled(s, agentId),
- !!s.agentMap[agentId]?.workspaceId,
- );
- };
+ (s: AgentStoreState): RuntimeEnvMode =>
+ executionTargetToRuntimeMode(getExecutionTargetById(agentId)(s));
const getSkillActivateModeById =
(agentId: string) =>
@@ -120,6 +131,7 @@ export const chatConfigByIdSelectors = {
getUseModelBuiltinSearchById,
isChatModeById,
isEnableSearchById,
+ getExecutionTargetById,
isLocalSystemEnabledById,
isMemoryToolEnabledById,
};