import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs" import { basename, dirname, join, relative, resolve } from "node:path" import { CliError, bool, c, defineCommand, log, note, num, warnErr } from "../cli" import { compileSceneEditor } from "../compile/sceneCompile" import { localShaderArtifact } from "../compile/shaders" import { loadPeer } from "../hosts/peerInstall" import { openBrowser } from "../platform/browserAuth" import { findProjectRoot, readManifest, type Manifest } from "../project/manifest" /* * `lecodes scene [path]` — the 3D scene editor (lecodes-tools/packages/lecodes-3d-editor) hosted on a * local project, the way `lecodes design` hosts the design board. Starts the editor's node:http server, * injects the CLI's compile closure (chisel + the vendored SDK + a vendored harness), and opens the * browser. `.scene.ts` files are edited visually (tree + inspector) and written back to disk; * external (IDE) edits hot-reload over SSE. * * Root resolution mirrors `design`: inside a cloned project the whole project is the compile input; * anywhere else it runs standalone against the current directory (or a folder/scene passed as `path`). */ const DEFAULT_PORT = 4488 type SceneContext = { root: string /** Null in standalone mode: the scene lives outside any cloned lecodes project. */ manifest: Manifest | null name: string /** The `.scene.ts` the positional arg named, as a project path ("./src/map.scene.ts") — the * editor opens on it (`?scene=`) instead of the project's first scene file. */ scene: string | null } /** The nearest ancestor (inclusive) holding an `app.json` — a local project's root — or null. */ const findAppRoot = (start: string): string | null => { let dir = start while (true) { if (existsSync(join(dir, "app.json"))) return dir const parent = dirname(dir) if (parent === dir) return null dir = parent } } /** The project a DIRECTORY belongs to: a cloned project's root, else the nearest ancestor with an * app.json, else the directory itself. `lecodes thumbs` resolves its root this way — its * positional args are targets, not the root, so it can't go through getContext. */ export const projectRootOf = (dir: string): string => { try { return findProjectRoot(dir) } catch { return findAppRoot(dir) ?? dir } } const getContext = (pathArg: string | undefined): SceneContext => { let root: string let manifest: Manifest | null try { root = findProjectRoot(process.cwd()) manifest = readManifest(root) } catch { // Standalone (a local project without a platform manifest): the current directory, or a // folder / .scene.ts passed as the positional arg. The whole-project compile needs the PROJECT // root — a scene file's imports (`../weaponRig`) resolve against it — so walk up to the nearest // `app.json`; only without one does a scene path fall back to its containing dir. root = process.cwd() manifest = null if (pathArg) { const abs = resolve(process.cwd(), pathArg) if (existsSync(abs) && statSync(abs).isDirectory()) root = abs else if (abs.endsWith(".scene.ts") && existsSync(abs)) root = findAppRoot(dirname(abs)) ?? dirname(abs) else throw new CliError(`No such folder or .scene.ts: ${pathArg}`) } else { root = findAppRoot(root) ?? root } } // a `.scene.ts` arg (either mode) picks the file the editor opens on let scene: string | null = null if (pathArg?.endsWith(".scene.ts")) { const abs = resolve(process.cwd(), pathArg) const rel = relative(root, abs).replace(/\\/g, "/") if (existsSync(abs) && !rel.startsWith("..")) scene = "./" + rel } return { root, manifest, name: manifest?.name ?? basename(root), scene } } /** Register the scene server as a project-scoped MCP server so Claude Code auto-discovers its * scene_state / check_scene tools. Merges into an existing .mcp.json (never clobbers a broken one). */ const writeMcpConfig = (root: string, port: number): void => { const path = join(root, ".mcp.json") const entry = { type: "http", url: `http://localhost:${port}/mcp` } let config: { mcpServers?: Record } = {} if (existsSync(path)) { try { config = JSON.parse(readFileSync(path, "utf8")) } catch { warnErr(".mcp.json exists but isn't valid JSON — left it untouched. Add the lecodes-scene server by hand."); return } } config.mcpServers ??= {} const existing = config.mcpServers["lecodes-scene"] as { url?: string } | undefined if (existing?.url === entry.url) { note("kept .mcp.json (lecodes-scene MCP server)"); return } config.mcpServers["lecodes-scene"] = entry writeFileSync(path, JSON.stringify(config, null, 2) + "\n") note(`${existing ? "updated" : "created"} .mcp.json (lecodes-scene MCP → ${entry.url})`) } /** How many `.scene.ts` files sit under root (node_modules / dot-dirs skipped). */ const countScenes = (dir: string): number => { let n = 0 for (const name of readdirSync(dir)) { if (name === "node_modules" || name.startsWith(".")) continue const full = join(dir, name) if (statSync(full).isDirectory()) n += countScenes(full) else if (name.endsWith(".scene.ts")) n++ } return n } export default defineCommand({ name: "scene", summary: "The scene editor: edit a .scene.ts visually (tree, inspector, gizmo)", usage: "[path]", description: "Needs the optional lecodes-3d-editor package (installed on first use). Works inside a cloned project or standalone in any folder; `path` is a folder or a .scene.ts to host. Registers an MCP server in .mcp.json so Claude Code can call scene_state / check_scene.", flags: { port: num("editor-server port", { default: DEFAULT_PORT }), "no-open": bool("don't open the browser"), "no-mcp": bool("don't register the MCP server in .mcp.json"), }, examples: ["lecodes scene", "lecodes scene src/forest.scene.ts --no-open"], run: async ({ args, flags }) => { const ctx = getContext(args[0]) const sceneServer = await loadPeer("lecodes-3d-editor", "server", { for: "lecodes scene" }) // The harness (the editor's half inside the scene's world) ships with the editor: the bundle is // compiled with the one of the package the UI is served from. if (typeof sceneServer.sceneHarness !== "function") { throw new CliError("The installed lecodes-3d-editor is older than this CLI: it carries no scene harness (0.9.0 has one). Run `lecodes update`.") } if (countScenes(ctx.root) === 0) warnErr(`No .scene.ts file under ${ctx.root} yet — add one and the editor will pick it up.`) const server = await sceneServer.startSceneServer({ root: ctx.root, port: flags.port, log: note, compile: (scenePath: string) => compileSceneEditor({ root: ctx.root, manifest: ctx.manifest, name: ctx.name, scenePath, harness: sceneServer.sceneHarness() }), // live material patches load a shader's compiled artifact (matc'd for the Rendered mode, // the lite JSON otherwise) from the local shader cache shaderArtifact: (shaderText, platform) => localShaderArtifact(ctx.root, shaderText, platform), }) if (!flags["no-mcp"]) writeMcpConfig(ctx.root, flags.port) log(`${c.bold("LeCodes Scene Editor")} — ${ctx.name}`) const editorUrl = ctx.scene ? `${server.url}/?scene=${encodeURIComponent(ctx.scene.replace(/^\.\//, ""))}` : server.url log(`Editor: ${c.bold(editorUrl)}`) log(`MCP: ${c.bold(server.url + "/mcp")}`) log(`Watching: ${ctx.root} (scenes hot-reload on save; Ctrl+C to stop)`) if (!flags["no-open"]) openBrowser(editorUrl) }, })