π€― 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.
Builtin Tool Architecture
The Five Faces
A builtin tool ships five distinct faces, each compiled into a different bundle:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β ./ β
β Manifest + Types + systemRole β
β β Pure data, no React, no Node-only deps. β
β β Imported by: server (LLM tool spec), client (registries), β
β anyone who needs to know "what tools exist". β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β ./executionRuntime β
β src/ExecutionRuntime/index.ts β
β β Pure runtime logic. Accepts services via constructor β β
β never imports concrete services or stores directly. β
β β Imported by: server (BuiltinServerRuntimeOutput), tests, β
β and the client executor as a delegate. β
β β Returns: BuiltinServerRuntimeOutput { content, state, β¦ } β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β ./executor β
β src/client/executor/index.ts β
β β BaseExecutor subclass. Wires Zustand stores and frontend β
β services into ExecutionRuntime, then funnels through β
β toResult() into BuiltinToolResult { content, state, error, β
β success }. β
β β Imported by: src/store/tool/slices/builtin/executors/ β
β index.ts (registered as a singleton). β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β ./client β
β src/client/{Inspector,Render,Placeholder,Streaming, β
β Intervention,Portal,components}/ β
β β React 'use client' surfaces. Read args + pluginState. β
β β Imported by: packages/builtin-tools/src/{inspectors, β
β renders,placeholders,streamings,interventions,portals}.ts. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Registry wiring β
β packages/builtin-tools/src/*.ts β
β src/store/tool/slices/builtin/executors/index.ts β
β β Aggregator maps: identifier β { apiName β component }. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
The split exists so:
- Server bundles import only
./and./executionRuntimeand never touch React. - Frontend bundles import
./clientand never touch Node-only services. - The runtime is testable without React or Electron present.
Why ExecutionRuntime is the Default Home for Logic
Old pattern (grandfathered): business logic in src/executor/ directly. Examples: builtin-tool-calculator, older tools. Works, but the executor mixes runtime logic with frontend service plumbing β hard to reuse on the server.
New pattern (preferred): business logic in src/ExecutionRuntime/, frontend wiring in src/client/executor/. Examples: builtin-tool-local-system, builtin-tool-web-browsing, builtin-tool-calculator.
ExecutionRuntime
ββ accepts services via constructor (or `static create(opts)`)
ββ returns BuiltinServerRuntimeOutput (content + state + success)
ββ no React, no Zustand, no `@/services/...` direct imports
client/executor
ββ extends BaseExecutor<typeof <Name>ApiName>
ββ holds a `runtime = new <Name>ExecutionRuntime(realService)` instance
ββ each ApiName method:
β 1. resolve scope / pull defaults from BuiltinToolContext
β 2. call runtime.<method>(args)
β 3. funnel through toResult() β BuiltinToolResult
ββ exported singleton: export const <name>Executor = new <Name>Executor()
Service injection
ExecutionRuntime should declare a TypeScript interface for the services it needs and accept the implementation via constructor. Server callers wire in real implementations; tests wire in mocks. Example from local-system:
export interface ILocalSystemService {
readLocalFile: (params: any) => Promise<any>;
writeFile: (params: any) => Promise<any>;
/* β¦ */
}
export class LocalSystemExecutionRuntime extends ComputerRuntime {
constructor(private service: ILocalSystemService) {
super();
}
/* methods delegate to this.service.* */
}
The client/executor instantiates it once with the real service:
import { localFileService } from '@/services/electron/localFileService';
import { LocalSystemExecutionRuntime } from '@lobechat/tool-runtime';
class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {
private runtime = new LocalSystemExecutionRuntime(localFileService);
/* β¦ */
}
When ExecutionRuntime is the only thing you ship
Some tools are server-only β there's no frontend executor. builtin-tool-web-browsing is the canonical example: only ./ and ./executionRuntime are exported, no ./executor, and the runtime is constructed by the server-side ToolExecutionService. Skip client/executor/ entirely for those.
When the executor reuses the runtime as-is
Pure-compute tools (builtin-tool-calculator) often have an executor whose ApiName methods call executor.calculate(args) and an ExecutionRuntime whose methods call calculatorExecutor.calculate(args) β same logic, two thin wrappers. That's fine; the duplication buys you the bundle split.
The Result Contract
BuiltinServerRuntimeOutput (what ExecutionRuntime returns)
{
content: string; // the LLM-facing text β never undefined; default to error message
state?: any; // result-domain object the UI reads as pluginState
success: boolean; // mandatory
error?: any; // raw error; the executor will repackage
}
BuiltinToolResult (what the executor returns to the runtime)
{
success: boolean;
content?: string;
state?: any;
error?: { type: string; message: string; body?: any };
metadata?: Record<string, any>; // rare; e.g. { agentCouncil: true }
stop?: boolean; // rare; halt the orchestration step
}
The toResult funnel (mandatory)
Every executor method returns through a single toResult() to enforce two invariants:
contentis never undefined. A missing content collapses downstream into'', leaving the Debug pane blank whilepluginStatewas already saved. See theglobLocalFilesregression inlocal-system/src/client/executor/index.ts:60-84.statesurvives failures. Renderers can keep showing partial output even whensuccess: false.
private toResult(output: BuiltinServerRuntimeOutput): BuiltinToolResult {
const errorMessage = typeof output.error?.message === 'string' ? output.error.message : undefined;
const safeContent = output.content || errorMessage || 'Tool execution failed';
if (!output.success) {
return {
success: false,
content: safeContent,
state: output.state,
error: output.error
? { type: 'PluginServerError', message: errorMessage ?? safeContent, body: output.error }
: undefined,
};
}
return { success: true, content: safeContent, state: output.state };
}
BaseExecutor β How Method Dispatch Works
BaseExecutor.invoke(apiName, params, ctx) does:
if (!this.hasApi(apiName)) return { error: { type: 'ApiNotFound', β¦ }, success: false };
return (this as any)[apiName](params, ctx); // method name MUST equal apiName value
So:
- Method names must equal
<Name>ApiNamevalues, exactly. A typo silently routes to "ApiNotFound". - Methods must be class fields, not class methods, because
thisis lost when registry callsexecutor.invoke(apiName, params, ctx). Always declare asmethodName = async (β¦) => { β¦ }. - Always destructure
apiEnumandidentifierasreadonlyinstance fields, not getters βBaseExecutor.hasApi/getApiNamesreads them synchronously.
BuiltinToolContext β What the Executor Receives
The runtime hands every executor method an optional BuiltinToolContext as the second argument:
| Field | Use |
|---|---|
agentId |
Default agent for "current agent" semantics (e.g. listTasks) |
groupId |
Group chat scope |
topicId |
Current topic β needed when creating messages/operations |
taskId |
Current task identifier β fallback for "implicit" param |
documentId |
Current page/document scope |
messageId |
The tool message being created (for state attachments) |
sourceMessageId |
The user message that triggered this tool turn |
operationId |
Operation lineage (use for cancellation, tracing) |
scope |
'task' | 'agent' | β¦ β toggles default behaviors |
signal: AbortSignal |
Honor for long-running ops |
stepContext |
Cross-message runtime state (lobe-agent todos, etc.) |
registerAfterCompletion(cb) |
Defer side-effects past message-update race |
groupOrchestration |
Group orchestration callbacks |
Use rule: read with ?., fall back to explicit params, never silently override an explicit param with a context value.
i18n Integration
Source of truth: packages/locales/src/default/plugin.ts. Keys follow builtins.<identifier>.<topic>.<β¦>:
| Key | Use |
|---|---|
builtins.<identifier>.title |
Display title (overrides manifest.meta.title when present) |
builtins.<identifier>.apiName.<api> |
Inspector header label (one per ApiName) |
builtins.<identifier>.inspector.<β¦> |
Extra Inspector strings ("no results", chips, counters) |
builtins.<identifier>.<feature>.<β¦> |
Render / Intervention strings, free-form per tool |
For dev preview, also seed locales/zh-CN/plugin.json and locales/en-US/plugin.json. Run bun run i18n before opening a PR β it's slow, so do it once at the end. (See the i18n skill for the full workflow.)
Registry Wiring
Five core files plus optional ones. Miss any and you'll see "tool not found", a missing chip, a blank result card, a stuck spinner, or an approval dialog that never appears.
| File | Add what |
|---|---|
| Required | |
packages/builtin-tools/src/index.ts |
Import <Name>Manifest; push entry to builtinTools. Set hidden/discoverable flags. |
packages/builtin-tools/src/identifiers.ts |
Add <Name>Manifest.identifier to builtinToolIdentifiers. |
packages/builtin-tools/src/inspectors.ts |
Import <Name>Inspectors, <Name>Manifest; add to BuiltinToolInspectors. |
src/store/tool/slices/builtin/executors/index.ts |
Import <name>Executor; add to registerExecutors([β¦]). |
| Conditional β add only if the surface exists | |
packages/builtin-tools/src/renders.ts |
Add to BuiltinToolsRenders if any API has a Render. |
packages/builtin-tools/src/placeholders.ts |
Add to BuiltinToolPlaceholders if any API has a Placeholder. |
packages/builtin-tools/src/streamings.ts |
Add to BuiltinToolStreamings if any API has a Streaming renderer. |
packages/builtin-tools/src/interventions.ts |
Add to BuiltinToolInterventions if any API has an Intervention component. |
packages/builtin-tools/src/portals.ts |
Add to BuiltinToolsPortals if the tool has a Portal. |
packages/builtin-tools/src/displayControls.ts |
Add if Render must show/hide based on result content (rare; see ClaudeCode/Codex). |
Optional flags in packages/builtin-tools/src/index.ts
{
identifier: TaskManifest.identifier,
manifest: TaskManifest,
type: 'builtin',
hidden: true, // hide from chat-input Tools popover
discoverable: false, // exclude from agent builder / skill discovery
}
Lists in the same file you may need to touch:
defaultToolIdsβ added to the agent's tool list by defaultalwaysOnToolIdsβ forced on regardless of user selection (use sparingly).lobe-skillsis the one exception to "always in full": a run with no skill to offer keeps only its sandbox shell (runCommand/exportFile), and the full manifest waits inOperationToolSet.deferredManifestMapuntil a skill is installed mid-run (planSkillsToolDeferralinpackages/mecha/src/toolSet/deferSkillsTool.ts)runtimeManagedToolIdsβ enable state controlled by runtime, not user UI; must mirror the rules map inapps/server/src/modules/Mecha/AgentToolsEngine/index.tsandsrc/helpers/toolEngineering/index.ts
File-Map at a Glance
packages/builtin-tool-<name>/
βββ package.json # exports: ., ./client, ./executor, ./executionRuntime
βββ src/
βββ index.ts # export Manifest, Identifier, types, systemPrompt
βββ manifest.ts # BuiltinToolManifest + Identifier const
βββ types.ts # ApiName + Params/State per API
βββ systemRole.ts # System prompt (multiple variants OK: systemRole.desktop.ts)
βββ ExecutionRuntime/
β βββ index.ts # <Name>ExecutionRuntime β pure runtime, service injection
βββ client/
βββ index.ts # exports for the registries
βββ executor/
β βββ index.ts # <Name>Executor extends BaseExecutor; export <name>Executor
βββ Inspector/
β βββ index.ts # <Name>Inspectors record
β βββ <ApiName>/index.tsx # one folder per API (or .tsx file when trivial)
βββ Render/
β βββ index.ts # <Name>Renders record
β βββ <ApiName>/ # rich renders β folder with subcomponents
βββ Placeholder/
β βββ index.ts
β βββ <ApiName>.tsx # usually a single skeleton file
βββ Streaming/
β βββ index.ts
β βββ <ApiName>/ # live-output renderer
βββ Intervention/
β βββ index.ts
β βββ <ApiName>/ # approval / edit-before-run UI
βββ Portal/
β βββ index.tsx # routing component (switch on apiName)
β βββ <ApiName>/ # full-screen detail view
βββ components/ # FileItem, EngineAvatar, etc. β shared subcomponents
Skip every client/<surface>/ directory you don't need β empty registries are fine.