A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(editor): a plugin can lend the agent a tool
yhh6dff9b70f757
diff --git a/desktop/electron/agent/host.ts b/desktop/electron/agent/host.tsindex 70193ba00..38d35b336 100644--- a/desktop/electron/agent/host.ts+++ b/desktop/electron/agent/host.ts@@ -21,7 +21,7 @@* finished turn all resolve it as declined — a kernel awaiting a promise* nobody will settle is a hang, not an error anyone can see.*/-import { runTurn, agentTools } from './kernel';+import { runTurn, agentTools, type ContributedTool } from './kernel';import { SYSTEM_PROMPT, editorContext } from './prompt';import type {AgentEvent, AgentProvider, AgentSession, ConfirmAnswer, ConfirmDecision, ConfirmRequest, UserImage,@@ -63,6 +63,14 @@ export interface AgentHostDeps {* an error, and the host carries on either way.*/persist?(conversation: PersistedConversation): void;+ /**+ * Tools loaded plugins have contributed, as the WINDOW last reported them.+ *+ * A pull rather than a push into this host: it is read once per session, and+ * the answer has to be whatever is true at that moment — a list captured at+ * construction would be the empty one, since plugins load after main does.+ */+ contributedTools?(): readonly ContributedTool[];}/** A conversation as the host hands it over to be kept. See agent/store.ts. */@@ -278,7 +286,10 @@ export function createAgentHost(deps: AgentHostDeps): AgentHost {if (!session) {try {const provider = deps.provider();- session = provider.createSession({ system: SYSTEM_PROMPT, tools: agentTools() }, resuming);+ session = provider.createSession(+ { system: SYSTEM_PROMPT, tools: agentTools(deps.contributedTools?.() ?? []) },+ resuming,+ );model = provider.model;acceptsImages = provider.acceptsImages;endpoint = provider.id;diff --git a/desktop/electron/agent/kernel.ts b/desktop/electron/agent/kernel.tsindex 9a85346ab..c92813585 100644--- a/desktop/electron/agent/kernel.ts+++ b/desktop/electron/agent/kernel.ts@@ -22,10 +22,57 @@ import { TOOLS, runTool, mutates, irreversible } from '../../shared/toolCatalog.const catalog = TOOLS as CatalogTool[];const byName = new Map(catalog.map((t) => [t.name, t]));-/** The tools an in-editor agent may call. Everything: the coarse- * ESTELLA_MCP_ALLOW_WRITES door exists because a REMOTE client has nobody to- * ask, and this one has the user right there (see the confirm gate below). */-export const agentTools = (): readonly CatalogTool[] => catalog;+/**+ * The tools an in-editor agent may call: the built-in catalog, plus whatever+ * loaded plugins contributed.+ *+ * Everything built-in is offered. The coarse ESTELLA_MCP_ALLOW_WRITES door+ * exists because a REMOTE client has nobody to ask, and this one has the user+ * right there (see the confirm gate below).+ *+ * Contributed tools are dispatched through ONE generic door on the editor+ * surface rather than each getting a method of its own — a plugin's tool runs+ * in the renderer where the plugin lives, and adding a transport per plugin+ * would be a second way for an agent to reach the editor.+ *+ * Snapshotted per SESSION, not per turn: the tool list renders first in the+ * prompt prefix, so a list that changed mid-conversation would invalidate every+ * cached byte after it. A plugin loaded while a conversation is open joins the+ * next one.+ */+export function agentTools(contributed: readonly ContributedTool[] = []): readonly CatalogTool[] {+ if (contributed.length === 0) return catalog;+ const out = [...catalog];+ const taken = new Set(catalog.map((t) => t.name));+ for (const tool of contributed) {+ // Refused rather than renamed. A tool the model calls by a name the plugin+ // did not choose is a tool whose own docs are wrong, and shadowing a+ // built-in would let a plugin quietly redefine `delete_entity`.+ if (taken.has(tool.name)) continue;+ taken.add(tool.name);+ out.push({+ name: tool.name,+ description: tool.description,+ schema: tool.schema,+ effect: tool.effect,+ root: 'editor',+ method: PLUGIN_TOOL_METHOD,+ args: (input: unknown) => [tool.name, input],+ } as unknown as CatalogTool);+ }+ return out;+}++/** One generic door on `window.__estellaEditor` for every contributed tool. */+const PLUGIN_TOOL_METHOD = 'runPluginTool';++/** What the window says a plugin contributed. The handler stays over there. */+export interface ContributedTool {+ name: string;+ description: string;+ schema: unknown;+ effect: 'read' | 'undoable' | 'irreversible';+}/** Why `tool` needs saying out loud. A code — the editor renders the sentence,* because it is the side that knows the reader's language. */diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex 295cba4eb..86129051b 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -47,6 +47,7 @@ import { mcpMode, startMcpEndpoint, stopMcpEndpoint, mcpEndpointStatus } from '.import { secretStatus, setSecret, clearSecret, readSecret } from './secrets';import { createSurfaceDriver } from './surfaceDriver';import { createAgentHost } from './agent/host';+import type { ContributedTool } from './agent/kernel';import {saveConversation, loadConversation, listConversations, deleteConversation,} from './agent/store';@@ -680,6 +681,8 @@ ipcMain.handle('secret:clear', (_e, id: string) => clearSecret(id));// separately; read at session creation, so a change lands on the next// conversation rather than under the one being read.let agentEndpoint: { baseUrl?: string; model?: string; keyId?: string; contextWindow?: number; effort?: string } = {};+/** Contributed agent tools, as the window last reported them. */+let agentPluginTools: ContributedTool[] = [];const agentHost = createAgentHost({driver: createSurfaceDriver(() => win),@@ -704,6 +707,7 @@ const agentHost = createAgentHost({// there is nowhere for them to go, which is a state, not a failure — and a// disk that will not take them must never cost the user their turn, so this// reports and moves on.+ contributedTools: () => agentPluginTools,persist: (conversation) => {if (!projectRoot) return;void saveConversation(projectRoot, conversation)@@ -732,12 +736,19 @@ ipcMain.handle('agent:resumeConversation', async (_e, id: string) => {ipcMain.handle('agent:deleteConversation', async (_e, id: string) => {if (projectRoot) await deleteConversation(projectRoot, id);});-ipcMain.handle('agent:setEndpoint', (_e, patch: { baseUrl?: string; model?: string; keyId?: string; contextWindow?: number }) => {+ipcMain.handle('agent:setEndpoint', (_e, patch: { baseUrl?: string; model?: string; keyId?: string; contextWindow?: number; effort?: string }) => {agentEndpoint = { ...agentEndpoint, ...patch };// `ready` is derived from which key this points at, so it just changed.agentHost.announce();});+// What loaded plugins have contributed for the agent to call. The window owns+// the handlers (they run where the plugin lives); this is only the metadata a+// session needs to describe them to the model.+ipcMain.handle('agent:setTools', (_e, tools: ContributedTool[]) => {+ agentPluginTools = Array.isArray(tools) ? tools : [];+});+// — Custom window controls (frameless Windows/Linux; macOS uses native traffic lights) —ipcMain.handle('window:minimize', () => win?.minimize());ipcMain.handle('window:toggleMaximize', () => {diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.tsindex 5afc7d1a1..ecfb00270 100644--- a/desktop/electron/preload.ts+++ b/desktop/electron/preload.ts@@ -141,6 +141,11 @@ const api = {* can push its own field. */setEndpoint: (patch: { baseUrl?: string; model?: string; keyId?: string; contextWindow?: number; effort?: string }): Promise<void> =>ipcRenderer.invoke('agent:setEndpoint', patch),+ /** Report what loaded plugins contributed for the agent to call. Metadata+ * only — the handlers stay in this window, reached through the editor+ * surface like every other tool. Read once per session. */+ setTools: (tools: readonly { name: string; description: string; schema: unknown; effect: string }[]): Promise<void> =>+ ipcRenderer.invoke('agent:setTools', tools),/** Transcript events + status changes, in the order they happened; returns* an unsubscribe. One channel because the two must not be reordered. */onMessage: (cb: (message: AgentMessage) => void): (() => void) => {diff --git a/desktop/src/i18n/messages/plugins.ts b/desktop/src/i18n/messages/plugins.tsindex 2bee747a8..ef147af09 100644--- a/desktop/src/i18n/messages/plugins.ts+++ b/desktop/src/i18n/messages/plugins.ts@@ -75,6 +75,7 @@ export const pluginMessages = defineMessages({'plug.kind.assetType': { en: 'Asset type', zh: '资产类型' },'plug.kind.entityTemplate': { en: 'Entity', zh: '实体' },'plug.kind.contextMenu': { en: 'Menu item', zh: '菜单项' },+ 'plug.kind.agentTool': { en: 'Agent tool', zh: 'Agent 工具' },// — New plugin. The editor writes the folder because the SHAPE of a plugin is// the part that is hard to know before you have seen one. —diff --git a/desktop/src/main.tsx b/desktop/src/main.tsxindex 2e4e9b667..c9caf4498 100644--- a/desktop/src/main.tsx+++ b/desktop/src/main.tsx@@ -46,6 +46,7 @@ import { useSelection } from './store/selectionStore';import { PlayRealm } from './engine/PlayRealm';import { dockApi } from './layout/dockApi';import { EditorControlSurface } from './engine/EditorSession';+import { runContributedTool } from './plugins/agentTools';import { EditorHistory } from './engine/EditorHistory';import { SceneModel } from './engine/SceneModel';import { EngineHost } from './engine/EngineHost';@@ -238,6 +239,15 @@ function buildEditorAutomation(): unknown {}),/** Dispatch any registered editor command by id (the UI's own channel). */runCommand: (id: string) => commands.run(id),+ /**+ * The one door every plugin-contributed agent tool is dispatched through.+ *+ * The handler lives here because the plugin does; main only ever knew the+ * metadata. One door rather than a method per tool: a transport per plugin+ * would be a second way for an agent to reach this editor, and the whole+ * point of the shared catalog is that there is one.+ */+ runPluginTool: (name: string, input: unknown) => runContributedTool(name, input),/** Save the open scene to disk (the toolbar Save, awaitable). */save: () => ProjectStore.save(),/** Patch the project's physics feature (Project Settings → Physics). */diff --git a/desktop/src/panels/PluginsPanel.tsx b/desktop/src/panels/PluginsPanel.tsxindex ed6695f7e..ee2ad2768 100644--- a/desktop/src/panels/PluginsPanel.tsx+++ b/desktop/src/panels/PluginsPanel.tsx@@ -56,6 +56,7 @@ const KIND_LABEL: Record<ContributionKind, MsgKey> = {assetType: 'plug.kind.assetType',entityTemplate: 'plug.kind.entityTemplate',contextMenu: 'plug.kind.contextMenu',+ agentTool: 'plug.kind.agentTool',};function PhaseChip({ phase }: { phase: PluginPhase }) {diff --git a/desktop/src/plugins/agentTools.ts b/desktop/src/plugins/agentTools.tsnew file mode 100644index 000000000..64b08ddea--- /dev/null+++ b/desktop/src/plugins/agentTools.ts@@ -0,0 +1,89 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file agentTools.ts+ * @brief Tools a plugin lends to the built-in agent.+ *+ * A plugin already extends what a PERSON can do here — a command, a panel, a+ * viewport tool. This is the same extension aimed at the other operator: the+ * agent's whole vocabulary is the tool catalog, so a plugin that adds a+ * capability the agent cannot name has added it for half the editor.+ *+ * The handler stays in this window, because that is where the plugin lives. All+ * that crosses to main is what a session needs in order to DESCRIBE the tool to+ * a model — name, description, schema, effect — and the kernel dispatches every+ * one of them back through a single door on the editor surface rather than+ * inventing a transport per plugin.+ *+ * The effect a plugin declares is taken at its word, and that is not a gap: a+ * plugin runs in this renderer with the whole editor surface in reach, so it+ * could do the same work through a command without declaring anything. The+ * boundary is the trust prompt at install, not this field. What the field buys+ * is the CONFIRM GATE working correctly for an honest plugin.+ */+import { ContributionRegistry, type Owner, type Disposable } from '@/contrib/ContributionRegistry';+import type { AgentToolContribution } from './types';++/** The registry keys by `id`; a tool's id IS its name — the model addresses it+ * by that and nothing else, so a second identifier could only disagree. */+type RegisteredTool = AgentToolContribution & { id: string };++const registry = new ContributionRegistry<RegisteredTool>('agent tool');++/**+ * Why this tool cannot be offered, or null.+ *+ * The name has to be namespaced with the plugin's id for the reason every other+ * contribution point says so — but here it also stops a plugin from being able+ * to define `delete_entity`, which a model would then call believing it knows+ * what it does.+ */+export function agentToolProblem(pluginId: string, tool: AgentToolContribution): string | null {+ if (!tool.name) return 'an agent tool needs a `name`';+ if (!tool.name.startsWith(`${pluginId}.`)) {+ return `\`name\` must start with "${pluginId}." — an un-namespaced tool can shadow a built-in one`;+ }+ // The model addresses tools by name on the wire; the API's own constraint.+ if (!/^[a-z0-9][a-z0-9_.-]*$/i.test(tool.name)) {+ return '`name` may contain only letters, digits, `_`, `.` and `-`';+ }+ if (!tool.description) {+ return 'an agent tool needs a `description` — it is the only thing the model reads to decide whether to call it';+ }+ if (typeof tool.run !== 'function') return 'an agent tool needs a `run(input)`';+ return null;+}++export const registerAgentTool = (tool: AgentToolContribution, owner: Owner): Disposable =>+ registry.register(owner, { ...tool, id: tool.name });++/** Everything contributed, in registration order. */+export const agentToolContributions = (): AgentToolContribution[] => [...registry.all()];++export const subscribeAgentTools = (fn: () => void): (() => void) => registry.subscribe(fn);++/** Run one by name. The door `window.__estellaEditor.runPluginTool` opens. */+export async function runContributedTool(name: string, input: unknown): Promise<unknown> {+ const tool = registry.all().find((t) => t.name === name);+ // Named, because the alternative is a model retrying a tool that will never+ // exist: the plugin that offered it was unloaded mid-conversation.+ if (!tool) throw new Error(`no such plugin tool: ${name} (was its plugin unloaded?)`);+ return tool.run(input);+}++/**+ * Tell main what is on offer, as metadata only.+ *+ * Pushed on every change rather than asked for: main reads the list when it+ * builds a session, which is synchronous, and a round trip cannot happen there.+ */+export function publishAgentTools(): void {+ void window.estella?.agent?.setTools(+ agentToolContributions().map((t) => ({+ name: t.name,+ description: t.description,+ schema: t.schema ?? { type: 'object' },+ effect: t.effect ?? 'read',+ })),+ );+}diff --git a/desktop/src/plugins/context.ts b/desktop/src/plugins/context.tsindex 25c6ae863..a3710d0f2 100644--- a/desktop/src/plugins/context.ts+++ b/desktop/src/plugins/context.ts@@ -39,7 +39,9 @@ import type { InspectorFieldValue } from '@/types';import type { Owner, Disposable as CoreDisposable } from '@/contrib/ContributionRegistry';import type { PointerInput as CorePointerInput } from '@/tools/EditorTool';import type { PluginManifest, PluginCapability } from './manifest';+import { agentToolProblem, registerAgentTool, publishAgentTools } from './agentTools';import type {+ AgentToolContribution,AssetTypeContribution, CommandContribution, ContextMenuContribution, Disposable, EditorEvents,EditorPlugin, EditorProjectApi, EditorSceneApi, EntityTemplateContribution, FieldValue,InspectorContribution, OverlayContribution, PanelContribution, PluginContext,@@ -195,7 +197,8 @@ export type ContributionKind =| 'inspector'| 'assetType'| 'entityTemplate'- | 'contextMenu';+ | 'contextMenu'+ | 'agentTool';/** One thing a plugin added, as the Plugins panel shows it. */export interface PluginContribution {@@ -404,6 +407,27 @@ export function buildPluginContext(}),);+ /**+ * A tool the agent may call. Registered like any other contribution, and then+ * ANNOUNCED: main reads the list when it builds a session, and it cannot ask+ * for it at that moment — session creation is synchronous.+ */+ const registerAgentToolContribution = (tool: AgentToolContribution): Disposable => {+ const problem = agentToolProblem(id, tool);+ // Named and refused, never silently dropped: the plugin's own docs will say+ // the tool exists, and an agent that never sees it looks broken from here.+ if (problem) {+ log.warn(`agent tool "${tool.name}": ${problem}`);+ return { dispose: () => {} };+ }+ const handle = noted('agentTool', tool.name, tool.name, registerAgentTool({+ ...tool,+ run: (input: unknown) => guard(`agent tool ${tool.name}`, () => tool.run(input), undefined),+ }, owner));+ publishAgentTools();+ return { dispose: () => { handle.dispose(); publishAgentTools(); } };+ };+const registerContextMenuItem = (item: ContextMenuContribution): Disposable =>noted('contextMenu',@@ -445,6 +469,7 @@ export function buildPluginContext(assets: { registerType: registerAssetType },entities: { registerTemplate },contextMenus: { register: registerContextMenuItem },+ agentTools: { register: registerAgentToolContribution },scene: sceneApi(),project: projectApi(),viewport: viewportProjection,diff --git a/desktop/src/plugins/types.ts b/desktop/src/plugins/types.tsindex e709ff67d..87f1ee75d 100644--- a/desktop/src/plugins/types.ts+++ b/desktop/src/plugins/types.ts@@ -334,6 +334,45 @@ export interface ContextMenuTarget {path?: string | null;}+/**+ * A tool the built-in agent may call.+ *+ * The agent's entire vocabulary is the tool catalog, so a plugin that adds a+ * capability without adding a tool has added it for the person and not for the+ * agent. Namespace `name` with your plugin id — an un-namespaced tool can+ * shadow a built-in one, and the model would call it believing it knows what it+ * does.+ *+ * `description` is not documentation; it is the ONLY thing the model reads when+ * deciding whether this is the right tool. Say what it does and when to reach+ * for it, in a sentence.+ */+export interface AgentToolContribution {+ /** Namespaced with your plugin id, e.g. `acme.bake-occlusion`. */+ name: string;+ /** What it does and when to use it — written for the model, not for a menu. */+ description: string;+ /**+ * JSON Schema for `input`. Defaults to "an object with no properties".+ * The kernel validates against this before your handler runs, so a+ * malformed call is refused rather than handed to you half-parsed.+ */+ schema?: unknown;+ /**+ * What calling it costs, which is what decides whether the person is asked+ * first: `read` and `undoable` run unasked (the turn's checkpoint is the+ * approval), `irreversible` stops and asks. Defaults to `read`.+ *+ * Declare it honestly. Nothing verifies it — a plugin already runs with the+ * whole editor surface in reach — but an `irreversible` tool declared+ * `read` is one that will run without anyone being asked.+ */+ effect?: 'read' | 'undoable' | 'irreversible';+ /** Do the work. Whatever it returns is JSON-encoded for the model; throwing+ * reports the message as a failed call, which the model can act on. */+ run(input: unknown): unknown | Promise<unknown>;+}+export interface ContextMenuContribution {/** Namespaced id, e.g. `acme.reveal-refs`. */id: string;@@ -495,6 +534,10 @@ export interface PluginContext {readonly contextMenus: {register(item: ContextMenuContribution): Disposable;};+ /** Lend the built-in agent a tool. See {@link AgentToolContribution}. */+ readonly agentTools: {+ register(tool: AgentToolContribution): Disposable;+ };readonly scene: EditorSceneApi;readonly project: EditorProjectApi;diff --git a/desktop/tests/agent-plugin-tools.test.ts b/desktop/tests/agent-plugin-tools.test.tsnew file mode 100644index 000000000..7e0bab6f8--- /dev/null+++ b/desktop/tests/agent-plugin-tools.test.ts@@ -0,0 +1,102 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Tools a plugin lends the agent.+ *+ * Two halves, tested where each lives. The kernel decides what may join the+ * catalog and how it is dispatched; the renderer decides what a plugin is+ * allowed to offer in the first place. The rule they share is the namespace —+ * an un-namespaced tool can shadow a built-in, and a model calling `delete_entity`+ * believes it knows what that does.+ */+import { describe, it, expect } from 'vitest';+import { agentTools, type ContributedTool } from '../electron/agent/kernel';+import { agentToolProblem } from '../src/plugins/agentTools';+import type { AgentToolContribution } from '../src/plugins/types';++const tool = (over: Partial<ContributedTool> = {}): ContributedTool => ({+ name: 'acme.bake',+ description: 'Bake the thing.',+ schema: { type: 'object' },+ effect: 'undoable',+ ...over,+});++describe('the catalog a session is given', () => {+ it('is the built-in one when nothing was contributed', () => {+ expect(agentTools()).toBe(agentTools([]));+ expect(agentTools().some((t) => t.name === 'get_scene_tree')).toBe(true);+ });++ it('appends what plugins offered, after the built-ins', () => {+ const merged = agentTools([tool()]);+ expect(merged).toHaveLength(agentTools().length + 1);+ expect(merged.at(-1)).toMatchObject({ name: 'acme.bake', effect: 'undoable' });+ });++ it('keeps the built-in when a plugin claims its name', () => {+ // Refused, not renamed: a model calling a shadowed `delete_entity`+ // believes it knows what happens next.+ const merged = agentTools([tool({ name: 'delete_entity', description: 'Not really.' })]);+ expect(merged.filter((t) => t.name === 'delete_entity')).toHaveLength(1);+ expect(merged.find((t) => t.name === 'delete_entity')?.description).not.toBe('Not really.');+ });++ it('keeps the first of two plugins claiming one name', () => {+ const merged = agentTools([tool({ description: 'first' }), tool({ description: 'second' })]);+ expect(merged.filter((t) => t.name === 'acme.bake')).toHaveLength(1);+ expect(merged.find((t) => t.name === 'acme.bake')?.description).toBe('first');+ });++ it('routes every contributed tool through the one door, carrying its own name', () => {+ const entry = agentTools([tool()]).at(-1) as unknown as {+ root: string; method: string; args: (i: unknown) => unknown[];+ };+ expect(entry.root).toBe('editor');+ expect(entry.method).toBe('runPluginTool');+ // The name goes with the call — main knows only metadata, so the window+ // has to be told which handler this is.+ expect(entry.args({ a: 1 })).toEqual(['acme.bake', { a: 1 }]);+ });++ it('carries the declared effect, which is what the confirm gate reads', () => {+ const irreversible = agentTools([tool({ name: 'acme.wipe', effect: 'irreversible' })]).at(-1);+ expect(irreversible?.effect).toBe('irreversible');+ });++ it('does not mutate the built-in catalog', () => {+ const before = agentTools().length;+ agentTools([tool()]);+ expect(agentTools()).toHaveLength(before);+ });+});++describe('what a plugin may offer', () => {+ const ok: AgentToolContribution = { name: 'acme.bake', description: 'Bake it.', run: () => 1 };++ it('accepts a namespaced, described tool with a handler', () => {+ expect(agentToolProblem('acme', ok)).toBeNull();+ });++ it('refuses a name that is not namespaced with the plugin id', () => {+ expect(agentToolProblem('acme', { ...ok, name: 'bake' })).toMatch(/must start with "acme\."/);+ // Someone else's namespace is just as much a shadow.+ expect(agentToolProblem('acme', { ...ok, name: 'other.bake' })).toMatch(/must start with/);+ });++ it('refuses a name the wire cannot address', () => {+ expect(agentToolProblem('acme', { ...ok, name: 'acme.bake it' })).toMatch(/only letters/);+ });++ it('refuses a tool with no description — that is all the model reads', () => {+ expect(agentToolProblem('acme', { ...ok, description: '' })).toMatch(/description/);+ });++ it('refuses one with no handler', () => {+ expect(agentToolProblem('acme', { ...ok, run: undefined as unknown as () => void })).toMatch(/run\(input\)/);+ });++ it('refuses an unnamed tool without blaming the namespace', () => {+ expect(agentToolProblem('acme', { ...ok, name: '' })).toMatch(/needs a `name`/);+ });+});diff --git a/docs/astro/src/content/docs/guides/editor-plugins.mdx b/docs/astro/src/content/docs/guides/editor-plugins.mdxindex 4e5a20f39..7ae6fea0b 100644--- a/docs/astro/src/content/docs/guides/editor-plugins.mdx+++ b/docs/astro/src/content/docs/guides/editor-plugins.mdx@@ -243,6 +243,44 @@ ctx.tools.activate('acme.measure');- `ctx.contextMenus.register(…)` — a row in the Outliner or Content Browserright-click menu, gated by the thing that was clicked.+### Lending the agent a tool++The built-in agent's entire vocabulary is the tool catalog. A plugin that adds a+capability without adding a tool has added it for the person and not for the+agent — so if your plugin can bake occlusion, teach the agent to ask for it:++```typescript+ctx.agentTools.register({+ name: 'acme.bake-occlusion', // must start with your plugin id+ description: 'Bake occlusion for the open scene. Use after moving walls.',+ schema: { type: 'object', properties: { quality: { type: 'number' } } },+ effect: 'undoable',+ run: ({ quality }) => bake(quality ?? 1),+});+```++`description` is not documentation — it is the only thing the model reads when+deciding whether this is the right tool. Say what it does and when to reach for+it.++`effect` decides whether the person is asked first: `read` and `undoable` run+unasked (the turn's checkpoint is the approval), `irreversible` stops and asks.+Nothing verifies it, and that is not a gap — your plugin already runs with the+whole editor surface in reach, so it could do the same work through a command.+The boundary is the trust prompt at install. What the field buys is the confirm+gate behaving correctly for an honest plugin, so declare it honestly.++The name must be namespaced with your plugin id. An un-namespaced tool could+shadow a built-in, and a model calling `delete_entity` believes it knows what+happens next. A tool that breaks any of these rules is refused with the reason+in the Output Log, rather than dropped silently.++Whatever `run` returns is JSON-encoded for the model; throwing reports the+message as a failed call, which the model can read and act on. A tool that+appears while a conversation is open joins the NEXT one — the tool list renders+first in the prompt, so changing it mid-conversation would throw away every+cached byte after it.+## Editing the sceneAlways go through `ctx.scene`. Those writes run through the editor's commanddiff --git a/docs/astro/src/content/docs/zh-cn/guides/editor-plugins.mdx b/docs/astro/src/content/docs/zh-cn/guides/editor-plugins.mdxindex 2676c0536..2f42d8be6 100644--- a/docs/astro/src/content/docs/zh-cn/guides/editor-plugins.mdx+++ b/docs/astro/src/content/docs/zh-cn/guides/editor-plugins.mdx@@ -226,6 +226,28 @@ ctx.tools.activate('acme.measure');- `ctx.contextMenus.register(…)`——大纲或内容浏览器右键菜单里的一行,可按被点击的对象决定是否出现。+### 借一个工具给 Agent++内置 Agent 的全部词汇就是工具目录。**插件加了能力却没加工具,等于只给人加了、没给 Agent 加**——所以如果你的插件能烘焙遮蔽,就把它教给 Agent:++```typescript+ctx.agentTools.register({+ name: 'acme.bake-occlusion', // 必须以你的插件 id 开头+ description: '为当前场景烘焙遮蔽。移动过墙体之后使用。',+ schema: { type: 'object', properties: { quality: { type: 'number' } } },+ effect: 'undoable',+ run: ({ quality }) => bake(quality ?? 1),+});+```++`description` **不是文档**——它是模型判断「该不该调这个」时唯一会读的东西。写清楚它做什么、什么时候该用。++`effect` 决定要不要先问人:`read` 和 `undoable` 直接跑(这一轮的检查点就是许可),`irreversible` 会停下来问。**没有任何东西会去核实它**,而这不是漏洞——你的插件本来就握着整个编辑器接口,同样的事它用一个命令也能做。边界在安装时的信任提示,不在这个字段。这个字段换来的是:对一个诚实的插件,确认门能正确工作。所以请如实声明。++名字必须以你的插件 id 开头。不带命名空间的工具可能**盖住内置工具**,而模型在调 `delete_entity` 时是相信自己知道会发生什么的。违反上述任一条的工具会被**拒绝并在输出日志里说明原因**,不会被静默丢掉。++`run` 返回什么就 JSON 编码给模型;抛出异常会作为一次失败调用上报,消息模型读得到、也能据此调整。对话进行中出现的新工具会加入**下一次**对话——工具列表排在提示词最前面,中途变更会让它之后的每一个缓存字节作废。+## 编辑场景一律走 `ctx.scene`。这些写入经过编辑器的命令层,因此会进入撤销历史,并且能扛过