/** Sending each tool call to the job that answers it. */ import type { ToolResponse } from '../answer-json.js'; import { declaredClassLines } from '../class-cache.js'; import { dictionary } from '../dictionary.js'; import { inOneSlot } from '../engine-slots.js'; import { DEPENDENCY_OPERATIONS, EDITOR_ANSWERS, EDITOR_CALLS, ENGINE_PASSES, HEADLESS_OPERATIONS, } from '../headless-operations.js'; import { keptInside } from '../paths.js'; import type { GodotServer } from '../server.js'; import { type OperationParams, readArray, readBoolean, readNonEmptyString, readNonNegativeNumber, readNumber, readPositiveNumber, readString, readStringArray, } from '../tool-args.js'; import { handleViaBridge, noEditorYet } from './bridge-calls.js'; import { handleEditorCapture } from './capture.js'; import { dispatchDebugTool } from './debug-tools.js'; import { waitForBridge } from './editor-connection.js'; import { greetingWaitMs, handleCloseEditor, handleLaunchEditor, handleRestartEditor, } from './editor-launch.js'; import { handleEditorStatus, handleRebindEditorServers } from './editor-status.js'; import { handleAddExportPreset, handleExportProject, handleRemoveExportPreset, handleSetExportPreset, } from './export.js'; import { handleRunProject } from './game-start.js'; import { headlessOutcomeAnswer, REFRESH_CLASS_CACHE, runHeadless } from './headless-ops.js'; import { askScriptInfo } from './language-servers.js'; import { alsoSayWhatTheEditorCannotSee, handleMoveFile } from './move-file.js'; import { handleRunProfile } from './profile.js'; import { checkedProject, containProjectFiles } from './project-checks.js'; import { handleProjectInfo, handleSearchProject } from './project-info.js'; import { handleStopProject } from './project-stop.js'; import { handleRefreshUids, handleReimport, handleSetImportOptions } from './reimport.js'; import { rebuildClassCache } from './reload.js'; import { handleRescanFilesystem } from './rescan.js'; import { handleGetDebugOutput } from './run-output.js'; import { handleWaitForRun } from './run-wait.js'; import { handleFindRuntimeNodes, handleLateAnswer, handleRuntimeCommand, handleRuntimeWait, patienceForFrames, runtimeTimeoutMs, whichGame, } from './runtime-calls.js'; import { readFromFile, saveFromTheEditor, viaEditorOrEngine } from './scene-writes.js'; import { handleScriptDiagnostics } from './script-diagnostics.js'; import { handleCreateScript, handleModifyScript, handleRenameSymbol } from './script-edits.js'; import { handleProjectSettingsWrite } from './settings-write.js'; import { handleRunTests } from './test-run.js'; /** [param fields] without the ones that are undefined, for parameters sent only when given. */ function withDefined(fields: Record): Record { return Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined)); } /** The language server request and the word for it that each script_info op uses. An op not listed is hover. */ const SCRIPT_INFO_CALLS = dictionary({ symbols: ['lsp_get_symbols', 'Symbols'], completion: ['lsp_get_completions', 'Completion'], }); /** * One tool call to the code that does it. `op` is empty for a tool that has none. */ export async function dispatch( server: GodotServer, tool: string, op: string, args: OperationParams, ): Promise { // Every call but the one that reports the state as it is waits out an editor still arriving, // so nothing is decided on a reading that is about to change: connected before the greeting, // then not while the command line is read. editor_status answers in the middle of it and says so. if (tool !== 'editor_status' && server.godotBridge.isArriving()) { await waitForBridge(() => !server.godotBridge.isArriving(), Date.now() + greetingWaitMs()); } return await dispatchPasses(server, tool, op, args); } /** The calls that run the engine over a project as a whole, before the headless operations are tried. */ async function dispatchPasses( server: GodotServer, tool: string, op: string, args: OperationParams, ): Promise { if (ENGINE_PASSES[tool]?.includes(op) === true) { return op === 'reimport' ? await handleReimport(server, args) : await handleRefreshUids(server, args); } const settingsWrite = tool === 'project_settings' && op !== 'get' ? HEADLESS_OPERATIONS[tool]?.[op] : undefined; if (settingsWrite !== undefined) { return await handleProjectSettingsWrite(server, op, settingsWrite, args); } if (tool === 'project_import' && op === 'set_options') { return await handleSetImportOptions(server, args); } if (tool === 'project_export' && op === 'add_preset') { return await handleAddExportPreset(server, args); } if (tool === 'project_export' && op === 'set_preset') { return await handleSetExportPreset(server, args); } if (tool === 'project_export' && op === 'remove_preset') { return await handleRemoveExportPreset(server, args); } return await dispatchHeadless(server, tool, op, args); } /** A call to an operation the engine runs headless, or on to the tools that have none. */ async function dispatchHeadless( server: GodotServer, tool: string, op: string, args: OperationParams, ): Promise { const headless = HEADLESS_OPERATIONS[tool]?.[op]; if (headless !== undefined) { // Asked of the editor instead, when the caller said so. The two are not the same reading and // that is the point of saying: disk is what the file holds and what a check running without // anybody's window open can reproduce, the editor is what it has been told, unsaved changes // and all. Refused rather than quietly answered from disk when there is no editor, because a // caller who asked for the editor's answer and silently got the file's would have no way to // know, which is the ambiguity the argument exists to remove. const { from: asked, ...answerable } = args; if (asked === 'editor') { return await readHeadlessFromEditor(server, tool, op, answerable); } return await dispatchHeadlessOperation(server, tool, headless, answerable, args); } return await dispatchTool(server, tool, op, args); } /** A headless operation asked of the editor with `from: "editor"`, refused where the editor cannot answer it. */ async function readHeadlessFromEditor( server: GodotServer, tool: string, op: string, answerable: OperationParams, ): Promise { const editorSide = EDITOR_ANSWERS[tool]?.[op]; if (editorSide === undefined) { return server.createErrorResponse(`${tool} ${op} cannot be read from the editor, only from disk.`, [ 'Leave from unset, or pass from: "disk"', ]); } if (!server.godotBridge.isConnected()) { const refused = await noEditorYet(server, answerable, [ `${tool} ${op} was asked of the editor. from: "disk" reads the file instead`, ]); if (refused !== null) { return refused; } } const { op: _dropped, ...asks } = answerable; const contained = containProjectFiles(server, asks); return contained.ok ? await handleViaBridge(server, editorSide, contained.value) : contained.response; } /** A headless operation read from disk: a script written, the class cache rebuilt, or the engine run. */ async function dispatchHeadlessOperation( server: GodotServer, tool: string, headless: string, answerable: OperationParams, args: OperationParams, ): Promise { if (headless === 'create_script') { return await handleCreateScript(server, answerable); } if (headless === 'modify_script') { return await handleModifyScript(server, answerable); } if (tool === 'editor_classes') { // A refusal names a class a script declares as the script's, and offers the nearest of them, // from the scripts on disk: the engine knows them only from the class cache, which lags them. const project = checkedProject(server, answerable); if (!project.ok) { return project.response; } const projectClasses = Object.fromEntries(declaredClassLines(project.value.path)); return await runHeadless(server, headless, { ...answerable, projectClasses }); } if (headless !== REFRESH_CLASS_CACHE) { return await runHeadless(server, headless, answerable); } const project = checkedProject(server, answerable); if (!project.ok) { return project.response; } const answered = headlessOutcomeAnswer(server, await rebuildClassCache(server, project.value.path)); // The one answer that reads most like a clean bill of health and is not: "added: []" means // the file on disk was already right, which is exactly the state an editor goes blind in. return server.godotBridge.isConnected() ? await alsoSayWhatTheEditorCannotSee(server, answered, args) : answered; } /** The two ways a tool's call reaches the editor: the bridge as it is, or the editor with the engine as the fallback. */ function editorCallers( server: GodotServer, tool: string, op: string, args: OperationParams, ): { bridge: (command: string, extra?: OperationParams) => Promise; editorOrEngine: (command: string, effect: 'reads' | 'writes') => Promise; editorCall: () => Promise; } { const { op: _op, ...arguments_ } = args; const bridge = async (command: string, extra: OperationParams = {}): Promise => { const contained = containProjectFiles(server, { ...arguments_, ...extra }); return contained.ok ? await handleViaBridge(server, command, contained.value, op === '' ? tool : `${tool} ${op}`) : contained.response; }; const editorOrEngine = async (command: string, effect: 'reads' | 'writes'): Promise => await viaEditorOrEngine(server, command, arguments_, `${tool} ${op}`, effect); const editorCall = async (): Promise => { const call = EDITOR_CALLS[tool]?.[op]; if (call === undefined) { throw new Error(`${tool} ${op} has no editor command`); } return await editorOrEngine(...call); }; return { bridge, editorOrEngine, editorCall }; } /** One tool call to the code that does it, for the project tools and for scene_create. */ async function dispatchTool( server: GodotServer, tool: string, op: string, args: OperationParams, ): Promise { const { editorOrEngine } = editorCallers(server, tool, op, args); switch (tool) { case 'project_info': return await handleProjectInfo(server, args); case 'project_search': return handleSearchProject(server, args); case 'project_dependencies': return await runHeadless( server, DEPENDENCY_OPERATIONS[args['direction'] === 'reverse' ? 'reverse' : 'forward'], args, ); case 'project_export': return await handleExportProject(server, args); case 'project_test': return await handleRunTests(server, args); case 'scene_create': if (op === 'create') { return await editorOrEngine('create_scene', 'writes'); } return args['from'] === undefined ? await editorOrEngine('save_scene', 'writes') : await saveFromTheEditor(server, args); default: return await dispatchSceneTool(server, tool, op, args); } } /** One tool call to the code that does it, for the scene tree, nodes and signals. */ async function dispatchSceneTool( server: GodotServer, tool: string, op: string, args: OperationParams, ): Promise { const { bridge, editorCall } = editorCallers(server, tool, op, args); switch (tool) { case 'scene_tree': { // includeDefaults names which properties to list, so given alone it can mean only that the // properties are wanted: read without them, it answered the bare tree and said nothing. const defaults = readBoolean(args, 'includeDefaults') ?? false; const asked = readBoolean(args, 'includeProperties'); if (defaults && asked === false) { return server.createErrorResponse( 'includeDefaults lists the defaults among the properties, and includeProperties false lists none: leave includeProperties out, or set it true.', ); } const properties = asked ?? defaults; return await readFromFile( server, args, 'scenePath', 'read_scene_tree', (file) => ({ scenePath: file, depth: readNumber(args, 'depth') ?? -1, includeProperties: properties, includeDefaults: defaults, }), async () => await bridge('list_scene_nodes', { includeProperties: properties }), ); } case 'scene_node': case 'scene_signal': return await editorCall(); default: return await dispatchAnimationAndScriptTool(server, tool, op, args); } } /** One tool call to the code that does it, for scene_animation and the script tools. */ async function dispatchAnimationAndScriptTool( server: GodotServer, tool: string, op: string, args: OperationParams, ): Promise { const { bridge, editorCall } = editorCallers(server, tool, op, args); switch (tool) { case 'scene_animation': switch (op) { case 'read': return await readFromFile( server, args, 'scenePath', 'read_animations', (file) => ({ scenePath: file, playerNodePath: readNonEmptyString(args, 'playerNodePath') ?? '.', animationName: readString(args, 'animationName') ?? '', }), async () => await bridge('read_animations'), ); case 'read_states': return await readFromFile( server, args, 'scenePath', 'read_animation_states', (file) => ({ scenePath: file, animTreePath: readString(args, 'animTreePath') ?? '', stateMachinePath: readString(args, 'stateMachinePath') ?? '', }), async () => await bridge('read_animation_states'), ); default: return await editorCall(); } case 'script_edit': return await handleRenameSymbol(server, args); case 'script_info': return await askScriptInfo(server, ...(SCRIPT_INFO_CALLS[op] ?? ['lsp_get_hover', 'Hover']), args); case 'script_diagnostics': return await inOneSlot(() => handleScriptDiagnostics(server, args)); default: return await dispatchResourceTool(server, tool, op, args); } } /** One tool call to the code that does it, for resource_edit. */ async function dispatchResourceTool( server: GodotServer, tool: string, op: string, args: OperationParams, ): Promise { const { bridge, editorCall } = editorCallers(server, tool, op, args); switch (tool) { case 'resource_edit': switch (op) { case 'move': return await handleMoveFile(server, args); case 'read': { const { file, inner } = keptInside(readString(args, 'resourcePath') ?? ''); const kept: OperationParams = inner === undefined ? {} : { resourcePath: file, subResource: inner }; return await readFromFile( server, { ...args, ...kept }, 'resourcePath', 'read_resource', (found) => ({ resourcePath: inner === undefined ? found : `${found}::${inner}`, includeDefaults: readBoolean(args, 'includeDefaults') ?? false, }), async () => await bridge('read_resource', kept), ); } default: return await editorCall(); } default: return await dispatchEditorTool(server, tool, op, args); } } /** One tool call to the code that does it, for the tools that launch, run and read the editor. */ async function dispatchEditorTool( server: GodotServer, tool: string, op: string, args: OperationParams, ): Promise { switch (tool) { case 'editor_launch': if (op === 'close') { return await handleCloseEditor(server); } if (op === 'rebind') { return await handleRebindEditorServers(server); } return op === 'restart' ? await handleRestartEditor(server, args) : await handleLaunchEditor(server, args); case 'editor_run': if (op === 'stop') { return await handleStopProject(server, args); } if (op === 'wait') { return await handleWaitForRun(server, args); } if (op === 'profile') { return await handleRunProfile(server, args); } return await handleRunProject(server, args, op); case 'editor_output': return await handleGetDebugOutput(server, args); case 'editor_status': return await handleEditorStatus(server); case 'editor_rescan': return await handleRescanFilesystem(server, args); default: return await dispatchCaptureAndInspectTool(server, tool, op, args); } } /** One tool call to the code that does it, for editor_capture and runtime_inspect. */ async function dispatchCaptureAndInspectTool( server: GodotServer, tool: string, op: string, args: OperationParams, ): Promise { switch (tool) { case 'editor_capture': return await handleEditorCapture(server, args); default: return await dispatchRuntimeInspectTool(server, tool, op, args); } } /** One tool call to the code that does it, for runtime_inspect. */ async function dispatchRuntimeInspectTool( server: GodotServer, tool: string, op: string, args: OperationParams, ): Promise { switch (tool) { case 'runtime_inspect': { const patience = readPositiveNumber(args, 'timeoutMs') ?? runtimeTimeoutMs(); switch (op) { case 'tree': { // Zero is the node alone, which is how one node's properties are read, and not an // omission: read as positive it fell back to three levels, which over a router node // answered four megabytes. The schema's range refuses anything below it. const depth = readNonNegativeNumber(args, 'depth'); return await handleRuntimeCommand( server, 'get_tree', { ...whichGame(args), root: readNonEmptyString(args, 'nodePath') ?? '/root', depth: depth ?? 3, include_properties: readBoolean(args, 'includeProperties') ?? false, properties: readArray(args, 'properties') ?? [], }, { tool: 'runtime_inspect', op, patience }, ); } case 'find': return await handleFindRuntimeNodes(server, args, patience); case 'text': return await handleRuntimeCommand( server, 'read_text', { ...whichGame(args), root: readNonEmptyString(args, 'nodePath') ?? '/root', include_hidden: readBoolean(args, 'includeHidden') ?? false, limit: readPositiveNumber(args, 'limit') ?? 500, }, { tool: 'runtime_inspect', op, patience }, ); default: return await inspectRuntimeMore(server, op, args, patience); } } default: return await dispatchRuntimeTool(server, tool, op, args); } } /** The runtime_inspect ops that read one node or the game's metrics. */ async function inspectRuntimeMore( server: GodotServer, op: string, args: OperationParams, patience: number, ): Promise { switch (op) { case 'rect': return await handleRuntimeCommand( server, 'get_rect', { ...whichGame(args), path: readNonEmptyString(args, 'nodePath') ?? '' }, { tool: 'runtime_inspect', op, patience }, ); case 'property': return await handleRuntimeCommand( server, 'get_property', { ...whichGame(args), path: readNonEmptyString(args, 'nodePath') ?? '', property: readNonEmptyString(args, 'property') ?? '', }, { tool: 'runtime_inspect', op, patience }, ); case 'accessibility': // Starting PowerShell and walking the tree until it settles takes longer than a query: the // game allows 45 s for a cold PowerShell and 15 s a window for the walks, and waiting // that out answers a slow machine's read rather than a pending one. return await handleRuntimeCommand( server, 'get_accessibility', { ...whichGame(args), // Only what was given, so the game's defaults stay the game's. ...withDefined({ node_path: readNonEmptyString(args, 'nodePath'), says: readNonEmptyString(args, 'says'), properties: readStringArray(args, 'properties'), limit: readPositiveNumber(args, 'limit'), }), }, { tool: 'runtime_inspect', op, patience: readPositiveNumber(args, 'timeoutMs') ?? Math.max(75_000, runtimeTimeoutMs()), }, ); default: return await handleRuntimeCommand( server, 'get_metrics', { ...whichGame(args), metrics: readArray(args, 'metrics') ?? [] }, { tool: 'runtime_inspect', op, patience }, ); } } /** One tool call to the code that does it, for the runtime tools that act on the running game. */ async function dispatchRuntimeTool( server: GodotServer, tool: string, op: string, args: OperationParams, ): Promise { switch (tool) { case 'runtime_invoke': { if (op === 'result') { return handleLateAnswer(server, args); } const patience = readPositiveNumber(args, 'timeoutMs') ?? runtimeTimeoutMs(); // The value and the arguments are fitted to the property's or the method's own types // on the game's side. return op === 'set' ? await handleRuntimeCommand( server, 'set_property', { ...whichGame(args), path: readNonEmptyString(args, 'nodePath') ?? '', property: readString(args, 'property') ?? '', value: args['value'], }, { tool: 'runtime_invoke', op, patience }, ) : await handleRuntimeCommand( server, 'call_method', { ...whichGame(args), path: readNonEmptyString(args, 'nodePath') ?? '', method: readString(args, 'method') ?? '', args: readArray(args, 'args') ?? [], ...(args['properties'] === undefined ? {} : { properties: args['properties'] }), }, { tool: 'runtime_invoke', op, patience }, ); } default: return await dispatchRuntimeCaptureTool(server, tool, op, args); } } /** One tool call to the code that does it, for runtime_capture and the tools after it. */ async function dispatchRuntimeCaptureTool( server: GodotServer, tool: string, op: string, args: OperationParams, ): Promise { switch (tool) { case 'runtime_capture': return await handleRuntimeCommand( server, op === 'screenshot' ? 'capture_screenshot' : 'capture_viewport', args, { tool: 'runtime_capture', op }, ); default: return await dispatchRuntimeInputTool(server, tool, op, args); } } /** One tool call to the code that does it, for runtime_input and runtime_wait. */ async function dispatchRuntimeInputTool( server: GodotServer, tool: string, op: string, args: OperationParams, ): Promise { switch (tool) { case 'runtime_input': if (op === 'click') { return await clickInGame(server, op, args); } return await chooseOrInjectInput(server, op, args); case 'runtime_wait': return await handleRuntimeWait(server, op, args); default: return await dispatchDebugTool(server, tool, op, args); } } /** A click in the running game, on a node or on the control that says the words given. */ async function clickInGame(server: GodotServer, op: string, args: OperationParams): Promise { if (readNonEmptyString(args, 'nodePath') === undefined && readNonEmptyString(args, 'says') === undefined) { return server.createErrorResponse( 'runtime_input click needs nodePath, or says with the words on the control to click.', ); } return await handleRuntimeCommand( server, 'click', { ...whichGame(args), path: readNonEmptyString(args, 'nodePath') ?? '', // As given, a number included: the addon names a button either way and refuses what is // neither, and read as a string alone a right click given as 2 went as the left button. button: args['button'] ?? 'left', double: readBoolean(args, 'doubleClick') ?? false, ...(readNonEmptyString(args, 'says') === undefined ? {} : { says: readNonEmptyString(args, 'says') }), ...(args['index'] === undefined ? {} : { index: args['index'] }), ...(args['x'] === undefined ? {} : { x: args['x'] }), ...(args['y'] === undefined ? {} : { y: args['y'] }), }, { tool: 'runtime_input', op }, ); } /** A runtime_input op that is not a click: choosing an item, or injecting a press, a stroke or a key. */ async function chooseOrInjectInput( server: GodotServer, op: string, args: OperationParams, ): Promise { if (op === 'choose') { // `index` is passed on only when it was given, because the addon reads whether it is // there as which of the two ways the caller named the item. return await handleRuntimeCommand( server, 'choose', { ...whichGame(args), path: readNonEmptyString(args, 'nodePath') ?? '', text: readString(args, 'text') ?? '', ...(args['index'] === undefined ? {} : { index: args['index'] }), }, { tool: 'runtime_input', op }, ); } { // A held press answers once it has let go, and a drag once its stroke is over, so each is // given as long as a frames wait of the same length. const holding = op === 'mouse_drag' || op === 'touch_drag' ? (readPositiveNumber(args, 'frames') ?? 1) + 2 : readPositiveNumber(args, 'holdFrames'); return await handleRuntimeCommand(server, `inject_${op}`, args, { tool: 'runtime_input', op, ...(holding === undefined ? {} : { patience: patienceForFrames(holding, runtimeTimeoutMs()) }), }); } }