Skip to content

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.

feat(editor): the project's TypeScript service, and the three questions it answer

esengine5eec7b203d75
diff --git a/desktop/electron-builder.yml b/desktop/electron-builder.yml
index d0a1407ca..7aa253f16 100644
--- a/desktop/electron-builder.yml
+++ b/desktop/electron-builder.yml
@@ -36,6 +36,10 @@ asarUnpack:
# The MCP front: an MCP client runs this with plain node (node cannot read
# inside an asar), which spawns/attaches the editor as the MCP host.
- dist-electron/mcp/**
+ # The TypeScript language service reads its own lib.*.d.ts off disk; keeping
+ # the package unpacked also keeps `getDefaultLibFilePath` returning a path that
+ # exists for anything that later shells out to it.
+ - "**/node_modules/typescript/**"
- "**/node_modules/esengine/dist/**"
- dist/wasm/**
- dist/wasm-wechat/**
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index dd2ac1b61..cf5876970 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -46,6 +46,7 @@ import { installCrashCapture, logsDir } from './resilience';
import { mcpMode, startMcpEndpoint, stopMcpEndpoint, mcpEndpointStatus } from './mcpEndpoint';
import { secretStatus, setSecret, clearSecret, readSecret } from './secrets';
import { createSurfaceDriver } from './surfaceDriver';
+import { adoptProjectScripts } from './scriptService';
import { createAgentHost } from './agent/host';
import type { ContributedTool } from './agent/kernel';
import {
@@ -593,7 +594,7 @@ function createWindow() {
if (pin !== null) win.webContents.on('did-finish-load', () => win?.webContents.setZoomFactor(pin));
if (shotOut) void runScreenshot(win, shotOut);
- if (mcpMode()) void startMcpEndpoint(() => win);
+ if (mcpMode()) void startMcpEndpoint(() => win, () => projectRoot);
// Unsaved-changes quit guard: prompt before closing a window with dirty
// documents (scene or asset editors — the renderer pushes the aggregate via
@@ -670,7 +671,7 @@ ipcMain.on('engine:status', (_e, status: string) => console.log('[engine]', stat
// serve `--attach` at all; `--mcp` keeps its own way in and outranks the setting.
ipcMain.handle('mcp:status', () => mcpEndpointStatus());
ipcMain.handle('mcp:setEnabled', (_e, on: boolean) =>
- on ? startMcpEndpoint(() => win) : stopMcpEndpoint());
+ on ? startMcpEndpoint(() => win, () => projectRoot) : stopMcpEndpoint());
// — Credentials a setting holds (secrets.ts) —
// Three handlers and deliberately no `get`: a secret crosses from the renderer
@@ -693,7 +694,7 @@ let agentEndpoint: { baseUrl?: string; model?: string; keyId?: string; contextWi
let agentPluginTools: ContributedTool[] = [];
const agentHost = createAgentHost({
- driver: createSurfaceDriver(() => win),
+ driver: createSurfaceDriver(() => win, () => projectRoot),
push: (message) => win?.webContents.send('agent:message', message),
// Which key, like which endpoint, is the window's to decide: it is the side
// that knows which provider the user picked.
@@ -819,6 +820,9 @@ const platformRuntimeDirs = (): PlatformRuntimeDirs => ({
async function adoptRoot(root: string): Promise<string | undefined> {
projectRoot = root;
if (win) startProjectWatch(root, win.webContents);
+ // The compiler follows the project. Built lazily on the first question, so an
+ // open pays nothing for a service it may never be asked one.
+ adoptProjectScripts(root);
try {
await ensureSdkTypes(root, SDK_TYPES_CANDIDATES, app.getVersion());
return undefined;
diff --git a/desktop/electron/mcpEndpoint.ts b/desktop/electron/mcpEndpoint.ts
index 4ddbc49e9..8b17a5699 100644
--- a/desktop/electron/mcpEndpoint.ts
+++ b/desktop/electron/mcpEndpoint.ts
@@ -94,12 +94,13 @@ export function mcpEndpointStatus(): McpEndpointStatus {
*/
export async function startMcpEndpoint(
getWin: () => BrowserWindow | null,
+ getRoot: () => string | null = () => null,
): Promise<McpEndpointStatus> {
if (server) return mcpEndpointStatus();
if (starting) return starting;
starting = (async (): Promise<McpEndpointStatus> => {
- const driver = createSurfaceDriver(getWin);
+ const driver = createSurfaceDriver(getWin, getRoot);
try {
server = await createExecEndpoint({
token: TOKEN,
diff --git a/desktop/electron/projectFs.ts b/desktop/electron/projectFs.ts
index d6468ac24..0ec896da8 100644
--- a/desktop/electron/projectFs.ts
+++ b/desktop/electron/projectFs.ts
@@ -194,6 +194,56 @@ export async function listFilesInRoot(root: string, relDir: string): Promise<str
return out;
}
+/** One matching line, with where it is. */
+export interface FileMatch {
+ file: string;
+ line: number;
+ text: string;
+}
+
+/**
+ * Lines matching `query` across the project's visible files — the door between
+ * "list every path" and "read a file whole".
+ *
+ * Without it the only way to find where something is written is to page files
+ * in a hundred lines at a time, which is what a 50k-line `.d.ts` turns into: the
+ * question was "what is on `Input`", and the cost was most of a context window.
+ *
+ * `glob` is a plain suffix/substring filter on the path, not a glob engine —
+ * `.ts` and `src/` both work, and a caller who wants more can filter results.
+ */
+export async function searchInRoot(
+ root: string,
+ opts: { query: string; regex?: boolean; glob?: string; maxResults?: number },
+): Promise<FileMatch[]> {
+ const query = opts.query ?? '';
+ if (!query) throw new Error('search needs a query');
+ const max = Math.max(1, Math.min(opts.maxResults ?? 100, 500));
+ const re = opts.regex
+ ? new RegExp(query, 'i')
+ : new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i');
+ const out: FileMatch[] = [];
+ for await (const rel of walkVisible(root, root)) {
+ if (opts.glob && !rel.includes(opts.glob)) continue;
+ let text: string;
+ try {
+ text = await readFile(resolveInRoot(root, rel), 'utf8');
+ } catch {
+ continue; // Unreadable or binary — a search is not the place to report it.
+ }
+ // A minified bundle or a generated .d.ts can hold one line of a megabyte;
+ // returning it verbatim is how a "search" becomes the thing it was meant to
+ // replace. The location still lands, the line is just clipped.
+ const lines = text.split('\n');
+ for (let i = 0; i < lines.length; i++) {
+ if (!re.test(lines[i])) continue;
+ out.push({ file: rel, line: i + 1, text: lines[i].trim().slice(0, 400) });
+ if (out.length >= max) return out;
+ }
+ }
+ return out;
+}
+
/**
* Rename / move a file or folder within the project. A file's `.meta` sidecar
* travels with it so rename preserves asset identity (uuid). Refuses to clobber
diff --git a/desktop/electron/scriptService.ts b/desktop/electron/scriptService.ts
new file mode 100644
index 000000000..99fac6c1d
--- /dev/null
+++ b/desktop/electron/scriptService.ts
@@ -0,0 +1,285 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file scriptService.ts — the open project's TypeScript language service.
+ *
+ * A project's scripts are TypeScript and the SDK ships `.d.ts`, so the compiler
+ * already knows what an author can only guess at: whether this file compiles,
+ * what `Res(Input)` hands you, which overload `screenToWorld` has. Nothing was
+ * asking it. An agent writing a system had one way to check its work — enter
+ * play and read the log — and one way to learn an API: page a 50k-line `.d.ts`
+ * a hundred lines at a time.
+ *
+ * TypeScript's own LanguageService, not an LSP server subprocess: the consumers
+ * here are tool calls that want three answers (diagnostics, what is this symbol,
+ * where is this text), and LSP would add a process, a protocol and a document
+ * sync layer to wrap the very API tsserver itself is built on.
+ *
+ * Files are read from disk and versioned by mtime, which is the whole of the
+ * sync story because every write in this editor lands on disk first.
+ */
+import ts from 'typescript';
+import { existsSync, readFileSync, statSync } from 'node:fs';
+import path from 'node:path';
+
+/** One diagnostic, in the shape a caller can act on without a compiler in hand. */
+export interface ScriptDiagnostic {
+ file: string;
+ line: number;
+ column: number;
+ code: number;
+ category: 'error' | 'warning' | 'suggestion' | 'message';
+ message: string;
+}
+
+/** What the compiler knows about a name, for someone who cannot read the .d.ts. */
+export interface SymbolInfo {
+ name: string;
+ kind: string;
+ /** The declaration's own text — the signature, as TypeScript renders it. */
+ signature: string;
+ /** Its doc comment, if it carries one. */
+ doc?: string;
+ file: string;
+ line: number;
+}
+
+const SCRIPT_EXT = /\.(ts|tsx|mts|cts)$/;
+
+/**
+ * The compiler options a project gets when it has no tsconfig of its own. The
+ * `esengine` path mirrors what `ensureSdkTypes` stages, so a scratch project
+ * still resolves the SDK rather than reporting every import as missing — a
+ * service that answers "cannot find module 'esengine'" 40 times is worse than
+ * no service at all.
+ */
+const fallbackOptions = (root: string): ts.CompilerOptions => ({
+ target: ts.ScriptTarget.ES2020,
+ module: ts.ModuleKind.ESNext,
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
+ strict: true,
+ skipLibCheck: true,
+ noEmit: true,
+ allowJs: false,
+ // Absolute, and no baseUrl: TypeScript 6 deprecates baseUrl, and a relative
+ // path in `paths` resolves against the tsconfig that declared it — which is
+ // exactly what a project WITHOUT one does not have.
+ paths: {
+ esengine: [path.join(root, '.esengine', 'sdk', 'index.d.ts')],
+ 'esengine/*': [path.join(root, '.esengine', 'sdk', '*')],
+ },
+});
+
+/**
+ * The staged SDK types, which belong in the compilation whether or not a project
+ * file happens to import them yet.
+ *
+ * A fresh project's `src/main.ts` imports only `./components`, so nothing pulled
+ * `esengine` in — and the moment someone most needs to ask what `Input` is (the
+ * one before they have written the import) `lookup_symbol` answered with an
+ * empty list. Naming them as roots costs one parse and makes the SDK askable
+ * from the first turn.
+ */
+function sdkTypeRoots(root: string): string[] {
+ const index = path.join(root, '.esengine', 'sdk', 'index.d.ts');
+ return existsSync(index) ? [index] : [];
+}
+
+function loadConfig(root: string): { options: ts.CompilerOptions; fileNames: string[] } {
+ const configPath = path.join(root, 'tsconfig.json');
+ if (!existsSync(configPath)) {
+ const src = path.join(root, 'src');
+ const fileNames = existsSync(src)
+ ? ts.sys.readDirectory(src, ['.ts', '.tsx'], undefined, undefined)
+ : [];
+ return { options: fallbackOptions(root), fileNames: [...fileNames, ...sdkTypeRoots(root)] };
+ }
+ const read = ts.readConfigFile(configPath, ts.sys.readFile);
+ const parsed = ts.parseJsonConfigFileContent(read.config ?? {}, ts.sys, root);
+ // A project tsconfig is written for `tsc` runs, so it may name an outDir and
+ // emit; the service only ever answers questions.
+ return {
+ options: { ...parsed.options, noEmit: true },
+ fileNames: [...parsed.fileNames, ...sdkTypeRoots(root)],
+ };
+}
+
+class ProjectScripts {
+ private readonly service: ts.LanguageService;
+ private readonly options: ts.CompilerOptions;
+ private fileNames: string[];
+ /** Bumped for a file whose mtime we cannot read (deleted, or mid-write). */
+ private readonly versions = new Map<string, string>();
+
+ constructor(readonly root: string) {
+ const { options, fileNames } = loadConfig(root);
+ this.options = options;
+ this.fileNames = fileNames;
+
+ const host: ts.LanguageServiceHost = {
+ getScriptFileNames: () => this.fileNames,
+ getScriptVersion: (fileName) => {
+ try {
+ return String(statSync(fileName).mtimeMs);
+ } catch {
+ return this.versions.get(fileName) ?? '0';
+ }
+ },
+ getScriptSnapshot: (fileName) => {
+ try {
+ return ts.ScriptSnapshot.fromString(readFileSync(fileName, 'utf8'));
+ } catch {
+ return undefined;
+ }
+ },
+ getCurrentDirectory: () => root,
+ getCompilationSettings: () => this.options,
+ getDefaultLibFileName: (o) => ts.getDefaultLibFilePath(o),
+ fileExists: ts.sys.fileExists,
+ readFile: ts.sys.readFile,
+ readDirectory: ts.sys.readDirectory,
+ directoryExists: ts.sys.directoryExists,
+ getDirectories: ts.sys.getDirectories,
+ realpath: ts.sys.realpath,
+ };
+ this.service = ts.createLanguageService(host, ts.createDocumentRegistry());
+ }
+
+ /** Re-read the file list: a script created since the service started is not in it. */
+ rescan(): void {
+ this.fileNames = loadConfig(this.root).fileNames;
+ }
+
+ private toDiagnostic(d: ts.Diagnostic): ScriptDiagnostic {
+ const file = d.file ? path.relative(this.root, d.file.fileName) : '(project)';
+ const pos = d.file && d.start !== undefined
+ ? d.file.getLineAndCharacterOfPosition(d.start)
+ : { line: 0, character: 0 };
+ const category = d.category === ts.DiagnosticCategory.Error ? 'error'
+ : d.category === ts.DiagnosticCategory.Warning ? 'warning'
+ : d.category === ts.DiagnosticCategory.Suggestion ? 'suggestion' : 'message';
+ return {
+ file,
+ line: pos.line + 1,
+ column: pos.character + 1,
+ code: d.code,
+ category,
+ message: ts.flattenDiagnosticMessageText(d.messageText, ' '),
+ };
+ }
+
+ /** Errors in one file, or across every script the project compiles. */
+ diagnostics(relPath?: string): ScriptDiagnostic[] {
+ this.rescan();
+ const wanted = relPath
+ ? [path.resolve(this.root, relPath)]
+ : this.fileNames.filter((f) => SCRIPT_EXT.test(f) && !f.endsWith('.d.ts'));
+ const out: ScriptDiagnostic[] = [];
+ for (const file of wanted) {
+ if (!existsSync(file)) continue;
+ for (const d of [
+ ...this.service.getSyntacticDiagnostics(file),
+ ...this.service.getSemanticDiagnostics(file),
+ ]) out.push(this.toDiagnostic(d));
+ }
+ return out;
+ }
+
+ /**
+ * What the compiler knows about a name — the answer that used to cost a
+ * hundred paged reads of the SDK's .d.ts.
+ *
+ * Exact-name matches first: someone asking for `Input` wants the class, not
+ * the thirty things whose names contain it.
+ */
+ /**
+ * The declaration as it is WRITTEN, from its line to the end of its body.
+ *
+ * quickInfo at a navigate-to hit degrades to the bare kind and name for
+ * declared functions, interfaces and type aliases — `function defineComponent`,
+ * `interface QueryBuilder` — which answers nothing and sends the asker back for
+ * another round trip. The source text always says the whole thing.
+ */
+ private declarationText(source: ts.SourceFile, start: number): string {
+ const text = source.getFullText();
+ const from = text.lastIndexOf('\n', start) + 1;
+ let depth = 0;
+ let end = from;
+ for (; end < text.length && end - from < 1200; end++) {
+ const ch = text[end];
+ if (ch === '{') depth++;
+ else if (ch === '}') { depth--; if (depth <= 0) { end++; break; } }
+ else if (ch === ';' && depth === 0) { end++; break; }
+ }
+ return text.slice(from, end).replace(/\s+/g, ' ').trim().slice(0, 800);
+ }
+
+ lookup(name: string, limit = 8): SymbolInfo[] {
+ this.rescan();
+ const items = this.service.getNavigateToItems(name, 64, undefined, false, true);
+ const ranked = [...items].sort((a, b) => {
+ const exact = (i: ts.NavigateToItem) => (i.name === name ? 0 : i.name.toLowerCase() === name.toLowerCase() ? 1 : 2);
+ return exact(a) - exact(b) || a.name.length - b.name.length;
+ });
+ const out: SymbolInfo[] = [];
+ for (const item of ranked.slice(0, limit)) {
+ const info = this.service.getQuickInfoAtPosition(item.fileName, item.textSpan.start);
+ const program = this.service.getProgram();
+ const source = program?.getSourceFile(item.fileName);
+ const line = source ? source.getLineAndCharacterOfPosition(item.textSpan.start).line + 1 : 0;
+ const quick = info ? ts.displayPartsToString(info.displayParts) : '';
+ // A quickInfo that names no parameters and no type is the degenerate form
+ // ("function Query"); the source text is then the only real answer. Where it
+ // IS complete it is better than raw source — it carries the owning type
+ // ("(method) InputState.isMouseButtonPressed(button: number): boolean").
+ const useQuick = quick.includes('(') || quick.includes(':');
+ const declared = source ? this.declarationText(source, item.textSpan.start) : '';
+ out.push({
+ name: item.name,
+ kind: item.kind,
+ signature: (useQuick ? quick : declared) || quick || `${item.kind} ${item.name}`,
+ doc: info?.documentation?.length ? ts.displayPartsToString(info.documentation) : undefined,
+ file: path.relative(this.root, item.fileName),
+ line,
+ });
+ }
+ return out;
+ }
+
+ dispose(): void {
+ this.service.dispose();
+ }
+}
+
+let current: ProjectScripts | null = null;
+
+/** Point the service at a project (idempotent for the one already open). */
+export function adoptProjectScripts(root: string): void {
+ if (current?.root === root) return;
+ current?.dispose();
+ current = null;
+ // Built lazily: opening a project must not pay for a service nobody asked a
+ // question of, and the first question pays for the SDK's .d.ts either way.
+ pendingRoot = root;
+}
+
+let pendingRoot: string | null = null;
+
+function service(): ProjectScripts {
+ if (!current) {
+ if (!pendingRoot) throw new Error('no project open — script diagnostics need one');
+ current = new ProjectScripts(pendingRoot);
+ }
+ return current;
+}
+
+export function scriptDiagnostics(relPath?: string): ScriptDiagnostic[] {
+ return service().diagnostics(relPath);
+}
+
+export function lookupScriptSymbol(name: string, limit?: number): SymbolInfo[] {
+ return service().lookup(name, limit);
+}
+
+/** Whether a path is something the service has an opinion about. */
+export const isScriptPath = (relPath: string): boolean => SCRIPT_EXT.test(relPath);
diff --git a/desktop/electron/surfaceDriver.ts b/desktop/electron/surfaceDriver.ts
index 2af52c55b..ca6694f73 100644
--- a/desktop/electron/surfaceDriver.ts
+++ b/desktop/electron/surfaceDriver.ts
@@ -17,6 +17,8 @@
* so an in-process caller and a remote MCP client cannot drift apart.
*/
import type { BrowserWindow } from 'electron';
+import { scriptDiagnostics, lookupScriptSymbol, isScriptPath } from './scriptService';
+import { searchInRoot, writeInRoot } from './projectFs';
/** What the tool registry calls: a surface/editor method, plus the two escape
* hatches it also knows about (`js` renderer code, `op` main-process routines). */
@@ -68,12 +70,20 @@ const encodeArgs = (args: readonly unknown[]): string =>
* recreated window keeps working and a driver built before the window exists
* is still valid.
*/
-export function createSurfaceDriver(getWin: () => BrowserWindow | null): SurfaceDriver {
+export function createSurfaceDriver(
+ getWin: () => BrowserWindow | null,
+ getRoot: () => string | null = () => null,
+): SurfaceDriver {
const requireWin = (): BrowserWindow => {
const win = getWin();
if (!win) throw new Error('no editor window');
return win;
};
+ const requireProjectRoot = (): string => {
+ const root = getRoot();
+ if (!root) throw new Error('no project open');
+ return root;
+ };
const exec = async (code: string): Promise<unknown> => {
const win = requireWin();
@@ -154,6 +164,29 @@ export function createSurfaceDriver(getWin: () => BrowserWindow | null): Surface
+ `const i = p.input; ${call} return 'ok'; })()`,
)));
}
+ // — What the TypeScript compiler knows. Main-process because the language
+ // service lives here (scriptService.ts), reading the project off disk. —
+ case 'check_scripts':
+ return scriptDiagnostics(input.path ? String(input.path) : undefined);
+ case 'lookup_symbol':
+ return lookupScriptSymbol(String(input.name ?? ''), input.limit === undefined ? undefined : Number(input.limit));
+ case 'search_project_files':
+ return searchInRoot(requireProjectRoot(), {
+ query: String(input.query ?? ''),
+ regex: Boolean(input.regex),
+ glob: input.glob === undefined ? undefined : String(input.glob),
+ maxResults: input.maxResults === undefined ? undefined : Number(input.maxResults),
+ });
+ case 'write_project_file': {
+ // The write and the compiler's verdict on it are ONE answer. Split apart
+ // they are two tool calls, the second of which nobody makes: an agent
+ // that has just written a file believes it.
+ const relPath = String(input.path ?? '');
+ await writeInRoot(requireProjectRoot(), relPath, String(input.content ?? ''));
+ if (!isScriptPath(relPath)) return { ok: true, path: relPath };
+ const diagnostics = scriptDiagnostics(relPath).filter((d) => d.category === 'error');
+ return { ok: true, path: relPath, errors: diagnostics.length, diagnostics: diagnostics.slice(0, 40) };
+ }
default:
throw new Error(`unknown main-process op: ${op}`);
}
diff --git a/desktop/package.json b/desktop/package.json
index 731b152a8..31af52411 100644
--- a/desktop/package.json
+++ b/desktop/package.json
@@ -80,6 +80,7 @@
"pngjs": "^7.0.0",
"react": "^19.2.0",
"react-dom": "^19.2.0",
+ "typescript": "^6.0.3",
"wasm-media-encoders": "^0.7.0",
"zustand": "^5.0.14"
},
@@ -93,7 +94,6 @@
"@vitejs/plugin-react": "^6.0.2",
"electron": "^42.4.1",
"electron-builder": "^26.15.3",
- "typescript": "^6.0.3",
"vite": "^8.0.16",
"vite-plugin-electron": "^1.0.4",
"vite-plugin-electron-renderer": "^1.0.0",
diff --git a/desktop/scripts/editor-mcp-host.mjs b/desktop/scripts/editor-mcp-host.mjs
index 9932d8b37..63506d1c7 100644
--- a/desktop/scripts/editor-mcp-host.mjs
+++ b/desktop/scripts/editor-mcp-host.mjs
@@ -88,6 +88,14 @@ app.whenReady().then(async () => {
const image = await win.webContents.capturePage();
return image.toPNG().toString('base64');
}
+ // Every other op is a main-process routine of the real app — the play
+ // realm, the project's files, its TypeScript service. Say which host has
+ // it, the way an editor-only surface call does, rather than falling
+ // through to a method lookup and reporting `api.undefined is not a
+ // function` for a tool that simply lives elsewhere.
+ if (op) {
+ throw new Error(`op "${op}" needs the live editor host — connect through editor-mcp.mjs --editor (or --attach)`);
+ }
if (root === 'editor') {
throw new Error(`${method} needs the live editor host — connect through editor-mcp.mjs --editor (or --attach)`);
}
diff --git a/desktop/shared/toolCatalog.mjs b/desktop/shared/toolCatalog.mjs
index 1b296956d..5f9af70e2 100644
--- a/desktop/shared/toolCatalog.mjs
+++ b/desktop/shared/toolCatalog.mjs
@@ -216,7 +216,12 @@ export const TOOLS = [
// `editor-mcp.mjs --editor`. —
{ name: 'list_project_templates',
description: "New-project templates the editor ships. Each entry: { name, dir, kind: 'starter' | 'example', description?, tag? } — the blank starter has kind 'starter'. Use an entry's dir with create_project.",
- schema: obj({}), js: () => `window.estella.templates.list()` },
+ // Without the thumbnails. Each is a data-URL PNG for the launcher's cards and
+ // they came to 1.4 MB of base64 in one reply — past any caller's truncation
+ // limit, and worth nothing to a caller that cannot look at a picture. The
+ // fields documented above are the whole answer.
+ schema: obj({}),
+ js: () => `window.estella.templates.list().then((all) => all.map(({ thumbnail, ...rest }) => rest))` },
{ name: 'create_project', effect: 'irreversible',
description: 'Create a new project from a template directory (see list_project_templates) at <location>/<name>; returns the new project root. Follow with open_project.',
schema: obj({ templateDir: { type: 'string' }, location: { type: 'string' }, name: { type: 'string' } },
@@ -416,9 +421,26 @@ export const TOOLS = [
js: (i) => `window.estella.fs.read(${JSON.stringify(i.path)}, ${i.offset ?? 'undefined'}, ${i.limit ?? 'undefined'})` },
{ name: 'write_project_file', effect: 'irreversible',
description: 'Write a text file by project-relative path, CREATING or OVERWRITING it. This is how game scripts (src/*.ts) are authored — create_asset only makes .meta-carrying asset types and refuses to overwrite (it uniquifies to "name 2"). '
- + 'Writing project sources does not itself rebuild them; the editor picks the change up through its file watcher.',
+ + 'Writing project sources does not itself rebuild them; the editor picks the change up through its file watcher. '
+ + 'Writing a .ts file returns the TypeScript errors in it — `{ ok, path, errors, diagnostics }` — so a script that does not compile says so HERE, not three steps later when the game plays black.',
schema: obj({ path: { type: 'string' }, content: { type: 'string' } }, ['path', 'content']),
- js: (i) => `window.estella.fs.write(${JSON.stringify(i.path)}, ${JSON.stringify(i.content)})` },
+ op: 'write_project_file' },
+ { name: 'check_scripts',
+ description: "TypeScript errors in the project's scripts — the whole of src/ by default, or one file with `path`. "
+ + 'Each entry is { file, line, column, code, category, message }. This is the same compiler the IDE runs, so an empty list means the code really does build.',
+ schema: obj({ path: { type: 'string' } }), op: 'check_scripts' },
+ { name: 'lookup_symbol',
+ description: "What an API actually IS, asked of the TypeScript compiler: `name` is a symbol (`Input`, `screenToWorld`, `MouseButton`) and the reply carries its rendered signature, its doc comment and where it is declared. "
+ + 'Use this INSTEAD of paging the SDK .d.ts — that file is tens of thousands of lines and reading it a hundred at a time costs a context window to learn one method name.',
+ schema: obj({ name: { type: 'string' }, limit: { type: 'number' } }, ['name']), op: 'lookup_symbol' },
+ { name: 'search_project_files',
+ description: 'Lines matching `query` across the project (case-insensitive substring, or a regular expression with `regex: true`); `glob` keeps only paths containing that text (".ts", "src/"). '
+ + 'Each hit is { file, line, text }. The door between list_project_files and reading a file whole.',
+ schema: obj({
+ query: { type: 'string' }, regex: { type: 'boolean' },
+ glob: { type: 'string' }, maxResults: { type: 'number' },
+ }, ['query']),
+ op: 'search_project_files' },
{ name: 'list_project_files',
description: 'Project-relative paths of every file under a project-relative directory (recursive). Use for source trees (src/) where list_assets — which only knows registered assets — sees nothing.',
schema: obj({ dir: { type: 'string' } }, ['dir']),
@@ -565,7 +587,16 @@ function typeMatches(spec, val) {
function validate(schema, raw) {
const input = raw ?? {};
for (const req of schema.required ?? []) {
- if (input[req] === undefined) throw new Error(`missing required argument: ${req}`);
+ if (input[req] === undefined) {
+ // Name what DID arrive. A caller that wrote `file` for `path` reads "missing
+ // required argument: path", looks at a call that plainly has a path in it,
+ // and spends a round trip resending the same mistake.
+ const got = Object.keys(input);
+ throw new Error(
+ `missing required argument: ${req}`
+ + (got.length ? ` — received ${got.map((k) => `\`${k}\``).join(', ')}` : ' — received no arguments'),
+ );
+ }
}
for (const [key, spec] of Object.entries(schema.properties ?? {})) {
if (input[key] !== undefined && spec.type && !typeMatches(spec.type, input[key])) {
diff --git a/desktop/tests/editor-mcp-tools.test.ts b/desktop/tests/editor-mcp-tools.test.ts
index fff88052f..a069061d4 100644
--- a/desktop/tests/editor-mcp-tools.test.ts
+++ b/desktop/tests/editor-mcp-tools.test.ts
@@ -171,15 +171,33 @@ describe('editor MCP tool registry', () => {
expect(driver).toHaveBeenCalledWith('setImportSettings', ['assets/ui/frame.png', patch], 'editor');
});
- it('write_project_file targets the project fs door with an escaped payload', async () => {
- const driver = vi.fn() as unknown as { js: ReturnType<typeof vi.fn> } & ((...a: unknown[]) => unknown);
- driver.js = vi.fn(async () => undefined);
+ it('write_project_file writes through main, which is what can answer with diagnostics', async () => {
+ // A main-process op rather than a renderer snippet: the write and the
+ // TypeScript verdict on it are one reply, and only main holds the language
+ // service. The payload crosses whole — a dropped `content` would write an
+ // empty file and report ok.
+ const driver = vi.fn() as unknown as { op: ReturnType<typeof vi.fn> } & ((...a: unknown[]) => unknown);
+ driver.op = vi.fn(async () => ({ ok: true, path: 'src/main.ts', errors: 0, diagnostics: [] }));
const write = TOOLS.find((t: { name: string }) => t.name === 'write_project_file');
await runTool(write, driver, { path: 'src/main.ts', content: 'const s = "hi";\n' });
- const code = driver.js.mock.calls[0][0];
- expect(code).toContain('window.estella.fs.write');
- // The content is JSON-encoded into the snippet — quotes/newlines must not break it.
- expect(code).toContain(JSON.stringify('const s = "hi";\n'));
+ expect(driver.op).toHaveBeenCalledWith('write_project_file', {
+ path: 'src/main.ts', content: 'const s = "hi";\n',
+ });
+ });
+
+ it('the compiler tools reach main, where the language service lives', async () => {
+ const driver = vi.fn() as unknown as { op: ReturnType<typeof vi.fn> } & ((...a: unknown[]) => unknown);
+ driver.op = vi.fn(async () => []);
+ for (const [name, args] of [
+ ['check_scripts', { path: 'src/main.ts' }],
+ ['lookup_symbol', { name: 'Input' }],
+ ['search_project_files', { query: 'Gomoku' }],
+ ] as Array<[string, Record<string, unknown>]>) {
+ const tool = TOOLS.find((t: { name: string }) => t.name === name);
+ expect([name, !!tool]).toEqual([name, true]);
+ await runTool(tool, driver, args);
+ expect(driver.op).toHaveBeenCalledWith(name, args);
+ }
});
it('every resource maps to a surface method with a JSON mime', () => {
diff --git a/desktop/tests/script-service.test.ts b/desktop/tests/script-service.test.ts
new file mode 100644
index 000000000..858424df1
--- /dev/null
+++ b/desktop/tests/script-service.test.ts
@@ -0,0 +1,171 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The project's TypeScript service: diagnostics, symbol lookup, search.
+ *
+ * Driven against a real temp project with a real tsconfig, because every
+ * interesting failure of a language service is a resolution failure — a fake host
+ * would answer questions about a compilation that does not exist.
+ */
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync, cpSync, existsSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { adoptProjectScripts, scriptDiagnostics, lookupScriptSymbol, isScriptPath } from '../electron/scriptService';
+import { searchInRoot } from '../electron/projectFs';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const SDK_DIST = path.join(HERE, '..', '..', 'sdk', 'dist');
+const SDK_TYPES = path.join(SDK_DIST, 'index.d.ts');
+let root: string;
+
+/** Stage the SDK .d.ts tree where ensureSdkTypes puts it for a real project. */
+function stageSdkTypes(into: string): void {
+ const dest = path.join(into, '.esengine', 'sdk');
+ mkdirSync(dest, { recursive: true });
+ cpSync(SDK_DIST, dest, { recursive: true, filter: (src) => !src.endsWith('.js') && !src.endsWith('.map') });
+}
+
+beforeAll(() => {
+ root = mkdtempSync(path.join(tmpdir(), 'estella-scripts-'));
+ mkdirSync(path.join(root, 'src'), { recursive: true });
+ // The SDK types as a real project carries them: the WHOLE staged tree, because
+ // the declarations live across it (defineComponent is in shared/app.d.ts, not
+ // in the index that re-exports it) and a hand-picked subset silently answers
+ // "no such symbol" for everything it left out.
+ stageSdkTypes(root);
+ writeFileSync(path.join(root, 'tsconfig.json'), JSON.stringify({
+ compilerOptions: {
+ target: 'ES2020', module: 'ESNext', moduleResolution: 'bundler',
+ strict: true, skipLibCheck: true,
+ paths: { esengine: ['./.esengine/sdk/index.d.ts'] },
+ },
+ include: ['src/**/*'],
+ }));
+ adoptProjectScripts(root);
+});
+
+afterAll(() => rmSync(root, { recursive: true, force: true }));
+
+describe('the project script service', () => {
+ it('reports nothing for a file that compiles', () => {
+ writeFileSync(path.join(root, 'src', 'clean.ts'), `
+ export const add = (a: number, b: number): number => a + b;
+ `);
+ expect(scriptDiagnostics('src/clean.ts')).toEqual([]);
+ });
+
+ it('names the line and the reason for one that does not', () => {
+ writeFileSync(path.join(root, 'src', 'broken.ts'), `
+ export const n: number = 'not a number';
+ `);
+ const found = scriptDiagnostics('src/broken.ts');
+ expect(found.length).toBeGreaterThan(0);
+ expect(found[0]).toMatchObject({ file: path.join('src', 'broken.ts'), line: 2, category: 'error' });
+ expect(found[0].message).toContain('not assignable');
+ });
+
+ it('sees a file written after it started', () => {
+ // The service is built once and the agent writes scripts all turn: a service
+ // whose file list froze at construction answers "no errors" for every file
+ // created since, which is the most confident way to be wrong.
+ writeFileSync(path.join(root, 'src', 'later.ts'), `export const x: string = 1;`);
+ expect(scriptDiagnostics('src/later.ts').map((d) => d.category)).toContain('error');
+ });
+
+ it('sees a REWRITE, not the version it first read', () => {
+ const file = path.join(root, 'src', 'edited.ts');
+ writeFileSync(file, `export const y: string = 1;`);
+ expect(scriptDiagnostics('src/edited.ts').length).toBeGreaterThan(0);
+ writeFileSync(file, `export const y: string = 'fixed';`);
+ expect(scriptDiagnostics('src/edited.ts')).toEqual([]);
+ });
+
+ it('catches the mistake the agent brief used to teach', () => {
+ // `MouseButton.Left` — the whole reason this service exists. The failure was
+ // silent at runtime (undefined reads false forever); the compiler has always
+ // known, and now something asks it.
+ if (!existsSync(SDK_TYPES)) return;
+ writeFileSync(path.join(root, 'src', 'mouse.ts'), `
+ import { MouseButton } from 'esengine';
+ export const pressed = (input: { isMouseButtonPressed(b: number): boolean }) =>
+ input.isMouseButtonPressed(MouseButton.Left);
+ `);
+ const found = scriptDiagnostics('src/mouse.ts');
+ expect(found.map((d) => d.message).join(' ')).toContain('Left');
+ });
+
+ it('looks a symbol up instead of paging the .d.ts', () => {
+ if (!existsSync(SDK_TYPES)) return;
+ writeFileSync(path.join(root, 'src', 'uses.ts'), `
+ import { Input } from 'esengine';
+ export type UseInput = typeof Input;
+ `);
+ const hits = lookupScriptSymbol('isMouseButtonPressed');
+ expect(hits.length).toBeGreaterThan(0);
+ expect(hits[0].name).toBe('isMouseButtonPressed');
+ expect(hits[0].signature).toContain('button');
+ });
+
+ it('answers about the SDK before any project file imports it', () => {
+ // The state every project starts in: src/main.ts imports './components' and
+ // nothing else, so `esengine` is in no compilation — and that is exactly when
+ // someone asks what `Input` is. An empty answer here reads as "no such API".
+ if (!existsSync(SDK_TYPES)) return;
+ const bare = mkdtempSync(path.join(tmpdir(), 'estella-bare-'));
+ mkdirSync(path.join(bare, 'src'), { recursive: true });
+ stageSdkTypes(bare);
+ writeFileSync(path.join(bare, 'src', 'main.ts'), "import './components';\n");
+ writeFileSync(path.join(bare, 'src', 'components.ts'), 'export {};\n');
+ adoptProjectScripts(bare);
+ const hits = lookupScriptSymbol('isMouseButtonPressed');
+ adoptProjectScripts(root); // hand the shared service back to the other cases
+ rmSync(bare, { recursive: true, force: true });
+ expect(hits.length).toBeGreaterThan(0);
+ expect(hits[0].name).toBe('isMouseButtonPressed');
+ expect(hits[0].signature).toContain('button');
+ });
+
+ it('gives a declared function its parameters, not just its name', () => {
+ // quickInfo at a navigate-to hit degrades to "function defineComponent" for
+ // a declared function — the asker learns nothing and comes back for another
+ // round trip, which is the cost this tool exists to remove.
+ if (!existsSync(SDK_TYPES)) return;
+ for (const name of ['defineComponent', 'defineSystem']) {
+ const hit = lookupScriptSymbol(name, 4).find((h) => h.name === name);
+ expect([name, !!hit]).toEqual([name, true]);
+ expect([name, hit!.signature.includes('(')]).toEqual([name, true]);
+ expect([name, hit!.signature]).not.toEqual([name, `function ${name}`]);
+ }
+ });
+
+ it('knows which paths it has an opinion about', () => {
+ expect([isScriptPath('src/a.ts'), isScriptPath('assets/a.png'), isScriptPath('a.json')])
+ .toEqual([true, false, false]);
+ });
+});
+
+describe('project search', () => {
+ it('finds a line and says where it is', async () => {
+ writeFileSync(path.join(root, 'src', 'needle.ts'), 'const a = 1;\nconst findMeHere = 2;\n');
+ const hits = await searchInRoot(root, { query: 'findMeHere', glob: '.ts' });
+ expect(hits.some((h) => h.file.endsWith('needle.ts') && h.line === 2)).toBe(true);
+ });
+
+ it('takes a regular expression when asked', async () => {
+ const hits = await searchInRoot(root, { query: 'const \\w+Here', regex: true, glob: '.ts' });
+ expect(hits.some((h) => h.text.includes('findMeHere'))).toBe(true);
+ });
+
+ it('refuses an empty query rather than returning the project', async () => {
+ await expect(searchInRoot(root, { query: '' })).rejects.toThrow(/needs a query/);
+ });
+
+ it('clips a very long line instead of returning it whole', async () => {
+ writeFileSync(path.join(root, 'src', 'long.ts'), `// ${'x'.repeat(5000)} marker\n`);
+ const hits = await searchInRoot(root, { query: 'xxxxx', glob: 'long.ts' });
+ expect(hits.length).toBeGreaterThan(0);
+ expect(hits[0].text.length).toBeLessThanOrEqual(400);
+ });
+});
diff --git a/desktop/vite.config.ts b/desktop/vite.config.ts
index 0b99fe36a..d6643a002 100644
--- a/desktop/vite.config.ts
+++ b/desktop/vite.config.ts
@@ -87,6 +87,11 @@ export default defineConfig({
// exportGame run it). Keep it external → required from node_modules at
// runtime where its binary resolution works. (Vite 8 = Rolldown, so the
// option is `rolldownOptions`, not `rollupOptions`.)
+ // typescript is external for the same shape of reason and one more: it is
+ // CommonJS, and bundling it into the ESM main broke the app on boot
+ // (`__filename is not defined in ES module scope`). It also ships as a
+ // RUNTIME dependency — the editor's language service (scriptService.ts)
+ // is a shipped feature, not a dev tool.
// esbuild + the vendored Basis KTX2 encoder + ffmpeg-static all resolve
// sibling binaries at runtime (native exe / wasm via import.meta.url /
// module __dirname), so bundling them breaks that — keep them external,
@@ -97,7 +102,7 @@ export default defineConfig({
vite: {
build: {
rolldownOptions: {
- external: ['esbuild', 'ffmpeg-static', 'electron-updater', /[\\/]build-tools[\\/]basis[\\/]/],
+ external: ['esbuild', 'typescript', 'ffmpeg-static', 'electron-updater', /[\\/]build-tools[\\/]basis[\\/]/],
},
},
},