/** Editor and document automation over the shared session command wire. * Modeling executes in the editor tab; this client owns no model state. */ import type { ActiveDocumentCapture, AssetKind, AssetPreviewCapture, AssetPreviewOptions, AssetPreviewShotSetDefinition, AssetPreviewSource, CaptureDimensions, DocumentLookOutcome, StageFrameCostReading, EditorChromeCapture, EditorChromeCaptureOptions, EditorState, EditorView, EditorWorkspaceName, InspectedFieldWrite, InspectedHierarchy, InspectedInspection, LabeledShotSetCapture, PresentedEditorView, ShadingMode, StructureOp, StructureOpOptions, StructureOpResult, ViewPreset, ViewportCapture, } from '@volter/sdk'; import type { EditorClient, HistoryStep, OpenedDocument } from './client.js'; import { LiveAssetLibrary } from './asset-library.js'; import { LiveEditorDocument } from './editor-document.js'; /** A panel `showPanel` can focus: the console, the build surface, or any key * the editor's own static-panel registry holds (`hierarchy`, `asset-library`, * `inspector`, `history`, …) — which is why this is open: the registry, not * this union, is the vocabulary. */ export type PanelName = | 'console' // Keeps the literals above in autocomplete while admitting every key the // editor's registry holds — the registry answers, this union only hints. | (string & {}); const EXTENSION_KIND: Record = { '.glb': 'model', '.gltf': 'model', '.png': 'image', '.jpg': 'image', '.jpeg': 'image', '.webp': 'image', '.gif': 'image', '.svg': 'image', '.hdr': 'image', '.exr': 'image', '.mp4': 'video', '.webm': 'video', '.mp3': 'audio', '.ogg': 'audio', '.wav': 'audio', '.flac': 'audio', '.glsl': 'source', '.vert': 'source', '.frag': 'source', // Source kinds select SourceAssetViewer, which routes project scripts by content to // LiveModuleDocument. Keep these extensions aligned with its isProjectScriptPath predicate. '.ts': 'source', '.tsx': 'source', '.mts': 'source', '.cts': 'source', '.js': 'source', '.jsx': 'source', '.mjs': 'source', '.cjs': 'source', }; /** * Lightweight extension-based `AssetKind` guess for `openAsset`'s optional * `kind` argument. Callers with an unusual extension can always pass `kind` * explicitly. */ export function inferAssetKind(path: string): AssetKind { // `'prefab'` is an `@volter/sdk` AssetKind that view links name. if (path.endsWith('.prefab.json')) return 'prefab'; const dot = path.lastIndexOf('.'); const ext = dot >= 0 ? path.slice(dot).toLowerCase() : ''; return EXTENSION_KIND[ext] ?? 'json'; } export class LiveEditor { /** `#`-private, not `private`: ` eval --list` enumerates this object's * real runtime members, and TypeScript's erased `private` would leave the * raw `EditorClient` advertised beside them. */ readonly #client: EditorClient; /** Read and drive DOM within a named scope: the active document by default, or editor chrome * such as header, shelf, rail, outliner, utility and area. Targets outside the scope are refused. * See `@volter/sdk`'s editor-document-probe for scope and gesture contracts. */ readonly document: LiveEditorDocument; /** The asset library: search a source, list an asset's files, download one into the project with its license * recorded (`asset-library.ts`). */ readonly assetLibrary: LiveAssetLibrary; constructor(client: EditorClient) { this.#client = client; this.document = new LiveEditorDocument(client); this.assetLibrary = new LiveAssetLibrary(client); } /** A verb a composed package contributes (`-`), waited on for its own row's budget. */ async contributedVerb>( type: string, fields: Record = {}, ): Promise { return this.#client.contributedVerb(type, fields); } /** * The active authoring adapter's persistence destination — where a save would * land (`status().savePath`). A read only: a stage root has no scene document * to open, and its root is activated instead. */ async scene(): Promise { const state = await this.#client.getState(); return state.savePath; } /** * Make the connected human editor show the same subject/view as the agent. * The returned URL is a compact, shareable projection — not a serialized * workspace or document payload. */ async present(view: EditorView): Promise { return this.#client.present(view); } /** The human editor's actual active document, selection, camera and utility. */ async currentView(): Promise { return this.#client.currentView(); } /** Capture the active document's render without viewport navigation gizmos or readouts. * A number requests a square; `{width, height}` requests a shaped frame, bounded by * `CaptureDimensions`. Supply a view to present and capture it in one request. * Use `captureEditorChrome({ region: 'document' })` to include viewport chrome. */ async captureActiveDocument( size?: CaptureDimensions, view?: EditorView, ): Promise { return this.#client.captureActiveDocument(size, view); } /** * Photograph the editor PAGE — every panel, tab strip and viewport as the * person sees it. the editor's `screenshot editor` command is this verb from the shell. The * one door for judging chrome sighted: a skin, a workspace arrangement or a * contributed panel is looked at through this, never guessed at from DOM * probes. The page at its own layout, `scale` output pixels per CSS pixel * (default `devicePixelRatio`) — a 1 px border or a glyph stroke is only * judgeable at the scale the reference it is compared against was captured * at, and the result reports its own `size` and `scale`. */ async captureEditorChrome(options?: EditorChromeCaptureOptions): Promise { return this.#client.captureEditorChrome(options); } /** `'all'` -> `EditorClient.selectAll()` (mirrors `volter select --all`); otherwise `EditorClient.select(id)` (mirrors `volter select `). */ async select(id: string | 'all'): Promise { if (id === 'all') { await this.#client.selectAll(); return; } await this.#client.select(id); } /** Mirrors `volter deselect`. */ async deselect(): Promise { await this.#client.select(null); } /** No `id` -> focus the current selection (mirrors bare `volter focus`); `id` given -> focus that entity. */ async focus(id?: string): Promise { if (id !== undefined) { await this.#client.focusEntity(id); return; } await this.#client.focusSelection(); } /** * Frame the edit viewport camera on one entity. Same framing as * `focus(id)`, but an entity id the scene does not know THROWS, naming the * id — where `focus` quietly does nothing. Reach for this whenever the next * step reads the viewport (`screenshot()`, an * `assetPreview(..., { stage: 'scene' })`): a framing that silently missed * would otherwise be indistinguishable from one that worked. */ async frame(entityId: string): Promise; /** * Bare `frame()` frames the OPEN asset document's subject instead — its * selection if it has one, else the whole model: the toolbar's own Frame * button, reachable from a script. `fit` scales the fitted distance (1 is * that button's tight fit, 1.5 stands back a little for a shot). */ async frame(options?: { readonly fit?: number }): Promise; async frame(target?: string | { readonly fit?: number }): Promise { if (typeof target === 'string') { await this.#client.frameEntity(target); return; } await this.#client.frameDocument(target?.fit); } /** * WATCH THE AGENT LOOK AROUND THE MODEL. * * Swings the open asset document's camera — the camera the human's tab is * showing — around the framed subject by `azimuth`/`elevation` RADIANS, * animated over `duration` seconds (default 0.6), and resolves when the move * ends. This is deliberately not a jump cut: the point of the verb is that a * person watching sees the agent walk around the thing it is working on. * * `await editor.orbit({ azimuth: Math.PI / 2 })` — a quarter turn to the right. * * There is ONE camera, and the human owns it: a drag during the move cancels * it exactly where it is, and the resolved outcome says `cancelledBy: * 'human'` rather than throwing. A second look verb supersedes the first. * The move is drawn by the document's own frame loop, so a document that * isn't being drawn (background tab, inactive panel) doesn't orbit. */ async orbit(options: { /** RADIANS, relative to where the camera is now. `Math.PI / 2` is a * quarter turn; degrees are not accepted and `90` is fourteen turns. */ readonly azimuth?: number; /** RADIANS, relative to where the camera is now. */ readonly elevation?: number; /** SECONDS the move takes (default 0.6). */ readonly duration?: number; }): Promise { // Refuse unknown keys by name and include the supported keys and units. const known = ['azimuth', 'elevation', 'duration']; const unknown = Object.keys(options ?? {}).filter((key) => !known.includes(key)); if (unknown.length > 0) throw new Error( `editor.orbit: ${unknown.join(', ')} ${unknown.length === 1 ? 'is not a key' : 'are not keys'} ` + 'this verb takes. It takes azimuth and elevation in RADIANS (relative to where the ' + 'camera is now) and duration in SECONDS.', ); return this.#client.orbitDocument(options); } /** * A slow full revolution of the open document's subject — {@link orbit} with * the turns spelled out and a constant angular rate. Resolves at the end of * the last revolution. */ async turntable(options?: { readonly seconds?: number; readonly revolutions?: number; }): Promise { return this.#client.turntableDocument(options); } /** * What a frame of the open 3D document's stage costs when nothing caps it: `frames` of the * stage's own frame back to back, each waited out on the GPU (median, p95, min ms), the canvas * with its device pixel ratio, what was drawn after culling against what the scene holds, and * the draw mode. `stage` names another stage by its id (a split's second area, * `#area-2`). */ async frameCost(options?: { readonly frames?: number; readonly stage?: string; readonly quality?: 'full' | 'navigation' }): Promise { return this.#client.frameCostDocument(options); } async view(preset: ViewPreset): Promise { await this.#client.viewPreset(preset); } async workspace(id: EditorWorkspaceName): Promise<{ readonly workspace: EditorWorkspaceName; readonly applied: boolean }> { return this.#client.setWorkspace(id); } /** * Apply a STYLE BUNDLE by id — the chrome's palette, material and icon set in * one gesture, the session door beside * `View →