@forgeax/engine-devkit 0.1.7 → 0.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +21 -2
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/__tests__/native-preview-dispatch.test.d.ts +2 -0
  4. package/dist/__tests__/native-preview-dispatch.test.d.ts.map +1 -0
  5. package/dist/__tests__/native-preview-subject-draw.unit.test.d.ts +2 -0
  6. package/dist/__tests__/native-preview-subject-draw.unit.test.d.ts.map +1 -0
  7. package/dist/__tests__/single-html-runtime.e2e.test.d.ts +2 -0
  8. package/dist/__tests__/single-html-runtime.e2e.test.d.ts.map +1 -0
  9. package/dist/__tests__/single-html.test.d.ts +2 -0
  10. package/dist/__tests__/single-html.test.d.ts.map +1 -0
  11. package/dist/bootstrap-commands.d.ts.map +1 -1
  12. package/dist/cli-output.d.ts.map +1 -1
  13. package/dist/cli.mjs +1777 -133
  14. package/dist/cli.mjs.map +1 -1
  15. package/dist/commands.d.ts.map +1 -1
  16. package/dist/dist.d.ts +2 -2
  17. package/dist/dist.d.ts.map +1 -1
  18. package/dist/host.d.ts +6 -1
  19. package/dist/host.d.ts.map +1 -1
  20. package/dist/index.d.ts +5 -3
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.mjs +2317 -1125
  23. package/dist/index.mjs.map +1 -1
  24. package/dist/sdk-bootstrap.d.ts +6 -1
  25. package/dist/sdk-bootstrap.d.ts.map +1 -1
  26. package/dist/sdk-cli.mjs +33 -15
  27. package/dist/sdk-cli.mjs.map +1 -1
  28. package/dist/sdk.d.ts +1 -3
  29. package/dist/sdk.d.ts.map +1 -1
  30. package/dist/single-html.d.ts +43 -0
  31. package/dist/single-html.d.ts.map +1 -0
  32. package/dist/software-capture.d.ts +38 -0
  33. package/dist/software-capture.d.ts.map +1 -1
  34. package/dist/tools/client.d.ts.map +1 -1
  35. package/dist/tools/native-preview.d.ts.map +1 -1
  36. package/dist/tools/preview-contributions.d.ts +0 -5
  37. package/dist/tools/preview-contributions.d.ts.map +1 -1
  38. package/dist/types.d.ts +2 -0
  39. package/dist/types.d.ts.map +1 -1
  40. package/package.json +33 -31
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/archive.ts","../src/dist.ts","../src/project.ts","../src/engine-binding.ts","../src/host.ts","../src/types.ts","../src/assets.ts","../package.json","../src/init.ts","../src/sdk.ts","../src/sdk-bootstrap.ts","../src/sdk-update.ts","../src/skill-install.ts","../src/bootstrap-commands.ts","../src/plugin-authoring.ts","../src/rhi-debug/cli-context.ts","../src/rhi-debug/operations.ts","../src/sdk-install.ts","../src/shader-check.ts","../src/software-capture.ts","../src/commands.ts","../src/tools/preview-catalog.ts","../src/tools/catalog.ts","../src/tools/preview-migration.ts","../src/tools/project-tools.ts","../src/tools/offline-analysis.ts","../src/tools/preview-contributions.ts","../src/tools/contributions.ts","../src/tools/runtime.ts","../src/index.ts","../src/tools/benchmark/statistics.ts","../src/tools/benchmark/report.ts","../src/tools/benchmark/harness.ts","../src/tools/bootstrap.ts","../src/tools/cache.ts","../src/tools/carrier-provider.ts","../src/tools/carrier-rendezvous.ts","../src/tools/cli-adapter.ts","../src/tools/client.ts","../src/tools/library.ts","../src/tools/migration.ts","../src/tools/browser-host.ts","../src/tools/preview-host.ts","../src/tools/private-executor.ts","../src/tools/realms.ts","../src/tools/service.ts","../src/tools/service-transport.ts"],"names":["entries","readFile","resolve","writeFile","selected","readdir","builtAt","stat","createHash","resolved","dirname","conditionalExport","relative","sep","moduleSpecifier","mkdir","devDependencies","access","fileURLToPath","rm","filesUnder","cp","realpath","basename","isAbsolute","execFileAsync","mkdtemp","rename","promisify","execFile","readManifest","GameProjectSchema","tmpdir","viteBuild","pathExists","createNetServer","createServer","captureUrl","runtime","ok","sha256","createViteConfig","vitePreview","projectPluginEntries","createToolRuntime","commandFailure","defineTool","buildCommand","pluginInstallCommand","capabilityUnavailableError","missingTool","runProjectTool","createServiceCapability","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es: Uint8Array;\n}\n\nconst ZIP32_LIMIT = 0xffff_ffff;\nconst ZIP_ENTRY_LIMIT = 0xffff;\nconst UTF8_FLAG = 0x0800;\nconst DEFLATE_METHOD = 8;\nconst DOS_EPOCH_DATE = 0x0021;\n\nconst CRC_TABLE = new Uint32Array(256);\nfor (let index = 0; index < CRC_TABLE.length; index += 1) {\n let value = index;\n for (let bit = 0; bit < 8; bit += 1) value = (value >>> 1) ^ (0xedb8_8320 & -(value & 1));\n CRC_TABLE[index] = value >>> 0;\n}\n\nfunction crc32(bytes: Uint8Array): number {\n let value = 0xffff_ffff;\n for (const byte of bytes) value = (value >>> 8) ^ (CRC_TABLE[(value ^ byte) & 0xff] ?? 0);\n return (value ^ 0xffff_ffff) >>> 0;\n}\n\nfunction assertArchivePath(path: string): void {\n if (\n path.length === 0 ||\n path.startsWith('/') ||\n path.includes('\\\\') ||\n path.split('/').some((segment) => segment.length === 0 || segment === '.' || segment === '..')\n ) {\n throw new TypeError(`invalid ZIP entry path: ${path}`);\n }\n}\n\nexport function createZip(entriesInput: readonly ZipEntry[]): Buffer {\n if (entriesInput.length > ZIP_ENTRY_LIMIT) throw new RangeError('ZIP32 entry limit exceeded');\n const entries = [...entriesInput].sort((left, right) => left.path.localeCompare(right.path));\n const seen = new Set<string>();\n const localParts: Buffer[] = [];\n const centralParts: Buffer[] = [];\n let offset = 0;\n\n for (const entry of entries) {\n assertArchivePath(entry.path);\n if (seen.has(entry.path)) throw new TypeError(`duplicate ZIP entry path: ${entry.path}`);\n seen.add(entry.path);\n const name = Buffer.from(entry.path, 'utf8');\n const source = Buffer.from(entry.bytes);\n const compressed = deflateRawSync(source, { level: 9 });\n if (source.byteLength > ZIP32_LIMIT || compressed.byteLength > ZIP32_LIMIT) {\n throw new RangeError(`ZIP32 file limit exceeded: ${entry.path}`);\n }\n const checksum = crc32(source);\n const local = Buffer.alloc(30);\n local.writeUInt32LE(0x0403_4b50, 0);\n local.writeUInt16LE(20, 4);\n local.writeUInt16LE(UTF8_FLAG, 6);\n local.writeUInt16LE(DEFLATE_METHOD, 8);\n local.writeUInt16LE(0, 10);\n local.writeUInt16LE(DOS_EPOCH_DATE, 12);\n local.writeUInt32LE(checksum, 14);\n local.writeUInt32LE(compressed.byteLength, 18);\n local.writeUInt32LE(source.byteLength, 22);\n local.writeUInt16LE(name.byteLength, 26);\n local.writeUInt16LE(0, 28);\n localParts.push(local, name, compressed);\n\n const central = Buffer.alloc(46);\n central.writeUInt32LE(0x0201_4b50, 0);\n central.writeUInt16LE(20, 4);\n central.writeUInt16LE(20, 6);\n central.writeUInt16LE(UTF8_FLAG, 8);\n central.writeUInt16LE(DEFLATE_METHOD, 10);\n central.writeUInt16LE(0, 12);\n central.writeUInt16LE(DOS_EPOCH_DATE, 14);\n central.writeUInt32LE(checksum, 16);\n central.writeUInt32LE(compressed.byteLength, 20);\n central.writeUInt32LE(source.byteLength, 24);\n central.writeUInt16LE(name.byteLength, 28);\n central.writeUInt16LE(0, 30);\n central.writeUInt16LE(0, 32);\n central.writeUInt16LE(0, 34);\n central.writeUInt16LE(0, 36);\n central.writeUInt32LE(0, 38);\n central.writeUInt32LE(offset, 42);\n centralParts.push(central, name);\n\n offset += local.byteLength + name.byteLength + compressed.byteLength;\n if (offset > ZIP32_LIMIT) throw new RangeError('ZIP32 archive limit exceeded');\n }\n\n const centralDirectory = Buffer.concat(centralParts);\n if (centralDirectory.byteLength > ZIP32_LIMIT)\n throw new RangeError('ZIP32 directory limit exceeded');\n const end = Buffer.alloc(22);\n end.writeUInt32LE(0x0605_4b50, 0);\n end.writeUInt16LE(entries.length, 8);\n end.writeUInt16LE(entries.length, 10);\n end.writeUInt32LE(centralDirectory.byteLength, 12);\n end.writeUInt32LE(offset, 16);\n return Buffer.concat([...localParts, centralDirectory, end]);\n}\n","import { createHash } from 'node:crypto';\nimport { readdir, readFile, stat, writeFile } from 'node:fs/promises';\nimport { relative, resolve, sep } from 'node:path';\nimport type { CommandResult, ProjectFacts } from './types.js';\n\ninterface DistArtifact {\n readonly path: string;\n readonly mediaType: string;\n readonly bytes: number;\n readonly sha256: string;\n}\n\nexport interface DistManifest {\n readonly schemaVersion: '1.0.0';\n readonly project: { readonly id: string; readonly name: string };\n readonly base: string;\n readonly runtime: {\n readonly packIndexUrl: string;\n readonly shaderManifestUrl: string;\n };\n readonly artifacts: readonly DistArtifact[];\n}\n\nfunction mediaType(path: string): string {\n if (path.endsWith('.html')) return 'text/html';\n if (path.endsWith('.js') || path.endsWith('.mjs')) return 'text/javascript';\n if (path.endsWith('.json')) return 'application/json';\n if (path.endsWith('.wasm')) return 'application/wasm';\n if (path.endsWith('.png')) return 'image/png';\n if (path.endsWith('.jpg') || path.endsWith('.jpeg')) return 'image/jpeg';\n return 'application/octet-stream';\n}\n\nasync function filesUnder(root: string, directory = root): Promise<string[]> {\n const result: string[] = [];\n for (const name of (await readdir(directory)).sort()) {\n const path = resolve(directory, name);\n const info = await stat(path);\n if (info.isDirectory()) result.push(...(await filesUnder(root, path)));\n else if (info.isFile() && name !== 'forgeax-dist.json') result.push(path);\n }\n return result;\n}\n\nexport async function writeDistManifest(\n facts: ProjectFacts,\n base: string,\n rootInput = resolve(facts.root, 'dist'),\n): Promise<DistManifest> {\n const root = resolve(rootInput);\n const artifacts = await Promise.all(\n (await filesUnder(root)).map(async (path): Promise<DistArtifact> => {\n const bytes = await readFile(path);\n return {\n path: relative(root, path).split(sep).join('/'),\n mediaType: mediaType(path),\n bytes: bytes.byteLength,\n sha256: createHash('sha256').update(bytes).digest('hex'),\n };\n }),\n );\n const manifest: DistManifest = {\n schemaVersion: '1.0.0',\n project: { id: facts.id, name: facts.name },\n base,\n runtime: {\n packIndexUrl: 'pack-index.json',\n shaderManifestUrl: 'shaders/manifest.json',\n },\n artifacts,\n };\n await writeFile(resolve(root, 'forgeax-dist.json'), `${JSON.stringify(manifest, null, 2)}\\n`);\n return manifest;\n}\n\nexport async function verifyDist(rootInput: string): Promise<CommandResult<DistManifest>> {\n const root = resolve(rootInput);\n let manifest: DistManifest;\n try {\n manifest = JSON.parse(\n await readFile(resolve(root, 'forgeax-dist.json'), 'utf8'),\n ) as DistManifest;\n } catch (cause) {\n return {\n ok: false,\n error: {\n code: 'dist-manifest-unreadable',\n expected: 'a readable dist/forgeax-dist.json',\n hint: 'Run forgeax build and do not edit its derived manifest.',\n detail: { root, reason: cause instanceof Error ? cause.message : String(cause) },\n },\n };\n }\n if (manifest.schemaVersion !== '1.0.0' || !Array.isArray(manifest.artifacts)) {\n return {\n ok: false,\n error: {\n code: 'dist-manifest-invalid',\n expected: 'forgeax-dist schema 1.0.0',\n hint: 'Rebuild the game with a compatible ForgeaX DevKit.',\n detail: { root },\n },\n };\n }\n const declaredPaths = new Set(manifest.artifacts.map((artifact) => artifact.path));\n if (declaredPaths.size !== manifest.artifacts.length) {\n return {\n ok: false,\n error: {\n code: 'dist-artifact-duplicate',\n expected: 'every dist artifact path to be declared exactly once',\n hint: 'Rebuild the derived dist manifest.',\n detail: { root },\n },\n };\n }\n for (const artifact of manifest.artifacts) {\n const path = resolve(root, artifact.path);\n if (relative(root, path).startsWith('..')) {\n return {\n ok: false,\n error: {\n code: 'dist-path-escape',\n expected: 'every artifact path to remain inside dist',\n hint: 'Rebuild the derived dist manifest.',\n detail: { path: artifact.path },\n },\n };\n }\n try {\n const bytes = await readFile(path);\n const digest = createHash('sha256').update(bytes).digest('hex');\n if (bytes.byteLength !== artifact.bytes || digest !== artifact.sha256) {\n return {\n ok: false,\n error: {\n code: 'dist-artifact-mismatch',\n expected: 'artifact bytes and SHA-256 to match forgeax-dist.json',\n hint: 'Restore the built artifact or rebuild the complete dist.',\n detail: { path: artifact.path },\n },\n };\n }\n } catch {\n return {\n ok: false,\n error: {\n code: 'dist-artifact-missing',\n expected: 'every declared dist artifact to exist',\n hint: 'Restore the built artifact or rebuild the complete dist.',\n detail: { path: artifact.path },\n },\n };\n }\n }\n for (const required of [\n 'index.html',\n manifest.runtime.packIndexUrl,\n manifest.runtime.shaderManifestUrl,\n ]) {\n if (!manifest.artifacts.some((artifact) => artifact.path === required)) {\n return {\n ok: false,\n error: {\n code: 'dist-required-artifact-missing',\n expected: 'HTML, Pack index, and Shader manifest in the dist closure',\n hint: 'Rebuild after repairing the owning producer.',\n detail: { path: required },\n },\n };\n }\n }\n for (const path of await filesUnder(root)) {\n const artifactPath = relative(root, path).split(sep).join('/');\n if (!declaredPaths.has(artifactPath)) {\n return {\n ok: false,\n error: {\n code: 'dist-artifact-undeclared',\n expected: 'every file in dist to be covered by forgeax-dist.json',\n hint: 'Remove the foreign file or rebuild the complete dist.',\n detail: { path: artifactPath },\n },\n };\n }\n }\n return { ok: true, value: manifest };\n}\n","import { readFile } from 'node:fs/promises';\nimport { isAbsolute, resolve } from 'node:path';\nimport { type GameProjectPluginEntry, GameProjectSchema } from '@forgeax/engine-project';\nimport type { CommandError, CommandResult, ProjectFacts } from './types.js';\n\nfunction projectError(\n code: string,\n expected: string,\n hint: string,\n detail: Readonly<Record<string, unknown>>,\n): CommandResult<never> {\n return { ok: false, error: { code, expected, hint, detail } };\n}\n\nasync function readJson(path: string): Promise<unknown> {\n return JSON.parse(await readFile(path, 'utf8')) as unknown;\n}\n\nfunction firstUnsupportedStandaloneRealm(\n entries: readonly GameProjectPluginEntry[],\n inheritedRealm: GameProjectPluginEntry['realm'] = 'engine',\n): { readonly id: string; readonly realm: 'host' | 'build' } | undefined {\n for (const entry of entries) {\n const realm = entry.realm ?? inheritedRealm ?? 'engine';\n if (realm !== 'engine') return { id: entry.id, realm };\n if (entry.group === true) {\n const unsupported = firstUnsupportedStandaloneRealm(\n entry.config as readonly GameProjectPluginEntry[],\n realm,\n );\n if (unsupported !== undefined) return unsupported;\n }\n }\n return undefined;\n}\n\nfunction pluginModuleNames(entries: readonly GameProjectPluginEntry[]): string[] {\n return entries.flatMap((entry) =>\n entry.group === true\n ? pluginModuleNames(entry.config as readonly GameProjectPluginEntry[])\n : [entry.name],\n );\n}\n\nexport async function readProjectFacts(\n rootInput = process.cwd(),\n): Promise<CommandResult<ProjectFacts>> {\n const root = resolve(rootInput);\n let forgeValue: unknown;\n let packageValue: unknown;\n try {\n [forgeValue, packageValue] = await Promise.all([\n readJson(resolve(root, 'forge.json')),\n readJson(resolve(root, 'package.json')),\n ]);\n } catch (cause) {\n return projectError(\n 'project-manifest-unreadable',\n 'readable forge.json and package.json files',\n 'Run the command from a ForgeaX game root or pass its directory.',\n { root, reason: cause instanceof Error ? cause.message : String(cause) },\n );\n }\n if (forgeValue === null || typeof forgeValue !== 'object') {\n return projectError(\n 'project-manifest-invalid',\n 'forge.json to contain an object',\n 'Repair forge.json before running DevKit.',\n { root },\n );\n }\n if (packageValue === null || typeof packageValue !== 'object') {\n return projectError(\n 'package-manifest-invalid',\n 'package.json to contain an object',\n 'Repair package.json before running DevKit.',\n { root },\n );\n }\n const parsedForge = GameProjectSchema.safeParse(forgeValue);\n if (!parsedForge.success) {\n return projectError(\n 'project-manifest-invalid',\n 'forge.json to satisfy @forgeax/engine-project GameProjectSchema',\n 'Repair the fields reported by the authoritative project schema.',\n { root, issues: parsedForge.error.issues },\n );\n }\n const forge = parsedForge.data;\n if (\n forge.id.length === 0 ||\n forge.name.length === 0 ||\n forge.entry === undefined ||\n forge.entry.length === 0\n ) {\n return projectError(\n 'project-manifest-invalid',\n 'forge.json to declare id, name, and entry',\n 'Restore the project entry; plugin Entries remain optional additions.',\n { root },\n );\n }\n const plugins = forge.plugins ?? [];\n const unsupportedRealm = firstUnsupportedStandaloneRealm(plugins);\n if (unsupportedRealm !== undefined) {\n return projectError(\n 'project-plugin-realm-unsupported',\n 'the standalone Devkit host to contain only engine-realm plugin Entries',\n 'Move Host or build plugins to a host that owns that physical realm.',\n { root, ...unsupportedRealm },\n );\n }\n const entryPath = isAbsolute(forge.entry) ? forge.entry : resolve(root, forge.entry);\n try {\n await readFile(entryPath);\n } catch {\n return projectError(\n 'project-entry-missing',\n 'forge.json#entry to resolve to a readable module',\n 'Restore the game entry or update forge.json#entry.',\n { root, entry: forge.entry },\n );\n }\n const packageJson = packageValue as Record<string, unknown>;\n const forgeax = packageJson.forgeax;\n const configuredRoots =\n forgeax !== null && typeof forgeax === 'object'\n ? (forgeax as { assets?: { roots?: unknown } }).assets?.roots\n : undefined;\n const assetRoots =\n Array.isArray(configuredRoots) && configuredRoots.every((value) => typeof value === 'string')\n ? configuredRoots\n : ['assets'];\n const configuredImporters =\n forgeax !== null && typeof forgeax === 'object'\n ? (forgeax as { assets?: { importers?: unknown } }).assets?.importers\n : undefined;\n const assetImporters =\n Array.isArray(configuredImporters) &&\n configuredImporters.every((value) => typeof value === 'string')\n ? configuredImporters\n : [];\n const configuredPublicDir =\n forgeax !== null && typeof forgeax === 'object'\n ? (forgeax as { assets?: { publicDir?: unknown } }).assets?.publicDir\n : undefined;\n const assetPublicDir = typeof configuredPublicDir === 'string' ? configuredPublicDir : undefined;\n const physics = forge.physics === '2d' || forge.physics === '3d' ? forge.physics : undefined;\n const defaultScene =\n typeof forge.defaultScene === 'string' && forge.defaultScene.length > 0\n ? forge.defaultScene\n : undefined;\n const normalizedEntry = forge.entry.startsWith('./') ? forge.entry : `./${forge.entry}`;\n const bootstrapEntry = pluginModuleNames(plugins)\n .map((name) => (name.startsWith('./') ? name : `./${name}`))\n .includes(normalizedEntry)\n ? undefined\n : forge.entry;\n return {\n ok: true,\n value: {\n root,\n id: forge.id,\n name: forge.name,\n entry: forge.entry,\n ...(bootstrapEntry === undefined ? {} : { bootstrapEntry }),\n plugins,\n ...(physics === undefined ? {} : { physics }),\n ...(defaultScene === undefined ? {} : { defaultScene }),\n assetRoots,\n ...(assetImporters.length === 0 ? {} : { assetImporters }),\n ...(assetPublicDir === undefined ? {} : { assetPublicDir }),\n packageJson,\n },\n };\n}\n\nexport function commandError(cause: unknown, fallbackCode: string): CommandError {\n if (\n cause !== null &&\n typeof cause === 'object' &&\n 'code' in cause &&\n 'expected' in cause &&\n 'hint' in cause &&\n 'detail' in cause\n ) {\n return cause as CommandError;\n }\n return {\n code: fallbackCode,\n expected: 'the ForgeaX command to complete',\n hint: 'Inspect the underlying diagnostic and repair the owning input.',\n detail: { reason: cause instanceof Error ? cause.message : String(cause) },\n };\n}\n","import { createHash } from 'node:crypto';\nimport {\n access,\n mkdir,\n readdir,\n readFile,\n realpath,\n rename,\n rm,\n stat,\n writeFile,\n} from 'node:fs/promises';\nimport { dirname, resolve } from 'node:path';\nimport { commandError, readProjectFacts } from './project.js';\nimport type { CommandError, CommandResult, ProjectCommandOptions } from './types.js';\n\nexport const ENGINE_BINDING_SCHEMA_VERSION = '1.0.0' as const;\n\nexport type EngineBindingMode = 'sdk' | 'local';\n\nexport interface EngineBinding {\n readonly schemaVersion: typeof ENGINE_BINDING_SCHEMA_VERSION;\n readonly path: string;\n}\n\nexport interface EnginePackageStatus {\n readonly name: string;\n readonly root: string;\n readonly version: string;\n readonly entry: string | null;\n readonly built: boolean;\n readonly entryDigest: string | null;\n readonly builtAt: string | null;\n}\n\nexport interface EngineWorkspaceStatus {\n readonly root: string;\n readonly packageCount: number;\n readonly builtPackages: number;\n readonly missingBuilds: readonly string[];\n readonly versions: readonly string[];\n readonly packages: readonly EnginePackageStatus[];\n readonly digest: string;\n readonly builtAt: string | null;\n}\n\nexport interface EngineStatusReport {\n readonly schemaVersion: typeof ENGINE_BINDING_SCHEMA_VERSION;\n readonly root: string;\n readonly binding: EngineBinding | null;\n readonly mode: EngineBindingMode;\n readonly resolved: {\n readonly root: string | null;\n readonly version: string | null;\n readonly entry: string | null;\n readonly built: boolean;\n readonly source: 'sdk' | 'local' | 'unresolved';\n };\n readonly workspace: EngineWorkspaceStatus | null;\n readonly projectDependencies: 'registry' | 'workspace' | 'mixed' | 'none';\n readonly npmCompatible: boolean;\n readonly healthy: boolean;\n readonly next: readonly string[];\n readonly diagnostic?: CommandError;\n}\n\nexport interface EngineBindingCommandOptions extends ProjectCommandOptions {\n readonly path?: string;\n readonly dryRun?: boolean;\n}\n\ninterface PackageManifest extends Readonly<Record<string, unknown>> {\n readonly name?: unknown;\n readonly version?: unknown;\n readonly main?: unknown;\n readonly module?: unknown;\n readonly exports?: unknown;\n}\n\nconst bindingFile = (root: string): string => resolve(root, '.forgeax', 'engine-binding.json');\n\nfunction bindingError(\n code: string,\n expected: string,\n hint: string,\n detail: Readonly<Record<string, unknown>> = {},\n): CommandResult<never> {\n return { ok: false, error: { code, expected, hint, detail } };\n}\n\nfunction isMissing(cause: unknown): boolean {\n return cause !== null && typeof cause === 'object' && 'code' in cause && cause.code === 'ENOENT';\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction parseBinding(value: unknown, path: string): CommandResult<EngineBinding> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n return bindingError(\n 'engine-binding-invalid',\n 'engine-binding.json to contain one object',\n 'Run forgeax engine unlink, then select a binding again.',\n { path },\n );\n }\n const candidate = value as {\n readonly schemaVersion?: unknown;\n readonly path?: unknown;\n };\n if (candidate.schemaVersion !== ENGINE_BINDING_SCHEMA_VERSION) {\n return bindingError(\n 'engine-binding-version-unsupported',\n `engine-binding.json schemaVersion ${ENGINE_BINDING_SCHEMA_VERSION}`,\n 'Upgrade the SDK or remove the stale binding with forgeax engine unlink.',\n { path, schemaVersion: candidate.schemaVersion ?? null },\n );\n }\n if (typeof candidate.path !== 'string' || candidate.path.length === 0) {\n return bindingError(\n 'engine-binding-path-missing',\n 'engine-binding.json to contain one non-empty local Engine path',\n 'Run forgeax engine use-local <engine-directory>.',\n { path },\n );\n }\n return {\n ok: true,\n value: {\n schemaVersion: ENGINE_BINDING_SCHEMA_VERSION,\n path: resolve(candidate.path),\n },\n };\n}\n\nexport async function readEngineBinding(\n rootInput = process.cwd(),\n): Promise<CommandResult<EngineBinding | null>> {\n const root = resolve(rootInput);\n const path = bindingFile(root);\n try {\n const value = JSON.parse(await readFile(path, 'utf8')) as unknown;\n return parseBinding(value, path);\n } catch (cause) {\n if (isMissing(cause)) return { ok: true, value: null };\n return bindingError(\n 'engine-binding-unreadable',\n 'engine-binding.json to be readable JSON',\n 'Repair or remove .forgeax/engine-binding.json, then select a binding again.',\n { path, reason: cause instanceof Error ? cause.message : String(cause) },\n );\n }\n}\n\nasync function writeEngineBinding(root: string, binding: EngineBinding): Promise<void> {\n const path = bindingFile(root);\n const partial = `${path}.partial-${process.pid}`;\n await mkdir(dirname(path), { recursive: true });\n await writeFile(partial, `${JSON.stringify(binding, null, 2)}\\n`, 'utf8');\n await rename(partial, path);\n}\n\nfunction conditionalExport(value: unknown): string | undefined {\n if (typeof value === 'string') return value;\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined;\n const record = value as Record<string, unknown>;\n for (const key of ['import', 'browser', 'node', 'default', 'require', 'types']) {\n const candidate = record[key];\n const selected = conditionalExport(candidate);\n if (selected !== undefined) return selected;\n }\n return undefined;\n}\n\nfunction packageEntry(manifest: PackageManifest): string | undefined {\n const exportsValue = manifest.exports;\n if (exportsValue !== undefined) {\n if (typeof exportsValue === 'object' && exportsValue !== null && !Array.isArray(exportsValue)) {\n const root = (exportsValue as Record<string, unknown>)['.'];\n const selected = conditionalExport(root ?? exportsValue);\n if (selected !== undefined) return selected;\n }\n const selected = conditionalExport(exportsValue);\n if (selected !== undefined) return selected;\n }\n return typeof manifest.module === 'string'\n ? manifest.module\n : typeof manifest.main === 'string'\n ? manifest.main\n : undefined;\n}\n\nasync function readManifest(path: string): Promise<PackageManifest> {\n const value = JSON.parse(await readFile(path, 'utf8')) as unknown;\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`engine-package-manifest-invalid: ${path}`);\n }\n return value as PackageManifest;\n}\n\nexport async function inspectEngineWorkspace(\n workspaceInput: string,\n): Promise<CommandResult<EngineWorkspaceStatus>> {\n const root = resolve(workspaceInput);\n const packageRoot = resolve(root, 'packages');\n try {\n await access(resolve(root, 'pnpm-workspace.yaml'));\n const entries = await readdir(packageRoot, { withFileTypes: true });\n const packages: EnginePackageStatus[] = [];\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n const packagePath = resolve(packageRoot, entry.name);\n let manifest: PackageManifest;\n try {\n manifest = await readManifest(resolve(packagePath, 'package.json'));\n } catch {\n continue;\n }\n if (typeof manifest.name !== 'string' || !manifest.name.startsWith('@forgeax/engine'))\n continue;\n if (typeof manifest.version !== 'string') {\n return bindingError(\n 'engine-package-version-missing',\n 'every local Engine package to declare a version',\n 'Restore the package manifest version before selecting a local Engine.',\n { package: manifest.name, root: packagePath },\n );\n }\n const target = packageEntry(manifest);\n const entryPath = target === undefined ? undefined : resolve(packagePath, target);\n let entryDigest: string | null = null;\n let builtAt: string | null = null;\n if (entryPath !== undefined && (await pathExists(entryPath))) {\n const [bytes, metadata] = await Promise.all([readFile(entryPath), stat(entryPath)]);\n entryDigest = `sha256:${createHash('sha256').update(bytes).digest('hex')}`;\n builtAt = metadata.mtime.toISOString();\n }\n packages.push({\n name: manifest.name,\n root: packagePath,\n version: manifest.version,\n entry: entryPath ?? null,\n built: entryDigest !== null,\n entryDigest,\n builtAt,\n });\n }\n packages.sort((a, b) => a.name.localeCompare(b.name));\n if (packages.length === 0) {\n return bindingError(\n 'engine-workspace-empty',\n 'the local Engine workspace to contain @forgeax/engine packages',\n 'Pass the Engine repository or its source/engine SDK directory.',\n { root, packageRoot },\n );\n }\n const versions = [...new Set(packages.map((item) => item.version))].sort();\n const missingBuilds = packages.filter((item) => !item.built).map((item) => item.name);\n const builtAt =\n packages\n .flatMap((item) => (item.builtAt === null ? [] : [item.builtAt]))\n .sort()\n .at(-1) ?? null;\n const digest = `sha256:${createHash('sha256')\n .update(\n packages\n .map((item) => `${item.name}\\0${item.version}\\0${item.entryDigest ?? 'unbuilt'}`)\n .join('\\n'),\n )\n .digest('hex')}`;\n return {\n ok: true,\n value: {\n root,\n packageCount: packages.length,\n builtPackages: packages.length - missingBuilds.length,\n missingBuilds,\n versions,\n packages,\n digest,\n builtAt,\n },\n };\n } catch (cause) {\n return bindingError(\n isMissing(cause) ? 'engine-workspace-missing' : 'engine-workspace-unreadable',\n 'a readable Engine workspace with pnpm-workspace.yaml and packages/',\n 'Pass the Engine repository root, not its packages/ directory.',\n { root, packageRoot, reason: cause instanceof Error ? cause.message : String(cause) },\n );\n }\n}\n\nfunction projectDependencyMode(\n packageJson: Readonly<Record<string, unknown>>,\n): EngineStatusReport['projectDependencies'] {\n let workspace = false;\n let registry = false;\n for (const section of [\n 'dependencies',\n 'devDependencies',\n 'optionalDependencies',\n 'peerDependencies',\n ]) {\n const value = packageJson[section];\n if (value === null || typeof value !== 'object' || Array.isArray(value)) continue;\n for (const version of Object.values(value)) {\n if (typeof version !== 'string') continue;\n if (version.startsWith('workspace:') || version.startsWith('file:')) workspace = true;\n else registry = true;\n }\n }\n return workspace ? (registry ? 'mixed' : 'workspace') : registry ? 'registry' : 'none';\n}\n\nasync function sdkResolution(root: string): Promise<EngineStatusReport['resolved']> {\n const packageJson = resolve(root, 'node_modules', '@forgeax', 'engine', 'package.json');\n try {\n const manifest = await readManifest(packageJson);\n const target = packageEntry(manifest);\n const entry = target === undefined ? null : resolve(dirname(packageJson), target);\n return {\n root: dirname(packageJson),\n version: typeof manifest.version === 'string' ? manifest.version : null,\n entry,\n built: entry !== null && (await pathExists(entry)),\n source: 'sdk',\n };\n } catch {\n return { root: null, version: null, entry: null, built: false, source: 'unresolved' };\n }\n}\n\nexport async function engineStatusCommand(\n options: EngineBindingCommandOptions = {},\n): Promise<CommandResult<EngineStatusReport>> {\n const facts = await readProjectFacts(options.root);\n if (!facts.ok) return facts;\n const bindingResult = await readEngineBinding(facts.value.root);\n if (!bindingResult.ok) return bindingResult;\n const binding = bindingResult.value;\n const mode: EngineBindingMode = binding === null ? 'sdk' : 'local';\n const projectDependencies = projectDependencyMode(facts.value.packageJson);\n if (binding !== null) {\n const localPath = binding.path;\n const localBinding: EngineBinding = {\n schemaVersion: ENGINE_BINDING_SCHEMA_VERSION,\n path: localPath,\n };\n const workspaceResult = await inspectEngineWorkspace(localPath);\n if (!workspaceResult.ok) {\n const resolved: EngineStatusReport['resolved'] = {\n root: localPath,\n version: null,\n entry: null,\n built: false,\n source: 'local',\n };\n return {\n ok: true,\n value: {\n schemaVersion: ENGINE_BINDING_SCHEMA_VERSION,\n root: facts.value.root,\n binding: localBinding,\n mode,\n resolved,\n workspace: null,\n projectDependencies,\n npmCompatible: projectDependencies === 'registry' || projectDependencies === 'none',\n healthy: false,\n next: ['forgeax engine unlink', 'forgeax engine use-local <engine-directory>'],\n diagnostic: workspaceResult.error,\n },\n };\n }\n const workspace = workspaceResult.value;\n const version = workspace.versions.length === 1 ? (workspace.versions[0] ?? null) : null;\n const umbrella = workspace.packages.find((item) => item.name === '@forgeax/engine');\n const resolved: EngineStatusReport['resolved'] = {\n root: localPath,\n version,\n entry: umbrella?.entry ?? null,\n built: umbrella?.built ?? false,\n source: 'local',\n };\n const healthy = workspace.versions.length === 1 && workspace.missingBuilds.length === 0;\n return {\n ok: true,\n value: {\n schemaVersion: ENGINE_BINDING_SCHEMA_VERSION,\n root: facts.value.root,\n binding: localBinding,\n mode,\n resolved,\n workspace,\n projectDependencies,\n npmCompatible: projectDependencies === 'registry' || projectDependencies === 'none',\n healthy,\n next: healthy\n ? ['forgeax build', 'forgeax capture --backend auto --require-ui']\n : ['pnpm build:engine', 'forgeax engine doctor'],\n },\n };\n }\n const resolved = await sdkResolution(facts.value.root);\n return {\n ok: true,\n value: {\n schemaVersion: ENGINE_BINDING_SCHEMA_VERSION,\n root: facts.value.root,\n binding,\n mode,\n resolved,\n workspace: null,\n projectDependencies,\n npmCompatible: projectDependencies === 'registry' || projectDependencies === 'none',\n healthy: resolved.source === 'sdk' && resolved.built,\n next:\n resolved.source === 'sdk' && resolved.built\n ? ['forgeax build', 'forgeax capture --backend auto --require-ui']\n : ['pnpm install', 'forgeax doctor'],\n },\n };\n}\n\nexport async function engineUseLocalCommand(\n options: EngineBindingCommandOptions,\n): Promise<CommandResult<EngineStatusReport>> {\n const root = resolve(options.root ?? process.cwd());\n if (options.path === undefined || options.path.trim().length === 0) {\n return bindingError(\n 'engine-binding-path-missing',\n 'forgeax engine use-local <engine-directory>',\n 'Pass the local Engine repository or SDK source directory.',\n );\n }\n let localPath: string;\n try {\n localPath = await realpath(resolve(root, options.path));\n } catch (cause) {\n return bindingError(\n 'engine-workspace-missing',\n 'the local Engine directory to exist',\n 'Pass an existing Engine repository or SDK source directory.',\n {\n path: resolve(root, options.path),\n reason: cause instanceof Error ? cause.message : String(cause),\n },\n );\n }\n const workspace = await inspectEngineWorkspace(localPath);\n if (!workspace.ok) return workspace;\n const binding: EngineBinding = {\n schemaVersion: ENGINE_BINDING_SCHEMA_VERSION,\n path: localPath,\n };\n if (options.dryRun !== true) await writeEngineBinding(root, binding);\n const status = await engineStatusCommand({ root });\n if (!status.ok) return status;\n return {\n ok: true,\n value: {\n ...status.value,\n next:\n workspace.value.missingBuilds.length === 0\n ? ['forgeax build', 'forgeax capture --backend auto --require-ui']\n : ['pnpm build:engine', 'forgeax engine doctor'],\n },\n };\n}\n\nexport async function engineUnlinkCommand(\n options: EngineBindingCommandOptions = {},\n): Promise<CommandResult<EngineStatusReport>> {\n const root = resolve(options.root ?? process.cwd());\n if (options.dryRun !== true) await rm(bindingFile(root), { force: true });\n return engineStatusCommand({ root });\n}\n\nexport async function engineDoctorCommand(\n options: EngineBindingCommandOptions = {},\n): Promise<CommandResult<EngineStatusReport>> {\n const status = await engineStatusCommand(options);\n if (!status.ok) return status;\n if (\n status.value.projectDependencies === 'workspace' ||\n status.value.projectDependencies === 'mixed'\n ) {\n return {\n ok: false,\n error: {\n code: 'engine-project-workspace-dependency',\n expected: 'the game project to use registry or SDK-resolved dependencies for npm consumers',\n hint: 'This project is a pnpm workspace; use pnpm here, or create a clean SDK game project for npm install.',\n detail: { root: status.value.root, projectDependencies: status.value.projectDependencies },\n },\n };\n }\n if (status.value.diagnostic !== undefined) return { ok: false, error: status.value.diagnostic };\n if (!status.value.healthy) {\n return {\n ok: false,\n error: {\n code:\n status.value.mode === 'local' ? 'engine-local-build-missing' : 'engine-sdk-unresolved',\n expected: 'the selected Engine binding to resolve to built packages',\n hint:\n status.value.mode === 'local'\n ? 'Run pnpm build:engine in the selected Engine checkout, then rerun forgeax engine doctor.'\n : 'Run pnpm install in the game project or select a valid local Engine checkout.',\n detail: { status: status.value },\n },\n };\n }\n return status;\n}\n\nexport function engineBindingFilePath(rootInput = process.cwd()): string {\n return bindingFile(resolve(rootInput));\n}\n\nexport function engineBindingError(cause: unknown): CommandError {\n return commandError(cause, 'engine-binding-failed');\n}\n","import { existsSync } from 'node:fs';\nimport { mkdir, readdir, readFile, writeFile } from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport { dirname, relative, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { audioImporter } from '@forgeax/engine-audio-webaudio/audio-importer';\nimport { fbxImporter } from '@forgeax/engine-fbx';\nimport { fontImporter } from '@forgeax/engine-font/font-importer';\nimport { gltfImporter } from '@forgeax/engine-gltf';\nimport { imageImporter } from '@forgeax/engine-image/image-importer';\nimport { BUILTIN_MESH_ASSETS } from '@forgeax/engine-pack/builtin';\nimport { scanInventory } from '@forgeax/engine-pack/scanner';\nimport { validateCanonicalKitReceipt } from '@forgeax/engine-preview';\nimport { createMaterialPackCooker } from '@forgeax/engine-shader-compiler';\nimport { createStandaloneRuntimeAssetBinding, type Importer } from '@forgeax/engine-types';\nimport { createParticleCodeNativeCookerFromRoots } from '@forgeax/engine-vfx-compiler';\nimport { pluginPack, reloadAssetHost } from '@forgeax/engine-vite-plugin-pack';\nimport { forgeaxShader } from '@forgeax/engine-vite-plugin-shader';\nimport type { InlineConfig, Plugin } from 'vite';\nimport { inspectEngineWorkspace, readEngineBinding } from './engine-binding.js';\nimport type { BootstrapRoot } from './host/base-host.js';\nimport type { ProjectFacts, ProjectPortOptions } from './types.js';\n\ninterface CatalogModule {\n readonly name: string;\n readonly realm: 'host' | 'engine';\n}\n\nexport function ignoreDevKitCatalogPath(path: string): boolean {\n const normalized = path.replace(/\\\\/g, '/');\n return normalized.split('/').includes('shaders');\n}\n\nexport function devKitDdcRoots(projectRoot: string): {\n readonly buildCacheRoot: string;\n readonly projectDdcRoot: string;\n} {\n return {\n buildCacheRoot: resolve(projectRoot, '.forgeax', 'ddc', 'build-cache'),\n projectDdcRoot: resolve(projectRoot, '.forgeax', 'ddc', 'v2'),\n };\n}\n\nfunction isResourcePreviewIgnoredPath(path: string): boolean {\n return (\n ignoreDevKitCatalogPath(path) ||\n path.endsWith('.wgsl.meta.json') ||\n path.endsWith('target-profile.json.meta.json')\n );\n}\n\nfunction isProjectSourceIgnoredPath(path: string): boolean {\n return ignoreDevKitCatalogPath(path) || path.endsWith('.wgsl.meta.json');\n}\n\ninterface CanonicalKitLocation {\n readonly root: string;\n readonly guid: string;\n}\n\n/**\n * Materialize the Engine-owned procedural mesh descriptors missing from a\n * standalone project. The project remains the author of any descriptor it\n * explicitly carries (for example, the game-default template); generated\n * rows fill only the GUID closure required by legacy scenes that reference\n * Engine builtins without embedding a duplicate declaration.\n */\nasync function prepareBuiltinPack(\n projectRoots: readonly string[],\n generated: string,\n ignorePath: (path: string) => boolean,\n): Promise<string | undefined> {\n const inventory = await scanInventory(projectRoots, { ignorePath });\n if (!inventory.ok) return undefined;\n const declared = new Set<string>();\n for (const declaration of inventory.value.declarations.values()) {\n if (declaration.format === 'pack.json') {\n for (const asset of declaration.value.assets) declared.add(asset.guid.toLowerCase());\n continue;\n }\n for (const asset of declaration.value.subAssets) declared.add(asset.guid.toLowerCase());\n }\n const missing = BUILTIN_MESH_ASSETS.filter((asset) => !declared.has(asset.guid.toLowerCase()));\n if (missing.length === 0) return undefined;\n const packPath = resolve(generated, 'engine-builtins.pack.json');\n await writeFile(\n packPath,\n `${JSON.stringify(\n {\n schemaVersion: '2.0.0',\n kind: 'internal-text-package',\n assets: missing.map((asset) => ({\n guid: asset.guid,\n kind: 'mesh',\n payload: { geometry: asset.geometry },\n refs: [],\n artifacts: {},\n })),\n },\n null,\n 2,\n )}\\n`,\n 'utf8',\n );\n return packPath;\n}\n\nconst hostRequire = createRequire(import.meta.url);\n\ninterface EngineWorkspacePackage {\n readonly root: string;\n readonly manifest: Readonly<Record<string, unknown>>;\n}\n\ntype PackageExportValue = string | null | { readonly [key: string]: PackageExportValue };\n\nfunction findEngineWorkspaceRoot(): string | undefined {\n let cursor = dirname(fileURLToPath(import.meta.url));\n for (;;) {\n if (existsSync(resolve(cursor, 'pnpm-workspace.yaml'))) return cursor;\n const parent = dirname(cursor);\n if (parent === cursor) return undefined;\n cursor = parent;\n }\n}\n\nasync function engineWorkspacePackages(\n workspaceRoot = findEngineWorkspaceRoot(),\n): Promise<ReadonlyMap<string, EngineWorkspacePackage>> {\n if (workspaceRoot === undefined) return new Map<string, EngineWorkspacePackage>();\n const packageRoot = resolve(workspaceRoot, 'packages');\n // A generated game is a pnpm workspace too, but it does not own a local\n // `packages/` tree. Its installed Engine packages are resolved by Node;\n // the workspace resolver is only an SDK/source-checkout fallback.\n if (!existsSync(packageRoot)) return new Map<string, EngineWorkspacePackage>();\n const packages = new Map<string, EngineWorkspacePackage>();\n for (const entry of await readdir(packageRoot, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const root = resolve(packageRoot, entry.name);\n try {\n const manifest = JSON.parse(await readFile(resolve(root, 'package.json'), 'utf8')) as unknown;\n if (manifest === null || typeof manifest !== 'object') continue;\n const name = (manifest as { readonly name?: unknown }).name;\n if (typeof name === 'string' && name.startsWith('@forgeax/engine')) {\n packages.set(name, { root, manifest: manifest as Readonly<Record<string, unknown>> });\n }\n } catch {\n // A partial SDK/source checkout may omit an unrelated package manifest. The\n // package remains resolvable from the consumer project when available.\n }\n }\n return packages;\n}\n\nfunction conditionalExport(value: PackageExportValue): string | undefined {\n if (typeof value === 'string') return value;\n if (value === null || Array.isArray(value)) return undefined;\n for (const condition of ['browser', 'import', 'node', 'default']) {\n const candidate = value[condition];\n if (candidate === undefined) continue;\n const selected = conditionalExport(candidate);\n if (selected !== undefined) return selected;\n }\n return undefined;\n}\n\nfunction packageExportTarget(\n manifest: Readonly<Record<string, unknown>>,\n subpath: string,\n): string | undefined {\n const exportsValue = manifest.exports as PackageExportValue | undefined;\n if (exportsValue === undefined) {\n if (subpath.length > 0) return undefined;\n const main = manifest.module ?? manifest.main;\n return typeof main === 'string' ? main : undefined;\n }\n if (typeof exportsValue === 'string' || exportsValue === null) {\n return subpath.length === 0 ? conditionalExport(exportsValue) : undefined;\n }\n const keys = Object.keys(exportsValue);\n const subpathMap = keys.some((key) => key === '.' || key.startsWith('./'));\n if (!subpathMap) return subpath.length === 0 ? conditionalExport(exportsValue) : undefined;\n const requested = subpath.length === 0 ? '.' : `./${subpath}`;\n const exact = exportsValue[requested];\n if (exact !== undefined) return conditionalExport(exact);\n for (const key of keys) {\n const marker = key.indexOf('*');\n if (marker < 0) continue;\n const prefix = key.slice(0, marker);\n const suffix = key.slice(marker + 1);\n if (!requested.startsWith(prefix) || !requested.endsWith(suffix)) continue;\n const replacement = requested.slice(prefix.length, requested.length - suffix.length);\n const exportTarget = exportsValue[key];\n if (exportTarget === undefined) continue;\n const selected = conditionalExport(exportTarget);\n return selected?.replaceAll('*', replacement);\n }\n return undefined;\n}\n\nfunction engineWorkspaceImport(\n source: string,\n packages: ReadonlyMap<string, EngineWorkspacePackage>,\n): string | undefined {\n if (!source.startsWith('@forgeax/engine')) return undefined;\n const separator = source.indexOf('/', '@forgeax/engine'.length);\n const packageName = separator < 0 ? source : source.slice(0, separator);\n const subpath = separator < 0 ? '' : source.slice(separator + 1);\n const packageInfo = packages.get(packageName);\n if (packageInfo === undefined) return undefined;\n const target = packageExportTarget(packageInfo.manifest, subpath);\n if (target === undefined) return undefined;\n const absolute = resolve(packageInfo.root, target);\n const inside = relative(packageInfo.root, absolute);\n if (inside === '..' || inside.startsWith(`..${sep}`) || absolute === packageInfo.root) {\n return undefined;\n }\n return absolute;\n}\n\nasync function createEngineWorkspaceResolver(projectRoot: string): Promise<Plugin | undefined> {\n const binding = await readEngineBinding(projectRoot);\n if (!binding.ok) {\n throw new Error(`${binding.error.code}: ${binding.error.hint}`);\n }\n const localRoot = binding.value?.path;\n if (localRoot !== undefined) {\n const inspected = await inspectEngineWorkspace(localRoot);\n if (!inspected.ok) throw new Error(`${inspected.error.code}: ${inspected.error.hint}`);\n }\n const packages = await engineWorkspacePackages(localRoot);\n if (packages.size === 0) return undefined;\n return {\n name: 'forgeax:devkit-engine-workspace-resolver',\n enforce: 'pre',\n async resolveId(source, importer) {\n const bareSource = source.split('?', 1)[0] ?? source;\n if (!bareSource.startsWith('@forgeax/engine')) return null;\n if (localRoot !== undefined) return engineWorkspaceImport(bareSource, packages);\n try {\n const resolved = await this.resolve(source, importer, { skipSelf: true });\n if (resolved !== null) return resolved;\n } catch {\n // Fall through to the Engine workspace only when the external project\n // has no installed copy of this package.\n }\n return engineWorkspaceImport(bareSource, packages);\n },\n };\n}\n\nasync function consumerEngineAliases(\n projectRoot: string,\n): Promise<readonly { readonly find: string; readonly replacement: string }[]> {\n const root = resolve(projectRoot, 'node_modules', '.pnpm', 'node_modules', '@forgeax');\n try {\n const entries = await readdir(root, { withFileTypes: true });\n return entries\n .filter((entry) => entry.isDirectory() && entry.name.startsWith('engine-'))\n .map((entry) => ({\n find: `@forgeax/${entry.name}`,\n replacement: resolve(root, entry.name),\n }))\n .sort((a, b) => a.find.localeCompare(b.find));\n } catch {\n return [];\n }\n}\n\nasync function resolveCanonicalKit(): Promise<CanonicalKitLocation> {\n const packageJson = hostRequire.resolve('@forgeax/engine-preview/package.json');\n const root = resolve(packageJson, '..', 'assets/canonical-kit');\n if (!existsSync(root)) throw new Error(`canonical preview kit root is missing: ${root}`);\n const receiptPath = resolve(root, 'cook-receipt.json');\n const receipt = validateCanonicalKitReceipt(JSON.parse(await readFile(receiptPath, 'utf8')));\n if (!receipt.ok) {\n throw new Error(`${receipt.error.code}: ${receipt.error.detail.field}`);\n }\n const sourcePath = resolve(root, receipt.value.transport.source);\n const metaPath = resolve(root, receipt.value.transport.meta);\n if (!existsSync(sourcePath) || !existsSync(metaPath)) {\n throw new Error('canonical preview kit source and Meta must be package-owned files');\n }\n return { root, guid: receipt.value.source.guid };\n}\n\nfunction moduleSpecifier(from: string, to: string): string {\n const value = relative(from, to).split(sep).join('/');\n return value.startsWith('.') ? value : `./${value}`;\n}\n\nfunction catalogModules(facts: ProjectFacts): CatalogModule[] {\n const modules = new Map<string, CatalogModule>();\n const visit = (\n entries: ProjectFacts['plugins'],\n inheritedRealm: 'host' | 'engine' | 'build' = 'engine',\n ): void => {\n for (const entry of entries) {\n const realm = entry.realm ?? inheritedRealm;\n if (entry.group === true) {\n visit(entry.config as ProjectFacts['plugins'], realm);\n continue;\n }\n if (entry.name.startsWith('cordis:') || realm === 'build') continue;\n const current = modules.get(entry.name);\n if (current !== undefined && current.realm !== realm) {\n throw new Error(`plugin module ${entry.name} is assigned to multiple realms`);\n }\n modules.set(entry.name, { name: entry.name, realm });\n }\n };\n visit(facts.plugins);\n return [...modules.values()];\n}\n\nfunction catalogImport(facts: ProjectFacts, generated: string, name: string): string {\n const specifier = name.startsWith('.')\n ? moduleSpecifier(generated, resolve(facts.root, name))\n : name;\n return `() => import(${JSON.stringify(specifier)})`;\n}\n\ntype JitiLoader = (id: string) => unknown;\ntype JitiFactory = (filename: string, options: { readonly esmResolve: boolean }) => JitiLoader;\n\nfunction projectImporters(facts: ProjectFacts): readonly Importer[] {\n const specs = facts.assetImporters ?? [];\n if (specs.length === 0) return [];\n const createJiti = hostRequire('jiti') as JitiFactory;\n const load = createJiti(resolve(facts.root, 'package.json'), { esmResolve: true });\n return specs.map((spec) => {\n const separator = spec.lastIndexOf('#');\n const moduleSpecifier = separator < 0 ? spec : spec.slice(0, separator);\n const exportName = separator < 0 ? 'default' : spec.slice(separator + 1);\n const modulePath = moduleSpecifier.startsWith('.')\n ? resolve(facts.root, moduleSpecifier)\n : moduleSpecifier;\n const namespace = load(modulePath);\n if (namespace === null || typeof namespace !== 'object') {\n throw new Error(`project-asset-importer-module-invalid: ${spec}`);\n }\n const factory = (namespace as Record<string, unknown>)[exportName];\n if (typeof factory !== 'function') {\n throw new Error(`project-asset-importer-export-missing: ${spec}`);\n }\n const importer = factory();\n if (importer === null || typeof importer !== 'object') {\n throw new Error(`project-asset-importer-invalid: ${spec}`);\n }\n return importer as Importer;\n });\n}\n\nfunction hostSource(\n facts: ProjectFacts,\n bootstrapRoot: BootstrapRoot,\n canonicalEnvironmentGuid?: string,\n): string {\n const generated = resolve(facts.root, '.forgeax', 'generated');\n const plugins =\n bootstrapRoot === 'resource-bootstrap'\n ? []\n : [\n `webAudioPlugin()`,\n `audioPlugin()`,\n `skinningPlugin()`,\n ...(facts.physics === undefined\n ? []\n : [`physicsPlugin('${facts.physics === '2d' ? 'rapier-2d' : 'rapier-3d'}')`]),\n ];\n const bootstrapPlugin =\n facts.bootstrapEntry === undefined\n ? ''\n : `const bootstrapModule = await import(${JSON.stringify(\n moduleSpecifier(generated, resolve(facts.root, facts.bootstrapEntry)),\n )});\nif (typeof bootstrapModule.bootstrap !== 'function') {\n throw new Error('forgeax: project entry must export bootstrap(world, context)');\n}\nawait app.pluginContext.plugin({\n name: 'project-entry-bootstrap',\n inject: ['gameHost'],\n async apply(ctx) {\n if (ctx.gameHost === undefined) throw new Error('forgeax: gameHost unavailable');\n await bootstrapModule.bootstrap(ctx.gameHost.app.world, ctx.gameHost);\n },\n});`;\n return `import { forgeaxBundlerAdapter } from 'virtual:forgeax/bundler';\nimport { createApp, createToolPreviewHost, createToolPreviewRecipe, fitToolPreviewCameraToAabb, gameHostPlugin, replayToolPreviewCapture } from '@forgeax/engine/app';\nimport { createCatalogSource } from '@forgeax/engine/assets-runtime';\nimport {\n createRuntimeAssetImportTransport,\n runtimeBinding,\n} from 'virtual:forgeax/pack-runtime';\nimport { installCatalogLoader, projectPluginEntries } from '@forgeax/engine/plugin/loader';\nimport { audioPlugin } from '@forgeax/engine/audio';\nimport { webAudioPlugin } from '@forgeax/engine/audio-webaudio';\nimport { physicsPlugin } from '@forgeax/engine/physics';\nimport { skinningPlugin } from '@forgeax/engine/skinning';\nimport { createPrimitiveMesh } from '@forgeax/engine/geometry';\nimport { mat4 } from '@forgeax/engine/math';\nimport { CAMERA_PROJECTION_ORTHOGRAPHIC, Camera, DirectionalLight, Materials, MeshFilter, MeshRenderer, Skylight, SkyboxBackground, TONEMAP_NONE, TONEMAP_REINHARD_EXTENDED } from '@forgeax/engine/render';\nimport { Transform } from '@forgeax/engine/scene';\nimport { type SceneAsset } from '@forgeax/engine/types';\nimport { ParticleEffectPlayer, vfxGpuEffectContribution } from '@forgeax/engine/vfx';\nimport { createVfxRuntimeHost } from '@forgeax/engine/vfx-render';\n\nconst pluginCatalog = new Map([\n${catalogModules(facts)\n .map(\n ({ name, realm }) =>\n ` [${JSON.stringify(name)}, { realm: ${JSON.stringify(realm)}, load: ${catalogImport(facts, generated, name)} }],`,\n )\n .join('\\n')}\n]);\nconst pluginEntries = ${JSON.stringify(facts.plugins, null, 2)};\nconst bootstrapRoot = ${JSON.stringify(bootstrapRoot)};\nconst canonicalEnvironmentGuid = ${JSON.stringify(canonicalEnvironmentGuid ?? null)};\nconst resourceValue = new URLSearchParams(location.search).get('forgeax-resource-preview');\nconst resource = resourceValue === null ? undefined : JSON.parse(resourceValue);\nconst previewCameraEntities = new WeakMap();\nconst previewCameraTargets = new WeakMap();\nlet previewWorld;\nconst vfxRuntimeHost = resource?.kind === 'vfx'\n ? createVfxRuntimeHost({\n camera: {\n read(world) {\n const cameraEntity = previewCameraEntities.get(world);\n if (cameraEntity === undefined) return undefined;\n const transform = world.get(cameraEntity, Transform);\n const camera = world.get(cameraEntity, Camera);\n if (!transform.ok || !camera.ok) return undefined;\n const position = new Float32Array(transform.value.pos);\n const target = previewCameraTargets.get(world) ?? [0, 0, 0];\n return {\n position,\n right: new Float32Array([1, 0, 0]),\n up: new Float32Array([0, 1, 0]),\n viewProjection: mat4.computeViewProj(\n mat4.create(),\n position,\n target,\n [0, 1, 0],\n camera.value.fov,\n camera.value.aspect,\n camera.value.near,\n camera.value.far,\n ),\n };\n },\n },\n })\n : undefined;\n\nfunction previewVfxBounds(payload) {\n if (payload?.kind !== 'particle-effect' || payload.program?.emitters?.length === 0) return undefined;\n let minX = Infinity;\n let minY = Infinity;\n let minZ = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n let maxZ = -Infinity;\n for (const emitter of payload.program.emitters) {\n const bounds = emitter.bounds;\n if (bounds?.kind === 'sphere' && Array.isArray(bounds.center) && typeof bounds.radius === 'number') {\n const [x, y, z] = bounds.center;\n if (![x, y, z, bounds.radius].every((value) => typeof value === 'number' && Number.isFinite(value)) || bounds.radius < 0) return undefined;\n minX = Math.min(minX, x - bounds.radius);\n minY = Math.min(minY, y - bounds.radius);\n minZ = Math.min(minZ, z - bounds.radius);\n maxX = Math.max(maxX, x + bounds.radius);\n maxY = Math.max(maxY, y + bounds.radius);\n maxZ = Math.max(maxZ, z + bounds.radius);\n continue;\n }\n if (bounds?.kind === 'aabb' && Array.isArray(bounds.min) && Array.isArray(bounds.max)) {\n const [loX, loY, loZ] = bounds.min;\n const [hiX, hiY, hiZ] = bounds.max;\n if (![loX, loY, loZ, hiX, hiY, hiZ].every((value) => typeof value === 'number' && Number.isFinite(value))) return undefined;\n minX = Math.min(minX, loX);\n minY = Math.min(minY, loY);\n minZ = Math.min(minZ, loZ);\n maxX = Math.max(maxX, hiX);\n maxY = Math.max(maxY, hiY);\n maxZ = Math.max(maxZ, hiZ);\n continue;\n }\n return undefined;\n }\n if (![minX, minY, minZ, maxX, maxY, maxZ].every(Number.isFinite)) return undefined;\n const center = [(minX + maxX) / 2, (minY + maxY) / 2, (minZ + maxZ) / 2];\n const radius = Math.max(1, Math.hypot(maxX - minX, maxY - minY, maxZ - minZ));\n return { aabb: [minX, minY, minZ, maxX, maxY, maxZ], center, radius };\n}\n\nconst canvas = document.querySelector('#app');\nif (!(canvas instanceof HTMLCanvasElement)) throw new Error('forgeax: missing canvas');\nconst resizeCanvas = () => {\n const dpr = Math.min(window.devicePixelRatio || 1, 2);\n const width = Math.max(1, Math.round(canvas.clientWidth * dpr));\n const height = Math.max(1, Math.round(canvas.clientHeight * dpr));\n if (canvas.width !== width) canvas.width = width;\n if (canvas.height !== height) canvas.height = height;\n};\nconst resizeObserver = new ResizeObserver(resizeCanvas);\nresizeObserver.observe(canvas);\nresizeCanvas();\nconst runtimeScopeBinding = runtimeBinding;\nif (runtimeScopeBinding === undefined) {\n throw new Error('forgeax: Vite Pack runtime binding is required in the generated host');\n}\nconst assetCatalog = createCatalogSource({\n url: import.meta.env.DEV\n ? runtimeScopeBinding.catalogUrl\n : new URL('pack-index.json', document.baseURI).href,\n ...(import.meta.env.DEV ? { expectedScope: runtimeScopeBinding } : {}),\n});\nconst bundler = {\n ...forgeaxBundlerAdapter(),\n ...(import.meta.env.DEV\n ? { importTransport: createRuntimeAssetImportTransport(runtimeScopeBinding) }\n : {}),\n};\nconst assetPreparation = new WeakMap();\n\nfunction prepareAssetRegistry(assets) {\n const existing = assetPreparation.get(assets);\n if (existing !== undefined) return existing;\n const pending = (async () => {\n if (import.meta.env.DEV) {\n assets.configureRuntimeBinding(runtimeScopeBinding);\n } else {\n assets.configurePackIndex(new URL('pack-index.json', document.baseURI).href);\n }\n assets.setCatalogSource(assetCatalog);\n if (vfxRuntimeHost !== undefined) {\n assets.installDecoder(vfxGpuEffectContribution.kind, vfxGpuEffectContribution.decoder);\n }\n const catalog = await assets.enumerateCatalog();\n if (!catalog.ok) throw catalog.error;\n })();\n assetPreparation.set(assets, pending);\n return pending;\n}\n\nfunction previewStable(value) {\n if (value instanceof ArrayBuffer) return 'ArrayBuffer:' + JSON.stringify(Array.from(new Uint8Array(value)));\n if (ArrayBuffer.isView(value)) return value.constructor.name + ':' + JSON.stringify(Array.from(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)));\n if (Array.isArray(value)) return '[' + value.map(previewStable).join(',') + ']';\n if (value !== null && typeof value === 'object') {\n const record = value;\n return '{' + Object.keys(record).sort().map((key) => JSON.stringify(key) + ':' + previewStable(record[key])).join(',') + '}';\n }\n return JSON.stringify(value) ?? 'null';\n}\n\nasync function previewDigest(value) {\n const bytes = new TextEncoder().encode(previewStable(value));\n const digest = await crypto.subtle.digest('SHA-256', bytes);\n return 'sha256:' + Array.from(new Uint8Array(digest)).map((byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n\nasync function previewOwnerFacts(assets, resource, payload) {\n if (resource.kind === 'material') {\n const primaryPass = Array.isArray(payload.passes) ? payload.passes[0] : undefined;\n const program = primaryPass?.program?.module;\n const pass = primaryPass?.name;\n return {\n subjectDigest: await previewDigest(payload),\n bindingsDigest: await previewDigest(payload.passes),\n closureDigest: await previewDigest(payload.values ?? payload.passes),\n ...(typeof program === 'string' ? { program } : {}),\n ...(typeof pass === 'string' ? { pass } : {}),\n };\n }\n if (resource.kind === 'mesh') {\n return {\n subjectDigest: await previewDigest(payload),\n vertexDigest: await previewDigest(payload.vertices),\n indexDigest: await previewDigest(payload.indices ?? []),\n submeshDigest: await previewDigest(payload.submeshes),\n aabbDigest: await previewDigest(payload.aabb),\n };\n }\n if (resource.kind === 'texture') {\n const mipCount = typeof payload.mipLevelCount === 'number' ? payload.mipLevelCount : 1;\n const filter = 'linear';\n return {\n subjectDigest: await previewDigest(payload),\n boundDigest: await previewDigest({ width: payload.width, height: payload.height, format: payload.format }),\n uvDigest: await previewDigest({ offset: [0, 0], scale: [1, 1], rotation: 0 }),\n bindingDigest: await previewDigest({ format: payload.format, colorSpace: payload.colorSpace, filter, mipCount }),\n format: payload.format,\n colorSpace: payload.colorSpace,\n filter,\n mipCount,\n dimensions: [payload.width, payload.height],\n payloadClass: 'color',\n };\n }\n return undefined;\n}\n\nasync function prepareProject(app) {\nawait prepareAssetRegistry(app.assets);\npreviewWorld = app.world;\nconst assets = app.assets;\nlet canonicalEnvironment;\nif (resource !== undefined) {\n if (resource.kind !== 'texture') {\n if (canonicalEnvironmentGuid === null) throw new Error('canonical preview environment is unavailable');\n const environment = await assets.loadByGuid(assets.parseGuid(canonicalEnvironmentGuid));\n if (!environment.ok) throw environment.error;\n if (environment.value.kind !== 'equirect') {\n throw new Error(\\`canonical preview environment expected equirect, received \\${environment.value.kind}\\`);\n }\n if (environment.value.width <= 0 || environment.value.height <= 0 || environment.value.data.byteLength === 0) {\n throw new Error('canonical preview environment must provide decoded equirect pixels');\n }\n canonicalEnvironment = app.world.allocSharedRef('EquirectAsset', environment.value);\n }\n if (resource.kind === 'vfx') {\n if (vfxRuntimeHost === undefined) throw new Error('VFX preview host was not created');\n const attached = await vfxRuntimeHost.attachWorld({ world: app.world, assets });\n if (!attached.ok) throw attached.error;\n }\n const loaded = await assets.loadByGuid(assets.parseGuid(resource.guid));\n if (!loaded.ok) throw loaded.error;\n const payload = loaded.value;\n if (resource.kind === 'vfx' && payload.kind !== 'particle-effect') {\n throw new Error(\\`VFX preview expected ParticleEffectAsset, received \\${payload.kind}\\`);\n }\n const vfxBounds = resource.kind === 'vfx' ? previewVfxBounds(payload) : undefined;\n if (resource.kind === 'vfx' && vfxBounds === undefined) {\n throw new Error('VFX preview owner did not publish finite emitter bounds');\n }\n const meshMaterialHandles = resource.kind === 'mesh' && payload.kind === 'mesh'\n ? await Promise.all(payload.materialSlots.map(async (slot) => {\n if (slot.defaultMaterial === undefined) return 0;\n const material = await assets.loadByGuid(assets.parseGuid(slot.defaultMaterial));\n if (!material.ok) throw material.error;\n if (material.value.kind !== 'material') {\n throw new Error('mesh material slot resolved to a non-material asset');\n }\n return app.world.allocSharedRef('MaterialAsset', material.value);\n }))\n : undefined;\n const meshHandle = resource.kind === 'mesh' && payload.kind === 'mesh'\n ? app.world.allocSharedRef('MeshAsset', payload)\n : app.world.internSharedRef(\n 'MeshAsset',\n createPrimitiveMesh(resource.kind === 'texture' ? 'quad' : 'sphere').unwrap(),\n );\n const textureHandle = resource.kind === 'texture' && payload.kind === 'texture'\n ? app.world.allocSharedRef('TextureAsset', payload)\n : undefined;\n if (textureHandle !== undefined && payload.kind === 'texture') {\n const bytes = payload.data instanceof Uint8ClampedArray\n ? new Uint8Array(payload.data.buffer, payload.data.byteOffset, payload.data.byteLength)\n : payload.data;\n const uploaded = await app.renderer.store.uploadTexture(textureHandle, payload, {\n bytes,\n width: payload.width,\n height: payload.height,\n mime: 'image/png',\n colorSpace: payload.colorSpace,\n mipmap: payload.mipmap,\n });\n if (!uploaded.ok) throw uploaded.error;\n }\n const materialPayload = resource.kind === 'texture' && payload.kind === 'texture'\n ? Materials.unlit([1, 1, 1, 1], { baseColorTexture: textureHandle })\n : resource.kind === 'material' && payload.kind === 'material'\n ? payload\n : undefined;\n const materialHandle = materialPayload === undefined\n ? undefined\n : app.world.allocSharedRef('MaterialAsset', materialPayload);\n const materialBindings = resource.kind === 'mesh'\n ? meshMaterialHandles\n : materialHandle === undefined\n ? undefined\n : [materialHandle];\n const rawAabb = payload.kind === 'mesh' ? payload.aabb : undefined;\n const aabb = rawAabb !== undefined && (Array.isArray(rawAabb) || ArrayBuffer.isView(rawAabb)) && rawAabb.length === 6\n ? Array.from(rawAabb)\n : resource.kind === 'mesh' && payload.kind === 'mesh'\n ? (() => { throw new Error('mesh owner did not publish a finite AABB'); })()\n : [-1, -1, -1, 1, 1, 1];\n const meshFrame = resource.kind === 'mesh'\n ? fitToolPreviewCameraToAabb(aabb, { aspect: 1, fov: Math.PI / 4 })\n : undefined;\n const textureWidth = resource.kind === 'texture' && payload.kind === 'texture' && typeof payload.width === 'number'\n ? Math.max(1, payload.width)\n : 1;\n const textureHeight = resource.kind === 'texture' && payload.kind === 'texture' && typeof payload.height === 'number'\n ? Math.max(1, payload.height)\n : 1;\n const textureAspect = textureWidth / textureHeight;\n const textureScale = textureAspect >= 1\n ? [textureAspect, 1, 1]\n : [1, 1 / textureAspect, 1];\n const center = meshFrame?.center ?? vfxBounds?.center ?? [(aabb[0] + aabb[3]) / 2, (aabb[1] + aabb[4]) / 2, (aabb[2] + aabb[5]) / 2];\n const radius = meshFrame?.radius ?? vfxBounds?.radius ?? Math.max(1, Math.hypot(aabb[3] - aabb[0], aabb[4] - aabb[1], aabb[5] - aabb[2]));\n const texturePreview = resource.kind === 'texture';\n if (resource.kind === 'vfx') {\n const effect = app.world.allocSharedRef('ParticleEffectAsset', payload);\n app.world.spawn(\n { component: Transform, data: { pos: center } },\n { component: ParticleEffectPlayer, data: { effect, playing: true, seed: 0, timeScale: 1 } },\n );\n } else {\n app.world.spawn(\n { component: Transform, data: { pos: center, ...(texturePreview ? { scale: textureScale } : {}) } },\n { component: MeshFilter, data: { assetHandle: meshHandle } },\n { component: MeshRenderer, data: materialBindings === undefined ? {} : { materials: materialBindings } },\n );\n }\n const cameraData = texturePreview\n ? {\n fov: 0,\n aspect: 1,\n near: 0.01,\n far: 100,\n projection: CAMERA_PROJECTION_ORTHOGRAPHIC,\n left: -textureScale[0] * 0.6,\n right: textureScale[0] * 0.6,\n bottom: -textureScale[1] * 0.6,\n top: textureScale[1] * 0.6,\n tonemap: TONEMAP_NONE,\n antialias: 0,\n bloom: 0,\n clearColor: [0, 0, 0, 1],\n }\n : {\n fov: Math.PI / 4,\n aspect: 1,\n near: meshFrame?.near ?? 0.01,\n far: meshFrame?.far ?? radius * 8,\n tonemap: TONEMAP_REINHARD_EXTENDED,\n };\n const cameraPosition = texturePreview\n ? [0, 0, 5]\n : [center[0], center[1], center[2] + (meshFrame?.distance ?? radius * 2.5)];\n const cameraEntity = app.world.spawn({ component: Camera, data: cameraData }, { component: Transform, data: { pos: cameraPosition } }).unwrap();\n previewCameraEntities.set(app.world, cameraEntity);\n previewCameraTargets.set(app.world, center);\n if (!texturePreview) {\n app.world.spawn({ component: DirectionalLight, data: { direction: [-0.5, -1, -0.3], intensity: 2 } });\n if (canonicalEnvironment === undefined) throw new Error('canonical preview environment was not loaded');\n app.world.spawn({ component: Skylight, data: { equirect: canonicalEnvironment } });\n app.world.spawn({ component: SkyboxBackground, data: { equirect: canonicalEnvironment } });\n }\n const ownerFacts = await previewOwnerFacts(assets, resource, payload);\n const publishedAsset = resource.kind === 'mesh' && payload.kind === 'mesh' && payload.aabb !== undefined\n ? { ...payload, aabb: Array.from(payload.aabb) }\n : payload;\n return {\n kind: resource.kind,\n guid: resource.guid,\n asset: publishedAsset,\n ...(ownerFacts === undefined ? {} : { ownerFacts }),\n };\n}\nif (bootstrapRoot === 'resource-bootstrap') return;\nlet defaultScene;\nlet defaultSceneRoot;\nconst defaultSceneGuid = ${JSON.stringify(facts.defaultScene)};\nif (defaultSceneGuid !== undefined) {\n const loaded = await assets.loadByGuid<SceneAsset>(assets.parseGuid(defaultSceneGuid));\n if (!loaded.ok) throw loaded.error;\n defaultScene = loaded.value;\n const handle = app.world.allocSharedRef('SceneAsset', loaded.value);\n const instantiated = assets.instantiate<SceneAsset>(handle, app.world);\n if (!instantiated.ok) throw instantiated.error;\n defaultSceneRoot = instantiated.value;\n}\nconst uiRoot = document.querySelector('#game-ui');\nawait app.pluginContext.plugin(gameHostPlugin({\n app,\n assets,\n canvas,\n renderer: app.renderer,\n ...(defaultScene === undefined ? {} : { defaultScene }),\n ...(defaultSceneRoot === undefined ? {} : { defaultSceneRoot }),\n uiRoot: uiRoot instanceof HTMLElement ? uiRoot : document.body,\n setPointerLockAllowed: (allowed) => app.input?.setPointerLockAllowed?.(allowed),\n}));\nconst { loader: pluginLoader } = await installCatalogLoader(app.pluginContext, pluginCatalog, 'engine');\nawait pluginLoader.root.update(projectPluginEntries(pluginEntries, 'engine'));\nawait pluginLoader.await();\n}\n\nconst query = new URLSearchParams(location.search);\nconst recipeValue = query.get('forgeax-tool-recipe');\nconst snapshotValue = query.get('forgeax-tool-snapshot');\nconst runIdValue = query.get('forgeax-tool-run-id');\nif (query.has('forgeax-tool-replay')) {\n globalThis.__forgeaxToolReplayHost = {\n ready: true,\n async run(capture) {\n const result = await replayToolPreviewCapture(capture);\n return result.ok ? { ok: true, result: result.value } : { ok: false, error: result.error };\n },\n };\n} else if (recipeValue !== null) {\n const previewRecipe = createToolPreviewRecipe(JSON.parse(recipeValue));\n const host = await createToolPreviewHost({\n ...(runIdValue === null ? {} : { runId: runIdValue }),\n recipe: previewRecipe,\n snapshot: JSON.parse(snapshotValue ?? 'null'),\n ...(resource === undefined ? {} : { resource }),\n canvas,\n app: {\n plugins: [${plugins.join(', ')}],\n ...(vfxRuntimeHost === undefined ? {} : { features: [vfxRuntimeHost.feature] }),\n },\n bundler,\n prepare: prepareProject,\n collectResourceFacts(app, current) {\n if (current === undefined) return current;\n if (resource?.kind !== 'vfx') {\n if (resource?.kind === 'material' || resource?.kind === 'mesh' || resource?.kind === 'texture') {\n if (app.renderer.drawCalls <= 0) return current;\n if (resource.kind === 'mesh') {\n const asset = current.asset;\n const aabb = asset?.aabb;\n const submeshes = asset?.submeshes;\n const materialSlots = asset?.materialSlots;\n if (!Array.isArray(aabb) || aabb.length !== 6 || !Array.isArray(submeshes) || !Array.isArray(materialSlots)) {\n return current;\n }\n return {\n ...current,\n observation: {\n ...current.ownerFacts,\n aabb,\n submeshCount: submeshes.length,\n materialSlotCount: materialSlots.length,\n },\n };\n }\n return {\n ...current,\n observation: current.ownerFacts,\n };\n }\n return current;\n }\n if (vfxRuntimeHost === undefined) return current;\n const hostInspection = vfxRuntimeHost.inspect(app.world);\n const player = hostInspection?.players[0];\n const renderObservation = vfxRuntimeHost.feature.inspect();\n if (player === undefined || renderObservation.frameNumber < 0) {\n return current;\n }\n const bounds = previewVfxBounds(current.asset);\n if (bounds === undefined) return current;\n const emitterDigest = JSON.stringify(player.emitters.map(({ id, module, capacity }) => ({ id, module, capacity })));\n const sampleDigest = JSON.stringify(player.emitters.map(({ id, schedule }) => ({ id, schedule })));\n const boundsDigest = JSON.stringify(player.emitters.map(({ id, bounds: emitterBounds }) => ({ id, bounds: emitterBounds })));\n const computeDigest = player.programFingerprint;\n const indirectDigest = JSON.stringify(player.emitters.map(({ id, renderers }) => ({ id, renderers: renderers.map(({ kind, enabled }) => ({ kind, enabled })) })));\n return {\n ...current,\n observation: {\n subjectDigest: current.asset.programFingerprint,\n programFingerprint: player.programFingerprint,\n emitterDigest,\n sampleDigest,\n boundsDigest,\n computeDigest,\n indirectDigest,\n authoredBounds: bounds.aabb,\n seed: player.seed,\n fixedDelta: player.fixedDelta,\n timelineFrames: previewRecipe.frames,\n dispatches: renderObservation.dispatches,\n indirectDraws: renderObservation.indirectDraws,\n subjectOutputs: renderObservation.subjectOutputs,\n },\n };\n },\n onDispose: async () => {\n if (vfxRuntimeHost === undefined || previewWorld === undefined) return;\n const detached = await vfxRuntimeHost.detachWorld({ world: previewWorld });\n if (!detached.ok) throw detached.error;\n },\n executeAction(action) {\n return !globalThis.dispatchEvent(new CustomEvent('forgeax-tool-action', {\n detail: action,\n cancelable: true,\n }));\n },\n });\n if (!host.ok) {\n globalThis.__forgeaxToolHost = {\n ready: true,\n capture: async () => ({ ok: false, error: host.error }),\n run: async () => ({ ok: false, error: host.error }),\n dispose: async () => undefined,\n };\n } else {\n globalThis.__forgeaxToolHost = {\n ready: true,\n async capture() {\n const result = await host.value.capture();\n return result.ok ? { ok: true, result: result.value } : { ok: false, error: result.error };\n },\n async run() {\n const result = await host.value.run();\n return result.ok ? { ok: true, result: result.value } : { ok: false, error: result.error };\n },\n dispose: () => host.value.dispose(),\n };\n window.addEventListener('pagehide', () => void host.value.dispose(), { once: true });\n }\n} else {\n // WebDriver/headless browsers cannot satisfy the trusted-gesture requirement\n // for pointer lock. Keep the game running and let its keyboard fallback own\n // camera input; real browser users retain the normal click-to-lock path.\n const pointerLockAllowed =\n typeof navigator !== 'undefined' && navigator.webdriver === true ? () => false : undefined;\n const result = await createApp(\n canvas,\n {\n plugins: [${plugins.join(', ')}],\n ...(pointerLockAllowed === undefined ? {} : { pointerLockAllowed }),\n },\n bundler,\n );\n if (!result.ok) throw result.error;\n const app = result.value;\n await prepareProject(app);\n${bootstrapPlugin}\n app.start().unwrap();\n let disposed = false;\n const dispose = () => {\n if (disposed) return;\n disposed = true;\n resizeObserver.disconnect();\n void app.dispose();\n };\n window.addEventListener('pagehide', dispose);\n}\n`;\n}\n\nfunction escapeHtml(value: string): string {\n return value.replace(/[&<>\"']/g, (character) => {\n switch (character) {\n case '&':\n return '&amp;';\n case '<':\n return '&lt;';\n case '>':\n return '&gt;';\n case '\"':\n return '&quot;';\n case \"'\":\n return '&#39;';\n }\n return character;\n });\n}\n\nfunction htmlSource(title: string): string {\n return `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <link rel=\"icon\" href=\"data:,\" />\n <title>${escapeHtml(title)}</title>\n <style>\n html, body, #app-shell, #app { width: 100%; height: 100%; margin: 0; overflow: hidden; }\n body { background: #05070b; }\n #app { display: block; }\n #app-shell { position: relative; }\n #game-ui { position: absolute; inset: 0; overflow: hidden; pointer-events: none; }\n #game-ui > * { pointer-events: auto; }\n #forgeax-fatal { position: fixed; inset: 0; z-index: 2147483647; display: none; place-items: center; padding: 24px; background: #0b0d10; color: #e6e6e6; font: 15px/1.6 system-ui, sans-serif; text-align: center; white-space: pre-wrap; }\n </style>\n </head>\n <body>\n <div id=\"app-shell\"><canvas id=\"app\"></canvas><div id=\"game-ui\"></div></div><div id=\"forgeax-fatal\" role=\"alert\"></div>\n <script>\n (() => {\n const appendStructuredFailure = (value, prefix, depth, seen, lines) => {\n if (value === null || typeof value !== 'object' || depth > 3) return;\n if (seen.has(value)) {\n lines.push((prefix || 'cause') + ': [circular]');\n return;\n }\n seen.add(value);\n const record = value;\n const name = typeof record.name === 'string' && record.name.length > 0\n ? record.name\n : undefined;\n const code = typeof record.code === 'string' && record.code.length > 0\n ? record.code\n : undefined;\n const message = typeof record.message === 'string' && record.message.length > 0\n ? record.message\n : undefined;\n if (name !== undefined || code !== undefined || message !== undefined) {\n const identity = [name || 'Error', code].filter(Boolean).join(' ');\n lines.push((prefix ? prefix + ': ' : '') + identity + (message ? ': ' + message : ''));\n }\n for (const key of ['expected', 'hint', 'reason']) {\n if (typeof record[key] === 'string' && record[key].length > 0) {\n lines.push((prefix ? prefix + '.' : '') + key + ': ' + record[key]);\n }\n }\n for (const key of ['cause', 'detail', 'webgpuError', 'wgpuError', 'error']) {\n const nested = record[key];\n const nestedPrefix = (prefix ? prefix + '.' : '') + key;\n if (nested !== null && typeof nested === 'object') {\n appendStructuredFailure(nested, nestedPrefix, depth + 1, seen, lines);\n } else if (typeof nested === 'string' && nested.length > 0) {\n lines.push(nestedPrefix + ': ' + nested);\n }\n }\n };\n const formatStartupFailure = (reason) => {\n if (reason !== null && typeof reason === 'object') {\n const lines = [];\n appendStructuredFailure(reason, '', 0, new Set(), lines);\n if (lines.length > 0) return lines.join('\\\\n');\n try {\n return JSON.stringify(reason) || 'Unknown structured startup failure';\n } catch {\n return 'Unserializable structured startup failure';\n }\n }\n return String(reason ?? 'Unknown startup failure');\n };\n const show = (reason) => {\n const notice = document.querySelector('#forgeax-fatal');\n if (!(notice instanceof HTMLElement)) return;\n let message = formatStartupFailure(reason);\n if (/webgpu|adapter-unavailable|no usable (rendering )?backend/i.test(message)) {\n message += '\\\\n\\\\nRenderer diagnosis: ForgeaX supports browser WebGPU and a wgpu/WebGL2 fallback. This failure alone does not prove that WebGPU is unsupported; use the structured code, hint, and nested backend causes above.';\n }\n notice.textContent = 'ForgeaX game failed to start.\\\\n' + message;\n notice.style.display = 'grid';\n };\n window.addEventListener('error', (event) => show(event.error ?? event.message));\n window.addEventListener('unhandledrejection', (event) => show(event.reason));\n })();\n </script>\n <script type=\"module\" src=\"./main.ts\"></script>\n </body>\n</html>\n`;\n}\n\nexport async function createViteConfig(\n facts: ProjectFacts,\n command: 'serve' | 'build',\n base = '/',\n options: {\n readonly bootstrapRoot?: BootstrapRoot;\n readonly outDir?: string;\n readonly server?: ProjectPortOptions;\n } = {},\n): Promise<InlineConfig> {\n const bootstrapRoot = options.bootstrapRoot ?? 'project-bootstrap';\n // The canonical kit ships the engine's default environment (sky.hdr equirect).\n // Authored scenes (e.g. the default game template) reference it as a Skylight /\n // SkyboxBackground dependency, so a self-contained standalone build must catalog\n // it on the game path too — not only the tool-preview (resource-bootstrap) path.\n const canonicalKit = await resolveCanonicalKit();\n const generated = resolve(facts.root, '.forgeax', 'generated');\n await mkdir(generated, { recursive: true });\n const projectRoots = facts.assetRoots.map((root) => resolve(facts.root, root));\n const ignorePath =\n bootstrapRoot === 'resource-bootstrap'\n ? isResourcePreviewIgnoredPath\n : isProjectSourceIgnoredPath;\n const builtinPack = await prepareBuiltinPack(projectRoots, generated, ignorePath);\n await Promise.all([\n writeFile(resolve(generated, 'index.html'), htmlSource(facts.name)),\n writeFile(resolve(generated, 'main.ts'), hostSource(facts, bootstrapRoot, canonicalKit?.guid)),\n ]);\n const roots = [\n ...projectRoots,\n ...(builtinPack === undefined ? [] : [builtinPack]),\n ...(canonicalKit === undefined ? [] : [canonicalKit.root]),\n ];\n const importers = [...projectImporters(facts)];\n const runtimeBinding = createStandaloneRuntimeAssetBinding(facts.id);\n const engineWorkspaceResolver = await createEngineWorkspaceResolver(facts.root);\n const consumerAliases = await consumerEngineAliases(facts.root);\n const plugins: Plugin[] = [\n ...(engineWorkspaceResolver === undefined ? [] : [engineWorkspaceResolver]),\n forgeaxShader() as Plugin,\n pluginPack({\n roots,\n runtimeBinding,\n ddc: devKitDdcRoots(facts.root),\n refresh: command === 'serve' ? reloadAssetHost() : undefined,\n importers: [\n audioImporter,\n imageImporter,\n fbxImporter,\n gltfImporter,\n fontImporter,\n ...importers,\n ],\n cookers: [createMaterialPackCooker(roots), createParticleCodeNativeCookerFromRoots(roots)],\n ignorePath,\n }) as Plugin,\n ];\n return {\n root: generated,\n base,\n configFile: false,\n publicDir:\n facts.assetPublicDir === undefined ? false : resolve(facts.root, facts.assetPublicDir),\n plugins,\n resolve: {\n alias: consumerAliases,\n dedupe: ['@forgeax/engine'],\n },\n server: { ...options.server, fs: { allow: [facts.root, ...roots] } },\n build: {\n target: 'esnext',\n outDir: options.outDir ?? resolve(facts.root, 'dist'),\n emptyOutDir: true,\n rollupOptions: { input: resolve(generated, 'index.html') },\n },\n };\n}\n","import type { GameProjectPluginEntry } from '@forgeax/engine-project';\n\nexport type ForgeaXCommand =\n | 'new'\n | 'init'\n | 'doctor'\n | 'test'\n | 'dev'\n | 'build'\n | 'package'\n | 'capture'\n | 'engine.status'\n | 'engine.use-local'\n | 'engine.unlink'\n | 'engine.doctor'\n | 'serve'\n | 'preview'\n | 'plugin.install'\n | 'plugin.uninstall'\n | 'skill.install'\n | 'skill.verify'\n | 'sdk.install'\n | 'asset.add'\n | 'asset.verify'\n | 'asset.inspect'\n | 'asset.list'\n | 'shader.check'\n | 'list'\n | 'describe'\n | 'run'\n | 'exec';\n\nexport interface CommandError {\n readonly code: string;\n readonly expected: string;\n readonly hint: string;\n readonly detail: Readonly<Record<string, unknown>>;\n}\n\nexport type CommandResult<T> =\n | { readonly ok: true; readonly value: T }\n | { readonly ok: false; readonly error: CommandError };\n\nexport interface CommandEnvelope<T = unknown> {\n readonly schemaVersion: '1.0.0';\n readonly command: ForgeaXCommand;\n readonly ok: boolean;\n readonly value?: T;\n readonly error?: CommandError;\n}\n\nexport interface ProjectFacts {\n readonly root: string;\n readonly id: string;\n readonly name: string;\n readonly entry: string;\n readonly bootstrapEntry?: string;\n readonly plugins: readonly GameProjectPluginEntry[];\n readonly physics?: '2d' | '3d';\n readonly defaultScene?: string;\n readonly assetRoots: readonly string[];\n readonly assetImporters?: readonly string[];\n readonly assetPublicDir?: string;\n readonly packageJson: Readonly<Record<string, unknown>>;\n}\n\nexport interface ProjectCommandOptions {\n readonly root?: string;\n readonly json?: boolean;\n readonly port?: number;\n}\n\nexport interface ProjectPortOptions {\n readonly port: number;\n readonly strictPort: boolean;\n}\n\nexport function parseProjectPortOption(\n value: string | undefined,\n provided: boolean,\n): CommandResult<number | undefined> {\n if (!provided) return { ok: true, value: undefined };\n if (value !== undefined && /^(0|[1-9]\\d*)$/.test(value)) {\n const port = Number(value);\n if (Number.isSafeInteger(port) && port <= 65_535) return { ok: true, value: port };\n }\n return {\n ok: false,\n error: {\n code: 'cli-parse-error',\n expected: '--port to be 0 or an integer from 1 to 65535',\n hint: 'Omit --port for strict 5173, pass a positive port for a strict binding, or pass 0 for an OS-assigned port.',\n detail: { option: '--port', received: value ?? null },\n },\n };\n}\n\nexport function resolveProjectPort(port: number | undefined): ProjectPortOptions {\n return { port: port ?? 5173, strictPort: port !== 0 };\n}\n\nexport interface InitOptions extends ProjectCommandOptions {\n readonly dryRun?: boolean;\n readonly install?: boolean;\n}\n\nexport interface NewOptions extends ProjectCommandOptions {\n readonly dryRun?: boolean;\n readonly template?: string;\n}\n\nexport interface BuildOptions extends ProjectCommandOptions {\n readonly base?: string;\n readonly outDir?: string;\n}\n\nexport interface PackageOptions extends ProjectCommandOptions {\n readonly output?: string;\n}\n\nexport type CaptureBackend = 'auto' | 'software' | 'hardware';\n\nexport interface BrowserCaptureOptions extends ProjectCommandOptions {\n /** Prefer a rendering lane, or let the browser choose and report it. */\n readonly backend?: CaptureBackend;\n /** Backwards-compatible alias for `backend: 'software'`. */\n readonly software?: boolean;\n readonly output?: string;\n readonly browser?: string;\n readonly width?: number;\n readonly height?: number;\n readonly waitMs?: number;\n readonly requireUi?: boolean;\n readonly deterministic?: boolean;\n readonly headless?: boolean;\n}\n\n/** @deprecated Use BrowserCaptureOptions with `backend: 'software'`. */\nexport interface SoftwareCaptureOptions extends BrowserCaptureOptions {\n readonly software: true;\n readonly backend?: 'software';\n}\n\nexport interface AssetAddOptions extends ProjectCommandOptions {\n readonly path: string;\n readonly dryRun?: boolean;\n}\n\nexport interface AssetInspectOptions extends ProjectCommandOptions {\n readonly subject: string;\n}\n\nexport interface ShaderCheckOptions extends ProjectCommandOptions {\n readonly path?: string;\n}\n\nexport interface OperationCommandOptions extends ProjectCommandOptions {\n readonly id?: string;\n readonly args?: string;\n readonly input?: string;\n readonly program?: string;\n}\n\nexport interface PluginInstallOptions extends ProjectCommandOptions {\n readonly id: string;\n readonly module: string;\n readonly realm?: 'host' | 'engine' | 'build';\n readonly dependency?: string;\n readonly dryRun?: boolean;\n}\n\nexport interface PluginUninstallOptions extends ProjectCommandOptions {\n readonly id: string;\n readonly dependency?: string;\n readonly dryRun?: boolean;\n}\n","import { readdir, readFile, stat, writeFile } from 'node:fs/promises';\nimport { basename, extname, resolve } from 'node:path';\nimport { runCliGltf } from '@forgeax/engine-gltf/cli-gltf';\nimport { scanEntries } from '@forgeax/engine-pack/cli-asset';\nimport { AssetGuid } from '@forgeax/engine-pack/guid';\nimport { commandError, readProjectFacts } from './project.js';\nimport type {\n AssetAddOptions,\n AssetInspectOptions,\n CommandError,\n CommandResult,\n ProjectCommandOptions,\n} from './types.js';\n\nconst imageExtensions = new Set(['.png', '.jpg', '.jpeg', '.hdr']);\nconst gltfExtensions = new Set(['.gltf', '.glb']);\n\nfunction failure(error: CommandError): CommandResult<never> {\n return { ok: false, error };\n}\n\nasync function sourcesAt(path: string): Promise<string[]> {\n const info = await stat(path);\n if (info.isFile()) return [path];\n if (!info.isDirectory()) return [];\n const output: string[] = [];\n const entries = await readdir(path, { withFileTypes: true });\n for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {\n if (entry.name.startsWith('.') || entry.name === 'node_modules' || entry.name === 'dist')\n continue;\n const child = resolve(path, entry.name);\n if (entry.isDirectory()) output.push(...(await sourcesAt(child)));\n else if (entry.isFile() && !entry.name.endsWith('.meta.json')) output.push(child);\n }\n return output;\n}\n\nasync function addImage(sourcePath: string, dryRun: boolean): Promise<CommandResult<unknown>> {\n const metaPath = `${sourcePath}.meta.json`;\n const source = basename(sourcePath);\n let existing: unknown;\n try {\n existing = JSON.parse(await readFile(metaPath, 'utf8')) as unknown;\n } catch (cause) {\n if ((cause as NodeJS.ErrnoException).code !== 'ENOENT') {\n return failure({\n code: 'asset-meta-unreadable',\n expected: 'an absent or readable JSON sidecar',\n hint: 'Repair the existing sidecar before adding the source again.',\n detail: { source: sourcePath, metaPath },\n });\n }\n }\n if (existing !== undefined) {\n const value = existing as {\n importer?: unknown;\n source?: unknown;\n subAssets?: readonly { guid?: unknown; kind?: unknown }[];\n };\n const row = value.subAssets?.[0];\n if (\n value.importer !== 'image' ||\n value.source !== source ||\n value.subAssets?.length !== 1 ||\n typeof row?.guid !== 'string' ||\n row.kind !== 'texture'\n ) {\n return failure({\n code: 'asset-meta-conflict',\n expected: 'the existing sidecar to describe this image source and one texture identity',\n hint: 'Resolve the sidecar conflict explicitly; DevKit will not replace authored identity.',\n detail: { source: sourcePath, metaPath },\n });\n }\n return { ok: true, value: { source: sourcePath, metaPath, guid: row.guid, reused: true } };\n }\n const guid = AssetGuid.format(AssetGuid.random());\n const linear = extname(sourcePath).toLowerCase() === '.hdr';\n const meta = {\n schemaVersion: '1.0.0',\n kind: 'external-asset-package',\n importer: 'image',\n source,\n importSettings: {\n colorSpace: linear ? 'linear' : 'srgb',\n mipmap: true,\n addressMode: 'repeat',\n filterMode: 'linear',\n },\n subAssets: [{ guid, sourceIndex: 0, kind: 'texture', sourceKey: 'texture' }],\n } as const;\n if (!dryRun) await writeFile(metaPath, `${JSON.stringify(meta, null, 2)}\\n`, { flag: 'wx' });\n return { ok: true, value: { source: sourcePath, metaPath, guid, reused: false, dryRun } };\n}\n\nasync function addGltf(sourcePath: string, dryRun: boolean): Promise<CommandResult<unknown>> {\n if (dryRun) {\n const exists = await stat(`${sourcePath}.meta.json`)\n .then(() => true)\n .catch(() => false);\n return {\n ok: true,\n value: {\n source: sourcePath,\n metaPath: `${sourcePath}.meta.json`,\n reused: exists,\n dryRun: true,\n },\n };\n }\n const stdout: string[] = [];\n const stderr: string[] = [];\n const exitCode = await runCliGltf(['import', sourcePath], {\n stdoutWrite: (line) => stdout.push(line),\n stderrWrite: (line) => stderr.push(line),\n });\n if (exitCode !== 0) {\n try {\n return failure(JSON.parse(stderr.at(-1) ?? '') as CommandError);\n } catch {\n return failure({\n code: 'asset-add-failed',\n expected: 'the glTF producer to create or reuse a valid sidecar',\n hint: 'Inspect the glTF source and its external references.',\n detail: { source: sourcePath, diagnostic: stderr.join('\\n') },\n });\n }\n }\n return { ok: true, value: { source: sourcePath, metaPath: `${sourcePath}.meta.json` } };\n}\n\nexport async function assetAddCommand(options: AssetAddOptions): Promise<CommandResult<unknown>> {\n const facts = await readProjectFacts(options.root);\n if (!facts.ok) return facts;\n const target = resolve(facts.value.root, options.path);\n try {\n const sources = await sourcesAt(target);\n const supported = sources.filter((source) => {\n const extension = extname(source).toLowerCase();\n return imageExtensions.has(extension) || gltfExtensions.has(extension);\n });\n if (supported.length === 0) {\n return failure({\n code: 'source-package-importer-missing',\n expected: 'a .png, .jpg, .jpeg, .hdr, .gltf, or .glb source',\n hint: 'Use a supported built-in importer or add an explicit producer before adding this source.',\n detail: { target },\n });\n }\n const assets: unknown[] = [];\n for (const source of supported) {\n const result = imageExtensions.has(extname(source).toLowerCase())\n ? await addImage(source, options.dryRun === true)\n : await addGltf(source, options.dryRun === true);\n if (!result.ok) return result;\n assets.push(result.value);\n }\n return { ok: true, value: { root: facts.value.root, assets, dryRun: options.dryRun === true } };\n } catch (cause) {\n return failure(commandError(cause, 'asset-add-failed'));\n }\n}\n\nasync function entries(options: ProjectCommandOptions) {\n const facts = await readProjectFacts(options.root);\n if (!facts.ok) return facts;\n const stdout: string[] = [];\n const stderr: string[] = [];\n const result = await scanEntries(\n facts.value.assetRoots.map((root) => resolve(facts.value.root, root)),\n { stdoutWrite: (line) => stdout.push(line), stderrWrite: (line) => stderr.push(line) },\n );\n if (!result.ok) {\n try {\n return failure(JSON.parse(stderr.at(-1) ?? '') as CommandError);\n } catch {\n return failure({\n code: 'asset-authority-invalid',\n expected: 'all asset roots and sidecars to pass the pack scanner',\n hint: 'Repair the first invalid asset authority reported by the scanner.',\n detail: { diagnostic: stderr.join('\\n') },\n });\n }\n }\n return { ok: true as const, value: { facts: facts.value, entries: result.value } };\n}\n\nexport async function assetListCommand(\n options: ProjectCommandOptions = {},\n): Promise<CommandResult<unknown>> {\n const result = await entries(options);\n if (!result.ok) return result;\n return { ok: true, value: result.value.entries };\n}\n\nexport async function assetVerifyCommand(\n options: ProjectCommandOptions = {},\n): Promise<CommandResult<unknown>> {\n const result = await entries(options);\n if (!result.ok) return result;\n return {\n ok: true,\n value: { root: result.value.facts.root, assetCount: result.value.entries.length },\n };\n}\n\nexport async function assetInspectCommand(\n options: AssetInspectOptions,\n): Promise<CommandResult<unknown>> {\n const result = await entries(options);\n if (!result.ok) return result;\n const subject = options.subject.toLowerCase();\n const matches = result.value.entries.filter(\n (entry) => entry.guid.toLowerCase() === subject || entry.name?.toLowerCase() === subject,\n );\n if (matches.length !== 1) {\n return failure({\n code: matches.length === 0 ? 'asset-not-found' : 'asset-subject-ambiguous',\n expected: 'the GUID or name to resolve to exactly one asset',\n hint:\n matches.length === 0\n ? 'Run asset list and choose a known subject.'\n : 'Use the stable GUID.',\n detail: { subject: options.subject, matches },\n });\n }\n return { ok: true, value: matches[0] };\n}\n","{\n \"name\": \"@forgeax/engine-devkit\",\n \"version\": \"0.0.0\",\n \"private\": false,\n \"type\": \"module\",\n \"license\": \"Apache-2.0\",\n \"sideEffects\": false,\n \"description\": \"ForgeaX external game project CLI and build orchestration.\",\n \"bin\": {\n \"forgeax\": \"./dist/cli.mjs\"\n },\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.mjs\"\n },\n \"./cli\": \"./dist/cli.mjs\",\n \"./package.json\": \"./package.json\"\n },\n \"main\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"files\": [\n \"dist\",\n \"README.md\",\n \"LICENSE\"\n ],\n \"scripts\": {\n \"build\": \"tsup\",\n \"test\": \"vitest run\"\n },\n \"dependencies\": {\n \"@forgeax/engine-animation\": \"workspace:*\",\n \"@forgeax/engine-app\": \"workspace:*\",\n \"@forgeax/engine-assets-runtime\": \"workspace:*\",\n \"@forgeax/engine-audio\": \"workspace:*\",\n \"@forgeax/engine-audio-webaudio\": \"workspace:*\",\n \"@forgeax/engine-fbx\": \"workspace:*\",\n \"@forgeax/engine-font\": \"workspace:*\",\n \"@forgeax/engine-gltf\": \"workspace:*\",\n \"@forgeax/engine-image\": \"workspace:*\",\n \"@forgeax/engine-input\": \"workspace:*\",\n \"@forgeax/engine-pack\": \"workspace:*\",\n \"@forgeax/engine-physics\": \"workspace:*\",\n \"@forgeax/engine-plugin\": \"workspace:*\",\n \"@forgeax/engine-preview\": \"workspace:*\",\n \"@forgeax/engine-project\": \"workspace:*\",\n \"@forgeax/engine-rhi-debug\": \"workspace:*\",\n \"@forgeax/engine-rhi-null\": \"workspace:*\",\n \"@forgeax/engine-rhi-webgpu\": \"workspace:*\",\n \"@forgeax/engine-render\": \"workspace:*\",\n \"@forgeax/engine-render-graph\": \"workspace:*\",\n \"@forgeax/engine-runtime\": \"workspace:*\",\n \"@forgeax/engine-scene\": \"workspace:*\",\n \"@forgeax/engine-shader-compiler\": \"workspace:*\",\n \"@forgeax/engine-skinning\": \"workspace:*\",\n \"@forgeax/engine-tool-runtime\": \"workspace:*\",\n \"@forgeax/engine-types\": \"workspace:*\",\n \"@forgeax/engine-vfx-compiler\": \"workspace:*\",\n \"@forgeax/engine-vite-plugin-pack\": \"workspace:*\",\n \"@forgeax/engine-vite-plugin-shader\": \"workspace:*\",\n \"jiti\": \"1.21.7\",\n \"playwright\": \"1.60.0\",\n \"vite\": \"8.0.10\",\n \"vitest\": \"4.0.18\",\n \"webgpu\": \"^0.4.0\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^20.14.0\"\n },\n \"forgeax\": {\n \"metrics\": {\n \"bundle-size\": {\n \"enabled\": true,\n \"path\": \"dist/cli.mjs\",\n \"compression\": \"gzip\"\n },\n \"fps\": {\n \"enabled\": false,\n \"reason\": \"Node-only build orchestration; runtime FPS belongs to consumer games\"\n },\n \"bench\": {\n \"enabled\": false,\n \"reason\": \"CLI latency is not a runtime hot path\"\n },\n \"gate\": {\n \"enabled\": true,\n \"command\": \"pnpm test\",\n \"cwd\": \"packages/devkit\"\n },\n \"spike-report\": {\n \"enabled\": false,\n \"reason\": \"production DevKit package\"\n }\n }\n }\n}\n","import { writeFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport devkitPackage from '../package.json' with { type: 'json' };\nimport type { SdkManifest } from './sdk.js';\nimport type { CommandResult, InitOptions, ProjectFacts } from './types.js';\n\nconst STANDARD_SCRIPTS = {\n dev: 'forgeax dev',\n build: 'forgeax build',\n package: 'forgeax package',\n serve: 'forgeax serve',\n preview: 'forgeax preview',\n doctor: 'forgeax doctor',\n test: 'forgeax test',\n} as const;\n\nconst SDK_DEV_DEPENDENCIES = {\n '@types/node': '20.19.40',\n '@webgpu/types': '0.1.71',\n tsx: '4.23.1',\n typescript: '6.0.3',\n vitest: '4.0.18',\n} as const;\n\nexport interface InitPlan {\n readonly root: string;\n readonly version: string;\n readonly pnpmVersion?: string;\n readonly archiveBacked: boolean;\n readonly dependencyChanges: readonly {\n readonly section: string;\n readonly name: string;\n readonly from?: string;\n readonly to: string;\n }[];\n readonly scriptChanges: readonly { readonly name: string; readonly to: string }[];\n}\n\nexport function createInitPlan(\n facts: ProjectFacts,\n sdk?: Pick<SdkManifest, 'sdkVersion' | 'packages' | 'requirements'>,\n): CommandResult<InitPlan> {\n const manifest = structuredClone(facts.packageJson) as Record<string, unknown>;\n const packageVersions = new Map(sdk?.packages.map((entry) => [entry.name, entry.version]));\n const devkitVersion = packageVersions.get('@forgeax/engine-devkit') ?? devkitPackage.version;\n const dependencyChanges: InitPlan['dependencyChanges'][number][] = [];\n if (sdk !== undefined) {\n for (const section of ['dependencies', 'devDependencies'] as const) {\n const dependencies = manifest[section];\n if (dependencies === null || typeof dependencies !== 'object') continue;\n const unsupported = Object.keys(dependencies).filter(\n (name) => !name.startsWith('@forgeax/engine-') && !(name in SDK_DEV_DEPENDENCIES),\n );\n if (unsupported.length > 0) {\n return {\n ok: false,\n error: {\n code: 'sdk-external-dependency-unsupported',\n expected: 'archive-backed init dependencies to belong to the SDK closure',\n hint: 'Remove the external dependency or use a network-backed package workflow explicitly.',\n detail: { root: facts.root, dependencies: unsupported.sort() },\n },\n };\n }\n }\n }\n for (const section of ['dependencies', 'devDependencies'] as const) {\n const dependencies = manifest[section];\n if (dependencies === null || typeof dependencies !== 'object') continue;\n for (const [name, value] of Object.entries(dependencies)) {\n if (\n name.startsWith('@forgeax/engine-') &&\n typeof value === 'string' &&\n value.startsWith('workspace:')\n ) {\n const version = packageVersions.get(name) ?? devkitVersion;\n dependencyChanges.push({ section, name, from: value, to: version });\n }\n }\n }\n if (sdk !== undefined) {\n const existingEngineNames = new Set(\n ['dependencies', 'devDependencies'].flatMap((section) => {\n const value = manifest[section];\n return value !== null && typeof value === 'object'\n ? Object.keys(value).filter((name) => name.startsWith('@forgeax/engine-'))\n : [];\n }),\n );\n for (const entry of sdk.packages) {\n if (entry.name === '@forgeax/engine-devkit' || existingEngineNames.has(entry.name)) continue;\n dependencyChanges.push({\n section: 'dependencies',\n name: entry.name,\n to: entry.version,\n });\n }\n const devDependencies =\n manifest.devDependencies !== null && typeof manifest.devDependencies === 'object'\n ? (manifest.devDependencies as Record<string, unknown>)\n : {};\n for (const [name, version] of Object.entries(SDK_DEV_DEPENDENCIES)) {\n if (devDependencies[name] === version) continue;\n dependencyChanges.push({\n section: 'devDependencies',\n name,\n ...(typeof devDependencies[name] === 'string' ? { from: devDependencies[name] } : {}),\n to: version,\n });\n }\n }\n const scriptsValue = manifest.scripts;\n const scripts =\n scriptsValue !== null && typeof scriptsValue === 'object'\n ? (scriptsValue as Record<string, unknown>)\n : {};\n const scriptChanges: InitPlan['scriptChanges'][number][] = [];\n for (const [name, command] of Object.entries(STANDARD_SCRIPTS)) {\n const existing = scripts[name];\n if (existing === undefined) scriptChanges.push({ name, to: command });\n else if (existing !== command) {\n return {\n ok: false,\n error: {\n code: 'project-script-conflict',\n expected: `package.json#scripts.${name} to be absent or ${JSON.stringify(command)}`,\n hint: `Rename the existing ${name} script, then rerun forgeax init.`,\n detail: { root: facts.root, script: name, existing },\n },\n };\n }\n }\n const devDependencies = manifest.devDependencies;\n const existingDevkit =\n devDependencies !== null && typeof devDependencies === 'object'\n ? (devDependencies as Record<string, unknown>)['@forgeax/engine-devkit']\n : undefined;\n if (existingDevkit !== devkitVersion) {\n dependencyChanges.push({\n section: 'devDependencies',\n name: '@forgeax/engine-devkit',\n ...(typeof existingDevkit === 'string' ? { from: existingDevkit } : {}),\n to: devkitVersion,\n });\n }\n return {\n ok: true,\n value: {\n root: facts.root,\n version: sdk?.sdkVersion ?? devkitVersion,\n ...(sdk === undefined ? {} : { pnpmVersion: sdk.requirements.pnpm }),\n archiveBacked: sdk !== undefined,\n dependencyChanges,\n scriptChanges,\n },\n };\n}\n\nexport async function applyInitPlan(\n facts: ProjectFacts,\n plan: InitPlan,\n options: InitOptions,\n): Promise<CommandResult<InitPlan>> {\n if (options.dryRun === true) return { ok: true, value: plan };\n const manifest = structuredClone(facts.packageJson) as Record<string, unknown>;\n for (const change of plan.dependencyChanges) {\n const sectionValue = manifest[change.section];\n const section =\n sectionValue !== null && typeof sectionValue === 'object'\n ? (sectionValue as Record<string, unknown>)\n : {};\n section[change.name] = change.to;\n manifest[change.section] = section;\n }\n const scriptsValue = manifest.scripts;\n const scripts =\n scriptsValue !== null && typeof scriptsValue === 'object'\n ? (scriptsValue as Record<string, unknown>)\n : {};\n for (const change of plan.scriptChanges) scripts[change.name] = change.to;\n manifest.scripts = scripts;\n if (plan.archiveBacked) {\n if (plan.pnpmVersion === undefined) throw new Error('sdk-pnpm-version-missing');\n manifest.packageManager = `pnpm@${plan.pnpmVersion}`;\n }\n await writeFile(resolve(facts.root, 'package.json'), `${JSON.stringify(manifest, null, 2)}\\n`);\n return { ok: true, value: plan };\n}\n","import { access, readFile } from 'node:fs/promises';\nimport { dirname, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nexport interface SdkPackage {\n readonly name: string;\n readonly version: string;\n readonly root: string;\n readonly fileCount: number;\n readonly byteCount: number;\n}\n\nexport interface SdkTemplate {\n readonly id: string;\n readonly root: string;\n readonly default: boolean;\n}\n\nexport interface SdkSkill {\n readonly id: string;\n readonly root: string;\n readonly fileCount: number;\n readonly byteCount: number;\n}\n\nexport interface SdkSourceWasm {\n readonly package: string;\n readonly root: string;\n readonly files: readonly string[];\n}\n\nexport interface SdkResource {\n readonly id: string;\n readonly package: string;\n readonly sourceRoot: string;\n readonly packageRoot: string;\n readonly files: readonly string[];\n}\n\nexport interface SdkTemplateResource {\n readonly id: string;\n readonly root: string;\n readonly files: readonly string[];\n}\n\nexport interface SdkSource {\n readonly root: 'source/engine';\n readonly format: 'git-archive-public-snapshot';\n readonly excluded: readonly ['.gitmodules', 'forgeax-engine-assets'];\n readonly fileCount: number;\n readonly byteCount: number;\n readonly prebuiltWasm: readonly SdkSourceWasm[];\n}\n\nexport interface SdkManifest {\n readonly schemaVersion: '1.6.0';\n readonly sdkVersion: string;\n readonly engineCommit: string;\n readonly requirements: {\n readonly node: string;\n readonly pnpm: string;\n readonly pnpmStoreFormat: string;\n };\n readonly capabilities: readonly string[];\n readonly packages: readonly SdkPackage[];\n readonly templates: readonly SdkTemplate[];\n readonly skills: readonly SdkSkill[];\n readonly resources: readonly SdkResource[];\n readonly templateResources: readonly SdkTemplateResource[];\n readonly source: SdkSource;\n}\n\nexport interface SdkContext {\n readonly root: string;\n readonly manifest: SdkManifest;\n /**\n * The full ZIP carries an immutable offline store. The npm carrier is a\n * deliberately smaller online surface and omits it, so consumers fall back\n * to the registry when this path is absent.\n */\n readonly store?: string;\n readonly templates: ReadonlyMap<string, string>;\n readonly defaultTemplate: string;\n}\n\nasync function readable(path: string): Promise<boolean> {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function findSdkContext(): Promise<SdkContext | undefined> {\n const configured = process.env.FORGEAX_SDK_ROOT;\n let cursor = resolve(configured ?? dirname(fileURLToPath(import.meta.url)));\n for (;;) {\n const manifestPath = resolve(cursor, 'sdk-manifest.json');\n if (await readable(manifestPath)) {\n const manifest = JSON.parse(await readFile(manifestPath, 'utf8')) as SdkManifest;\n const templates = new Map(\n manifest.templates.map((template) => [template.id, resolve(cursor, template.root)]),\n );\n const defaultTemplate = manifest.templates.find((template) => template.default);\n if (defaultTemplate === undefined) throw new Error('sdk-default-template-missing');\n const store = resolve(cursor, 'store', 'pnpm');\n return {\n root: cursor,\n manifest,\n ...((await readable(store)) ? { store } : {}),\n templates,\n defaultTemplate: defaultTemplate.id,\n };\n }\n const parent = dirname(cursor);\n if (parent === cursor) return undefined;\n cursor = parent;\n }\n}\n","import { execFile } from 'node:child_process';\nimport { cp, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { resolve } from 'node:path';\nimport { promisify } from 'node:util';\nimport type { SdkContext } from './sdk.js';\nimport type { CommandResult } from './types.js';\n\nconst execFileAsync = promisify(execFile);\nconst SDK_INIT_PATH = ['.forgeax', 'sdk-init.json'] as const;\nconst SDK_INIT_SCHEMA_VERSION = '1.0.0' as const;\n\nexport interface SdkInitState {\n readonly schemaVersion: typeof SDK_INIT_SCHEMA_VERSION;\n readonly sdkVersion: string;\n readonly engineCommit: string;\n readonly pnpm: string;\n readonly node: string;\n readonly platform: NodeJS.Platform;\n readonly arch: string;\n}\n\nexport interface SdkInitReport extends SdkInitState {\n readonly root: string;\n readonly store: 'offline' | 'registry';\n readonly onboarding: AgentOnboarding;\n}\n\nexport interface AgentOnboarding {\n readonly read: readonly string[];\n readonly next: {\n readonly cwd: string;\n readonly argv: readonly string[];\n };\n}\n\nexport function agentOnboarding(sdk: SdkContext, projectRoot?: string): AgentOnboarding {\n const root = projectRoot ?? sdk.root;\n return {\n read: [\n resolve(root, 'AGENTS.md'),\n resolve(root, 'skills', 'forgeax-engine-sdk', 'SKILL.md'),\n resolve(root, 'skills', 'forgeax-engine-sdk', 'references', 'feature-catalog.md'),\n ],\n next:\n projectRoot === undefined\n ? {\n cwd: root,\n argv: ['node', './bin/forgeax.mjs', 'new', '../my-game'],\n }\n : { cwd: root, argv: ['pnpm', 'exec', 'forgeax', 'list', '--json'] },\n };\n}\n\nfunction sdkInitPath(sdk: SdkContext): string {\n return resolve(sdk.root, ...SDK_INIT_PATH);\n}\n\nfunction commandFailure(\n code: string,\n expected: string,\n hint: string,\n detail: Readonly<Record<string, unknown>> = {},\n): CommandResult<never> {\n return { ok: false, error: { code, expected, hint, detail } };\n}\n\nexport function sdkProjectInstallArgs(store: string | undefined): string[] {\n const common = [\n 'install',\n '--frozen-lockfile',\n '--ignore-scripts',\n '--config.pm-on-fail=ignore',\n '--side-effects-cache=true',\n '--child-concurrency=1',\n ];\n return store === undefined\n ? common\n : [...common, '--offline', '--config.trust-lockfile=true', '--store-dir', store];\n}\n\nfunction sdkBootstrapInstallArgs(store: string | undefined): string[] {\n const common = [\n 'install',\n '--frozen-lockfile',\n '--config.pm-on-fail=ignore',\n '--child-concurrency=1',\n '--side-effects-cache=true',\n ];\n return store === undefined\n ? common\n : [...common, '--offline', '--config.trust-lockfile=true', '--store-dir', store];\n}\n\nfunction supportedPnpm(version: string): boolean {\n const [major = 0, minor = 0] = version.split('.').map(Number);\n return major === 11 && minor >= 7;\n}\n\nasync function currentPnpm(): Promise<CommandResult<string>> {\n try {\n const result = await execFileAsync('pnpm', ['--version'], { maxBuffer: 1024 * 1024 });\n const version = result.stdout.trim();\n if (version.length === 0) throw new Error('pnpm returned an empty version');\n return { ok: true, value: version };\n } catch (cause) {\n return commandFailure(\n 'pnpm-unavailable',\n 'pnpm 11.7.0 or newer in the pnpm 11 line to be available on PATH',\n 'Install or activate pnpm 11, then rerun forgeax init from the SDK root.',\n { reason: cause instanceof Error ? cause.message : String(cause) },\n );\n }\n}\n\nfunction matchesState(sdk: SdkContext, state: unknown): state is SdkInitState {\n if (state === null || typeof state !== 'object' || Array.isArray(state)) return false;\n const value = state as Record<string, unknown>;\n return (\n value.schemaVersion === SDK_INIT_SCHEMA_VERSION &&\n value.sdkVersion === sdk.manifest.sdkVersion &&\n value.engineCommit === sdk.manifest.engineCommit &&\n typeof value.pnpm === 'string' &&\n supportedPnpm(value.pnpm) &&\n value.node === process.versions.node &&\n value.platform === process.platform &&\n value.arch === process.arch\n );\n}\n\nexport async function readSdkInitState(sdk: SdkContext): Promise<SdkInitState | undefined> {\n try {\n const value = JSON.parse(await readFile(sdkInitPath(sdk), 'utf8')) as unknown;\n return matchesState(sdk, value) ? value : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport async function requireSdkInitialization(\n sdk: SdkContext,\n): Promise<CommandResult<SdkInitState>> {\n const state = await readSdkInitState(sdk);\n if (state === undefined) {\n return commandFailure(\n 'sdk-not-initialized',\n 'the downloaded SDK to be initialized for this Node/pnpm/platform tuple',\n 'Run ./bin/forgeax init from the SDK root once, then run forgeax new outside the SDK.',\n {\n sdkRoot: sdk.root,\n sdkVersion: sdk.manifest.sdkVersion,\n pnpm: sdk.manifest.requirements.pnpm,\n node: process.versions.node,\n platform: process.platform,\n arch: process.arch,\n },\n );\n }\n return { ok: true, value: state };\n}\n\nasync function copyBootstrapInputs(sdk: SdkContext, root: string): Promise<void> {\n const template = sdk.templates.get(sdk.defaultTemplate);\n if (template === undefined) throw new Error('sdk-default-template-missing');\n for (const name of ['package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml'] as const) {\n await cp(resolve(template, name), resolve(root, name));\n }\n try {\n await cp(resolve(template, '.npmrc'), resolve(root, '.npmrc'));\n } catch (cause) {\n if (\n cause === null ||\n typeof cause !== 'object' ||\n !('code' in cause) ||\n cause.code !== 'ENOENT'\n ) {\n throw cause;\n }\n }\n}\n\nexport async function sdkInitCommand(\n sdk: SdkContext,\n options: { readonly dryRun?: boolean; readonly install?: boolean } = {},\n): Promise<CommandResult<SdkInitReport>> {\n const pnpmResult = await currentPnpm();\n if (!pnpmResult.ok) return pnpmResult;\n if (!supportedPnpm(pnpmResult.value)) {\n return commandFailure(\n 'pnpm-version-unsupported',\n 'pnpm >=11.7.0 <12',\n 'Activate pnpm 11.7.0 or newer in the pnpm 11 line, then rerun forgeax init.',\n { actual: pnpmResult.value, expected: sdk.manifest.requirements.pnpm },\n );\n }\n const state: SdkInitState = {\n schemaVersion: SDK_INIT_SCHEMA_VERSION,\n sdkVersion: sdk.manifest.sdkVersion,\n engineCommit: sdk.manifest.engineCommit,\n pnpm: pnpmResult.value,\n node: process.versions.node,\n platform: process.platform,\n arch: process.arch,\n };\n const report: SdkInitReport = {\n ...state,\n root: sdk.root,\n store: sdk.store === undefined ? 'registry' : 'offline',\n onboarding: agentOnboarding(sdk),\n };\n if (options.dryRun === true || options.install === false) return { ok: true, value: report };\n\n let staging: string | undefined;\n try {\n staging = await mkdtemp(resolve(tmpdir(), 'forgeax-sdk-init-'));\n await copyBootstrapInputs(sdk, staging);\n await execFileAsync('pnpm', sdkBootstrapInstallArgs(sdk.store), {\n cwd: staging,\n env: { ...process.env, CI: 'true' },\n maxBuffer: 16 * 1024 * 1024,\n });\n await mkdir(resolve(sdk.root, '.forgeax'), { recursive: true });\n await writeFile(sdkInitPath(sdk), `${JSON.stringify(state, null, 2)}\\n`);\n return { ok: true, value: report };\n } catch (cause) {\n return commandFailure(\n 'sdk-init-failed',\n 'the SDK dependency closure to install and build native packages successfully',\n 'Inspect the pnpm output, repair Node/pnpm or platform permissions, then rerun forgeax init from the SDK root.',\n { reason: cause instanceof Error ? cause.message : String(cause), sdkRoot: sdk.root },\n );\n } finally {\n if (staging !== undefined) await rm(staging, { recursive: true, force: true });\n }\n}\n","const UPDATE_MIGRATION_RISK =\n 'Install a newer SDK in a separate directory. Existing games remain pinned and are not migrated automatically; review release notes and migrate and test each game before changing its Engine version.';\n\nexport type SdkUpdateStatus =\n | {\n readonly status: 'available';\n readonly currentVersion: string;\n readonly latestVersion: string;\n readonly migrationRisk: typeof UPDATE_MIGRATION_RISK;\n }\n | {\n readonly status: 'current';\n readonly currentVersion: string;\n readonly latestVersion: string;\n }\n | {\n readonly status: 'skipped';\n readonly currentVersion: string;\n readonly reason: 'offline' | 'disabled';\n }\n | {\n readonly status: 'unavailable';\n readonly currentVersion: string;\n readonly reason: string;\n };\n\ninterface ParsedVersion {\n readonly core: readonly [string, string, string];\n readonly prerelease?: readonly string[];\n}\n\nfunction parseVersion(version: string): ParsedVersion | undefined {\n const match =\n /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-([0-9A-Za-z.-]+))?(?:\\+[0-9A-Za-z.-]+)?$/.exec(\n version,\n );\n if (match === null) return undefined;\n const major = match[1];\n const minor = match[2];\n const patch = match[3];\n if (major === undefined || minor === undefined || patch === undefined) return undefined;\n const prerelease = match[4]?.split('.');\n if (\n prerelease?.some(\n (identifier) =>\n identifier.length === 0 || (/^\\d+$/.test(identifier) && /^0\\d+/.test(identifier)),\n )\n ) {\n return undefined;\n }\n return {\n core: [major, minor, patch],\n ...(prerelease === undefined ? {} : { prerelease }),\n };\n}\n\nfunction compareNumericIdentifier(current: string, latest: string): number {\n if (current.length !== latest.length) return latest.length > current.length ? 1 : -1;\n if (current === latest) return 0;\n return latest > current ? 1 : -1;\n}\n\nfunction comparePrerelease(current: readonly string[], latest: readonly string[]): number {\n const length = Math.max(current.length, latest.length);\n for (let index = 0; index < length; index += 1) {\n const currentIdentifier = current[index];\n const latestIdentifier = latest[index];\n if (currentIdentifier === undefined) return 1;\n if (latestIdentifier === undefined) return -1;\n if (currentIdentifier === latestIdentifier) continue;\n const currentNumeric = /^\\d+$/.test(currentIdentifier);\n const latestNumeric = /^\\d+$/.test(latestIdentifier);\n if (currentNumeric && latestNumeric) {\n return compareNumericIdentifier(currentIdentifier, latestIdentifier);\n }\n if (currentNumeric !== latestNumeric) return latestNumeric ? -1 : 1;\n return latestIdentifier > currentIdentifier ? 1 : -1;\n }\n return 0;\n}\n\nexport function newerSdkVersion(currentVersion: string, latestVersion: string): boolean {\n const current = parseVersion(currentVersion);\n const latest = parseVersion(latestVersion);\n if (current === undefined || latest === undefined) return false;\n for (let index = 0; index < current.core.length; index += 1) {\n const precedence = compareNumericIdentifier(\n current.core[index] ?? '0',\n latest.core[index] ?? '0',\n );\n if (precedence !== 0) return precedence > 0;\n }\n if (current.prerelease !== undefined && latest.prerelease === undefined) return true;\n if (current.prerelease === undefined || latest.prerelease === undefined) return false;\n return comparePrerelease(current.prerelease, latest.prerelease) > 0;\n}\n\nfunction offline(): boolean {\n return ['1', 'true'].includes((process.env.npm_config_offline ?? '').toLowerCase());\n}\n\nexport async function checkSdkUpdate(currentVersion: string): Promise<SdkUpdateStatus> {\n if (process.env.FORGEAX_DISABLE_UPDATE_CHECK === '1') {\n return { status: 'skipped', currentVersion, reason: 'disabled' };\n }\n if (offline()) return { status: 'skipped', currentVersion, reason: 'offline' };\n try {\n const registry = process.env.npm_config_registry ?? 'https://registry.npmjs.org/';\n const response = await fetch(\n new URL('@forgeax%2Fengine-sdk', `${registry.replace(/\\/$/, '')}/`),\n {\n headers: { accept: 'application/vnd.npm.install-v1+json' },\n signal: AbortSignal.timeout(2_000),\n },\n );\n if (!response.ok) throw new Error(`registry-http-${response.status}`);\n const metadata = (await response.json()) as {\n readonly 'dist-tags'?: { readonly latest?: unknown };\n };\n const latestVersion = metadata['dist-tags']?.latest;\n if (typeof latestVersion !== 'string') throw new Error('registry-latest-version-missing');\n return newerSdkVersion(currentVersion, latestVersion)\n ? {\n status: 'available',\n currentVersion,\n latestVersion,\n migrationRisk: UPDATE_MIGRATION_RISK,\n }\n : { status: 'current', currentVersion, latestVersion };\n } catch (cause) {\n return {\n status: 'unavailable',\n currentVersion,\n reason: cause instanceof Error ? cause.message : String(cause),\n };\n }\n}\n","import {\n cp,\n lstat,\n mkdir,\n readdir,\n readFile,\n readlink,\n rm,\n rmdir,\n symlink,\n writeFile,\n} from 'node:fs/promises';\nimport { dirname, relative, resolve, sep } from 'node:path';\nimport { commandError, readProjectFacts } from './project.js';\nimport type { SdkContext, SdkSkill } from './sdk.js';\nimport type { CommandResult, ProjectCommandOptions } from './types.js';\n\nexport const PROJECT_SKILL_MOUNT_ROOTS = Object.freeze([\n '.codebuddy/skills',\n '.cursor/skills',\n '.agents/skills',\n '.claude/skills',\n '.workbuddy/skills',\n '.forgeax/skills',\n]);\nconst RETIRED_PROJECT_SKILL_MOUNT_ROOTS = new Set(['.claude-internal/skills']);\n\nconst MANIFEST_PATH = '.forgeax/skill-install-manifest.json';\nconst GITIGNORE_BEGIN = '# BEGIN FORGEAX MANAGED SKILLS';\nconst GITIGNORE_END = '# END FORGEAX MANAGED SKILLS';\n\ninterface InstalledSkill extends SdkSkill {}\n\ninterface SkillInstallManifest {\n readonly schemaVersion: '1.0.0';\n readonly sourceRoot: 'skills';\n readonly sdkVersion?: string;\n readonly engineCommit?: string;\n readonly skills: readonly InstalledSkill[];\n readonly mounts: readonly {\n readonly root: string;\n readonly skills: readonly string[];\n }[];\n}\n\nexport interface SkillInstallReport {\n readonly root: string;\n readonly sourceRoot: string;\n readonly manifest: string;\n readonly skills: readonly string[];\n readonly mountRoots: readonly string[];\n}\n\nfunction slash(path: string): string {\n return path.split(sep).join('/');\n}\n\nfunction contained(parent: string, child: string): boolean {\n const path = relative(parent, child);\n return path !== '' && path !== '..' && !path.startsWith(`..${sep}`) && !path.startsWith(sep);\n}\n\nasync function pathKind(path: string): Promise<'missing' | 'directory' | 'file' | 'symlink'> {\n try {\n const info = await lstat(path);\n if (info.isSymbolicLink()) return 'symlink';\n if (info.isDirectory()) return 'directory';\n return 'file';\n } catch (cause) {\n if (cause !== null && typeof cause === 'object' && 'code' in cause && cause.code === 'ENOENT') {\n return 'missing';\n }\n throw cause;\n }\n}\n\nasync function filesUnder(root: string, directory = root): Promise<readonly string[]> {\n const files: string[] = [];\n for (const name of (await readdir(directory)).sort()) {\n const path = resolve(directory, name);\n const info = await lstat(path);\n if (info.isSymbolicLink()) throw new Error(`skill-source-symlink: ${path}`);\n if (info.isDirectory()) files.push(...(await filesUnder(root, path)));\n else if (info.isFile()) files.push(path);\n }\n return files;\n}\n\nasync function skillRow(sourceRoot: string, id: string): Promise<InstalledSkill> {\n if (!/^[a-z0-9][a-z0-9-]*$/.test(id)) throw new Error(`skill-id-invalid: ${id}`);\n const root = resolve(sourceRoot, id);\n if ((await pathKind(root)) !== 'directory') throw new Error(`skill-source-invalid: ${id}`);\n if ((await pathKind(resolve(root, 'SKILL.md'))) !== 'file') {\n throw new Error(`skill-entry-missing: ${id}/SKILL.md`);\n }\n const files = await filesUnder(root);\n return {\n id,\n root: `skills/${id}`,\n fileCount: files.length,\n byteCount: (\n await Promise.all(files.map(async (path) => (await readFile(path)).byteLength))\n ).reduce((sum, bytes) => sum + bytes, 0),\n };\n}\n\nasync function discoverProjectSkills(root: string): Promise<readonly InstalledSkill[]> {\n const sourceRoot = resolve(root, 'skills');\n if ((await pathKind(sourceRoot)) !== 'directory') throw new Error('project-skills-missing');\n const entries = await readdir(sourceRoot, { withFileTypes: true });\n const ids = entries\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name)\n .sort();\n if (ids.length === 0) throw new Error('project-skills-empty');\n return Promise.all(ids.map((id) => skillRow(sourceRoot, id)));\n}\n\nasync function sameFiles(leftRoot: string, rightRoot: string): Promise<boolean> {\n const left = await filesUnder(leftRoot);\n const right = await filesUnder(rightRoot);\n const leftNames = left.map((path) => slash(relative(leftRoot, path)));\n const rightNames = right.map((path) => slash(relative(rightRoot, path)));\n if (JSON.stringify(leftNames) !== JSON.stringify(rightNames)) return false;\n for (let index = 0; index < left.length; index += 1) {\n const leftPath = left[index];\n const rightPath = right[index];\n if (leftPath === undefined || rightPath === undefined) return false;\n if (!(await readFile(leftPath)).equals(await readFile(rightPath))) return false;\n }\n return true;\n}\n\nexport async function copySdkSkills(sdk: SdkContext, projectRoot: string): Promise<void> {\n const targetSourceRoot = resolve(projectRoot, 'skills');\n const copies: { source: string; destination: string }[] = [];\n for (const skill of sdk.manifest.skills) {\n const source = resolve(sdk.root, skill.root);\n const destination = resolve(projectRoot, skill.root);\n if (!contained(sdk.root, source) || !contained(projectRoot, destination)) {\n throw new Error(`sdk-skill-path-invalid: ${skill.id}`);\n }\n const actual = await skillRow(resolve(sdk.root, 'skills'), skill.id);\n if (\n actual.root !== skill.root ||\n actual.fileCount !== skill.fileCount ||\n actual.byteCount !== skill.byteCount\n ) {\n throw new Error(`sdk-skill-manifest-drift: ${skill.id}`);\n }\n const kind = await pathKind(destination);\n if (kind === 'missing') {\n copies.push({ source, destination });\n } else if (kind !== 'directory' || !(await sameFiles(source, destination))) {\n throw new Error(`project-skill-source-conflict: ${skill.id}`);\n }\n }\n const created: string[] = [];\n try {\n await mkdir(targetSourceRoot, { recursive: true });\n for (const { source, destination } of copies) {\n await cp(source, destination, { recursive: true, errorOnExist: true, force: false });\n created.push(destination);\n }\n } catch (cause) {\n await Promise.all(created.map((path) => rm(path, { recursive: true, force: true })));\n throw cause;\n }\n}\n\nfunction expectedLinkTarget(projectRoot: string, mountRoot: string, id: string): string {\n const mountParent = resolve(projectRoot, mountRoot);\n const target = resolve(projectRoot, 'skills', id);\n return process.platform === 'win32' ? target : relative(mountParent, target);\n}\n\nasync function linkMatches(path: string, target: string): Promise<boolean> {\n if ((await pathKind(path)) !== 'symlink') return false;\n const actual = await readlink(path);\n return resolve(dirname(path), actual) === resolve(dirname(path), target);\n}\n\nfunction updateManagedGitignore(previous: string, skillIds: readonly string[]): string {\n const block = `${GITIGNORE_BEGIN}\\n${skillIds.map((id) => `/${id}`).join('\\n')}\\n${GITIGNORE_END}`;\n const begin = previous.indexOf(GITIGNORE_BEGIN);\n const end = previous.indexOf(GITIGNORE_END);\n if (begin >= 0 && end >= begin) {\n const after = end + GITIGNORE_END.length;\n return `${previous.slice(0, begin)}${block}${previous.slice(after)}`.replace(/^\\n+/, '');\n }\n return previous.length === 0 ? `${block}\\n` : `${previous.replace(/\\s*$/, '')}\\n\\n${block}\\n`;\n}\n\nfunction removeManagedGitignore(previous: string): string {\n const begin = previous.indexOf(GITIGNORE_BEGIN);\n const end = previous.indexOf(GITIGNORE_END);\n if (begin < 0 || end < begin) return previous;\n const before = previous.slice(0, begin).trimEnd();\n const after = previous.slice(end + GITIGNORE_END.length).trimStart();\n const retained = [before, after].filter((part) => part.length > 0).join('\\n');\n return retained.length === 0 ? '' : `${retained}\\n`;\n}\n\nasync function removeEmptyDirectory(path: string): Promise<void> {\n try {\n await rmdir(path);\n } catch (cause) {\n if (\n cause !== null &&\n typeof cause === 'object' &&\n 'code' in cause &&\n (cause.code === 'ENOENT' || cause.code === 'ENOTEMPTY' || cause.code === 'EEXIST')\n ) {\n return;\n }\n throw cause;\n }\n}\n\nasync function readOptional(path: string): Promise<string | undefined> {\n try {\n return await readFile(path, 'utf8');\n } catch (cause) {\n if (cause !== null && typeof cause === 'object' && 'code' in cause && cause.code === 'ENOENT') {\n return undefined;\n }\n throw cause;\n }\n}\n\nasync function readInstallManifest(root: string): Promise<SkillInstallManifest | undefined> {\n const value = await readOptional(resolve(root, MANIFEST_PATH));\n return value === undefined ? undefined : (JSON.parse(value) as SkillInstallManifest);\n}\n\nexport async function installProjectSkills(\n root: string,\n provenance?: Pick<SdkContext['manifest'], 'sdkVersion' | 'engineCommit'>,\n): Promise<SkillInstallReport> {\n const projectRoot = resolve(root);\n const skills = await discoverProjectSkills(projectRoot);\n const ids = skills.map((skill) => skill.id);\n const priorManifest = await readInstallManifest(projectRoot);\n const desiredLinks = PROJECT_SKILL_MOUNT_ROOTS.flatMap((mountRoot) =>\n ids.map((id) => ({\n path: resolve(projectRoot, mountRoot, id),\n target: expectedLinkTarget(projectRoot, mountRoot, id),\n })),\n );\n const desiredPaths = new Set(desiredLinks.map((entry) => entry.path));\n const desiredMountRoots = new Set<string>(PROJECT_SKILL_MOUNT_ROOTS);\n const retiredMountRoots = (priorManifest?.mounts ?? [])\n .map((mount) => mount.root)\n .filter(\n (mountRoot) =>\n !desiredMountRoots.has(mountRoot) && RETIRED_PROJECT_SKILL_MOUNT_ROOTS.has(mountRoot),\n );\n const staleLinks = (priorManifest?.mounts ?? [])\n .flatMap((mount) =>\n mount.skills.map((id) => ({\n path: resolve(projectRoot, mount.root, id),\n target: expectedLinkTarget(projectRoot, mount.root, id),\n })),\n )\n .filter((entry) => !desiredPaths.has(entry.path));\n\n for (const entry of desiredLinks) {\n const kind = await pathKind(entry.path);\n if (kind !== 'missing' && !(await linkMatches(entry.path, entry.target))) {\n throw new Error(`skill-mount-conflict: ${slash(relative(projectRoot, entry.path))}`);\n }\n }\n for (const entry of staleLinks) {\n const kind = await pathKind(entry.path);\n if (kind !== 'missing' && !(await linkMatches(entry.path, entry.target))) {\n throw new Error(`skill-stale-mount-conflict: ${slash(relative(projectRoot, entry.path))}`);\n }\n }\n\n const ignoreSnapshots = new Map<string, string | undefined>();\n const createdLinks: string[] = [];\n const removedLinks: { path: string; target: string }[] = [];\n const manifestPath = resolve(projectRoot, MANIFEST_PATH);\n const priorManifestText = await readOptional(manifestPath);\n try {\n for (const entry of staleLinks) {\n if ((await pathKind(entry.path)) === 'symlink') {\n await rm(entry.path);\n removedLinks.push(entry);\n }\n }\n for (const mountRoot of retiredMountRoots) {\n const mountParent = resolve(projectRoot, mountRoot);\n const ignorePath = resolve(mountParent, '.gitignore');\n const previous = await readOptional(ignorePath);\n ignoreSnapshots.set(ignorePath, previous);\n if (previous !== undefined) {\n const retained = removeManagedGitignore(previous);\n if (retained.length === 0) await rm(ignorePath);\n else await writeFile(ignorePath, retained);\n }\n await removeEmptyDirectory(mountParent);\n await removeEmptyDirectory(dirname(mountParent));\n }\n for (const mountRoot of PROJECT_SKILL_MOUNT_ROOTS) {\n const mountParent = resolve(projectRoot, mountRoot);\n await mkdir(mountParent, { recursive: true });\n const ignorePath = resolve(mountParent, '.gitignore');\n const previous = await readOptional(ignorePath);\n ignoreSnapshots.set(ignorePath, previous);\n await writeFile(ignorePath, updateManagedGitignore(previous ?? '', ids));\n for (const id of ids) {\n const path = resolve(mountParent, id);\n if ((await pathKind(path)) === 'missing') {\n const target = expectedLinkTarget(projectRoot, mountRoot, id);\n await symlink(target, path, process.platform === 'win32' ? 'junction' : 'dir');\n createdLinks.push(path);\n }\n }\n }\n const sdkVersion = provenance?.sdkVersion ?? priorManifest?.sdkVersion;\n const engineCommit = provenance?.engineCommit ?? priorManifest?.engineCommit;\n const manifest: SkillInstallManifest = {\n schemaVersion: '1.0.0',\n sourceRoot: 'skills',\n ...(sdkVersion === undefined ? {} : { sdkVersion }),\n ...(engineCommit === undefined ? {} : { engineCommit }),\n skills,\n mounts: PROJECT_SKILL_MOUNT_ROOTS.map((mountRoot) => ({ root: mountRoot, skills: ids })),\n };\n await mkdir(dirname(manifestPath), { recursive: true });\n await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\\n`);\n } catch (cause) {\n await Promise.all(createdLinks.map((path) => rm(path, { force: true })));\n await Promise.all(\n removedLinks.map(async ({ path, target }) => {\n await mkdir(dirname(path), { recursive: true });\n await symlink(target, path, process.platform === 'win32' ? 'junction' : 'dir');\n }),\n );\n await Promise.all(\n [...ignoreSnapshots].map(async ([path, value]) => {\n if (value === undefined) await rm(path, { force: true });\n else {\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, value);\n }\n }),\n );\n if (priorManifestText === undefined) await rm(manifestPath, { force: true });\n else await writeFile(manifestPath, priorManifestText);\n throw cause;\n }\n return {\n root: projectRoot,\n sourceRoot: resolve(projectRoot, 'skills'),\n manifest: manifestPath,\n skills: ids,\n mountRoots: PROJECT_SKILL_MOUNT_ROOTS,\n };\n}\n\nexport async function verifyProjectSkills(root: string): Promise<SkillInstallReport> {\n const projectRoot = resolve(root);\n const skills = await discoverProjectSkills(projectRoot);\n const ids = skills.map((skill) => skill.id);\n const manifest = await readInstallManifest(projectRoot);\n if (manifest === undefined) throw new Error('skill-install-manifest-missing');\n if (\n manifest.schemaVersion !== '1.0.0' ||\n manifest.sourceRoot !== 'skills' ||\n JSON.stringify(manifest.skills) !== JSON.stringify(skills) ||\n JSON.stringify(manifest.mounts.map((mount) => mount.root)) !==\n JSON.stringify(PROJECT_SKILL_MOUNT_ROOTS)\n ) {\n throw new Error('skill-install-manifest-drift');\n }\n for (const mountRoot of PROJECT_SKILL_MOUNT_ROOTS) {\n const declared = manifest.mounts.find((mount) => mount.root === mountRoot);\n if (declared === undefined || JSON.stringify(declared.skills) !== JSON.stringify(ids)) {\n throw new Error(`skill-install-manifest-mount-drift: ${mountRoot}`);\n }\n const ignore = await readOptional(resolve(projectRoot, mountRoot, '.gitignore'));\n if (ignore === undefined || updateManagedGitignore(ignore, ids) !== ignore) {\n throw new Error(`skill-mount-gitignore-drift: ${mountRoot}`);\n }\n for (const id of ids) {\n const path = resolve(projectRoot, mountRoot, id);\n const target = expectedLinkTarget(projectRoot, mountRoot, id);\n if (!(await linkMatches(path, target))) {\n throw new Error(`skill-mount-drift: ${mountRoot}/${id}`);\n }\n }\n }\n return {\n root: projectRoot,\n sourceRoot: resolve(projectRoot, 'skills'),\n manifest: resolve(projectRoot, MANIFEST_PATH),\n skills: ids,\n mountRoots: PROJECT_SKILL_MOUNT_ROOTS,\n };\n}\n\nexport async function skillInstallCommand(\n options: ProjectCommandOptions = {},\n): Promise<CommandResult<SkillInstallReport>> {\n const facts = await readProjectFacts(options.root);\n if (!facts.ok) return facts;\n try {\n return { ok: true, value: await installProjectSkills(facts.value.root) };\n } catch (cause) {\n return { ok: false, error: commandError(cause, 'skill-install-failed') };\n }\n}\n\nexport async function skillVerifyCommand(\n options: ProjectCommandOptions = {},\n): Promise<CommandResult<SkillInstallReport>> {\n const facts = await readProjectFacts(options.root);\n if (!facts.ok) return facts;\n try {\n return { ok: true, value: await verifyProjectSkills(facts.value.root) };\n } catch (cause) {\n return { ok: false, error: commandError(cause, 'skill-verify-failed') };\n }\n}\n","import { execFile } from 'node:child_process';\nimport {\n copyFile,\n cp,\n mkdir,\n mkdtemp,\n readdir,\n readFile,\n realpath,\n rename,\n rm,\n writeFile,\n} from 'node:fs/promises';\nimport { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';\nimport { promisify } from 'node:util';\nimport { applyInitPlan, createInitPlan } from './init.js';\nimport { commandError, readProjectFacts } from './project.js';\nimport { findSdkContext } from './sdk.js';\nimport {\n agentOnboarding,\n requireSdkInitialization,\n sdkInitCommand,\n sdkProjectInstallArgs,\n} from './sdk-bootstrap.js';\nimport { checkSdkUpdate } from './sdk-update.js';\nimport { copySdkSkills, installProjectSkills } from './skill-install.js';\nimport type { CommandResult, InitOptions, NewOptions, ProjectCommandOptions } from './types.js';\n\nconst execFileAsync = promisify(execFile);\n\nfunction isMissingPathError(cause: unknown): boolean {\n return cause !== null && typeof cause === 'object' && 'code' in cause && cause.code === 'ENOENT';\n}\n\nasync function canonicalProspectivePath(path: string): Promise<string> {\n let cursor = resolve(path);\n const suffix: string[] = [];\n for (;;) {\n try {\n return resolve(await realpath(cursor), ...suffix.reverse());\n } catch (cause) {\n if (!isMissingPathError(cause)) throw cause;\n const parent = dirname(cursor);\n if (parent === cursor) throw cause;\n suffix.push(basename(cursor));\n cursor = parent;\n }\n }\n}\n\nasync function configureSdkStore(root: string, store: string | undefined): Promise<void> {\n if (store === undefined) return;\n const path = resolve(root, '.npmrc');\n let content = '';\n try {\n content = await readFile(path, 'utf8');\n } catch (cause) {\n if (!isMissingPathError(cause)) throw cause;\n }\n const lines = content\n .split(/\\r?\\n/)\n .filter((line) => line.trim().length > 0 && !/^\\s*store-dir\\s*=/.test(line));\n lines.push(`store-dir=${store}`);\n await writeFile(path, `${lines.join('\\n')}\\n`);\n}\n\nfunction containsOrEquals(parent: string, child: string): boolean {\n const path = relative(parent, child);\n return path === '' || (path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path));\n}\n\nexport interface DoctorReport {\n readonly root: string;\n readonly projectId: string;\n readonly node: string;\n readonly pnpm: string;\n readonly workspaceDependencies: readonly string[];\n}\n\nfunction nodeSupported(): boolean {\n const [major = 0, minor = 0] = process.versions.node.split('.').map(Number);\n return major > 22 || (major === 22 && minor >= 13);\n}\n\nfunction pnpmSupported(version: string): boolean {\n const [major = 0, minor = 0] = version.split('.').map(Number);\n return major === 11 && minor >= 7;\n}\n\nexport async function doctorCommand(\n options: ProjectCommandOptions = {},\n): Promise<CommandResult<DoctorReport>> {\n const facts = await readProjectFacts(options.root);\n if (!facts.ok) return facts;\n let pnpm: string;\n try {\n pnpm = (await execFileAsync('pnpm', ['--version'], { cwd: facts.value.root })).stdout.trim();\n } catch (cause) {\n return {\n ok: false,\n error: {\n code: 'pnpm-unavailable',\n expected: 'pnpm to be available on PATH',\n hint: 'Install the SDK-supported pnpm version and retry.',\n detail: { reason: cause instanceof Error ? cause.message : String(cause) },\n },\n };\n }\n if (!nodeSupported()) {\n return {\n ok: false,\n error: {\n code: 'node-version-unsupported',\n expected: 'Node.js >=22.13.0',\n hint: 'Select a supported Node.js installation and retry.',\n detail: { actual: process.versions.node },\n },\n };\n }\n if (!pnpmSupported(pnpm)) {\n return {\n ok: false,\n error: {\n code: 'pnpm-version-unsupported',\n expected: 'pnpm >=11.7.0 <12',\n hint: 'Enable the packageManager-declared pnpm version with Corepack and retry.',\n detail: { actual: pnpm },\n },\n };\n }\n const workspaceDependencies: string[] = [];\n for (const section of ['dependencies', 'devDependencies']) {\n const value = facts.value.packageJson[section];\n if (value === null || typeof value !== 'object') continue;\n for (const [name, version] of Object.entries(value)) {\n if (\n typeof version === 'string' &&\n (version.startsWith('workspace:') || version.startsWith('file:'))\n ) {\n workspaceDependencies.push(name);\n }\n }\n }\n if (workspaceDependencies.length > 0) {\n return {\n ok: false,\n error: {\n code: 'project-local-dependency',\n expected: 'all external project dependencies to use SDK-resolved exact versions',\n hint: 'Run forgeax init from the unpacked SDK and commit the resulting lockfile.',\n detail: { dependencies: workspaceDependencies.sort() },\n },\n };\n }\n return {\n ok: true,\n value: {\n root: facts.value.root,\n projectId: facts.value.id,\n node: process.versions.node,\n pnpm,\n workspaceDependencies,\n },\n };\n}\n\nexport async function initCommand(options: InitOptions = {}): Promise<CommandResult<unknown>> {\n try {\n const sdk = await findSdkContext();\n const root = await canonicalProspectivePath(options.root ?? process.cwd());\n if (sdk !== undefined && root === (await canonicalProspectivePath(sdk.root))) {\n return sdkInitCommand(sdk, options);\n }\n const facts = await readProjectFacts(root);\n if (!facts.ok) return facts;\n const plan = createInitPlan(facts.value, sdk?.manifest);\n if (!plan.ok) return plan;\n if (sdk !== undefined && options.dryRun !== true) {\n const initialized = await requireSdkInitialization(sdk);\n if (!initialized.ok) return initialized;\n }\n const applied = await applyInitPlan(facts.value, plan.value, options);\n if (!applied.ok || options.dryRun === true) return applied;\n if (sdk !== undefined) {\n const template = sdk.templates.get(sdk.defaultTemplate);\n if (template === undefined) throw new Error('sdk-default-template-missing');\n await copyFile(\n resolve(template, 'pnpm-lock.yaml'),\n resolve(facts.value.root, 'pnpm-lock.yaml'),\n );\n await copyFile(\n resolve(template, 'pnpm-workspace.yaml'),\n resolve(facts.value.root, 'pnpm-workspace.yaml'),\n );\n try {\n await readFile(resolve(facts.value.root, '.npmrc'), 'utf8');\n } catch (cause) {\n if (!isMissingPathError(cause)) throw cause;\n try {\n await copyFile(resolve(template, '.npmrc'), resolve(facts.value.root, '.npmrc'));\n } catch (templateCause) {\n if (!isMissingPathError(templateCause)) throw templateCause;\n }\n }\n await copySdkSkills(sdk, facts.value.root);\n await installProjectSkills(facts.value.root, sdk.manifest);\n await configureSdkStore(\n facts.value.root,\n sdk.store === undefined ? undefined : await canonicalProspectivePath(sdk.store),\n );\n }\n if (options.install === false) return applied;\n const store =\n sdk === undefined || sdk.store === undefined\n ? undefined\n : await canonicalProspectivePath(sdk.store);\n const installArgs =\n sdk === undefined ? ['install', '--frozen-lockfile=false'] : sdkProjectInstallArgs(store);\n await execFileAsync('pnpm', installArgs, {\n cwd: facts.value.root,\n env: { ...process.env, CI: 'true' },\n maxBuffer: 16 * 1024 * 1024,\n });\n return applied;\n } catch (cause) {\n return { ok: false, error: commandError(cause, 'project-init-failed') };\n }\n}\n\nexport async function newCommand(options: NewOptions = {}): Promise<CommandResult<unknown>> {\n try {\n const sdk = await findSdkContext();\n if (sdk === undefined) {\n return {\n ok: false,\n error: {\n code: 'sdk-context-missing',\n expected: 'forgeax new to run from an unpacked ForgeaX SDK',\n hint: 'Run the SDK archive bin/forgeax.mjs entry or set FORGEAX_SDK_ROOT.',\n detail: {},\n },\n };\n }\n const root = resolve(options.root ?? process.cwd());\n if (\n containsOrEquals(\n await canonicalProspectivePath(sdk.root),\n await canonicalProspectivePath(root),\n )\n ) {\n return {\n ok: false,\n error: {\n code: 'project-target-inside-sdk',\n expected: 'forgeax new target to be outside the unpacked SDK root',\n hint: 'Choose a sibling directory or an absolute path outside the SDK.',\n detail: { root, sdkRoot: sdk.root },\n },\n };\n }\n const templateId = options.template ?? sdk.defaultTemplate;\n const template = sdk.templates.get(templateId);\n if (template === undefined) {\n return {\n ok: false,\n error: {\n code: 'sdk-template-not-found',\n expected: 'a template id declared by sdk-manifest.json',\n hint: `Choose one of: ${[...sdk.templates.keys()].sort().join(', ')}.`,\n detail: { template: templateId },\n },\n };\n }\n let targetExists = true;\n let entries: string[];\n try {\n entries = await readdir(root);\n } catch (cause) {\n if (!isMissingPathError(cause)) throw cause;\n targetExists = false;\n entries = [];\n }\n if (entries.length > 0) {\n return {\n ok: false,\n error: {\n code: 'project-target-not-empty',\n expected: 'forgeax new target to be absent or empty',\n hint: 'Choose an empty directory so existing files cannot be overwritten.',\n detail: { root },\n },\n };\n }\n if (options.dryRun === true) {\n return {\n ok: true,\n value: { root, template: templateId, sdkVersion: sdk.manifest.sdkVersion },\n };\n }\n const initialized = await requireSdkInitialization(sdk);\n if (!initialized.ok) return initialized;\n const parent = dirname(root);\n await mkdir(parent, { recursive: true });\n let staging: string | undefined = await mkdtemp(\n resolve(parent, `.${basename(root)}.forgeax-staging-`),\n );\n const committedNames: string[] = [];\n let committed = false;\n try {\n for (const name of await readdir(template)) {\n await cp(resolve(template, name), resolve(staging, name), {\n recursive: true,\n errorOnExist: true,\n force: false,\n });\n }\n await copySdkSkills(sdk, staging);\n await installProjectSkills(staging, sdk.manifest);\n const store = sdk.store === undefined ? undefined : await canonicalProspectivePath(sdk.store);\n await configureSdkStore(staging, store);\n if (!targetExists) {\n await rename(staging, root);\n staging = undefined;\n committedNames.push(...(await readdir(root)));\n } else {\n for (const name of await readdir(staging)) {\n await rename(resolve(staging, name), resolve(root, name));\n committedNames.push(name);\n }\n await rm(staging, { recursive: true, force: true });\n staging = undefined;\n }\n committed = true;\n // Install after the final rename so pnpm's virtual-store metadata keeps\n // the real project path. Installing inside staging would force a second\n // registry resolution when `pnpm exec` runs from the committed project.\n await execFileAsync('pnpm', sdkProjectInstallArgs(store), {\n cwd: root,\n env: { ...process.env, CI: 'true' },\n maxBuffer: 16 * 1024 * 1024,\n });\n const sdkUpdate = await checkSdkUpdate(sdk.manifest.sdkVersion);\n return {\n ok: true,\n value: {\n root,\n template: templateId,\n sdkVersion: sdk.manifest.sdkVersion,\n onboarding: agentOnboarding(sdk, root),\n sdkUpdate,\n },\n };\n } catch (cause) {\n if (staging !== undefined) await rm(staging, { recursive: true, force: true });\n if (committed) {\n if (!targetExists) {\n await rm(root, { recursive: true, force: true });\n return { ok: false, error: commandError(cause, 'project-create-failed') };\n }\n const cleanupNames = new Set([...committedNames, 'node_modules']);\n await Promise.all(\n [...cleanupNames].map((name) =>\n rm(resolve(root, name), { recursive: true, force: true }),\n ),\n );\n } else {\n await Promise.all(\n committedNames.map((name) => rm(resolve(root, name), { recursive: true, force: true })),\n );\n }\n return { ok: false, error: commandError(cause, 'project-create-failed') };\n }\n } catch (cause) {\n return { ok: false, error: commandError(cause, 'project-create-failed') };\n }\n}\n","import { execFile } from 'node:child_process';\nimport { readFile, rename, unlink, writeFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { promisify } from 'node:util';\nimport { type GameProjectPluginEntry, GameProjectSchema } from '@forgeax/engine-project';\nimport type { CommandResult, PluginInstallOptions, PluginUninstallOptions } from './types.js';\n\nconst execFileAsync = promisify(execFile);\n\nasync function readManifest(root: string): Promise<CommandResult<{ raw: string; value: unknown }>> {\n const path = resolve(root, 'forge.json');\n try {\n const raw = await readFile(path, 'utf8');\n return { ok: true, value: { raw, value: JSON.parse(raw) as unknown } };\n } catch (cause) {\n return {\n ok: false,\n error: {\n code: 'plugin-manifest-unreadable',\n expected: 'a readable forge.json',\n hint: 'Repair the project manifest before changing plugin installation state.',\n detail: { path, reason: cause instanceof Error ? cause.message : String(cause) },\n },\n };\n }\n}\n\nasync function writeManifest(root: string, value: unknown): Promise<void> {\n const path = resolve(root, 'forge.json');\n const temporary = resolve(root, `.forgeax-plugin-${process.pid}.tmp`);\n await writeFile(temporary, `${JSON.stringify(value, null, 2)}\\n`);\n try {\n await rename(temporary, path);\n } catch (cause) {\n await unlink(temporary).catch(() => undefined);\n throw cause;\n }\n}\n\nfunction allEntries(entries: readonly GameProjectPluginEntry[]): GameProjectPluginEntry[] {\n return entries.flatMap((entry) => [\n entry,\n ...(entry.group === true ? allEntries(entry.config as readonly GameProjectPluginEntry[]) : []),\n ]);\n}\n\nfunction withoutEntry(\n entries: readonly GameProjectPluginEntry[],\n id: string,\n): GameProjectPluginEntry[] {\n return entries.flatMap((entry) => {\n if (entry.id === id) return [];\n if (entry.group !== true) return [entry];\n return [\n {\n ...entry,\n config: withoutEntry(entry.config as readonly GameProjectPluginEntry[], id),\n },\n ];\n });\n}\n\nasync function mutateDependency(\n root: string,\n action: 'add' | 'remove',\n dependency: string | undefined,\n): Promise<void> {\n if (dependency === undefined) return;\n await execFileAsync('pnpm', [action, dependency], { cwd: root, maxBuffer: 16 * 1024 * 1024 });\n}\n\nexport async function pluginInstallCommand(\n options: PluginInstallOptions,\n): Promise<CommandResult<unknown>> {\n const root = resolve(options.root ?? process.cwd());\n const manifest = await readManifest(root);\n if (!manifest.ok) return manifest;\n const parsed = GameProjectSchema.safeParse(manifest.value.value);\n if (!parsed.success) {\n return {\n ok: false,\n error: {\n code: 'plugin-manifest-invalid',\n expected: 'forge.json to satisfy GameProjectSchema',\n hint: 'Repair the manifest before installing a plugin.',\n detail: { issues: parsed.error.issues },\n },\n };\n }\n const entries = parsed.data.plugins ?? [];\n if (allEntries(entries).some((entry) => entry.id === options.id)) {\n return {\n ok: false,\n error: {\n code: 'plugin-entry-id-conflict',\n expected: 'a project-unique plugin Entry id',\n hint: 'Choose a stable id not already present in forge.json#plugins.',\n detail: { id: options.id },\n },\n };\n }\n const next = {\n ...parsed.data,\n plugins: [\n ...entries,\n { id: options.id, name: options.module, realm: options.realm ?? 'engine' },\n ],\n };\n if (options.dryRun === true) return { ok: true, value: { root, manifest: next } };\n try {\n await writeManifest(root, next);\n await mutateDependency(root, 'add', options.dependency);\n return { ok: true, value: { root, id: options.id, module: options.module } };\n } catch (cause) {\n await writeFile(resolve(root, 'forge.json'), manifest.value.raw);\n return {\n ok: false,\n error: {\n code: 'plugin-install-failed',\n expected: 'dependency and forge.json Entry mutations to commit together',\n hint: 'Inspect the package-manager failure; the original forge.json was restored.',\n detail: { reason: cause instanceof Error ? cause.message : String(cause) },\n },\n };\n }\n}\n\nexport async function pluginUninstallCommand(\n options: PluginUninstallOptions,\n): Promise<CommandResult<unknown>> {\n const root = resolve(options.root ?? process.cwd());\n const manifest = await readManifest(root);\n if (!manifest.ok) return manifest;\n const parsed = GameProjectSchema.safeParse(manifest.value.value);\n if (!parsed.success) {\n return {\n ok: false,\n error: {\n code: 'plugin-manifest-invalid',\n expected: 'forge.json to satisfy GameProjectSchema',\n hint: 'Repair the manifest before uninstalling a plugin.',\n detail: { issues: parsed.error.issues },\n },\n };\n }\n const entries = parsed.data.plugins ?? [];\n if (!allEntries(entries).some((entry) => entry.id === options.id)) {\n return {\n ok: false,\n error: {\n code: 'plugin-entry-missing',\n expected: 'the plugin Entry id to exist',\n hint: 'Inspect forge.json#plugins and pass an installed Entry id.',\n detail: { id: options.id },\n },\n };\n }\n const next = { ...parsed.data, plugins: withoutEntry(entries, options.id) };\n if (options.dryRun === true) return { ok: true, value: { root, manifest: next } };\n try {\n await writeManifest(root, next);\n await mutateDependency(root, 'remove', options.dependency);\n return { ok: true, value: { root, id: options.id } };\n } catch (cause) {\n await writeFile(resolve(root, 'forge.json'), manifest.value.raw);\n return {\n ok: false,\n error: {\n code: 'plugin-uninstall-failed',\n expected: 'Entry and dependency removal to commit together',\n hint: 'Inspect the package-manager failure; the original forge.json was restored.',\n detail: { reason: cause instanceof Error ? cause.message : String(cause) },\n },\n };\n }\n}\n","import { readFile } from 'node:fs/promises';\nimport { createRhiDebugError, replayDeviceRequest, type V7Tape } from '@forgeax/engine-rhi-debug';\nimport { createShaderModule, rhi } from '@forgeax/engine-rhi-webgpu';\nimport { err } from '@forgeax/engine-types';\nimport type { ArtifactRef, RhiDebugOperationContext } from './operations.js';\n\nexport function createCliRhiDebugOperationContext(): RhiDebugOperationContext {\n return {\n captureFrame: async () =>\n err(\n createRhiDebugError('capture-unavailable', {\n stage: 'capture',\n cause:\n 'the standalone CLI has no live App capture provider; start a recorder-enabled live host and invoke its rhiCapture root',\n }),\n ),\n async readArtifact(artifact: ArtifactRef) {\n if (artifact.path === undefined) {\n return {\n ok: false as const,\n error: {\n code: 'artifact-path-missing',\n expected: 'ArtifactRef.path to identify a readable .rhitape file',\n hint: 'Pass the path returned by the capture host together with its digest.',\n detail: { digest: artifact.digest },\n },\n };\n }\n try {\n return { ok: true as const, value: new Uint8Array(await readFile(artifact.path)) };\n } catch (cause) {\n return {\n ok: false as const,\n error: {\n code: 'artifact-read-failed',\n expected: 'the ArtifactRef path to be readable',\n hint: 'Check the tape path and recapture if the artifact was removed.',\n detail: {\n path: artifact.path,\n reason: cause instanceof Error ? cause.message : String(cause),\n },\n },\n };\n }\n },\n async createReplayBackend(tape: V7Tape) {\n let createDawn: (options: readonly string[]) => GPU;\n let gpuGlobals: Record<string, unknown>;\n try {\n const dawn = await import('webgpu');\n createDawn = dawn.create as (options: readonly string[]) => GPU;\n gpuGlobals = dawn.globals as Record<string, unknown>;\n } catch (cause) {\n return {\n ok: false as const,\n error: {\n code: 'replay-backend-unavailable',\n expected: 'the Dawn WebGPU provider to load',\n hint: 'Install the DevKit runtime closure and retry rhi.inspect.',\n detail: {\n stage: 'provider',\n cause: cause instanceof Error ? cause.message : String(cause),\n },\n },\n };\n }\n Object.assign(globalThis, gpuGlobals);\n const gpu = createDawn([]);\n if (!('navigator' in globalThis) || globalThis.navigator === undefined) {\n Object.defineProperty(globalThis, 'navigator', {\n value: {},\n configurable: true,\n writable: true,\n });\n }\n Object.defineProperty(globalThis.navigator, 'gpu', {\n value: gpu,\n configurable: true,\n writable: true,\n });\n const adapter = await rhi.requestAdapter();\n if (!adapter.ok) {\n return {\n ok: false as const,\n error: {\n code: 'replay-backend-unavailable',\n expected: 'a fresh Dawn WebGPU adapter',\n hint: adapter.error.hint,\n detail: { stage: 'adapter', cause: adapter.error.hint },\n },\n };\n }\n const device = await adapter.value.requestDevice(\n replayDeviceRequest(tape, adapter.value.features, adapter.value.limits),\n );\n if (!device.ok) {\n return {\n ok: false as const,\n error: {\n code: 'replay-backend-unavailable',\n expected: 'a fresh Dawn WebGPU device satisfying the recorded tape',\n hint: device.error.hint,\n detail: { stage: 'device', cause: device.error.hint },\n },\n };\n }\n return { ok: true as const, value: { device: device.value, createShaderModule } };\n },\n };\n}\n","import {\n buildFrameModel,\n decodeTape,\n type FrameModel,\n type InspectField,\n openReplay,\n type ReplayBackend,\n type RhiDebugError,\n type V7Tape,\n type WorkInspection,\n} from '@forgeax/engine-rhi-debug';\nimport { ok, type Result } from '@forgeax/engine-types';\nimport type { CommandError, CommandResult } from '../types.js';\n\nexport const RHI_TAPE_ARTIFACT_KIND = 'rhi-tape' as const;\n\nexport interface ArtifactRef {\n readonly kind: typeof RHI_TAPE_ARTIFACT_KIND;\n readonly digest: string;\n readonly source: string;\n readonly path?: string;\n}\n\nexport interface CapturedRhiTape extends ArtifactRef {\n readonly bytes: Uint8Array;\n}\n\nexport interface RhiCaptureFrameValue {\n readonly kind: typeof RHI_TAPE_ARTIFACT_KIND;\n readonly digest: string;\n readonly bytes: Uint8Array;\n readonly source?: string;\n readonly path?: string;\n}\n\nexport interface RhiCaptureInput {\n readonly signal?: AbortSignal;\n}\n\nexport interface RhiSummaryInput {\n readonly artifact: ArtifactRef;\n}\n\nexport interface RhiInspectInput {\n readonly artifact: ArtifactRef;\n readonly workIndex: number;\n readonly fields?: readonly InspectField[];\n}\n\nexport type RhiDebugOperationName = 'rhi.capture' | 'rhi.summary' | 'rhi.inspect';\n\nexport type RhiDebugOperationInput = RhiCaptureInput | RhiSummaryInput | RhiInspectInput;\n\nexport interface RhiSummaryOutput {\n readonly artifact: ArtifactRef;\n readonly model: FrameModel;\n}\n\nexport interface RhiInspectOutput {\n readonly artifact: ArtifactRef;\n readonly inspection: WorkInspection;\n}\n\nexport type RhiDebugOperationOutput = ArtifactRef | RhiSummaryOutput | RhiInspectOutput;\n\nexport interface RhiDebugOperationContext {\n readonly captureFrame: (\n input?: RhiCaptureInput,\n ) => Promise<Result<CapturedRhiTape, RhiDebugError>>;\n readonly readArtifact: (artifact: ArtifactRef) => Promise<CommandResult<Uint8Array>>;\n readonly createReplayBackend?: (tape: V7Tape) => Promise<CommandResult<ReplayBackend>>;\n}\n\nexport interface RhiDebugOperationHost {\n readonly captureFrame: (\n input?: RhiCaptureInput,\n ) => Promise<Result<RhiCaptureFrameValue, RhiDebugError>>;\n readonly readArtifact: (artifact: ArtifactRef) => Promise<CommandResult<Uint8Array>>;\n readonly createReplayBackend?: (tape: V7Tape) => Promise<CommandResult<ReplayBackend>>;\n}\n\nexport function createRhiDebugOperationContext(\n host: RhiDebugOperationHost,\n): RhiDebugOperationContext {\n return {\n async captureFrame(input) {\n const captured = await host.captureFrame(input);\n if (!captured.ok) return captured;\n return ok({\n kind: RHI_TAPE_ARTIFACT_KIND,\n digest: captured.value.digest,\n source: captured.value.source ?? 'rhi.capture',\n ...(captured.value.path === undefined ? {} : { path: captured.value.path }),\n bytes: captured.value.bytes,\n });\n },\n readArtifact: host.readArtifact,\n ...(host.createReplayBackend === undefined\n ? {}\n : { createReplayBackend: host.createReplayBackend }),\n };\n}\n\nexport interface JsonSchema {\n readonly type: 'object' | 'string' | 'integer' | 'array';\n readonly properties?: Readonly<Record<string, JsonSchema>>;\n readonly required?: readonly string[];\n readonly items?: JsonSchema;\n readonly enum?: readonly string[];\n readonly minimum?: number;\n readonly additionalProperties?: boolean;\n}\n\nexport interface RhiDebugOperationDescriptor {\n readonly name: RhiDebugOperationName;\n readonly summary: string;\n readonly inputSchema: JsonSchema;\n readonly outputSchema: JsonSchema;\n readonly recoveryCodes: readonly string[];\n}\n\nexport interface RhiDebugOperationManifest {\n readonly schemaVersion: '1.0.0';\n readonly artifactRefSchema: JsonSchema;\n readonly operations: readonly RhiDebugOperationDescriptor[];\n}\n\nconst artifactRefSchema: JsonSchema = {\n type: 'object',\n properties: {\n kind: { type: 'string', enum: [RHI_TAPE_ARTIFACT_KIND] },\n digest: { type: 'string' },\n source: { type: 'string' },\n path: { type: 'string' },\n },\n required: ['kind', 'digest', 'source'],\n additionalProperties: false,\n};\n\nconst summaryOutputSchema: JsonSchema = {\n type: 'object',\n properties: {\n artifact: artifactRefSchema,\n model: { type: 'object', additionalProperties: true },\n },\n required: ['artifact', 'model'],\n additionalProperties: false,\n};\n\nconst inspectOutputSchema: JsonSchema = {\n type: 'object',\n properties: {\n artifact: artifactRefSchema,\n inspection: { type: 'object', additionalProperties: true },\n },\n required: ['artifact', 'inspection'],\n additionalProperties: false,\n};\n\nexport const RHI_DEBUG_OPERATION_MANIFEST: RhiDebugOperationManifest = {\n schemaVersion: '1.0.0',\n artifactRefSchema,\n operations: [\n {\n name: 'rhi.capture',\n summary: 'Capture the next frame and return one rhi-tape ArtifactRef.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n outputSchema: artifactRefSchema,\n recoveryCodes: [\n 'capture-unavailable',\n 'capture-busy',\n 'capture-snapshot-failed',\n 'capture-timeout',\n ],\n },\n {\n name: 'rhi.summary',\n summary: 'Strictly decode one ArtifactRef and return its CPU FrameModel.',\n inputSchema: {\n type: 'object',\n properties: { artifact: artifactRefSchema },\n required: ['artifact'],\n additionalProperties: false,\n },\n outputSchema: summaryOutputSchema,\n recoveryCodes: ['tape-invalid', 'tape-version-unsupported'],\n },\n {\n name: 'rhi.inspect',\n summary: 'Replay one ArtifactRef on a fresh backend and inspect a workIndex.',\n inputSchema: {\n type: 'object',\n properties: {\n artifact: artifactRefSchema,\n workIndex: { type: 'integer', minimum: 0 },\n fields: {\n type: 'array',\n items: { type: 'string', enum: ['bindings', 'pipeline', 'pixels'] },\n },\n },\n required: ['artifact', 'workIndex'],\n additionalProperties: false,\n },\n outputSchema: inspectOutputSchema,\n recoveryCodes: [\n 'tape-invalid',\n 'tape-version-unsupported',\n 'replay-capability-mismatch',\n 'replay-event-failed',\n 'replay-position-invalid',\n 'readback-failed',\n 'readback-unsupported',\n ],\n },\n ],\n};\n\nexport function discoverRhiDebugOperations(): readonly RhiDebugOperationDescriptor[] {\n return RHI_DEBUG_OPERATION_MANIFEST.operations;\n}\n\nexport function renderRhiDebugHelp(): string {\n return [\n 'forgeax run <operation>',\n ...discoverRhiDebugOperations().map((operation) => ` ${operation.name}: ${operation.summary}`),\n 'Usage:',\n ' forgeax run rhi.summary --artifact PATH --digest SHA256 --json',\n ' forgeax run rhi.inspect --artifact PATH --digest SHA256 --work-index N --fields pipeline,bindings,pixels --json',\n 'ArtifactRef schema:',\n JSON.stringify(RHI_DEBUG_OPERATION_MANIFEST.artifactRefSchema),\n ].join('\\n');\n}\n\nexport function recoverRhiDebugError(error: RhiDebugError): string {\n switch (error.code) {\n case 'capture-unavailable':\n case 'capture-busy':\n case 'capture-snapshot-failed':\n case 'capture-timeout':\n return `${error.hint}: ${error.detail?.cause ?? 'capture failed'}`;\n case 'tape-invalid':\n return `${error.hint}: ${error.detail?.cause ?? 'tape validation failed'}`;\n case 'tape-version-unsupported':\n return `${error.hint}: found ${error.detail?.foundVersion}, expected ${error.detail?.expectedVersion}`;\n case 'replay-capability-mismatch':\n return `${error.hint}: ${error.detail?.cause ?? 'capability mismatch'}`;\n case 'replay-event-failed':\n return `${error.hint}: event ${error.detail?.eventIndex} ${error.detail?.kind} at ${error.detail?.stage}`;\n case 'replay-position-invalid':\n return `${error.hint}: requested ${error.detail?.requested}, available ${error.detail?.available}`;\n case 'readback-failed':\n return `${error.hint}: ${error.detail?.cause ?? 'readback failed'}`;\n case 'readback-unsupported':\n return `${error.hint}: ${error.detail?.reason ?? 'readback is unsupported'}`;\n }\n}\n\nfunction coreError(error: RhiDebugError): CommandError {\n return {\n code: error.code,\n expected: error.expected,\n hint: recoverRhiDebugError(error),\n detail: error.detail === undefined ? {} : Object.fromEntries(Object.entries(error.detail)),\n };\n}\n\nfunction operationError(\n code: string,\n expected: string,\n hint: string,\n detail: Readonly<Record<string, unknown>> = {},\n): CommandResult<never> {\n return { ok: false, error: { code, expected, hint, detail } };\n}\n\nfunction validateArtifactRef(\n value: unknown,\n):\n | { readonly ok: true; readonly value: ArtifactRef }\n | { readonly ok: false; readonly error: CommandError } {\n if (value === null || typeof value !== 'object') {\n return operationError(\n 'artifact-ref-invalid',\n 'an ArtifactRef object',\n 'Pass the ArtifactRef returned by rhi.capture unchanged.',\n );\n }\n const candidate = value as Record<string, unknown>;\n if (candidate.kind !== RHI_TAPE_ARTIFACT_KIND) {\n return operationError(\n 'artifact-kind-invalid',\n `ArtifactRef.kind to equal ${RHI_TAPE_ARTIFACT_KIND}`,\n 'Capture a new RHI tape and pass its ArtifactRef unchanged.',\n { kind: candidate.kind ?? null },\n );\n }\n if (typeof candidate.digest !== 'string' || candidate.digest.length === 0) {\n return operationError(\n 'artifact-digest-invalid',\n 'ArtifactRef.digest to be a non-empty digest',\n 'Use the digest returned with the captured tape.',\n );\n }\n if (typeof candidate.source !== 'string' || candidate.source.length === 0) {\n return operationError(\n 'artifact-source-invalid',\n 'ArtifactRef.source to identify the producing operation',\n 'Use the complete ArtifactRef returned by rhi.capture.',\n );\n }\n return {\n ok: true,\n value: {\n kind: RHI_TAPE_ARTIFACT_KIND,\n digest: candidate.digest,\n source: candidate.source,\n ...(typeof candidate.path === 'string' ? { path: candidate.path } : {}),\n },\n };\n}\n\nasync function readTape(\n artifact: ArtifactRef,\n context: RhiDebugOperationContext,\n): Promise<CommandResult<Uint8Array>> {\n const validated = validateArtifactRef(artifact);\n if (!validated.ok) return validated;\n return context.readArtifact(validated.value);\n}\n\nexport function runRhiDebugOperation(\n name: 'rhi.capture',\n input: RhiCaptureInput,\n context: RhiDebugOperationContext,\n): Promise<CommandResult<ArtifactRef>>;\nexport function runRhiDebugOperation(\n name: 'rhi.summary',\n input: RhiSummaryInput,\n context: RhiDebugOperationContext,\n): Promise<CommandResult<RhiSummaryOutput>>;\nexport function runRhiDebugOperation(\n name: 'rhi.inspect',\n input: RhiInspectInput,\n context: RhiDebugOperationContext,\n): Promise<CommandResult<RhiInspectOutput>>;\nexport function runRhiDebugOperation(\n name: RhiDebugOperationName,\n input: RhiDebugOperationInput,\n context: RhiDebugOperationContext,\n): Promise<CommandResult<RhiDebugOperationOutput>>;\nexport async function runRhiDebugOperation(\n name: RhiDebugOperationName,\n input: RhiDebugOperationInput,\n context: RhiDebugOperationContext,\n): Promise<CommandResult<RhiDebugOperationOutput>> {\n switch (name) {\n case 'rhi.capture': {\n const capture = await context.captureFrame(input as RhiCaptureInput);\n if (!capture.ok) return { ok: false, error: coreError(capture.error) };\n const artifact = validateArtifactRef(capture.value);\n if (!artifact.ok) return artifact;\n return { ok: true, value: artifact.value };\n }\n case 'rhi.summary': {\n const summaryInput = input as RhiSummaryInput;\n const bytes = await readTape(summaryInput.artifact, context);\n if (!bytes.ok) return bytes;\n const decoded = decodeTape(bytes.value);\n if (!decoded.ok) return { ok: false, error: coreError(decoded.error) };\n const artifact = validateArtifactRef(summaryInput.artifact);\n if (!artifact.ok) return artifact;\n return {\n ok: true,\n value: { artifact: artifact.value, model: buildFrameModel(decoded.value) },\n };\n }\n case 'rhi.inspect': {\n const inspectInput = input as RhiInspectInput;\n if (!Number.isInteger(inspectInput.workIndex) || inspectInput.workIndex < 0) {\n return operationError(\n 'work-index-invalid',\n 'workIndex to be a non-negative integer',\n 'Choose workIndex from the FrameModel returned by rhi.summary.',\n { workIndex: inspectInput.workIndex },\n );\n }\n const bytes = await readTape(inspectInput.artifact, context);\n if (!bytes.ok) return bytes;\n const decoded = decodeTape(bytes.value);\n if (!decoded.ok) return { ok: false, error: coreError(decoded.error) };\n if (context.createReplayBackend === undefined) {\n return operationError(\n 'replay-backend-unavailable',\n 'a fresh ReplayBackend factory',\n 'Provide a fresh device and shader factory before running rhi.inspect.',\n );\n }\n const backend = await context.createReplayBackend(decoded.value);\n if (!backend.ok) return backend;\n const opened = await openReplay(decoded.value, backend.value);\n if (!opened.ok) return { ok: false, error: coreError(opened.error) };\n try {\n const inspection = await opened.value.inspectWork(\n inspectInput.workIndex,\n inspectInput.fields,\n );\n if (!inspection.ok) return { ok: false, error: coreError(inspection.error) };\n const artifact = validateArtifactRef(inspectInput.artifact);\n if (!artifact.ok) return artifact;\n return { ok: true, value: { artifact: artifact.value, inspection: inspection.value } };\n } finally {\n await opened.value.dispose();\n }\n }\n }\n}\n","import { execFile } from 'node:child_process';\nimport { cp, mkdir, mkdtemp, readdir, readFile, rename, rm } from 'node:fs/promises';\nimport { basename, dirname, resolve } from 'node:path';\nimport { promisify } from 'node:util';\nimport { commandError } from './project.js';\nimport type { CommandResult } from './types.js';\n\nconst execFileAsync = promisify(execFile);\n\nexport interface SdkInstallOptions {\n readonly root: string;\n readonly version?: string;\n}\n\nasync function packageVersion(): Promise<string> {\n const manifest = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));\n if (typeof manifest.version !== 'string' || manifest.version.length === 0) {\n throw new Error('sdk-installer-version-missing');\n }\n return manifest.version;\n}\n\nexport async function sdkInstallCommand(\n options: SdkInstallOptions,\n): Promise<CommandResult<unknown>> {\n const root = resolve(options.root);\n let targetExists = true;\n let entries: string[];\n try {\n entries = await readdir(root);\n } catch (cause) {\n if (\n cause === null ||\n typeof cause !== 'object' ||\n !('code' in cause) ||\n cause.code !== 'ENOENT'\n ) {\n return { ok: false, error: commandError(cause, 'sdk-install-failed') };\n }\n targetExists = false;\n entries = [];\n }\n if (entries.length > 0) {\n return {\n ok: false,\n error: {\n code: 'sdk-target-not-empty',\n expected: 'the SDK install target to be absent or empty',\n hint: 'Choose an empty versioned SDK directory so existing files cannot be overwritten.',\n detail: { root },\n },\n };\n }\n\n const version = options.version ?? (await packageVersion());\n const parent = dirname(root);\n await mkdir(parent, { recursive: true });\n let staging: string | undefined;\n let download: string | undefined;\n try {\n staging = await mkdtemp(resolve(parent, `.${basename(root)}.forgeax-sdk-staging-`));\n download = await mkdtemp(resolve(parent, `.${basename(root)}.forgeax-sdk-download-`));\n await execFileAsync(\n process.env.FORGEAX_NPM_CLIENT ?? 'npm',\n [\n 'install',\n '--prefix',\n download,\n '--ignore-scripts',\n '--no-package-lock',\n '--no-save',\n '--fund=false',\n '--audit=false',\n `@forgeax/engine-sdk@${version}`,\n ],\n { env: { ...process.env, CI: 'true' }, maxBuffer: 16 * 1024 * 1024 },\n );\n const carrier = resolve(download, 'node_modules', '@forgeax', 'engine-sdk', 'sdk');\n const manifest = JSON.parse(await readFile(resolve(carrier, 'sdk-manifest.json'), 'utf8'));\n if (manifest.sdkVersion !== version) throw new Error('sdk-carrier-version-mismatch');\n for (const name of await readdir(carrier)) {\n await cp(resolve(carrier, name), resolve(staging, name), {\n recursive: true,\n errorOnExist: true,\n force: false,\n });\n }\n if (!targetExists) {\n await rename(staging, root);\n staging = undefined;\n } else {\n for (const name of await readdir(staging)) {\n await rename(resolve(staging, name), resolve(root, name));\n }\n }\n return {\n ok: true,\n value: {\n root,\n sdkVersion: version,\n source: '@forgeax/engine-sdk',\n next: { cwd: root, argv: ['node', './bin/forgeax.mjs', 'init'] },\n },\n };\n } catch (cause) {\n return { ok: false, error: commandError(cause, 'sdk-install-failed') };\n } finally {\n if (staging !== undefined) await rm(staging, { recursive: true, force: true });\n if (download !== undefined) await rm(download, { recursive: true, force: true });\n }\n}\n","import { mkdtemp, readFile, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { resolve } from 'node:path';\nimport { build as viteBuild } from 'vite';\nimport { createViteConfig } from './host.js';\nimport { commandError, readProjectFacts } from './project.js';\nimport type { CommandResult, ShaderCheckOptions } from './types.js';\n\nexport async function shaderCheckCommand(\n options: ShaderCheckOptions = {},\n): Promise<CommandResult<unknown>> {\n const facts = await readProjectFacts(options.root);\n if (!facts.ok) return facts;\n const target = options.path === undefined ? undefined : resolve(facts.value.root, options.path);\n if (target !== undefined) {\n try {\n await readFile(target);\n } catch (cause) {\n return { ok: false, error: commandError(cause, 'shader-source-unreadable') };\n }\n }\n const temporary = await mkdtemp(resolve(tmpdir(), 'forgeax-shader-check-'));\n const previous = process.cwd();\n try {\n process.chdir(facts.value.root);\n const config = await createViteConfig(facts.value, 'build');\n await viteBuild({\n ...config,\n build: { ...config.build, outDir: temporary, emptyOutDir: true, write: true },\n });\n return { ok: true, value: { root: facts.value.root, path: target ?? null } };\n } catch (cause) {\n return { ok: false, error: commandError(cause, 'shader-check-failed') };\n } finally {\n process.chdir(previous);\n await rm(temporary, { recursive: true, force: true });\n }\n}\n","import { type ChildProcess, spawn } from 'node:child_process';\nimport { createHash, randomUUID } from 'node:crypto';\nimport { access, mkdir, writeFile } from 'node:fs/promises';\nimport { createServer as createNetServer } from 'node:net';\nimport { dirname, resolve } from 'node:path';\nimport { FORGEAX_FRAME_SUBMITTED_DATASET } from '@forgeax/engine-app';\nimport { parseImage } from '@forgeax/engine-image/parse-image';\nimport { type Browser, chromium, type Page } from 'playwright';\nimport type { ViteDevServer } from 'vite';\nimport { createViteConfig } from './host.js';\nimport { commandError, readProjectFacts } from './project.js';\nimport type {\n BrowserCaptureOptions,\n CaptureBackend,\n CommandError,\n CommandResult,\n SoftwareCaptureOptions,\n} from './types.js';\n\ninterface VirtualDisplay {\n readonly value?: string;\n close(): Promise<void>;\n}\n\nexport interface CapturePixelWitness {\n readonly width: number;\n readonly height: number;\n readonly sampledPixels: number;\n readonly lumaMin: number;\n readonly lumaMax: number;\n readonly lumaRange: number;\n readonly varyingPixels: number;\n readonly rendered: boolean;\n}\n\nexport interface SoftwareCaptureRuntimeWitness {\n readonly title: string;\n readonly canvas: { readonly width: number; readonly height: number } | null;\n readonly domUi: {\n readonly rootChildren: number;\n readonly openShadowRoots: number;\n readonly textWitness: string;\n };\n readonly adapter: Readonly<Record<string, unknown>> | null;\n readonly adapterError: string | null;\n readonly engineFrameId: number | null;\n readonly captureReady: string | null;\n readonly userAgent: string;\n}\n\nexport interface SoftwareCaptureRecord {\n readonly index: number;\n readonly checkpoint: string | null;\n readonly ok: boolean;\n readonly output: string;\n readonly digest: string;\n readonly pixels: CapturePixelWitness;\n readonly runtime: SoftwareCaptureRuntimeWitness;\n}\n\nexport interface SoftwareCaptureRunReport {\n readonly schemaVersion: '2.0.0';\n readonly runId: string;\n readonly ok: boolean;\n readonly mode: 'browser-compositor' | 'advanced-cpu-only-development';\n readonly root: string;\n readonly url: string;\n readonly report: string;\n readonly backendRequested: CaptureBackend;\n readonly backend: 'software' | 'hardware' | 'unknown';\n /** @deprecated Read `backendRequested` instead. */\n readonly softwareRequested: boolean;\n readonly deterministicRequested: boolean;\n readonly viewport: {\n readonly width: number;\n readonly height: number;\n readonly deviceScaleFactor: 1;\n readonly colorProfile: 'srgb';\n readonly colorScheme: 'light';\n readonly locale: 'en-US';\n readonly timezone: 'UTC';\n };\n readonly browser: { readonly version: string; readonly executable: string };\n readonly display: string | null;\n readonly lavapipeIcd: string | null;\n readonly captures: readonly SoftwareCaptureRecord[];\n readonly consoleErrors: readonly string[];\n readonly pageErrors: readonly string[];\n readonly closedAt?: string;\n readonly boundary: string;\n}\n\nexport interface SoftwareBrowserOpenOptions {\n /** `auto` preserves the host/browser lane; the other values are assertions. */\n readonly backend?: CaptureBackend;\n /** @deprecated Use `backend: 'software'`. */\n readonly software?: boolean;\n readonly browser?: string;\n readonly width?: number;\n readonly height?: number;\n readonly port?: number;\n readonly requireUi?: boolean;\n readonly deterministic?: boolean;\n readonly outputDir?: string;\n readonly report?: string;\n readonly runId?: string;\n readonly headless?: boolean;\n}\n\nexport interface SoftwareCaptureCheckpointOptions {\n readonly output?: string;\n readonly waitMs?: number;\n readonly requireUi?: boolean;\n}\n\nexport interface SoftwareBrowserSession {\n readonly page: Page;\n readonly url: string;\n readonly reportPath: string;\n capture(\n checkpoint?: string,\n options?: SoftwareCaptureCheckpointOptions,\n ): Promise<SoftwareCaptureRecord>;\n report(): SoftwareCaptureRunReport;\n close(): Promise<void>;\n}\n\nexport interface SoftwareBrowser {\n open(options: SoftwareBrowserOpenOptions): Promise<SoftwareBrowserSession>;\n close(): Promise<void>;\n}\n\n/** General browser-compositor capture surface. */\nexport type BrowserCaptureRuntimeWitness = SoftwareCaptureRuntimeWitness;\nexport type BrowserCaptureRecord = SoftwareCaptureRecord;\nexport type BrowserCaptureRunReport = SoftwareCaptureRunReport;\nexport type BrowserCaptureOpenOptions = SoftwareBrowserOpenOptions;\nexport type BrowserCaptureCheckpointOptions = SoftwareCaptureCheckpointOptions;\nexport type BrowserCaptureSession = SoftwareBrowserSession;\nexport type BrowserCapture = SoftwareBrowser;\n\nclass SoftwareCaptureError extends Error implements CommandError {\n constructor(\n readonly code: string,\n readonly expected: string,\n readonly hint: string,\n readonly detail: Readonly<Record<string, unknown>>,\n ) {\n super(`${code}: ${hint}`);\n this.name = 'SoftwareCaptureError';\n }\n}\n\nfunction fail(\n code: string,\n expected: string,\n hint: string,\n detail: Readonly<Record<string, unknown>> = {},\n): never {\n throw new SoftwareCaptureError(code, expected, hint, detail);\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function reservePort(): Promise<number> {\n const reservation = createNetServer();\n await new Promise<void>((resolveListen, rejectListen) => {\n reservation.once('error', rejectListen);\n reservation.listen(0, '127.0.0.1', resolveListen);\n });\n const address = reservation.address();\n const port = typeof address === 'object' && address !== null ? address.port : 0;\n await new Promise<void>((resolveClose, rejectClose) => {\n reservation.close((error) => (error === undefined ? resolveClose() : rejectClose(error)));\n });\n if (port === 0) throw new Error('OS did not assign an ephemeral capture port');\n return port;\n}\n\nasync function stopProcess(child: ChildProcess): Promise<void> {\n if (child.exitCode !== null || child.signalCode !== null) return;\n await new Promise<void>((resolveStop) => {\n const timeout = setTimeout(() => {\n child.kill('SIGKILL');\n resolveStop();\n }, 2_000);\n child.once('exit', () => {\n clearTimeout(timeout);\n resolveStop();\n });\n child.kill('SIGTERM');\n });\n}\n\nasync function startVirtualDisplay(width: number, height: number): Promise<VirtualDisplay> {\n if (process.platform !== 'linux' || process.env.DISPLAY !== undefined) {\n return {\n ...(process.env.DISPLAY === undefined ? {} : { value: process.env.DISPLAY }),\n async close() {},\n };\n }\n for (let offset = 0; offset < 100; offset += 1) {\n const number = 90 + ((process.pid + offset) % 100);\n const socket = `/tmp/.X11-unix/X${number}`;\n const lock = `/tmp/.X${number}-lock`;\n if ((await pathExists(socket)) || (await pathExists(lock))) continue;\n const display = `:${number}`;\n const child = spawn(\n 'Xvfb',\n [display, '-screen', '0', `${width}x${height}x24`, '-nolisten', 'tcp'],\n { stdio: ['ignore', 'ignore', 'pipe'] },\n );\n let diagnostic = '';\n child.stderr?.setEncoding('utf8');\n child.stderr?.on('data', (chunk: string) => {\n diagnostic += chunk;\n });\n try {\n await new Promise<void>((resolveReady, rejectReady) => {\n const timeout = setTimeout(\n () => rejectReady(new Error(`Xvfb did not create ${socket}: ${diagnostic.trim()}`)),\n 5_000,\n );\n const poll = setInterval(() => {\n void pathExists(socket).then((exists) => {\n if (!exists) return;\n clearTimeout(timeout);\n clearInterval(poll);\n resolveReady();\n });\n }, 50);\n child.once('error', (error) => {\n clearTimeout(timeout);\n clearInterval(poll);\n rejectReady(error);\n });\n child.once('exit', (code, signal) => {\n clearTimeout(timeout);\n clearInterval(poll);\n rejectReady(\n new Error(`Xvfb exited before ready (${code ?? signal}): ${diagnostic.trim()}`),\n );\n });\n });\n return { value: display, close: () => stopProcess(child) };\n } catch (cause) {\n await stopProcess(child);\n throw cause;\n }\n }\n throw new Error('no free X11 display number was available for browser capture');\n}\n\nasync function lavapipeIcd(): Promise<string | undefined> {\n for (const candidate of [\n '/usr/share/vulkan/icd.d/lvp_icd.x86_64.json',\n '/usr/share/vulkan/icd.d/lvp_icd.aarch64.json',\n ]) {\n if (await pathExists(candidate)) return candidate;\n }\n return undefined;\n}\n\nfunction evidencePath(output: string): string {\n return output.toLowerCase().endsWith('.png') ? `${output.slice(0, -4)}.json` : `${output}.json`;\n}\n\nfunction newRunId(): string {\n return `${new Date().toISOString().replace(/[:.]/g, '-')}-${randomUUID().slice(0, 8)}`;\n}\n\nfunction checkpointSlug(checkpoint: string | undefined): string {\n const value = (checkpoint ?? 'capture')\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 80);\n return value.length === 0 ? 'capture' : value;\n}\n\nfunction captureDigest(bytes: Uint8Array): string {\n return `sha256:${createHash('sha256').update(bytes).digest('hex')}`;\n}\n\ntype CaptureBackendObserved = 'software' | 'hardware' | 'unknown';\n\nfunction observedBackend(runtime: SoftwareCaptureRuntimeWitness): CaptureBackendObserved {\n if (runtime.adapter === null) return 'unknown';\n return isSoftwareAdapter(runtime) ? 'software' : 'hardware';\n}\n\nasync function resolveBrowserExecutable(\n requested: string | undefined,\n): Promise<string | undefined> {\n const candidates = [\n requested,\n process.env.FORGEAX_BROWSER_EXECUTABLE,\n '/opt/google/chrome-beta/chrome',\n '/usr/bin/google-chrome',\n '/usr/bin/google-chrome-stable',\n '/usr/bin/chromium',\n '/usr/bin/chromium-browser',\n ].filter((candidate): candidate is string => candidate !== undefined && candidate.length > 0);\n for (const candidate of candidates) {\n if (await pathExists(candidate)) return candidate;\n }\n // Playwright can supply a managed browser when its browser cache is present.\n // Leave executablePath unset so the caller receives Playwright's own diagnostic\n // rather than a misleading Chrome-Beta-only error.\n return undefined;\n}\n\nfunction browserLaunchArgs(backend: CaptureBackend): string[] {\n const common = [\n '--enable-unsafe-webgpu',\n '--ignore-gpu-blocklist',\n '--disable-gpu-driver-bug-workarounds',\n '--force-color-profile=srgb',\n '--force-device-scale-factor=1',\n ];\n if (backend !== 'software') return common;\n return [\n ...common,\n '--enable-features=Vulkan',\n '--use-vulkan=swiftshader',\n '--use-angle=swiftshader',\n '--disable-vulkan-surface',\n ];\n}\n\nexport function summarizeCapturePixels(\n rgba: Uint8Array,\n width: number,\n height: number,\n): CapturePixelWitness {\n const pixelCount = width * height;\n const stride = Math.max(1, Math.floor(pixelCount / 4096));\n const histogram = new Uint32Array(16);\n let lumaMin = 255;\n let lumaMax = 0;\n let sampledPixels = 0;\n for (let pixel = 0; pixel < pixelCount; pixel += stride) {\n const offset = pixel * 4;\n const red = rgba[offset];\n const green = rgba[offset + 1];\n const blue = rgba[offset + 2];\n if (red === undefined || green === undefined || blue === undefined) break;\n const luma = Math.round((54 * red + 183 * green + 19 * blue) / 256);\n lumaMin = Math.min(lumaMin, luma);\n lumaMax = Math.max(lumaMax, luma);\n const bucket = Math.min(15, Math.floor(luma / 16));\n histogram[bucket] = (histogram[bucket] ?? 0) + 1;\n sampledPixels += 1;\n }\n const dominantPixels = histogram.reduce((largest, count) => Math.max(largest, count), 0);\n const varyingPixels = sampledPixels - dominantPixels;\n const lumaRange = lumaMax - lumaMin;\n const requiredVariation = Math.min(sampledPixels, Math.max(8, Math.ceil(sampledPixels * 0.002)));\n return {\n width,\n height,\n sampledPixels,\n lumaMin,\n lumaMax,\n lumaRange,\n varyingPixels,\n rendered: lumaRange >= 8 && varyingPixels >= requiredVariation,\n };\n}\n\nfunction inspectCapturePng(png: Uint8Array): CapturePixelWitness {\n const decoded = parseImage(png, 'image/png', { mipmap: false });\n if (!decoded.ok) throw decoded.error;\n return summarizeCapturePixels(decoded.value.bytes, decoded.value.width, decoded.value.height);\n}\n\nasync function screenshotWithWitness(\n page: Page,\n): Promise<{ readonly png: Uint8Array; readonly pixels: CapturePixelWitness }> {\n const canvasPng = await page.locator('canvas').first().screenshot({\n type: 'png',\n style: '* { visibility: hidden !important; } canvas { visibility: visible !important; }',\n });\n const png = await page.screenshot({ type: 'png', caret: 'hide' });\n return { png, pixels: inspectCapturePng(canvasPng) };\n}\n\nasync function waitForCompositor(page: Page): Promise<void> {\n await page.evaluate(async () => {\n await document.fonts.ready;\n await new Promise<void>((resolveFrame) => requestAnimationFrame(() => resolveFrame()));\n await new Promise<void>((resolveFrame) => requestAnimationFrame(() => resolveFrame()));\n });\n}\n\nasync function runtimeWitness(page: Page): Promise<SoftwareCaptureRuntimeWitness> {\n return page.evaluate(async (datasetKey) => {\n const canvas = document.querySelector('canvas');\n const uiRoot = document.querySelector('#game-ui');\n const shadowHosts = [...(uiRoot?.querySelectorAll('*') ?? [])].filter(\n (element) => element.shadowRoot?.childElementCount !== 0,\n );\n let adapter: Readonly<Record<string, unknown>> | null = null;\n let adapterError: string | null = null;\n try {\n const gpuAdapter = await navigator.gpu?.requestAdapter();\n if (gpuAdapter === null || gpuAdapter === undefined) {\n adapterError = 'navigator.gpu.requestAdapter() returned null';\n } else {\n const info = gpuAdapter.info;\n adapter = {\n vendor: info.vendor,\n architecture: info.architecture,\n device: info.device,\n description: info.description,\n };\n }\n } catch (cause) {\n adapterError = String(cause);\n }\n const frameId = Number(document.documentElement.dataset[datasetKey]);\n return {\n title: document.title,\n canvas:\n canvas instanceof HTMLCanvasElement ? { width: canvas.width, height: canvas.height } : null,\n domUi: {\n rootChildren: uiRoot?.childElementCount ?? 0,\n openShadowRoots: shadowHosts.length,\n textWitness: shadowHosts\n .map((host) => host.shadowRoot?.textContent?.replace(/\\s+/g, ' ').trim() ?? '')\n .filter((text) => text.length > 0)\n .join(' | ')\n .slice(0, 500),\n },\n adapter,\n adapterError,\n engineFrameId: Number.isSafeInteger(frameId) && frameId > 0 ? frameId : null,\n captureReady: document.documentElement.dataset.forgeaxCaptureReady ?? null,\n userAgent: navigator.userAgent,\n };\n }, FORGEAX_FRAME_SUBMITTED_DATASET);\n}\n\nfunction isSoftwareAdapter(runtime: SoftwareCaptureRuntimeWitness): boolean {\n const witness = Object.values(runtime.adapter ?? {})\n .map((value) => String(value).toLowerCase())\n .join(' ');\n return ['swiftshader', 'llvmpipe', 'lavapipe', 'software'].some((token) =>\n witness.includes(token),\n );\n}\n\nasync function writeRunReport(report: SoftwareCaptureRunReport): Promise<void> {\n await mkdir(dirname(report.report), { recursive: true });\n await writeFile(report.report, `${JSON.stringify(report, null, 2)}\\n`, 'utf8');\n}\n\nasync function openBrowserCaptureSession(\n root: string,\n options: BrowserCaptureOpenOptions,\n): Promise<BrowserCaptureSession> {\n const backend: CaptureBackend =\n options.backend ?? (options.software === true ? 'software' : 'auto');\n if (\n options.software === true &&\n options.backend !== undefined &&\n options.backend !== 'software'\n ) {\n fail(\n 'browser-capture-option-conflict',\n 'software and backend options to describe the same capture lane',\n 'Use either software: true or backend: software; use backend: auto for a portable capture.',\n { software: options.software, backend: options.backend },\n );\n }\n const facts = await readProjectFacts(root);\n if (!facts.ok) {\n throw new SoftwareCaptureError(\n facts.error.code,\n facts.error.expected,\n facts.error.hint,\n facts.error.detail,\n );\n }\n const width = options.width ?? 1280;\n const height = options.height ?? 720;\n const browserPath = await resolveBrowserExecutable(options.browser);\n if (options.browser !== undefined && browserPath === undefined) {\n fail(\n 'browser-capture-browser-missing',\n `a runnable browser at ${options.browser}`,\n 'Install Chrome/Chromium or pass --browser with an executable path.',\n { browser: options.browser },\n );\n }\n\n const id = options.runId ?? newRunId();\n const outputDirectory = resolve(\n facts.value.root,\n options.outputDir ?? `artifacts/playthrough/${id}`,\n );\n const reportPath = resolve(\n facts.value.root,\n options.report ?? resolve(outputDirectory, 'run.json'),\n );\n const port =\n options.port === undefined || options.port === 0 ? await reservePort() : options.port;\n let server: ViteDevServer | undefined;\n let browser: Browser | undefined;\n let page: Page | undefined;\n let display: VirtualDisplay | undefined;\n try {\n const { createServer } = await import('vite');\n server = await createServer(\n await createViteConfig(facts.value, 'serve', '/', {\n server: { port, strictPort: true },\n }),\n );\n await server.listen(port);\n display = await startVirtualDisplay(width, height);\n const captureDisplay = display;\n const icd = await lavapipeIcd();\n const consoleErrors: string[] = [];\n const pageErrors: string[] = [];\n const hasDisplay = display.value !== undefined;\n const headless = options.headless ?? (!hasDisplay && process.platform !== 'linux');\n const baseUrl = new URL(server.resolvedUrls?.local[0] ?? `http://127.0.0.1:${port}/`);\n const openPage = async (\n launchBackend: CaptureBackend,\n ): Promise<SoftwareCaptureRuntimeWitness> => {\n const browserEnvironment: Record<string, string> = {\n ...Object.fromEntries(\n Object.entries(process.env).filter(\n (entry): entry is [string, string] => entry[1] !== undefined,\n ),\n ),\n ...(launchBackend === 'software' ? { LIBGL_ALWAYS_SOFTWARE: '1' } : {}),\n ...(captureDisplay.value === undefined ? {} : { DISPLAY: captureDisplay.value }),\n };\n const launchOptions = {\n headless,\n env: browserEnvironment,\n args: browserLaunchArgs(launchBackend),\n ...(browserPath === undefined ? {} : { executablePath: browserPath }),\n };\n browser = await chromium.launch(launchOptions);\n page = await browser.newPage({\n viewport: { width, height },\n screen: { width, height },\n deviceScaleFactor: 1,\n colorScheme: 'light',\n locale: 'en-US',\n timezoneId: 'UTC',\n serviceWorkers: 'block',\n });\n page.on('console', (message) => {\n if (message.type() === 'error') consoleErrors.push(message.text());\n });\n page.on('pageerror', (error) => pageErrors.push(String(error)));\n const captureUrl = new URL(baseUrl.href);\n if (options.deterministic === true) captureUrl.searchParams.set('forgeaxCapture', '1');\n await page.goto(captureUrl.href, { waitUntil: 'domcontentloaded', timeout: 120_000 });\n await page.waitForFunction(\n (requireUi) => {\n const canvas = document.querySelector('canvas');\n if (!(canvas instanceof HTMLCanvasElement) || canvas.width <= 0 || canvas.height <= 0)\n return false;\n if (!requireUi) return true;\n const uiRoot = document.querySelector('#game-ui');\n return uiRoot !== null && uiRoot.childElementCount > 0;\n },\n options.requireUi === true,\n { timeout: 120_000 },\n );\n return runtimeWitness(page);\n };\n\n // Auto first preserves a physical adapter. If WebGPU is unavailable, retry\n // once through the same explicit software lane used by CPU-only hosts. This\n // keeps the public capture contract portable without masking a flat frame.\n const initialLaunchBackend: CaptureBackend = backend === 'software' ? 'software' : 'hardware';\n let runtime = await openPage(initialLaunchBackend);\n let observed = observedBackend(runtime);\n if (backend === 'auto' && runtime.adapter === null) {\n await browser?.close();\n browser = undefined;\n page = undefined;\n consoleErrors.length = 0;\n pageErrors.length = 0;\n runtime = await openPage('software');\n observed = observedBackend(runtime);\n }\n const captureUrl = new URL(baseUrl.href);\n if (options.deterministic === true) captureUrl.searchParams.set('forgeaxCapture', '1');\n if (page === undefined || browser === undefined) {\n fail(\n 'browser-capture-browser-unavailable',\n 'the browser capture session to open',\n 'Inspect the browser launch diagnostic and retry with --browser or --headless.',\n );\n }\n\n const captures: SoftwareCaptureRecord[] = [];\n let closed = false;\n const report: SoftwareCaptureRunReport = {\n schemaVersion: '2.0.0',\n runId: id,\n ok: false,\n mode: 'browser-compositor',\n root: facts.value.root,\n url: captureUrl.href,\n report: reportPath,\n backendRequested: backend,\n backend: observed,\n softwareRequested: backend === 'software',\n deterministicRequested: options.deterministic === true,\n viewport: {\n width,\n height,\n deviceScaleFactor: 1,\n colorProfile: 'srgb',\n colorScheme: 'light',\n locale: 'en-US',\n timezone: 'UTC',\n },\n browser: { version: browser.version(), executable: browserPath ?? 'playwright-managed' },\n display: display.value ?? null,\n lavapipeIcd: icd ?? null,\n captures,\n consoleErrors,\n pageErrors,\n boundary:\n 'Browser-compositor capture is visual iteration evidence, not physical-GPU performance, HDR-display output, or release acceptance.',\n };\n await writeRunReport(report);\n\n const updateReport = async (): Promise<void> => {\n Object.assign(report, {\n ok:\n captures.length > 0 &&\n captures.every((capture) => capture.ok) &&\n consoleErrors.length === 0 &&\n pageErrors.length === 0,\n });\n await writeRunReport(report);\n };\n const close = async (): Promise<void> => {\n if (closed) return;\n closed = true;\n await Promise.allSettled([browser?.close(), display?.close(), server?.close()]);\n Object.assign(report, { closedAt: new Date().toISOString() });\n await updateReport();\n };\n\n return {\n page,\n url: captureUrl.href,\n reportPath,\n async capture(checkpoint, captureOptions = {}) {\n if (closed) {\n fail(\n 'browser-capture-session-closed',\n 'capture to run inside an open browser session',\n 'Open one session, complete all checkpoints, then close it.',\n { report: reportPath },\n );\n }\n const activePage = page;\n if (activePage === undefined) {\n fail(\n 'browser-capture-browser-unavailable',\n 'an open Playwright page',\n 'Inspect the browser launch diagnostic and retry the capture.',\n );\n }\n const expectedReady = checkpoint ?? (options.deterministic === true ? 'true' : undefined);\n await activePage.waitForFunction(\n ({ datasetKey }) => Number(document.documentElement.dataset[datasetKey]) > 0,\n { datasetKey: FORGEAX_FRAME_SUBMITTED_DATASET },\n { timeout: 120_000 },\n );\n if (expectedReady !== undefined) {\n await activePage.waitForFunction(\n (expected) => document.documentElement.dataset.forgeaxCaptureReady === expected,\n expectedReady,\n { timeout: 120_000 },\n );\n }\n await waitForCompositor(activePage);\n let captured = await screenshotWithWitness(activePage);\n const deadline = Date.now() + 120_000;\n while (!captured.pixels.rendered && Date.now() < deadline) {\n await activePage.waitForTimeout(500);\n await waitForCompositor(activePage);\n captured = await screenshotWithWitness(activePage);\n }\n const waitMs = captureOptions.waitMs ?? 0;\n if (waitMs > 0) {\n await activePage.waitForTimeout(waitMs);\n await waitForCompositor(activePage);\n captured = await screenshotWithWitness(activePage);\n while (!captured.pixels.rendered && Date.now() < deadline) {\n await activePage.waitForTimeout(500);\n await waitForCompositor(activePage);\n captured = await screenshotWithWitness(activePage);\n }\n }\n const runtime = await runtimeWitness(activePage);\n const uiPresent = runtime.domUi.rootChildren > 0;\n const requireUi = captureOptions.requireUi ?? options.requireUi ?? false;\n const captureBackend = observedBackend(runtime);\n if (captureBackend !== 'unknown') Object.assign(report, { backend: captureBackend });\n const backendMatches = backend === 'auto' || captureBackend === backend;\n const ok =\n runtime.canvas !== null &&\n captured.pixels.rendered &&\n backendMatches &&\n runtime.engineFrameId !== null &&\n consoleErrors.length === 0 &&\n pageErrors.length === 0 &&\n (expectedReady === undefined || runtime.captureReady === expectedReady) &&\n (!requireUi || uiPresent);\n const index = captures.length + 1;\n const output = resolve(\n facts.value.root,\n captureOptions.output ??\n resolve(\n outputDirectory,\n `${String(index).padStart(3, '0')}-${checkpointSlug(checkpoint)}.png`,\n ),\n );\n await mkdir(dirname(output), { recursive: true });\n await writeFile(output, captured.png);\n const record: SoftwareCaptureRecord = {\n index,\n checkpoint: checkpoint ?? null,\n ok,\n output,\n digest: captureDigest(captured.png),\n pixels: captured.pixels,\n runtime,\n };\n captures.push(record);\n await updateReport();\n if (!ok) {\n fail(\n `${backend === 'software' ? 'software' : 'browser'}-capture-runtime-failed`,\n 'non-flat canvas pixels, the requested browser backend/checkpoint, and no browser errors',\n 'Inspect the run report and repair the first browser runtime failure.',\n { checkpoint: checkpoint ?? null, output, report: reportPath },\n );\n }\n return record;\n },\n report: () => report,\n close,\n };\n } catch (cause) {\n await Promise.allSettled([browser?.close(), display?.close(), server?.close()]);\n throw cause;\n }\n}\n\nexport function createBrowserCapture(root: string): BrowserCapture {\n const sessions = new Set<BrowserCaptureSession>();\n return {\n async open(options) {\n const session = await openBrowserCaptureSession(root, options);\n sessions.add(session);\n return session;\n },\n async close() {\n await Promise.allSettled([...sessions].map((session) => session.close()));\n sessions.clear();\n },\n };\n}\n\n/**\n * Compatibility facade for callers that still request the original software\n * lane. New integrations should use createBrowserCapture({ backend }).\n */\nexport function createSoftwareBrowser(root: string): SoftwareBrowser {\n const browser = createBrowserCapture(root);\n return {\n async open(options) {\n return browser.open({ ...options, backend: 'software', software: true });\n },\n close: () => browser.close(),\n };\n}\n\nfunction captureCommandError(cause: unknown, legacySoftware = false): CommandError {\n if (cause instanceof SoftwareCaptureError) {\n const code =\n legacySoftware && cause.code.startsWith('browser-capture-')\n ? cause.code.replace(/^browser-capture-/, 'software-capture-')\n : cause.code;\n return {\n code,\n expected: cause.expected,\n hint: cause.hint,\n detail: cause.detail,\n };\n }\n return commandError(cause, legacySoftware ? 'software-capture-failed' : 'browser-capture-failed');\n}\n\nexport async function browserCaptureCommand(\n options: BrowserCaptureOptions,\n): Promise<CommandResult<BrowserCaptureRunReport>> {\n const root = options.root ?? process.cwd();\n const output = resolve(root, options.output ?? 'artifacts/capture/game-ui.png');\n const browser = createBrowserCapture(root);\n try {\n const backend = options.backend ?? (options.software === true ? 'software' : 'auto');\n const session = await browser.open({\n backend,\n ...(backend === 'software' ? { software: true } : {}),\n ...(options.browser === undefined ? {} : { browser: options.browser }),\n ...(options.width === undefined ? {} : { width: options.width }),\n ...(options.height === undefined ? {} : { height: options.height }),\n ...(options.port === undefined ? {} : { port: options.port }),\n ...(options.headless === undefined ? {} : { headless: options.headless }),\n requireUi: options.requireUi === true,\n deterministic: options.deterministic === true,\n outputDir: dirname(output),\n report: evidencePath(output),\n });\n await session.capture(options.deterministic === true ? 'true' : undefined, {\n output,\n waitMs: options.waitMs ?? 4000,\n requireUi: options.requireUi === true,\n });\n await session.close();\n return { ok: true, value: session.report() };\n } catch (cause) {\n return { ok: false, error: captureCommandError(cause) };\n } finally {\n await browser.close();\n }\n}\n\nexport async function softwareCaptureCommand(\n options: SoftwareCaptureOptions,\n): Promise<CommandResult<unknown>> {\n const result = await browserCaptureCommand({ ...options, backend: 'software', software: true });\n if (result.ok) return result;\n return { ok: false, error: captureCommandErrorFromResult(result.error, true) };\n}\n\nfunction captureCommandErrorFromResult(error: CommandError, legacySoftware: boolean): CommandError {\n if (!legacySoftware || !error.code.startsWith('browser-capture-')) return error;\n return { ...error, code: error.code.replace(/^browser-capture-/, 'software-capture-') };\n}\n","import { createHash } from 'node:crypto';\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { createServer as createNetServer } from 'node:net';\nimport { basename, dirname, relative, resolve } from 'node:path';\nimport { build as viteBuild, preview as vitePreview } from 'vite';\nimport { startVitest } from 'vitest/node';\nimport { createZip } from './archive.js';\nimport { verifyDist, writeDistManifest } from './dist.js';\nimport { createViteConfig } from './host.js';\nimport { commandError, readProjectFacts } from './project.js';\nimport { resolveProjectPort } from './types.js';\n\nexport {\n assetAddCommand,\n assetInspectCommand,\n assetListCommand,\n assetVerifyCommand,\n} from './assets.js';\nexport type { DoctorReport } from './bootstrap-commands.js';\nexport { doctorCommand, initCommand, newCommand } from './bootstrap-commands.js';\nexport {\n engineDoctorCommand,\n engineStatusCommand,\n engineUnlinkCommand,\n engineUseLocalCommand,\n} from './engine-binding.js';\nexport { pluginInstallCommand, pluginUninstallCommand } from './plugin-authoring.js';\nexport { createCliRhiDebugOperationContext } from './rhi-debug/cli-context.js';\nexport type {\n ArtifactRef,\n CapturedRhiTape,\n RhiCaptureFrameValue,\n RhiDebugOperationContext,\n RhiDebugOperationDescriptor,\n RhiDebugOperationInput,\n RhiDebugOperationName,\n RhiDebugOperationOutput,\n RhiInspectInput,\n RhiInspectOutput,\n RhiSummaryInput,\n RhiSummaryOutput,\n} from './rhi-debug/operations.js';\nexport {\n createRhiDebugOperationContext,\n discoverRhiDebugOperations,\n RHI_DEBUG_OPERATION_MANIFEST,\n recoverRhiDebugError,\n renderRhiDebugHelp,\n runRhiDebugOperation,\n} from './rhi-debug/operations.js';\nexport { sdkInstallCommand } from './sdk-install.js';\nexport { shaderCheckCommand } from './shader-check.js';\nexport { skillInstallCommand, skillVerifyCommand } from './skill-install.js';\nexport { browserCaptureCommand, softwareCaptureCommand } from './software-capture.js';\n\nimport {\n type RhiDebugOperationContext,\n type RhiDebugOperationInput,\n type RhiDebugOperationName,\n type RhiDebugOperationOutput,\n runRhiDebugOperation,\n} from './rhi-debug/operations.js';\nimport type {\n BuildOptions,\n CommandResult,\n PackageOptions,\n ProjectCommandOptions,\n} from './types.js';\n\nexport function runRhiDebugCommand(\n name: RhiDebugOperationName,\n input: RhiDebugOperationInput,\n context: RhiDebugOperationContext,\n): Promise<CommandResult<RhiDebugOperationOutput>> {\n return runRhiDebugOperation(name, input, context);\n}\n\nasync function materializeViteDevPort(port: number): Promise<number> {\n if (port !== 0) return port;\n const reservation = createNetServer();\n await new Promise<void>((resolveListen, rejectListen) => {\n reservation.once('error', rejectListen);\n reservation.listen(0, '127.0.0.1', resolveListen);\n });\n const address = reservation.address();\n const assigned = typeof address === 'object' && address !== null ? address.port : 0;\n await new Promise<void>((resolveClose, rejectClose) => {\n reservation.close((error) => (error === undefined ? resolveClose() : rejectClose(error)));\n });\n if (assigned === 0) throw new Error('OS did not assign an ephemeral preview port');\n return assigned;\n}\n\nexport async function buildCommand(options: BuildOptions = {}): Promise<CommandResult<unknown>> {\n const facts = await readProjectFacts(options.root);\n if (!facts.ok) return facts;\n const previous = process.cwd();\n const base = options.base ?? '/';\n const outDir = resolve(facts.value.root, options.outDir ?? 'dist');\n try {\n process.chdir(facts.value.root);\n await viteBuild(await createViteConfig(facts.value, 'build', base, { outDir }));\n return { ok: true, value: await writeDistManifest(facts.value, base, outDir) };\n } catch (cause) {\n return { ok: false, error: commandError(cause, 'game-build-failed') };\n } finally {\n process.chdir(previous);\n }\n}\n\nfunction releaseSlug(name: string): string {\n const slug = name\n .normalize('NFKD')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '');\n return slug.length > 0 ? slug : 'forgeax-game';\n}\n\nexport async function packageCommand(\n options: PackageOptions = {},\n): Promise<CommandResult<unknown>> {\n const facts = await readProjectFacts(options.root);\n if (!facts.ok) return facts;\n const built = await buildCommand({\n root: facts.value.root,\n base: './',\n ...(options.json === undefined ? {} : { json: options.json }),\n });\n if (!built.ok) return built;\n const distRoot = resolve(facts.value.root, 'dist');\n const verified = await verifyDist(distRoot);\n if (!verified.ok) return verified;\n const archive = resolve(\n facts.value.root,\n options.output ?? `release/${releaseSlug(facts.value.name)}-web.zip`,\n );\n const archiveRelativeToDist = relative(distRoot, archive);\n if (archiveRelativeToDist === '' || !archiveRelativeToDist.startsWith('..')) {\n return {\n ok: false,\n error: {\n code: 'release-output-inside-dist',\n expected: 'the release archive to live outside the derived dist directory',\n hint: 'Use --output release/<game>-web.zip or another path outside dist.',\n detail: { archive, distRoot },\n },\n };\n }\n const temporaryArchive = `${archive}.partial-${process.pid}`;\n const checksumPath = `${archive}.sha256`;\n const temporaryChecksum = `${checksumPath}.partial-${process.pid}`;\n try {\n const paths = [\n ...verified.value.artifacts.map((artifact) => artifact.path),\n 'forgeax-dist.json',\n ];\n const entries = await Promise.all(\n paths.map(async (path) => ({ path, bytes: await readFile(resolve(distRoot, path)) })),\n );\n const bytes = createZip(entries);\n const sha256 = createHash('sha256').update(bytes).digest('hex');\n const manifestBytes = await readFile(resolve(distRoot, 'forgeax-dist.json'));\n await mkdir(dirname(archive), { recursive: true });\n await writeFile(temporaryArchive, bytes);\n await writeFile(temporaryChecksum, `${sha256} ${basename(archive)}\\n`);\n await rename(temporaryChecksum, checksumPath);\n await rename(temporaryArchive, archive);\n return {\n ok: true,\n value: {\n schemaVersion: '1.0.0',\n format: 'forgeax-web-game',\n target: 'web',\n project: verified.value.project,\n base: verified.value.base,\n engine: {\n delivery: 'bundled-runtime',\n wasm: verified.value.artifacts.some((artifact) => artifact.path.endsWith('.wasm')),\n },\n archive: { path: archive, bytes: bytes.byteLength, sha256 },\n checksumPath,\n distManifestSha256: createHash('sha256').update(manifestBytes).digest('hex'),\n run: {\n local: 'forgeax preview',\n shared: 'upload the ZIP to an HTTPS static or HTML-game host and share its URL',\n },\n },\n };\n } catch (cause) {\n return { ok: false, error: commandError(cause, 'game-package-failed') };\n } finally {\n await Promise.all([\n rm(temporaryArchive, { force: true }),\n rm(temporaryChecksum, { force: true }),\n ]);\n }\n}\n\nexport async function devCommand(\n options: ProjectCommandOptions = {},\n): Promise<CommandResult<unknown>> {\n const facts = await readProjectFacts(options.root);\n if (!facts.ok) return facts;\n const previous = process.cwd();\n let server: Awaited<ReturnType<typeof import('vite')['createServer']>> | undefined;\n try {\n const { createServer } = await import('vite');\n const { createViteConfig } = await import('./host.js');\n const port = resolveProjectPort(options.port);\n const vitePort = { ...port, port: await materializeViteDevPort(port.port) };\n process.chdir(facts.value.root);\n server = await createServer(\n await createViteConfig(facts.value, 'serve', '/', {\n server: vitePort,\n }),\n );\n await server.listen(vitePort.port);\n if (options.json !== true) server.printUrls();\n return {\n ok: true,\n value: {\n root: facts.value.root,\n urls: server.resolvedUrls,\n mode: 'dev',\n serves: 'source',\n capabilities: {\n 'rhi.capture': {\n available: false,\n realm: 'host',\n reason: 'standalone-dev-server-has-no-live-app-cli-attachment',\n },\n },\n },\n };\n } catch (cause) {\n await server?.close();\n process.chdir(previous);\n return { ok: false, error: commandError(cause, 'dev-server-failed') };\n }\n}\n\nexport async function previewCommand(\n options: ProjectCommandOptions = {},\n): Promise<CommandResult<unknown>> {\n const root = resolve(options.root ?? process.cwd());\n const verified = await verifyDist(resolve(root, 'dist'));\n if (!verified.ok) return verified;\n try {\n const port = resolveProjectPort(options.port);\n const server = await vitePreview({\n root,\n configFile: false,\n base: verified.value.base,\n preview: { open: false, ...port },\n build: { outDir: resolve(root, 'dist') },\n });\n if (options.json !== true) server.printUrls();\n return {\n ok: true,\n value: {\n root,\n urls: server.resolvedUrls,\n mode: 'preview',\n serves: 'dist',\n capabilities: {\n 'rhi.capture': {\n available: false,\n realm: 'host',\n reason: 'static-dist-host-does-not-install-dev-capture',\n },\n },\n },\n };\n } catch (cause) {\n return { ok: false, error: commandError(cause, 'preview-server-failed') };\n }\n}\n\nexport async function testCommand(\n options: ProjectCommandOptions = {},\n): Promise<CommandResult<unknown>> {\n const facts = await readProjectFacts(options.root);\n if (!facts.ok) return facts;\n try {\n const context = await startVitest('test', [], {\n root: facts.value.root,\n run: true,\n watch: false,\n passWithNoTests: false,\n });\n if (context === undefined) {\n return {\n ok: false,\n error: {\n code: 'test-runner-unavailable',\n expected: 'Vitest to create a project test context',\n hint: 'Inspect the project test configuration.',\n detail: { root: facts.value.root },\n },\n };\n }\n const failed = context.state.getFiles().filter((file) => file.result?.state === 'fail');\n await context.close();\n if (failed.length > 0) {\n return {\n ok: false,\n error: {\n code: 'project-tests-failed',\n expected: 'all project tests to pass',\n hint: 'Repair the failing game test before building a release.',\n detail: { files: failed.map((file) => file.filepath) },\n },\n };\n }\n return { ok: true, value: { root: facts.value.root } };\n } catch (cause) {\n return { ok: false, error: commandError(cause, 'project-tests-failed') };\n }\n}\n","import type { PluginCatalog, ToolPlugin } from '@forgeax/engine-plugin';\nimport { bindPreviewHost, type NativePreviewHost } from '@forgeax/engine-preview';\nimport materialPreviewPlugin from '@forgeax/engine-preview/material';\nimport meshPreviewPlugin from '@forgeax/engine-preview/mesh';\nimport texturePreviewPlugin from '@forgeax/engine-preview/texture';\nimport vfxPreviewPlugin from '@forgeax/engine-preview/vfx';\nimport type { ToolDescriptor } from '@forgeax/engine-tool-runtime';\n\nexport const nativePreviewPlugins = [\n ['@forgeax/engine-preview/material', materialPreviewPlugin],\n ['@forgeax/engine-preview/mesh', meshPreviewPlugin],\n ['@forgeax/engine-preview/vfx', vfxPreviewPlugin],\n ['@forgeax/engine-preview/texture', texturePreviewPlugin],\n] as const;\n\nexport const nativePreviewTools = nativePreviewPlugins.flatMap(([, plugin]) => plugin.tools);\nexport const nativePreviewDescriptors: readonly ToolDescriptor[] = nativePreviewTools.map(\n ({ descriptor }) => descriptor,\n);\n\nexport function createNativePreviewCatalog(\n host: NativePreviewHost,\n selectedName?: string,\n): PluginCatalog {\n return new Map(\n nativePreviewPlugins\n .filter(([name]) => selectedName === undefined || name === selectedName)\n .map(([name, plugin]) => [\n name,\n {\n realm: 'host' as const,\n load: async () => ({\n default: bindPreviewHost(plugin as ToolPlugin, host),\n }),\n },\n ]),\n );\n}\n","import { createHash } from 'node:crypto';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport {\n capabilityUnavailableError,\n createToolRuntime,\n type ToolContribution,\n type ToolDescriptor,\n type ToolRunOptions,\n type ToolRuntime,\n type ToolSchema,\n type ToolTerminal,\n} from '@forgeax/engine-tool-runtime';\nimport type { BuildOptions, PluginInstallOptions } from '../types.js';\nimport type { OfflineAnalysisRequest, OfflineAnalysisResult } from './offline-analysis.js';\nimport { nativePreviewDescriptors } from './preview-catalog.js';\nimport type { PreviewHostRequest, PreviewHostResult } from './preview-host.js';\n\nexport interface ToolCatalogAuthority {\n readonly authorityDigest?: string;\n readonly root?: string;\n readonly read?: () => Promise<ToolCatalogAuthoritySnapshot>;\n readonly projectionPath?: string;\n}\n\nexport interface ToolCatalogAuthoritySnapshot {\n readonly authorityDigest: string;\n readonly descriptors: readonly ToolDescriptor[];\n}\n\nexport interface ToolCatalogEntry {\n readonly id: string;\n readonly title: string;\n readonly summary: string;\n readonly realm: ToolDescriptor['realm'];\n readonly evidence: ToolDescriptor['evidence'];\n readonly argsSchema?: string;\n readonly resultSchema?: string;\n}\n\nexport interface ToolCatalog {\n readonly schemaVersion: '1.0.0';\n readonly authorityDigest: string;\n readonly digest: string;\n readonly entries: readonly ToolCatalogEntry[];\n}\n\nexport type ToolCatalogLoadResult =\n | {\n readonly ok: true;\n readonly value: ToolCatalog;\n }\n | {\n readonly ok: false;\n readonly error: {\n readonly code: 'tool-catalog-authority-unreadable' | 'tool-catalog-projection-invalid';\n readonly expected: string;\n readonly hint: string;\n readonly detail: Readonly<Record<string, string>>;\n };\n };\n\nconst buildArgsSchema: ToolSchema<BuildOptions> = {\n parse(value) {\n if (value === null || typeof value !== 'object')\n return { ok: false, error: 'expected an options object' };\n return { ok: true, value: value as BuildOptions };\n },\n describe: '{\"type\":\"object\",\"properties\":{\"root\":{\"type\":\"string\"},\"base\":{\"type\":\"string\"}}}',\n};\n\nconst pluginInstallArgsSchema: ToolSchema<PluginInstallOptions> = {\n parse(value) {\n if (value === null || typeof value !== 'object')\n return { ok: false, error: 'expected a plugin install options object' };\n return { ok: true, value: value as PluginInstallOptions };\n },\n describe:\n '{\"type\":\"object\",\"required\":[\"id\",\"module\"],\"properties\":{\"id\":{\"type\":\"string\"},\"module\":{\"type\":\"string\"},\"realm\":{\"enum\":[\"host\",\"engine\",\"build\"]},\"dependency\":{\"type\":\"string\"},\"root\":{\"type\":\"string\"}}}',\n};\n\nconst previewArgsSchema: ToolSchema<PreviewHostRequest> = {\n parse(value) {\n if (value === null || typeof value !== 'object')\n return { ok: false, error: 'expected a preview request object' };\n const request = value as { readonly recipe?: unknown };\n if (request.recipe === undefined || typeof request.recipe !== 'object')\n return { ok: false, error: 'expected recipe in the preview request' };\n return { ok: true, value: value as PreviewHostRequest };\n },\n describe:\n '{\"type\":\"object\",\"required\":[\"recipe\"],\"properties\":{\"recipe\":{\"type\":\"object\",\"required\":[\"snapshot\"],\"properties\":{\"snapshot\":{\"type\":\"object\",\"required\":[\"revision\",\"digest\"]},\"backend\":{\"const\":\"webgpu\"},\"presentation\":{\"enum\":[\"hidden\",\"visible\"]},\"viewport\":{\"type\":\"object\",\"properties\":{\"width\":{\"type\":\"integer\",\"minimum\":1},\"height\":{\"type\":\"integer\",\"minimum\":1}}},\"actions\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"required\":[\"frame\",\"name\"],\"properties\":{\"frame\":{\"type\":\"integer\",\"minimum\":0},\"name\":{\"type\":\"string\",\"minLength\":1},\"value\":{}}}},\"deltaSeconds\":{\"type\":\"number\",\"minimum\":0},\"frames\":{\"type\":\"integer\",\"minimum\":1}}}}}',\n};\n\nconst resultSchema: ToolSchema<unknown> = {\n parse: (value) => ({ ok: true, value }),\n describe: '{\"type\":\"object\"}',\n};\n\nconst offlineAnalysisArgsSchema: ToolSchema<OfflineAnalysisRequest> = {\n parse(value) {\n if (value === null || typeof value !== 'object')\n return { ok: false, error: 'expected an offline analysis request object' };\n const request = value as { readonly manifest?: unknown };\n if (request.manifest === undefined || typeof request.manifest !== 'object')\n return { ok: false, error: 'expected manifest in the offline analysis request' };\n return { ok: true, value: value as OfflineAnalysisRequest };\n },\n describe:\n '{\"type\":\"object\",\"required\":[\"manifest\"],\"properties\":{\"manifest\":{\"type\":\"object\",\"required\":[\"schemaVersion\",\"identity\",\"artifacts\"]},\"required\":{\"type\":\"array\",\"items\":{\"enum\":[\"rhi-tape\",\"png\",\"profile-capture\"]}}}}',\n};\n\nexport const projectBuildDescriptor: ToolDescriptor<BuildOptions, unknown> = {\n id: 'project.build',\n title: 'Build project',\n summary: 'Builds the project through the existing Vite and Pack authorities.',\n realm: 'build',\n argsSchema: buildArgsSchema,\n resultSchema,\n evidence: [],\n};\nexport const authorPluginInstallDescriptor: ToolDescriptor<PluginInstallOptions, unknown> = {\n id: 'author.plugin-install',\n title: 'Install project plugin',\n summary: 'Writes one plugin Entry through the project authoring authority.',\n realm: 'build',\n argsSchema: pluginInstallArgsSchema,\n resultSchema,\n evidence: [],\n};\nexport const previewRunDescriptor: ToolDescriptor<PreviewHostRequest, PreviewHostResult> = {\n id: 'preview.run',\n title: 'Run hidden WebGPU preview',\n summary: 'Runs one fixed real-WebGPU preview recipe and returns structured evidence refs.',\n realm: 'host',\n argsSchema: previewArgsSchema,\n resultSchema: resultSchema as ToolDescriptor<\n PreviewHostRequest,\n PreviewHostResult\n >['resultSchema'],\n evidence: ['rhi-tape', 'png', 'profile-capture'],\n};\nexport const previewOfflineAnalysisDescriptor: ToolDescriptor<\n OfflineAnalysisRequest,\n OfflineAnalysisResult\n> = {\n id: 'preview.offline-analysis',\n title: 'Analyze preview artifacts',\n summary: 'Validates owner-separated evidence identity before offline consumption.',\n realm: 'build',\n argsSchema: offlineAnalysisArgsSchema,\n resultSchema: resultSchema as ToolSchema<OfflineAnalysisResult>,\n evidence: ['rhi-tape', 'png', 'profile-capture'],\n};\n\nexport const defaultToolDescriptors: readonly ToolDescriptor[] = [\n projectBuildDescriptor,\n authorPluginInstallDescriptor,\n ...nativePreviewDescriptors,\n];\n\nfunction projectDescriptor(descriptor: ToolDescriptor): ToolCatalogEntry {\n return {\n id: descriptor.id,\n title: descriptor.title,\n summary: descriptor.summary,\n realm: descriptor.realm,\n evidence: [...descriptor.evidence],\n ...(descriptor.argsSchema.describe === undefined\n ? {}\n : { argsSchema: descriptor.argsSchema.describe }),\n ...(descriptor.resultSchema.describe === undefined\n ? {}\n : { resultSchema: descriptor.resultSchema.describe }),\n };\n}\n\nexport interface ToolRealmOwner {\n readonly realm: ToolDescriptor['realm'];\n readonly contributions: readonly ToolContribution[];\n}\n\nexport interface ToolRealmDispatch {\n readonly list: () => readonly ToolDescriptor[];\n readonly describe: (id: string) => ToolDescriptor | undefined;\n readonly run: <TResult = unknown>(\n id: string,\n args: unknown,\n options?: ToolRunOptions,\n ) => Promise<ToolTerminal<TResult>>;\n}\n\nfunction missingRealmOwner<TResult>(\n descriptor: ToolDescriptor | undefined,\n id: string,\n): ToolTerminal<TResult> {\n const realm = descriptor?.realm ?? 'build';\n return {\n outcome: 'failed',\n failure: capabilityUnavailableError(`realm:${realm}:tool:${id}`, realm),\n artifacts: [],\n } as ToolTerminal<TResult>;\n}\n\n/** Dispatches a descriptor to the one physical owner for its declared realm. */\nexport function createRealmDispatch(\n contributions: readonly ToolContribution[],\n owners: readonly ToolRealmOwner[],\n): ToolRealmDispatch {\n const contributionById = new Map(\n contributions.map((contribution) => [contribution.descriptor.id, contribution]),\n );\n const ownerByRealm = new Map<ToolDescriptor['realm'], ToolRuntime>();\n for (const owner of owners) {\n if (ownerByRealm.has(owner.realm)) throw new TypeError(`Duplicate realm owner: ${owner.realm}`);\n const invalid = owner.contributions.find(\n (contribution) => contribution.descriptor.realm !== owner.realm,\n );\n if (invalid !== undefined) {\n throw new TypeError(\n `Tool ${invalid.descriptor.id} declares ${invalid.descriptor.realm} but owner is ${owner.realm}`,\n );\n }\n ownerByRealm.set(owner.realm, createToolRuntime(owner.contributions));\n }\n return {\n list: () => contributions.map((contribution) => contribution.descriptor),\n describe: (id) => contributionById.get(id)?.descriptor,\n async run<TResult = unknown>(id: string, args: unknown, options: ToolRunOptions = {}) {\n const contribution = contributionById.get(id);\n if (contribution === undefined)\n return missingRealmOwner(undefined, id) as ToolTerminal<TResult>;\n const owner = ownerByRealm.get(contribution.descriptor.realm);\n if (owner === undefined) return missingRealmOwner(contribution.descriptor, id);\n const bound = owner.get(id);\n if (bound === undefined) return missingRealmOwner(contribution.descriptor, id);\n return (await owner.run(bound, args, options).terminal) as ToolTerminal<TResult>;\n },\n };\n}\n\nfunction requiredAuthorityDigest(authority: ToolCatalogAuthority): string {\n if (authority.authorityDigest === undefined) {\n throw new TypeError('Catalog materialization requires an authority digest');\n }\n return authority.authorityDigest;\n}\n\nfunction digestCatalog(authorityDigest: string, entries: readonly ToolCatalogEntry[]): string {\n return `sha256:${createHash('sha256')\n .update(JSON.stringify({ authorityDigest, entries }))\n .digest('hex')}`;\n}\n\nfunction digestAuthority(bytes: readonly Uint8Array[]): string {\n const hash = createHash('sha256');\n for (const value of bytes) hash.update(value);\n return `sha256:${hash.digest('hex')}`;\n}\n\nfunction projectionValid(\n catalog: unknown,\n authorityDigest: string,\n descriptors: readonly ToolDescriptor[] = defaultToolDescriptors,\n): catalog is ToolCatalog {\n if (catalog === null || typeof catalog !== 'object') return false;\n const value = catalog as Partial<ToolCatalog>;\n const expectedEntries = descriptors\n .map(projectDescriptor)\n .sort((left, right) => left.id.localeCompare(right.id));\n return (\n value.schemaVersion === '1.0.0' &&\n value.authorityDigest === authorityDigest &&\n Array.isArray(value.entries) &&\n JSON.stringify(value.entries) === JSON.stringify(expectedEntries) &&\n value.digest === digestCatalog(authorityDigest, value.entries as ToolCatalogEntry[])\n );\n}\n\nexport function createProjectToolCatalogAuthority(\n rootInput: string,\n descriptors: readonly ToolDescriptor[] = defaultToolDescriptors,\n): ToolCatalogAuthority {\n const root = resolve(rootInput);\n return {\n root,\n projectionPath: resolve(root, '.forgeax/generated/tool-catalog.json'),\n async read() {\n const [forge, packageJson] = await Promise.all([\n readFile(resolve(root, 'forge.json')),\n readFile(resolve(root, 'package.json')),\n ]);\n return { authorityDigest: digestAuthority([forge, packageJson]), descriptors };\n },\n };\n}\n\nexport async function loadToolCatalog(\n authority: ToolCatalogAuthority,\n descriptors: readonly ToolDescriptor[] = defaultToolDescriptors,\n): Promise<ToolCatalogLoadResult> {\n const read = authority.read;\n if (read === undefined) {\n if (authority.authorityDigest === undefined) {\n return {\n ok: false,\n error: {\n code: 'tool-catalog-authority-unreadable',\n expected: 'an injectable project authority reader',\n hint: 'Create a project authority from a real project root before listing tools.',\n detail: { reason: 'authority reader is missing' },\n },\n };\n }\n return { ok: true, value: materializeToolDescriptorCatalog(descriptors, authority) };\n }\n let snapshot: ToolCatalogAuthoritySnapshot;\n try {\n snapshot = await read();\n } catch (cause) {\n return {\n ok: false,\n error: {\n code: 'tool-catalog-authority-unreadable',\n expected: 'project authority files to be readable',\n hint: 'Repair forge.json and package.json, then retry catalog rebuild.',\n detail: { reason: cause instanceof Error ? cause.message : String(cause) },\n },\n };\n }\n const projectionPath = authority.projectionPath;\n if (projectionPath !== undefined) {\n try {\n const current = JSON.parse(await readFile(projectionPath, 'utf8')) as unknown;\n if (projectionValid(current, snapshot.authorityDigest, snapshot.descriptors)) {\n return { ok: true, value: current };\n }\n } catch {\n // Missing or corrupt projections are rebuilt from the authority below.\n }\n }\n const catalog = materializeToolDescriptorCatalog(snapshot.descriptors, {\n authorityDigest: snapshot.authorityDigest,\n });\n if (projectionPath !== undefined) {\n try {\n await mkdir(resolve(projectionPath, '..'), { recursive: true });\n await writeFile(projectionPath, `${JSON.stringify(catalog, null, 2)}\\n`, 'utf8');\n } catch (cause) {\n return {\n ok: false,\n error: {\n code: 'tool-catalog-projection-invalid',\n expected: 'the generated catalog projection to be writable',\n hint: 'Restore write access to .forgeax/generated and retry cold rebuild.',\n detail: { reason: cause instanceof Error ? cause.message : String(cause) },\n },\n };\n }\n }\n return { ok: true, value: catalog };\n}\n\nexport function materializeToolCatalog<TArgs, TResult>(\n contributions: readonly ToolContribution<TArgs, TResult>[],\n authority: ToolCatalogAuthority,\n): ToolCatalog;\nexport function materializeToolCatalog(\n contributions: readonly unknown[],\n authority: ToolCatalogAuthority,\n): ToolCatalog;\nexport function materializeToolCatalog(\n contributions: readonly unknown[],\n authority: ToolCatalogAuthority,\n): ToolCatalog {\n const entries = contributions\n .map((candidate) => {\n if (typeof candidate !== 'object' || candidate === null)\n throw new TypeError('Invalid tool contribution');\n return projectDescriptor((candidate as ToolContribution<unknown, unknown>).descriptor);\n })\n .sort((left, right) => left.id.localeCompare(right.id));\n const authorityDigest = requiredAuthorityDigest(authority);\n return {\n schemaVersion: '1.0.0',\n authorityDigest,\n digest: digestCatalog(authorityDigest, entries),\n entries,\n };\n}\n\nexport function materializeToolDescriptorCatalog(\n descriptors: readonly ToolDescriptor[],\n authority: ToolCatalogAuthority,\n): ToolCatalog {\n const entries = descriptors\n .map(projectDescriptor)\n .sort((left, right) => left.id.localeCompare(right.id));\n const authorityDigest = requiredAuthorityDigest(authority);\n return {\n schemaVersion: '1.0.0',\n authorityDigest,\n digest: digestCatalog(authorityDigest, entries),\n entries,\n };\n}\n\nexport function rebuildToolCatalog<TArgs, TResult>(\n contributions: readonly ToolContribution<TArgs, TResult>[],\n current: ToolCatalog | undefined,\n authority: ToolCatalogAuthority,\n): ToolCatalog;\nexport function rebuildToolCatalog(\n contributions: readonly unknown[],\n current: ToolCatalog | undefined,\n authority: ToolCatalogAuthority,\n): ToolCatalog {\n if (\n current !== undefined &&\n authority.authorityDigest !== undefined &&\n current.authorityDigest === authority.authorityDigest &&\n projectionValid(current, authority.authorityDigest)\n )\n return current;\n if (authority.authorityDigest === undefined) {\n throw new TypeError('Catalog rebuild requires an authority digest');\n }\n return materializeToolCatalog(contributions, authority);\n}\n\nexport function listTools(catalog: ToolCatalog): readonly ToolCatalogEntry[] {\n return catalog.entries;\n}\n\nexport function describeTool(catalog: ToolCatalog, id: string): ToolCatalogEntry | undefined {\n return catalog.entries.find((entry) => entry.id === id);\n}\n","import {\n domainFailureError,\n type ToolDomainFailure,\n type ToolTerminal,\n} from '@forgeax/engine-tool-runtime';\n\nexport const retiredPreviewOperationFailure: ToolDomainFailure = {\n code: 'preview-operation-migrated',\n expected: 'a domain-specific preview contribution selected from the project catalog',\n hint: 'Use material.preview, mesh.preview, vfx.preview, or texture.preview with a Project GUID.',\n detail: {\n operation: 'preview.run',\n replacements: ['material.preview', 'mesh.preview', 'vfx.preview', 'texture.preview'],\n },\n};\n\nexport function retiredPreviewTool(): ToolTerminal<never> {\n return {\n outcome: 'failed',\n failure: domainFailureError(\n retiredPreviewOperationFailure.code,\n retiredPreviewOperationFailure.expected,\n retiredPreviewOperationFailure.hint,\n retiredPreviewOperationFailure.detail,\n ),\n artifacts: [],\n };\n}\n","import { readFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { Context, isToolPlugin, type ToolPlugin } from '@forgeax/engine-plugin';\nimport {\n type GamePluginEntry,\n installCatalogLoader,\n type PluginCatalog,\n type PluginRealm,\n projectPluginEntries,\n} from '@forgeax/engine-plugin/loader';\nimport { type GameProjectPluginEntry, GameProjectSchema } from '@forgeax/engine-project';\nimport type {\n ToolContribution,\n ToolEvidenceKind,\n ToolRunOptions,\n ToolTerminal,\n} from '@forgeax/engine-tool-runtime';\nimport { createServer, type ViteDevServer } from 'vite';\n\nexport interface ProjectToolBinding {\n readonly contribution: ToolContribution<unknown, unknown>;\n readonly entry: GameProjectPluginEntry;\n readonly moduleName: string;\n readonly realm: PluginRealm;\n readonly toolPlugin?: ToolPlugin;\n readonly loadToolPlugin: () => Promise<ToolPlugin>;\n}\n\nexport interface ProjectToolModuleLoader {\n readonly load: (name: string) => Promise<unknown>;\n readonly close: () => Promise<void>;\n}\n\nexport interface ProjectToolDiscoveryOptions {\n readonly moduleLoader?: ProjectToolModuleLoader;\n readonly loadModules?: boolean;\n}\n\ninterface ProjectPluginLeaf {\n readonly entry: GameProjectPluginEntry;\n readonly moduleName: string;\n readonly realm: PluginRealm;\n}\n\ninterface StaticToolDeclaration {\n readonly id: string;\n readonly title: string;\n readonly summary: string;\n readonly realm: PluginRealm;\n readonly argsSchema?: string;\n readonly resultSchema?: string;\n readonly evidence?: readonly ToolEvidenceKind[];\n}\n\nfunction projectLeaves(\n entries: readonly GameProjectPluginEntry[],\n inheritedRealm: PluginRealm = 'engine',\n): ProjectPluginLeaf[] {\n const leaves: ProjectPluginLeaf[] = [];\n for (const entry of entries) {\n const realm = entry.realm ?? inheritedRealm;\n if (entry.disabled === true) continue;\n if (entry.group === true) {\n leaves.push(...projectLeaves(entry.config as readonly GameProjectPluginEntry[], realm));\n continue;\n }\n if (!entry.name.startsWith('cordis:')) {\n leaves.push({ entry, moduleName: entry.name, realm });\n }\n }\n return leaves;\n}\n\nfunction exportedToolPlugin(module: unknown): ToolPlugin | undefined {\n if (isToolPlugin(module)) return module;\n if (typeof module !== 'object' || module === null) return undefined;\n const value = Reflect.get(module, 'default');\n return isToolPlugin(value) ? value : undefined;\n}\n\nfunction staticContributions(\n entry: GameProjectPluginEntry,\n): readonly ToolContribution<unknown, unknown>[] {\n if (entry.config === null || typeof entry.config !== 'object') return [];\n const tools = Reflect.get(entry.config, 'tools');\n if (!Array.isArray(tools)) return [];\n return tools.flatMap((candidate: unknown) => {\n if (candidate === null || typeof candidate !== 'object') return [];\n const declaration = candidate as Partial<StaticToolDeclaration>;\n if (\n typeof declaration.id !== 'string' ||\n typeof declaration.title !== 'string' ||\n typeof declaration.summary !== 'string' ||\n (declaration.realm !== 'build' &&\n declaration.realm !== 'host' &&\n declaration.realm !== 'engine')\n )\n return [];\n const descriptor = {\n id: declaration.id,\n title: declaration.title,\n summary: declaration.summary,\n realm: declaration.realm,\n argsSchema: {\n parse: (value: unknown) => ({ ok: true as const, value }),\n ...(declaration.argsSchema === undefined ? {} : { describe: declaration.argsSchema }),\n },\n resultSchema: {\n parse: (value: unknown) => ({ ok: true as const, value }),\n ...(declaration.resultSchema === undefined ? {} : { describe: declaration.resultSchema }),\n },\n evidence: declaration.evidence ?? [],\n };\n return [\n {\n descriptor,\n execute: async () => ({\n ok: false as const,\n error: { code: 'tool-static-descriptor', detail: {} },\n }),\n },\n ];\n });\n}\n\nfunction hasStaticToolDeclarations(entry: GameProjectPluginEntry): boolean {\n if (entry.config === null || typeof entry.config !== 'object') return false;\n return Array.isArray(Reflect.get(entry.config, 'tools'));\n}\n\nasync function createViteModuleLoader(root: string): Promise<ProjectToolModuleLoader> {\n const server: ViteDevServer = await createServer({\n root,\n appType: 'custom',\n configFile: false,\n logLevel: 'silent',\n server: { middlewareMode: true },\n });\n return {\n load(name) {\n const id = name.startsWith('.') ? `/@fs/${resolve(root, name)}` : name;\n return server.ssrLoadModule(id);\n },\n close: () => server.close(),\n };\n}\n\nasync function readProjectEntries(root: string): Promise<readonly GameProjectPluginEntry[]> {\n const raw = JSON.parse(await readFile(resolve(root, 'forge.json'), 'utf8')) as unknown;\n const parsed = GameProjectSchema.safeParse(raw);\n if (!parsed.success) {\n throw new TypeError(`Invalid forge.json: ${parsed.error.message}`);\n }\n return parsed.data.plugins ?? [];\n}\n\nexport async function discoverProjectTools(\n rootInput: string,\n options: ProjectToolDiscoveryOptions = {},\n): Promise<readonly ProjectToolBinding[]> {\n const root = resolve(rootInput);\n const loadModules = options.loadModules ?? true;\n const loader = loadModules\n ? (options.moduleLoader ?? (await createViteModuleLoader(root)))\n : undefined;\n try {\n const bindings: ProjectToolBinding[] = [];\n const ids = new Map<string, string>();\n for (const leaf of projectLeaves(await readProjectEntries(root))) {\n if (leaf.realm !== 'build' && leaf.realm !== 'host' && leaf.realm !== 'engine') continue;\n // Gameplay entries are part of the engine closure, not the tool catalog. They\n // are only evaluated when they explicitly publish static tool declarations;\n // this keeps discovery from importing an unrelated gameplay module.\n if (leaf.realm === 'engine' && !hasStaticToolDeclarations(leaf.entry)) continue;\n const toolPlugin = loadModules\n ? exportedToolPlugin(await (loader as ProjectToolModuleLoader).load(leaf.moduleName))\n : undefined;\n const contributions = toolPlugin?.tools ?? staticContributions(leaf.entry);\n for (const contribution of contributions) {\n if (contribution.descriptor.realm !== leaf.realm) {\n throw new TypeError(\n `Tool ${contribution.descriptor.id} declares ${contribution.descriptor.realm} but Entry ${leaf.entry.id} owns ${leaf.realm}`,\n );\n }\n const existing = ids.get(contribution.descriptor.id);\n if (existing !== undefined) {\n throw new TypeError(\n `Duplicate project tool id ${contribution.descriptor.id} from ${existing} and ${leaf.entry.id}`,\n );\n }\n ids.set(contribution.descriptor.id, leaf.entry.id);\n bindings.push({\n contribution,\n entry: leaf.entry,\n moduleName: leaf.moduleName,\n realm: leaf.realm,\n ...(toolPlugin === undefined ? {} : { toolPlugin }),\n loadToolPlugin: async () => {\n if (toolPlugin !== undefined) return toolPlugin;\n const selectedLoader = options.moduleLoader ?? (await createViteModuleLoader(root));\n try {\n const loaded = exportedToolPlugin(await selectedLoader.load(leaf.moduleName));\n if (loaded === undefined)\n throw new TypeError(`Entry ${leaf.entry.id} does not export a ToolPlugin`);\n return loaded;\n } finally {\n await selectedLoader.close();\n }\n },\n });\n }\n }\n return bindings;\n } finally {\n if (loader !== undefined) await loader.close();\n }\n}\n\nfunction activationFailure(cause: unknown): ToolTerminal<never> {\n const message = cause instanceof Error ? cause.message : String(cause);\n return {\n outcome: 'failed',\n failure: {\n code: 'tool-domain-failed',\n expected: 'the owning project plugin Fiber to become ready',\n hint: 'Repair the project Entry, plugin dependencies, or plugin apply failure before retrying.',\n detail: { code: 'tool-plugin-activation-failed', payload: message },\n },\n artifacts: [],\n };\n}\n\nexport async function runProjectTool(\n binding: ProjectToolBinding,\n args: unknown,\n options: ToolRunOptions,\n): Promise<ToolTerminal<unknown>> {\n const ctx = new Context();\n try {\n const toolPlugin = await binding.loadToolPlugin();\n const contribution = toolPlugin.tools.find(\n (candidate) => candidate.descriptor.id === binding.contribution.descriptor.id,\n );\n if (contribution === undefined)\n return activationFailure(new Error('selected tool is absent from Entry'));\n const catalog: PluginCatalog = new Map([\n [\n binding.moduleName,\n {\n realm: binding.realm,\n load: async () => ({ default: toolPlugin }),\n },\n ],\n ]);\n const { loader } = await installCatalogLoader(ctx, catalog, binding.realm);\n const entries = projectPluginEntries(\n [binding.entry as GamePluginEntry],\n binding.realm,\n binding.realm,\n );\n await loader.root.update(entries);\n await loader.await();\n const { createToolRuntime } = await import('@forgeax/engine-tool-runtime');\n const { createContextCapabilityResolver } = await import('@forgeax/engine-plugin');\n return await createToolRuntime([contribution]).run(contribution, args, {\n ...options,\n capabilityResolver: createContextCapabilityResolver(ctx),\n }).terminal;\n } catch (cause) {\n return activationFailure(cause);\n } finally {\n await ctx.fiber.dispose();\n }\n}\n","import {\n type PreviewArtifactManifest,\n type PreviewArtifactRole,\n validatePreviewArtifactManifest,\n} from '@forgeax/engine-preview';\nimport {\n type ToolArtifactManifest,\n type ToolDomainFailure,\n type ToolEvidenceKind,\n validateArtifactManifest,\n} from '@forgeax/engine-tool-runtime';\n\nexport interface OfflineAnalysisRequest {\n readonly manifest: PreviewArtifactManifest | ToolArtifactManifest;\n readonly required?: readonly (PreviewArtifactRole | ToolEvidenceKind)[];\n}\n\nexport interface OfflineAnalysisResult {\n readonly runId: string;\n readonly captureId: string;\n readonly artifacts: readonly { readonly kind: string; readonly digest: string }[];\n}\n\nexport function analyzePreviewArtifacts(\n request: OfflineAnalysisRequest,\n):\n | { readonly ok: true; readonly value: OfflineAnalysisResult }\n | { readonly ok: false; readonly error: ToolDomainFailure } {\n const required = request.required ?? [];\n const validated =\n request.manifest.schemaVersion === '1.0.0'\n ? required.some((kind) => kind !== 'rhi-tape' && kind !== 'png' && kind !== 'profile-capture')\n ? {\n ok: false as const,\n error: {\n code: 'tool-artifact-manifest-invalid',\n expected: 'requested evidence kinds to belong to the v1 artifact manifest',\n hint: 'Request one of rhi-tape, png, or profile-capture for a v1 manifest.',\n detail: { reason: 'unsupported required evidence kind' },\n },\n }\n : validateArtifactManifest(request.manifest, required as readonly ToolEvidenceKind[])\n : validatePreviewArtifactManifest(\n request.manifest,\n (request.required ?? []).filter(\n (role): role is PreviewArtifactRole =>\n role === 'report' ||\n role === 'rhi-tape' ||\n role === 'capture' ||\n role === 'fresh-replay' ||\n role === 'profile-capture' ||\n role === 'contact-sheet',\n ),\n );\n if (!validated.ok) return { ok: false, error: validated.error as ToolDomainFailure };\n return {\n ok: true,\n value: {\n runId: request.manifest.identity.runId,\n captureId: request.manifest.identity.captureId,\n artifacts: request.manifest.artifacts.map(({ kind, digest }) => ({ kind, digest })),\n },\n };\n}\n","import {\n createMaterialPreviewContribution,\n createMeshPreviewContribution,\n createTexturePreviewContribution,\n createVfxPreviewContribution,\n} from '@forgeax/engine-preview';\nimport { defineTool, type ToolContribution } from '@forgeax/engine-tool-runtime';\nimport { previewOfflineAnalysisDescriptor, previewRunDescriptor } from './catalog.js';\nimport {\n analyzePreviewArtifacts,\n type OfflineAnalysisRequest,\n type OfflineAnalysisResult,\n} from './offline-analysis.js';\nimport type { PreviewHostRequest, PreviewHostResult } from './preview-host.js';\nimport { retiredPreviewOperationFailure } from './preview-migration.js';\n\nexport function createPreviewContribution(): ToolContribution<\n PreviewHostRequest,\n PreviewHostResult\n> {\n return defineTool(previewRunDescriptor, async () => ({\n ok: false as const,\n error: retiredPreviewOperationFailure,\n }));\n}\n\nexport function createOfflineAnalysisContribution(): ToolContribution<\n OfflineAnalysisRequest,\n OfflineAnalysisResult\n> {\n return defineTool(\n {\n ...previewOfflineAnalysisDescriptor,\n },\n (request) => analyzePreviewArtifacts(request),\n );\n}\n\nexport function createPreviewContributions(): readonly ToolContribution<unknown, unknown>[] {\n return [\n createPreviewContribution() as ToolContribution<unknown, unknown>,\n createOfflineAnalysisContribution() as ToolContribution<unknown, unknown>,\n ];\n}\n\n/**\n * The discoverable preview surface is domain-specific. The generic recipe\n * contribution remains available only as an explicit migration error.\n */\nexport function createDomainPreviewContributions(): readonly ToolContribution<unknown, unknown>[] {\n return [\n createMaterialPreviewContribution() as ToolContribution<unknown, unknown>,\n createMeshPreviewContribution() as ToolContribution<unknown, unknown>,\n createVfxPreviewContribution() as ToolContribution<unknown, unknown>,\n createTexturePreviewContribution() as ToolContribution<unknown, unknown>,\n ];\n}\n","import {\n defineTool,\n type JsonValue,\n type ToolContribution,\n type ToolDomainFailure,\n} from '@forgeax/engine-tool-runtime';\nimport type { BuildOptions, PluginInstallOptions } from '../types.js';\nimport { authorPluginInstallDescriptor, projectBuildDescriptor } from './catalog.js';\nimport { createDomainPreviewContributions } from './preview-contributions.js';\n\n// The historical createPreviewContributions helper is private proof code; the\n// discoverable default path intentionally uses domain contributions instead.\n\nfunction commandFailure(error: {\n readonly code: string;\n readonly expected: string;\n readonly hint: string;\n readonly detail: Record<string, unknown>;\n}): { readonly ok: false; readonly error: ToolDomainFailure } {\n return { ok: false, error: { ...error, detail: error.detail as unknown as JsonValue } };\n}\n\nexport function createBuildContribution(\n projectRoot = process.cwd(),\n): ToolContribution<BuildOptions, unknown> {\n return defineTool(\n projectBuildDescriptor as typeof projectBuildDescriptor & {\n readonly argsSchema: import('@forgeax/engine-tool-runtime').ToolSchema<BuildOptions>;\n },\n async (options) => {\n const { buildCommand } = await import('../commands.js');\n const result = await buildCommand({ ...options, root: options.root ?? projectRoot });\n return result.ok ? result.value : commandFailure(result.error);\n },\n );\n}\n\nexport function createAuthorContribution(\n projectRoot = process.cwd(),\n): ToolContribution<PluginInstallOptions, unknown> {\n return defineTool(\n authorPluginInstallDescriptor as typeof authorPluginInstallDescriptor & {\n readonly argsSchema: import('@forgeax/engine-tool-runtime').ToolSchema<PluginInstallOptions>;\n },\n async (options) => {\n const { pluginInstallCommand } = await import('../plugin-authoring.js');\n const result = await pluginInstallCommand({ ...options, root: options.root ?? projectRoot });\n return result.ok ? result.value : commandFailure(result.error);\n },\n );\n}\n\nexport function createDefaultContributions(\n projectRoot = process.cwd(),\n): readonly (\n | ToolContribution<BuildOptions, unknown>\n | ToolContribution<PluginInstallOptions, unknown>\n | ToolContribution<unknown, unknown>\n)[] {\n return [\n createBuildContribution(projectRoot),\n createAuthorContribution(projectRoot),\n ...createDomainPreviewContributions(),\n ];\n}\n","import {\n createToolRuntime,\n type ToolContribution,\n type ToolRuntime,\n} from '@forgeax/engine-tool-runtime';\nimport { createPreviewContributions } from './preview-contributions.js';\n\nexport function createDevkitToolRuntime<TArgs, TResult>(\n contributions: readonly ToolContribution<TArgs, TResult>[],\n): ToolRuntime;\nexport function createDevkitToolRuntime(contributions: readonly unknown[]): ToolRuntime;\nexport function createDevkitToolRuntime(contributions: readonly unknown[]): ToolRuntime {\n return createToolRuntime(contributions);\n}\n\nexport function createPreviewToolRuntime(): ToolRuntime {\n return createToolRuntime(createPreviewContributions());\n}\n","export {\n assetAddCommand,\n assetInspectCommand,\n assetListCommand,\n assetVerifyCommand,\n browserCaptureCommand,\n buildCommand,\n createCliRhiDebugOperationContext,\n devCommand,\n doctorCommand,\n engineDoctorCommand,\n engineStatusCommand,\n engineUnlinkCommand,\n engineUseLocalCommand,\n initCommand,\n newCommand,\n packageCommand,\n pluginInstallCommand,\n pluginUninstallCommand,\n previewCommand,\n runRhiDebugCommand,\n sdkInstallCommand,\n shaderCheckCommand,\n skillInstallCommand,\n skillVerifyCommand,\n softwareCaptureCommand,\n testCommand,\n} from './commands.js';\nexport { verifyDist, writeDistManifest } from './dist.js';\nexport type {\n EngineBinding,\n EngineBindingCommandOptions,\n EngineBindingMode,\n EnginePackageStatus,\n EngineStatusReport,\n EngineWorkspaceStatus,\n} from './engine-binding.js';\nexport {\n ENGINE_BINDING_SCHEMA_VERSION,\n engineBindingFilePath,\n inspectEngineWorkspace,\n readEngineBinding,\n} from './engine-binding.js';\nexport type { BootstrapRoot } from './host/base-host.js';\nexport type { ProjectBootstrapPlan } from './host/project-bootstrap.js';\nexport type {\n ResourceBootstrapPlan,\n ResourceBootstrapTrace,\n} from './host/resource-bootstrap.js';\nexport { createInitPlan } from './init.js';\nexport { readProjectFacts } from './project.js';\nexport type {\n ArtifactRef,\n CapturedRhiTape,\n RhiCaptureFrameValue,\n RhiDebugOperationContext,\n RhiDebugOperationDescriptor,\n RhiDebugOperationInput,\n RhiDebugOperationName,\n RhiDebugOperationOutput,\n RhiInspectInput,\n RhiInspectOutput,\n RhiSummaryInput,\n RhiSummaryOutput,\n} from './rhi-debug/operations.js';\nexport {\n createRhiDebugOperationContext,\n discoverRhiDebugOperations,\n RHI_DEBUG_OPERATION_MANIFEST,\n recoverRhiDebugError,\n renderRhiDebugHelp,\n runRhiDebugOperation,\n} from './rhi-debug/operations.js';\nexport type {\n BrowserCapture,\n BrowserCaptureCheckpointOptions,\n BrowserCaptureOpenOptions,\n BrowserCaptureRecord,\n BrowserCaptureRunReport,\n BrowserCaptureRuntimeWitness,\n CapturePixelWitness,\n SoftwareBrowser,\n SoftwareBrowserOpenOptions,\n SoftwareBrowserSession,\n SoftwareCaptureCheckpointOptions,\n SoftwareCaptureRecord,\n SoftwareCaptureRunReport,\n SoftwareCaptureRuntimeWitness,\n} from './software-capture.js';\nexport { createBrowserCapture, createSoftwareBrowser } from './software-capture.js';\nexport {\n type AdmissionThresholds,\n type BenchmarkAdmissionReport,\n type BenchmarkMeasurement,\n type BenchmarkRecipe,\n type BenchmarkSample,\n createAdmissionReport,\n DEFAULT_ADMISSION_THRESHOLDS,\n runBenchmarkAdmission,\n summarizeBenchmarkSamples,\n} from './tools/benchmark/index.js';\nexport {\n bootstrapRealm,\n type RealmBootstrapInput,\n type RealmBootstrapResult,\n type RealmLifecycleAdapter,\n type RealmLifecycleHandle,\n} from './tools/bootstrap.js';\nexport { createServiceCache, type ServiceCache, type ServiceCacheEntry } from './tools/cache.js';\nexport {\n createServiceCapability,\n type ServiceAdmissionExpectation,\n type ServiceAdmissionRef,\n type ServiceCapability,\n} from './tools/capability.js';\nexport {\n type CarrierProvider,\n type CarrierProviderService,\n type CarrierProviderServiceOptions,\n createCarrierProvider,\n createCarrierProviderService,\n} from './tools/carrier-provider.js';\nexport {\n type CarrierRendezvous,\n type CarrierRendezvousOptions,\n createCarrierRendezvous,\n} from './tools/carrier-rendezvous.js';\nexport {\n describeTool,\n listTools,\n materializeToolCatalog,\n rebuildToolCatalog,\n} from './tools/catalog.js';\nexport { runGenericTool, runNamedTool } from './tools/cli-adapter.js';\nexport {\n createToolClient,\n type ToolClient,\n type ToolClientOptions,\n} from './tools/client.js';\nexport type { ForgeaXExecContext } from './tools/commands.js';\nexport {\n createAuthorContribution,\n createBuildContribution,\n createDefaultContributions,\n} from './tools/contributions.js';\nexport { runLibraryTool } from './tools/library.js';\nexport {\n createCapabilityToken,\n createMigrationRecipe,\n createMigrationRoster,\n type MigrationCapabilityProbe,\n type MigrationOperation,\n type MigrationPath,\n type MigrationRecipe,\n type MigrationResolution,\n type MigrationResolutionResult,\n type MigrationRosterEntry,\n type MigrationTarget,\n probeMigrationTarget,\n resolveMigration,\n} from './tools/migration.js';\nexport {\n analyzePreviewArtifacts,\n type OfflineAnalysisRequest,\n type OfflineAnalysisResult,\n} from './tools/offline-analysis.js';\nexport {\n createDomainPreviewContributions,\n createOfflineAnalysisContribution,\n createPreviewContribution,\n createPreviewContributions,\n} from './tools/preview-contributions.js';\nexport {\n type PreviewCarrierRoute,\n type PreviewHostRequest,\n type PreviewHostResult,\n type PreviewHostRunner,\n runCarrierPreviewRoute,\n runPreviewHost,\n} from './tools/preview-host.js';\nexport { runPrivateTool } from './tools/private-executor.js';\nexport {\n createRealmCapabilityMatrix,\n createResourceProbe,\n type RealmCapability,\n type RealmCapabilityInput,\n type RealmCapabilityMatrix,\n type ResourceOwner,\n resolveRealmCapability,\n} from './tools/realms.js';\nexport { createDevkitToolRuntime, createPreviewToolRuntime } from './tools/runtime.js';\nexport {\n createServiceExecutor,\n type ServiceExecutor,\n type ServiceExecutorOptions,\n} from './tools/service.js';\nexport {\n type AuthenticatedLoopbackService,\n type AuthenticatedLoopbackServiceOptions,\n type AuthenticatedLoopbackTransport,\n type AuthenticatedLoopbackTransportOptions,\n createAuthenticatedLoopbackService,\n createAuthenticatedLoopbackTransport,\n type ServiceWireHandler,\n type ServiceWireRequest,\n} from './tools/service-transport.js';\nexport type {\n AssetAddOptions,\n AssetInspectOptions,\n BrowserCaptureOptions,\n BuildOptions,\n CaptureBackend,\n CommandEnvelope,\n CommandError,\n CommandResult,\n ForgeaXCommand,\n InitOptions,\n NewOptions,\n PluginInstallOptions,\n PluginUninstallOptions,\n ProjectCommandOptions,\n ProjectFacts,\n ShaderCheckOptions,\n SoftwareCaptureOptions,\n} from './types.js';\nexport { resolveProjectPort } from './types.js';\n","export interface SampleStatistics {\n readonly count: number;\n readonly median: number;\n readonly p95: number;\n readonly max: number;\n}\n\nexport function calculateSampleStatistics(samples: readonly number[]): SampleStatistics {\n if (samples.length === 0) throw new RangeError('benchmark samples must not be empty');\n const sorted = [...samples].sort((left, right) => left - right);\n const medianIndex = (sorted.length - 1) / 2;\n const median = interpolate(sorted, medianIndex);\n const p95 = interpolate(sorted, Math.ceil(sorted.length * 0.95) - 1);\n const max = sorted[sorted.length - 1];\n if (max === undefined) throw new RangeError('benchmark samples must not be empty');\n return { count: sorted.length, median, p95, max };\n}\n\nfunction interpolate(values: readonly number[], index: number): number {\n const lower = Math.floor(index);\n const upper = Math.ceil(index);\n const lowerValue = values[lower];\n const upperValue = values[upper];\n if (lowerValue === undefined || upperValue === undefined) {\n throw new RangeError('benchmark percentile index is out of range');\n }\n return lower === upper ? lowerValue : lowerValue + (upperValue - lowerValue) * (index - lower);\n}\n","import { calculateSampleStatistics, type SampleStatistics } from './statistics.js';\n\nexport interface BenchmarkRecipe {\n readonly snapshotDigest: string;\n readonly backend: string;\n readonly viewport: readonly [number, number];\n readonly inputDigest: string;\n readonly frameCount: number;\n readonly rhiDebug: boolean;\n readonly profiler: boolean;\n readonly carrierRendezvous: boolean;\n readonly digest: string;\n}\n\nexport interface BenchmarkSample {\n readonly mode: 'private' | 'service';\n readonly phase: 'cold' | 'warm';\n readonly durationMs: number;\n readonly peakRssBytes: number;\n readonly exclusivePhasesMs: Readonly<Record<string, number>>;\n readonly rhiDebugOverheadMs: number;\n readonly carrierRendezvousMs: number;\n readonly cleanupPassed: boolean;\n readonly evictionPassed: boolean;\n readonly recipeDigest: string;\n}\n\nexport interface BenchmarkModeReport {\n readonly samples: number;\n readonly durationMs: SampleStatistics;\n readonly peakRssBytes: SampleStatistics;\n readonly cleanupPassed: boolean;\n readonly evictionPassed: boolean;\n readonly exclusivePhasesMs: Readonly<Record<string, SampleStatistics>>;\n}\n\nexport interface AdmissionThresholds {\n readonly sampleCountPerPhase: number;\n readonly medianImprovement: number;\n readonly p95Improvement: number;\n readonly maxRegression: number;\n readonly peakRssMultiplier: number;\n}\n\nexport const DEFAULT_ADMISSION_THRESHOLDS: AdmissionThresholds = {\n sampleCountPerPhase: 30,\n medianImprovement: 0.2,\n p95Improvement: 0.1,\n maxRegression: 0.1,\n peakRssMultiplier: 1.25,\n};\n\nexport interface BenchmarkAdmissionReport {\n readonly schema: 'forgeax.tool-service-admission.v1';\n readonly recipe: BenchmarkRecipe;\n readonly thresholds: AdmissionThresholds;\n readonly order: readonly BenchmarkSample['mode'][];\n readonly private: BenchmarkModeReport;\n readonly service: BenchmarkModeReport;\n readonly valid: boolean;\n readonly admitted: boolean;\n readonly reasons: readonly string[];\n}\n\nexport function summarizeBenchmarkSamples(\n samples: readonly BenchmarkSample[],\n): BenchmarkModeReport {\n if (samples.length === 0) {\n return {\n samples: 0,\n durationMs: { count: 0, median: 0, p95: 0, max: 0 },\n peakRssBytes: { count: 0, median: 0, p95: 0, max: 0 },\n cleanupPassed: false,\n evictionPassed: false,\n exclusivePhasesMs: {},\n };\n }\n const durations = samples.map((sample) => sample.durationMs);\n const rss = samples.map((sample) => sample.peakRssBytes);\n const phaseNames = [\n ...new Set(samples.flatMap((sample) => Object.keys(sample.exclusivePhasesMs))),\n ];\n const exclusivePhasesMs = Object.fromEntries(\n phaseNames.map((phase) => [\n phase,\n calculateSampleStatistics(samples.map((sample) => sample.exclusivePhasesMs[phase] ?? 0)),\n ]),\n );\n return {\n samples: samples.length,\n durationMs: calculateSampleStatistics(durations),\n peakRssBytes: calculateSampleStatistics(rss),\n cleanupPassed: samples.every((sample) => sample.cleanupPassed),\n evictionPassed: samples.every((sample) => sample.evictionPassed),\n exclusivePhasesMs,\n };\n}\n\nexport function createAdmissionReport(\n recipe: BenchmarkRecipe,\n samples: readonly BenchmarkSample[],\n thresholds: AdmissionThresholds = DEFAULT_ADMISSION_THRESHOLDS,\n): BenchmarkAdmissionReport {\n const privateSamples = samples.filter((sample) => sample.mode === 'private');\n const serviceSamples = samples.filter((sample) => sample.mode === 'service');\n const order = samples.map((sample) => sample.mode);\n const privateReport = summarizeBenchmarkSamples(privateSamples);\n const serviceReport = summarizeBenchmarkSamples(serviceSamples);\n const reasons: string[] = [];\n const expectedSamples = thresholds.sampleCountPerPhase * 2;\n const complete =\n privateSamples.length === expectedSamples && serviceSamples.length === expectedSamples;\n if (!complete) {\n reasons.push('sample count is incomplete');\n }\n if (samples.some((sample) => sample.recipeDigest !== recipe.digest)) {\n reasons.push('recipe identity drifted');\n }\n if (!privateReport.cleanupPassed || !serviceReport.cleanupPassed) reasons.push('cleanup failed');\n if (!privateReport.evictionPassed || !serviceReport.evictionPassed)\n reasons.push('eviction failed');\n if (order.some((mode, index) => index > 0 && mode === order[index - 1])) {\n reasons.push('private and service samples were not alternated');\n }\n const medianLimit = privateReport.durationMs.median * (1 - thresholds.medianImprovement);\n const p95Limit = privateReport.durationMs.p95 * (1 - thresholds.p95Improvement);\n const maxLimit = privateReport.durationMs.max * (1 + thresholds.maxRegression);\n const rssLimit = privateReport.peakRssBytes.median * thresholds.peakRssMultiplier;\n if (complete && serviceReport.durationMs.median > medianLimit)\n reasons.push('median improvement threshold missed');\n if (complete && serviceReport.durationMs.p95 > p95Limit)\n reasons.push('p95 improvement threshold missed');\n if (complete && serviceReport.durationMs.max > maxLimit)\n reasons.push('max regression threshold exceeded');\n if (complete && serviceReport.peakRssBytes.median > rssLimit)\n reasons.push('peak RSS threshold exceeded');\n return {\n schema: 'forgeax.tool-service-admission.v1',\n recipe,\n thresholds,\n order,\n private: privateReport,\n service: serviceReport,\n valid:\n complete &&\n !reasons.some((reason) =>\n [\n 'recipe identity drifted',\n 'cleanup failed',\n 'eviction failed',\n 'private and service samples were not alternated',\n ].includes(reason),\n ),\n admitted: reasons.length === 0,\n reasons,\n };\n}\n","import {\n type AdmissionThresholds,\n type BenchmarkAdmissionReport,\n type BenchmarkRecipe,\n type BenchmarkSample,\n createAdmissionReport,\n} from './report.js';\n\nexport interface BenchmarkMeasurement {\n readonly durationMs: number;\n readonly peakRssBytes: number;\n readonly exclusivePhasesMs?: Readonly<Record<string, number>>;\n readonly rhiDebugOverheadMs?: number;\n readonly carrierRendezvousMs?: number;\n readonly cleanupPassed: boolean;\n readonly evictionPassed: boolean;\n}\n\nexport interface BenchmarkHarnessOptions {\n readonly recipe: BenchmarkRecipe;\n readonly measure: (\n mode: BenchmarkSample['mode'],\n phase: BenchmarkSample['phase'],\n index: number,\n ) => Promise<BenchmarkMeasurement> | BenchmarkMeasurement;\n readonly thresholds?: AdmissionThresholds;\n}\n\nexport async function runBenchmarkAdmission(\n options: BenchmarkHarnessOptions,\n): Promise<BenchmarkAdmissionReport> {\n const sampleCount = options.thresholds?.sampleCountPerPhase ?? 30;\n const samples: BenchmarkSample[] = [];\n const phases = ['cold', 'warm'] as const satisfies readonly BenchmarkSample['phase'][];\n const modes = ['private', 'service'] as const satisfies readonly BenchmarkSample['mode'][];\n for (const phase of phases) {\n for (let index = 0; index < sampleCount; index += 1) {\n for (const mode of modes) {\n const measurement = await options.measure(mode, phase, index);\n samples.push({\n mode,\n phase,\n durationMs: measurement.durationMs,\n peakRssBytes: measurement.peakRssBytes,\n exclusivePhasesMs: measurement.exclusivePhasesMs ?? {},\n rhiDebugOverheadMs: measurement.rhiDebugOverheadMs ?? 0,\n carrierRendezvousMs: measurement.carrierRendezvousMs ?? 0,\n cleanupPassed: measurement.cleanupPassed,\n evictionPassed: measurement.evictionPassed,\n recipeDigest: options.recipe.digest,\n });\n }\n }\n }\n return createAdmissionReport(options.recipe, samples, options.thresholds);\n}\n","import type { Context } from '@forgeax/engine-plugin';\nimport {\n bootstrapCatalogLoader,\n type CatalogLoaderBootstrapValue,\n type GamePluginEntry,\n type PluginCatalog,\n type PluginRealm,\n projectPluginEntries,\n} from '@forgeax/engine-plugin/loader';\nimport {\n type RealmCapabilityMatrix,\n validateRealmBootstrapPayload,\n} from '@forgeax/engine-tool-runtime';\nimport {\n createProjectBootstrapPlan,\n type ProjectBootstrapPlan,\n} from '../host/project-bootstrap.js';\nimport {\n createResourceBootstrapPlan,\n type ResourceBootstrapPlan,\n} from '../host/resource-bootstrap.js';\nimport type { ProjectFacts } from '../types.js';\n\nexport interface PreviewBootstrapRoots {\n readonly project: ProjectBootstrapPlan;\n readonly resource: (guid: string) => ResourceBootstrapPlan;\n}\n\n/** Derives both physical roots without sharing project gameplay closure. */\nexport function createPreviewBootstrapRoots(facts: ProjectFacts): PreviewBootstrapRoots {\n return {\n project: createProjectBootstrapPlan(facts),\n resource: (guid) => createResourceBootstrapPlan(facts, guid),\n };\n}\n\nexport interface RealmBootstrapInput {\n readonly realm: PluginRealm;\n readonly catalog: PluginCatalog;\n readonly catalogDigest: string;\n readonly supportedRealms: readonly PluginRealm[];\n readonly entries: readonly GamePluginEntry[];\n readonly payload?: unknown;\n readonly lifecycle?: RealmLifecycleAdapter;\n}\n\nexport interface RealmLifecycleHandle {\n readonly stop: () => Promise<void>;\n}\n\nexport interface RealmLifecycleAdapter {\n readonly start: (input: {\n readonly realm: PluginRealm;\n readonly entries: readonly ReturnType<typeof projectPluginEntries>[number][];\n readonly catalog: PluginCatalog;\n readonly catalogDigest: string;\n }) => Promise<RealmLifecycleHandle>;\n}\n\nexport type RealmBootstrapResult =\n | {\n readonly ok: true;\n readonly value: {\n readonly realm: PluginRealm;\n readonly catalogDigest: string;\n readonly entries: readonly ReturnType<typeof projectPluginEntries>[number][];\n readonly loader?: CatalogLoaderBootstrapValue;\n readonly lifecycle?: RealmLifecycleHandle;\n };\n }\n | { readonly ok: false; readonly error: unknown };\n\n/** Bootstrap one declared realm from the same static Catalog and clone-safe input. */\nexport async function bootstrapRealm(\n ctx: Context | undefined,\n input: RealmBootstrapInput,\n): Promise<RealmBootstrapResult> {\n const cloneSafe = validateRealmBootstrapPayload(input.payload);\n if (!cloneSafe.ok) return cloneSafe;\n if (!input.supportedRealms.includes(input.realm)) {\n return {\n ok: false,\n error: {\n code: 'realm-capability-unavailable',\n realm: input.realm,\n supportedRealms: input.supportedRealms,\n },\n };\n }\n const entries = projectPluginEntries(input.entries, input.realm, input.realm);\n if (input.realm === 'build') {\n if (input.lifecycle === undefined) {\n return {\n ok: false,\n error: {\n code: 'realm-lifecycle-adapter-missing',\n realm: input.realm,\n hint: 'Inject a build lifecycle adapter that owns execution and stop cleanup.',\n },\n };\n }\n const lifecycle = await input.lifecycle.start({\n realm: input.realm,\n entries,\n catalog: input.catalog,\n catalogDigest: input.catalogDigest,\n });\n return {\n ok: true,\n value: { realm: input.realm, catalogDigest: input.catalogDigest, entries, lifecycle },\n };\n }\n if (ctx === undefined) {\n return {\n ok: false,\n error: { code: 'realm-context-missing', realm: input.realm },\n };\n }\n const loaded = await bootstrapCatalogLoader(ctx, input.catalog, input.realm, {\n catalogDigest: input.catalogDigest,\n supportedRealms: input.supportedRealms,\n });\n if (!loaded.ok) return loaded;\n return {\n ok: true,\n value: {\n realm: input.realm,\n catalogDigest: input.catalogDigest,\n entries,\n loader: loaded.value,\n },\n };\n}\n\nexport function assertRealmCapability(matrix: RealmCapabilityMatrix, realm: PluginRealm): void {\n const capability = matrix.realms[realm];\n if (!capability.supported) {\n throw new Error(`realm-capability-unavailable:${realm}`);\n }\n}\n","import type { JsonValue } from '@forgeax/engine-tool-runtime';\n\nexport interface ServiceCacheEntry {\n readonly artifactDigest: string;\n readonly value?: JsonValue;\n}\n\nexport interface ServiceCache {\n readonly get: (key: string) => ServiceCacheEntry | undefined;\n readonly set: (key: string, entry: ServiceCacheEntry) => void;\n readonly evict: (key: string) => boolean;\n readonly clear: () => void;\n readonly size: () => number;\n}\n\nexport function createServiceCache(): ServiceCache {\n const entries = new Map<string, ServiceCacheEntry>();\n return {\n get: (key) => entries.get(key),\n set: (key, entry) => entries.set(key, entry),\n evict: (key) => entries.delete(key),\n clear: () => entries.clear(),\n size: () => entries.size,\n };\n}\n","import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';\nimport type {\n CarrierLeaseRequest,\n CarrierOffer,\n CarrierResult,\n CarrierState,\n CarrierStateMachine,\n ToolTerminal,\n} from '@forgeax/engine-tool-runtime';\n\nexport interface CarrierProvider {\n readonly offer: CarrierOffer;\n readonly accept: (request: CarrierLeaseRequest) => CarrierResult<{ readonly leaseId: string }>;\n readonly started: (leaseId: string) => CarrierResult<CarrierState>;\n readonly exit: (leaseId: string) => CarrierResult<CarrierState>;\n}\n\nexport interface CarrierProviderServiceOptions {\n readonly machine: CarrierStateMachine;\n readonly descriptorDigest: string;\n readonly recipeDigest: string;\n readonly execute: (\n request: CarrierExecutionRequest,\n ) => Promise<ToolTerminal<unknown>> | ToolTerminal<unknown>;\n readonly host?: '127.0.0.1' | 'localhost';\n}\n\n/** Local structural view keeps DevKit source-compatible with an unbuilt runtime dist. */\nexport interface CarrierExecutionRequest {\n readonly leaseId: string;\n readonly descriptorDigest: string;\n readonly recipeDigest: string;\n readonly args: unknown;\n}\n\nexport interface CarrierProviderService {\n readonly endpoint: string;\n readonly offer: CarrierOffer;\n readonly close: () => Promise<void>;\n}\n\ntype WireResult =\n | { readonly ok: true; readonly value: unknown; readonly state: string }\n | { readonly ok: false; readonly error: unknown };\n\nfunction errorResult(\n code: string,\n expected: string,\n hint: string,\n detail: Record<string, unknown> = {},\n): WireResult {\n return { ok: false, error: { code, expected, hint, detail } };\n}\n\nasync function readBody(request: IncomingMessage): Promise<Record<string, unknown>> {\n const chunks: Buffer[] = [];\n for await (const chunk of request) chunks.push(Buffer.from(chunk));\n const value: unknown = JSON.parse(Buffer.concat(chunks).toString('utf8'));\n if (typeof value !== 'object' || value === null || Array.isArray(value))\n throw new Error('carrier request must be an object');\n return value as Record<string, unknown>;\n}\n\nfunction reply(response: ServerResponse, status: number, payload: WireResult): void {\n response.statusCode = status;\n response.setHeader('content-type', 'application/json');\n response.end(JSON.stringify(payload));\n}\n\nexport async function createCarrierProviderService(\n options: CarrierProviderServiceOptions,\n): Promise<CarrierProviderService> {\n const host = options.host ?? '127.0.0.1';\n const bearerToken = options.machine.offer.bearerToken;\n const server = createServer(async (request, response) => {\n if (request.method !== 'POST' || !request.url?.startsWith('/carrier/')) {\n reply(\n response,\n 404,\n errorResult(\n 'carrier-provider-exit',\n 'a carrier protocol route',\n 'Request a fresh visible offer from the provider.',\n ),\n );\n return;\n }\n if (request.headers.authorization !== `Bearer ${bearerToken}`) {\n reply(\n response,\n 401,\n errorResult(\n 'carrier-token-invalid',\n 'the ephemeral bearer token',\n 'Request a fresh authenticated offer; never guess or persist bearer tokens.',\n ),\n );\n return;\n }\n try {\n const body = await readBody(request);\n const route = request.url.slice('/carrier/'.length);\n if (route === 'lease') {\n const result = options.machine.lease({\n consumerId: String(body.consumerId ?? ''),\n bearerToken,\n now: Number(body.now),\n descriptorDigest:\n typeof body.descriptorDigest === 'string' ? body.descriptorDigest : undefined,\n recipeDigest: typeof body.recipeDigest === 'string' ? body.recipeDigest : undefined,\n } as CarrierLeaseRequest);\n reply(response, result.ok ? 200 : 409, result.ok ? result : result);\n return;\n }\n const leaseId = typeof body.leaseId === 'string' ? body.leaseId : '';\n if (route === 'start') {\n const result = options.machine.started(leaseId);\n reply(response, result.ok ? 200 : 409, result.ok ? result : result);\n return;\n }\n if (route === 'exit') {\n const result = options.machine.exit(leaseId);\n reply(response, result.ok ? 200 : 409, result.ok ? result : result);\n return;\n }\n if (route === 'execute') {\n const snapshot = options.machine.snapshot();\n if (snapshot.leaseId !== leaseId || snapshot.state !== 'started') {\n reply(\n response,\n 409,\n errorResult(\n snapshot.state === 'exited' ? 'carrier-exited' : 'carrier-lease-required',\n 'a started carrier lease',\n 'Do not fallback after started; report the structured terminal error and offer a new carrier.',\n ),\n );\n return;\n }\n if (body.descriptorDigest !== options.descriptorDigest) {\n reply(\n response,\n 409,\n errorResult(\n 'carrier-descriptor-mismatch',\n 'the offered descriptor digest',\n 'Rebuild the offer from the current descriptor before retrying.',\n ),\n );\n return;\n }\n if (body.recipeDigest !== options.recipeDigest) {\n reply(\n response,\n 409,\n errorResult(\n 'carrier-recipe-mismatch',\n 'the offered recipe digest',\n 'Serialize a fresh snapshot and request a new carrier before retrying.',\n ),\n );\n return;\n }\n const terminal = await options.execute({\n leaseId,\n descriptorDigest: options.descriptorDigest,\n recipeDigest: options.recipeDigest,\n args: body.args,\n });\n reply(response, 200, { ok: true, value: terminal, state: 'started' });\n return;\n }\n reply(\n response,\n 404,\n errorResult(\n 'carrier-provider-exit',\n 'a carrier protocol route',\n 'Request a fresh visible offer from the provider.',\n ),\n );\n } catch (cause) {\n reply(\n response,\n 400,\n errorResult(\n 'carrier-provider-exit',\n 'a valid carrier request',\n 'Serialize POD only and retry from the last safe snapshot.',\n { cause: cause instanceof Error ? cause.message : String(cause) },\n ),\n );\n }\n });\n await new Promise<void>((resolve, reject) => {\n const onError = (error: Error) => {\n server.off('listening', onListening);\n reject(error);\n };\n const onListening = () => {\n server.off('error', onError);\n resolve();\n };\n server.once('error', onError);\n server.once('listening', onListening);\n server.listen(0, host);\n });\n const address = server.address();\n if (address === null || typeof address === 'string')\n throw new Error('carrier provider did not expose a loopback port');\n const endpoint = `http://${host}:${address.port}/carrier`;\n let closed = false;\n return {\n endpoint,\n offer: options.machine.offer,\n async close() {\n if (closed) return;\n closed = true;\n await new Promise<void>((resolve, reject) =>\n server.close((error) => (error === undefined ? resolve() : reject(error))),\n );\n },\n };\n}\n\nexport function createCarrierProvider(machine: CarrierStateMachine): CarrierProvider {\n return {\n offer: machine.offer,\n accept(request) {\n const result = machine.lease(request);\n if (!result.ok) return result;\n return { ok: true, value: { leaseId: result.value.leaseId }, state: result.state };\n },\n started: machine.started,\n exit: machine.exit,\n };\n}\n","import {\n type CarrierOffer,\n type CarrierStateMachine,\n createCarrierStateMachine,\n} from '@forgeax/engine-tool-runtime';\n\nexport { type CarrierProvider, createCarrierProvider } from './carrier-provider.js';\n\nexport interface CarrierRendezvousOptions {\n readonly presentation: 'hidden' | 'visible';\n readonly projectId: string;\n readonly consumerId: string;\n readonly now: number;\n readonly endpoint?: string;\n readonly ttlMs?: number;\n}\n\nexport interface CarrierRendezvous extends CarrierStateMachine {\n readonly lookup: () => CarrierOffer | undefined;\n readonly lookupCount: number;\n}\n\nexport function createCarrierRendezvous(options: CarrierRendezvousOptions): CarrierRendezvous {\n const machine = createCarrierStateMachine({\n projectId: options.projectId,\n consumerId: options.consumerId,\n endpoint: options.endpoint ?? 'http://127.0.0.1:5740/carrier',\n now: options.now,\n ttlMs: options.ttlMs ?? 30_000,\n });\n let lookupCount = 0;\n const lookup = (): CarrierOffer | undefined => {\n if (options.presentation !== 'visible' || machine.snapshot().state !== 'offered') return;\n lookupCount += 1;\n return machine.offer;\n };\n return {\n ...machine,\n lookup,\n get lookupCount() {\n return lookupCount;\n },\n };\n}\n","import { describeResourcePreviewFailure } from '@forgeax/engine-preview';\nimport {\n capabilityUnavailableError,\n type JsonValue,\n type ToolRuntime,\n type ToolTerminal,\n} from '@forgeax/engine-tool-runtime';\n\nexport function decorateResourcePreviewTerminal<TResult>(\n terminal: ToolTerminal<TResult>,\n): ToolTerminal<TResult> {\n if (terminal.outcome === 'succeeded') return terminal;\n const recovery = describeResourcePreviewFailure(terminal.failure);\n if (recovery === undefined) return terminal;\n if (terminal.failure.code !== 'tool-domain-failed') return terminal;\n return {\n ...terminal,\n failure: {\n ...terminal.failure,\n detail: {\n ...terminal.failure.detail,\n ...(recovery.suggestedOperation === undefined\n ? {}\n : { suggestedOperation: recovery.suggestedOperation }),\n recovery: recovery.actions,\n },\n },\n };\n}\n\nfunction missingTool(id: string): ToolTerminal<never> {\n return {\n outcome: 'failed',\n failure: capabilityUnavailableError(`tool:${id}`, 'build'),\n artifacts: [],\n };\n}\n\nexport function runNamedTool(\n runtime: ToolRuntime,\n id: string,\n args: unknown,\n): Promise<ToolTerminal<unknown>> {\n const contribution = runtime.get(id);\n if (contribution === undefined) return Promise.resolve(missingTool(id));\n return runtime.run(contribution, args).terminal.then(decorateResourcePreviewTerminal);\n}\n\nexport function runGenericTool(\n runtime: ToolRuntime,\n id: string,\n encodedArgs: string,\n): Promise<ToolTerminal<unknown>> {\n let args: JsonValue;\n try {\n args = JSON.parse(encodedArgs) as JsonValue;\n } catch {\n return Promise.resolve({\n outcome: 'failed',\n failure: {\n code: 'tool-invalid-args',\n expected: 'generic CLI arguments to be valid JSON',\n hint: 'Encode one JSON value that conforms to the descriptor argsSchema.',\n detail: { message: 'Invalid JSON', value: null },\n },\n artifacts: [],\n });\n }\n return runNamedTool(runtime, id, args);\n}\n","import {\n createToolRuntime,\n type ToolContribution,\n type ToolRunOptions,\n type ToolTerminal,\n} from '@forgeax/engine-tool-runtime';\nimport {\n createProjectToolCatalogAuthority,\n createRealmDispatch,\n describeTool,\n listTools,\n loadToolCatalog,\n type ToolCatalogEntry,\n type ToolRealmOwner,\n} from './catalog.js';\nimport { decorateResourcePreviewTerminal } from './cli-adapter.js';\nimport { retiredPreviewTool } from './preview-migration.js';\nimport type { ProjectToolBinding, ProjectToolDiscoveryOptions } from './project-tools.js';\n\nexport interface ToolClientOptions extends ProjectToolDiscoveryOptions {\n readonly projectRoot: string;\n /** Optional physical realm owners used by a host/carrier integration. */\n readonly realmOwners?: readonly ToolRealmOwner[];\n /** Injectable builtins for physical host tests and alternate Engine adapters. */\n readonly baseContributions?: readonly ToolContribution[];\n readonly projectDiscovery?: (projectRoot: string) => Promise<readonly ProjectToolBinding[]>;\n}\n\nexport interface ToolClient {\n readonly list: () => readonly ToolCatalogEntry[];\n readonly describe: (id: string) => ToolCatalogEntry | undefined;\n readonly run: <TResult = unknown>(\n id: string,\n args: unknown,\n options?: ToolRunOptions,\n ) => Promise<ToolTerminal<TResult>>;\n}\n\nfunction missingTool(id: string): ToolTerminal<never> {\n return {\n outcome: 'failed',\n failure: {\n code: 'tool-capability-unavailable',\n expected: `tool ${id} to exist in the project-derived catalog`,\n hint: 'Run tool list and choose one of the discovered operation ids.',\n detail: { capability: `tool:${id}`, realm: 'build' },\n },\n artifacts: [],\n };\n}\n\nexport async function createToolClient(options: ToolClientOptions): Promise<ToolClient> {\n const projectDiscovery = options.projectDiscovery;\n const runProjectTool =\n projectDiscovery === undefined\n ? (await import('./project-tools.js')).runProjectTool\n : undefined;\n const builtins =\n options.baseContributions ??\n (await import('./contributions.js')).createDefaultContributions(options.projectRoot);\n const project =\n projectDiscovery === undefined\n ? await (await import('./project-tools.js')).discoverProjectTools(\n options.projectRoot,\n options,\n )\n : await projectDiscovery(options.projectRoot);\n const contributions = [...builtins, ...project.map(({ contribution }) => contribution)];\n const runtime =\n options.baseContributions === undefined\n ? (await import('./runtime.js')).createDevkitToolRuntime(contributions as readonly unknown[])\n : createToolRuntime(contributions as readonly unknown[]);\n const realmDispatch =\n options.realmOwners === undefined\n ? undefined\n : createRealmDispatch(contributions as readonly ToolContribution[], options.realmOwners);\n const bindingById = new Map<string, ProjectToolBinding>(\n project.map((binding) => [binding.contribution.descriptor.id, binding]),\n );\n const descriptors = runtime.list();\n const loaded = await loadToolCatalog(\n createProjectToolCatalogAuthority(options.projectRoot, descriptors),\n descriptors,\n );\n if (!loaded.ok) throw loaded.error;\n return {\n list: () => listTools(loaded.value),\n describe: (id) => describeTool(loaded.value, id),\n async run<TResult = unknown>(id: string, args: unknown, runOptions: ToolRunOptions = {}) {\n if (id === 'preview.run') return retiredPreviewTool() as ToolTerminal<TResult>;\n const contribution = runtime.get(id);\n if (contribution === undefined) return missingTool(id) as ToolTerminal<TResult>;\n const binding = bindingById.get(id);\n const terminal =\n binding !== undefined && runProjectTool !== undefined\n ? await runProjectTool(binding, args, runOptions)\n : realmDispatch === undefined\n ? await runtime.run(contribution, args, runOptions).terminal\n : await realmDispatch.run(id, args, runOptions);\n return decorateResourcePreviewTerminal(terminal as ToolTerminal<TResult>);\n },\n };\n}\n","import {\n createToolRuntime,\n type ToolContribution,\n type ToolRunOptions,\n type ToolTerminal,\n} from '@forgeax/engine-tool-runtime';\n\nexport function runLibraryTool<TArgs, TResult>(\n contribution: ToolContribution<TArgs, TResult>,\n args: TArgs,\n options?: ToolRunOptions,\n): Promise<ToolTerminal<TResult>> {\n return createToolRuntime([contribution]).run(contribution, args, options).terminal;\n}\n","import type { MigrationCapabilityProbe, MigrationOperation } from '@forgeax/engine-tool-runtime';\nimport {\n type ArtifactRef,\n capabilityUnavailableError,\n createServiceCapability,\n type ServiceCapability,\n type ToolEvidenceKind,\n type ToolRealm,\n} from '@forgeax/engine-tool-runtime';\n\nexport {\n createCapabilityToken,\n createMigrationRecipe,\n type MigrationCapabilityProbe,\n type MigrationOperation,\n type MigrationRecipe,\n probeMigrationTarget,\n} from '@forgeax/engine-tool-runtime';\n\nexport type MigrationPath = 'private' | 'service';\n\nexport interface MigrationTarget extends MigrationCapabilityProbe {}\n\nexport interface MigrationRosterEntry {\n readonly operation: MigrationOperation;\n readonly owner: string;\n readonly realm: ToolRealm;\n readonly artifacts: readonly MigrationEvidence[];\n readonly benefit: string;\n readonly fallback: 'private';\n}\n\nexport interface MigrationEvidence {\n readonly owner: string;\n readonly source: 'M3';\n readonly ref: ArtifactRef;\n}\n\nexport interface MigrationResolution {\n readonly path: MigrationPath;\n readonly operation: MigrationOperation;\n readonly owner: string;\n readonly artifacts: readonly MigrationEvidence[];\n readonly service: ServiceCapability;\n}\n\nexport type MigrationResolutionResult =\n | { readonly ok: true; readonly value: MigrationResolution }\n | { readonly ok: false; readonly error: ReturnType<typeof capabilityUnavailableError> };\n\nconst roster: readonly MigrationRosterEntry[] = [\n {\n operation: 'project.preview',\n owner: 'devkit/preview-host',\n realm: 'host',\n artifacts: previewArtifacts(),\n benefit: 'reuse the real WebGPU hidden preview recipe',\n fallback: 'private',\n },\n {\n operation: 'material.preview',\n owner: 'engine-preview/material',\n realm: 'host',\n artifacts: previewArtifacts(),\n benefit: 'preview one material subject through the canonical lit rig',\n fallback: 'private',\n },\n {\n operation: 'mesh.preview',\n owner: 'engine-preview/mesh',\n realm: 'host',\n artifacts: previewArtifacts(),\n benefit: 'preview one mesh subject with every submesh and AABB evidence',\n fallback: 'private',\n },\n {\n operation: 'vfx.preview',\n owner: 'engine-preview/vfx',\n realm: 'host',\n artifacts: previewArtifacts(),\n benefit: 'preview one bounded VFX timeline with compute evidence',\n fallback: 'private',\n },\n {\n operation: 'texture.preview',\n owner: 'engine-preview/texture',\n realm: 'host',\n artifacts: previewArtifacts(),\n benefit: 'preview one texture on the aspect-preserving unlit quad',\n fallback: 'private',\n },\n];\n\nfunction previewArtifacts(): readonly MigrationEvidence[] {\n return [\n {\n owner: 'preview-tool-proof',\n source: 'M3',\n ref: {\n kind: 'rhi-tape',\n digest: 'sha256:e62a302dd29e302e1d0928306fe9c90c47ee336aa2e9e35fdc1d75586ae0018d',\n uri: 'repo:apps/preview/__tests__/tool-proof.recipe.integration.test.ts',\n },\n },\n {\n owner: 'preview-tool-proof',\n source: 'M3',\n ref: {\n kind: 'profile-capture',\n digest: 'sha256:11ec9024e1ea08b38f0901db272847ac402d2dce0c757efe744315608e889c5c',\n uri: 'repo:packages/profiler/src/__tests__/fixtures/profile-capture/model-input.json',\n },\n },\n ];\n}\n\nfunction validEvidence(entry: MigrationRosterEntry): boolean {\n return (\n entry.owner.length > 0 &&\n entry.artifacts.length > 0 &&\n entry.artifacts.every(\n ({ owner, source, ref }) =>\n owner.length > 0 &&\n source === 'M3' &&\n /^sha256:[0-9a-f]{64}$/.test(ref.digest) &&\n typeof ref.uri === 'string' &&\n ref.uri.startsWith('repo:') &&\n isSupportedEvidenceKind(ref.kind),\n )\n );\n}\n\nfunction isSupportedEvidenceKind(kind: ArtifactRef['kind']): kind is ToolEvidenceKind {\n return kind === 'rhi-tape' || kind === 'profile-capture' || kind === 'png';\n}\n\nexport function createMigrationRoster(): readonly MigrationRosterEntry[] {\n return roster.filter(validEvidence).map((entry) => ({\n ...entry,\n artifacts: entry.artifacts.map((artifact) => ({ ...artifact, ref: { ...artifact.ref } })),\n }));\n}\n\nexport function resolveMigration(\n entries: readonly MigrationRosterEntry[],\n operation: MigrationOperation,\n target: MigrationTarget,\n): MigrationResolutionResult {\n const entry = entries.find((candidate) => candidate.operation === operation);\n if (entry === undefined || !validEvidence(entry)) {\n return {\n ok: false,\n error: capabilityUnavailableError(`migration:${operation}`, target.realm),\n };\n }\n if (entry.realm !== target.realm || target.catalogDigest.length === 0) {\n return { ok: false, error: capabilityUnavailableError(`migration:${operation}`, target.realm) };\n }\n if (entry.realm === 'host' && target.rhiBackend !== 'webgpu') {\n return { ok: false, error: capabilityUnavailableError(`rhi:${operation}`, target.realm) };\n }\n const evidenceKinds = entry.artifacts.map(({ ref }) => ref.kind).filter(isSupportedEvidenceKind);\n if (!evidenceKinds.every((kind) => target.evidence.includes(kind))) {\n return { ok: false, error: capabilityUnavailableError(`evidence:${operation}`, target.realm) };\n }\n const service: ServiceCapability = createServiceCapability(undefined, {\n toolId: operation,\n descriptorDigest: entry.artifacts[0]?.ref.digest ?? '',\n recipeDigest: entry.artifacts[0]?.ref.digest ?? '',\n workloadClass: `migration:${operation}`,\n codeDigest: target.catalogDigest,\n browserVersion: 'unavailable',\n backend: 'webgpu',\n });\n return {\n ok: true,\n value: {\n path: service.available ? 'service' : 'private',\n operation,\n owner: entry.owner,\n artifacts: entry.artifacts.map((artifact) => ({ ...artifact, ref: { ...artifact.ref } })),\n service,\n },\n };\n}\n","import { createHash } from 'node:crypto';\nimport { mkdir, mkdtemp, rename, rm, writeFile } from 'node:fs/promises';\nimport { type AddressInfo, createServer as createTcpServer } from 'node:net';\nimport { join, relative, sep } from 'node:path';\nimport type {\n ToolPreviewCaptureResult,\n ToolPreviewRecipe,\n ToolPreviewResourceRequest,\n} from '@forgeax/engine-app';\nimport { createResourcePreviewReport, type ResourcePreviewReport } from '@forgeax/engine-preview';\nimport {\n createPreviewArtifactManifest,\n type JsonValue,\n type PreviewArtifactManifestEntry,\n type SnapshotRef,\n type ToolDomainFailure,\n validatePreviewArtifactManifest,\n} from '@forgeax/engine-tool-runtime';\nimport { type Browser, chromium, type Page } from 'playwright';\nimport { createServer, type ViteDevServer } from 'vite';\nimport type { BootstrapRoot } from '../host/base-host.js';\nimport { createViteConfig } from '../host.js';\nimport { readProjectFacts } from '../project.js';\nimport type { PreviewHostResult } from './preview-host.js';\n\nexport type BrowserHostResult =\n | { readonly ok: true; readonly value: PreviewHostResult }\n | { readonly ok: false; readonly error: ToolDomainFailure };\n\nfunction transportCause(cause: unknown): JsonValue {\n if (cause instanceof Error) {\n return {\n name: cause.name,\n message: cause.message,\n ...(cause.stack === undefined ? {} : { stack: cause.stack }),\n };\n }\n if (cause === undefined) return 'undefined';\n try {\n return JSON.parse(JSON.stringify(cause)) as JsonValue;\n } catch {\n return String(cause);\n }\n}\n\nfunction dataUriBytes(uri: string): Uint8Array {\n const separator = uri.indexOf(',');\n if (separator < 0) throw new TypeError('preview artifact must be a data URI before publication');\n return Buffer.from(uri.slice(separator + 1), 'base64');\n}\n\nfunction projectUri(projectRoot: string, path: string): string {\n return relative(projectRoot, path).split(sep).join('/');\n}\n\nexport interface ResourcePreviewReportInput {\n readonly snapshot: SnapshotRef;\n readonly subject: ResourcePreviewReport['subject'];\n readonly presentation: ResourcePreviewReport['presentation'];\n readonly oracle: ResourcePreviewReport['oracle'];\n}\n\nexport interface BrowserHostOptions {\n readonly publish?: boolean;\n}\n\n/** @internal Vite treats port 0 as its default 5173, not as an OS-assigned port. */\nexport async function allocateLoopbackPort(): Promise<number> {\n const probe = createTcpServer();\n try {\n await new Promise<void>((resolve, reject) => {\n const onError = (error: Error): void => {\n probe.off('listening', onListening);\n reject(error);\n };\n const onListening = (): void => {\n probe.off('error', onError);\n resolve();\n };\n probe.once('error', onError);\n probe.once('listening', onListening);\n probe.listen(0, '127.0.0.1');\n });\n const address = probe.address();\n if (address === null || typeof address === 'string') {\n throw new Error('loopback port probe did not expose a TCP address');\n }\n return address.port;\n } finally {\n if (probe.listening) {\n await new Promise<void>((resolve) => probe.close(() => resolve()));\n }\n }\n}\n\nfunction sha256(bytes: Uint8Array): string {\n return `sha256:${createHash('sha256').update(bytes).digest('hex')}`;\n}\n\nfunction artifactRef(artifact: PreviewArtifactManifestEntry) {\n const kind =\n artifact.kind === 'report' || artifact.kind === 'contact-sheet'\n ? ('tool-result' as const)\n : artifact.kind;\n return {\n kind,\n digest: artifact.digest,\n uri: artifact.uri,\n mediaType: artifact.mediaType,\n sizeBytes: artifact.byteLength,\n };\n}\n\nexport async function publishPreviewArtifacts(\n projectRoot: string,\n runId: string,\n result: PreviewHostResult,\n reportInput?: ResourcePreviewReportInput,\n): Promise<PreviewHostResult> {\n if (result.manifest.identity.runId !== runId) {\n throw new Error(\n `preview artifact run identity mismatch: manifest=${result.manifest.identity.runId} requested=${runId}`,\n );\n }\n const runsRoot = join(projectRoot, '.forgeax', 'tool-runs');\n await mkdir(runsRoot, { recursive: true });\n const directoryName = runId.replace(/[^a-zA-Z0-9._-]/g, '_');\n const published = join(runsRoot, directoryName);\n const finalPaths = {\n tapeJson: join(published, 'rhi-tape.json'),\n tapeBlob: join(published, 'rhi-tape.bin'),\n capturePng: join(published, 'capture.png'),\n freshReplayPng: join(published, 'fresh-replay.png'),\n profile: join(published, 'profile.json'),\n manifest: join(published, 'manifest.json'),\n report: join(published, 'report.json'),\n };\n const tapeJson = dataUriBytes(result.tape.jsonUri);\n const tapeBlob = dataUriBytes(result.tape.blobUri);\n const capturePng = dataUriBytes(result.capturePng.uri);\n const freshReplayPng = dataUriBytes(result.png.uri);\n const profile = dataUriBytes(result.profile.uri);\n const bytesByRole = {\n 'rhi-tape': tapeJson,\n capture: capturePng,\n 'fresh-replay': freshReplayPng,\n 'profile-capture': profile,\n } as const;\n const uriByRole = {\n 'rhi-tape': projectUri(projectRoot, finalPaths.tapeJson),\n capture: projectUri(projectRoot, finalPaths.capturePng),\n 'fresh-replay': projectUri(projectRoot, finalPaths.freshReplayPng),\n 'profile-capture': projectUri(projectRoot, finalPaths.profile),\n } as const;\n const mediaTypeByRole = {\n 'rhi-tape': 'application/vnd.forgeax.rhi-tape+json',\n capture: 'image/png',\n 'fresh-replay': 'image/png',\n 'profile-capture': 'application/vnd.forgeax.profile+json',\n } as const;\n const requiredRoles = ['rhi-tape', 'capture', 'fresh-replay', 'profile-capture'] as const;\n const nonReportArtifacts = result.manifest.artifacts\n .filter((artifact) => artifact.role !== 'report')\n .map((artifact) => {\n if (!(artifact.role in bytesByRole)) {\n return artifact;\n }\n const role = artifact.role as keyof typeof bytesByRole;\n const bytes = bytesByRole[role];\n const digest = sha256(bytes);\n if (artifact.digest !== digest) {\n throw new Error(`preview artifact digest mismatch for ${artifact.role}`);\n }\n return {\n ...artifact,\n uri: uriByRole[role],\n digest,\n byteLength: bytes.byteLength,\n mediaType: mediaTypeByRole[role],\n };\n });\n if (\n requiredRoles.some((role) => !nonReportArtifacts.some((artifact) => artifact.role === role))\n ) {\n throw new Error(\n 'preview publication is missing capture, fresh-replay, tape, or profile artifact',\n );\n }\n let report: ResourcePreviewReport | undefined;\n let reportBytes: Uint8Array | undefined;\n if (reportInput !== undefined) {\n if (reportInput.snapshot.digest !== result.manifest.identity.snapshotDigest) {\n throw new Error('preview report snapshot identity does not match the artifact manifest');\n }\n report = createResourcePreviewReport({\n runId,\n snapshot: reportInput.snapshot,\n subject: reportInput.subject,\n presentation: reportInput.presentation,\n oracle: reportInput.oracle,\n artifacts: nonReportArtifacts,\n });\n reportBytes = new TextEncoder().encode(JSON.stringify(report));\n }\n const reportArtifact: PreviewArtifactManifestEntry | undefined =\n reportBytes === undefined\n ? undefined\n : {\n owner: 'resource-preview',\n kind: 'report',\n role: 'report',\n uri: projectUri(projectRoot, finalPaths.report),\n digest: sha256(reportBytes),\n byteLength: reportBytes.byteLength,\n mediaType: 'application/vnd.forgeax.resource-preview+json',\n derivedFrom: nonReportArtifacts.map((artifact) => artifact.digest),\n };\n const manifest = createPreviewArtifactManifest({\n ...result.manifest,\n artifacts:\n reportArtifact === undefined ? nonReportArtifacts : [reportArtifact, ...nonReportArtifacts],\n });\n const validated = validatePreviewArtifactManifest(\n manifest,\n reportArtifact === undefined ? requiredRoles : ['report', ...requiredRoles],\n );\n if (!validated.ok) throw new Error(JSON.stringify(validated.error.detail));\n const staging = await mkdtemp(join(runsRoot, '.staging-'));\n const paths = {\n tapeJson: join(staging, 'rhi-tape.json'),\n tapeBlob: join(staging, 'rhi-tape.bin'),\n capturePng: join(staging, 'capture.png'),\n freshReplayPng: join(staging, 'fresh-replay.png'),\n profile: join(staging, 'profile.json'),\n manifest: join(staging, 'manifest.json'),\n report: join(staging, 'report.json'),\n };\n try {\n await Promise.all([\n writeFile(paths.tapeJson, tapeJson),\n writeFile(paths.tapeBlob, tapeBlob),\n writeFile(paths.capturePng, capturePng),\n writeFile(paths.freshReplayPng, freshReplayPng),\n writeFile(paths.profile, profile),\n ...(reportBytes === undefined ? [] : [writeFile(paths.report, reportBytes)]),\n ]);\n await writeFile(paths.manifest, `${JSON.stringify(manifest, null, 2)}\\n`);\n await rename(staging, published);\n } catch (cause) {\n await rm(staging, { recursive: true, force: true });\n throw cause;\n }\n return {\n ...result,\n tape: {\n ...result.tape,\n jsonUri: projectUri(projectRoot, finalPaths.tapeJson),\n blobUri: projectUri(projectRoot, finalPaths.tapeBlob),\n },\n profile: { ...result.profile, uri: projectUri(projectRoot, finalPaths.profile) },\n capturePng: { ...result.capturePng, uri: projectUri(projectRoot, finalPaths.capturePng) },\n png: { ...result.png, uri: projectUri(projectRoot, finalPaths.freshReplayPng) },\n manifest,\n artifacts: manifest.artifacts.map(artifactRef),\n };\n}\n\nfunction browserFailure(\n phase: string,\n cause: unknown,\n pageErrors: readonly string[] = [],\n): BrowserHostResult {\n return {\n ok: false,\n error: {\n code: 'tool-preview-browser-host-failed',\n expected: 'a real Chromium page, project bootstrap, WebGPU device, and bounded preview run',\n hint: 'Inspect the Browser Host phase and repair the project or local WebGPU capability.',\n detail: {\n phase,\n cause: transportCause(cause),\n pageErrors,\n },\n },\n };\n}\n\nexport async function runBrowserPreviewHost(\n projectRoot: string,\n recipe: ToolPreviewRecipe,\n snapshot: SnapshotRef,\n runId: string,\n signal: AbortSignal,\n bootstrapRoot: BootstrapRoot = 'project-bootstrap',\n resource?: ToolPreviewResourceRequest,\n options: BrowserHostOptions = {},\n): Promise<BrowserHostResult> {\n const facts = await readProjectFacts(projectRoot);\n if (!facts.ok)\n return { ok: false, error: { ...facts.error, detail: facts.error.detail as never } };\n const config = await createViteConfig(facts.value, 'serve', '/', { bootstrapRoot });\n // A Browser Host is a disposable Vite realm. A shared cache lets adjacent\n // coverage groups observe a partially-written optimized dependency graph.\n // Keep the cache inside the project lifecycle and remove it with the Host.\n const cacheDir = await mkdtemp(join(facts.value.root, '.forgeax', '.browser-host-vite-'));\n let server: ViteDevServer;\n try {\n const port = await allocateLoopbackPort();\n server = await createServer({\n ...config,\n cacheDir,\n logLevel: 'silent',\n optimizeDeps: {\n ...config.optimizeDeps,\n // Tool runs must observe the current workspace build, even when a\n // persistent runner retains Vite's optimized-dependency cache.\n force: true,\n },\n server: {\n ...config.server,\n host: '127.0.0.1',\n port,\n // Vite's port 0 means its default 5173. Bind the probed port exactly so\n // another project or runner cannot be mistaken for this Browser Host.\n strictPort: true,\n },\n });\n } catch (cause) {\n await rm(cacheDir, { recursive: true, force: true });\n throw cause;\n }\n const hostStartedAtMs = performance.now();\n let phase = 'server-listen';\n let browser: Browser | undefined;\n let page: Page | undefined;\n let pageErrors: string[] = [];\n let responseDiagnostics: Promise<void>[] = [];\n const launchBrowser = (headless: boolean): Promise<Browser> =>\n chromium.launch({\n channel: process.env.FORGEAX_CHROME_CHANNEL ?? 'chrome',\n headless,\n args: [\n '--enable-unsafe-webgpu',\n '--enable-features=Vulkan,UseSkiaRenderer,SharedArrayBuffer',\n '--use-vulkan=swiftshader',\n '--use-angle=swiftshader',\n '--disable-vulkan-surface',\n '--ignore-gpu-blocklist',\n '--disable-gpu-driver-bug-workarounds',\n '--disable-dawn-features=disallow_unsafe_apis',\n '--autoplay-policy=no-user-gesture-required',\n ],\n });\n const observePage = (target: Page): void => {\n target.on('pageerror', (error) => pageErrors.push(error.message));\n target.on('console', (message) => {\n if (message.type() === 'error' || message.type() === 'warning') {\n pageErrors.push(`${message.type()}: ${message.text()}`);\n }\n });\n target.on('response', (response) => {\n if (response.status() >= 400) {\n responseDiagnostics.push(\n response\n .text()\n .then((body) => {\n pageErrors.push(`HTTP ${response.status()}: ${response.url()} ${body}`);\n })\n .catch(() => {\n pageErrors.push(`HTTP ${response.status()}: ${response.url()}`);\n }),\n );\n }\n });\n };\n const closeBrowserProcess = async (): Promise<void> => {\n await page?.close().catch(() => undefined);\n page = undefined;\n await browser?.close().catch(() => undefined);\n browser = undefined;\n };\n const abort = (): void => {\n void closeBrowserProcess();\n void server.close();\n };\n signal.addEventListener('abort', abort, { once: true });\n try {\n if (signal.aborted) throw new Error('Browser Host aborted before launch');\n await server.listen();\n const address = server.httpServer?.address() as AddressInfo | null | undefined;\n if (address === null || address === undefined || typeof address === 'string') {\n throw new Error('Vite Browser Host did not expose a loopback TCP address');\n }\n\n phase = 'server-transform';\n const entryTransform = await server.transformRequest('/main.ts');\n if (entryTransform === null) {\n throw new Error('Vite Browser Host entry transform returned no module');\n }\n\n phase = 'capture-browser-launch';\n browser = await launchBrowser(recipe.presentation === 'hidden');\n phase = 'capture-page-bootstrap';\n page = await browser.newPage({\n viewport: recipe.viewport,\n deviceScaleFactor: 1,\n });\n observePage(page);\n const captureUrl = new URL(`http://127.0.0.1:${address.port}/`);\n captureUrl.searchParams.set('forgeax-tool-recipe', JSON.stringify(recipe));\n captureUrl.searchParams.set('forgeax-tool-snapshot', JSON.stringify(snapshot));\n captureUrl.searchParams.set('forgeax-tool-run-id', runId);\n if (resource !== undefined)\n captureUrl.searchParams.set('forgeax-resource-preview', JSON.stringify(resource));\n await page.goto(captureUrl.href, { waitUntil: 'networkidle', timeout: 45_000 });\n await page.waitForFunction(\n () =>\n (\n globalThis as unknown as {\n __forgeaxToolHost?: { readonly ready?: boolean };\n }\n ).__forgeaxToolHost?.ready === true,\n undefined,\n { timeout: 45_000 },\n );\n phase = 'capture-run';\n const captured = await page.evaluate(async () => {\n const host = (\n globalThis as unknown as {\n __forgeaxToolHost: {\n capture(): Promise<\n | { readonly ok: true; readonly result: ToolPreviewCaptureResult }\n | { readonly ok: false; readonly error: ToolDomainFailure }\n >;\n };\n }\n ).__forgeaxToolHost;\n const value = await host.capture();\n return JSON.parse(\n JSON.stringify(value, (_key, nested) =>\n nested instanceof Error\n ? {\n ...nested,\n name: nested.name,\n message: nested.message,\n stack: nested.stack,\n }\n : nested,\n ),\n ) as Awaited<ReturnType<typeof host.capture>>;\n });\n await Promise.all(responseDiagnostics);\n if (!captured.ok) return browserFailure('capture-run', captured.error, pageErrors);\n if (pageErrors.length > 0)\n return browserFailure('capture-page-runtime', pageErrors[0], pageErrors);\n const capturePng = await page.screenshot({ type: 'png' });\n const capturedResult: ToolPreviewCaptureResult = {\n ...captured.result,\n capturePng: {\n uri: `data:image/png;base64,${capturePng.toString('base64')}`,\n width: recipe.viewport.width,\n height: recipe.viewport.height,\n },\n };\n\n await closeBrowserProcess();\n pageErrors = [];\n responseDiagnostics = [];\n\n phase = 'replay-browser-launch';\n browser = await launchBrowser(true);\n phase = 'replay-page-bootstrap';\n page = await browser.newPage({\n viewport: recipe.viewport,\n deviceScaleFactor: 1,\n });\n observePage(page);\n const replayUrl = new URL(`http://127.0.0.1:${address.port}/`);\n replayUrl.searchParams.set('forgeax-tool-replay', '1');\n await page.goto(replayUrl.href, { waitUntil: 'networkidle', timeout: 45_000 });\n await page.waitForFunction(\n () =>\n (\n globalThis as unknown as {\n __forgeaxToolReplayHost?: { readonly ready?: boolean };\n }\n ).__forgeaxToolReplayHost?.ready === true,\n undefined,\n { timeout: 45_000 },\n );\n phase = 'replay-run';\n const result = (await page.evaluate(async (serializedCapture: string): Promise<unknown> => {\n const host = (\n globalThis as unknown as {\n __forgeaxToolReplayHost: {\n run(value: ToolPreviewCaptureResult): Promise<unknown>;\n };\n }\n ).__forgeaxToolReplayHost;\n const value = await host.run(JSON.parse(serializedCapture) as ToolPreviewCaptureResult);\n return JSON.parse(\n JSON.stringify(value, (_key, nested) =>\n nested instanceof Error\n ? {\n ...nested,\n name: nested.name,\n message: nested.message,\n stack: nested.stack,\n }\n : nested,\n ),\n ) as unknown;\n }, JSON.stringify(capturedResult))) as\n | { readonly ok: true; readonly result: PreviewHostResult }\n | { readonly ok: false; readonly error: ToolDomainFailure };\n await Promise.all(responseDiagnostics);\n if (!result.ok) return browserFailure('replay-run', result.error, pageErrors);\n if (pageErrors.length > 0)\n return browserFailure('replay-page-runtime', pageErrors[0], pageErrors);\n\n const endedAtMs = performance.now();\n const phases = result.result.operationTiming.phases;\n const observedDurationMs =\n phases === undefined\n ? 0\n : Object.values(phases).reduce(\n (total, observation) =>\n total + (observation.status === 'observed' ? observation.durationMs : 0),\n 0,\n );\n const durationMs = endedAtMs - hostStartedAtMs;\n const value: PreviewHostResult = {\n ...result.result,\n operationTiming: {\n ...result.result.operationTiming,\n startedAtMs: hostStartedAtMs,\n endedAtMs,\n durationMs,\n ...(phases === undefined\n ? { unattributedMs: durationMs }\n : {\n phases: {\n ...phases,\n transport: {\n status: 'observed',\n durationMs: Math.max(0, durationMs - observedDurationMs),\n },\n },\n unattributedMs: 0,\n }),\n },\n actualCarrier: recipe.presentation === 'hidden' ? 'headless-private' : 'headed-private',\n };\n phase = 'artifact-publish';\n return {\n ok: true,\n value:\n options.publish === false\n ? value\n : await publishPreviewArtifacts(projectRoot, runId, value),\n };\n } catch (cause) {\n await Promise.all(responseDiagnostics);\n return browserFailure(phase, cause, pageErrors);\n } finally {\n signal.removeEventListener('abort', abort);\n await closeBrowserProcess();\n await server.close().catch(() => undefined);\n await rm(cacheDir, { recursive: true, force: true });\n }\n}\n\nexport function runBrowserResourcePreviewHost(\n projectRoot: string,\n recipe: ToolPreviewRecipe,\n snapshot: SnapshotRef,\n runId: string,\n signal: AbortSignal,\n resource: ToolPreviewResourceRequest,\n options: BrowserHostOptions = {},\n): Promise<BrowserHostResult> {\n return runBrowserPreviewHost(\n projectRoot,\n recipe,\n snapshot,\n runId,\n signal,\n 'resource-bootstrap',\n resource,\n options,\n );\n}\n","import {\n createToolPreviewHost,\n createToolPreviewRecipe,\n type ToolPreviewRecipeOptions,\n type ToolPreviewRunResult,\n type ToolPreviewTrace,\n} from '@forgeax/engine-app';\nimport type {\n CarrierLeaseRequest,\n CarrierOffer,\n CarrierResult,\n CarrierState,\n ToolDomainFailure,\n ToolExecutionContext,\n} from '@forgeax/engine-tool-runtime';\nimport { runBrowserPreviewHost } from './browser-host.js';\n\nexport interface PreviewHostRequest {\n readonly recipe: ToolPreviewRecipeOptions;\n readonly projectRoot?: string;\n readonly carrier?: PreviewCarrierRoute;\n}\n\nexport interface PreviewHostMechanisms {\n readonly runId: string;\n readonly projectRoot: string;\n readonly backend: 'webgpu';\n readonly signal: AbortSignal;\n}\n\nexport interface PreviewHostSession {\n readonly withSession: <T>(\n execute: (mechanisms: PreviewHostMechanisms) => Promise<T>,\n ) => Promise<T>;\n}\n\n/**\n * Creates the physical host lease. Domain identity stays in the executor;\n * this seam carries only browser, backend, and lexical run ownership.\n */\nexport function createPreviewHostSession(input: {\n readonly runId: string;\n readonly projectRoot: string;\n readonly signal: AbortSignal;\n}): PreviewHostSession {\n let active = true;\n return {\n async withSession(execute) {\n if (!active || input.signal.aborted) throw new Error('preview-host-session-terminal');\n try {\n return await execute({\n runId: input.runId,\n projectRoot: input.projectRoot,\n backend: 'webgpu',\n signal: input.signal,\n });\n } finally {\n active = false;\n }\n },\n };\n}\n\nexport interface PreviewCarrierRoute {\n readonly lookup: () => CarrierOffer | undefined;\n readonly lease: (request: CarrierLeaseRequest) => CarrierResult<{ readonly leaseId: string }>;\n readonly started: (leaseId: string) => CarrierResult<CarrierState>;\n readonly execute: (\n leaseId: string,\n request: Omit<PreviewHostRequest, 'carrier'>,\n context: Pick<ToolExecutionContext, 'runId' | 'signal'>,\n ) => Promise<PreviewRouteResult<PreviewHostResult>>;\n readonly exit: (leaseId: string) => CarrierResult<CarrierState>;\n readonly now?: () => number;\n}\n\nexport interface PreviewHostResult {\n readonly actualCarrier: 'headless-private' | 'headed-private' | 'visible-consumer';\n readonly trace: ToolPreviewTrace;\n readonly captureId: string;\n readonly drawCalls: number;\n readonly committedDrawIndex: number;\n readonly nonBlackPixels: number;\n readonly actionTrace: ToolPreviewRunResult['actionTrace'];\n readonly tape: ToolPreviewRunResult['tape'];\n readonly profile: ToolPreviewRunResult['profile'];\n readonly capturePng: ToolPreviewRunResult['capturePng'];\n readonly png: ToolPreviewRunResult['png'];\n readonly manifest: ToolPreviewRunResult['manifest'];\n readonly artifacts: ToolPreviewRunResult['artifacts'];\n readonly operationTiming: ToolPreviewRunResult['operationTiming'];\n readonly resource?: import('@forgeax/engine-app').ToolPreviewResourceFacts;\n}\n\nexport type PreviewHostRunner = (\n request: PreviewHostRequest,\n context: ToolExecutionContext,\n) => Promise<\n | { readonly ok: true; readonly value: PreviewHostResult }\n | { readonly ok: false; readonly error: ToolDomainFailure }\n>;\n\ntype PreviewRouteResult<T> =\n | { readonly ok: true; readonly value: T }\n | { readonly ok: false; readonly error: ToolDomainFailure };\n\nexport interface CarrierCleanupTrace {\n readonly actualCarrier: 'headless-private' | 'headed-private' | 'visible-consumer';\n readonly backend: 'webgpu';\n readonly cleanup: readonly ['gpu', 'canvas', 'page', 'carrier'];\n readonly failure: {\n readonly code: 'tool-preview-carrier-exit';\n readonly detail: { readonly carrier: CarrierCleanupTrace['actualCarrier'] };\n };\n}\n\nexport function createCarrierCleanupTrace(input: {\n readonly actualCarrier: CarrierCleanupTrace['actualCarrier'];\n readonly backend: 'webgpu';\n}): CarrierCleanupTrace {\n return {\n actualCarrier: input.actualCarrier,\n backend: input.backend,\n cleanup: ['gpu', 'canvas', 'page', 'carrier'],\n failure: {\n code: 'tool-preview-carrier-exit',\n detail: { carrier: input.actualCarrier },\n },\n };\n}\n\nfunction carrierRouteFailure(\n code: string,\n expected: string,\n hint: string,\n detail: Readonly<Record<string, unknown>>,\n): PreviewRouteResult<never> {\n return { ok: false, error: { code, expected, hint, detail: detail as never } };\n}\n\nexport async function runCarrierPreviewRoute<T>(\n presentation: ToolPreviewRecipeOptions['presentation'],\n carrier: PreviewCarrierRoute | undefined,\n executePrivate: () => Promise<PreviewRouteResult<T>>,\n executeConsumer: (leaseId: string) => Promise<PreviewRouteResult<T>> = executePrivate,\n): Promise<PreviewRouteResult<T>> {\n if (presentation === 'hidden' || carrier === undefined) return executePrivate();\n const offer = carrier.lookup();\n if (offer === undefined) return executePrivate();\n const leased = carrier.lease({\n consumerId: offer.consumerId,\n bearerToken: offer.bearerToken,\n now: carrier.now?.() ?? Date.now(),\n });\n if (!leased.ok) return executePrivate();\n const started = carrier.started(leased.value.leaseId);\n if (!started.ok) return executePrivate();\n const result = await executeConsumer(leased.value.leaseId);\n const exited = carrier.exit(leased.value.leaseId);\n if (!exited.ok)\n return carrierRouteFailure(\n exited.error.code,\n exited.error.expected,\n exited.error.hint,\n exited.error.detail,\n );\n return result;\n}\n\nexport const runPreviewHost: PreviewHostRunner = async (request, context) => {\n if (context.snapshot === undefined) {\n return carrierRouteFailure(\n 'tool-snapshot-missing',\n 'ToolExecutionContext.snapshot before Browser or Renderer creation',\n 'Start the operation with an authority snapshot and retry the lexical ToolRun.',\n { phase: 'snapshot' },\n );\n }\n const snapshot = context.snapshot;\n const recipe = createToolPreviewRecipe(request.recipe);\n return runCarrierPreviewRoute(\n recipe.presentation,\n request.carrier,\n async () => {\n if (typeof document === 'undefined') {\n if (request.projectRoot === undefined) {\n return carrierRouteFailure(\n 'tool-preview-project-root-missing',\n 'the Browser Host to receive a real ForgeaX project root',\n 'Create the ToolClient with projectRoot or pass projectRoot in the preview request.',\n { phase: 'project-authority' },\n );\n }\n return runBrowserPreviewHost(\n request.projectRoot,\n recipe,\n snapshot,\n context.runId,\n context.signal,\n );\n }\n const host = await createToolPreviewHost({ recipe, snapshot });\n if (!host.ok) {\n return {\n ok: false,\n error: {\n code: host.error.code,\n expected: host.error.expected,\n hint: host.error.hint,\n detail: host.error.detail as never,\n },\n };\n }\n try {\n const result = await host.value.run();\n if (!result.ok) {\n return {\n ok: false,\n error: {\n code: result.error.code,\n expected: result.error.expected,\n hint: result.error.hint,\n detail: result.error.detail as never,\n },\n };\n }\n return {\n ok: true,\n value: {\n ...result.value,\n actualCarrier: recipe.presentation === 'hidden' ? 'headless-private' : 'headed-private',\n },\n };\n } finally {\n await host.value.dispose();\n }\n },\n async (leaseId) => {\n const carrier = request.carrier;\n if (carrier === undefined) {\n return carrierRouteFailure(\n 'tool-preview-carrier-unavailable',\n 'a leased Consumer provider',\n 'Retry the ordinary private visible carrier.',\n { phase: 'consumer-execute' },\n );\n }\n const { carrier: _carrier, ...consumerRequest } = request;\n return carrier.execute(leaseId, consumerRequest, context);\n },\n );\n};\n","import type {\n ToolContribution,\n ToolRunOptions,\n ToolRuntime,\n ToolTerminal,\n} from '@forgeax/engine-tool-runtime';\n\nexport function runPrivateTool<TArgs, TResult>(\n runtime: ToolRuntime,\n contribution: ToolContribution<TArgs, TResult>,\n args: TArgs,\n options?: ToolRunOptions,\n): Promise<ToolTerminal<TResult>> {\n return runtime.run(contribution, args, options).terminal;\n}\n","import type { ToolRealm } from '@forgeax/engine-tool-runtime';\nimport {\n createRealmCapabilityMatrix as createRuntimeRealmCapabilityMatrix,\n type RealmCapability,\n type RealmCapabilityInput,\n type RealmCapabilityMatrix,\n} from '@forgeax/engine-tool-runtime';\n\nexport type { RealmCapability, RealmCapabilityInput, RealmCapabilityMatrix };\nexport { createRuntimeRealmCapabilityMatrix as createRealmCapabilityMatrix };\n\nexport function resolveRealmCapability(\n matrix: RealmCapabilityMatrix,\n realm: ToolRealm,\n): RealmCapability {\n return matrix.realms[realm];\n}\n\nconst RESOURCE_KINDS = ['process', 'port', 'page', 'canvas', 'fiber'] as const;\nexport type ResourceKind = (typeof RESOURCE_KINDS)[number];\n\nexport interface ResourceProbe {\n readonly observe: (kind: ResourceKind, id: string) => void;\n readonly release: (kind: ResourceKind, id: string) => void;\n readonly owner: (id: string) => ResourceOwner;\n readonly snapshot: () => Readonly<Record<ResourceKind, readonly string[]>>;\n}\n\nexport interface ResourceOwner {\n readonly id: string;\n readonly observe: (kind: ResourceKind, resourceId: string) => void;\n readonly release: (kind: ResourceKind, resourceId: string) => void;\n readonly stop: () => void;\n}\n\nexport function createResourceProbe(): ResourceProbe {\n const live = new Map<ResourceKind, Set<string>>(RESOURCE_KINDS.map((kind) => [kind, new Set()]));\n const owned = new Map<string, Set<string>>();\n const key = (kind: ResourceKind, id: string): string => `${kind}:${id}`;\n const releaseOwned = (ownerId: string, kind: ResourceKind, id: string): void => {\n live.get(kind)?.delete(id);\n owned.get(ownerId)?.delete(key(kind, id));\n };\n return {\n observe(kind, id) {\n live.get(kind)?.add(id);\n },\n release(kind, id) {\n live.get(kind)?.delete(id);\n },\n owner(id) {\n if (owned.has(id)) throw new Error(`resource-owner-duplicate:${id}`);\n owned.set(id, new Set());\n let stopped = false;\n return {\n id,\n observe(kind, resourceId) {\n if (stopped) throw new Error(`resource-owner-stopped:${id}`);\n live.get(kind)?.add(resourceId);\n owned.get(id)?.add(key(kind, resourceId));\n },\n release(kind, resourceId) {\n releaseOwned(id, kind, resourceId);\n },\n stop() {\n if (stopped) return;\n stopped = true;\n for (const resource of owned.get(id) ?? []) {\n const separator = resource.indexOf(':');\n const kind = resource.slice(0, separator) as ResourceKind;\n const resourceId = resource.slice(separator + 1);\n live.get(kind)?.delete(resourceId);\n }\n owned.delete(id);\n },\n };\n },\n snapshot() {\n return Object.fromEntries(\n [...live.entries()].map(([kind, ids]) => [kind, [...ids].sort()]),\n ) as unknown as Readonly<Record<ResourceKind, readonly string[]>>;\n },\n };\n}\n\nexport {\n createResourceBootstrapPlan,\n createResourceBootstrapTrace,\n type ResourceBootstrapPlan,\n type ResourceBootstrapTrace,\n type ResourceBootstrapTraceInput,\n} from '../host/resource-bootstrap.js';\n","import {\n type AuthenticatedLoopbackTransport,\n cancellationError,\n createServiceCapability,\n disconnectedError,\n domainFailureError,\n type JsonValue,\n type ServiceAdmissionRef,\n type ServiceCapability,\n type ToolContribution,\n type ToolTerminal,\n} from '@forgeax/engine-tool-runtime';\n\nexport interface ServiceExecutorOptions<TArgs, TResult> {\n readonly contribution: ToolContribution<TArgs, TResult>;\n readonly privateExecutor: (args: TArgs) => Promise<ToolTerminal<TResult>>;\n readonly transport: AuthenticatedLoopbackTransport;\n readonly admission?: ServiceAdmissionRef;\n readonly descriptorDigest: string;\n readonly recipeDigest: string;\n readonly workloadClass: string;\n readonly codeDigest: string;\n readonly browserVersion: string;\n readonly bearerToken?: string;\n}\n\nexport interface ServiceExecutor<TArgs, TResult> {\n readonly capability: ServiceCapability;\n readonly run: (\n args: TArgs,\n options?: { readonly recipeDigest?: string; readonly signal?: AbortSignal },\n ) => Promise<ToolTerminal<TResult>>;\n}\n\nexport function createServiceExecutor<TArgs, TResult>(\n options: ServiceExecutorOptions<TArgs, TResult>,\n): ServiceExecutor<TArgs, TResult> {\n const capability = createServiceCapability(options.admission, {\n toolId: options.contribution.descriptor.id,\n descriptorDigest: options.descriptorDigest,\n recipeDigest: options.recipeDigest,\n workloadClass: options.workloadClass,\n codeDigest: options.codeDigest,\n browserVersion: options.browserVersion,\n backend: 'webgpu',\n });\n return {\n capability,\n async run(args, runOptions = {}) {\n if (!capability.available) return options.privateExecutor(args);\n const request = {\n descriptorDigest: options.descriptorDigest,\n recipeDigest: runOptions.recipeDigest ?? options.recipeDigest,\n args: args as JsonValue,\n };\n try {\n const terminal = await options.transport.request(\n request,\n options.bearerToken ?? 'service-default-token',\n runOptions.signal === undefined ? {} : { signal: runOptions.signal },\n );\n return terminal as ToolTerminal<TResult>;\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n if (runOptions.signal?.aborted) {\n return {\n outcome: 'failed',\n failure: cancellationError(String(runOptions.signal.reason ?? 'aborted')),\n artifacts: [],\n };\n }\n const failure = message.includes('disconnected')\n ? disconnectedError(options.transport.endpoint)\n : domainFailureError(\n 'service-transport-failed',\n 'the authenticated loopback service to accept the request',\n 'Check the service token and recipe digest, then retry the private executor.',\n message,\n );\n return { outcome: 'failed', failure, artifacts: [] };\n }\n },\n };\n}\n","import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';\nimport {\n type AuthenticatedLoopbackTransport,\n createAuthenticatedLoopbackTransport,\n type ServiceWireHandler,\n type ServiceWireRequest,\n type ToolTerminal,\n} from '@forgeax/engine-tool-runtime';\n\nexport type {\n AuthenticatedLoopbackTransport,\n AuthenticatedLoopbackTransportOptions,\n ServiceWireHandler,\n ServiceWireRequest,\n} from '@forgeax/engine-tool-runtime';\nexport { createAuthenticatedLoopbackTransport } from '@forgeax/engine-tool-runtime';\n\nexport interface AuthenticatedLoopbackServiceOptions {\n readonly bearerToken: string;\n readonly handler: ServiceWireHandler;\n readonly host?: '127.0.0.1' | 'localhost';\n readonly expectedDescriptorDigest?: string;\n readonly expectedRecipeDigest?: string;\n}\n\nexport interface AuthenticatedLoopbackService {\n readonly endpoint: string;\n readonly transport: AuthenticatedLoopbackTransport;\n readonly close: () => Promise<void>;\n}\n\nasync function readJson(request: IncomingMessage): Promise<unknown> {\n const chunks: Buffer[] = [];\n for await (const chunk of request) chunks.push(Buffer.from(chunk));\n const body = Buffer.concat(chunks);\n if (body.byteLength > 1024 * 1024) throw new Error('request body is too large');\n return JSON.parse(body.toString('utf8')) as unknown;\n}\n\nfunction reply(\n response: ServerResponse,\n status: number,\n payload: ToolTerminal<unknown> | { readonly error: string },\n): void {\n response.statusCode = status;\n response.setHeader('content-type', 'application/json');\n response.end(JSON.stringify(payload));\n}\n\nfunction parseRequest(value: unknown): ServiceWireRequest {\n if (typeof value !== 'object' || value === null) throw new Error('request must be an object');\n const request = value as Record<string, unknown>;\n if (\n typeof request.descriptorDigest !== 'string' ||\n typeof request.recipeDigest !== 'string' ||\n request.args === undefined\n ) {\n throw new Error('request is missing descriptorDigest, recipeDigest, or args');\n }\n return {\n descriptorDigest: request.descriptorDigest,\n recipeDigest: request.recipeDigest,\n args: request.args as ServiceWireRequest['args'],\n };\n}\n\nfunction isAuthorized(request: IncomingMessage, bearerToken: string): boolean {\n return request.headers.authorization === `Bearer ${bearerToken}`;\n}\n\nexport async function createAuthenticatedLoopbackService(\n options: AuthenticatedLoopbackServiceOptions,\n): Promise<AuthenticatedLoopbackService> {\n if (options.bearerToken.length < 8) throw new TypeError('service bearer token is too short');\n const host = options.host ?? '127.0.0.1';\n const server = createServer(async (request, response) => {\n if (request.method !== 'POST' || request.url !== '/run') {\n reply(response, 404, { error: 'service route not found' });\n return;\n }\n if (!isAuthorized(request, options.bearerToken)) {\n reply(response, 401, { error: 'service bearer token rejected' });\n return;\n }\n try {\n const wireRequest = parseRequest(await readJson(request));\n if (\n options.expectedDescriptorDigest !== undefined &&\n wireRequest.descriptorDigest !== options.expectedDescriptorDigest\n ) {\n reply(response, 409, { error: 'service descriptor digest mismatch' });\n return;\n }\n if (\n options.expectedRecipeDigest !== undefined &&\n wireRequest.recipeDigest !== options.expectedRecipeDigest\n ) {\n reply(response, 409, { error: 'service recipe digest mismatch' });\n return;\n }\n reply(response, 200, await options.handler(wireRequest));\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n reply(response, 400, { error: message });\n }\n });\n await new Promise<void>((resolve, reject) => {\n const onError = (error: Error) => {\n server.off('listening', onListening);\n reject(error);\n };\n const onListening = () => {\n server.off('error', onError);\n resolve();\n };\n server.once('error', onError);\n server.once('listening', onListening);\n server.listen(0, host);\n });\n const address = server.address();\n if (address === null || typeof address === 'string') {\n await new Promise<void>((resolve) => server.close(() => resolve()));\n throw new Error('loopback service did not expose a TCP address');\n }\n const endpoint = `http://${host}:${address.port}/run`;\n const transport = createAuthenticatedLoopbackTransport({\n endpoint,\n bearerToken: options.bearerToken,\n });\n let closed = false;\n return {\n endpoint,\n transport,\n async close() {\n if (closed) return;\n closed = true;\n await new Promise<void>((resolve, reject) => {\n server.close((error) => (error === undefined ? resolve() : reject(error)));\n });\n transport.close();\n },\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/archive.ts","../src/dist.ts","../src/project.ts","../src/engine-binding.ts","../src/host.ts","../src/single-html.ts","../src/types.ts","../src/assets.ts","../package.json","../src/init.ts","../src/sdk.ts","../src/sdk-bootstrap.ts","../src/sdk-update.ts","../src/skill-install.ts","../src/bootstrap-commands.ts","../src/plugin-authoring.ts","../src/rhi-debug/cli-context.ts","../src/rhi-debug/operations.ts","../src/sdk-install.ts","../src/shader-check.ts","../src/software-capture.ts","../src/commands.ts","../src/tools/preview-catalog.ts","../src/tools/catalog.ts","../src/tools/preview-migration.ts","../src/tools/project-tools.ts","../src/tools/contributions.ts","../src/tools/offline-analysis.ts","../src/tools/preview-contributions.ts","../src/tools/runtime.ts","../src/tools/browser-host.ts","../src/tools/native-preview.ts","../src/index.ts","../src/tools/benchmark/statistics.ts","../src/tools/benchmark/report.ts","../src/tools/benchmark/harness.ts","../src/tools/bootstrap.ts","../src/tools/cache.ts","../src/tools/carrier-provider.ts","../src/tools/carrier-rendezvous.ts","../src/tools/cli-adapter.ts","../src/tools/client.ts","../src/tools/library.ts","../src/tools/migration.ts","../src/tools/preview-host.ts","../src/tools/private-executor.ts","../src/tools/realms.ts","../src/tools/service.ts","../src/tools/service-transport.ts"],"names":["entries","readFile","resolve","writeFile","selected","readdir","builtAt","stat","createHash","resolved","dirname","conditionalExport","relative","sep","moduleSpecifier","mkdir","document","attribute","element","filesUnder","viteBuild","rm","sha256","rename","basename","devDependencies","access","fileURLToPath","mkdtemp","tmpdir","cp","realpath","isAbsolute","execFileAsync","promisify","execFile","readManifest","GameProjectSchema","pathExists","createNetServer","createServer","captureUrl","pathToFileURL","runtime","ok","createViteConfig","vitePreview","projectPluginEntries","createToolRuntime","createContextCapabilityResolver","commandFailure","buildCommand","pluginInstallCommand","defineTool","createTcpServer","validatePreviewArtifactManifest","chromium","value","failure","Context","installCatalogLoader","errorResult","capabilityUnavailableError","missingTool","runProjectTool","createServiceCapability","createToolPreviewRecipe","domainFailureError","readJson","reply"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,SAAS,MAAM,KAAA,EAA2B;AACxC,EAAA,IAAI,KAAA,GAAQ,UAAA;AACZ,EAAA,KAAA,MAAW,IAAA,IAAQ,OAAO,KAAA,GAAS,KAAA,KAAU,KAAM,SAAA,CAAA,CAAW,KAAA,GAAQ,IAAA,IAAQ,GAAI,CAAA,IAAK,CAAA,CAAA;AACvF,EAAA,OAAA,CAAQ,QAAQ,UAAA,MAAiB,CAAA;AACnC;AAEA,SAAS,kBAAkB,IAAA,EAAoB;AAC7C,EAAA,IACE,IAAA,CAAK,MAAA,KAAW,CAAA,IAChB,IAAA,CAAK,UAAA,CAAW,GAAG,CAAA,IACnB,IAAA,CAAK,QAAA,CAAS,IAAI,CAAA,IAClB,IAAA,CAAK,MAAM,GAAG,CAAA,CAAE,IAAA,CAAK,CAAC,OAAA,KAAY,OAAA,CAAQ,MAAA,KAAW,CAAA,IAAK,OAAA,KAAY,GAAA,IAAO,OAAA,KAAY,IAAI,CAAA,EAC7F;AACA,IAAA,MAAM,IAAI,SAAA,CAAU,CAAA,wBAAA,EAA2B,IAAI,CAAA,CAAE,CAAA;AAAA,EACvD;AACF;AAEO,SAAS,UAAU,YAAA,EAA2C;AACnE,EAAA,IAAI,aAAa,MAAA,GAAS,eAAA,EAAiB,MAAM,IAAI,WAAW,4BAA4B,CAAA;AAC5F,EAAA,MAAMA,QAAAA,GAAU,CAAC,GAAG,YAAY,EAAE,IAAA,CAAK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AAA,KAAU,SAAYA,SAAAA,EAAQ,GAAI,MAAA,CAAO,KAAK,CAAE,CAAA;AAAA,MAC3E,CAAC,CAAA;AACD,MAAA,SAAA,CAAU,KAAA,EAAM;AAAA,IAClB;AAAA,GACF;AACF;;;AhBsGA,UAAA,EAAA","file":"index.mjs","sourcesContent":["import { deflateRawSync } from 'node:zlib';\n\nexport interface ZipEntry {\n readonly path: string;\n readonly bytes: Uint8Array;\n}\n\nconst ZIP32_LIMIT = 0xffff_ffff;\nconst ZIP_ENTRY_LIMIT = 0xffff;\nconst UTF8_FLAG = 0x0800;\nconst DEFLATE_METHOD = 8;\nconst DOS_EPOCH_DATE = 0x0021;\n\nconst CRC_TABLE = new Uint32Array(256);\nfor (let index = 0; index < CRC_TABLE.length; index += 1) {\n let value = index;\n for (let bit = 0; bit < 8; bit += 1) value = (value >>> 1) ^ (0xedb8_8320 & -(value & 1));\n CRC_TABLE[index] = value >>> 0;\n}\n\nfunction crc32(bytes: Uint8Array): number {\n let value = 0xffff_ffff;\n for (const byte of bytes) value = (value >>> 8) ^ (CRC_TABLE[(value ^ byte) & 0xff] ?? 0);\n return (value ^ 0xffff_ffff) >>> 0;\n}\n\nfunction assertArchivePath(path: string): void {\n if (\n path.length === 0 ||\n path.startsWith('/') ||\n path.includes('\\\\') ||\n path.split('/').some((segment) => segment.length === 0 || segment === '.' || segment === '..')\n ) {\n throw new TypeError(`invalid ZIP entry path: ${path}`);\n }\n}\n\nexport function createZip(entriesInput: readonly ZipEntry[]): Buffer {\n if (entriesInput.length > ZIP_ENTRY_LIMIT) throw new RangeError('ZIP32 entry limit exceeded');\n const entries = [...entriesInput].sort((left, right) => left.path.localeCompare(right.path));\n const seen = new Set<string>();\n const localParts: Buffer[] = [];\n const centralParts: Buffer[] = [];\n let offset = 0;\n\n for (const entry of entries) {\n assertArchivePath(entry.path);\n if (seen.has(entry.path)) throw new TypeError(`duplicate ZIP entry path: ${entry.path}`);\n seen.add(entry.path);\n const name = Buffer.from(entry.path, 'utf8');\n const source = Buffer.from(entry.bytes);\n const compressed = deflateRawSync(source, { level: 9 });\n if (source.byteLength > ZIP32_LIMIT || compressed.byteLength > ZIP32_LIMIT) {\n throw new RangeError(`ZIP32 file limit exceeded: ${entry.path}`);\n }\n const checksum = crc32(source);\n const local = Buffer.alloc(30);\n local.writeUInt32LE(0x0403_4b50, 0);\n local.writeUInt16LE(20, 4);\n local.writeUInt16LE(UTF8_FLAG, 6);\n local.writeUInt16LE(DEFLATE_METHOD, 8);\n local.writeUInt16LE(0, 10);\n local.writeUInt16LE(DOS_EPOCH_DATE, 12);\n local.writeUInt32LE(checksum, 14);\n local.writeUInt32LE(compressed.byteLength, 18);\n local.writeUInt32LE(source.byteLength, 22);\n local.writeUInt16LE(name.byteLength, 26);\n local.writeUInt16LE(0, 28);\n localParts.push(local, name, compressed);\n\n const central = Buffer.alloc(46);\n central.writeUInt32LE(0x0201_4b50, 0);\n central.writeUInt16LE(20, 4);\n central.writeUInt16LE(20, 6);\n central.writeUInt16LE(UTF8_FLAG, 8);\n central.writeUInt16LE(DEFLATE_METHOD, 10);\n central.writeUInt16LE(0, 12);\n central.writeUInt16LE(DOS_EPOCH_DATE, 14);\n central.writeUInt32LE(checksum, 16);\n central.writeUInt32LE(compressed.byteLength, 20);\n central.writeUInt32LE(source.byteLength, 24);\n central.writeUInt16LE(name.byteLength, 28);\n central.writeUInt16LE(0, 30);\n central.writeUInt16LE(0, 32);\n central.writeUInt16LE(0, 34);\n central.writeUInt16LE(0, 36);\n central.writeUInt32LE(0, 38);\n central.writeUInt32LE(offset, 42);\n centralParts.push(central, name);\n\n offset += local.byteLength + name.byteLength + compressed.byteLength;\n if (offset > ZIP32_LIMIT) throw new RangeError('ZIP32 archive limit exceeded');\n }\n\n const centralDirectory = Buffer.concat(centralParts);\n if (centralDirectory.byteLength > ZIP32_LIMIT)\n throw new RangeError('ZIP32 directory limit exceeded');\n const end = Buffer.alloc(22);\n end.writeUInt32LE(0x0605_4b50, 0);\n end.writeUInt16LE(entries.length, 8);\n end.writeUInt16LE(entries.length, 10);\n end.writeUInt32LE(centralDirectory.byteLength, 12);\n end.writeUInt32LE(offset, 16);\n return Buffer.concat([...localParts, centralDirectory, end]);\n}\n","import { createHash } from 'node:crypto';\nimport { readdir, readFile, stat, writeFile } from 'node:fs/promises';\nimport { relative, resolve, sep } from 'node:path';\nimport type { CommandResult, ProjectFacts } from './types.js';\n\nexport interface DistArtifact {\n readonly path: string;\n readonly mediaType: string;\n readonly bytes: number;\n readonly sha256: string;\n}\n\nexport interface DistManifest {\n readonly schemaVersion: '1.0.0';\n readonly project: { readonly id: string; readonly name: string };\n readonly base: string;\n readonly runtime: {\n readonly packIndexUrl: string;\n readonly shaderManifestUrl: string;\n };\n readonly artifacts: readonly DistArtifact[];\n}\n\nexport function mediaType(path: string): string {\n if (path.endsWith('.html')) return 'text/html';\n if (path.endsWith('.js') || path.endsWith('.mjs')) return 'text/javascript';\n if (path.endsWith('.json')) return 'application/json';\n if (path.endsWith('.wasm')) return 'application/wasm';\n if (path.endsWith('.png')) return 'image/png';\n if (path.endsWith('.jpg') || path.endsWith('.jpeg')) return 'image/jpeg';\n if (path.endsWith('.css')) return 'text/css';\n if (path.endsWith('.svg')) return 'image/svg+xml';\n if (path.endsWith('.webp')) return 'image/webp';\n if (path.endsWith('.gif')) return 'image/gif';\n if (path.endsWith('.mp3')) return 'audio/mpeg';\n if (path.endsWith('.wav')) return 'audio/wav';\n if (path.endsWith('.ogg')) return 'audio/ogg';\n if (path.endsWith('.mp4')) return 'video/mp4';\n if (path.endsWith('.webm')) return 'video/webm';\n if (path.endsWith('.woff')) return 'font/woff';\n if (path.endsWith('.woff2')) return 'font/woff2';\n if (path.endsWith('.ttf')) return 'font/ttf';\n if (path.endsWith('.otf')) return 'font/otf';\n if (path.endsWith('.wgsl') || path.endsWith('.glsl')) return 'text/plain';\n return 'application/octet-stream';\n}\n\nasync function filesUnder(root: string, directory = root): Promise<string[]> {\n const result: string[] = [];\n for (const name of (await readdir(directory)).sort()) {\n const path = resolve(directory, name);\n const info = await stat(path);\n if (info.isDirectory()) result.push(...(await filesUnder(root, path)));\n else if (info.isFile() && name !== 'forgeax-dist.json') result.push(path);\n }\n return result;\n}\n\nexport async function writeDistManifest(\n facts: ProjectFacts,\n base: string,\n rootInput = resolve(facts.root, 'dist'),\n): Promise<DistManifest> {\n const root = resolve(rootInput);\n const artifacts = await Promise.all(\n (await filesUnder(root)).map(async (path): Promise<DistArtifact> => {\n const bytes = await readFile(path);\n return {\n path: relative(root, path).split(sep).join('/'),\n mediaType: mediaType(path),\n bytes: bytes.byteLength,\n sha256: createHash('sha256').update(bytes).digest('hex'),\n };\n }),\n );\n const manifest: DistManifest = {\n schemaVersion: '1.0.0',\n project: { id: facts.id, name: facts.name },\n base,\n runtime: {\n packIndexUrl: 'pack-index.json',\n shaderManifestUrl: 'shaders/manifest.json',\n },\n artifacts,\n };\n await writeFile(resolve(root, 'forgeax-dist.json'), `${JSON.stringify(manifest, null, 2)}\\n`);\n return manifest;\n}\n\nexport async function verifyDist(rootInput: string): Promise<CommandResult<DistManifest>> {\n const root = resolve(rootInput);\n let manifest: DistManifest;\n try {\n manifest = JSON.parse(\n await readFile(resolve(root, 'forgeax-dist.json'), 'utf8'),\n ) as DistManifest;\n } catch (cause) {\n return {\n ok: false,\n error: {\n code: 'dist-manifest-unreadable',\n expected: 'a readable dist/forgeax-dist.json',\n hint: 'Run forgeax build and do not edit its derived manifest.',\n detail: { root, reason: cause instanceof Error ? cause.message : String(cause) },\n },\n };\n }\n if (manifest.schemaVersion !== '1.0.0' || !Array.isArray(manifest.artifacts)) {\n return {\n ok: false,\n error: {\n code: 'dist-manifest-invalid',\n expected: 'forgeax-dist schema 1.0.0',\n hint: 'Rebuild the game with a compatible ForgeaX DevKit.',\n detail: { root },\n },\n };\n }\n const declaredPaths = new Set(manifest.artifacts.map((artifact) => artifact.path));\n if (declaredPaths.size !== manifest.artifacts.length) {\n return {\n ok: false,\n error: {\n code: 'dist-artifact-duplicate',\n expected: 'every dist artifact path to be declared exactly once',\n hint: 'Rebuild the derived dist manifest.',\n detail: { root },\n },\n };\n }\n for (const artifact of manifest.artifacts) {\n const path = resolve(root, artifact.path);\n if (relative(root, path).startsWith('..')) {\n return {\n ok: false,\n error: {\n code: 'dist-path-escape',\n expected: 'every artifact path to remain inside dist',\n hint: 'Rebuild the derived dist manifest.',\n detail: { path: artifact.path },\n },\n };\n }\n try {\n const bytes = await readFile(path);\n const digest = createHash('sha256').update(bytes).digest('hex');\n if (bytes.byteLength !== artifact.bytes || digest !== artifact.sha256) {\n return {\n ok: false,\n error: {\n code: 'dist-artifact-mismatch',\n expected: 'artifact bytes and SHA-256 to match forgeax-dist.json',\n hint: 'Restore the built artifact or rebuild the complete dist.',\n detail: { path: artifact.path },\n },\n };\n }\n } catch {\n return {\n ok: false,\n error: {\n code: 'dist-artifact-missing',\n expected: 'every declared dist artifact to exist',\n hint: 'Restore the built artifact or rebuild the complete dist.',\n detail: { path: artifact.path },\n },\n };\n }\n }\n for (const required of [\n 'index.html',\n manifest.runtime.packIndexUrl,\n manifest.runtime.shaderManifestUrl,\n ]) {\n if (!manifest.artifacts.some((artifact) => artifact.path === required)) {\n return {\n ok: false,\n error: {\n code: 'dist-required-artifact-missing',\n expected: 'HTML, Pack index, and Shader manifest in the dist closure',\n hint: 'Rebuild after repairing the owning producer.',\n detail: { path: required },\n },\n };\n }\n }\n for (const path of await filesUnder(root)) {\n const artifactPath = relative(root, path).split(sep).join('/');\n if (!declaredPaths.has(artifactPath)) {\n return {\n ok: false,\n error: {\n code: 'dist-artifact-undeclared',\n expected: 'every file in dist to be covered by forgeax-dist.json',\n hint: 'Remove the foreign file or rebuild the complete dist.',\n detail: { path: artifactPath },\n },\n };\n }\n }\n return { ok: true, value: manifest };\n}\n","import { readFile } from 'node:fs/promises';\nimport { isAbsolute, resolve } from 'node:path';\nimport { type GameProjectPluginEntry, GameProjectSchema } from '@forgeax/engine-project';\nimport type { CommandError, CommandResult, ProjectFacts } from './types.js';\n\nfunction projectError(\n code: string,\n expected: string,\n hint: string,\n detail: Readonly<Record<string, unknown>>,\n): CommandResult<never> {\n return { ok: false, error: { code, expected, hint, detail } };\n}\n\nasync function readJson(path: string): Promise<unknown> {\n return JSON.parse(await readFile(path, 'utf8')) as unknown;\n}\n\nfunction firstUnsupportedStandaloneRealm(\n entries: readonly GameProjectPluginEntry[],\n inheritedRealm: GameProjectPluginEntry['realm'] = 'engine',\n): { readonly id: string; readonly realm: 'host' | 'build' } | undefined {\n for (const entry of entries) {\n const realm = entry.realm ?? inheritedRealm ?? 'engine';\n if (realm !== 'engine') return { id: entry.id, realm };\n if (entry.group === true) {\n const unsupported = firstUnsupportedStandaloneRealm(\n entry.config as readonly GameProjectPluginEntry[],\n realm,\n );\n if (unsupported !== undefined) return unsupported;\n }\n }\n return undefined;\n}\n\nfunction pluginModuleNames(entries: readonly GameProjectPluginEntry[]): string[] {\n return entries.flatMap((entry) =>\n entry.group === true\n ? pluginModuleNames(entry.config as readonly GameProjectPluginEntry[])\n : [entry.name],\n );\n}\n\nexport async function readProjectFacts(\n rootInput = process.cwd(),\n): Promise<CommandResult<ProjectFacts>> {\n const root = resolve(rootInput);\n let forgeValue: unknown;\n let packageValue: unknown;\n try {\n [forgeValue, packageValue] = await Promise.all([\n readJson(resolve(root, 'forge.json')),\n readJson(resolve(root, 'package.json')),\n ]);\n } catch (cause) {\n return projectError(\n 'project-manifest-unreadable',\n 'readable forge.json and package.json files',\n 'Run the command from a ForgeaX game root or pass its directory.',\n { root, reason: cause instanceof Error ? cause.message : String(cause) },\n );\n }\n if (forgeValue === null || typeof forgeValue !== 'object') {\n return projectError(\n 'project-manifest-invalid',\n 'forge.json to contain an object',\n 'Repair forge.json before running DevKit.',\n { root },\n );\n }\n if (packageValue === null || typeof packageValue !== 'object') {\n return projectError(\n 'package-manifest-invalid',\n 'package.json to contain an object',\n 'Repair package.json before running DevKit.',\n { root },\n );\n }\n const parsedForge = GameProjectSchema.safeParse(forgeValue);\n if (!parsedForge.success) {\n return projectError(\n 'project-manifest-invalid',\n 'forge.json to satisfy @forgeax/engine-project GameProjectSchema',\n 'Repair the fields reported by the authoritative project schema.',\n { root, issues: parsedForge.error.issues },\n );\n }\n const forge = parsedForge.data;\n if (\n forge.id.length === 0 ||\n forge.name.length === 0 ||\n forge.entry === undefined ||\n forge.entry.length === 0\n ) {\n return projectError(\n 'project-manifest-invalid',\n 'forge.json to declare id, name, and entry',\n 'Restore the project entry; plugin Entries remain optional additions.',\n { root },\n );\n }\n const plugins = forge.plugins ?? [];\n const unsupportedRealm = firstUnsupportedStandaloneRealm(plugins);\n if (unsupportedRealm !== undefined) {\n return projectError(\n 'project-plugin-realm-unsupported',\n 'the standalone Devkit host to contain only engine-realm plugin Entries',\n 'Move Host or build plugins to a host that owns that physical realm.',\n { root, ...unsupportedRealm },\n );\n }\n const entryPath = isAbsolute(forge.entry) ? forge.entry : resolve(root, forge.entry);\n try {\n await readFile(entryPath);\n } catch {\n return projectError(\n 'project-entry-missing',\n 'forge.json#entry to resolve to a readable module',\n 'Restore the game entry or update forge.json#entry.',\n { root, entry: forge.entry },\n );\n }\n const packageJson = packageValue as Record<string, unknown>;\n const forgeax = packageJson.forgeax;\n const configuredRoots =\n forgeax !== null && typeof forgeax === 'object'\n ? (forgeax as { assets?: { roots?: unknown } }).assets?.roots\n : undefined;\n const assetRoots =\n Array.isArray(configuredRoots) && configuredRoots.every((value) => typeof value === 'string')\n ? configuredRoots\n : ['assets'];\n const configuredImporters =\n forgeax !== null && typeof forgeax === 'object'\n ? (forgeax as { assets?: { importers?: unknown } }).assets?.importers\n : undefined;\n const assetImporters =\n Array.isArray(configuredImporters) &&\n configuredImporters.every((value) => typeof value === 'string')\n ? configuredImporters\n : [];\n const configuredPublicDir =\n forgeax !== null && typeof forgeax === 'object'\n ? (forgeax as { assets?: { publicDir?: unknown } }).assets?.publicDir\n : undefined;\n const assetPublicDir = typeof configuredPublicDir === 'string' ? configuredPublicDir : undefined;\n const physics = forge.physics === '2d' || forge.physics === '3d' ? forge.physics : undefined;\n const defaultScene =\n typeof forge.defaultScene === 'string' && forge.defaultScene.length > 0\n ? forge.defaultScene\n : undefined;\n const normalizedEntry = forge.entry.startsWith('./') ? forge.entry : `./${forge.entry}`;\n const bootstrapEntry = pluginModuleNames(plugins)\n .map((name) => (name.startsWith('./') ? name : `./${name}`))\n .includes(normalizedEntry)\n ? undefined\n : forge.entry;\n return {\n ok: true,\n value: {\n root,\n id: forge.id,\n name: forge.name,\n entry: forge.entry,\n ...(bootstrapEntry === undefined ? {} : { bootstrapEntry }),\n plugins,\n ...(physics === undefined ? {} : { physics }),\n ...(defaultScene === undefined ? {} : { defaultScene }),\n assetRoots,\n ...(assetImporters.length === 0 ? {} : { assetImporters }),\n ...(assetPublicDir === undefined ? {} : { assetPublicDir }),\n packageJson,\n },\n };\n}\n\nexport function commandError(cause: unknown, fallbackCode: string): CommandError {\n if (\n cause !== null &&\n typeof cause === 'object' &&\n 'code' in cause &&\n 'expected' in cause &&\n 'hint' in cause &&\n 'detail' in cause\n ) {\n return cause as CommandError;\n }\n return {\n code: fallbackCode,\n expected: 'the ForgeaX command to complete',\n hint: 'Inspect the underlying diagnostic and repair the owning input.',\n detail: { reason: cause instanceof Error ? cause.message : String(cause) },\n };\n}\n","import { createHash } from 'node:crypto';\nimport {\n access,\n mkdir,\n readdir,\n readFile,\n realpath,\n rename,\n rm,\n stat,\n writeFile,\n} from 'node:fs/promises';\nimport { dirname, resolve } from 'node:path';\nimport { commandError, readProjectFacts } from './project.js';\nimport type { CommandError, CommandResult, ProjectCommandOptions } from './types.js';\n\nexport const ENGINE_BINDING_SCHEMA_VERSION = '1.0.0' as const;\n\nexport type EngineBindingMode = 'sdk' | 'local';\n\nexport interface EngineBinding {\n readonly schemaVersion: typeof ENGINE_BINDING_SCHEMA_VERSION;\n readonly path: string;\n}\n\nexport interface EnginePackageStatus {\n readonly name: string;\n readonly root: string;\n readonly version: string;\n readonly entry: string | null;\n readonly built: boolean;\n readonly entryDigest: string | null;\n readonly builtAt: string | null;\n}\n\nexport interface EngineWorkspaceStatus {\n readonly root: string;\n readonly packageCount: number;\n readonly builtPackages: number;\n readonly missingBuilds: readonly string[];\n readonly versions: readonly string[];\n readonly packages: readonly EnginePackageStatus[];\n readonly digest: string;\n readonly builtAt: string | null;\n}\n\nexport interface EngineStatusReport {\n readonly schemaVersion: typeof ENGINE_BINDING_SCHEMA_VERSION;\n readonly root: string;\n readonly binding: EngineBinding | null;\n readonly mode: EngineBindingMode;\n readonly resolved: {\n readonly root: string | null;\n readonly version: string | null;\n readonly entry: string | null;\n readonly built: boolean;\n readonly source: 'sdk' | 'local' | 'unresolved';\n };\n readonly workspace: EngineWorkspaceStatus | null;\n readonly projectDependencies: 'registry' | 'workspace' | 'mixed' | 'none';\n readonly npmCompatible: boolean;\n readonly healthy: boolean;\n readonly next: readonly string[];\n readonly diagnostic?: CommandError;\n}\n\nexport interface EngineBindingCommandOptions extends ProjectCommandOptions {\n readonly path?: string;\n readonly dryRun?: boolean;\n}\n\ninterface PackageManifest extends Readonly<Record<string, unknown>> {\n readonly name?: unknown;\n readonly version?: unknown;\n readonly main?: unknown;\n readonly module?: unknown;\n readonly exports?: unknown;\n}\n\nconst bindingFile = (root: string): string => resolve(root, '.forgeax', 'engine-binding.json');\n\nfunction bindingError(\n code: string,\n expected: string,\n hint: string,\n detail: Readonly<Record<string, unknown>> = {},\n): CommandResult<never> {\n return { ok: false, error: { code, expected, hint, detail } };\n}\n\nfunction isMissing(cause: unknown): boolean {\n return cause !== null && typeof cause === 'object' && 'code' in cause && cause.code === 'ENOENT';\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction parseBinding(value: unknown, path: string): CommandResult<EngineBinding> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n return bindingError(\n 'engine-binding-invalid',\n 'engine-binding.json to contain one object',\n 'Run forgeax engine unlink, then select a binding again.',\n { path },\n );\n }\n const candidate = value as {\n readonly schemaVersion?: unknown;\n readonly path?: unknown;\n };\n if (candidate.schemaVersion !== ENGINE_BINDING_SCHEMA_VERSION) {\n return bindingError(\n 'engine-binding-version-unsupported',\n `engine-binding.json schemaVersion ${ENGINE_BINDING_SCHEMA_VERSION}`,\n 'Upgrade the SDK or remove the stale binding with forgeax engine unlink.',\n { path, schemaVersion: candidate.schemaVersion ?? null },\n );\n }\n if (typeof candidate.path !== 'string' || candidate.path.length === 0) {\n return bindingError(\n 'engine-binding-path-missing',\n 'engine-binding.json to contain one non-empty local Engine path',\n 'Run forgeax engine use-local <engine-directory>.',\n { path },\n );\n }\n return {\n ok: true,\n value: {\n schemaVersion: ENGINE_BINDING_SCHEMA_VERSION,\n path: resolve(candidate.path),\n },\n };\n}\n\nexport async function readEngineBinding(\n rootInput = process.cwd(),\n): Promise<CommandResult<EngineBinding | null>> {\n const root = resolve(rootInput);\n const path = bindingFile(root);\n try {\n const value = JSON.parse(await readFile(path, 'utf8')) as unknown;\n return parseBinding(value, path);\n } catch (cause) {\n if (isMissing(cause)) return { ok: true, value: null };\n return bindingError(\n 'engine-binding-unreadable',\n 'engine-binding.json to be readable JSON',\n 'Repair or remove .forgeax/engine-binding.json, then select a binding again.',\n { path, reason: cause instanceof Error ? cause.message : String(cause) },\n );\n }\n}\n\nasync function writeEngineBinding(root: string, binding: EngineBinding): Promise<void> {\n const path = bindingFile(root);\n const partial = `${path}.partial-${process.pid}`;\n await mkdir(dirname(path), { recursive: true });\n await writeFile(partial, `${JSON.stringify(binding, null, 2)}\\n`, 'utf8');\n await rename(partial, path);\n}\n\nfunction conditionalExport(value: unknown): string | undefined {\n if (typeof value === 'string') return value;\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined;\n const record = value as Record<string, unknown>;\n for (const key of ['import', 'browser', 'node', 'default', 'require', 'types']) {\n const candidate = record[key];\n const selected = conditionalExport(candidate);\n if (selected !== undefined) return selected;\n }\n return undefined;\n}\n\nfunction packageEntry(manifest: PackageManifest): string | undefined {\n const exportsValue = manifest.exports;\n if (exportsValue !== undefined) {\n if (typeof exportsValue === 'object' && exportsValue !== null && !Array.isArray(exportsValue)) {\n const root = (exportsValue as Record<string, unknown>)['.'];\n const selected = conditionalExport(root ?? exportsValue);\n if (selected !== undefined) return selected;\n }\n const selected = conditionalExport(exportsValue);\n if (selected !== undefined) return selected;\n }\n return typeof manifest.module === 'string'\n ? manifest.module\n : typeof manifest.main === 'string'\n ? manifest.main\n : undefined;\n}\n\nasync function readManifest(path: string): Promise<PackageManifest> {\n const value = JSON.parse(await readFile(path, 'utf8')) as unknown;\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`engine-package-manifest-invalid: ${path}`);\n }\n return value as PackageManifest;\n}\n\nexport async function inspectEngineWorkspace(\n workspaceInput: string,\n): Promise<CommandResult<EngineWorkspaceStatus>> {\n const root = resolve(workspaceInput);\n const packageRoot = resolve(root, 'packages');\n try {\n await access(resolve(root, 'pnpm-workspace.yaml'));\n const entries = await readdir(packageRoot, { withFileTypes: true });\n const packages: EnginePackageStatus[] = [];\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n const packagePath = resolve(packageRoot, entry.name);\n let manifest: PackageManifest;\n try {\n manifest = await readManifest(resolve(packagePath, 'package.json'));\n } catch {\n continue;\n }\n if (typeof manifest.name !== 'string' || !manifest.name.startsWith('@forgeax/engine'))\n continue;\n if (typeof manifest.version !== 'string') {\n return bindingError(\n 'engine-package-version-missing',\n 'every local Engine package to declare a version',\n 'Restore the package manifest version before selecting a local Engine.',\n { package: manifest.name, root: packagePath },\n );\n }\n const target = packageEntry(manifest);\n const entryPath = target === undefined ? undefined : resolve(packagePath, target);\n let entryDigest: string | null = null;\n let builtAt: string | null = null;\n if (entryPath !== undefined && (await pathExists(entryPath))) {\n const [bytes, metadata] = await Promise.all([readFile(entryPath), stat(entryPath)]);\n entryDigest = `sha256:${createHash('sha256').update(bytes).digest('hex')}`;\n builtAt = metadata.mtime.toISOString();\n }\n packages.push({\n name: manifest.name,\n root: packagePath,\n version: manifest.version,\n entry: entryPath ?? null,\n built: entryDigest !== null,\n entryDigest,\n builtAt,\n });\n }\n packages.sort((a, b) => a.name.localeCompare(b.name));\n if (packages.length === 0) {\n return bindingError(\n 'engine-workspace-empty',\n 'the local Engine workspace to contain @forgeax/engine packages',\n 'Pass the Engine repository or its source/engine SDK directory.',\n { root, packageRoot },\n );\n }\n const versions = [...new Set(packages.map((item) => item.version))].sort();\n const missingBuilds = packages.filter((item) => !item.built).map((item) => item.name);\n const builtAt =\n packages\n .flatMap((item) => (item.builtAt === null ? [] : [item.builtAt]))\n .sort()\n .at(-1) ?? null;\n const digest = `sha256:${createHash('sha256')\n .update(\n packages\n .map((item) => `${item.name}\\0${item.version}\\0${item.entryDigest ?? 'unbuilt'}`)\n .join('\\n'),\n )\n .digest('hex')}`;\n return {\n ok: true,\n value: {\n root,\n packageCount: packages.length,\n builtPackages: packages.length - missingBuilds.length,\n missingBuilds,\n versions,\n packages,\n digest,\n builtAt,\n },\n };\n } catch (cause) {\n return bindingError(\n isMissing(cause) ? 'engine-workspace-missing' : 'engine-workspace-unreadable',\n 'a readable Engine workspace with pnpm-workspace.yaml and packages/',\n 'Pass the Engine repository root, not its packages/ directory.',\n { root, packageRoot, reason: cause instanceof Error ? cause.message : String(cause) },\n );\n }\n}\n\nfunction projectDependencyMode(\n packageJson: Readonly<Record<string, unknown>>,\n): EngineStatusReport['projectDependencies'] {\n let workspace = false;\n let registry = false;\n for (const section of [\n 'dependencies',\n 'devDependencies',\n 'optionalDependencies',\n 'peerDependencies',\n ]) {\n const value = packageJson[section];\n if (value === null || typeof value !== 'object' || Array.isArray(value)) continue;\n for (const version of Object.values(value)) {\n if (typeof version !== 'string') continue;\n if (version.startsWith('workspace:') || version.startsWith('file:')) workspace = true;\n else registry = true;\n }\n }\n return workspace ? (registry ? 'mixed' : 'workspace') : registry ? 'registry' : 'none';\n}\n\nasync function sdkResolution(root: string): Promise<EngineStatusReport['resolved']> {\n const packageJson = resolve(root, 'node_modules', '@forgeax', 'engine', 'package.json');\n try {\n const manifest = await readManifest(packageJson);\n const target = packageEntry(manifest);\n const entry = target === undefined ? null : resolve(dirname(packageJson), target);\n return {\n root: dirname(packageJson),\n version: typeof manifest.version === 'string' ? manifest.version : null,\n entry,\n built: entry !== null && (await pathExists(entry)),\n source: 'sdk',\n };\n } catch {\n return { root: null, version: null, entry: null, built: false, source: 'unresolved' };\n }\n}\n\nexport async function engineStatusCommand(\n options: EngineBindingCommandOptions = {},\n): Promise<CommandResult<EngineStatusReport>> {\n const facts = await readProjectFacts(options.root);\n if (!facts.ok) return facts;\n const bindingResult = await readEngineBinding(facts.value.root);\n if (!bindingResult.ok) return bindingResult;\n const binding = bindingResult.value;\n const mode: EngineBindingMode = binding === null ? 'sdk' : 'local';\n const projectDependencies = projectDependencyMode(facts.value.packageJson);\n if (binding !== null) {\n const localPath = binding.path;\n const localBinding: EngineBinding = {\n schemaVersion: ENGINE_BINDING_SCHEMA_VERSION,\n path: localPath,\n };\n const workspaceResult = await inspectEngineWorkspace(localPath);\n if (!workspaceResult.ok) {\n const resolved: EngineStatusReport['resolved'] = {\n root: localPath,\n version: null,\n entry: null,\n built: false,\n source: 'local',\n };\n return {\n ok: true,\n value: {\n schemaVersion: ENGINE_BINDING_SCHEMA_VERSION,\n root: facts.value.root,\n binding: localBinding,\n mode,\n resolved,\n workspace: null,\n projectDependencies,\n npmCompatible: projectDependencies === 'registry' || projectDependencies === 'none',\n healthy: false,\n next: ['forgeax engine unlink', 'forgeax engine use-local <engine-directory>'],\n diagnostic: workspaceResult.error,\n },\n };\n }\n const workspace = workspaceResult.value;\n const version = workspace.versions.length === 1 ? (workspace.versions[0] ?? null) : null;\n const umbrella = workspace.packages.find((item) => item.name === '@forgeax/engine');\n const resolved: EngineStatusReport['resolved'] = {\n root: localPath,\n version,\n entry: umbrella?.entry ?? null,\n built: umbrella?.built ?? false,\n source: 'local',\n };\n const healthy = workspace.versions.length === 1 && workspace.missingBuilds.length === 0;\n return {\n ok: true,\n value: {\n schemaVersion: ENGINE_BINDING_SCHEMA_VERSION,\n root: facts.value.root,\n binding: localBinding,\n mode,\n resolved,\n workspace,\n projectDependencies,\n npmCompatible: projectDependencies === 'registry' || projectDependencies === 'none',\n healthy,\n next: healthy\n ? ['forgeax build', 'forgeax capture --backend auto --require-ui']\n : ['pnpm build:engine', 'forgeax engine doctor'],\n },\n };\n }\n const resolved = await sdkResolution(facts.value.root);\n return {\n ok: true,\n value: {\n schemaVersion: ENGINE_BINDING_SCHEMA_VERSION,\n root: facts.value.root,\n binding,\n mode,\n resolved,\n workspace: null,\n projectDependencies,\n npmCompatible: projectDependencies === 'registry' || projectDependencies === 'none',\n healthy: resolved.source === 'sdk' && resolved.built,\n next:\n resolved.source === 'sdk' && resolved.built\n ? ['forgeax build', 'forgeax capture --backend auto --require-ui']\n : ['pnpm install', 'forgeax doctor'],\n },\n };\n}\n\nexport async function engineUseLocalCommand(\n options: EngineBindingCommandOptions,\n): Promise<CommandResult<EngineStatusReport>> {\n const root = resolve(options.root ?? process.cwd());\n if (options.path === undefined || options.path.trim().length === 0) {\n return bindingError(\n 'engine-binding-path-missing',\n 'forgeax engine use-local <engine-directory>',\n 'Pass the local Engine repository or SDK source directory.',\n );\n }\n let localPath: string;\n try {\n localPath = await realpath(resolve(root, options.path));\n } catch (cause) {\n return bindingError(\n 'engine-workspace-missing',\n 'the local Engine directory to exist',\n 'Pass an existing Engine repository or SDK source directory.',\n {\n path: resolve(root, options.path),\n reason: cause instanceof Error ? cause.message : String(cause),\n },\n );\n }\n const workspace = await inspectEngineWorkspace(localPath);\n if (!workspace.ok) return workspace;\n const binding: EngineBinding = {\n schemaVersion: ENGINE_BINDING_SCHEMA_VERSION,\n path: localPath,\n };\n if (options.dryRun !== true) await writeEngineBinding(root, binding);\n const status = await engineStatusCommand({ root });\n if (!status.ok) return status;\n return {\n ok: true,\n value: {\n ...status.value,\n next:\n workspace.value.missingBuilds.length === 0\n ? ['forgeax build', 'forgeax capture --backend auto --require-ui']\n : ['pnpm build:engine', 'forgeax engine doctor'],\n },\n };\n}\n\nexport async function engineUnlinkCommand(\n options: EngineBindingCommandOptions = {},\n): Promise<CommandResult<EngineStatusReport>> {\n const root = resolve(options.root ?? process.cwd());\n if (options.dryRun !== true) await rm(bindingFile(root), { force: true });\n return engineStatusCommand({ root });\n}\n\nexport async function engineDoctorCommand(\n options: EngineBindingCommandOptions = {},\n): Promise<CommandResult<EngineStatusReport>> {\n const status = await engineStatusCommand(options);\n if (!status.ok) return status;\n if (\n status.value.projectDependencies === 'workspace' ||\n status.value.projectDependencies === 'mixed'\n ) {\n return {\n ok: false,\n error: {\n code: 'engine-project-workspace-dependency',\n expected: 'the game project to use registry or SDK-resolved dependencies for npm consumers',\n hint: 'This project is a pnpm workspace; use pnpm here, or create a clean SDK game project for npm install.',\n detail: { root: status.value.root, projectDependencies: status.value.projectDependencies },\n },\n };\n }\n if (status.value.diagnostic !== undefined) return { ok: false, error: status.value.diagnostic };\n if (!status.value.healthy) {\n return {\n ok: false,\n error: {\n code:\n status.value.mode === 'local' ? 'engine-local-build-missing' : 'engine-sdk-unresolved',\n expected: 'the selected Engine binding to resolve to built packages',\n hint:\n status.value.mode === 'local'\n ? 'Run pnpm build:engine in the selected Engine checkout, then rerun forgeax engine doctor.'\n : 'Run pnpm install in the game project or select a valid local Engine checkout.',\n detail: { status: status.value },\n },\n };\n }\n return status;\n}\n\nexport function engineBindingFilePath(rootInput = process.cwd()): string {\n return bindingFile(resolve(rootInput));\n}\n\nexport function engineBindingError(cause: unknown): CommandError {\n return commandError(cause, 'engine-binding-failed');\n}\n","import { existsSync } from 'node:fs';\nimport { mkdir, readdir, readFile, writeFile } from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport { dirname, relative, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { audioImporter } from '@forgeax/engine-audio-webaudio/audio-importer';\nimport { fbxImporter } from '@forgeax/engine-fbx';\nimport { fontImporter } from '@forgeax/engine-font/font-importer';\nimport { gltfImporter } from '@forgeax/engine-gltf';\nimport { imageImporter } from '@forgeax/engine-image/image-importer';\nimport { BUILTIN_MESH_ASSETS } from '@forgeax/engine-pack/builtin';\nimport { scanInventory } from '@forgeax/engine-pack/scanner';\nimport { validateCanonicalKitReceipt } from '@forgeax/engine-preview';\nimport { createMaterialPackCooker } from '@forgeax/engine-shader-compiler';\nimport { createStandaloneRuntimeAssetBinding, type Importer } from '@forgeax/engine-types';\nimport { createParticleCodeNativeCookerFromRoots } from '@forgeax/engine-vfx-compiler';\nimport { pluginPack, reloadAssetHost } from '@forgeax/engine-vite-plugin-pack';\nimport { vitePluginRhiDebug } from '@forgeax/engine-vite-plugin-rhi-debug';\nimport { forgeaxShader } from '@forgeax/engine-vite-plugin-shader';\nimport type { InlineConfig, Plugin } from 'vite';\nimport { inspectEngineWorkspace, readEngineBinding } from './engine-binding.js';\nimport type { BootstrapRoot } from './host/base-host.js';\nimport type { ProjectFacts, ProjectPortOptions } from './types.js';\n\ninterface CatalogModule {\n readonly name: string;\n readonly realm: 'host' | 'engine';\n}\n\nexport function ignoreDevKitCatalogPath(path: string): boolean {\n const normalized = path.replace(/\\\\/g, '/');\n return normalized.split('/').includes('shaders');\n}\n\nexport function devKitDdcRoots(projectRoot: string): {\n readonly buildCacheRoot: string;\n readonly projectDdcRoot: string;\n} {\n return {\n buildCacheRoot: resolve(projectRoot, '.forgeax', 'ddc', 'build-cache'),\n projectDdcRoot: resolve(projectRoot, '.forgeax', 'ddc', 'v2'),\n };\n}\n\nfunction isResourcePreviewIgnoredPath(path: string): boolean {\n return (\n ignoreDevKitCatalogPath(path) ||\n path.endsWith('.wgsl.meta.json') ||\n path.endsWith('target-profile.json.meta.json')\n );\n}\n\nfunction isProjectSourceIgnoredPath(path: string): boolean {\n return ignoreDevKitCatalogPath(path) || path.endsWith('.wgsl.meta.json');\n}\n\ninterface CanonicalKitLocation {\n readonly root: string;\n readonly guid: string;\n}\n\n/**\n * Materialize the Engine-owned procedural mesh descriptors missing from a\n * standalone project. The project remains the author of any descriptor it\n * explicitly carries (for example, the game-default template); generated\n * rows fill only the GUID closure required by legacy scenes that reference\n * Engine builtins without embedding a duplicate declaration.\n */\nasync function prepareBuiltinPack(\n projectRoots: readonly string[],\n generated: string,\n ignorePath: (path: string) => boolean,\n): Promise<string | undefined> {\n const inventory = await scanInventory(projectRoots, { ignorePath });\n if (!inventory.ok) return undefined;\n const declared = new Set<string>();\n for (const declaration of inventory.value.declarations.values()) {\n if (declaration.format === 'pack.json') {\n for (const asset of declaration.value.assets) declared.add(asset.guid.toLowerCase());\n continue;\n }\n for (const asset of declaration.value.subAssets) declared.add(asset.guid.toLowerCase());\n }\n const missing = BUILTIN_MESH_ASSETS.filter((asset) => !declared.has(asset.guid.toLowerCase()));\n if (missing.length === 0) return undefined;\n const packPath = resolve(generated, 'engine-builtins.pack.json');\n await writeFile(\n packPath,\n `${JSON.stringify(\n {\n schemaVersion: '2.0.0',\n kind: 'internal-text-package',\n assets: missing.map((asset) => ({\n guid: asset.guid,\n kind: 'mesh',\n payload: { geometry: asset.geometry },\n refs: [],\n artifacts: {},\n })),\n },\n null,\n 2,\n )}\\n`,\n 'utf8',\n );\n return packPath;\n}\n\nconst hostRequire = createRequire(import.meta.url);\n\ninterface EngineWorkspacePackage {\n readonly root: string;\n readonly manifest: Readonly<Record<string, unknown>>;\n}\n\ntype PackageExportValue = string | null | { readonly [key: string]: PackageExportValue };\n\nfunction findEngineWorkspaceRoot(): string | undefined {\n let cursor = dirname(fileURLToPath(import.meta.url));\n for (;;) {\n if (existsSync(resolve(cursor, 'pnpm-workspace.yaml'))) return cursor;\n const parent = dirname(cursor);\n if (parent === cursor) return undefined;\n cursor = parent;\n }\n}\n\nasync function engineWorkspacePackages(\n workspaceRoot = findEngineWorkspaceRoot(),\n): Promise<ReadonlyMap<string, EngineWorkspacePackage>> {\n if (workspaceRoot === undefined) return new Map<string, EngineWorkspacePackage>();\n const packageRoot = resolve(workspaceRoot, 'packages');\n // A generated game is a pnpm workspace too, but it does not own a local\n // `packages/` tree. Its installed Engine packages are resolved by Node;\n // the workspace resolver is only an SDK/source-checkout fallback.\n if (!existsSync(packageRoot)) return new Map<string, EngineWorkspacePackage>();\n const packages = new Map<string, EngineWorkspacePackage>();\n for (const entry of await readdir(packageRoot, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const root = resolve(packageRoot, entry.name);\n try {\n const manifest = JSON.parse(await readFile(resolve(root, 'package.json'), 'utf8')) as unknown;\n if (manifest === null || typeof manifest !== 'object') continue;\n const name = (manifest as { readonly name?: unknown }).name;\n if (typeof name === 'string' && name.startsWith('@forgeax/engine')) {\n packages.set(name, { root, manifest: manifest as Readonly<Record<string, unknown>> });\n }\n } catch {\n // A partial SDK/source checkout may omit an unrelated package manifest. The\n // package remains resolvable from the consumer project when available.\n }\n }\n return packages;\n}\n\nfunction conditionalExport(value: PackageExportValue): string | undefined {\n if (typeof value === 'string') return value;\n if (value === null || Array.isArray(value)) return undefined;\n for (const condition of ['browser', 'import', 'node', 'default']) {\n const candidate = value[condition];\n if (candidate === undefined) continue;\n const selected = conditionalExport(candidate);\n if (selected !== undefined) return selected;\n }\n return undefined;\n}\n\nfunction packageExportTarget(\n manifest: Readonly<Record<string, unknown>>,\n subpath: string,\n): string | undefined {\n const exportsValue = manifest.exports as PackageExportValue | undefined;\n if (exportsValue === undefined) {\n if (subpath.length > 0) return undefined;\n const main = manifest.module ?? manifest.main;\n return typeof main === 'string' ? main : undefined;\n }\n if (typeof exportsValue === 'string' || exportsValue === null) {\n return subpath.length === 0 ? conditionalExport(exportsValue) : undefined;\n }\n const keys = Object.keys(exportsValue);\n const subpathMap = keys.some((key) => key === '.' || key.startsWith('./'));\n if (!subpathMap) return subpath.length === 0 ? conditionalExport(exportsValue) : undefined;\n const requested = subpath.length === 0 ? '.' : `./${subpath}`;\n const exact = exportsValue[requested];\n if (exact !== undefined) return conditionalExport(exact);\n for (const key of keys) {\n const marker = key.indexOf('*');\n if (marker < 0) continue;\n const prefix = key.slice(0, marker);\n const suffix = key.slice(marker + 1);\n if (!requested.startsWith(prefix) || !requested.endsWith(suffix)) continue;\n const replacement = requested.slice(prefix.length, requested.length - suffix.length);\n const exportTarget = exportsValue[key];\n if (exportTarget === undefined) continue;\n const selected = conditionalExport(exportTarget);\n return selected?.replaceAll('*', replacement);\n }\n return undefined;\n}\n\nfunction engineWorkspaceImport(\n source: string,\n packages: ReadonlyMap<string, EngineWorkspacePackage>,\n): string | undefined {\n if (!source.startsWith('@forgeax/engine')) return undefined;\n const separator = source.indexOf('/', '@forgeax/engine'.length);\n const packageName = separator < 0 ? source : source.slice(0, separator);\n const subpath = separator < 0 ? '' : source.slice(separator + 1);\n const packageInfo = packages.get(packageName);\n if (packageInfo === undefined) return undefined;\n const target = packageExportTarget(packageInfo.manifest, subpath);\n if (target === undefined) return undefined;\n const absolute = resolve(packageInfo.root, target);\n const inside = relative(packageInfo.root, absolute);\n if (inside === '..' || inside.startsWith(`..${sep}`) || absolute === packageInfo.root) {\n return undefined;\n }\n return absolute;\n}\n\nasync function createEngineWorkspaceResolver(projectRoot: string): Promise<Plugin | undefined> {\n const binding = await readEngineBinding(projectRoot);\n if (!binding.ok) {\n throw new Error(`${binding.error.code}: ${binding.error.hint}`);\n }\n const localRoot = binding.value?.path;\n if (localRoot !== undefined) {\n const inspected = await inspectEngineWorkspace(localRoot);\n if (!inspected.ok) throw new Error(`${inspected.error.code}: ${inspected.error.hint}`);\n }\n const packages = await engineWorkspacePackages(localRoot);\n if (packages.size === 0) return undefined;\n return {\n name: 'forgeax:devkit-engine-workspace-resolver',\n enforce: 'pre',\n async resolveId(source, importer) {\n const bareSource = source.split('?', 1)[0] ?? source;\n if (!bareSource.startsWith('@forgeax/engine')) return null;\n if (localRoot !== undefined) return engineWorkspaceImport(bareSource, packages);\n try {\n const resolved = await this.resolve(source, importer, { skipSelf: true });\n if (resolved !== null) return resolved;\n } catch {\n // Fall through to the Engine workspace only when the external project\n // has no installed copy of this package.\n }\n return engineWorkspaceImport(bareSource, packages);\n },\n };\n}\n\n/**\n * Reuse the production host's workspace fallback when a second bundle pass\n * resolves Engine packages from a source checkout.\n */\nexport async function createEngineWorkspaceResolverForProject(\n projectRoot: string,\n): Promise<Plugin | undefined> {\n return createEngineWorkspaceResolver(projectRoot);\n}\n\nasync function consumerEngineAliases(\n projectRoot: string,\n): Promise<readonly { readonly find: string; readonly replacement: string }[]> {\n const root = resolve(projectRoot, 'node_modules', '.pnpm', 'node_modules', '@forgeax');\n try {\n const entries = await readdir(root, { withFileTypes: true });\n return entries\n .filter((entry) => entry.isDirectory() && entry.name.startsWith('engine-'))\n .map((entry) => ({\n find: `@forgeax/${entry.name}`,\n replacement: resolve(root, entry.name),\n }))\n .sort((a, b) => a.find.localeCompare(b.find));\n } catch {\n return [];\n }\n}\n\nasync function resolveCanonicalKit(): Promise<CanonicalKitLocation> {\n const packageJson = hostRequire.resolve('@forgeax/engine-preview/package.json');\n const root = resolve(packageJson, '..', 'assets/canonical-kit');\n if (!existsSync(root)) throw new Error(`canonical preview kit root is missing: ${root}`);\n const receiptPath = resolve(root, 'cook-receipt.json');\n const receipt = validateCanonicalKitReceipt(JSON.parse(await readFile(receiptPath, 'utf8')));\n if (!receipt.ok) {\n throw new Error(`${receipt.error.code}: ${receipt.error.detail.field}`);\n }\n const sourcePath = resolve(root, receipt.value.transport.source);\n const metaPath = resolve(root, receipt.value.transport.meta);\n if (!existsSync(sourcePath) || !existsSync(metaPath)) {\n throw new Error('canonical preview kit source and Meta must be package-owned files');\n }\n return { root, guid: receipt.value.source.guid };\n}\n\nfunction moduleSpecifier(from: string, to: string): string {\n const value = relative(from, to).split(sep).join('/');\n return value.startsWith('.') ? value : `./${value}`;\n}\n\nfunction catalogModules(facts: ProjectFacts): CatalogModule[] {\n const modules = new Map<string, CatalogModule>();\n const visit = (\n entries: ProjectFacts['plugins'],\n inheritedRealm: 'host' | 'engine' | 'build' = 'engine',\n ): void => {\n for (const entry of entries) {\n const realm = entry.realm ?? inheritedRealm;\n if (entry.group === true) {\n visit(entry.config as ProjectFacts['plugins'], realm);\n continue;\n }\n if (entry.name.startsWith('cordis:') || realm === 'build') continue;\n const current = modules.get(entry.name);\n if (current !== undefined && current.realm !== realm) {\n throw new Error(`plugin module ${entry.name} is assigned to multiple realms`);\n }\n modules.set(entry.name, { name: entry.name, realm });\n }\n };\n visit(facts.plugins);\n return [...modules.values()];\n}\n\nfunction catalogImport(facts: ProjectFacts, generated: string, name: string): string {\n const specifier = name.startsWith('.')\n ? moduleSpecifier(generated, resolve(facts.root, name))\n : name;\n return `() => import(${JSON.stringify(specifier)})`;\n}\n\ntype JitiLoader = (id: string) => unknown;\ntype JitiFactory = (filename: string, options: { readonly esmResolve: boolean }) => JitiLoader;\n\nfunction projectImporters(facts: ProjectFacts): readonly Importer[] {\n const specs = facts.assetImporters ?? [];\n if (specs.length === 0) return [];\n const createJiti = hostRequire('jiti') as JitiFactory;\n const load = createJiti(resolve(facts.root, 'package.json'), { esmResolve: true });\n return specs.map((spec) => {\n const separator = spec.lastIndexOf('#');\n const moduleSpecifier = separator < 0 ? spec : spec.slice(0, separator);\n const exportName = separator < 0 ? 'default' : spec.slice(separator + 1);\n const modulePath = moduleSpecifier.startsWith('.')\n ? resolve(facts.root, moduleSpecifier)\n : moduleSpecifier;\n const namespace = load(modulePath);\n if (namespace === null || typeof namespace !== 'object') {\n throw new Error(`project-asset-importer-module-invalid: ${spec}`);\n }\n const factory = (namespace as Record<string, unknown>)[exportName];\n if (typeof factory !== 'function') {\n throw new Error(`project-asset-importer-export-missing: ${spec}`);\n }\n const importer = factory();\n if (importer === null || typeof importer !== 'object') {\n throw new Error(`project-asset-importer-invalid: ${spec}`);\n }\n return importer as Importer;\n });\n}\n\nfunction hostSource(\n facts: ProjectFacts,\n bootstrapRoot: BootstrapRoot,\n canonicalEnvironmentGuid?: string,\n): string {\n const generated = resolve(facts.root, '.forgeax', 'generated');\n const plugins =\n bootstrapRoot === 'resource-bootstrap'\n ? []\n : [\n `webAudioPlugin()`,\n `audioPlugin()`,\n `skinningPlugin()`,\n ...(facts.physics === undefined\n ? []\n : [`physicsPlugin('${facts.physics === '2d' ? 'rapier-2d' : 'rapier-3d'}')`]),\n ];\n const bootstrapPlugin =\n facts.bootstrapEntry === undefined\n ? ''\n : `const bootstrapModule = await import(${JSON.stringify(\n moduleSpecifier(generated, resolve(facts.root, facts.bootstrapEntry)),\n )});\nif (typeof bootstrapModule.bootstrap !== 'function') {\n throw new Error('forgeax: project entry must export bootstrap(world, context)');\n}\nawait app.pluginContext.plugin({\n name: 'project-entry-bootstrap',\n inject: ['gameHost'],\n async apply(ctx) {\n if (ctx.gameHost === undefined) throw new Error('forgeax: gameHost unavailable');\n await bootstrapModule.bootstrap(ctx.gameHost.app.world, ctx.gameHost);\n },\n});`;\n return `import { forgeaxBundlerAdapter } from 'virtual:forgeax/bundler';\nimport { createApp, createToolPreviewHost, createToolPreviewRecipe, fitToolPreviewCameraToAabb, gameHostPlugin, replayToolPreviewCapture } from '@forgeax/engine/app';\nimport { createCatalogSource } from '@forgeax/engine/assets-runtime';\nimport {\n createRuntimeAssetImportTransport,\n runtimeBinding,\n} from 'virtual:forgeax/pack-runtime';\nimport { installCatalogLoader, projectPluginEntries } from '@forgeax/engine/plugin/loader';\nimport { audioPlugin } from '@forgeax/engine/audio';\nimport { webAudioPlugin } from '@forgeax/engine/audio-webaudio';\nimport { physicsPlugin } from '@forgeax/engine/physics';\nimport { skinningPlugin } from '@forgeax/engine/skinning';\nimport { createPrimitiveMesh } from '@forgeax/engine/geometry';\nimport { mat4 } from '@forgeax/engine/math';\nimport { CAMERA_PROJECTION_ORTHOGRAPHIC, Camera, DirectionalLight, Materials, MeshFilter, MeshRenderer, Skylight, SkyboxBackground, TONEMAP_NONE, TONEMAP_REINHARD_EXTENDED } from '@forgeax/engine/render';\nimport { Transform } from '@forgeax/engine/scene';\nimport { type SceneAsset } from '@forgeax/engine/types';\nimport { ParticleEffectPlayer, vfxGpuEffectContribution } from '@forgeax/engine/vfx';\nimport { createVfxRuntimeHost } from '@forgeax/engine/vfx-render';\n\nconst pluginCatalog = new Map([\n${catalogModules(facts)\n .map(\n ({ name, realm }) =>\n ` [${JSON.stringify(name)}, { realm: ${JSON.stringify(realm)}, load: ${catalogImport(facts, generated, name)} }],`,\n )\n .join('\\n')}\n]);\nconst pluginEntries = ${JSON.stringify(facts.plugins, null, 2)};\nconst bootstrapRoot = ${JSON.stringify(bootstrapRoot)};\nconst canonicalEnvironmentGuid = ${JSON.stringify(canonicalEnvironmentGuid ?? null)};\nconst resourceValue = new URLSearchParams(location.search).get('forgeax-resource-preview');\nconst resource = resourceValue === null ? undefined : JSON.parse(resourceValue);\nconst previewCameraEntities = new WeakMap();\nconst previewCameraTargets = new WeakMap();\nlet previewWorld;\nconst vfxRuntimeHost = resource?.kind === 'vfx'\n ? createVfxRuntimeHost({\n camera: {\n read(world) {\n const cameraEntity = previewCameraEntities.get(world);\n if (cameraEntity === undefined) return undefined;\n const transform = world.get(cameraEntity, Transform);\n const camera = world.get(cameraEntity, Camera);\n if (!transform.ok || !camera.ok) return undefined;\n const position = new Float32Array(transform.value.pos);\n const target = previewCameraTargets.get(world) ?? [0, 0, 0];\n return {\n position,\n right: new Float32Array([1, 0, 0]),\n up: new Float32Array([0, 1, 0]),\n viewProjection: mat4.computeViewProj(\n mat4.create(),\n position,\n target,\n [0, 1, 0],\n camera.value.fov,\n camera.value.aspect,\n camera.value.near,\n camera.value.far,\n ),\n };\n },\n },\n })\n : undefined;\n\nfunction previewVfxBounds(payload) {\n if (payload?.kind !== 'particle-effect' || payload.program?.emitters?.length === 0) return undefined;\n let minX = Infinity;\n let minY = Infinity;\n let minZ = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n let maxZ = -Infinity;\n for (const emitter of payload.program.emitters) {\n const bounds = emitter.bounds;\n if (bounds?.kind === 'sphere' && Array.isArray(bounds.center) && typeof bounds.radius === 'number') {\n const [x, y, z] = bounds.center;\n if (![x, y, z, bounds.radius].every((value) => typeof value === 'number' && Number.isFinite(value)) || bounds.radius < 0) return undefined;\n minX = Math.min(minX, x - bounds.radius);\n minY = Math.min(minY, y - bounds.radius);\n minZ = Math.min(minZ, z - bounds.radius);\n maxX = Math.max(maxX, x + bounds.radius);\n maxY = Math.max(maxY, y + bounds.radius);\n maxZ = Math.max(maxZ, z + bounds.radius);\n continue;\n }\n if (bounds?.kind === 'aabb' && Array.isArray(bounds.min) && Array.isArray(bounds.max)) {\n const [loX, loY, loZ] = bounds.min;\n const [hiX, hiY, hiZ] = bounds.max;\n if (![loX, loY, loZ, hiX, hiY, hiZ].every((value) => typeof value === 'number' && Number.isFinite(value))) return undefined;\n minX = Math.min(minX, loX);\n minY = Math.min(minY, loY);\n minZ = Math.min(minZ, loZ);\n maxX = Math.max(maxX, hiX);\n maxY = Math.max(maxY, hiY);\n maxZ = Math.max(maxZ, hiZ);\n continue;\n }\n return undefined;\n }\n if (![minX, minY, minZ, maxX, maxY, maxZ].every(Number.isFinite)) return undefined;\n const center = [(minX + maxX) / 2, (minY + maxY) / 2, (minZ + maxZ) / 2];\n const radius = Math.max(1, Math.hypot(maxX - minX, maxY - minY, maxZ - minZ));\n return { aabb: [minX, minY, minZ, maxX, maxY, maxZ], center, radius };\n}\n\nconst canvas = document.querySelector('#app');\nif (!(canvas instanceof HTMLCanvasElement)) throw new Error('forgeax: missing canvas');\nconst resizeCanvas = () => {\n const dpr = Math.min(window.devicePixelRatio || 1, 2);\n const width = Math.max(1, Math.round(canvas.clientWidth * dpr));\n const height = Math.max(1, Math.round(canvas.clientHeight * dpr));\n if (canvas.width !== width) canvas.width = width;\n if (canvas.height !== height) canvas.height = height;\n};\nconst resizeObserver = new ResizeObserver(resizeCanvas);\nresizeObserver.observe(canvas);\nresizeCanvas();\nconst runtimeScopeBinding = runtimeBinding;\nif (runtimeScopeBinding === undefined) {\n throw new Error('forgeax: Vite Pack runtime binding is required in the generated host');\n}\nconst assetCatalog = createCatalogSource({\n url: import.meta.env.DEV\n ? runtimeScopeBinding.catalogUrl\n : new URL('pack-index.json', document.baseURI).href,\n ...(import.meta.env.DEV ? { expectedScope: runtimeScopeBinding } : {}),\n});\nconst bundler = {\n ...forgeaxBundlerAdapter(),\n ...(import.meta.env.DEV\n ? { importTransport: createRuntimeAssetImportTransport(runtimeScopeBinding) }\n : {}),\n};\nconst assetPreparation = new WeakMap();\n\nfunction prepareAssetRegistry(assets) {\n const existing = assetPreparation.get(assets);\n if (existing !== undefined) return existing;\n const pending = (async () => {\n if (import.meta.env.DEV) {\n assets.configureRuntimeBinding(runtimeScopeBinding);\n } else {\n assets.configurePackIndex(new URL('pack-index.json', document.baseURI).href);\n }\n assets.setCatalogSource(assetCatalog);\n if (vfxRuntimeHost !== undefined) {\n assets.installDecoder(vfxGpuEffectContribution.kind, vfxGpuEffectContribution.decoder);\n }\n const catalog = await assets.enumerateCatalog();\n if (!catalog.ok) throw catalog.error;\n })();\n assetPreparation.set(assets, pending);\n return pending;\n}\n\nfunction previewStable(value) {\n if (value instanceof ArrayBuffer) return 'ArrayBuffer:' + JSON.stringify(Array.from(new Uint8Array(value)));\n if (ArrayBuffer.isView(value)) return value.constructor.name + ':' + JSON.stringify(Array.from(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)));\n if (Array.isArray(value)) return '[' + value.map(previewStable).join(',') + ']';\n if (value !== null && typeof value === 'object') {\n const record = value;\n return '{' + Object.keys(record).sort().map((key) => JSON.stringify(key) + ':' + previewStable(record[key])).join(',') + '}';\n }\n return JSON.stringify(value) ?? 'null';\n}\n\nasync function previewDigest(value) {\n const bytes = new TextEncoder().encode(previewStable(value));\n const digest = await crypto.subtle.digest('SHA-256', bytes);\n return 'sha256:' + Array.from(new Uint8Array(digest)).map((byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n\nasync function previewOwnerFacts(assets, resource, payload) {\n if (resource.kind === 'material') {\n const primaryPass = Array.isArray(payload.passes) ? payload.passes[0] : undefined;\n const program = primaryPass?.program?.module;\n const pass = primaryPass?.name;\n return {\n subjectDigest: await previewDigest(payload),\n bindingsDigest: await previewDigest(payload.passes),\n closureDigest: await previewDigest(payload.values ?? payload.passes),\n ...(typeof program === 'string' ? { program } : {}),\n ...(typeof pass === 'string' ? { pass } : {}),\n };\n }\n if (resource.kind === 'mesh') {\n return {\n subjectDigest: await previewDigest(payload),\n vertexDigest: await previewDigest(payload.vertices),\n indexDigest: await previewDigest(payload.indices ?? []),\n submeshDigest: await previewDigest(payload.submeshes),\n aabbDigest: await previewDigest(payload.aabb),\n };\n }\n if (resource.kind === 'texture') {\n const mipCount = typeof payload.mipLevelCount === 'number' ? payload.mipLevelCount : 1;\n const filter = 'linear';\n return {\n subjectDigest: await previewDigest(payload),\n boundDigest: await previewDigest({ width: payload.width, height: payload.height, format: payload.format }),\n uvDigest: await previewDigest({ offset: [0, 0], scale: [1, 1], rotation: 0 }),\n bindingDigest: await previewDigest({ format: payload.format, colorSpace: payload.colorSpace, filter, mipCount }),\n format: payload.format,\n colorSpace: payload.colorSpace,\n filter,\n mipCount,\n dimensions: [payload.width, payload.height],\n payloadClass: 'color',\n };\n }\n return undefined;\n}\n\nconst gameProjectionDefinitions = new Map();\nfunction registerGameProjection(kind, definition) {\n if (gameProjectionDefinitions.has(definition.id)) {\n throw new Error('forgeax: duplicate game projection id ' + definition.id);\n }\n const entry = { kind, definition };\n gameProjectionDefinitions.set(definition.id, entry);\n return () => {\n if (gameProjectionDefinitions.get(definition.id) === entry) {\n gameProjectionDefinitions.delete(definition.id);\n }\n };\n}\nconst gameProjection = {\n registerAction: (definition) => registerGameProjection('action', definition),\n registerRead: (definition) => registerGameProjection('read', definition),\n};\nfunction exposeGameInspection(app) {\n globalThis.__forgeaxGameInspection = {\n list() {\n return {\n reads: Array.from(gameProjectionDefinitions.entries())\n .filter(([, entry]) => entry.kind === 'read')\n .map(([id]) => id),\n };\n },\n async read(id) {\n const entry = gameProjectionDefinitions.get(id);\n if (entry?.kind !== 'read') throw new Error('forgeax: game read projection not found ' + id);\n return entry.definition.read();\n },\n renderer() {\n const inspection = app.renderer.inspect();\n return { state: inspection.state, frameId: inspection.frame.frameId };\n },\n };\n}\n\nasync function prepareProject(app) {\nawait prepareAssetRegistry(app.assets);\npreviewWorld = app.world;\nconst assets = app.assets;\nlet canonicalEnvironment;\nif (resource !== undefined) {\n if (resource.kind !== 'texture') {\n if (canonicalEnvironmentGuid === null) throw new Error('canonical preview environment is unavailable');\n const environment = await assets.loadByGuid(assets.parseGuid(canonicalEnvironmentGuid));\n if (!environment.ok) throw environment.error;\n if (environment.value.kind !== 'equirect') {\n throw new Error(\\`canonical preview environment expected equirect, received \\${environment.value.kind}\\`);\n }\n if (environment.value.width <= 0 || environment.value.height <= 0 || environment.value.data.byteLength === 0) {\n throw new Error('canonical preview environment must provide decoded equirect pixels');\n }\n canonicalEnvironment = app.world.allocSharedRef('EquirectAsset', environment.value);\n }\n if (resource.kind === 'vfx') {\n if (vfxRuntimeHost === undefined) throw new Error('VFX preview host was not created');\n const attached = await vfxRuntimeHost.attachWorld({ world: app.world, assets });\n if (!attached.ok) throw attached.error;\n }\n const loaded = await assets.loadByGuid(assets.parseGuid(resource.guid));\n if (!loaded.ok) throw loaded.error;\n const payload = loaded.value;\n if (resource.kind === 'vfx' && payload.kind !== 'particle-effect') {\n throw new Error(\\`VFX preview expected ParticleEffectAsset, received \\${payload.kind}\\`);\n }\n const vfxBounds = resource.kind === 'vfx' ? previewVfxBounds(payload) : undefined;\n if (resource.kind === 'vfx' && vfxBounds === undefined) {\n throw new Error('VFX preview owner did not publish finite emitter bounds');\n }\n const meshMaterialHandles = resource.kind === 'mesh' && payload.kind === 'mesh'\n ? await Promise.all(payload.materialSlots.map(async (slot) => {\n if (slot.defaultMaterial === undefined) return 0;\n const material = await assets.loadByGuid(assets.parseGuid(slot.defaultMaterial));\n if (!material.ok) throw material.error;\n if (material.value.kind !== 'material') {\n throw new Error('mesh material slot resolved to a non-material asset');\n }\n return app.world.allocSharedRef('MaterialAsset', material.value);\n }))\n : undefined;\n const meshHandle = resource.kind === 'mesh' && payload.kind === 'mesh'\n ? app.world.allocSharedRef('MeshAsset', payload)\n : app.world.internSharedRef(\n 'MeshAsset',\n createPrimitiveMesh(resource.kind === 'texture' ? 'quad' : 'sphere').unwrap(),\n );\n const textureHandle = resource.kind === 'texture' && payload.kind === 'texture'\n ? app.world.allocSharedRef('TextureAsset', payload)\n : undefined;\n if (textureHandle !== undefined && payload.kind === 'texture') {\n const bytes = payload.data instanceof Uint8ClampedArray\n ? new Uint8Array(payload.data.buffer, payload.data.byteOffset, payload.data.byteLength)\n : payload.data;\n const uploaded = await app.renderer.store.uploadTexture(textureHandle, payload, {\n bytes,\n width: payload.width,\n height: payload.height,\n mime: 'image/png',\n colorSpace: payload.colorSpace,\n mipmap: payload.mipmap,\n });\n if (!uploaded.ok) throw uploaded.error;\n }\n const materialPayload = resource.kind === 'texture' && payload.kind === 'texture'\n ? Materials.unlit([1, 1, 1, 1], { baseColorTexture: textureHandle })\n : resource.kind === 'material' && payload.kind === 'material'\n ? payload\n : undefined;\n const materialHandle = materialPayload === undefined\n ? undefined\n : app.world.allocSharedRef('MaterialAsset', materialPayload);\n const materialBindings = resource.kind === 'mesh'\n ? meshMaterialHandles\n : materialHandle === undefined\n ? undefined\n : [materialHandle];\n const rawAabb = payload.kind === 'mesh' ? payload.aabb : undefined;\n const aabb = rawAabb !== undefined && (Array.isArray(rawAabb) || ArrayBuffer.isView(rawAabb)) && rawAabb.length === 6\n ? Array.from(rawAabb)\n : resource.kind === 'mesh' && payload.kind === 'mesh'\n ? (() => { throw new Error('mesh owner did not publish a finite AABB'); })()\n : [-1, -1, -1, 1, 1, 1];\n const meshFrame = resource.kind === 'mesh'\n ? fitToolPreviewCameraToAabb(aabb, { aspect: 1, fov: Math.PI / 4 })\n : undefined;\n const textureWidth = resource.kind === 'texture' && payload.kind === 'texture' && typeof payload.width === 'number'\n ? Math.max(1, payload.width)\n : 1;\n const textureHeight = resource.kind === 'texture' && payload.kind === 'texture' && typeof payload.height === 'number'\n ? Math.max(1, payload.height)\n : 1;\n const textureAspect = textureWidth / textureHeight;\n const textureScale = textureAspect >= 1\n ? [textureAspect, 1, 1]\n : [1, 1 / textureAspect, 1];\n const center = meshFrame?.center ?? vfxBounds?.center ?? [(aabb[0] + aabb[3]) / 2, (aabb[1] + aabb[4]) / 2, (aabb[2] + aabb[5]) / 2];\n const radius = meshFrame?.radius ?? vfxBounds?.radius ?? Math.max(1, Math.hypot(aabb[3] - aabb[0], aabb[4] - aabb[1], aabb[5] - aabb[2]));\n const texturePreview = resource.kind === 'texture';\n if (resource.kind === 'vfx') {\n const effect = app.world.allocSharedRef('ParticleEffectAsset', payload);\n app.world.spawn(\n { component: Transform, data: { pos: center } },\n { component: ParticleEffectPlayer, data: { effect, playing: true, seed: 0, timeScale: 1 } },\n );\n } else {\n app.world.spawn(\n { component: Transform, data: { pos: center, ...(texturePreview ? { scale: textureScale } : {}) } },\n { component: MeshFilter, data: { assetHandle: meshHandle } },\n { component: MeshRenderer, data: materialBindings === undefined ? {} : { materials: materialBindings } },\n );\n }\n const cameraData = texturePreview\n ? {\n fov: 0,\n aspect: 1,\n near: 0.01,\n far: 100,\n projection: CAMERA_PROJECTION_ORTHOGRAPHIC,\n left: -textureScale[0] * 0.6,\n right: textureScale[0] * 0.6,\n bottom: -textureScale[1] * 0.6,\n top: textureScale[1] * 0.6,\n tonemap: TONEMAP_NONE,\n antialias: 0,\n bloom: 0,\n clearColor: [0, 0, 0, 1],\n }\n : {\n fov: Math.PI / 4,\n aspect: 1,\n near: meshFrame?.near ?? 0.01,\n far: meshFrame?.far ?? radius * 8,\n tonemap: TONEMAP_REINHARD_EXTENDED,\n };\n const cameraPosition = texturePreview\n ? [0, 0, 5]\n : [center[0], center[1], center[2] + (meshFrame?.distance ?? radius * 2.5)];\n const cameraEntity = app.world.spawn({ component: Camera, data: cameraData }, { component: Transform, data: { pos: cameraPosition } }).unwrap();\n previewCameraEntities.set(app.world, cameraEntity);\n previewCameraTargets.set(app.world, center);\n if (!texturePreview) {\n app.world.spawn({ component: DirectionalLight, data: { direction: [-0.5, -1, -0.3], intensity: 2 } });\n if (canonicalEnvironment === undefined) throw new Error('canonical preview environment was not loaded');\n app.world.spawn({ component: Skylight, data: { equirect: canonicalEnvironment } });\n app.world.spawn({ component: SkyboxBackground, data: { equirect: canonicalEnvironment } });\n }\n const ownerFacts = await previewOwnerFacts(assets, resource, payload);\n const publishedAsset = resource.kind === 'mesh' && payload.kind === 'mesh' && payload.aabb !== undefined\n ? { ...payload, aabb: Array.from(payload.aabb) }\n : payload;\n return {\n kind: resource.kind,\n guid: resource.guid,\n asset: publishedAsset,\n ...(ownerFacts === undefined ? {} : { ownerFacts }),\n };\n}\nif (bootstrapRoot === 'resource-bootstrap') return;\nlet defaultScene;\nlet defaultSceneRoot;\nconst defaultSceneGuid = ${JSON.stringify(facts.defaultScene)};\nif (defaultSceneGuid !== undefined) {\n const loaded = await assets.loadByGuid<SceneAsset>(assets.parseGuid(defaultSceneGuid));\n if (!loaded.ok) throw loaded.error;\n defaultScene = loaded.value;\n const handle = app.world.allocSharedRef('SceneAsset', loaded.value);\n const instantiated = assets.instantiate<SceneAsset>(handle, app.world);\n if (!instantiated.ok) throw instantiated.error;\n defaultSceneRoot = instantiated.value;\n}\nconst uiRoot = document.querySelector('#game-ui');\nawait app.pluginContext.plugin(gameHostPlugin({\n app,\n assets,\n canvas,\n renderer: app.renderer,\n ...(defaultScene === undefined ? {} : { defaultScene }),\n ...(defaultSceneRoot === undefined ? {} : { defaultSceneRoot }),\n uiRoot: uiRoot instanceof HTMLElement ? uiRoot : document.body,\n setPointerLockAllowed: (allowed) => app.input?.setPointerLockAllowed?.(allowed),\n ...(import.meta.env.DEV ? { gameProjection } : {}),\n}));\nconst { loader: pluginLoader } = await installCatalogLoader(app.pluginContext, pluginCatalog, 'engine');\nawait pluginLoader.root.update(projectPluginEntries(pluginEntries, 'engine'));\nawait pluginLoader.await();\n}\n\nconst query = new URLSearchParams(location.search);\nconst recipeValue = query.get('forgeax-tool-recipe');\nconst snapshotValue = query.get('forgeax-tool-snapshot');\nconst runIdValue = query.get('forgeax-tool-run-id');\nif (query.has('forgeax-tool-replay')) {\n globalThis.__forgeaxToolReplayHost = {\n ready: true,\n async run(capture) {\n const result = await replayToolPreviewCapture(capture);\n return result.ok ? { ok: true, result: result.value } : { ok: false, error: result.error };\n },\n };\n} else if (recipeValue !== null) {\n const previewRecipe = createToolPreviewRecipe(JSON.parse(recipeValue));\n const host = await createToolPreviewHost({\n ...(runIdValue === null ? {} : { runId: runIdValue }),\n recipe: previewRecipe,\n snapshot: JSON.parse(snapshotValue ?? 'null'),\n ...(resource === undefined ? {} : { resource }),\n canvas,\n app: {\n plugins: [${plugins.join(', ')}],\n ...(vfxRuntimeHost === undefined ? {} : { features: [vfxRuntimeHost.feature] }),\n },\n bundler,\n prepare: prepareProject,\n collectResourceFacts(app, current) {\n if (current === undefined) return current;\n if (resource?.kind !== 'vfx') {\n if (resource?.kind === 'material' || resource?.kind === 'mesh' || resource?.kind === 'texture') {\n const subjectDrawn = resource.kind === 'texture'\n ? app.renderer.drawCalls > 0\n : app.renderer.drawCalls > 2;\n if (!subjectDrawn) return current;\n if (resource.kind === 'mesh') {\n const asset = current.asset;\n const aabb = asset?.aabb;\n const submeshes = asset?.submeshes;\n const materialSlots = asset?.materialSlots;\n if (!Array.isArray(aabb) || aabb.length !== 6 || !Array.isArray(submeshes) || !Array.isArray(materialSlots)) {\n return current;\n }\n return {\n ...current,\n observation: {\n ...current.ownerFacts,\n aabb,\n submeshCount: submeshes.length,\n materialSlotCount: materialSlots.length,\n },\n };\n }\n return {\n ...current,\n observation: current.ownerFacts,\n };\n }\n return current;\n }\n if (vfxRuntimeHost === undefined) return current;\n const hostInspection = vfxRuntimeHost.inspect(app.world);\n const player = hostInspection?.players[0];\n const renderObservation = vfxRuntimeHost.feature.inspect();\n if (player === undefined || renderObservation.frameNumber < 0) {\n return current;\n }\n const bounds = previewVfxBounds(current.asset);\n if (bounds === undefined) return current;\n const emitterDigest = JSON.stringify(player.emitters.map(({ id, module, capacity }) => ({ id, module, capacity })));\n const sampleDigest = JSON.stringify(player.emitters.map(({ id, schedule }) => ({ id, schedule })));\n const boundsDigest = JSON.stringify(player.emitters.map(({ id, bounds: emitterBounds }) => ({ id, bounds: emitterBounds })));\n const computeDigest = player.programFingerprint;\n const indirectDigest = JSON.stringify(player.emitters.map(({ id, renderers }) => ({ id, renderers: renderers.map(({ kind, enabled }) => ({ kind, enabled })) })));\n return {\n ...current,\n observation: {\n subjectDigest: current.asset.programFingerprint,\n programFingerprint: player.programFingerprint,\n emitterDigest,\n sampleDigest,\n boundsDigest,\n computeDigest,\n indirectDigest,\n authoredBounds: bounds.aabb,\n seed: player.seed,\n fixedDelta: player.fixedDelta,\n timelineFrames: previewRecipe.frames,\n dispatches: renderObservation.dispatches,\n indirectDraws: renderObservation.indirectDraws,\n subjectOutputs: renderObservation.subjectOutputs,\n },\n };\n },\n onDispose: async () => {\n if (vfxRuntimeHost === undefined || previewWorld === undefined) return;\n const detached = await vfxRuntimeHost.detachWorld({ world: previewWorld });\n if (!detached.ok) throw detached.error;\n },\n executeAction(action) {\n return !globalThis.dispatchEvent(new CustomEvent('forgeax-tool-action', {\n detail: action,\n cancelable: true,\n }));\n },\n });\n if (!host.ok) {\n globalThis.__forgeaxToolHost = {\n ready: true,\n capture: async () => ({ ok: false, error: host.error }),\n run: async () => ({ ok: false, error: host.error }),\n dispose: async () => undefined,\n };\n } else {\n globalThis.__forgeaxToolHost = {\n ready: true,\n async capture() {\n const result = await host.value.capture();\n return result.ok ? { ok: true, result: result.value } : { ok: false, error: result.error };\n },\n async run() {\n const result = await host.value.run();\n return result.ok ? { ok: true, result: result.value } : { ok: false, error: result.error };\n },\n dispose: () => host.value.dispose(),\n };\n window.addEventListener('pagehide', () => void host.value.dispose(), { once: true });\n }\n} else {\n // WebDriver/headless browsers cannot satisfy the trusted-gesture requirement\n // for pointer lock. Keep the game running and let its keyboard fallback own\n // camera input; real browser users retain the normal click-to-lock path.\n const pointerLockAllowed =\n typeof navigator !== 'undefined' && navigator.webdriver === true ? () => false : undefined;\n const result = await createApp(\n canvas,\n {\n plugins: [${plugins.join(', ')}],\n ...(pointerLockAllowed === undefined ? {} : { pointerLockAllowed }),\n },\n bundler,\n );\n if (!result.ok) throw result.error;\n const app = result.value;\n if (import.meta.env.DEV) exposeGameInspection(app);\n await prepareProject(app);\n${bootstrapPlugin}\n app.start().unwrap();\n let disposed = false;\n const dispose = () => {\n if (disposed) return;\n disposed = true;\n resizeObserver.disconnect();\n void app.dispose();\n };\n window.addEventListener('pagehide', dispose);\n}\n`;\n}\n\nfunction escapeHtml(value: string): string {\n return value.replace(/[&<>\"']/g, (character) => {\n switch (character) {\n case '&':\n return '&amp;';\n case '<':\n return '&lt;';\n case '>':\n return '&gt;';\n case '\"':\n return '&quot;';\n case \"'\":\n return '&#39;';\n }\n return character;\n });\n}\n\nfunction htmlSource(title: string): string {\n return `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <link rel=\"icon\" href=\"data:,\" />\n <title>${escapeHtml(title)}</title>\n <style>\n html, body, #app-shell, #app { width: 100%; height: 100%; margin: 0; overflow: hidden; }\n body { background: #05070b; }\n #app { display: block; }\n #app-shell { position: relative; }\n #game-ui { position: absolute; inset: 0; overflow: hidden; pointer-events: none; }\n #game-ui > * { pointer-events: auto; }\n #forgeax-fatal { position: fixed; inset: 0; z-index: 2147483647; display: none; place-items: center; padding: 24px; background: #0b0d10; color: #e6e6e6; font: 15px/1.6 system-ui, sans-serif; text-align: center; white-space: pre-wrap; }\n </style>\n </head>\n <body>\n <div id=\"app-shell\"><canvas id=\"app\"></canvas><div id=\"game-ui\"></div></div><div id=\"forgeax-fatal\" role=\"alert\"></div>\n <script>\n (() => {\n const appendStructuredFailure = (value, prefix, depth, seen, lines) => {\n if (value === null || typeof value !== 'object' || depth > 3) return;\n if (seen.has(value)) {\n lines.push((prefix || 'cause') + ': [circular]');\n return;\n }\n seen.add(value);\n const record = value;\n const name = typeof record.name === 'string' && record.name.length > 0\n ? record.name\n : undefined;\n const code = typeof record.code === 'string' && record.code.length > 0\n ? record.code\n : undefined;\n const message = typeof record.message === 'string' && record.message.length > 0\n ? record.message\n : undefined;\n if (name !== undefined || code !== undefined || message !== undefined) {\n const identity = [name || 'Error', code].filter(Boolean).join(' ');\n lines.push((prefix ? prefix + ': ' : '') + identity + (message ? ': ' + message : ''));\n }\n for (const key of ['expected', 'hint', 'reason']) {\n if (typeof record[key] === 'string' && record[key].length > 0) {\n lines.push((prefix ? prefix + '.' : '') + key + ': ' + record[key]);\n }\n }\n for (const key of ['cause', 'detail', 'webgpuError', 'wgpuError', 'error']) {\n const nested = record[key];\n const nestedPrefix = (prefix ? prefix + '.' : '') + key;\n if (nested !== null && typeof nested === 'object') {\n appendStructuredFailure(nested, nestedPrefix, depth + 1, seen, lines);\n } else if (typeof nested === 'string' && nested.length > 0) {\n lines.push(nestedPrefix + ': ' + nested);\n }\n }\n };\n const formatStartupFailure = (reason) => {\n if (reason !== null && typeof reason === 'object') {\n const lines = [];\n appendStructuredFailure(reason, '', 0, new Set(), lines);\n if (lines.length > 0) return lines.join('\\\\n');\n try {\n return JSON.stringify(reason) || 'Unknown structured startup failure';\n } catch {\n return 'Unserializable structured startup failure';\n }\n }\n return String(reason ?? 'Unknown startup failure');\n };\n const show = (reason) => {\n const notice = document.querySelector('#forgeax-fatal');\n if (!(notice instanceof HTMLElement)) return;\n let message = formatStartupFailure(reason);\n if (/webgpu|adapter-unavailable|no usable (rendering )?backend/i.test(message)) {\n message += '\\\\n\\\\nRenderer diagnosis: ForgeaX supports browser WebGPU and a wgpu/WebGL2 fallback. This failure alone does not prove that WebGPU is unsupported; use the structured code, hint, and nested backend causes above.';\n }\n notice.textContent = 'ForgeaX game failed to start.\\\\n' + message;\n notice.style.display = 'grid';\n };\n window.addEventListener('error', (event) => show(event.error ?? event.message));\n window.addEventListener('unhandledrejection', (event) => show(event.reason));\n })();\n </script>\n <script type=\"module\" src=\"./main.ts\"></script>\n </body>\n</html>\n`;\n}\n\nexport async function createViteConfig(\n facts: ProjectFacts,\n command: 'serve' | 'build',\n base = '/',\n options: {\n readonly bootstrapRoot?: BootstrapRoot;\n readonly outDir?: string;\n readonly server?: ProjectPortOptions;\n } = {},\n): Promise<InlineConfig> {\n const bootstrapRoot = options.bootstrapRoot ?? 'project-bootstrap';\n // The canonical kit ships the engine's default environment (sky.hdr equirect).\n // Authored scenes (e.g. the default game template) reference it as a Skylight /\n // SkyboxBackground dependency, so a self-contained standalone build must catalog\n // it on the game path too — not only the tool-preview (resource-bootstrap) path.\n const canonicalKit = await resolveCanonicalKit();\n const generated = resolve(facts.root, '.forgeax', 'generated');\n await mkdir(generated, { recursive: true });\n const projectRoots = facts.assetRoots.map((root) => resolve(facts.root, root));\n const ignorePath =\n bootstrapRoot === 'resource-bootstrap'\n ? isResourcePreviewIgnoredPath\n : isProjectSourceIgnoredPath;\n const builtinPack = await prepareBuiltinPack(projectRoots, generated, ignorePath);\n await Promise.all([\n writeFile(resolve(generated, 'index.html'), htmlSource(facts.name)),\n writeFile(resolve(generated, 'main.ts'), hostSource(facts, bootstrapRoot, canonicalKit?.guid)),\n ]);\n const roots = [\n ...projectRoots,\n ...(builtinPack === undefined ? [] : [builtinPack]),\n ...(canonicalKit === undefined ? [] : [canonicalKit.root]),\n ];\n const importers = [...projectImporters(facts)];\n const runtimeBinding = createStandaloneRuntimeAssetBinding(facts.id);\n const engineWorkspaceResolver = await createEngineWorkspaceResolver(facts.root);\n const consumerAliases = await consumerEngineAliases(facts.root);\n const plugins: Plugin[] = [\n ...(engineWorkspaceResolver === undefined ? [] : [engineWorkspaceResolver]),\n ...(command === 'serve' && process.env.FORGEAX_ENGINE_RHI_DEBUG === '1'\n ? [vitePluginRhiDebug({ rootDir: facts.root }) as Plugin]\n : []),\n forgeaxShader() as Plugin,\n pluginPack({\n roots,\n runtimeBinding,\n ddc: devKitDdcRoots(facts.root),\n refresh: command === 'serve' ? reloadAssetHost() : undefined,\n importers: [\n audioImporter,\n imageImporter,\n fbxImporter,\n gltfImporter,\n fontImporter,\n ...importers,\n ],\n cookers: [createMaterialPackCooker(roots), createParticleCodeNativeCookerFromRoots(roots)],\n ignorePath,\n }) as Plugin,\n ];\n return {\n root: generated,\n base,\n configFile: false,\n publicDir:\n facts.assetPublicDir === undefined ? false : resolve(facts.root, facts.assetPublicDir),\n plugins,\n resolve: {\n alias: consumerAliases,\n dedupe: ['@forgeax/engine'],\n },\n server: { ...options.server, fs: { allow: [facts.root, ...roots] } },\n build: {\n target: 'esnext',\n outDir: options.outDir ?? resolve(facts.root, 'dist'),\n emptyOutDir: true,\n rollupOptions: { input: resolve(generated, 'index.html') },\n },\n };\n}\n","import { createHash } from 'node:crypto';\nimport { mkdir, mkdtemp, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { basename, dirname, relative, resolve, sep } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { type DefaultTreeAdapterTypes, parse } from 'parse5';\nimport { type Plugin, parseAst, Visitor, build as viteBuild } from 'vite';\nimport { type DistArtifact, type DistManifest, mediaType } from './dist.js';\nimport { createEngineWorkspaceResolverForProject } from './host.js';\nimport type { CommandError, CommandResult } from './types.js';\n\nconst SINGLE_HTML_FORMAT = 'forgeax-single-html-game' as const;\nconst GENERATED_PREFIX = '__forgeax-bundle/';\n\nexport interface SingleHtmlBundleArtifact {\n readonly path: string;\n readonly bytes: Uint8Array;\n readonly mediaType: string;\n}\n\nexport interface SingleHtmlBundle {\n readonly entrySource: string;\n readonly artifacts: readonly SingleHtmlBundleArtifact[];\n}\n\nexport interface SingleHtmlPackageOptions {\n readonly distRoot: string;\n readonly output: string;\n readonly manifest: DistManifest;\n readonly bundle: SingleHtmlBundle;\n}\n\nexport interface SingleHtmlPackageResult {\n readonly schemaVersion: '1.0.0';\n readonly format: typeof SINGLE_HTML_FORMAT;\n readonly target: 'file';\n readonly project: DistManifest['project'];\n readonly base: DistManifest['base'];\n readonly html: { readonly path: string; readonly bytes: number; readonly sha256: string };\n readonly checksumPath: string;\n readonly distManifestSha256: string;\n readonly embeddedAssets: number;\n readonly run: {\n readonly local: string;\n readonly shared: string;\n };\n}\n\nclass SingleHtmlError extends Error implements CommandError {\n constructor(\n readonly code: string,\n readonly expected: string,\n readonly hint: string,\n readonly detail: Readonly<Record<string, unknown>>,\n ) {\n super(`${code}: ${hint}`);\n this.name = 'SingleHtmlError';\n }\n}\n\nfunction errorResult(\n code: string,\n expected: string,\n hint: string,\n detail: Readonly<Record<string, unknown>> = {},\n): CommandResult<never> {\n return { ok: false, error: new SingleHtmlError(code, expected, hint, detail) };\n}\n\nfunction toErrorResult(\n cause: unknown,\n code: string,\n expected: string,\n hint: string,\n): CommandResult<never> {\n if (cause instanceof SingleHtmlError) return { ok: false, error: cause };\n return errorResult(code, expected, hint, {\n reason: cause instanceof Error ? cause.message : String(cause),\n });\n}\n\nfunction normalizePath(value: string): string | undefined {\n let decoded: string;\n try {\n decoded = decodeURIComponent(value.split(/[?#]/, 1)[0] ?? value);\n } catch {\n return undefined;\n }\n const normalized = decoded.replace(/\\\\/g, '/').replace(/^\\.\\//, '').replace(/^\\/+/, '');\n const segments = normalized.split('/');\n if (\n normalized.length === 0 ||\n segments.some((segment) => segment.length === 0 || segment === '.' || segment === '..')\n ) {\n return undefined;\n }\n return normalized;\n}\n\nfunction safeScriptText(value: string): string {\n return value.replace(/<\\/script/gi, '<\\\\/script');\n}\n\nfunction hashBytes(bytes: Uint8Array): string {\n return createHash('sha256').update(bytes).digest('hex');\n}\n\nfunction contentTypeForDataUri(value: string): string {\n const semicolon = value.indexOf(';');\n return semicolon < 0 ? value : value.slice(0, semicolon);\n}\n\nfunction dataUri(bytes: Uint8Array, type: string): string {\n return `data:${contentTypeForDataUri(type)};base64,${Buffer.from(bytes).toString('base64')}`;\n}\n\ninterface HtmlElement {\n readonly name: string;\n readonly start: number;\n readonly openEnd: number;\n readonly end: number;\n readonly contentStart?: number;\n readonly contentEnd?: number;\n readonly attributes: readonly { readonly name: string; readonly value: string }[];\n readonly attributeLocations: Readonly<\n Record<string, { readonly startOffset: number; readonly endOffset: number }>\n >;\n}\n\ninterface Replacement {\n readonly start: number;\n readonly end: number;\n readonly value: string;\n}\n\ntype ParsedElement = DefaultTreeAdapterTypes.Element;\ntype ParsedNode = DefaultTreeAdapterTypes.Node;\n\nfunction attributeValueRange(\n source: string,\n location: { readonly startOffset: number; readonly endOffset: number },\n): { readonly startOffset: number; readonly endOffset: number } | undefined {\n const raw = source.slice(location.startOffset, location.endOffset);\n const equals = raw.indexOf('=');\n if (equals < 0) return undefined;\n let cursor = equals + 1;\n while (/\\s/.test(raw[cursor] ?? '')) cursor += 1;\n const quote = raw[cursor] === '\"' || raw[cursor] === \"'\" ? raw[cursor] : undefined;\n if (quote !== undefined) {\n const start = cursor + 1;\n const end = raw.lastIndexOf(quote);\n return end <= start\n ? undefined\n : { startOffset: location.startOffset + start, endOffset: location.startOffset + end };\n }\n return {\n startOffset: location.startOffset + cursor,\n endOffset: location.endOffset,\n };\n}\n\nfunction scanHtmlElements(source: string): readonly HtmlElement[] {\n const document = parse(source, { sourceCodeLocationInfo: true });\n const elements: HtmlElement[] = [];\n const visit = (node: ParsedNode): void => {\n if (node.nodeName === '#document' || node.nodeName === '#document-fragment') {\n for (const child of node.childNodes) visit(child);\n return;\n }\n if (\n node.nodeName === '#text' ||\n node.nodeName === '#comment' ||\n node.nodeName === '#documentType'\n ) {\n return;\n }\n const element = node as ParsedElement;\n const location = element.sourceCodeLocation;\n if (location?.startTag === undefined) {\n for (const child of element.childNodes) visit(child);\n return;\n }\n const name = element.tagName.toLowerCase();\n const attributes = element.attrs.map(({ name: attributeName, value }) => ({\n name: attributeName.toLowerCase(),\n value,\n }));\n const attributeLocations: Record<\n string,\n { readonly startOffset: number; readonly endOffset: number }\n > = {};\n for (const attribute of attributes) {\n const attributeLocation = location.attrs?.[attribute.name];\n if (attributeLocation !== undefined) attributeLocations[attribute.name] = attributeLocation;\n }\n elements.push({\n name,\n start: location.startTag.startOffset,\n openEnd: location.startTag.endOffset,\n end: location.endTag?.endOffset ?? location.startTag.endOffset,\n ...(name === 'script' || name === 'style'\n ? {\n contentStart: location.startTag.endOffset,\n contentEnd: location.endTag?.startOffset ?? location.startTag.endOffset,\n }\n : {}),\n attributes,\n attributeLocations,\n });\n for (const child of element.childNodes) visit(child);\n };\n visit(document);\n return elements;\n}\n\nfunction attribute(\n element: HtmlElement,\n name: string,\n): { readonly name: string; readonly value: string } | undefined {\n return element.attributes.find((candidate) => candidate.name === name);\n}\n\nfunction attributeValue(element: HtmlElement, name: string): string | undefined {\n return attribute(element, name)?.value;\n}\n\nfunction isModuleScript(element: HtmlElement): boolean {\n return element.name === 'script' && attributeValue(element, 'type')?.toLowerCase() === 'module';\n}\n\nfunction isStylesheet(element: HtmlElement): boolean {\n return (\n element.name === 'link' &&\n attributeValue(element, 'rel')?.toLowerCase().split(/\\s+/).includes('stylesheet') === true\n );\n}\n\nfunction isModulePreload(element: HtmlElement): boolean {\n return (\n element.name === 'link' &&\n attributeValue(element, 'rel')?.toLowerCase().split(/\\s+/).includes('modulepreload') === true\n );\n}\n\nfunction resourceForPath(\n path: string,\n resources: ReadonlyMap<string, SingleHtmlBundleArtifact>,\n): SingleHtmlBundleArtifact | undefined {\n const normalized = normalizePath(path);\n if (normalized === undefined) return undefined;\n const direct = resources.get(normalized);\n if (direct !== undefined) return direct;\n const suffix = [...resources.entries()].filter(([candidate]) =>\n candidate.endsWith(`/${normalized}`),\n );\n return suffix.length === 1 ? suffix[0]?.[1] : undefined;\n}\n\nfunction resourcePath(reference: string, basePath: string): string | undefined {\n try {\n return normalizePath(new URL(reference, `https://forgeax.invalid/${basePath}`).pathname);\n } catch {\n return undefined;\n }\n}\n\nfunction applyReplacements(source: string, replacements: readonly Replacement[]): string {\n const unique = new Map<string, Replacement>();\n for (const replacement of replacements) {\n unique.set(`${replacement.start}:${replacement.end}`, replacement);\n }\n const ordered = [...unique.values()].sort((left, right) => left.start - right.start);\n for (let index = 1; index < ordered.length; index += 1) {\n const previous = ordered[index - 1];\n const current = ordered[index];\n if (previous !== undefined && current !== undefined && previous.end > current.start) {\n throw new Error(\n `single-html AST replacements overlap (${previous.start}:${previous.end} and ${current.start}:${current.end})`,\n );\n }\n }\n return ordered\n .reverse()\n .reduce(\n (value, replacement) =>\n value.slice(0, replacement.start) + replacement.value + value.slice(replacement.end),\n source,\n );\n}\n\nfunction inlineCss(\n css: string,\n cssPath: string,\n resources: ReadonlyMap<string, SingleHtmlBundleArtifact>,\n): CommandResult<string> {\n const replacements: Replacement[] = [];\n const pattern = /url\\(\\s*([\"']?)(.*?)\\1\\s*\\)/gi;\n for (;;) {\n const match = pattern.exec(css);\n if (match === null) break;\n const reference = match[2]?.trim();\n if (\n reference === undefined ||\n reference.length === 0 ||\n reference.startsWith('data:') ||\n reference.startsWith('#')\n ) {\n continue;\n }\n if (/^(?:https?:|blob:)/i.test(reference)) {\n return errorResult(\n 'single-html-css-external-resource',\n 'CSS URL references to be embedded or data/blob URLs',\n 'Move the CSS resource into the verified dist closure before packaging.',\n { cssPath, reference },\n );\n }\n const path = resourcePath(reference, cssPath);\n const resource = path === undefined ? undefined : resourceForPath(path, resources);\n if (resource === undefined) {\n return errorResult(\n 'single-html-css-asset-missing',\n 'every local CSS URL to resolve to an embedded dist artifact',\n 'Add the referenced asset to the project asset closure and rebuild.',\n { cssPath, reference, path: path ?? null },\n );\n }\n replacements.push({\n start: match.index,\n end: match.index + match[0].length,\n value: `url(${dataUri(resource.bytes, resource.mediaType)})`,\n });\n }\n return { ok: true, value: applyReplacements(css, replacements) };\n}\n\nfunction collectEntrySource(html: string): CommandResult<string> {\n const entries = scanHtmlElements(html).filter((element) => isModuleScript(element));\n const external = entries.filter((element) => attributeValue(element, 'src') !== undefined);\n const inline = entries.filter((element) => attributeValue(element, 'src') === undefined);\n if (external.length === 0 && inline.length === 0) {\n return errorResult(\n 'single-html-entry-missing',\n 'production index.html to contain one module entry',\n 'Rebuild the game with a module entry in its generated host.',\n );\n }\n if (external.length > 1 || inline.length > 1) {\n return errorResult(\n 'single-html-entry-ambiguous',\n 'production index.html to contain exactly one module entry',\n 'Converge the generated host to one ForgeaX module entry before packaging.',\n { external: external.length, inline: inline.length },\n );\n }\n const element = external[0] ?? inline[0];\n if (element === undefined) throw new Error('single-html entry selection was unexpectedly empty');\n const src = attributeValue(element, 'src');\n if (src === undefined && element.contentStart !== undefined && element.contentEnd !== undefined) {\n return { ok: true, value: html.slice(element.contentStart, element.contentEnd) };\n }\n if (src === undefined) {\n return errorResult(\n 'single-html-entry-missing',\n 'a module entry source',\n 'Add a module entry to index.html.',\n );\n }\n if (/^(?:https?:|file:|data:|blob:)/i.test(src)) {\n return errorResult(\n 'single-html-entry-external',\n 'the module entry to be a project-local dist artifact',\n 'Rebuild the game so the generated host points at a local production module.',\n { src },\n );\n }\n return { ok: true, value: src };\n}\n\nasync function filesUnder(root: string, directory = root): Promise<string[]> {\n const result: string[] = [];\n for (const name of (await readdir(directory)).sort()) {\n const path = resolve(directory, name);\n const info = await stat(path);\n if (info.isDirectory()) result.push(...(await filesUnder(root, path)));\n else if (info.isFile()) result.push(path);\n }\n return result;\n}\n\nfunction isPreloadHelperSource(value: unknown): value is string {\n if (typeof value !== 'string') return false;\n const path = value.split(/[?#]/, 1)[0] ?? value;\n const name = path.slice(path.lastIndexOf('/') + 1);\n return name.startsWith('preload-helper-') && name.endsWith('.js');\n}\n\nfunction isStaticImportSource(source: {\n readonly type?: string;\n readonly expressions?: readonly unknown[];\n}): boolean {\n return (\n source.type === 'Literal' ||\n source.type === 'StringLiteral' ||\n (source.type === 'TemplateLiteral' && source.expressions?.length === 0)\n );\n}\n\ntype SingleHtmlProgram = ReturnType<typeof parseAst>;\n\ninterface SingleHtmlMagicString {\n overwrite(start: number, end: number, content: string): SingleHtmlMagicString;\n hasChanged(): boolean;\n}\n\ninterface SingleHtmlTransformMeta {\n readonly ast?: SingleHtmlProgram;\n readonly magicString?: SingleHtmlMagicString;\n}\n\ninterface SingleHtmlPluginContext {\n error(message: string): never;\n}\n\ninterface SingleHtmlOutputChunk {\n type: 'chunk';\n fileName: string;\n code: string;\n}\n\ninterface SingleHtmlOutputAsset {\n type: 'asset';\n fileName: string;\n source?: string | Uint8Array;\n}\n\ntype SingleHtmlOutputBundle = Record<string, SingleHtmlOutputChunk | SingleHtmlOutputAsset>;\n\nfunction programReplacements(program: SingleHtmlProgram): readonly Replacement[] {\n const replacements: Replacement[] = [];\n const preloadBindings = new Set<string>();\n new Visitor({\n ImportDeclaration(node) {\n if (!isPreloadHelperSource(node.source.value)) return;\n for (const specifier of node.specifiers) {\n if (specifier.type === 'ImportSpecifier') preloadBindings.add(specifier.local.name);\n }\n },\n CallExpression(node) {\n if (\n node.callee.type !== 'Identifier' ||\n !preloadBindings.has(node.callee.name) ||\n node.arguments.length < 2\n ) {\n return;\n }\n const dependencies = node.arguments[1];\n if (dependencies !== undefined) {\n replacements.push({ start: dependencies.start, end: dependencies.end, value: 'void 0' });\n }\n },\n ImportExpression(node) {\n if (isStaticImportSource(node.source)) return;\n replacements.push({\n start: node.start,\n end: node.start + 'import'.length,\n value: 'globalThis.__forgeaxImport',\n });\n },\n }).visit(program);\n return replacements;\n}\n\nfunction outputReplacements(program: SingleHtmlProgram): readonly Replacement[] {\n const replacements: Replacement[] = [];\n new Visitor({\n ImportExpression(node) {\n replacements.push({\n start: node.start,\n end: node.start + 'import'.length,\n value: 'globalThis.__forgeaxImport',\n });\n },\n }).visit(program);\n return replacements;\n}\n\nfunction rewriteOutputJavaScript(code: string): string {\n const program = parseAst(code);\n return applyReplacements(code, outputReplacements(program));\n}\n\nfunction residualImportStart(code: string): number | undefined {\n let residualStart: number | undefined;\n new Visitor({\n ImportExpression(node) {\n residualStart ??= node.start;\n },\n }).visit(parseAst(code));\n return residualStart;\n}\n\nfunction isJavaScriptOutputAsset(fileName: string): boolean {\n return /\\.(?:c?js|mjs)$/i.test(fileName);\n}\n\nfunction singleHtmlBundlePlugin(): Plugin {\n const plugin = {\n name: 'forgeax-single-html-bundle-runtime',\n enforce: 'post',\n transform: {\n order: 'post',\n handler(\n this: SingleHtmlPluginContext,\n code: string,\n _id: string,\n meta?: SingleHtmlTransformMeta,\n ) {\n let program = meta?.ast;\n if (program === undefined) {\n try {\n program = parseAst(code);\n } catch {\n return null;\n }\n }\n const replacements = programReplacements(program);\n if (replacements.length === 0) return null;\n if (meta?.magicString !== undefined) {\n for (const replacement of replacements) {\n meta.magicString.overwrite(replacement.start, replacement.end, replacement.value);\n }\n return meta.magicString.hasChanged() ? meta.magicString : null;\n }\n return applyReplacements(code, replacements);\n },\n },\n generateBundle(\n this: SingleHtmlPluginContext,\n _outputOptions: unknown,\n bundle: SingleHtmlOutputBundle,\n ) {\n for (const output of Object.values(bundle)) {\n if (output.type === 'chunk') {\n output.code = rewriteOutputJavaScript(output.code);\n } else if (isJavaScriptOutputAsset(output.fileName) && output.source !== undefined) {\n const source =\n typeof output.source === 'string'\n ? output.source\n : Buffer.from(output.source).toString('utf8');\n output.source = rewriteOutputJavaScript(source);\n } else {\n continue;\n }\n const code = output.type === 'chunk' ? output.code : String(output.source);\n const residualStart = residualImportStart(code);\n if (residualStart !== undefined) {\n this.error(\n `single-html bundle left a native dynamic import in ${output.fileName} at ${residualStart}`,\n );\n }\n }\n },\n resolveFileUrl: ({ fileName }: { readonly fileName: string }) =>\n JSON.stringify(`${GENERATED_PREFIX}${fileName}`),\n } as unknown as Plugin;\n return plugin;\n}\n\nexport async function bundleSingleHtmlEntry(\n distRootInput: string,\n indexHtml: string,\n projectRoot?: string,\n): Promise<CommandResult<SingleHtmlBundle>> {\n const distRoot = resolve(distRootInput);\n const selected = collectEntrySource(indexHtml);\n if (!selected.ok) return selected;\n const source = selected.value;\n const entryPath = normalizePath(source);\n const temporaryRoot = await mkdtemp(resolve(tmpdir(), 'forgeax-single-html-bundle-'));\n try {\n let inputPath: string | undefined;\n if (entryPath !== undefined) {\n const candidate = resolve(distRoot, entryPath);\n try {\n const candidateInfo = await stat(candidate);\n if (candidateInfo.isFile()) inputPath = candidate;\n } catch {\n // A missing path is reported by Vite below as a bundle failure; keep\n // inline source handling deterministic rather than guessing from text.\n }\n }\n if (inputPath === undefined) {\n inputPath = resolve(temporaryRoot, 'inline-entry.mjs');\n await writeFile(inputPath, source, 'utf8');\n }\n const outputRoot = resolve(temporaryRoot, 'dist');\n const resolver: Plugin | undefined =\n projectRoot === undefined\n ? undefined\n : await createEngineWorkspaceResolverForProject(projectRoot);\n await viteBuild({\n configFile: false,\n root: distRoot,\n base: './',\n logLevel: 'error',\n plugins: [singleHtmlBundlePlugin(), ...(resolver === undefined ? [] : [resolver])],\n experimental: {\n renderBuiltUrl: (filename: string) => `forgeax-resource:///${GENERATED_PREFIX}${filename}`,\n },\n build: {\n outDir: outputRoot,\n emptyOutDir: true,\n target: 'esnext',\n minify: false,\n sourcemap: false,\n assetsInlineLimit: 0,\n modulePreload: false,\n rolldownOptions: {\n input: inputPath,\n output: {\n codeSplitting: false,\n entryFileNames: 'entry.mjs',\n chunkFileNames: 'assets/[name]-[hash].mjs',\n assetFileNames: 'assets/[name]-[hash][extname]',\n },\n experimental: { nativeMagicString: true },\n },\n },\n });\n const paths = (await filesUnder(outputRoot)).map((path) =>\n relative(outputRoot, path).split(sep).join('/'),\n );\n const entry = paths.find((path) => path === 'entry.mjs');\n if (entry === undefined) {\n return errorResult(\n 'single-html-bundle-entry-missing',\n 'Vite to emit exactly one entry.mjs',\n 'Inspect the production entry and the single-html bundler output.',\n { outputRoot, paths },\n );\n }\n const generatedPaths = paths.filter((path) => path !== entry);\n const artifacts: SingleHtmlBundleArtifact[] = [];\n for (const path of generatedPaths) {\n const bytes = await readFile(resolve(outputRoot, path));\n artifacts.push({\n path: `${GENERATED_PREFIX}${path}`,\n bytes,\n mediaType: mediaType(path),\n });\n }\n const entryBytes = await readFile(resolve(outputRoot, entry));\n return {\n ok: true,\n value: {\n entrySource: entryBytes.toString('utf8'),\n artifacts,\n },\n };\n } catch (cause) {\n return toErrorResult(\n cause,\n 'single-html-bundle-failed',\n 'the production module entry to converge into one executable bundle',\n 'Repair the production entry or inspect the Vite/Rolldown diagnostic before packaging.',\n );\n } finally {\n await rm(temporaryRoot, { recursive: true, force: true });\n }\n}\n\nfunction workerPrelude(resources: readonly SingleHtmlBundleArtifact[]): string {\n const payload = resources.map((resource) => ({\n path: resource.path,\n mime: resource.mediaType,\n data: Buffer.from(resource.bytes).toString('base64'),\n }));\n const template = `globalThis.process??={env:{},versions:{node:'0.0.0'},platform:'browser',argv:[]};\nconst __forgeaxWorkerPayload=${JSON.stringify(payload)};\nconst __forgeaxSourcePath=__FORGEAX_SOURCE_PATH__;\nconst __forgeaxNativeURL=globalThis.URL;\nconst __forgeaxNativeFetch=globalThis.fetch?.bind(globalThis);\nconst __forgeaxNativePostMessage=globalThis.postMessage?.bind(globalThis);\nconst __forgeaxOwnedUrls=new Set();\nconst __forgeaxBytes=(value)=>{const binary=atob(value);const bytes=new Uint8Array(binary.length);for(let index=0;index<binary.length;index+=1)bytes[index]=binary.charCodeAt(index);return bytes;};\nconst __forgeaxDataURL=(source)=>{const bytes=new TextEncoder().encode(source);let binary='';for(const byte of bytes)binary+=String.fromCharCode(byte);return 'data:text/javascript;base64,'+btoa(binary);};\nconst __forgeaxWorkerURL=(source)=>{if(/^(?:file:|data:|about:)/i.test(String(globalThis.location?.protocol??'')))return __forgeaxDataURL(source);const blob=__forgeaxNativeURL.createObjectURL(new Blob([source],{type:'text/javascript'}));__forgeaxOwnedUrls.add(blob);return blob;};\nconst __forgeaxNormalize=(value)=>{try{return decodeURIComponent(String(value).split(/[?#]/,1)[0]).replaceAll('\\\\\\\\','/').replace(/^\\\\/+/, '');}catch{return undefined;}};\nconst __forgeaxWithoutBundle=(value)=>String(value).replace(/^__forgeax-bundle\\\\//,'');\nconst __forgeaxLookup=(value)=>{let url;try{url=value instanceof __forgeaxNativeURL?value:new __forgeaxNativeURL(String(value),'https://forgeax.invalid/'+__forgeaxSourcePath);}catch{return undefined;}const path=__forgeaxNormalize(url.pathname);if(path===undefined)return undefined;const normalized=__forgeaxWithoutBundle(path);const exact=__forgeaxWorkerPayload.find((entry)=>entry.path===path||__forgeaxWithoutBundle(entry.path)===normalized);if(exact!==undefined)return exact;const suffix=__forgeaxWorkerPayload.filter((entry)=>normalized.endsWith('/'+__forgeaxWithoutBundle(entry.path)));if(suffix.length===1)return suffix[0];const name=normalized.slice(normalized.lastIndexOf('/')+1);const matches=__forgeaxWorkerPayload.filter((entry)=>__forgeaxWithoutBundle(entry.path).slice(__forgeaxWithoutBundle(entry.path).lastIndexOf('/')+1)===name);return matches.length===1?matches[0]:undefined;};\nconst __forgeaxResourceURL=(value)=>{const raw=String(value);try{const url=new __forgeaxNativeURL(raw,'https://forgeax.invalid/'+__forgeaxSourcePath);if(url.protocol!=='http:'&&url.protocol!=='https:')return url;const path=__forgeaxNormalize(url.pathname);return path===undefined?url:new __forgeaxNativeURL('forgeax-resource:///'+__forgeaxWithoutBundle(path));}catch{return new __forgeaxNativeURL(raw,'https://forgeax.invalid/'+__forgeaxSourcePath);}};\nglobalThis.__forgeaxURL=__forgeaxResourceURL;\nclass __ForgeaxURL extends __forgeaxNativeURL{constructor(input,base){if(base!==undefined&&/^blob:/i.test(String(base))&&!/^[a-z][a-z0-9+.-]*:/i.test(String(input))){super(__forgeaxResourceURL(input));return;}super(input,base);}}\nglobalThis.URL=__ForgeaxURL;\nconst __forgeaxNote=(kind,specifier)=>{const value={kind,specifier:String(specifier)};try{__forgeaxNativePostMessage?.({__forgeaxResourceMiss:value});}catch{}};\nconst __forgeaxNoteHit=()=>{try{__forgeaxNativePostMessage?.({__forgeaxResourceHit:1});}catch{}};\nconst __forgeaxNoteExternal=(kind,specifier)=>{const value={kind,specifier:String(specifier)};try{__forgeaxNativePostMessage?.({__forgeaxExternalRequest:value});}catch{}};\nconst __forgeaxResponse=(entry)=>{__forgeaxNoteHit();return new Response(__forgeaxBytes(entry.data),{status:200,headers:{'Content-Type':entry.mime}});};\nconst __forgeaxImportUrls=new Map();\nconst __forgeaxImport=async(value)=>{const entry=__forgeaxLookup(value);if(entry===undefined){__forgeaxNote('import',value);throw new TypeError('forgeax single-html worker resource miss');}let url=__forgeaxImportUrls.get(entry.path);if(url===undefined){url=__forgeaxNativeURL.createObjectURL(new Blob([__forgeaxBytes(entry.data)],{type:'text/javascript'}));__forgeaxOwnedUrls.add(url);__forgeaxImportUrls.set(entry.path,url);}__forgeaxNoteHit();return import(url);};\nglobalThis.__forgeaxImport=__forgeaxImport;\nif(typeof __forgeaxNativeFetch==='function')globalThis.fetch=(input,init)=>{const entry=__forgeaxLookup(input);if(entry!==undefined)return Promise.resolve(__forgeaxResponse(entry));const text=String(input);if(/^(?:data:|blob:)/i.test(text))return __forgeaxNativeFetch(input,init);if(/^https?:/i.test(text)){__forgeaxNoteExternal('fetch',input);}else{__forgeaxNote('fetch',input);}return Promise.reject(new TypeError('forgeax single-html worker resource miss'));};\nconst __forgeaxWorkerPrelude=__FORGEAX_WORKER_FACTORY__;\nconst __forgeaxNativeWorker=globalThis.Worker;\nif(typeof __forgeaxNativeWorker==='function')globalThis.Worker=class extends __forgeaxNativeWorker{constructor(input,options){const entry=__forgeaxLookup(input);if(entry===undefined){__forgeaxNote('worker',input);throw new TypeError('forgeax single-html worker resource miss');}const source=new TextDecoder().decode(__forgeaxBytes(entry.data));super(__forgeaxWorkerURL(__forgeaxWorkerPrelude(entry.path)+source),options);}};\nglobalThis.addEventListener?.('message',(event)=>{if(event.data?.__forgeaxResourceMiss||event.data?.__forgeaxResourceHit||event.data?.__forgeaxExternalRequest){try{__forgeaxNativePostMessage?.(event.data);}catch{}event.stopImmediatePropagation?.();}});\nglobalThis.addEventListener?.('unload',()=>{for(const url of __forgeaxOwnedUrls)__forgeaxNativeURL.revokeObjectURL(url);__forgeaxOwnedUrls.clear();});`;\n // The factory is copied into every worker prelude so nested workers keep the\n // same complete resource table and can recursively create their own prelude.\n // It is self-referential by source text rather than by a host-side closure:\n // workers are independent realms and cannot capture this function.\n const factoryToken = '__FORGEAX_WORKER_FACTORY__';\n const recursiveTemplate = template;\n const factorySource = `(sourcePath)=>{const source=${JSON.stringify(recursiveTemplate)};return source.replace(${JSON.stringify(factoryToken)},()=> '('+__forgeaxWorkerPrelude.toString()+')').replace('__FORGEAX_SOURCE_PATH__',()=>JSON.stringify(sourcePath));}`;\n return `const __forgeaxWorkerPrelude=${factorySource};`;\n}\n\nfunction runtimeBootstrap(resources: readonly SingleHtmlBundleArtifact[]): string {\n const workerFactory = workerPrelude(resources);\n return `(() => {\n globalThis.process ??= { env: {}, versions: { node: '0.0.0' }, platform: 'browser', argv: [] };\n const nativeURL = globalThis.URL;\n const nativeFetch = globalThis.fetch?.bind(globalThis);\n const nodes = [...document.querySelectorAll('script[data-forgeax-asset]')];\n const entries = nodes.map((node) => ({ path: node.getAttribute('data-path'), mime: node.getAttribute('data-mime') || 'application/octet-stream', data: (node.textContent || '').trim() })).filter((entry) => typeof entry.path === 'string');\n const decode = (value) => { const binary = atob(value); const bytes = new Uint8Array(binary.length); for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index); return bytes; };\n const normalize = (value) => { try { return decodeURIComponent(String(value).split(/[?#]/, 1)[0]).replaceAll('\\\\\\\\', '/').replace(/^\\\\/+/, ''); } catch { return undefined; } };\n const withoutBundle = (value) => String(value).replace(/^__forgeax-bundle\\\\//, '');\n const lookup = (input) => { let url; try { url = input instanceof nativeURL ? input : new nativeURL(String(input), document.baseURI); } catch { return undefined; } if (url.protocol === 'data:' || url.protocol === 'blob:') return undefined; const path = normalize(url.pathname); if (path === undefined) return undefined; const normalized = withoutBundle(path); const exact = entries.find((entry) => entry.path === path || withoutBundle(entry.path) === normalized); if (exact !== undefined) return exact; const suffix = entries.filter((entry) => normalized.endsWith('/' + withoutBundle(entry.path))); if (suffix.length === 1) return suffix[0]; const name = normalized.slice(normalized.lastIndexOf('/') + 1); const matches = entries.filter((entry) => withoutBundle(entry.path).slice(withoutBundle(entry.path).lastIndexOf('/') + 1) === name); return matches.length === 1 ? matches[0] : undefined; };\n const resourceMisses = [];\n const externalRequests = [];\n let resourceHits = 0;\n const noteMiss = (kind, specifier) => { resourceMisses.push({ kind, specifier: String(specifier), realm: 'main' }); };\n const noteExternal = (kind, specifier) => { externalRequests.push({ kind, specifier: String(specifier), realm: 'main' }); };\n const response = (entry) => { resourceHits += 1; return new Response(decode(entry.data), { status: 200, headers: { 'Content-Type': entry.mime } }); };\n const ownedBlobUrls = new Set();\n const makeBlobUrl = (entry) => { const url = nativeURL.createObjectURL(new Blob([decode(entry.data)], { type: entry.mime })); ownedBlobUrls.add(url); return url; };\n const dataUrl = (source) => { const bytes = new TextEncoder().encode(source); let binary = ''; for (const byte of bytes) binary += String.fromCharCode(byte); return 'data:text/javascript;base64,' + btoa(binary); };\n const workerUrl = (source) => { if (/^(?:file:|data:|about:)/i.test(String(globalThis.location?.protocol ?? ''))) return dataUrl(source); const url = nativeURL.createObjectURL(new Blob([source], { type: 'text/javascript' })); ownedBlobUrls.add(url); return url; };\n const importUrls = new Map();\n const forgeaxImport = async (specifier) => { const entry = lookup(specifier); if (entry === undefined) { const text = String(specifier); if (/^(?:https?:)/i.test(text)) noteExternal('import', text); else noteMiss('import', text); throw new TypeError('forgeax single-html resource miss'); } let url = importUrls.get(entry.path); if (url === undefined) { url = makeBlobUrl(entry); importUrls.set(entry.path, url); } resourceHits += 1; return import(url); };\n globalThis.__forgeaxImport = forgeaxImport;\n const external = (input) => { try { const url = input instanceof nativeURL ? input : new nativeURL(String(input), document.baseURI); return url.protocol === 'http:' || url.protocol === 'https:'; } catch { return false; } };\n if (typeof nativeFetch === 'function') globalThis.fetch = (input, init) => { const entry = lookup(input); if (entry !== undefined) return Promise.resolve(response(entry)); if (/^(?:data:|blob:)/i.test(String(input))) return nativeFetch(input, init); if (external(input)) { noteExternal('fetch', input); return Promise.reject(new TypeError('forgeax single-html blocked an external request')); } noteMiss('fetch', input); return Promise.reject(new TypeError('forgeax single-html resource miss')); };\n ${workerFactory}\n const nativeWorker = globalThis.Worker;\n const attachWorker = (worker) => { worker.addEventListener('message', (event) => { const miss = event.data?.__forgeaxResourceMiss; if (miss !== undefined) { resourceMisses.push({ ...miss, realm: 'worker' }); event.stopImmediatePropagation?.(); } const externalRequest = event.data?.__forgeaxExternalRequest; if (externalRequest !== undefined) { externalRequests.push({ ...externalRequest, realm: 'worker' }); event.stopImmediatePropagation?.(); } const hit = event.data?.__forgeaxResourceHit; if (typeof hit === 'number' && Number.isFinite(hit)) resourceHits += hit; }); return worker; };\n if (typeof nativeWorker === 'function') globalThis.Worker = class extends nativeWorker { constructor(input, options) { const entry = lookup(input); if (entry === undefined) { const text = String(input); if (external(input)) noteExternal('worker', text); else noteMiss('worker', text); throw new TypeError('forgeax single-html worker resource miss'); } const source = new TextDecoder().decode(decode(entry.data)); super(workerUrl(__forgeaxWorkerPrelude(entry.path) + source), options); attachWorker(this); } };\n const witness = () => ({ ready: document.documentElement.dataset.forgeaxSingleHtmlReady === 'true', resourceHits, resourceMisses: resourceMisses.slice(), externalRequests: externalRequests.slice() });\n globalThis.__forgeaxSingleHtml = { lookup, entries: entries.map(({ path, mime }) => ({ path, mime })), witness };\n globalThis.addEventListener('pagehide', () => { for (const url of ownedBlobUrls) nativeURL.revokeObjectURL(url); ownedBlobUrls.clear(); }, { once: true });\n document.documentElement.dataset.forgeaxSingleHtmlReady = 'true';\n})();`;\n}\n\nfunction escapeAttribute(value: string): string {\n return value\n .replace(/&/g, '&amp;')\n .replace(/\"/g, '&quot;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;');\n}\n\nfunction distResources(\n distRoot: string,\n manifest: DistManifest,\n): Promise<SingleHtmlBundleArtifact[]> {\n const rows: readonly (DistArtifact | { readonly path: string })[] = [\n ...manifest.artifacts,\n { path: 'forgeax-dist.json' },\n ];\n return Promise.all(\n rows\n .filter((artifact) => artifact.path !== 'index.html')\n .map(async (artifact) => ({\n path: artifact.path,\n bytes: await readFile(resolve(distRoot, artifact.path)),\n mediaType: 'mediaType' in artifact ? artifact.mediaType : mediaType(artifact.path),\n })),\n );\n}\n\nfunction buildHtml(\n indexHtml: string,\n distArtifacts: readonly SingleHtmlBundleArtifact[],\n bundle: SingleHtmlBundle,\n): CommandResult<{ readonly html: string; readonly embeddedAssets: number }> {\n const resources = new Map<string, SingleHtmlBundleArtifact>();\n for (const resource of [...distArtifacts, ...bundle.artifacts]) {\n if (resources.has(resource.path)) {\n return errorResult(\n 'single-html-asset-duplicate',\n 'embedded resource paths to be unique',\n 'Repair the generated bundle path collision before packaging.',\n { path: resource.path },\n );\n }\n resources.set(resource.path, resource);\n }\n\n const replacements: Replacement[] = [];\n for (const element of scanHtmlElements(indexHtml)) {\n if (isModuleScript(element) || isModulePreload(element)) {\n replacements.push({ start: element.start, end: element.end, value: '' });\n continue;\n }\n if (isStylesheet(element)) {\n const href = attributeValue(element, 'href');\n if (href === undefined) {\n return errorResult(\n 'single-html-stylesheet-missing',\n 'stylesheet link to contain href',\n 'Repair the generated HTML stylesheet link.',\n );\n }\n const path = resourcePath(href, 'index.html');\n const stylesheet = path === undefined ? undefined : resourceForPath(path, resources);\n if (stylesheet === undefined) {\n return errorResult(\n 'single-html-css-asset-missing',\n 'stylesheet link to resolve to an embedded artifact',\n 'Add the stylesheet to the dist closure and rebuild.',\n { href, path: path ?? null },\n );\n }\n const css = inlineCss(\n Buffer.from(stylesheet.bytes).toString('utf8'),\n stylesheet.path,\n resources,\n );\n if (!css.ok) return css;\n replacements.push({\n start: element.start,\n end: element.end,\n value: `<style data-forgeax-inline-css>${css.value}</style>`,\n });\n continue;\n }\n if (\n element.name === 'style' &&\n element.contentStart !== undefined &&\n element.contentEnd !== undefined\n ) {\n const css = inlineCss(\n indexHtml.slice(element.contentStart, element.contentEnd),\n 'index.html',\n resources,\n );\n if (!css.ok) return css;\n replacements.push({ start: element.contentStart, end: element.contentEnd, value: css.value });\n continue;\n }\n const resourceAttribute =\n element.name === 'img' ||\n element.name === 'source' ||\n element.name === 'video' ||\n element.name === 'audio' ||\n element.name === 'link'\n ? element.attributes.find((candidate) => ['src', 'poster', 'href'].includes(candidate.name))\n : undefined;\n const resourceAttributeLocation =\n resourceAttribute === undefined\n ? undefined\n : element.attributeLocations[resourceAttribute.name];\n const resourceAttributeRange =\n resourceAttribute === undefined || resourceAttributeLocation === undefined\n ? undefined\n : attributeValueRange(indexHtml, resourceAttributeLocation);\n if (\n resourceAttribute?.value !== undefined &&\n resourceAttributeRange !== undefined &&\n !/^(?:data:|blob:|#)/i.test(resourceAttribute.value)\n ) {\n const path = resourcePath(resourceAttribute.value, 'index.html');\n const embedded = path === undefined ? undefined : resourceForPath(path, resources);\n if (embedded === undefined) {\n return errorResult(\n 'single-html-asset-missing',\n 'every local HTML resource to resolve to an embedded dist artifact',\n 'Add the referenced asset to the project closure and rebuild.',\n { value: resourceAttribute.value, path: path ?? null },\n );\n }\n replacements.push({\n start: resourceAttributeRange.startOffset,\n end: resourceAttributeRange.endOffset,\n value: dataUri(embedded.bytes, embedded.mediaType),\n });\n continue;\n }\n if (element.name === 'script' && attributeValue(element, 'src') !== undefined) {\n return errorResult(\n 'single-html-script-external',\n 'non-module script sources to be absent from the generated host',\n 'Move the script into the production module entry before packaging.',\n { src: attributeValue(element, 'src') },\n );\n }\n }\n\n const assetNodes = [...resources.values()]\n .sort((left, right) => left.path.localeCompare(right.path))\n .map(\n (resource, index) =>\n `<script type=\"application/octet-stream\" id=\"forgeax-asset-${index}\" data-forgeax-asset data-path=\"${escapeAttribute(resource.path)}\" data-mime=\"${escapeAttribute(resource.mediaType)}\">${Buffer.from(resource.bytes).toString('base64')}</script>`,\n )\n .join('');\n const bootstrap = `<script type=\"application/javascript\">${safeScriptText(runtimeBootstrap([...resources.values()]))}</script>`;\n const entry = `<script type=\"module\">${safeScriptText(bundle.entrySource)}</script>`;\n const withResources = applyReplacements(indexHtml, replacements);\n const body = `${assetNodes}${bootstrap}${entry}`;\n const html = withResources.includes('</body>')\n ? withResources.replace(/<\\/body>/i, () => `${body}</body>`)\n : `${withResources}${body}`;\n return { ok: true, value: { html, embeddedAssets: resources.size } };\n}\n\nexport async function writeSingleHtml(\n options: SingleHtmlPackageOptions,\n): Promise<CommandResult<SingleHtmlPackageResult>> {\n const distRoot = resolve(options.distRoot);\n const output = resolve(options.output);\n const checksumPath = `${output}.sha256`;\n const temporary = `${output}.partial-${process.pid}`;\n const temporaryChecksum = `${checksumPath}.partial-${process.pid}`;\n try {\n const indexHtml = await readFile(resolve(distRoot, 'index.html'), 'utf8');\n const resources = await distResources(distRoot, options.manifest);\n const built = buildHtml(indexHtml, resources, options.bundle);\n if (!built.ok) return built;\n const bytes = Buffer.from(built.value.html, 'utf8');\n const sha256 = hashBytes(bytes);\n const manifestBytes = await readFile(resolve(distRoot, 'forgeax-dist.json'));\n await mkdir(dirname(output), { recursive: true });\n await writeFile(temporary, bytes);\n await writeFile(temporaryChecksum, `${sha256} ${basename(output)}\\n`, 'utf8');\n await rename(temporaryChecksum, checksumPath);\n await rename(temporary, output);\n return {\n ok: true,\n value: {\n schemaVersion: '1.0.0',\n format: SINGLE_HTML_FORMAT,\n target: 'file',\n project: options.manifest.project,\n base: options.manifest.base,\n html: { path: output, bytes: bytes.byteLength, sha256 },\n checksumPath,\n distManifestSha256: hashBytes(manifestBytes),\n embeddedAssets: built.value.embeddedAssets,\n run: {\n local: pathToFileURL(output).href,\n shared: 'send the HTML file and open it in a desktop Chrome with WebGPU support',\n },\n },\n };\n } catch (cause) {\n return toErrorResult(\n cause,\n 'single-html-write-failed',\n 'the single HTML candidate and adjacent SHA-256 to be written atomically',\n 'Repair the dist closure or output directory, then retry packaging.',\n );\n } finally {\n await Promise.all([rm(temporary, { force: true }), rm(temporaryChecksum, { force: true })]);\n }\n}\n\nexport function packageFormatError(format: string): CommandResult<never> {\n return errorResult(\n 'package-format-unsupported',\n 'package format to be web-zip or single-html',\n 'Use web-zip for HTTPS hosting or single-html for a self-contained file:// delivery.',\n { format },\n );\n}\n\nexport function packageOutputError(\n output: string,\n format: 'web-zip' | 'single-html',\n): CommandResult<never> {\n const expectedSuffix = format === 'single-html' ? '.html' : '.zip';\n return errorResult(\n 'package-output-suffix-mismatch',\n `package output to end with ${expectedSuffix}`,\n `Use a ${expectedSuffix} output path for ${format}.`,\n { output, format },\n );\n}\n","import type { GameProjectPluginEntry } from '@forgeax/engine-project';\n\nexport type ForgeaXCommand =\n | 'new'\n | 'init'\n | 'doctor'\n | 'test'\n | 'dev'\n | 'build'\n | 'package'\n | 'capture'\n | 'engine.status'\n | 'engine.use-local'\n | 'engine.unlink'\n | 'engine.doctor'\n | 'serve'\n | 'preview'\n | 'plugin.install'\n | 'plugin.uninstall'\n | 'skill.install'\n | 'skill.verify'\n | 'sdk.install'\n | 'asset.add'\n | 'asset.verify'\n | 'asset.inspect'\n | 'asset.list'\n | 'shader.check'\n | 'list'\n | 'describe'\n | 'run'\n | 'exec';\n\nexport interface CommandError {\n readonly code: string;\n readonly expected: string;\n readonly hint: string;\n readonly detail: Readonly<Record<string, unknown>>;\n}\n\nexport type CommandResult<T> =\n | { readonly ok: true; readonly value: T }\n | { readonly ok: false; readonly error: CommandError };\n\nexport interface CommandEnvelope<T = unknown> {\n readonly schemaVersion: '1.0.0';\n readonly command: ForgeaXCommand;\n readonly ok: boolean;\n readonly value?: T;\n readonly error?: CommandError;\n}\n\nexport interface ProjectFacts {\n readonly root: string;\n readonly id: string;\n readonly name: string;\n readonly entry: string;\n readonly bootstrapEntry?: string;\n readonly plugins: readonly GameProjectPluginEntry[];\n readonly physics?: '2d' | '3d';\n readonly defaultScene?: string;\n readonly assetRoots: readonly string[];\n readonly assetImporters?: readonly string[];\n readonly assetPublicDir?: string;\n readonly packageJson: Readonly<Record<string, unknown>>;\n}\n\nexport interface ProjectCommandOptions {\n readonly root?: string;\n readonly json?: boolean;\n readonly port?: number;\n}\n\nexport interface ProjectPortOptions {\n readonly port: number;\n readonly strictPort: boolean;\n}\n\nexport function parseProjectPortOption(\n value: string | undefined,\n provided: boolean,\n): CommandResult<number | undefined> {\n if (!provided) return { ok: true, value: undefined };\n if (value !== undefined && /^(0|[1-9]\\d*)$/.test(value)) {\n const port = Number(value);\n if (Number.isSafeInteger(port) && port <= 65_535) return { ok: true, value: port };\n }\n return {\n ok: false,\n error: {\n code: 'cli-parse-error',\n expected: '--port to be 0 or an integer from 1 to 65535',\n hint: 'Omit --port for strict 5173, pass a positive port for a strict binding, or pass 0 for an OS-assigned port.',\n detail: { option: '--port', received: value ?? null },\n },\n };\n}\n\nexport function resolveProjectPort(port: number | undefined): ProjectPortOptions {\n return { port: port ?? 5173, strictPort: port !== 0 };\n}\n\nexport interface InitOptions extends ProjectCommandOptions {\n readonly dryRun?: boolean;\n readonly install?: boolean;\n}\n\nexport interface NewOptions extends ProjectCommandOptions {\n readonly dryRun?: boolean;\n readonly template?: string;\n}\n\nexport interface BuildOptions extends ProjectCommandOptions {\n readonly base?: string;\n readonly outDir?: string;\n}\n\nexport interface PackageOptions extends ProjectCommandOptions {\n readonly output?: string;\n readonly format?: PackageFormat;\n}\n\nexport type PackageFormat = 'web-zip' | 'single-html';\n\nexport type CaptureBackend = 'auto' | 'software' | 'hardware';\n\nexport interface BrowserCaptureOptions extends ProjectCommandOptions {\n /** Prefer a rendering lane, or let the browser choose and report it. */\n readonly backend?: CaptureBackend;\n /** Backwards-compatible alias for `backend: 'software'`. */\n readonly software?: boolean;\n readonly output?: string;\n readonly browser?: string;\n readonly width?: number;\n readonly height?: number;\n readonly waitMs?: number;\n readonly requireUi?: boolean;\n readonly deterministic?: boolean;\n readonly headless?: boolean;\n}\n\n/** @deprecated Use BrowserCaptureOptions with `backend: 'software'`. */\nexport interface SoftwareCaptureOptions extends BrowserCaptureOptions {\n readonly software: true;\n readonly backend?: 'software';\n}\n\nexport interface AssetAddOptions extends ProjectCommandOptions {\n readonly path: string;\n readonly dryRun?: boolean;\n}\n\nexport interface AssetInspectOptions extends ProjectCommandOptions {\n readonly subject: string;\n}\n\nexport interface ShaderCheckOptions extends ProjectCommandOptions {\n readonly path?: string;\n}\n\nexport interface OperationCommandOptions extends ProjectCommandOptions {\n readonly id?: string;\n readonly args?: string;\n readonly input?: string;\n readonly program?: string;\n}\n\nexport interface PluginInstallOptions extends ProjectCommandOptions {\n readonly id: string;\n readonly module: string;\n readonly realm?: 'host' | 'engine' | 'build';\n readonly dependency?: string;\n readonly dryRun?: boolean;\n}\n\nexport interface PluginUninstallOptions extends ProjectCommandOptions {\n readonly id: string;\n readonly dependency?: string;\n readonly dryRun?: boolean;\n}\n","import { readdir, readFile, stat, writeFile } from 'node:fs/promises';\nimport { basename, extname, resolve } from 'node:path';\nimport { runCliGltf } from '@forgeax/engine-gltf/cli-gltf';\nimport { scanEntries } from '@forgeax/engine-pack/cli-asset';\nimport { AssetGuid } from '@forgeax/engine-pack/guid';\nimport { commandError, readProjectFacts } from './project.js';\nimport type {\n AssetAddOptions,\n AssetInspectOptions,\n CommandError,\n CommandResult,\n ProjectCommandOptions,\n} from './types.js';\n\nconst imageExtensions = new Set(['.png', '.jpg', '.jpeg', '.hdr']);\nconst gltfExtensions = new Set(['.gltf', '.glb']);\n\nfunction failure(error: CommandError): CommandResult<never> {\n return { ok: false, error };\n}\n\nasync function sourcesAt(path: string): Promise<string[]> {\n const info = await stat(path);\n if (info.isFile()) return [path];\n if (!info.isDirectory()) return [];\n const output: string[] = [];\n const entries = await readdir(path, { withFileTypes: true });\n for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {\n if (entry.name.startsWith('.') || entry.name === 'node_modules' || entry.name === 'dist')\n continue;\n const child = resolve(path, entry.name);\n if (entry.isDirectory()) output.push(...(await sourcesAt(child)));\n else if (entry.isFile() && !entry.name.endsWith('.meta.json')) output.push(child);\n }\n return output;\n}\n\nasync function addImage(sourcePath: string, dryRun: boolean): Promise<CommandResult<unknown>> {\n const metaPath = `${sourcePath}.meta.json`;\n const source = basename(sourcePath);\n let existing: unknown;\n try {\n existing = JSON.parse(await readFile(metaPath, 'utf8')) as unknown;\n } catch (cause) {\n if ((cause as NodeJS.ErrnoException).code !== 'ENOENT') {\n return failure({\n code: 'asset-meta-unreadable',\n expected: 'an absent or readable JSON sidecar',\n hint: 'Repair the existing sidecar before adding the source again.',\n detail: { source: sourcePath, metaPath },\n });\n }\n }\n if (existing !== undefined) {\n const value = existing as {\n importer?: unknown;\n source?: unknown;\n subAssets?: readonly { guid?: unknown; kind?: unknown }[];\n };\n const row = value.subAssets?.[0];\n if (\n value.importer !== 'image' ||\n value.source !== source ||\n value.subAssets?.length !== 1 ||\n typeof row?.guid !== 'string' ||\n row.kind !== 'texture'\n ) {\n return failure({\n code: 'asset-meta-conflict',\n expected: 'the existing sidecar to describe this image source and one texture identity',\n hint: 'Resolve the sidecar conflict explicitly; DevKit will not replace authored identity.',\n detail: { source: sourcePath, metaPath },\n });\n }\n return { ok: true, value: { source: sourcePath, metaPath, guid: row.guid, reused: true } };\n }\n const guid = AssetGuid.format(AssetGuid.random());\n const linear = extname(sourcePath).toLowerCase() === '.hdr';\n const meta = {\n schemaVersion: '1.0.0',\n kind: 'external-asset-package',\n importer: 'image',\n source,\n importSettings: {\n colorSpace: linear ? 'linear' : 'srgb',\n mipmap: true,\n addressMode: 'repeat',\n filterMode: 'linear',\n },\n subAssets: [{ guid, sourceIndex: 0, kind: 'texture', sourceKey: 'texture' }],\n } as const;\n if (!dryRun) await writeFile(metaPath, `${JSON.stringify(meta, null, 2)}\\n`, { flag: 'wx' });\n return { ok: true, value: { source: sourcePath, metaPath, guid, reused: false, dryRun } };\n}\n\nasync function addGltf(sourcePath: string, dryRun: boolean): Promise<CommandResult<unknown>> {\n if (dryRun) {\n const exists = await stat(`${sourcePath}.meta.json`)\n .then(() => true)\n .catch(() => false);\n return {\n ok: true,\n value: {\n source: sourcePath,\n metaPath: `${sourcePath}.meta.json`,\n reused: exists,\n dryRun: true,\n },\n };\n }\n const stdout: string[] = [];\n const stderr: string[] = [];\n const exitCode = await runCliGltf(['import', sourcePath], {\n stdoutWrite: (line) => stdout.push(line),\n stderrWrite: (line) => stderr.push(line),\n });\n if (exitCode !== 0) {\n try {\n return failure(JSON.parse(stderr.at(-1) ?? '') as CommandError);\n } catch {\n return failure({\n code: 'asset-add-failed',\n expected: 'the glTF producer to create or reuse a valid sidecar',\n hint: 'Inspect the glTF source and its external references.',\n detail: { source: sourcePath, diagnostic: stderr.join('\\n') },\n });\n }\n }\n return { ok: true, value: { source: sourcePath, metaPath: `${sourcePath}.meta.json` } };\n}\n\nexport async function assetAddCommand(options: AssetAddOptions): Promise<CommandResult<unknown>> {\n const facts = await readProjectFacts(options.root);\n if (!facts.ok) return facts;\n const target = resolve(facts.value.root, options.path);\n try {\n const sources = await sourcesAt(target);\n const supported = sources.filter((source) => {\n const extension = extname(source).toLowerCase();\n return imageExtensions.has(extension) || gltfExtensions.has(extension);\n });\n if (supported.length === 0) {\n return failure({\n code: 'source-package-importer-missing',\n expected: 'a .png, .jpg, .jpeg, .hdr, .gltf, or .glb source',\n hint: 'Use a supported built-in importer or add an explicit producer before adding this source.',\n detail: { target },\n });\n }\n const assets: unknown[] = [];\n for (const source of supported) {\n const result = imageExtensions.has(extname(source).toLowerCase())\n ? await addImage(source, options.dryRun === true)\n : await addGltf(source, options.dryRun === true);\n if (!result.ok) return result;\n assets.push(result.value);\n }\n return { ok: true, value: { root: facts.value.root, assets, dryRun: options.dryRun === true } };\n } catch (cause) {\n return failure(commandError(cause, 'asset-add-failed'));\n }\n}\n\nasync function entries(options: ProjectCommandOptions) {\n const facts = await readProjectFacts(options.root);\n if (!facts.ok) return facts;\n const stdout: string[] = [];\n const stderr: string[] = [];\n const result = await scanEntries(\n facts.value.assetRoots.map((root) => resolve(facts.value.root, root)),\n { stdoutWrite: (line) => stdout.push(line), stderrWrite: (line) => stderr.push(line) },\n );\n if (!result.ok) {\n try {\n return failure(JSON.parse(stderr.at(-1) ?? '') as CommandError);\n } catch {\n return failure({\n code: 'asset-authority-invalid',\n expected: 'all asset roots and sidecars to pass the pack scanner',\n hint: 'Repair the first invalid asset authority reported by the scanner.',\n detail: { diagnostic: stderr.join('\\n') },\n });\n }\n }\n return { ok: true as const, value: { facts: facts.value, entries: result.value } };\n}\n\nexport async function assetListCommand(\n options: ProjectCommandOptions = {},\n): Promise<CommandResult<unknown>> {\n const result = await entries(options);\n if (!result.ok) return result;\n return { ok: true, value: result.value.entries };\n}\n\nexport async function assetVerifyCommand(\n options: ProjectCommandOptions = {},\n): Promise<CommandResult<unknown>> {\n const result = await entries(options);\n if (!result.ok) return result;\n return {\n ok: true,\n value: { root: result.value.facts.root, assetCount: result.value.entries.length },\n };\n}\n\nexport async function assetInspectCommand(\n options: AssetInspectOptions,\n): Promise<CommandResult<unknown>> {\n const result = await entries(options);\n if (!result.ok) return result;\n const subject = options.subject.toLowerCase();\n const matches = result.value.entries.filter(\n (entry) => entry.guid.toLowerCase() === subject || entry.name?.toLowerCase() === subject,\n );\n if (matches.length !== 1) {\n return failure({\n code: matches.length === 0 ? 'asset-not-found' : 'asset-subject-ambiguous',\n expected: 'the GUID or name to resolve to exactly one asset',\n hint:\n matches.length === 0\n ? 'Run asset list and choose a known subject.'\n : 'Use the stable GUID.',\n detail: { subject: options.subject, matches },\n });\n }\n return { ok: true, value: matches[0] };\n}\n","{\n \"name\": \"@forgeax/engine-devkit\",\n \"version\": \"0.0.0\",\n \"private\": false,\n \"type\": \"module\",\n \"license\": \"Apache-2.0\",\n \"sideEffects\": false,\n \"description\": \"ForgeaX external game project CLI and build orchestration.\",\n \"bin\": {\n \"forgeax\": \"./dist/cli.mjs\"\n },\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.mjs\"\n },\n \"./cli\": \"./dist/cli.mjs\",\n \"./package.json\": \"./package.json\"\n },\n \"main\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"files\": [\n \"dist\",\n \"README.md\",\n \"LICENSE\"\n ],\n \"scripts\": {\n \"build\": \"tsup\",\n \"test\": \"vitest run\"\n },\n \"dependencies\": {\n \"@forgeax/engine-animation\": \"workspace:*\",\n \"@forgeax/engine-app\": \"workspace:*\",\n \"@forgeax/engine-assets-runtime\": \"workspace:*\",\n \"@forgeax/engine-audio\": \"workspace:*\",\n \"@forgeax/engine-audio-webaudio\": \"workspace:*\",\n \"@forgeax/engine-fbx\": \"workspace:*\",\n \"@forgeax/engine-font\": \"workspace:*\",\n \"@forgeax/engine-gltf\": \"workspace:*\",\n \"@forgeax/engine-image\": \"workspace:*\",\n \"@forgeax/engine-input\": \"workspace:*\",\n \"@forgeax/engine-pack\": \"workspace:*\",\n \"@forgeax/engine-physics\": \"workspace:*\",\n \"@forgeax/engine-plugin\": \"workspace:*\",\n \"@forgeax/engine-preview\": \"workspace:*\",\n \"@forgeax/engine-project\": \"workspace:*\",\n \"@forgeax/engine-rhi-debug\": \"workspace:*\",\n \"@forgeax/engine-rhi-null\": \"workspace:*\",\n \"@forgeax/engine-rhi-webgpu\": \"workspace:*\",\n \"@forgeax/engine-render\": \"workspace:*\",\n \"@forgeax/engine-render-graph\": \"workspace:*\",\n \"@forgeax/engine-runtime\": \"workspace:*\",\n \"@forgeax/engine-scene\": \"workspace:*\",\n \"@forgeax/engine-shader-compiler\": \"workspace:*\",\n \"@forgeax/engine-skinning\": \"workspace:*\",\n \"@forgeax/engine-tool-runtime\": \"workspace:*\",\n \"@forgeax/engine-types\": \"workspace:*\",\n \"@forgeax/engine-vfx-compiler\": \"workspace:*\",\n \"@forgeax/engine-vite-plugin-pack\": \"workspace:*\",\n \"@forgeax/engine-vite-plugin-rhi-debug\": \"workspace:*\",\n \"@forgeax/engine-vite-plugin-shader\": \"workspace:*\",\n \"jiti\": \"1.21.7\",\n \"parse5\": \"7.3.0\",\n \"playwright\": \"1.60.0\",\n \"vite\": \"8.0.10\",\n \"vitest\": \"4.1.11\",\n \"webgpu\": \"^0.4.0\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^20.14.0\"\n },\n \"forgeax\": {\n \"metrics\": {\n \"bundle-size\": {\n \"enabled\": true,\n \"path\": \"dist/cli.mjs\",\n \"compression\": \"gzip\"\n },\n \"fps\": {\n \"enabled\": false,\n \"reason\": \"Node-only build orchestration; runtime FPS belongs to consumer games\"\n },\n \"bench\": {\n \"enabled\": false,\n \"reason\": \"CLI latency is not a runtime hot path\"\n },\n \"gate\": {\n \"enabled\": true,\n \"command\": \"pnpm test\",\n \"cwd\": \"packages/devkit\"\n },\n \"spike-report\": {\n \"enabled\": false,\n \"reason\": \"production DevKit package\"\n }\n }\n }\n}\n","import { writeFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport devkitPackage from '../package.json' with { type: 'json' };\nimport type { SdkManifest } from './sdk.js';\nimport type { CommandResult, InitOptions, ProjectFacts } from './types.js';\n\nconst STANDARD_SCRIPTS = {\n dev: 'forgeax dev',\n build: 'forgeax build',\n package: 'forgeax package',\n serve: 'forgeax serve',\n preview: 'forgeax preview',\n doctor: 'forgeax doctor',\n test: 'forgeax test',\n} as const;\n\nconst SDK_DEV_DEPENDENCIES = {\n '@types/node': '20.19.40',\n '@webgpu/types': '0.1.71',\n tsx: '4.23.1',\n typescript: '6.0.3',\n vitest: '4.1.11',\n} as const;\n\nexport interface InitPlan {\n readonly root: string;\n readonly version: string;\n readonly pnpmVersion?: string;\n readonly archiveBacked: boolean;\n readonly dependencyChanges: readonly {\n readonly section: string;\n readonly name: string;\n readonly from?: string;\n readonly to: string;\n }[];\n readonly scriptChanges: readonly { readonly name: string; readonly to: string }[];\n}\n\nexport function createInitPlan(\n facts: ProjectFacts,\n sdk?: Pick<SdkManifest, 'sdkVersion' | 'packages' | 'requirements'>,\n): CommandResult<InitPlan> {\n const manifest = structuredClone(facts.packageJson) as Record<string, unknown>;\n const packageVersions = new Map(sdk?.packages.map((entry) => [entry.name, entry.version]));\n const devkitVersion = packageVersions.get('@forgeax/engine-devkit') ?? devkitPackage.version;\n const dependencyChanges: InitPlan['dependencyChanges'][number][] = [];\n if (sdk !== undefined) {\n for (const section of ['dependencies', 'devDependencies'] as const) {\n const dependencies = manifest[section];\n if (dependencies === null || typeof dependencies !== 'object') continue;\n const unsupported = Object.keys(dependencies).filter(\n (name) => !name.startsWith('@forgeax/engine-') && !(name in SDK_DEV_DEPENDENCIES),\n );\n if (unsupported.length > 0) {\n return {\n ok: false,\n error: {\n code: 'sdk-external-dependency-unsupported',\n expected: 'archive-backed init dependencies to belong to the SDK closure',\n hint: 'Remove the external dependency or use a network-backed package workflow explicitly.',\n detail: { root: facts.root, dependencies: unsupported.sort() },\n },\n };\n }\n }\n }\n for (const section of ['dependencies', 'devDependencies'] as const) {\n const dependencies = manifest[section];\n if (dependencies === null || typeof dependencies !== 'object') continue;\n for (const [name, value] of Object.entries(dependencies)) {\n if (\n name.startsWith('@forgeax/engine-') &&\n typeof value === 'string' &&\n value.startsWith('workspace:')\n ) {\n const version = packageVersions.get(name) ?? devkitVersion;\n dependencyChanges.push({ section, name, from: value, to: version });\n }\n }\n }\n if (sdk !== undefined) {\n const existingEngineNames = new Set(\n ['dependencies', 'devDependencies'].flatMap((section) => {\n const value = manifest[section];\n return value !== null && typeof value === 'object'\n ? Object.keys(value).filter((name) => name.startsWith('@forgeax/engine-'))\n : [];\n }),\n );\n for (const entry of sdk.packages) {\n if (entry.name === '@forgeax/engine-devkit' || existingEngineNames.has(entry.name)) continue;\n dependencyChanges.push({\n section: 'dependencies',\n name: entry.name,\n to: entry.version,\n });\n }\n const devDependencies =\n manifest.devDependencies !== null && typeof manifest.devDependencies === 'object'\n ? (manifest.devDependencies as Record<string, unknown>)\n : {};\n for (const [name, version] of Object.entries(SDK_DEV_DEPENDENCIES)) {\n if (devDependencies[name] === version) continue;\n dependencyChanges.push({\n section: 'devDependencies',\n name,\n ...(typeof devDependencies[name] === 'string' ? { from: devDependencies[name] } : {}),\n to: version,\n });\n }\n }\n const scriptsValue = manifest.scripts;\n const scripts =\n scriptsValue !== null && typeof scriptsValue === 'object'\n ? (scriptsValue as Record<string, unknown>)\n : {};\n const scriptChanges: InitPlan['scriptChanges'][number][] = [];\n for (const [name, command] of Object.entries(STANDARD_SCRIPTS)) {\n const existing = scripts[name];\n if (existing === undefined) scriptChanges.push({ name, to: command });\n else if (existing !== command) {\n return {\n ok: false,\n error: {\n code: 'project-script-conflict',\n expected: `package.json#scripts.${name} to be absent or ${JSON.stringify(command)}`,\n hint: `Rename the existing ${name} script, then rerun forgeax init.`,\n detail: { root: facts.root, script: name, existing },\n },\n };\n }\n }\n const devDependencies = manifest.devDependencies;\n const existingDevkit =\n devDependencies !== null && typeof devDependencies === 'object'\n ? (devDependencies as Record<string, unknown>)['@forgeax/engine-devkit']\n : undefined;\n if (existingDevkit !== devkitVersion) {\n dependencyChanges.push({\n section: 'devDependencies',\n name: '@forgeax/engine-devkit',\n ...(typeof existingDevkit === 'string' ? { from: existingDevkit } : {}),\n to: devkitVersion,\n });\n }\n return {\n ok: true,\n value: {\n root: facts.root,\n version: sdk?.sdkVersion ?? devkitVersion,\n ...(sdk === undefined ? {} : { pnpmVersion: sdk.requirements.pnpm }),\n archiveBacked: sdk !== undefined,\n dependencyChanges,\n scriptChanges,\n },\n };\n}\n\nexport async function applyInitPlan(\n facts: ProjectFacts,\n plan: InitPlan,\n options: InitOptions,\n): Promise<CommandResult<InitPlan>> {\n if (options.dryRun === true) return { ok: true, value: plan };\n const manifest = structuredClone(facts.packageJson) as Record<string, unknown>;\n for (const change of plan.dependencyChanges) {\n const sectionValue = manifest[change.section];\n const section =\n sectionValue !== null && typeof sectionValue === 'object'\n ? (sectionValue as Record<string, unknown>)\n : {};\n section[change.name] = change.to;\n manifest[change.section] = section;\n }\n const scriptsValue = manifest.scripts;\n const scripts =\n scriptsValue !== null && typeof scriptsValue === 'object'\n ? (scriptsValue as Record<string, unknown>)\n : {};\n for (const change of plan.scriptChanges) scripts[change.name] = change.to;\n manifest.scripts = scripts;\n if (plan.archiveBacked) {\n if (plan.pnpmVersion === undefined) throw new Error('sdk-pnpm-version-missing');\n manifest.packageManager = `pnpm@${plan.pnpmVersion}`;\n }\n await writeFile(resolve(facts.root, 'package.json'), `${JSON.stringify(manifest, null, 2)}\\n`);\n return { ok: true, value: plan };\n}\n","import { access, readFile } from 'node:fs/promises';\nimport { dirname, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nexport interface SdkPackage {\n readonly name: string;\n readonly version: string;\n readonly root: string;\n readonly fileCount: number;\n readonly byteCount: number;\n}\n\nexport interface SdkTemplate {\n readonly id: string;\n readonly root: string;\n}\n\nexport interface SdkSkill {\n readonly id: string;\n readonly root: string;\n readonly fileCount: number;\n readonly byteCount: number;\n}\n\nexport interface SdkSourceWasm {\n readonly package: string;\n readonly root: string;\n readonly files: readonly string[];\n}\n\nexport interface SdkResource {\n readonly id: string;\n readonly package: string;\n readonly sourceRoot: string;\n readonly packageRoot: string;\n readonly files: readonly string[];\n}\n\nexport interface SdkTemplateResource {\n readonly id: string;\n readonly root: string;\n readonly files: readonly string[];\n}\n\nexport interface SdkSource {\n readonly root: 'source/engine';\n readonly format: 'git-archive-public-snapshot';\n readonly excluded: readonly ['.gitmodules', 'forgeax-engine-assets'];\n readonly fileCount: number;\n readonly byteCount: number;\n readonly prebuiltWasm: readonly SdkSourceWasm[];\n}\n\nexport interface SdkManifest {\n readonly schemaVersion: '1.7.0';\n readonly sdkVersion: string;\n readonly engineCommit: string;\n readonly requirements: {\n readonly node: string;\n readonly pnpm: string;\n readonly pnpmStoreFormat: string;\n };\n readonly capabilities: readonly string[];\n readonly packages: readonly SdkPackage[];\n readonly templates: readonly SdkTemplate[];\n readonly skills: readonly SdkSkill[];\n readonly resources: readonly SdkResource[];\n readonly templateResources: readonly SdkTemplateResource[];\n readonly source: SdkSource;\n}\n\nexport interface SdkContext {\n readonly root: string;\n readonly manifest: SdkManifest;\n /**\n * The full ZIP carries an immutable offline store. The npm carrier is a\n * deliberately smaller online surface and omits it, so consumers fall back\n * to the registry when this path is absent.\n */\n readonly store?: string;\n readonly templates: ReadonlyMap<string, string>;\n}\n\nasync function readable(path: string): Promise<boolean> {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function findSdkContext(): Promise<SdkContext | undefined> {\n const configured = process.env.FORGEAX_SDK_ROOT;\n let cursor = resolve(configured ?? dirname(fileURLToPath(import.meta.url)));\n for (;;) {\n const manifestPath = resolve(cursor, 'sdk-manifest.json');\n if (await readable(manifestPath)) {\n const manifest = JSON.parse(await readFile(manifestPath, 'utf8')) as SdkManifest;\n const templates = new Map(\n manifest.templates.map((template) => [template.id, resolve(cursor, template.root)]),\n );\n const store = resolve(cursor, 'store', 'pnpm');\n return {\n root: cursor,\n manifest,\n ...((await readable(store)) ? { store } : {}),\n templates,\n };\n }\n const parent = dirname(cursor);\n if (parent === cursor) return undefined;\n cursor = parent;\n }\n}\n","import { execFile } from 'node:child_process';\nimport { cp, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { resolve } from 'node:path';\nimport { promisify } from 'node:util';\nimport type { SdkContext } from './sdk.js';\nimport type { CommandResult } from './types.js';\n\nconst execFileAsync = promisify(execFile);\nconst SDK_INIT_PATH = ['.forgeax', 'sdk-init.json'] as const;\nconst SDK_INIT_SCHEMA_VERSION = '1.0.0' as const;\n\nexport interface SdkInitState {\n readonly schemaVersion: typeof SDK_INIT_SCHEMA_VERSION;\n readonly sdkVersion: string;\n readonly engineCommit: string;\n readonly pnpm: string;\n readonly node: string;\n readonly platform: NodeJS.Platform;\n readonly arch: string;\n}\n\nexport interface SdkInitReport extends SdkInitState {\n readonly root: string;\n readonly store: 'offline' | 'registry';\n readonly onboarding: AgentOnboarding;\n}\n\nexport interface AgentOnboarding {\n readonly read: readonly string[];\n readonly templateSelection?: {\n readonly required: true;\n readonly game3d: 'game-3d';\n readonly otherwise: 'empty';\n };\n readonly next?: {\n readonly cwd: string;\n readonly argv: readonly string[];\n };\n}\n\nexport function agentOnboarding(sdk: SdkContext, projectRoot?: string): AgentOnboarding {\n const root = projectRoot ?? sdk.root;\n return {\n read: [\n resolve(root, 'AGENTS.md'),\n resolve(root, 'skills', 'forgeax-engine-sdk', 'SKILL.md'),\n resolve(root, 'skills', 'forgeax-engine-sdk', 'references', 'feature-catalog.md'),\n ],\n ...(projectRoot === undefined\n ? {\n templateSelection: {\n required: true as const,\n game3d: 'game-3d' as const,\n otherwise: 'empty' as const,\n },\n }\n : {}),\n ...(projectRoot === undefined\n ? {}\n : { next: { cwd: root, argv: ['pnpm', 'exec', 'forgeax', 'list', '--json'] } }),\n };\n}\n\nfunction sdkInitPath(sdk: SdkContext): string {\n return resolve(sdk.root, ...SDK_INIT_PATH);\n}\n\nfunction commandFailure(\n code: string,\n expected: string,\n hint: string,\n detail: Readonly<Record<string, unknown>> = {},\n): CommandResult<never> {\n return { ok: false, error: { code, expected, hint, detail } };\n}\n\nexport function sdkProjectInstallArgs(store: string | undefined): string[] {\n const common = [\n 'install',\n '--frozen-lockfile',\n '--ignore-scripts',\n '--config.pm-on-fail=ignore',\n '--side-effects-cache=true',\n '--child-concurrency=1',\n ];\n return store === undefined\n ? common\n : [...common, '--offline', '--config.trust-lockfile=true', '--store-dir', store];\n}\n\nfunction sdkBootstrapInstallArgs(store: string | undefined): string[] {\n const common = [\n 'install',\n '--frozen-lockfile',\n '--config.pm-on-fail=ignore',\n '--child-concurrency=1',\n '--side-effects-cache=true',\n ];\n return store === undefined\n ? common\n : [...common, '--offline', '--config.trust-lockfile=true', '--store-dir', store];\n}\n\nfunction supportedPnpm(version: string): boolean {\n const [major = 0, minor = 0] = version.split('.').map(Number);\n return major === 11 && minor >= 7;\n}\n\nasync function currentPnpm(): Promise<CommandResult<string>> {\n try {\n const result = await execFileAsync('pnpm', ['--version'], { maxBuffer: 1024 * 1024 });\n const version = result.stdout.trim();\n if (version.length === 0) throw new Error('pnpm returned an empty version');\n return { ok: true, value: version };\n } catch (cause) {\n return commandFailure(\n 'pnpm-unavailable',\n 'pnpm 11.7.0 or newer in the pnpm 11 line to be available on PATH',\n 'Install or activate pnpm 11, then rerun forgeax init from the SDK root.',\n { reason: cause instanceof Error ? cause.message : String(cause) },\n );\n }\n}\n\nfunction matchesState(sdk: SdkContext, state: unknown): state is SdkInitState {\n if (state === null || typeof state !== 'object' || Array.isArray(state)) return false;\n const value = state as Record<string, unknown>;\n return (\n value.schemaVersion === SDK_INIT_SCHEMA_VERSION &&\n value.sdkVersion === sdk.manifest.sdkVersion &&\n value.engineCommit === sdk.manifest.engineCommit &&\n typeof value.pnpm === 'string' &&\n supportedPnpm(value.pnpm) &&\n value.node === process.versions.node &&\n value.platform === process.platform &&\n value.arch === process.arch\n );\n}\n\nexport async function readSdkInitState(sdk: SdkContext): Promise<SdkInitState | undefined> {\n try {\n const value = JSON.parse(await readFile(sdkInitPath(sdk), 'utf8')) as unknown;\n return matchesState(sdk, value) ? value : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport async function requireSdkInitialization(\n sdk: SdkContext,\n): Promise<CommandResult<SdkInitState>> {\n const state = await readSdkInitState(sdk);\n if (state === undefined) {\n return commandFailure(\n 'sdk-not-initialized',\n 'the downloaded SDK to be initialized for this Node/pnpm/platform tuple',\n 'Run ./bin/forgeax init from the SDK root once, then run forgeax new outside the SDK.',\n {\n sdkRoot: sdk.root,\n sdkVersion: sdk.manifest.sdkVersion,\n pnpm: sdk.manifest.requirements.pnpm,\n node: process.versions.node,\n platform: process.platform,\n arch: process.arch,\n },\n );\n }\n return { ok: true, value: state };\n}\n\nasync function copyBootstrapInputs(sdk: SdkContext, root: string): Promise<void> {\n const template = sdk.templates.get('empty');\n if (template === undefined) throw new Error('sdk-bootstrap-template-missing');\n for (const name of ['package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml'] as const) {\n await cp(resolve(template, name), resolve(root, name));\n }\n try {\n await cp(resolve(template, '.npmrc'), resolve(root, '.npmrc'));\n } catch (cause) {\n if (\n cause === null ||\n typeof cause !== 'object' ||\n !('code' in cause) ||\n cause.code !== 'ENOENT'\n ) {\n throw cause;\n }\n }\n}\n\nexport async function sdkInitCommand(\n sdk: SdkContext,\n options: { readonly dryRun?: boolean; readonly install?: boolean } = {},\n): Promise<CommandResult<SdkInitReport>> {\n const pnpmResult = await currentPnpm();\n if (!pnpmResult.ok) return pnpmResult;\n if (!supportedPnpm(pnpmResult.value)) {\n return commandFailure(\n 'pnpm-version-unsupported',\n 'pnpm >=11.7.0 <12',\n 'Activate pnpm 11.7.0 or newer in the pnpm 11 line, then rerun forgeax init.',\n { actual: pnpmResult.value, expected: sdk.manifest.requirements.pnpm },\n );\n }\n const state: SdkInitState = {\n schemaVersion: SDK_INIT_SCHEMA_VERSION,\n sdkVersion: sdk.manifest.sdkVersion,\n engineCommit: sdk.manifest.engineCommit,\n pnpm: pnpmResult.value,\n node: process.versions.node,\n platform: process.platform,\n arch: process.arch,\n };\n const report: SdkInitReport = {\n ...state,\n root: sdk.root,\n store: sdk.store === undefined ? 'registry' : 'offline',\n onboarding: agentOnboarding(sdk),\n };\n if (options.dryRun === true || options.install === false) return { ok: true, value: report };\n\n let staging: string | undefined;\n try {\n staging = await mkdtemp(resolve(tmpdir(), 'forgeax-sdk-init-'));\n await copyBootstrapInputs(sdk, staging);\n await execFileAsync('pnpm', sdkBootstrapInstallArgs(sdk.store), {\n cwd: staging,\n env: { ...process.env, CI: 'true' },\n maxBuffer: 16 * 1024 * 1024,\n });\n await mkdir(resolve(sdk.root, '.forgeax'), { recursive: true });\n await writeFile(sdkInitPath(sdk), `${JSON.stringify(state, null, 2)}\\n`);\n return { ok: true, value: report };\n } catch (cause) {\n return commandFailure(\n 'sdk-init-failed',\n 'the SDK dependency closure to install and build native packages successfully',\n 'Inspect the pnpm output, repair Node/pnpm or platform permissions, then rerun forgeax init from the SDK root.',\n { reason: cause instanceof Error ? cause.message : String(cause), sdkRoot: sdk.root },\n );\n } finally {\n if (staging !== undefined) await rm(staging, { recursive: true, force: true });\n }\n}\n","const UPDATE_MIGRATION_RISK =\n 'Install a newer SDK in a separate directory. Existing games remain pinned and are not migrated automatically; review release notes and migrate and test each game before changing its Engine version.';\n\nexport type SdkUpdateStatus =\n | {\n readonly status: 'available';\n readonly currentVersion: string;\n readonly latestVersion: string;\n readonly migrationRisk: typeof UPDATE_MIGRATION_RISK;\n }\n | {\n readonly status: 'current';\n readonly currentVersion: string;\n readonly latestVersion: string;\n }\n | {\n readonly status: 'skipped';\n readonly currentVersion: string;\n readonly reason: 'offline' | 'disabled';\n }\n | {\n readonly status: 'unavailable';\n readonly currentVersion: string;\n readonly reason: string;\n };\n\ninterface ParsedVersion {\n readonly core: readonly [string, string, string];\n readonly prerelease?: readonly string[];\n}\n\nfunction parseVersion(version: string): ParsedVersion | undefined {\n const match =\n /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-([0-9A-Za-z.-]+))?(?:\\+[0-9A-Za-z.-]+)?$/.exec(\n version,\n );\n if (match === null) return undefined;\n const major = match[1];\n const minor = match[2];\n const patch = match[3];\n if (major === undefined || minor === undefined || patch === undefined) return undefined;\n const prerelease = match[4]?.split('.');\n if (\n prerelease?.some(\n (identifier) =>\n identifier.length === 0 || (/^\\d+$/.test(identifier) && /^0\\d+/.test(identifier)),\n )\n ) {\n return undefined;\n }\n return {\n core: [major, minor, patch],\n ...(prerelease === undefined ? {} : { prerelease }),\n };\n}\n\nfunction compareNumericIdentifier(current: string, latest: string): number {\n if (current.length !== latest.length) return latest.length > current.length ? 1 : -1;\n if (current === latest) return 0;\n return latest > current ? 1 : -1;\n}\n\nfunction comparePrerelease(current: readonly string[], latest: readonly string[]): number {\n const length = Math.max(current.length, latest.length);\n for (let index = 0; index < length; index += 1) {\n const currentIdentifier = current[index];\n const latestIdentifier = latest[index];\n if (currentIdentifier === undefined) return 1;\n if (latestIdentifier === undefined) return -1;\n if (currentIdentifier === latestIdentifier) continue;\n const currentNumeric = /^\\d+$/.test(currentIdentifier);\n const latestNumeric = /^\\d+$/.test(latestIdentifier);\n if (currentNumeric && latestNumeric) {\n return compareNumericIdentifier(currentIdentifier, latestIdentifier);\n }\n if (currentNumeric !== latestNumeric) return latestNumeric ? -1 : 1;\n return latestIdentifier > currentIdentifier ? 1 : -1;\n }\n return 0;\n}\n\nexport function newerSdkVersion(currentVersion: string, latestVersion: string): boolean {\n const current = parseVersion(currentVersion);\n const latest = parseVersion(latestVersion);\n if (current === undefined || latest === undefined) return false;\n for (let index = 0; index < current.core.length; index += 1) {\n const precedence = compareNumericIdentifier(\n current.core[index] ?? '0',\n latest.core[index] ?? '0',\n );\n if (precedence !== 0) return precedence > 0;\n }\n if (current.prerelease !== undefined && latest.prerelease === undefined) return true;\n if (current.prerelease === undefined || latest.prerelease === undefined) return false;\n return comparePrerelease(current.prerelease, latest.prerelease) > 0;\n}\n\nfunction offline(): boolean {\n return ['1', 'true'].includes((process.env.npm_config_offline ?? '').toLowerCase());\n}\n\nexport async function checkSdkUpdate(currentVersion: string): Promise<SdkUpdateStatus> {\n if (process.env.FORGEAX_DISABLE_UPDATE_CHECK === '1') {\n return { status: 'skipped', currentVersion, reason: 'disabled' };\n }\n if (offline()) return { status: 'skipped', currentVersion, reason: 'offline' };\n try {\n const registry = process.env.npm_config_registry ?? 'https://registry.npmjs.org/';\n const response = await fetch(\n new URL('@forgeax%2Fengine-sdk', `${registry.replace(/\\/$/, '')}/`),\n {\n headers: { accept: 'application/vnd.npm.install-v1+json' },\n signal: AbortSignal.timeout(2_000),\n },\n );\n if (!response.ok) throw new Error(`registry-http-${response.status}`);\n const metadata = (await response.json()) as {\n readonly 'dist-tags'?: { readonly latest?: unknown };\n };\n const latestVersion = metadata['dist-tags']?.latest;\n if (typeof latestVersion !== 'string') throw new Error('registry-latest-version-missing');\n return newerSdkVersion(currentVersion, latestVersion)\n ? {\n status: 'available',\n currentVersion,\n latestVersion,\n migrationRisk: UPDATE_MIGRATION_RISK,\n }\n : { status: 'current', currentVersion, latestVersion };\n } catch (cause) {\n return {\n status: 'unavailable',\n currentVersion,\n reason: cause instanceof Error ? cause.message : String(cause),\n };\n }\n}\n","import {\n cp,\n lstat,\n mkdir,\n readdir,\n readFile,\n readlink,\n rm,\n rmdir,\n symlink,\n writeFile,\n} from 'node:fs/promises';\nimport { dirname, relative, resolve, sep } from 'node:path';\nimport { commandError, readProjectFacts } from './project.js';\nimport type { SdkContext, SdkSkill } from './sdk.js';\nimport type { CommandResult, ProjectCommandOptions } from './types.js';\n\nexport const PROJECT_SKILL_MOUNT_ROOTS = Object.freeze([\n '.codebuddy/skills',\n '.cursor/skills',\n '.agents/skills',\n '.claude/skills',\n '.workbuddy/skills',\n '.forgeax/skills',\n]);\nconst RETIRED_PROJECT_SKILL_MOUNT_ROOTS = new Set(['.claude-internal/skills']);\n\nconst MANIFEST_PATH = '.forgeax/skill-install-manifest.json';\nconst GITIGNORE_BEGIN = '# BEGIN FORGEAX MANAGED SKILLS';\nconst GITIGNORE_END = '# END FORGEAX MANAGED SKILLS';\n\ninterface InstalledSkill extends SdkSkill {}\n\ninterface SkillInstallManifest {\n readonly schemaVersion: '1.0.0';\n readonly sourceRoot: 'skills';\n readonly sdkVersion?: string;\n readonly engineCommit?: string;\n readonly skills: readonly InstalledSkill[];\n readonly mounts: readonly {\n readonly root: string;\n readonly skills: readonly string[];\n }[];\n}\n\nexport interface SkillInstallReport {\n readonly root: string;\n readonly sourceRoot: string;\n readonly manifest: string;\n readonly skills: readonly string[];\n readonly mountRoots: readonly string[];\n}\n\nfunction slash(path: string): string {\n return path.split(sep).join('/');\n}\n\nfunction contained(parent: string, child: string): boolean {\n const path = relative(parent, child);\n return path !== '' && path !== '..' && !path.startsWith(`..${sep}`) && !path.startsWith(sep);\n}\n\nasync function pathKind(path: string): Promise<'missing' | 'directory' | 'file' | 'symlink'> {\n try {\n const info = await lstat(path);\n if (info.isSymbolicLink()) return 'symlink';\n if (info.isDirectory()) return 'directory';\n return 'file';\n } catch (cause) {\n if (cause !== null && typeof cause === 'object' && 'code' in cause && cause.code === 'ENOENT') {\n return 'missing';\n }\n throw cause;\n }\n}\n\nasync function filesUnder(root: string, directory = root): Promise<readonly string[]> {\n const files: string[] = [];\n for (const name of (await readdir(directory)).sort()) {\n const path = resolve(directory, name);\n const info = await lstat(path);\n if (info.isSymbolicLink()) throw new Error(`skill-source-symlink: ${path}`);\n if (info.isDirectory()) files.push(...(await filesUnder(root, path)));\n else if (info.isFile()) files.push(path);\n }\n return files;\n}\n\nasync function skillRow(sourceRoot: string, id: string): Promise<InstalledSkill> {\n if (!/^[a-z0-9][a-z0-9-]*$/.test(id)) throw new Error(`skill-id-invalid: ${id}`);\n const root = resolve(sourceRoot, id);\n if ((await pathKind(root)) !== 'directory') throw new Error(`skill-source-invalid: ${id}`);\n if ((await pathKind(resolve(root, 'SKILL.md'))) !== 'file') {\n throw new Error(`skill-entry-missing: ${id}/SKILL.md`);\n }\n const files = await filesUnder(root);\n return {\n id,\n root: `skills/${id}`,\n fileCount: files.length,\n byteCount: (\n await Promise.all(files.map(async (path) => (await readFile(path)).byteLength))\n ).reduce((sum, bytes) => sum + bytes, 0),\n };\n}\n\nasync function discoverProjectSkills(root: string): Promise<readonly InstalledSkill[]> {\n const sourceRoot = resolve(root, 'skills');\n if ((await pathKind(sourceRoot)) !== 'directory') throw new Error('project-skills-missing');\n const entries = await readdir(sourceRoot, { withFileTypes: true });\n const ids = entries\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name)\n .sort();\n if (ids.length === 0) throw new Error('project-skills-empty');\n return Promise.all(ids.map((id) => skillRow(sourceRoot, id)));\n}\n\nasync function sameFiles(leftRoot: string, rightRoot: string): Promise<boolean> {\n const left = await filesUnder(leftRoot);\n const right = await filesUnder(rightRoot);\n const leftNames = left.map((path) => slash(relative(leftRoot, path)));\n const rightNames = right.map((path) => slash(relative(rightRoot, path)));\n if (JSON.stringify(leftNames) !== JSON.stringify(rightNames)) return false;\n for (let index = 0; index < left.length; index += 1) {\n const leftPath = left[index];\n const rightPath = right[index];\n if (leftPath === undefined || rightPath === undefined) return false;\n if (!(await readFile(leftPath)).equals(await readFile(rightPath))) return false;\n }\n return true;\n}\n\nexport async function copySdkSkills(sdk: SdkContext, projectRoot: string): Promise<void> {\n const targetSourceRoot = resolve(projectRoot, 'skills');\n const copies: { source: string; destination: string }[] = [];\n for (const skill of sdk.manifest.skills) {\n const source = resolve(sdk.root, skill.root);\n const destination = resolve(projectRoot, skill.root);\n if (!contained(sdk.root, source) || !contained(projectRoot, destination)) {\n throw new Error(`sdk-skill-path-invalid: ${skill.id}`);\n }\n const actual = await skillRow(resolve(sdk.root, 'skills'), skill.id);\n if (\n actual.root !== skill.root ||\n actual.fileCount !== skill.fileCount ||\n actual.byteCount !== skill.byteCount\n ) {\n throw new Error(`sdk-skill-manifest-drift: ${skill.id}`);\n }\n const kind = await pathKind(destination);\n if (kind === 'missing') {\n copies.push({ source, destination });\n } else if (kind !== 'directory' || !(await sameFiles(source, destination))) {\n throw new Error(`project-skill-source-conflict: ${skill.id}`);\n }\n }\n const created: string[] = [];\n try {\n await mkdir(targetSourceRoot, { recursive: true });\n for (const { source, destination } of copies) {\n await cp(source, destination, { recursive: true, errorOnExist: true, force: false });\n created.push(destination);\n }\n } catch (cause) {\n await Promise.all(created.map((path) => rm(path, { recursive: true, force: true })));\n throw cause;\n }\n}\n\nfunction expectedLinkTarget(projectRoot: string, mountRoot: string, id: string): string {\n const mountParent = resolve(projectRoot, mountRoot);\n const target = resolve(projectRoot, 'skills', id);\n return process.platform === 'win32' ? target : relative(mountParent, target);\n}\n\nasync function linkMatches(path: string, target: string): Promise<boolean> {\n if ((await pathKind(path)) !== 'symlink') return false;\n const actual = await readlink(path);\n return resolve(dirname(path), actual) === resolve(dirname(path), target);\n}\n\nfunction updateManagedGitignore(previous: string, skillIds: readonly string[]): string {\n const block = `${GITIGNORE_BEGIN}\\n${skillIds.map((id) => `/${id}`).join('\\n')}\\n${GITIGNORE_END}`;\n const begin = previous.indexOf(GITIGNORE_BEGIN);\n const end = previous.indexOf(GITIGNORE_END);\n if (begin >= 0 && end >= begin) {\n const after = end + GITIGNORE_END.length;\n return `${previous.slice(0, begin)}${block}${previous.slice(after)}`.replace(/^\\n+/, '');\n }\n return previous.length === 0 ? `${block}\\n` : `${previous.replace(/\\s*$/, '')}\\n\\n${block}\\n`;\n}\n\nfunction removeManagedGitignore(previous: string): string {\n const begin = previous.indexOf(GITIGNORE_BEGIN);\n const end = previous.indexOf(GITIGNORE_END);\n if (begin < 0 || end < begin) return previous;\n const before = previous.slice(0, begin).trimEnd();\n const after = previous.slice(end + GITIGNORE_END.length).trimStart();\n const retained = [before, after].filter((part) => part.length > 0).join('\\n');\n return retained.length === 0 ? '' : `${retained}\\n`;\n}\n\nasync function removeEmptyDirectory(path: string): Promise<void> {\n try {\n await rmdir(path);\n } catch (cause) {\n if (\n cause !== null &&\n typeof cause === 'object' &&\n 'code' in cause &&\n (cause.code === 'ENOENT' || cause.code === 'ENOTEMPTY' || cause.code === 'EEXIST')\n ) {\n return;\n }\n throw cause;\n }\n}\n\nasync function readOptional(path: string): Promise<string | undefined> {\n try {\n return await readFile(path, 'utf8');\n } catch (cause) {\n if (cause !== null && typeof cause === 'object' && 'code' in cause && cause.code === 'ENOENT') {\n return undefined;\n }\n throw cause;\n }\n}\n\nasync function readInstallManifest(root: string): Promise<SkillInstallManifest | undefined> {\n const value = await readOptional(resolve(root, MANIFEST_PATH));\n return value === undefined ? undefined : (JSON.parse(value) as SkillInstallManifest);\n}\n\nexport async function installProjectSkills(\n root: string,\n provenance?: Pick<SdkContext['manifest'], 'sdkVersion' | 'engineCommit'>,\n): Promise<SkillInstallReport> {\n const projectRoot = resolve(root);\n const skills = await discoverProjectSkills(projectRoot);\n const ids = skills.map((skill) => skill.id);\n const priorManifest = await readInstallManifest(projectRoot);\n const desiredLinks = PROJECT_SKILL_MOUNT_ROOTS.flatMap((mountRoot) =>\n ids.map((id) => ({\n path: resolve(projectRoot, mountRoot, id),\n target: expectedLinkTarget(projectRoot, mountRoot, id),\n })),\n );\n const desiredPaths = new Set(desiredLinks.map((entry) => entry.path));\n const desiredMountRoots = new Set<string>(PROJECT_SKILL_MOUNT_ROOTS);\n const retiredMountRoots = (priorManifest?.mounts ?? [])\n .map((mount) => mount.root)\n .filter(\n (mountRoot) =>\n !desiredMountRoots.has(mountRoot) && RETIRED_PROJECT_SKILL_MOUNT_ROOTS.has(mountRoot),\n );\n const staleLinks = (priorManifest?.mounts ?? [])\n .flatMap((mount) =>\n mount.skills.map((id) => ({\n path: resolve(projectRoot, mount.root, id),\n target: expectedLinkTarget(projectRoot, mount.root, id),\n })),\n )\n .filter((entry) => !desiredPaths.has(entry.path));\n\n for (const entry of desiredLinks) {\n const kind = await pathKind(entry.path);\n if (kind !== 'missing' && !(await linkMatches(entry.path, entry.target))) {\n throw new Error(`skill-mount-conflict: ${slash(relative(projectRoot, entry.path))}`);\n }\n }\n for (const entry of staleLinks) {\n const kind = await pathKind(entry.path);\n if (kind !== 'missing' && !(await linkMatches(entry.path, entry.target))) {\n throw new Error(`skill-stale-mount-conflict: ${slash(relative(projectRoot, entry.path))}`);\n }\n }\n\n const ignoreSnapshots = new Map<string, string | undefined>();\n const createdLinks: string[] = [];\n const removedLinks: { path: string; target: string }[] = [];\n const manifestPath = resolve(projectRoot, MANIFEST_PATH);\n const priorManifestText = await readOptional(manifestPath);\n try {\n for (const entry of staleLinks) {\n if ((await pathKind(entry.path)) === 'symlink') {\n await rm(entry.path);\n removedLinks.push(entry);\n }\n }\n for (const mountRoot of retiredMountRoots) {\n const mountParent = resolve(projectRoot, mountRoot);\n const ignorePath = resolve(mountParent, '.gitignore');\n const previous = await readOptional(ignorePath);\n ignoreSnapshots.set(ignorePath, previous);\n if (previous !== undefined) {\n const retained = removeManagedGitignore(previous);\n if (retained.length === 0) await rm(ignorePath);\n else await writeFile(ignorePath, retained);\n }\n await removeEmptyDirectory(mountParent);\n await removeEmptyDirectory(dirname(mountParent));\n }\n for (const mountRoot of PROJECT_SKILL_MOUNT_ROOTS) {\n const mountParent = resolve(projectRoot, mountRoot);\n await mkdir(mountParent, { recursive: true });\n const ignorePath = resolve(mountParent, '.gitignore');\n const previous = await readOptional(ignorePath);\n ignoreSnapshots.set(ignorePath, previous);\n await writeFile(ignorePath, updateManagedGitignore(previous ?? '', ids));\n for (const id of ids) {\n const path = resolve(mountParent, id);\n if ((await pathKind(path)) === 'missing') {\n const target = expectedLinkTarget(projectRoot, mountRoot, id);\n await symlink(target, path, process.platform === 'win32' ? 'junction' : 'dir');\n createdLinks.push(path);\n }\n }\n }\n const sdkVersion = provenance?.sdkVersion ?? priorManifest?.sdkVersion;\n const engineCommit = provenance?.engineCommit ?? priorManifest?.engineCommit;\n const manifest: SkillInstallManifest = {\n schemaVersion: '1.0.0',\n sourceRoot: 'skills',\n ...(sdkVersion === undefined ? {} : { sdkVersion }),\n ...(engineCommit === undefined ? {} : { engineCommit }),\n skills,\n mounts: PROJECT_SKILL_MOUNT_ROOTS.map((mountRoot) => ({ root: mountRoot, skills: ids })),\n };\n await mkdir(dirname(manifestPath), { recursive: true });\n await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\\n`);\n } catch (cause) {\n await Promise.all(createdLinks.map((path) => rm(path, { force: true })));\n await Promise.all(\n removedLinks.map(async ({ path, target }) => {\n await mkdir(dirname(path), { recursive: true });\n await symlink(target, path, process.platform === 'win32' ? 'junction' : 'dir');\n }),\n );\n await Promise.all(\n [...ignoreSnapshots].map(async ([path, value]) => {\n if (value === undefined) await rm(path, { force: true });\n else {\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, value);\n }\n }),\n );\n if (priorManifestText === undefined) await rm(manifestPath, { force: true });\n else await writeFile(manifestPath, priorManifestText);\n throw cause;\n }\n return {\n root: projectRoot,\n sourceRoot: resolve(projectRoot, 'skills'),\n manifest: manifestPath,\n skills: ids,\n mountRoots: PROJECT_SKILL_MOUNT_ROOTS,\n };\n}\n\nexport async function verifyProjectSkills(root: string): Promise<SkillInstallReport> {\n const projectRoot = resolve(root);\n const skills = await discoverProjectSkills(projectRoot);\n const ids = skills.map((skill) => skill.id);\n const manifest = await readInstallManifest(projectRoot);\n if (manifest === undefined) throw new Error('skill-install-manifest-missing');\n if (\n manifest.schemaVersion !== '1.0.0' ||\n manifest.sourceRoot !== 'skills' ||\n JSON.stringify(manifest.skills) !== JSON.stringify(skills) ||\n JSON.stringify(manifest.mounts.map((mount) => mount.root)) !==\n JSON.stringify(PROJECT_SKILL_MOUNT_ROOTS)\n ) {\n throw new Error('skill-install-manifest-drift');\n }\n for (const mountRoot of PROJECT_SKILL_MOUNT_ROOTS) {\n const declared = manifest.mounts.find((mount) => mount.root === mountRoot);\n if (declared === undefined || JSON.stringify(declared.skills) !== JSON.stringify(ids)) {\n throw new Error(`skill-install-manifest-mount-drift: ${mountRoot}`);\n }\n const ignore = await readOptional(resolve(projectRoot, mountRoot, '.gitignore'));\n if (ignore === undefined || updateManagedGitignore(ignore, ids) !== ignore) {\n throw new Error(`skill-mount-gitignore-drift: ${mountRoot}`);\n }\n for (const id of ids) {\n const path = resolve(projectRoot, mountRoot, id);\n const target = expectedLinkTarget(projectRoot, mountRoot, id);\n if (!(await linkMatches(path, target))) {\n throw new Error(`skill-mount-drift: ${mountRoot}/${id}`);\n }\n }\n }\n return {\n root: projectRoot,\n sourceRoot: resolve(projectRoot, 'skills'),\n manifest: resolve(projectRoot, MANIFEST_PATH),\n skills: ids,\n mountRoots: PROJECT_SKILL_MOUNT_ROOTS,\n };\n}\n\nexport async function skillInstallCommand(\n options: ProjectCommandOptions = {},\n): Promise<CommandResult<SkillInstallReport>> {\n const facts = await readProjectFacts(options.root);\n if (!facts.ok) return facts;\n try {\n return { ok: true, value: await installProjectSkills(facts.value.root) };\n } catch (cause) {\n return { ok: false, error: commandError(cause, 'skill-install-failed') };\n }\n}\n\nexport async function skillVerifyCommand(\n options: ProjectCommandOptions = {},\n): Promise<CommandResult<SkillInstallReport>> {\n const facts = await readProjectFacts(options.root);\n if (!facts.ok) return facts;\n try {\n return { ok: true, value: await verifyProjectSkills(facts.value.root) };\n } catch (cause) {\n return { ok: false, error: commandError(cause, 'skill-verify-failed') };\n }\n}\n","import { execFile } from 'node:child_process';\nimport {\n copyFile,\n cp,\n mkdir,\n mkdtemp,\n readdir,\n readFile,\n realpath,\n rename,\n rm,\n writeFile,\n} from 'node:fs/promises';\nimport { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';\nimport { promisify } from 'node:util';\nimport { applyInitPlan, createInitPlan } from './init.js';\nimport { commandError, readProjectFacts } from './project.js';\nimport { findSdkContext } from './sdk.js';\nimport {\n agentOnboarding,\n requireSdkInitialization,\n sdkInitCommand,\n sdkProjectInstallArgs,\n} from './sdk-bootstrap.js';\nimport { checkSdkUpdate } from './sdk-update.js';\nimport { copySdkSkills, installProjectSkills } from './skill-install.js';\nimport type { CommandResult, InitOptions, NewOptions, ProjectCommandOptions } from './types.js';\n\nconst execFileAsync = promisify(execFile);\n\nfunction isMissingPathError(cause: unknown): boolean {\n return cause !== null && typeof cause === 'object' && 'code' in cause && cause.code === 'ENOENT';\n}\n\nasync function canonicalProspectivePath(path: string): Promise<string> {\n let cursor = resolve(path);\n const suffix: string[] = [];\n for (;;) {\n try {\n return resolve(await realpath(cursor), ...suffix.reverse());\n } catch (cause) {\n if (!isMissingPathError(cause)) throw cause;\n const parent = dirname(cursor);\n if (parent === cursor) throw cause;\n suffix.push(basename(cursor));\n cursor = parent;\n }\n }\n}\n\nasync function configureSdkStore(root: string, store: string | undefined): Promise<void> {\n if (store === undefined) return;\n const path = resolve(root, '.npmrc');\n let content = '';\n try {\n content = await readFile(path, 'utf8');\n } catch (cause) {\n if (!isMissingPathError(cause)) throw cause;\n }\n const lines = content\n .split(/\\r?\\n/)\n .filter((line) => line.trim().length > 0 && !/^\\s*store-dir\\s*=/.test(line));\n lines.push(`store-dir=${store}`);\n await writeFile(path, `${lines.join('\\n')}\\n`);\n}\n\nfunction containsOrEquals(parent: string, child: string): boolean {\n const path = relative(parent, child);\n return path === '' || (path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path));\n}\n\nexport interface DoctorReport {\n readonly root: string;\n readonly projectId: string;\n readonly node: string;\n readonly pnpm: string;\n readonly workspaceDependencies: readonly string[];\n}\n\nfunction nodeSupported(): boolean {\n const [major = 0, minor = 0] = process.versions.node.split('.').map(Number);\n return major > 22 || (major === 22 && minor >= 13);\n}\n\nfunction pnpmSupported(version: string): boolean {\n const [major = 0, minor = 0] = version.split('.').map(Number);\n return major === 11 && minor >= 7;\n}\n\nexport async function doctorCommand(\n options: ProjectCommandOptions = {},\n): Promise<CommandResult<DoctorReport>> {\n const facts = await readProjectFacts(options.root);\n if (!facts.ok) return facts;\n let pnpm: string;\n try {\n pnpm = (await execFileAsync('pnpm', ['--version'], { cwd: facts.value.root })).stdout.trim();\n } catch (cause) {\n return {\n ok: false,\n error: {\n code: 'pnpm-unavailable',\n expected: 'pnpm to be available on PATH',\n hint: 'Install the SDK-supported pnpm version and retry.',\n detail: { reason: cause instanceof Error ? cause.message : String(cause) },\n },\n };\n }\n if (!nodeSupported()) {\n return {\n ok: false,\n error: {\n code: 'node-version-unsupported',\n expected: 'Node.js >=22.13.0',\n hint: 'Select a supported Node.js installation and retry.',\n detail: { actual: process.versions.node },\n },\n };\n }\n if (!pnpmSupported(pnpm)) {\n return {\n ok: false,\n error: {\n code: 'pnpm-version-unsupported',\n expected: 'pnpm >=11.7.0 <12',\n hint: 'Enable the packageManager-declared pnpm version with Corepack and retry.',\n detail: { actual: pnpm },\n },\n };\n }\n const workspaceDependencies: string[] = [];\n for (const section of ['dependencies', 'devDependencies']) {\n const value = facts.value.packageJson[section];\n if (value === null || typeof value !== 'object') continue;\n for (const [name, version] of Object.entries(value)) {\n if (\n typeof version === 'string' &&\n (version.startsWith('workspace:') || version.startsWith('file:'))\n ) {\n workspaceDependencies.push(name);\n }\n }\n }\n if (workspaceDependencies.length > 0) {\n return {\n ok: false,\n error: {\n code: 'project-local-dependency',\n expected: 'all external project dependencies to use SDK-resolved exact versions',\n hint: 'Run forgeax init from the unpacked SDK and commit the resulting lockfile.',\n detail: { dependencies: workspaceDependencies.sort() },\n },\n };\n }\n return {\n ok: true,\n value: {\n root: facts.value.root,\n projectId: facts.value.id,\n node: process.versions.node,\n pnpm,\n workspaceDependencies,\n },\n };\n}\n\nexport async function initCommand(options: InitOptions = {}): Promise<CommandResult<unknown>> {\n try {\n const sdk = await findSdkContext();\n const root = await canonicalProspectivePath(options.root ?? process.cwd());\n if (sdk !== undefined && root === (await canonicalProspectivePath(sdk.root))) {\n return sdkInitCommand(sdk, options);\n }\n const facts = await readProjectFacts(root);\n if (!facts.ok) return facts;\n const plan = createInitPlan(facts.value, sdk?.manifest);\n if (!plan.ok) return plan;\n if (sdk !== undefined && options.dryRun !== true) {\n const initialized = await requireSdkInitialization(sdk);\n if (!initialized.ok) return initialized;\n }\n const applied = await applyInitPlan(facts.value, plan.value, options);\n if (!applied.ok || options.dryRun === true) return applied;\n if (sdk !== undefined) {\n const template = sdk.templates.get('empty');\n if (template === undefined) throw new Error('sdk-bootstrap-template-missing');\n await copyFile(\n resolve(template, 'pnpm-lock.yaml'),\n resolve(facts.value.root, 'pnpm-lock.yaml'),\n );\n await copyFile(\n resolve(template, 'pnpm-workspace.yaml'),\n resolve(facts.value.root, 'pnpm-workspace.yaml'),\n );\n try {\n await readFile(resolve(facts.value.root, '.npmrc'), 'utf8');\n } catch (cause) {\n if (!isMissingPathError(cause)) throw cause;\n try {\n await copyFile(resolve(template, '.npmrc'), resolve(facts.value.root, '.npmrc'));\n } catch (templateCause) {\n if (!isMissingPathError(templateCause)) throw templateCause;\n }\n }\n await copySdkSkills(sdk, facts.value.root);\n await installProjectSkills(facts.value.root, sdk.manifest);\n await configureSdkStore(\n facts.value.root,\n sdk.store === undefined ? undefined : await canonicalProspectivePath(sdk.store),\n );\n }\n if (options.install === false) return applied;\n const store =\n sdk === undefined || sdk.store === undefined\n ? undefined\n : await canonicalProspectivePath(sdk.store);\n const installArgs =\n sdk === undefined ? ['install', '--frozen-lockfile=false'] : sdkProjectInstallArgs(store);\n await execFileAsync('pnpm', installArgs, {\n cwd: facts.value.root,\n env: { ...process.env, CI: 'true' },\n maxBuffer: 16 * 1024 * 1024,\n });\n return applied;\n } catch (cause) {\n return { ok: false, error: commandError(cause, 'project-init-failed') };\n }\n}\n\nexport async function newCommand(options: NewOptions = {}): Promise<CommandResult<unknown>> {\n try {\n const sdk = await findSdkContext();\n if (sdk === undefined) {\n return {\n ok: false,\n error: {\n code: 'sdk-context-missing',\n expected: 'forgeax new to run from an unpacked ForgeaX SDK',\n hint: 'Run the SDK archive bin/forgeax.mjs entry or set FORGEAX_SDK_ROOT.',\n detail: {},\n },\n };\n }\n const root = resolve(options.root ?? process.cwd());\n if (\n containsOrEquals(\n await canonicalProspectivePath(sdk.root),\n await canonicalProspectivePath(root),\n )\n ) {\n return {\n ok: false,\n error: {\n code: 'project-target-inside-sdk',\n expected: 'forgeax new target to be outside the unpacked SDK root',\n hint: 'Choose a sibling directory or an absolute path outside the SDK.',\n detail: { root, sdkRoot: sdk.root },\n },\n };\n }\n if (options.template === undefined) {\n return {\n ok: false,\n error: {\n code: 'sdk-template-required',\n expected: 'forgeax new to select exactly one template with --template',\n hint: 'Use --template game-3d for a 3D game; otherwise use --template empty.',\n detail: { templates: [...sdk.templates.keys()].sort() },\n },\n };\n }\n const templateId = options.template;\n const template = sdk.templates.get(templateId);\n if (template === undefined) {\n return {\n ok: false,\n error: {\n code: 'sdk-template-not-found',\n expected: 'a template id declared by sdk-manifest.json',\n hint: `Choose one of: ${[...sdk.templates.keys()].sort().join(', ')}.`,\n detail: { template: templateId },\n },\n };\n }\n let targetExists = true;\n let entries: string[];\n try {\n entries = await readdir(root);\n } catch (cause) {\n if (!isMissingPathError(cause)) throw cause;\n targetExists = false;\n entries = [];\n }\n if (entries.length > 0) {\n return {\n ok: false,\n error: {\n code: 'project-target-not-empty',\n expected: 'forgeax new target to be absent or empty',\n hint: 'Choose an empty directory so existing files cannot be overwritten.',\n detail: { root },\n },\n };\n }\n if (options.dryRun === true) {\n return {\n ok: true,\n value: { root, template: templateId, sdkVersion: sdk.manifest.sdkVersion },\n };\n }\n const initialized = await requireSdkInitialization(sdk);\n if (!initialized.ok) return initialized;\n const parent = dirname(root);\n await mkdir(parent, { recursive: true });\n let staging: string | undefined = await mkdtemp(\n resolve(parent, `.${basename(root)}.forgeax-staging-`),\n );\n const committedNames: string[] = [];\n let committed = false;\n try {\n for (const name of await readdir(template)) {\n await cp(resolve(template, name), resolve(staging, name), {\n recursive: true,\n errorOnExist: true,\n force: false,\n });\n }\n await copySdkSkills(sdk, staging);\n await installProjectSkills(staging, sdk.manifest);\n const store = sdk.store === undefined ? undefined : await canonicalProspectivePath(sdk.store);\n await configureSdkStore(staging, store);\n if (!targetExists) {\n await rename(staging, root);\n staging = undefined;\n committedNames.push(...(await readdir(root)));\n } else {\n for (const name of await readdir(staging)) {\n await rename(resolve(staging, name), resolve(root, name));\n committedNames.push(name);\n }\n await rm(staging, { recursive: true, force: true });\n staging = undefined;\n }\n committed = true;\n // Install after the final rename so pnpm's virtual-store metadata keeps\n // the real project path. Installing inside staging would force a second\n // registry resolution when `pnpm exec` runs from the committed project.\n await execFileAsync('pnpm', sdkProjectInstallArgs(store), {\n cwd: root,\n env: { ...process.env, CI: 'true' },\n maxBuffer: 16 * 1024 * 1024,\n });\n const sdkUpdate = await checkSdkUpdate(sdk.manifest.sdkVersion);\n return {\n ok: true,\n value: {\n root,\n template: templateId,\n sdkVersion: sdk.manifest.sdkVersion,\n onboarding: agentOnboarding(sdk, root),\n sdkUpdate,\n },\n };\n } catch (cause) {\n if (staging !== undefined) await rm(staging, { recursive: true, force: true });\n if (committed) {\n if (!targetExists) {\n await rm(root, { recursive: true, force: true });\n return { ok: false, error: commandError(cause, 'project-create-failed') };\n }\n const cleanupNames = new Set([...committedNames, 'node_modules']);\n await Promise.all(\n [...cleanupNames].map((name) =>\n rm(resolve(root, name), { recursive: true, force: true }),\n ),\n );\n } else {\n await Promise.all(\n committedNames.map((name) => rm(resolve(root, name), { recursive: true, force: true })),\n );\n }\n return { ok: false, error: commandError(cause, 'project-create-failed') };\n }\n } catch (cause) {\n return { ok: false, error: commandError(cause, 'project-create-failed') };\n }\n}\n","import { execFile } from 'node:child_process';\nimport { readFile, rename, unlink, writeFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { promisify } from 'node:util';\nimport { type GameProjectPluginEntry, GameProjectSchema } from '@forgeax/engine-project';\nimport type { CommandResult, PluginInstallOptions, PluginUninstallOptions } from './types.js';\n\nconst execFileAsync = promisify(execFile);\n\nasync function readManifest(root: string): Promise<CommandResult<{ raw: string; value: unknown }>> {\n const path = resolve(root, 'forge.json');\n try {\n const raw = await readFile(path, 'utf8');\n return { ok: true, value: { raw, value: JSON.parse(raw) as unknown } };\n } catch (cause) {\n return {\n ok: false,\n error: {\n code: 'plugin-manifest-unreadable',\n expected: 'a readable forge.json',\n hint: 'Repair the project manifest before changing plugin installation state.',\n detail: { path, reason: cause instanceof Error ? cause.message : String(cause) },\n },\n };\n }\n}\n\nasync function writeManifest(root: string, value: unknown): Promise<void> {\n const path = resolve(root, 'forge.json');\n const temporary = resolve(root, `.forgeax-plugin-${process.pid}.tmp`);\n await writeFile(temporary, `${JSON.stringify(value, null, 2)}\\n`);\n try {\n await rename(temporary, path);\n } catch (cause) {\n await unlink(temporary).catch(() => undefined);\n throw cause;\n }\n}\n\nfunction allEntries(entries: readonly GameProjectPluginEntry[]): GameProjectPluginEntry[] {\n return entries.flatMap((entry) => [\n entry,\n ...(entry.group === true ? allEntries(entry.config as readonly GameProjectPluginEntry[]) : []),\n ]);\n}\n\nfunction withoutEntry(\n entries: readonly GameProjectPluginEntry[],\n id: string,\n): GameProjectPluginEntry[] {\n return entries.flatMap((entry) => {\n if (entry.id === id) return [];\n if (entry.group !== true) return [entry];\n return [\n {\n ...entry,\n config: withoutEntry(entry.config as readonly GameProjectPluginEntry[], id),\n },\n ];\n });\n}\n\nasync function mutateDependency(\n root: string,\n action: 'add' | 'remove',\n dependency: string | undefined,\n): Promise<void> {\n if (dependency === undefined) return;\n await execFileAsync('pnpm', [action, dependency], { cwd: root, maxBuffer: 16 * 1024 * 1024 });\n}\n\nexport async function pluginInstallCommand(\n options: PluginInstallOptions,\n): Promise<CommandResult<unknown>> {\n const root = resolve(options.root ?? process.cwd());\n const manifest = await readManifest(root);\n if (!manifest.ok) return manifest;\n const parsed = GameProjectSchema.safeParse(manifest.value.value);\n if (!parsed.success) {\n return {\n ok: false,\n error: {\n code: 'plugin-manifest-invalid',\n expected: 'forge.json to satisfy GameProjectSchema',\n hint: 'Repair the manifest before installing a plugin.',\n detail: { issues: parsed.error.issues },\n },\n };\n }\n const entries = parsed.data.plugins ?? [];\n if (allEntries(entries).some((entry) => entry.id === options.id)) {\n return {\n ok: false,\n error: {\n code: 'plugin-entry-id-conflict',\n expected: 'a project-unique plugin Entry id',\n hint: 'Choose a stable id not already present in forge.json#plugins.',\n detail: { id: options.id },\n },\n };\n }\n const next = {\n ...parsed.data,\n plugins: [\n ...entries,\n { id: options.id, name: options.module, realm: options.realm ?? 'engine' },\n ],\n };\n if (options.dryRun === true) return { ok: true, value: { root, manifest: next } };\n try {\n await writeManifest(root, next);\n await mutateDependency(root, 'add', options.dependency);\n return { ok: true, value: { root, id: options.id, module: options.module } };\n } catch (cause) {\n await writeFile(resolve(root, 'forge.json'), manifest.value.raw);\n return {\n ok: false,\n error: {\n code: 'plugin-install-failed',\n expected: 'dependency and forge.json Entry mutations to commit together',\n hint: 'Inspect the package-manager failure; the original forge.json was restored.',\n detail: { reason: cause instanceof Error ? cause.message : String(cause) },\n },\n };\n }\n}\n\nexport async function pluginUninstallCommand(\n options: PluginUninstallOptions,\n): Promise<CommandResult<unknown>> {\n const root = resolve(options.root ?? process.cwd());\n const manifest = await readManifest(root);\n if (!manifest.ok) return manifest;\n const parsed = GameProjectSchema.safeParse(manifest.value.value);\n if (!parsed.success) {\n return {\n ok: false,\n error: {\n code: 'plugin-manifest-invalid',\n expected: 'forge.json to satisfy GameProjectSchema',\n hint: 'Repair the manifest before uninstalling a plugin.',\n detail: { issues: parsed.error.issues },\n },\n };\n }\n const entries = parsed.data.plugins ?? [];\n if (!allEntries(entries).some((entry) => entry.id === options.id)) {\n return {\n ok: false,\n error: {\n code: 'plugin-entry-missing',\n expected: 'the plugin Entry id to exist',\n hint: 'Inspect forge.json#plugins and pass an installed Entry id.',\n detail: { id: options.id },\n },\n };\n }\n const next = { ...parsed.data, plugins: withoutEntry(entries, options.id) };\n if (options.dryRun === true) return { ok: true, value: { root, manifest: next } };\n try {\n await writeManifest(root, next);\n await mutateDependency(root, 'remove', options.dependency);\n return { ok: true, value: { root, id: options.id } };\n } catch (cause) {\n await writeFile(resolve(root, 'forge.json'), manifest.value.raw);\n return {\n ok: false,\n error: {\n code: 'plugin-uninstall-failed',\n expected: 'Entry and dependency removal to commit together',\n hint: 'Inspect the package-manager failure; the original forge.json was restored.',\n detail: { reason: cause instanceof Error ? cause.message : String(cause) },\n },\n };\n }\n}\n","import { readFile } from 'node:fs/promises';\nimport { createRhiDebugError, replayDeviceRequest, type V7Tape } from '@forgeax/engine-rhi-debug';\nimport { createShaderModule, rhi } from '@forgeax/engine-rhi-webgpu';\nimport { err } from '@forgeax/engine-types';\nimport type { ArtifactRef, RhiDebugOperationContext } from './operations.js';\n\nexport function createCliRhiDebugOperationContext(): RhiDebugOperationContext {\n return {\n captureFrame: async () =>\n err(\n createRhiDebugError('capture-unavailable', {\n stage: 'capture',\n cause:\n 'the standalone CLI has no live App capture provider; start a recorder-enabled live host and invoke its rhiCapture root',\n }),\n ),\n async readArtifact(artifact: ArtifactRef) {\n if (artifact.path === undefined) {\n return {\n ok: false as const,\n error: {\n code: 'artifact-path-missing',\n expected: 'ArtifactRef.path to identify a readable .rhitape file',\n hint: 'Pass the path returned by the capture host together with its digest.',\n detail: { digest: artifact.digest },\n },\n };\n }\n try {\n return { ok: true as const, value: new Uint8Array(await readFile(artifact.path)) };\n } catch (cause) {\n return {\n ok: false as const,\n error: {\n code: 'artifact-read-failed',\n expected: 'the ArtifactRef path to be readable',\n hint: 'Check the tape path and recapture if the artifact was removed.',\n detail: {\n path: artifact.path,\n reason: cause instanceof Error ? cause.message : String(cause),\n },\n },\n };\n }\n },\n async createReplayBackend(tape: V7Tape) {\n let createDawn: (options: readonly string[]) => GPU;\n let gpuGlobals: Record<string, unknown>;\n try {\n const dawn = await import('webgpu');\n createDawn = dawn.create as (options: readonly string[]) => GPU;\n gpuGlobals = dawn.globals as Record<string, unknown>;\n } catch (cause) {\n return {\n ok: false as const,\n error: {\n code: 'replay-backend-unavailable',\n expected: 'the Dawn WebGPU provider to load',\n hint: 'Install the DevKit runtime closure and retry rhi.inspect.',\n detail: {\n stage: 'provider',\n cause: cause instanceof Error ? cause.message : String(cause),\n },\n },\n };\n }\n Object.assign(globalThis, gpuGlobals);\n const gpu = createDawn([]);\n if (!('navigator' in globalThis) || globalThis.navigator === undefined) {\n Object.defineProperty(globalThis, 'navigator', {\n value: {},\n configurable: true,\n writable: true,\n });\n }\n Object.defineProperty(globalThis.navigator, 'gpu', {\n value: gpu,\n configurable: true,\n writable: true,\n });\n const adapter = await rhi.requestAdapter();\n if (!adapter.ok) {\n return {\n ok: false as const,\n error: {\n code: 'replay-backend-unavailable',\n expected: 'a fresh Dawn WebGPU adapter',\n hint: adapter.error.hint,\n detail: { stage: 'adapter', cause: adapter.error.hint },\n },\n };\n }\n const device = await adapter.value.requestDevice(\n replayDeviceRequest(tape, adapter.value.features, adapter.value.limits),\n );\n if (!device.ok) {\n return {\n ok: false as const,\n error: {\n code: 'replay-backend-unavailable',\n expected: 'a fresh Dawn WebGPU device satisfying the recorded tape',\n hint: device.error.hint,\n detail: { stage: 'device', cause: device.error.hint },\n },\n };\n }\n return { ok: true as const, value: { device: device.value, createShaderModule } };\n },\n };\n}\n","import {\n buildFrameModel,\n decodeTape,\n type FrameModel,\n type InspectField,\n openReplay,\n type ReplayBackend,\n type RhiDebugError,\n type V7Tape,\n type WorkInspection,\n} from '@forgeax/engine-rhi-debug';\nimport { ok, type Result } from '@forgeax/engine-types';\nimport type { CommandError, CommandResult } from '../types.js';\n\nexport const RHI_TAPE_ARTIFACT_KIND = 'rhi-tape' as const;\n\nexport interface ArtifactRef {\n readonly kind: typeof RHI_TAPE_ARTIFACT_KIND;\n readonly digest: string;\n readonly source: string;\n readonly path?: string;\n}\n\nexport interface CapturedRhiTape extends ArtifactRef {\n readonly bytes: Uint8Array;\n}\n\nexport interface RhiCaptureFrameValue {\n readonly kind: typeof RHI_TAPE_ARTIFACT_KIND;\n readonly digest: string;\n readonly bytes: Uint8Array;\n readonly source?: string;\n readonly path?: string;\n}\n\nexport interface RhiCaptureInput {\n readonly signal?: AbortSignal;\n}\n\nexport interface RhiSummaryInput {\n readonly artifact: ArtifactRef;\n}\n\nexport interface RhiInspectInput {\n readonly artifact: ArtifactRef;\n readonly workIndex: number;\n readonly fields?: readonly InspectField[];\n}\n\nexport type RhiDebugOperationName = 'rhi.capture' | 'rhi.summary' | 'rhi.inspect';\n\nexport type RhiDebugOperationInput = RhiCaptureInput | RhiSummaryInput | RhiInspectInput;\n\nexport interface RhiSummaryOutput {\n readonly artifact: ArtifactRef;\n readonly model: FrameModel;\n}\n\nexport interface RhiInspectOutput {\n readonly artifact: ArtifactRef;\n readonly inspection: WorkInspection;\n}\n\nexport type RhiDebugOperationOutput = ArtifactRef | RhiSummaryOutput | RhiInspectOutput;\n\nexport interface RhiDebugOperationContext {\n readonly captureFrame: (\n input?: RhiCaptureInput,\n ) => Promise<Result<CapturedRhiTape, RhiDebugError>>;\n readonly readArtifact: (artifact: ArtifactRef) => Promise<CommandResult<Uint8Array>>;\n readonly createReplayBackend?: (tape: V7Tape) => Promise<CommandResult<ReplayBackend>>;\n}\n\nexport interface RhiDebugOperationHost {\n readonly captureFrame: (\n input?: RhiCaptureInput,\n ) => Promise<Result<RhiCaptureFrameValue, RhiDebugError>>;\n readonly readArtifact: (artifact: ArtifactRef) => Promise<CommandResult<Uint8Array>>;\n readonly createReplayBackend?: (tape: V7Tape) => Promise<CommandResult<ReplayBackend>>;\n}\n\nexport function createRhiDebugOperationContext(\n host: RhiDebugOperationHost,\n): RhiDebugOperationContext {\n return {\n async captureFrame(input) {\n const captured = await host.captureFrame(input);\n if (!captured.ok) return captured;\n return ok({\n kind: RHI_TAPE_ARTIFACT_KIND,\n digest: captured.value.digest,\n source: captured.value.source ?? 'rhi.capture',\n ...(captured.value.path === undefined ? {} : { path: captured.value.path }),\n bytes: captured.value.bytes,\n });\n },\n readArtifact: host.readArtifact,\n ...(host.createReplayBackend === undefined\n ? {}\n : { createReplayBackend: host.createReplayBackend }),\n };\n}\n\nexport interface JsonSchema {\n readonly type: 'object' | 'string' | 'integer' | 'array';\n readonly properties?: Readonly<Record<string, JsonSchema>>;\n readonly required?: readonly string[];\n readonly items?: JsonSchema;\n readonly enum?: readonly string[];\n readonly minimum?: number;\n readonly additionalProperties?: boolean;\n}\n\nexport interface RhiDebugOperationDescriptor {\n readonly name: RhiDebugOperationName;\n readonly summary: string;\n readonly inputSchema: JsonSchema;\n readonly outputSchema: JsonSchema;\n readonly recoveryCodes: readonly string[];\n}\n\nexport interface RhiDebugOperationManifest {\n readonly schemaVersion: '1.0.0';\n readonly artifactRefSchema: JsonSchema;\n readonly operations: readonly RhiDebugOperationDescriptor[];\n}\n\nconst artifactRefSchema: JsonSchema = {\n type: 'object',\n properties: {\n kind: { type: 'string', enum: [RHI_TAPE_ARTIFACT_KIND] },\n digest: { type: 'string' },\n source: { type: 'string' },\n path: { type: 'string' },\n },\n required: ['kind', 'digest', 'source'],\n additionalProperties: false,\n};\n\nconst summaryOutputSchema: JsonSchema = {\n type: 'object',\n properties: {\n artifact: artifactRefSchema,\n model: { type: 'object', additionalProperties: true },\n },\n required: ['artifact', 'model'],\n additionalProperties: false,\n};\n\nconst inspectOutputSchema: JsonSchema = {\n type: 'object',\n properties: {\n artifact: artifactRefSchema,\n inspection: { type: 'object', additionalProperties: true },\n },\n required: ['artifact', 'inspection'],\n additionalProperties: false,\n};\n\nexport const RHI_DEBUG_OPERATION_MANIFEST: RhiDebugOperationManifest = {\n schemaVersion: '1.0.0',\n artifactRefSchema,\n operations: [\n {\n name: 'rhi.capture',\n summary: 'Capture the next frame and return one rhi-tape ArtifactRef.',\n inputSchema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n outputSchema: artifactRefSchema,\n recoveryCodes: [\n 'capture-unavailable',\n 'capture-busy',\n 'capture-snapshot-failed',\n 'capture-timeout',\n ],\n },\n {\n name: 'rhi.summary',\n summary: 'Strictly decode one ArtifactRef and return its CPU FrameModel.',\n inputSchema: {\n type: 'object',\n properties: { artifact: artifactRefSchema },\n required: ['artifact'],\n additionalProperties: false,\n },\n outputSchema: summaryOutputSchema,\n recoveryCodes: ['tape-invalid', 'tape-version-unsupported'],\n },\n {\n name: 'rhi.inspect',\n summary: 'Replay one ArtifactRef on a fresh backend and inspect a workIndex.',\n inputSchema: {\n type: 'object',\n properties: {\n artifact: artifactRefSchema,\n workIndex: { type: 'integer', minimum: 0 },\n fields: {\n type: 'array',\n items: { type: 'string', enum: ['bindings', 'pipeline', 'pixels'] },\n },\n },\n required: ['artifact', 'workIndex'],\n additionalProperties: false,\n },\n outputSchema: inspectOutputSchema,\n recoveryCodes: [\n 'tape-invalid',\n 'tape-version-unsupported',\n 'replay-capability-mismatch',\n 'replay-event-failed',\n 'replay-position-invalid',\n 'readback-failed',\n 'readback-unsupported',\n ],\n },\n ],\n};\n\nexport function discoverRhiDebugOperations(): readonly RhiDebugOperationDescriptor[] {\n return RHI_DEBUG_OPERATION_MANIFEST.operations;\n}\n\nexport function renderRhiDebugHelp(): string {\n return [\n 'forgeax run <operation>',\n ...discoverRhiDebugOperations().map((operation) => ` ${operation.name}: ${operation.summary}`),\n 'Usage:',\n ' forgeax run rhi.summary --artifact PATH --digest SHA256 --json',\n ' forgeax run rhi.inspect --artifact PATH --digest SHA256 --work-index N --fields pipeline,bindings,pixels --json',\n 'ArtifactRef schema:',\n JSON.stringify(RHI_DEBUG_OPERATION_MANIFEST.artifactRefSchema),\n ].join('\\n');\n}\n\nexport function recoverRhiDebugError(error: RhiDebugError): string {\n switch (error.code) {\n case 'capture-unavailable':\n case 'capture-busy':\n case 'capture-snapshot-failed':\n case 'capture-timeout':\n return `${error.hint}: ${error.detail?.cause ?? 'capture failed'}`;\n case 'tape-invalid':\n return `${error.hint}: ${error.detail?.cause ?? 'tape validation failed'}`;\n case 'tape-version-unsupported':\n return `${error.hint}: found ${error.detail?.foundVersion}, expected ${error.detail?.expectedVersion}`;\n case 'replay-capability-mismatch':\n return `${error.hint}: ${error.detail?.cause ?? 'capability mismatch'}`;\n case 'replay-event-failed':\n return `${error.hint}: event ${error.detail?.eventIndex} ${error.detail?.kind} at ${error.detail?.stage}`;\n case 'replay-position-invalid':\n return `${error.hint}: requested ${error.detail?.requested}, available ${error.detail?.available}`;\n case 'readback-failed':\n return `${error.hint}: ${error.detail?.cause ?? 'readback failed'}`;\n case 'readback-unsupported':\n return `${error.hint}: ${error.detail?.reason ?? 'readback is unsupported'}`;\n }\n}\n\nfunction coreError(error: RhiDebugError): CommandError {\n return {\n code: error.code,\n expected: error.expected,\n hint: recoverRhiDebugError(error),\n detail: error.detail === undefined ? {} : Object.fromEntries(Object.entries(error.detail)),\n };\n}\n\nfunction operationError(\n code: string,\n expected: string,\n hint: string,\n detail: Readonly<Record<string, unknown>> = {},\n): CommandResult<never> {\n return { ok: false, error: { code, expected, hint, detail } };\n}\n\nfunction validateArtifactRef(\n value: unknown,\n):\n | { readonly ok: true; readonly value: ArtifactRef }\n | { readonly ok: false; readonly error: CommandError } {\n if (value === null || typeof value !== 'object') {\n return operationError(\n 'artifact-ref-invalid',\n 'an ArtifactRef object',\n 'Pass the ArtifactRef returned by rhi.capture unchanged.',\n );\n }\n const candidate = value as Record<string, unknown>;\n if (candidate.kind !== RHI_TAPE_ARTIFACT_KIND) {\n return operationError(\n 'artifact-kind-invalid',\n `ArtifactRef.kind to equal ${RHI_TAPE_ARTIFACT_KIND}`,\n 'Capture a new RHI tape and pass its ArtifactRef unchanged.',\n { kind: candidate.kind ?? null },\n );\n }\n if (typeof candidate.digest !== 'string' || candidate.digest.length === 0) {\n return operationError(\n 'artifact-digest-invalid',\n 'ArtifactRef.digest to be a non-empty digest',\n 'Use the digest returned with the captured tape.',\n );\n }\n if (typeof candidate.source !== 'string' || candidate.source.length === 0) {\n return operationError(\n 'artifact-source-invalid',\n 'ArtifactRef.source to identify the producing operation',\n 'Use the complete ArtifactRef returned by rhi.capture.',\n );\n }\n return {\n ok: true,\n value: {\n kind: RHI_TAPE_ARTIFACT_KIND,\n digest: candidate.digest,\n source: candidate.source,\n ...(typeof candidate.path === 'string' ? { path: candidate.path } : {}),\n },\n };\n}\n\nasync function readTape(\n artifact: ArtifactRef,\n context: RhiDebugOperationContext,\n): Promise<CommandResult<Uint8Array>> {\n const validated = validateArtifactRef(artifact);\n if (!validated.ok) return validated;\n return context.readArtifact(validated.value);\n}\n\nexport function runRhiDebugOperation(\n name: 'rhi.capture',\n input: RhiCaptureInput,\n context: RhiDebugOperationContext,\n): Promise<CommandResult<ArtifactRef>>;\nexport function runRhiDebugOperation(\n name: 'rhi.summary',\n input: RhiSummaryInput,\n context: RhiDebugOperationContext,\n): Promise<CommandResult<RhiSummaryOutput>>;\nexport function runRhiDebugOperation(\n name: 'rhi.inspect',\n input: RhiInspectInput,\n context: RhiDebugOperationContext,\n): Promise<CommandResult<RhiInspectOutput>>;\nexport function runRhiDebugOperation(\n name: RhiDebugOperationName,\n input: RhiDebugOperationInput,\n context: RhiDebugOperationContext,\n): Promise<CommandResult<RhiDebugOperationOutput>>;\nexport async function runRhiDebugOperation(\n name: RhiDebugOperationName,\n input: RhiDebugOperationInput,\n context: RhiDebugOperationContext,\n): Promise<CommandResult<RhiDebugOperationOutput>> {\n switch (name) {\n case 'rhi.capture': {\n const capture = await context.captureFrame(input as RhiCaptureInput);\n if (!capture.ok) return { ok: false, error: coreError(capture.error) };\n const artifact = validateArtifactRef(capture.value);\n if (!artifact.ok) return artifact;\n return { ok: true, value: artifact.value };\n }\n case 'rhi.summary': {\n const summaryInput = input as RhiSummaryInput;\n const bytes = await readTape(summaryInput.artifact, context);\n if (!bytes.ok) return bytes;\n const decoded = decodeTape(bytes.value);\n if (!decoded.ok) return { ok: false, error: coreError(decoded.error) };\n const artifact = validateArtifactRef(summaryInput.artifact);\n if (!artifact.ok) return artifact;\n return {\n ok: true,\n value: { artifact: artifact.value, model: buildFrameModel(decoded.value) },\n };\n }\n case 'rhi.inspect': {\n const inspectInput = input as RhiInspectInput;\n if (!Number.isInteger(inspectInput.workIndex) || inspectInput.workIndex < 0) {\n return operationError(\n 'work-index-invalid',\n 'workIndex to be a non-negative integer',\n 'Choose workIndex from the FrameModel returned by rhi.summary.',\n { workIndex: inspectInput.workIndex },\n );\n }\n const bytes = await readTape(inspectInput.artifact, context);\n if (!bytes.ok) return bytes;\n const decoded = decodeTape(bytes.value);\n if (!decoded.ok) return { ok: false, error: coreError(decoded.error) };\n if (context.createReplayBackend === undefined) {\n return operationError(\n 'replay-backend-unavailable',\n 'a fresh ReplayBackend factory',\n 'Provide a fresh device and shader factory before running rhi.inspect.',\n );\n }\n const backend = await context.createReplayBackend(decoded.value);\n if (!backend.ok) return backend;\n const opened = await openReplay(decoded.value, backend.value);\n if (!opened.ok) return { ok: false, error: coreError(opened.error) };\n try {\n const inspection = await opened.value.inspectWork(\n inspectInput.workIndex,\n inspectInput.fields,\n );\n if (!inspection.ok) return { ok: false, error: coreError(inspection.error) };\n const artifact = validateArtifactRef(inspectInput.artifact);\n if (!artifact.ok) return artifact;\n return { ok: true, value: { artifact: artifact.value, inspection: inspection.value } };\n } finally {\n await opened.value.dispose();\n }\n }\n }\n}\n","import { execFile } from 'node:child_process';\nimport { cp, mkdir, mkdtemp, readdir, readFile, rename, rm } from 'node:fs/promises';\nimport { basename, dirname, resolve } from 'node:path';\nimport { promisify } from 'node:util';\nimport { commandError } from './project.js';\nimport type { CommandResult } from './types.js';\n\nconst execFileAsync = promisify(execFile);\n\nexport interface SdkInstallOptions {\n readonly root: string;\n readonly version?: string;\n}\n\nasync function packageVersion(): Promise<string> {\n const manifest = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));\n if (typeof manifest.version !== 'string' || manifest.version.length === 0) {\n throw new Error('sdk-installer-version-missing');\n }\n return manifest.version;\n}\n\nexport async function sdkInstallCommand(\n options: SdkInstallOptions,\n): Promise<CommandResult<unknown>> {\n const root = resolve(options.root);\n let targetExists = true;\n let entries: string[];\n try {\n entries = await readdir(root);\n } catch (cause) {\n if (\n cause === null ||\n typeof cause !== 'object' ||\n !('code' in cause) ||\n cause.code !== 'ENOENT'\n ) {\n return { ok: false, error: commandError(cause, 'sdk-install-failed') };\n }\n targetExists = false;\n entries = [];\n }\n if (entries.length > 0) {\n return {\n ok: false,\n error: {\n code: 'sdk-target-not-empty',\n expected: 'the SDK install target to be absent or empty',\n hint: 'Choose an empty versioned SDK directory so existing files cannot be overwritten.',\n detail: { root },\n },\n };\n }\n\n const version = options.version ?? (await packageVersion());\n const parent = dirname(root);\n await mkdir(parent, { recursive: true });\n let staging: string | undefined;\n let download: string | undefined;\n try {\n staging = await mkdtemp(resolve(parent, `.${basename(root)}.forgeax-sdk-staging-`));\n download = await mkdtemp(resolve(parent, `.${basename(root)}.forgeax-sdk-download-`));\n await execFileAsync(\n process.env.FORGEAX_NPM_CLIENT ?? 'npm',\n [\n 'install',\n '--prefix',\n download,\n '--ignore-scripts',\n '--no-package-lock',\n '--no-save',\n '--fund=false',\n '--audit=false',\n `@forgeax/engine-sdk@${version}`,\n ],\n { env: { ...process.env, CI: 'true' }, maxBuffer: 16 * 1024 * 1024 },\n );\n const carrier = resolve(download, 'node_modules', '@forgeax', 'engine-sdk', 'sdk');\n const manifest = JSON.parse(await readFile(resolve(carrier, 'sdk-manifest.json'), 'utf8'));\n if (manifest.sdkVersion !== version) throw new Error('sdk-carrier-version-mismatch');\n for (const name of await readdir(carrier)) {\n await cp(resolve(carrier, name), resolve(staging, name), {\n recursive: true,\n errorOnExist: true,\n force: false,\n });\n }\n if (!targetExists) {\n await rename(staging, root);\n staging = undefined;\n } else {\n for (const name of await readdir(staging)) {\n await rename(resolve(staging, name), resolve(root, name));\n }\n }\n return {\n ok: true,\n value: {\n root,\n sdkVersion: version,\n source: '@forgeax/engine-sdk',\n next: { cwd: root, argv: ['node', './bin/forgeax.mjs', 'init'] },\n },\n };\n } catch (cause) {\n return { ok: false, error: commandError(cause, 'sdk-install-failed') };\n } finally {\n if (staging !== undefined) await rm(staging, { recursive: true, force: true });\n if (download !== undefined) await rm(download, { recursive: true, force: true });\n }\n}\n","import { mkdtemp, readFile, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { resolve } from 'node:path';\nimport { build as viteBuild } from 'vite';\nimport { createViteConfig } from './host.js';\nimport { commandError, readProjectFacts } from './project.js';\nimport type { CommandResult, ShaderCheckOptions } from './types.js';\n\nexport async function shaderCheckCommand(\n options: ShaderCheckOptions = {},\n): Promise<CommandResult<unknown>> {\n const facts = await readProjectFacts(options.root);\n if (!facts.ok) return facts;\n const target = options.path === undefined ? undefined : resolve(facts.value.root, options.path);\n if (target !== undefined) {\n try {\n await readFile(target);\n } catch (cause) {\n return { ok: false, error: commandError(cause, 'shader-source-unreadable') };\n }\n }\n const temporary = await mkdtemp(resolve(tmpdir(), 'forgeax-shader-check-'));\n const previous = process.cwd();\n try {\n process.chdir(facts.value.root);\n const config = await createViteConfig(facts.value, 'build');\n await viteBuild({\n ...config,\n build: { ...config.build, outDir: temporary, emptyOutDir: true, write: true },\n });\n return { ok: true, value: { root: facts.value.root, path: target ?? null } };\n } catch (cause) {\n return { ok: false, error: commandError(cause, 'shader-check-failed') };\n } finally {\n process.chdir(previous);\n await rm(temporary, { recursive: true, force: true });\n }\n}\n","import { type ChildProcess, spawn } from 'node:child_process';\nimport { createHash, randomUUID } from 'node:crypto';\nimport { access, mkdir, stat, writeFile } from 'node:fs/promises';\nimport { createServer as createNetServer } from 'node:net';\nimport { dirname, resolve } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { FORGEAX_FRAME_SUBMITTED_DATASET } from '@forgeax/engine-app';\nimport { parseImage } from '@forgeax/engine-image/parse-image';\nimport { type Browser, chromium, type Page, type Request, type Response } from 'playwright';\nimport type { ViteDevServer } from 'vite';\nimport { createViteConfig } from './host.js';\nimport { commandError, readProjectFacts } from './project.js';\nimport type {\n BrowserCaptureOptions,\n CaptureBackend,\n CommandError,\n CommandResult,\n SoftwareCaptureOptions,\n} from './types.js';\n\ninterface VirtualDisplay {\n readonly value?: string;\n close(): Promise<void>;\n}\n\nexport interface CapturePixelWitness {\n readonly width: number;\n readonly height: number;\n readonly sampledPixels: number;\n readonly lumaMin: number;\n readonly lumaMax: number;\n readonly lumaRange: number;\n readonly varyingPixels: number;\n readonly rendered: boolean;\n}\n\nexport interface SoftwareCaptureRuntimeWitness {\n readonly title: string;\n readonly canvas: { readonly width: number; readonly height: number } | null;\n readonly domUi: {\n readonly rootChildren: number;\n readonly openShadowRoots: number;\n readonly textWitness: string;\n };\n readonly adapter: Readonly<Record<string, unknown>> | null;\n readonly adapterError: string | null;\n readonly engineFrameId: number | null;\n readonly captureReady: string | null;\n readonly singleHtml: {\n readonly ready: boolean;\n readonly resourceHits: number;\n readonly resourceMisses: readonly Readonly<Record<string, unknown>>[];\n readonly externalRequests: readonly Readonly<Record<string, unknown>>[];\n } | null;\n readonly userAgent: string;\n}\n\nexport interface SoftwareCaptureRequestWitness {\n readonly url: string;\n readonly resourceType: string;\n readonly status: number | null;\n readonly failed: boolean;\n readonly failure: string | null;\n readonly resourceMiss: boolean;\n}\n\nexport interface SoftwareCaptureRequestReport {\n readonly documents: number;\n readonly http: number;\n readonly https: number;\n readonly failed: number;\n readonly resourceMisses: number;\n readonly entries: readonly SoftwareCaptureRequestWitness[];\n}\n\nexport interface SoftwareCaptureRecord {\n readonly index: number;\n readonly checkpoint: string | null;\n readonly ok: boolean;\n readonly output: string;\n readonly digest: string;\n readonly pixels: CapturePixelWitness;\n readonly runtime: SoftwareCaptureRuntimeWitness;\n}\n\nexport interface SoftwareCaptureRunReport {\n readonly schemaVersion: '2.0.0';\n readonly runId: string;\n readonly ok: boolean;\n readonly mode: 'browser-compositor' | 'advanced-cpu-only-development';\n readonly root: string;\n readonly url: string;\n readonly target: BrowserCaptureTarget;\n readonly launchProfile: BrowserLaunchProfile;\n readonly report: string;\n readonly backendRequested: CaptureBackend;\n readonly backend: 'software' | 'hardware' | 'unknown';\n /** @deprecated Read `backendRequested` instead. */\n readonly softwareRequested: boolean;\n readonly deterministicRequested: boolean;\n readonly viewport: {\n readonly width: number;\n readonly height: number;\n readonly deviceScaleFactor: 1;\n readonly colorProfile: 'srgb';\n readonly colorScheme: 'light';\n readonly locale: 'en-US';\n readonly timezone: 'UTC';\n };\n readonly browser: { readonly version: string; readonly executable: string };\n readonly display: string | null;\n readonly lavapipeIcd: string | null;\n readonly captures: readonly SoftwareCaptureRecord[];\n readonly requests: SoftwareCaptureRequestReport;\n readonly singleHtml: SoftwareCaptureRuntimeWitness['singleHtml'];\n readonly consoleErrors: readonly string[];\n readonly pageErrors: readonly string[];\n readonly closedAt?: string;\n readonly boundary: string;\n}\n\nexport type BrowserCaptureTarget =\n | { readonly kind: 'project' }\n | { readonly kind: 'single-html'; readonly path: string };\n\nexport type BrowserLaunchProfile = 'development' | 'release';\n\nexport interface SoftwareBrowserOpenOptions {\n /** `auto` preserves the host/browser lane; the other values are assertions. */\n readonly backend?: CaptureBackend;\n /** @deprecated Use `backend: 'software'`. */\n readonly software?: boolean;\n readonly browser?: string;\n readonly width?: number;\n readonly height?: number;\n readonly port?: number;\n readonly requireUi?: boolean;\n readonly deterministic?: boolean;\n readonly outputDir?: string;\n readonly report?: string;\n readonly runId?: string;\n readonly headless?: boolean;\n readonly target?: BrowserCaptureTarget;\n /** Release omits unsafe WebGPU/file-access flags; development preserves the legacy lane. */\n readonly launchProfile?: BrowserLaunchProfile;\n}\n\nexport interface SoftwareCaptureCheckpointOptions {\n readonly output?: string;\n readonly waitMs?: number;\n readonly requireUi?: boolean;\n}\n\nexport interface SoftwareBrowserSession {\n readonly page: Page;\n readonly url: string;\n readonly reportPath: string;\n capture(\n checkpoint?: string,\n options?: SoftwareCaptureCheckpointOptions,\n ): Promise<SoftwareCaptureRecord>;\n report(): SoftwareCaptureRunReport;\n close(): Promise<void>;\n}\n\nexport interface SoftwareBrowser {\n open(options: SoftwareBrowserOpenOptions): Promise<SoftwareBrowserSession>;\n close(): Promise<void>;\n}\n\n/** General browser-compositor capture surface. */\nexport type BrowserCaptureRuntimeWitness = SoftwareCaptureRuntimeWitness;\nexport type BrowserCaptureRecord = SoftwareCaptureRecord;\nexport type BrowserCaptureRunReport = SoftwareCaptureRunReport;\nexport type BrowserCaptureRequestWitness = SoftwareCaptureRequestWitness;\nexport type BrowserCaptureRequestReport = SoftwareCaptureRequestReport;\nexport type BrowserCaptureOpenOptions = SoftwareBrowserOpenOptions;\nexport type BrowserCaptureCheckpointOptions = SoftwareCaptureCheckpointOptions;\nexport type BrowserCaptureSession = SoftwareBrowserSession;\nexport type BrowserCapture = SoftwareBrowser;\n\nclass SoftwareCaptureError extends Error implements CommandError {\n constructor(\n readonly code: string,\n readonly expected: string,\n readonly hint: string,\n readonly detail: Readonly<Record<string, unknown>>,\n ) {\n super(`${code}: ${hint}`);\n this.name = 'SoftwareCaptureError';\n }\n}\n\nfunction fail(\n code: string,\n expected: string,\n hint: string,\n detail: Readonly<Record<string, unknown>> = {},\n): never {\n throw new SoftwareCaptureError(code, expected, hint, detail);\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function reservePort(): Promise<number> {\n const reservation = createNetServer();\n await new Promise<void>((resolveListen, rejectListen) => {\n reservation.once('error', rejectListen);\n reservation.listen(0, '127.0.0.1', resolveListen);\n });\n const address = reservation.address();\n const port = typeof address === 'object' && address !== null ? address.port : 0;\n await new Promise<void>((resolveClose, rejectClose) => {\n reservation.close((error) => (error === undefined ? resolveClose() : rejectClose(error)));\n });\n if (port === 0) throw new Error('OS did not assign an ephemeral capture port');\n return port;\n}\n\nasync function stopProcess(child: ChildProcess): Promise<void> {\n if (child.exitCode !== null || child.signalCode !== null) return;\n await new Promise<void>((resolveStop) => {\n const timeout = setTimeout(() => {\n child.kill('SIGKILL');\n resolveStop();\n }, 2_000);\n child.once('exit', () => {\n clearTimeout(timeout);\n resolveStop();\n });\n child.kill('SIGTERM');\n });\n}\n\nasync function startVirtualDisplay(width: number, height: number): Promise<VirtualDisplay> {\n if (process.platform !== 'linux' || process.env.DISPLAY !== undefined) {\n return {\n ...(process.env.DISPLAY === undefined ? {} : { value: process.env.DISPLAY }),\n async close() {},\n };\n }\n for (let offset = 0; offset < 100; offset += 1) {\n const number = 90 + ((process.pid + offset) % 100);\n const socket = `/tmp/.X11-unix/X${number}`;\n const lock = `/tmp/.X${number}-lock`;\n if ((await pathExists(socket)) || (await pathExists(lock))) continue;\n const display = `:${number}`;\n const child = spawn(\n 'Xvfb',\n [display, '-screen', '0', `${width}x${height}x24`, '-nolisten', 'tcp'],\n { stdio: ['ignore', 'ignore', 'pipe'] },\n );\n let diagnostic = '';\n child.stderr?.setEncoding('utf8');\n child.stderr?.on('data', (chunk: string) => {\n diagnostic += chunk;\n });\n try {\n await new Promise<void>((resolveReady, rejectReady) => {\n const timeout = setTimeout(\n () => rejectReady(new Error(`Xvfb did not create ${socket}: ${diagnostic.trim()}`)),\n 5_000,\n );\n const poll = setInterval(() => {\n void pathExists(socket).then((exists) => {\n if (!exists) return;\n clearTimeout(timeout);\n clearInterval(poll);\n resolveReady();\n });\n }, 50);\n child.once('error', (error) => {\n clearTimeout(timeout);\n clearInterval(poll);\n rejectReady(error);\n });\n child.once('exit', (code, signal) => {\n clearTimeout(timeout);\n clearInterval(poll);\n rejectReady(\n new Error(`Xvfb exited before ready (${code ?? signal}): ${diagnostic.trim()}`),\n );\n });\n });\n return { value: display, close: () => stopProcess(child) };\n } catch (cause) {\n await stopProcess(child);\n throw cause;\n }\n }\n throw new Error('no free X11 display number was available for browser capture');\n}\n\nasync function lavapipeIcd(): Promise<string | undefined> {\n for (const candidate of [\n '/usr/share/vulkan/icd.d/lvp_icd.x86_64.json',\n '/usr/share/vulkan/icd.d/lvp_icd.aarch64.json',\n ]) {\n if (await pathExists(candidate)) return candidate;\n }\n return undefined;\n}\n\nfunction evidencePath(output: string): string {\n return output.toLowerCase().endsWith('.png') ? `${output.slice(0, -4)}.json` : `${output}.json`;\n}\n\nfunction newRunId(): string {\n return `${new Date().toISOString().replace(/[:.]/g, '-')}-${randomUUID().slice(0, 8)}`;\n}\n\nfunction checkpointSlug(checkpoint: string | undefined): string {\n const value = (checkpoint ?? 'capture')\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 80);\n return value.length === 0 ? 'capture' : value;\n}\n\nfunction captureDigest(bytes: Uint8Array): string {\n return `sha256:${createHash('sha256').update(bytes).digest('hex')}`;\n}\n\ntype CaptureBackendObserved = 'software' | 'hardware' | 'unknown';\n\nfunction observedBackend(runtime: SoftwareCaptureRuntimeWitness): CaptureBackendObserved {\n if (runtime.adapter === null) return 'unknown';\n return isSoftwareAdapter(runtime) ? 'software' : 'hardware';\n}\n\nasync function resolveBrowserExecutable(\n requested: string | undefined,\n): Promise<string | undefined> {\n if (requested !== undefined && requested.length > 0) {\n return (await pathExists(requested)) ? requested : undefined;\n }\n const candidates = [\n process.env.FORGEAX_BROWSER_EXECUTABLE,\n '/opt/google/chrome-beta/chrome',\n '/usr/bin/google-chrome',\n '/usr/bin/google-chrome-stable',\n '/usr/bin/chromium',\n '/usr/bin/chromium-browser',\n typeof chromium.executablePath === 'function' ? chromium.executablePath() : undefined,\n ].filter((candidate): candidate is string => candidate !== undefined && candidate.length > 0);\n for (const candidate of candidates) {\n if (await pathExists(candidate)) return candidate;\n }\n // Playwright can supply a managed browser when its browser cache is present.\n // Leave executablePath unset so the caller receives Playwright's own diagnostic\n // rather than a misleading Chrome-Beta-only error.\n return undefined;\n}\n\nfunction browserLaunchArgs(backend: CaptureBackend, profile: BrowserLaunchProfile): string[] {\n const common = ['--force-color-profile=srgb', '--force-device-scale-factor=1'];\n if (profile === 'development') {\n common.unshift(\n '--enable-unsafe-webgpu',\n '--ignore-gpu-blocklist',\n '--disable-gpu-driver-bug-workarounds',\n );\n }\n if (backend !== 'software') return common;\n return [\n ...common,\n '--enable-features=Vulkan',\n '--use-vulkan=swiftshader',\n '--use-angle=swiftshader',\n '--disable-vulkan-surface',\n ];\n}\n\nexport function summarizeCapturePixels(\n rgba: Uint8Array,\n width: number,\n height: number,\n): CapturePixelWitness {\n const pixelCount = width * height;\n const stride = Math.max(1, Math.floor(pixelCount / 4096));\n const histogram = new Uint32Array(16);\n let lumaMin = 255;\n let lumaMax = 0;\n let sampledPixels = 0;\n for (let pixel = 0; pixel < pixelCount; pixel += stride) {\n const offset = pixel * 4;\n const red = rgba[offset];\n const green = rgba[offset + 1];\n const blue = rgba[offset + 2];\n if (red === undefined || green === undefined || blue === undefined) break;\n const luma = Math.round((54 * red + 183 * green + 19 * blue) / 256);\n lumaMin = Math.min(lumaMin, luma);\n lumaMax = Math.max(lumaMax, luma);\n const bucket = Math.min(15, Math.floor(luma / 16));\n histogram[bucket] = (histogram[bucket] ?? 0) + 1;\n sampledPixels += 1;\n }\n const dominantPixels = histogram.reduce((largest, count) => Math.max(largest, count), 0);\n const varyingPixels = sampledPixels - dominantPixels;\n const lumaRange = lumaMax - lumaMin;\n const requiredVariation = Math.min(sampledPixels, Math.max(8, Math.ceil(sampledPixels * 0.002)));\n return {\n width,\n height,\n sampledPixels,\n lumaMin,\n lumaMax,\n lumaRange,\n varyingPixels,\n rendered: lumaRange >= 8 && varyingPixels >= requiredVariation,\n };\n}\n\nfunction inspectCapturePng(png: Uint8Array): CapturePixelWitness {\n const decoded = parseImage(png, 'image/png', { mipmap: false });\n if (!decoded.ok) throw decoded.error;\n return summarizeCapturePixels(decoded.value.bytes, decoded.value.width, decoded.value.height);\n}\n\nasync function screenshotWithWitness(\n page: Page,\n): Promise<{ readonly png: Uint8Array; readonly pixels: CapturePixelWitness }> {\n const canvasPng = await page.locator('canvas').first().screenshot({\n type: 'png',\n style: '* { visibility: hidden !important; } canvas { visibility: visible !important; }',\n });\n const png = await page.screenshot({ type: 'png', caret: 'hide' });\n return { png, pixels: inspectCapturePng(canvasPng) };\n}\n\nasync function waitForCompositor(page: Page): Promise<void> {\n await page.evaluate(async () => {\n await document.fonts.ready;\n await new Promise<void>((resolveFrame) => requestAnimationFrame(() => resolveFrame()));\n await new Promise<void>((resolveFrame) => requestAnimationFrame(() => resolveFrame()));\n });\n}\n\nasync function runtimeWitness(page: Page): Promise<SoftwareCaptureRuntimeWitness> {\n return page.evaluate(async (datasetKey) => {\n const canvas = document.querySelector('canvas');\n const uiRoot = document.querySelector('#game-ui');\n const shadowHosts = [...(uiRoot?.querySelectorAll('*') ?? [])].filter(\n (element) => element.shadowRoot?.childElementCount !== 0,\n );\n let adapter: Readonly<Record<string, unknown>> | null = null;\n let adapterError: string | null = null;\n try {\n const gpuAdapter = await navigator.gpu?.requestAdapter();\n if (gpuAdapter === null || gpuAdapter === undefined) {\n adapterError = 'navigator.gpu.requestAdapter() returned null';\n } else {\n const info = gpuAdapter.info;\n adapter = {\n vendor: info.vendor,\n architecture: info.architecture,\n device: info.device,\n description: info.description,\n };\n }\n } catch (cause) {\n adapterError = String(cause);\n }\n const frameId = Number(document.documentElement.dataset[datasetKey]);\n const singleHtmlState = (\n globalThis as typeof globalThis & {\n __forgeaxSingleHtml?: {\n witness?: () => {\n ready: boolean;\n resourceHits: number;\n resourceMisses: readonly Readonly<Record<string, unknown>>[];\n externalRequests: readonly Readonly<Record<string, unknown>>[];\n };\n };\n }\n ).__forgeaxSingleHtml;\n return {\n title: document.title,\n canvas:\n canvas instanceof HTMLCanvasElement ? { width: canvas.width, height: canvas.height } : null,\n domUi: {\n rootChildren: uiRoot?.childElementCount ?? 0,\n openShadowRoots: shadowHosts.length,\n textWitness: shadowHosts\n .map((host) => host.shadowRoot?.textContent?.replace(/\\s+/g, ' ').trim() ?? '')\n .filter((text) => text.length > 0)\n .join(' | ')\n .slice(0, 500),\n },\n adapter,\n adapterError,\n engineFrameId: Number.isSafeInteger(frameId) && frameId > 0 ? frameId : null,\n captureReady: document.documentElement.dataset.forgeaxCaptureReady ?? null,\n singleHtml: singleHtmlState?.witness?.() ?? null,\n userAgent: navigator.userAgent,\n };\n }, FORGEAX_FRAME_SUBMITTED_DATASET);\n}\n\nfunction isSoftwareAdapter(runtime: SoftwareCaptureRuntimeWitness): boolean {\n const witness = Object.values(runtime.adapter ?? {})\n .map((value) => String(value).toLowerCase())\n .join(' ');\n return ['swiftshader', 'llvmpipe', 'lavapipe', 'software'].some((token) =>\n witness.includes(token),\n );\n}\n\nasync function writeRunReport(report: SoftwareCaptureRunReport): Promise<void> {\n await mkdir(dirname(report.report), { recursive: true });\n await writeFile(report.report, `${JSON.stringify(report, null, 2)}\\n`, 'utf8');\n}\n\ninterface MutableRequestWitness extends SoftwareCaptureRequestWitness {\n status: number | null;\n failed: boolean;\n failure: string | null;\n resourceMiss: boolean;\n}\n\nfunction requestProtocol(url: string): string | undefined {\n try {\n return new URL(url).protocol;\n } catch {\n return undefined;\n }\n}\n\nfunction requestRecord(\n request: Request,\n target: BrowserCaptureTarget,\n candidateUrl: string,\n): MutableRequestWitness {\n const url = request.url();\n const protocol = requestProtocol(url);\n const requestDocument = url.split(/[?#]/, 1)[0];\n const candidateDocument = candidateUrl.split(/[?#]/, 1)[0];\n return {\n url,\n resourceType: request.resourceType(),\n status: null,\n failed: false,\n failure: null,\n resourceMiss:\n target.kind === 'single-html' &&\n protocol === 'file:' &&\n requestDocument !== candidateDocument,\n };\n}\n\nfunction summarizeRequests(\n records: readonly MutableRequestWitness[],\n): SoftwareCaptureRequestReport {\n return {\n documents: records.filter((record) => record.resourceType === 'document').length,\n http: records.filter((record) => requestProtocol(record.url) === 'http:').length,\n https: records.filter((record) => requestProtocol(record.url) === 'https:').length,\n failed: records.filter((record) => record.failed).length,\n resourceMisses: records.filter((record) => record.resourceMiss).length,\n entries: records.map((record) => ({ ...record })),\n };\n}\n\nfunction singleHtmlRuntimeClean(\n target: BrowserCaptureTarget,\n runtime: SoftwareCaptureRuntimeWitness | null,\n requests: SoftwareCaptureRequestReport,\n): boolean {\n if (target.kind !== 'single-html') return true;\n const singleHtml = runtime?.singleHtml;\n return (\n singleHtml?.ready === true &&\n singleHtml.resourceMisses.length === 0 &&\n singleHtml.externalRequests.length === 0 &&\n requests.http === 0 &&\n requests.https === 0 &&\n requests.failed === 0 &&\n requests.resourceMisses === 0\n );\n}\n\nfunction markResponse(\n records: ReadonlyMap<Request, MutableRequestWitness>,\n response: Response,\n): void {\n const record = records.get(response.request());\n if (record === undefined) return;\n record.status = response.status();\n if (record.status >= 400) record.resourceMiss = true;\n}\n\nfunction markFailed(records: ReadonlyMap<Request, MutableRequestWitness>, request: Request): void {\n const record = records.get(request);\n if (record === undefined) return;\n record.failed = true;\n record.failure = request.failure()?.errorText ?? 'request failed';\n record.resourceMiss = true;\n}\n\nasync function openBrowserCaptureSession(\n root: string,\n options: BrowserCaptureOpenOptions,\n): Promise<BrowserCaptureSession> {\n const backend: CaptureBackend =\n options.backend ?? (options.software === true ? 'software' : 'auto');\n const launchProfile = options.launchProfile ?? 'development';\n const requestedTarget = options.target ?? { kind: 'project' as const };\n const target: BrowserCaptureTarget =\n requestedTarget.kind === 'single-html'\n ? { kind: 'single-html', path: resolve(requestedTarget.path) }\n : { kind: 'project' };\n if (target.kind === 'single-html') {\n if (!target.path.toLowerCase().endsWith('.html')) {\n fail(\n 'browser-capture-target-invalid',\n 'single-html target path to end with .html',\n 'Pass the exact forgeax package --format single-html candidate.',\n { path: target.path },\n );\n }\n try {\n const info = await stat(target.path);\n if (!info.isFile()) throw new Error('target is not a regular file');\n } catch (cause) {\n fail(\n 'browser-capture-target-missing',\n 'single-html target path to exist',\n 'Package the game first, then pass its candidate HTML path.',\n { path: target.path, reason: cause instanceof Error ? cause.message : String(cause) },\n );\n }\n }\n if (\n options.software === true &&\n options.backend !== undefined &&\n options.backend !== 'software'\n ) {\n fail(\n 'browser-capture-option-conflict',\n 'software and backend options to describe the same capture lane',\n 'Use either software: true or backend: software; use backend: auto for a portable capture.',\n { software: options.software, backend: options.backend },\n );\n }\n const facts = await readProjectFacts(root);\n if (!facts.ok) {\n throw new SoftwareCaptureError(\n facts.error.code,\n facts.error.expected,\n facts.error.hint,\n facts.error.detail,\n );\n }\n const width = options.width ?? 1280;\n const height = options.height ?? 720;\n const browserPath = await resolveBrowserExecutable(options.browser);\n if (options.browser !== undefined && browserPath === undefined) {\n fail(\n 'browser-capture-browser-missing',\n `a runnable browser at ${options.browser}`,\n 'Install Chrome/Chromium or pass --browser with an executable path.',\n { browser: options.browser },\n );\n }\n\n const id = options.runId ?? newRunId();\n const outputDirectory = resolve(\n facts.value.root,\n options.outputDir ?? `artifacts/playthrough/${id}`,\n );\n const reportPath = resolve(\n facts.value.root,\n options.report ?? resolve(outputDirectory, 'run.json'),\n );\n const port =\n target.kind === 'project'\n ? options.port === undefined || options.port === 0\n ? await reservePort()\n : options.port\n : undefined;\n let server: ViteDevServer | undefined;\n let browser: Browser | undefined;\n let page: Page | undefined;\n let display: VirtualDisplay | undefined;\n try {\n if (target.kind === 'project') {\n const { createServer } = await import('vite');\n if (port === undefined) throw new Error('project capture did not reserve a port');\n server = await createServer(\n await createViteConfig(facts.value, 'serve', '/', {\n server: { port, strictPort: true },\n }),\n );\n await server.listen(port);\n }\n display = await startVirtualDisplay(width, height);\n const captureDisplay = display;\n const icd = await lavapipeIcd();\n const consoleErrors: string[] = [];\n const pageErrors: string[] = [];\n const requestRecords: MutableRequestWitness[] = [];\n const requestByObject = new Map<Request, MutableRequestWitness>();\n const hasDisplay = display.value !== undefined;\n const headless = options.headless ?? (!hasDisplay && process.platform !== 'linux');\n const baseUrl =\n target.kind === 'project'\n ? new URL(server?.resolvedUrls?.local[0] ?? `http://127.0.0.1:${port ?? 0}/`)\n : undefined;\n const openPage = async (\n launchBackend: CaptureBackend,\n ): Promise<SoftwareCaptureRuntimeWitness> => {\n const browserEnvironment: Record<string, string> = {\n ...Object.fromEntries(\n Object.entries(process.env).filter(\n (entry): entry is [string, string] => entry[1] !== undefined,\n ),\n ),\n ...(launchBackend === 'software' ? { LIBGL_ALWAYS_SOFTWARE: '1' } : {}),\n ...(captureDisplay.value === undefined ? {} : { DISPLAY: captureDisplay.value }),\n };\n const launchOptions = {\n headless,\n env: browserEnvironment,\n args: browserLaunchArgs(launchBackend, launchProfile),\n ...(browserPath === undefined ? {} : { executablePath: browserPath }),\n };\n browser = await chromium.launch(launchOptions);\n page = await browser.newPage({\n viewport: { width, height },\n screen: { width, height },\n deviceScaleFactor: 1,\n colorScheme: 'light',\n locale: 'en-US',\n timezoneId: 'UTC',\n serviceWorkers: 'block',\n });\n page.on('console', (message) => {\n if (message.type() === 'error') consoleErrors.push(message.text());\n });\n page.on('pageerror', (error) => pageErrors.push(String(error)));\n const captureUrl =\n target.kind === 'single-html'\n ? new URL(pathToFileURL(target.path).href)\n : new URL(baseUrl?.href ?? 'http://127.0.0.1/');\n page.on('request', (request) => {\n const record = requestRecord(request, target, captureUrl.href);\n requestRecords.push(record);\n requestByObject.set(request, record);\n });\n page.on('response', (response) => markResponse(requestByObject, response));\n page.on('requestfailed', (request) => markFailed(requestByObject, request));\n if (options.deterministic === true) captureUrl.searchParams.set('forgeaxCapture', '1');\n await page.goto(captureUrl.href, { waitUntil: 'domcontentloaded', timeout: 120_000 });\n await page.waitForFunction(\n (requireUi) => {\n const canvas = document.querySelector('canvas');\n if (!(canvas instanceof HTMLCanvasElement) || canvas.width <= 0 || canvas.height <= 0)\n return false;\n if (!requireUi) return true;\n const uiRoot = document.querySelector('#game-ui');\n return uiRoot !== null && uiRoot.childElementCount > 0;\n },\n options.requireUi === true,\n { timeout: 120_000 },\n );\n return runtimeWitness(page);\n };\n\n // Auto first preserves a physical adapter. If WebGPU is unavailable, retry\n // once through the same explicit software lane used by CPU-only hosts. This\n // keeps the public capture contract portable without masking a flat frame.\n const initialLaunchBackend: CaptureBackend = backend === 'software' ? 'software' : 'hardware';\n let runtime = await openPage(initialLaunchBackend);\n let observed = observedBackend(runtime);\n if (backend === 'auto' && runtime.adapter === null) {\n await browser?.close();\n browser = undefined;\n page = undefined;\n consoleErrors.length = 0;\n pageErrors.length = 0;\n requestRecords.length = 0;\n requestByObject.clear();\n runtime = await openPage('software');\n observed = observedBackend(runtime);\n }\n const captureUrl =\n target.kind === 'single-html'\n ? new URL(pathToFileURL(target.path).href)\n : new URL(baseUrl?.href ?? 'http://127.0.0.1/');\n if (options.deterministic === true) captureUrl.searchParams.set('forgeaxCapture', '1');\n if (page === undefined || browser === undefined) {\n fail(\n 'browser-capture-browser-unavailable',\n 'the browser capture session to open',\n 'Inspect the browser launch diagnostic and retry with --browser or --headless.',\n );\n }\n\n const captures: SoftwareCaptureRecord[] = [];\n let latestRuntime: SoftwareCaptureRuntimeWitness | null = runtime;\n let closed = false;\n const report: SoftwareCaptureRunReport = {\n schemaVersion: '2.0.0',\n runId: id,\n ok: false,\n mode: 'browser-compositor',\n root: facts.value.root,\n url: captureUrl.href,\n target,\n launchProfile,\n report: reportPath,\n backendRequested: backend,\n backend: observed,\n softwareRequested: backend === 'software',\n deterministicRequested: options.deterministic === true,\n viewport: {\n width,\n height,\n deviceScaleFactor: 1,\n colorProfile: 'srgb',\n colorScheme: 'light',\n locale: 'en-US',\n timezone: 'UTC',\n },\n browser: { version: browser.version(), executable: browserPath ?? 'playwright-managed' },\n display: display.value ?? null,\n lavapipeIcd: icd ?? null,\n captures,\n requests: summarizeRequests(requestRecords),\n singleHtml: runtime.singleHtml,\n consoleErrors,\n pageErrors,\n boundary:\n 'Browser-compositor capture is visual iteration evidence, not physical-GPU performance, HDR-display output, or release acceptance.',\n };\n await writeRunReport(report);\n\n const updateReport = async (): Promise<void> => {\n const requests = summarizeRequests(requestRecords);\n Object.assign(report, {\n requests,\n singleHtml: latestRuntime?.singleHtml ?? null,\n ok:\n captures.length > 0 &&\n captures.every((capture) => capture.ok) &&\n consoleErrors.length === 0 &&\n pageErrors.length === 0 &&\n singleHtmlRuntimeClean(target, latestRuntime, requests),\n });\n await writeRunReport(report);\n };\n const close = async (): Promise<void> => {\n if (closed) return;\n closed = true;\n await Promise.allSettled([browser?.close(), display?.close(), server?.close()]);\n Object.assign(report, { closedAt: new Date().toISOString() });\n await updateReport();\n };\n\n return {\n page,\n url: captureUrl.href,\n reportPath,\n async capture(checkpoint, captureOptions = {}) {\n if (closed) {\n fail(\n 'browser-capture-session-closed',\n 'capture to run inside an open browser session',\n 'Open one session, complete all checkpoints, then close it.',\n { report: reportPath },\n );\n }\n const activePage = page;\n if (activePage === undefined) {\n fail(\n 'browser-capture-browser-unavailable',\n 'an open Playwright page',\n 'Inspect the browser launch diagnostic and retry the capture.',\n );\n }\n const expectedReady = checkpoint ?? (options.deterministic === true ? 'true' : undefined);\n await activePage.waitForFunction(\n ({ datasetKey }) => Number(document.documentElement.dataset[datasetKey]) > 0,\n { datasetKey: FORGEAX_FRAME_SUBMITTED_DATASET },\n { timeout: 120_000 },\n );\n if (expectedReady !== undefined) {\n await activePage.waitForFunction(\n (expected) => document.documentElement.dataset.forgeaxCaptureReady === expected,\n expectedReady,\n { timeout: 120_000 },\n );\n }\n await waitForCompositor(activePage);\n let captured = await screenshotWithWitness(activePage);\n const deadline = Date.now() + 120_000;\n while (!captured.pixels.rendered && Date.now() < deadline) {\n await activePage.waitForTimeout(500);\n await waitForCompositor(activePage);\n captured = await screenshotWithWitness(activePage);\n }\n const waitMs = captureOptions.waitMs ?? 0;\n if (waitMs > 0) {\n await activePage.waitForTimeout(waitMs);\n await waitForCompositor(activePage);\n captured = await screenshotWithWitness(activePage);\n while (!captured.pixels.rendered && Date.now() < deadline) {\n await activePage.waitForTimeout(500);\n await waitForCompositor(activePage);\n captured = await screenshotWithWitness(activePage);\n }\n }\n const runtime = await runtimeWitness(activePage);\n latestRuntime = runtime;\n const requestSummary = summarizeRequests(requestRecords);\n const uiPresent = runtime.domUi.rootChildren > 0;\n const requireUi = captureOptions.requireUi ?? options.requireUi ?? false;\n const captureBackend = observedBackend(runtime);\n if (captureBackend !== 'unknown') Object.assign(report, { backend: captureBackend });\n const backendMatches = backend === 'auto' || captureBackend === backend;\n const ok =\n runtime.canvas !== null &&\n captured.pixels.rendered &&\n backendMatches &&\n runtime.engineFrameId !== null &&\n consoleErrors.length === 0 &&\n pageErrors.length === 0 &&\n singleHtmlRuntimeClean(target, runtime, requestSummary) &&\n (expectedReady === undefined || runtime.captureReady === expectedReady) &&\n (!requireUi || uiPresent);\n const index = captures.length + 1;\n const output = resolve(\n facts.value.root,\n captureOptions.output ??\n resolve(\n outputDirectory,\n `${String(index).padStart(3, '0')}-${checkpointSlug(checkpoint)}.png`,\n ),\n );\n await mkdir(dirname(output), { recursive: true });\n await writeFile(output, captured.png);\n const record: SoftwareCaptureRecord = {\n index,\n checkpoint: checkpoint ?? null,\n ok,\n output,\n digest: captureDigest(captured.png),\n pixels: captured.pixels,\n runtime,\n };\n captures.push(record);\n await updateReport();\n if (!ok) {\n fail(\n `${backend === 'software' ? 'software' : 'browser'}-capture-runtime-failed`,\n 'non-flat canvas pixels, the requested browser backend/checkpoint, and no browser errors',\n 'Inspect the run report and repair the first browser runtime failure.',\n { checkpoint: checkpoint ?? null, output, report: reportPath },\n );\n }\n return record;\n },\n report: () => report,\n close,\n };\n } catch (cause) {\n await Promise.allSettled([browser?.close(), display?.close(), server?.close()]);\n throw cause;\n }\n}\n\nexport function createBrowserCapture(root: string): BrowserCapture {\n const sessions = new Set<BrowserCaptureSession>();\n return {\n async open(options) {\n const session = await openBrowserCaptureSession(root, options);\n sessions.add(session);\n return session;\n },\n async close() {\n await Promise.allSettled([...sessions].map((session) => session.close()));\n sessions.clear();\n },\n };\n}\n\n/**\n * Compatibility facade for callers that still request the original software\n * lane. New integrations should use createBrowserCapture({ backend }).\n */\nexport function createSoftwareBrowser(root: string): SoftwareBrowser {\n const browser = createBrowserCapture(root);\n return {\n async open(options) {\n return browser.open({ ...options, backend: 'software', software: true });\n },\n close: () => browser.close(),\n };\n}\n\nfunction captureCommandError(cause: unknown, legacySoftware = false): CommandError {\n if (cause instanceof SoftwareCaptureError) {\n const code =\n legacySoftware && cause.code.startsWith('browser-capture-')\n ? cause.code.replace(/^browser-capture-/, 'software-capture-')\n : cause.code;\n return {\n code,\n expected: cause.expected,\n hint: cause.hint,\n detail: cause.detail,\n };\n }\n return commandError(cause, legacySoftware ? 'software-capture-failed' : 'browser-capture-failed');\n}\n\nexport async function browserCaptureCommand(\n options: BrowserCaptureOptions,\n): Promise<CommandResult<BrowserCaptureRunReport>> {\n const root = options.root ?? process.cwd();\n const output = resolve(root, options.output ?? 'artifacts/capture/game-ui.png');\n const browser = createBrowserCapture(root);\n try {\n const backend = options.backend ?? (options.software === true ? 'software' : 'auto');\n const session = await browser.open({\n backend,\n ...(backend === 'software' ? { software: true } : {}),\n ...(options.browser === undefined ? {} : { browser: options.browser }),\n ...(options.width === undefined ? {} : { width: options.width }),\n ...(options.height === undefined ? {} : { height: options.height }),\n ...(options.port === undefined ? {} : { port: options.port }),\n ...(options.headless === undefined ? {} : { headless: options.headless }),\n requireUi: options.requireUi === true,\n deterministic: options.deterministic === true,\n outputDir: dirname(output),\n report: evidencePath(output),\n });\n await session.capture(options.deterministic === true ? 'true' : undefined, {\n output,\n waitMs: options.waitMs ?? 4000,\n requireUi: options.requireUi === true,\n });\n await session.close();\n return { ok: true, value: session.report() };\n } catch (cause) {\n return { ok: false, error: captureCommandError(cause) };\n } finally {\n await browser.close();\n }\n}\n\nexport async function softwareCaptureCommand(\n options: SoftwareCaptureOptions,\n): Promise<CommandResult<unknown>> {\n const result = await browserCaptureCommand({ ...options, backend: 'software', software: true });\n if (result.ok) return result;\n return { ok: false, error: captureCommandErrorFromResult(result.error, true) };\n}\n\nfunction captureCommandErrorFromResult(error: CommandError, legacySoftware: boolean): CommandError {\n if (!legacySoftware || !error.code.startsWith('browser-capture-')) return error;\n return { ...error, code: error.code.replace(/^browser-capture-/, 'software-capture-') };\n}\n","import { createHash } from 'node:crypto';\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { createServer as createNetServer } from 'node:net';\nimport { basename, dirname, relative, resolve } from 'node:path';\nimport { build as viteBuild, preview as vitePreview } from 'vite';\nimport { startVitest } from 'vitest/node';\nimport { createZip } from './archive.js';\nimport { verifyDist, writeDistManifest } from './dist.js';\nimport { createViteConfig } from './host.js';\nimport { commandError, readProjectFacts } from './project.js';\nimport {\n bundleSingleHtmlEntry,\n packageFormatError,\n packageOutputError,\n writeSingleHtml,\n} from './single-html.js';\nimport { resolveProjectPort } from './types.js';\n\nexport {\n assetAddCommand,\n assetInspectCommand,\n assetListCommand,\n assetVerifyCommand,\n} from './assets.js';\nexport type { DoctorReport } from './bootstrap-commands.js';\nexport { doctorCommand, initCommand, newCommand } from './bootstrap-commands.js';\nexport {\n engineDoctorCommand,\n engineStatusCommand,\n engineUnlinkCommand,\n engineUseLocalCommand,\n} from './engine-binding.js';\nexport { pluginInstallCommand, pluginUninstallCommand } from './plugin-authoring.js';\nexport { createCliRhiDebugOperationContext } from './rhi-debug/cli-context.js';\nexport type {\n ArtifactRef,\n CapturedRhiTape,\n RhiCaptureFrameValue,\n RhiDebugOperationContext,\n RhiDebugOperationDescriptor,\n RhiDebugOperationInput,\n RhiDebugOperationName,\n RhiDebugOperationOutput,\n RhiInspectInput,\n RhiInspectOutput,\n RhiSummaryInput,\n RhiSummaryOutput,\n} from './rhi-debug/operations.js';\nexport {\n createRhiDebugOperationContext,\n discoverRhiDebugOperations,\n RHI_DEBUG_OPERATION_MANIFEST,\n recoverRhiDebugError,\n renderRhiDebugHelp,\n runRhiDebugOperation,\n} from './rhi-debug/operations.js';\nexport { sdkInstallCommand } from './sdk-install.js';\nexport { shaderCheckCommand } from './shader-check.js';\nexport { skillInstallCommand, skillVerifyCommand } from './skill-install.js';\nexport { browserCaptureCommand, softwareCaptureCommand } from './software-capture.js';\n\nimport {\n type RhiDebugOperationContext,\n type RhiDebugOperationInput,\n type RhiDebugOperationName,\n type RhiDebugOperationOutput,\n runRhiDebugOperation,\n} from './rhi-debug/operations.js';\nimport type {\n BuildOptions,\n CommandResult,\n PackageOptions,\n ProjectCommandOptions,\n} from './types.js';\n\nexport function runRhiDebugCommand(\n name: RhiDebugOperationName,\n input: RhiDebugOperationInput,\n context: RhiDebugOperationContext,\n): Promise<CommandResult<RhiDebugOperationOutput>> {\n return runRhiDebugOperation(name, input, context);\n}\n\nasync function materializeViteDevPort(port: number): Promise<number> {\n if (port !== 0) return port;\n const reservation = createNetServer();\n await new Promise<void>((resolveListen, rejectListen) => {\n reservation.once('error', rejectListen);\n reservation.listen(0, '127.0.0.1', resolveListen);\n });\n const address = reservation.address();\n const assigned = typeof address === 'object' && address !== null ? address.port : 0;\n await new Promise<void>((resolveClose, rejectClose) => {\n reservation.close((error) => (error === undefined ? resolveClose() : rejectClose(error)));\n });\n if (assigned === 0) throw new Error('OS did not assign an ephemeral preview port');\n return assigned;\n}\n\nexport async function buildCommand(options: BuildOptions = {}): Promise<CommandResult<unknown>> {\n const facts = await readProjectFacts(options.root);\n if (!facts.ok) return facts;\n const previous = process.cwd();\n const base = options.base ?? '/';\n const outDir = resolve(facts.value.root, options.outDir ?? 'dist');\n try {\n process.chdir(facts.value.root);\n await viteBuild(await createViteConfig(facts.value, 'build', base, { outDir }));\n return { ok: true, value: await writeDistManifest(facts.value, base, outDir) };\n } catch (cause) {\n return { ok: false, error: commandError(cause, 'game-build-failed') };\n } finally {\n process.chdir(previous);\n }\n}\n\nfunction releaseSlug(name: string): string {\n const slug = name\n .normalize('NFKD')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '');\n return slug.length > 0 ? slug : 'forgeax-game';\n}\n\nexport async function packageCommand(\n options: PackageOptions = {},\n): Promise<CommandResult<unknown>> {\n const facts = await readProjectFacts(options.root);\n if (!facts.ok) return facts;\n const format = options.format ?? 'web-zip';\n if (format !== 'web-zip' && format !== 'single-html') return packageFormatError(String(format));\n const defaultOutput =\n format === 'single-html'\n ? `release/${releaseSlug(facts.value.name)}-offline.html`\n : `release/${releaseSlug(facts.value.name)}-web.zip`;\n const output = resolve(facts.value.root, options.output ?? defaultOutput);\n const expectedSuffix = format === 'single-html' ? '.html' : '.zip';\n if (!output.toLowerCase().endsWith(expectedSuffix)) {\n return packageOutputError(output, format);\n }\n const distRoot = resolve(facts.value.root, 'dist');\n const outputRelativeToDist = relative(distRoot, output);\n if (\n outputRelativeToDist === '' ||\n (!outputRelativeToDist.startsWith('..') && outputRelativeToDist !== '..')\n ) {\n return {\n ok: false,\n error: {\n code: 'release-output-inside-dist',\n expected: 'the release artifact to live outside the derived dist directory',\n hint: 'Use --output release/<game>-web.zip or release/<game>-offline.html.',\n detail: { output, distRoot, format },\n },\n };\n }\n const built = await buildCommand({\n root: facts.value.root,\n base: './',\n ...(options.json === undefined ? {} : { json: options.json }),\n });\n if (!built.ok) return built;\n const verified = await verifyDist(distRoot);\n if (!verified.ok) return verified;\n if (format === 'single-html') {\n const indexHtml = await readFile(resolve(distRoot, 'index.html'), 'utf8');\n const bundle = await bundleSingleHtmlEntry(distRoot, indexHtml, facts.value.root);\n if (!bundle.ok) return bundle;\n return writeSingleHtml({\n distRoot,\n output,\n manifest: verified.value,\n bundle: bundle.value,\n });\n }\n const archive = output;\n const temporaryArchive = `${archive}.partial-${process.pid}`;\n const checksumPath = `${archive}.sha256`;\n const temporaryChecksum = `${checksumPath}.partial-${process.pid}`;\n try {\n const paths = [\n ...verified.value.artifacts.map((artifact) => artifact.path),\n 'forgeax-dist.json',\n ];\n const entries = await Promise.all(\n paths.map(async (path) => ({ path, bytes: await readFile(resolve(distRoot, path)) })),\n );\n const bytes = createZip(entries);\n const sha256 = createHash('sha256').update(bytes).digest('hex');\n const manifestBytes = await readFile(resolve(distRoot, 'forgeax-dist.json'));\n await mkdir(dirname(archive), { recursive: true });\n await writeFile(temporaryArchive, bytes);\n await writeFile(temporaryChecksum, `${sha256} ${basename(archive)}\\n`);\n await rename(temporaryChecksum, checksumPath);\n await rename(temporaryArchive, archive);\n return {\n ok: true,\n value: {\n schemaVersion: '1.0.0',\n format: 'forgeax-web-game',\n target: 'web',\n project: verified.value.project,\n base: verified.value.base,\n engine: {\n delivery: 'bundled-runtime',\n wasm: verified.value.artifacts.some((artifact) => artifact.path.endsWith('.wasm')),\n },\n archive: { path: archive, bytes: bytes.byteLength, sha256 },\n checksumPath,\n distManifestSha256: createHash('sha256').update(manifestBytes).digest('hex'),\n run: {\n local: 'forgeax preview',\n shared: 'upload the ZIP to an HTTPS static or HTML-game host and share its URL',\n },\n },\n };\n } catch (cause) {\n return { ok: false, error: commandError(cause, 'game-package-failed') };\n } finally {\n await Promise.all([\n rm(temporaryArchive, { force: true }),\n rm(temporaryChecksum, { force: true }),\n ]);\n }\n}\n\nexport async function devCommand(\n options: ProjectCommandOptions = {},\n): Promise<CommandResult<unknown>> {\n const facts = await readProjectFacts(options.root);\n if (!facts.ok) return facts;\n const previous = process.cwd();\n let server: Awaited<ReturnType<typeof import('vite')['createServer']>> | undefined;\n try {\n const { createServer } = await import('vite');\n const { createViteConfig } = await import('./host.js');\n const port = resolveProjectPort(options.port);\n const vitePort = { ...port, port: await materializeViteDevPort(port.port) };\n process.chdir(facts.value.root);\n server = await createServer(\n await createViteConfig(facts.value, 'serve', '/', {\n server: vitePort,\n }),\n );\n await server.listen(vitePort.port);\n if (options.json !== true) server.printUrls();\n return {\n ok: true,\n value: {\n root: facts.value.root,\n urls: server.resolvedUrls,\n mode: 'dev',\n serves: 'source',\n capabilities: {\n 'rhi.capture': {\n available: false,\n realm: 'host',\n reason: 'standalone-dev-server-has-no-live-app-cli-attachment',\n },\n },\n },\n };\n } catch (cause) {\n await server?.close();\n process.chdir(previous);\n return { ok: false, error: commandError(cause, 'dev-server-failed') };\n }\n}\n\nexport async function previewCommand(\n options: ProjectCommandOptions = {},\n): Promise<CommandResult<unknown>> {\n const root = resolve(options.root ?? process.cwd());\n const verified = await verifyDist(resolve(root, 'dist'));\n if (!verified.ok) return verified;\n try {\n const port = resolveProjectPort(options.port);\n const server = await vitePreview({\n root,\n configFile: false,\n base: verified.value.base,\n preview: { open: false, ...port },\n build: { outDir: resolve(root, 'dist') },\n });\n if (options.json !== true) server.printUrls();\n return {\n ok: true,\n value: {\n root,\n urls: server.resolvedUrls,\n mode: 'preview',\n serves: 'dist',\n capabilities: {\n 'rhi.capture': {\n available: false,\n realm: 'host',\n reason: 'static-dist-host-does-not-install-dev-capture',\n },\n },\n },\n };\n } catch (cause) {\n return { ok: false, error: commandError(cause, 'preview-server-failed') };\n }\n}\n\nexport async function testCommand(\n options: ProjectCommandOptions = {},\n): Promise<CommandResult<unknown>> {\n const facts = await readProjectFacts(options.root);\n if (!facts.ok) return facts;\n try {\n const context = await startVitest('test', [], {\n root: facts.value.root,\n run: true,\n watch: false,\n passWithNoTests: false,\n });\n if (context === undefined) {\n return {\n ok: false,\n error: {\n code: 'test-runner-unavailable',\n expected: 'Vitest to create a project test context',\n hint: 'Inspect the project test configuration.',\n detail: { root: facts.value.root },\n },\n };\n }\n const failed = context.state.getFiles().filter((file) => file.result?.state === 'fail');\n await context.close();\n if (failed.length > 0) {\n return {\n ok: false,\n error: {\n code: 'project-tests-failed',\n expected: 'all project tests to pass',\n hint: 'Repair the failing game test before building a release.',\n detail: { files: failed.map((file) => file.filepath) },\n },\n };\n }\n return { ok: true, value: { root: facts.value.root } };\n } catch (cause) {\n return { ok: false, error: commandError(cause, 'project-tests-failed') };\n }\n}\n","import type { PluginCatalog, ToolPlugin } from '@forgeax/engine-plugin';\nimport { bindPreviewHost, type NativePreviewHost } from '@forgeax/engine-preview';\nimport materialPreviewPlugin from '@forgeax/engine-preview/material';\nimport meshPreviewPlugin from '@forgeax/engine-preview/mesh';\nimport texturePreviewPlugin from '@forgeax/engine-preview/texture';\nimport vfxPreviewPlugin from '@forgeax/engine-preview/vfx';\nimport type { ToolDescriptor } from '@forgeax/engine-tool-runtime';\n\nexport const nativePreviewPlugins = [\n ['@forgeax/engine-preview/material', materialPreviewPlugin],\n ['@forgeax/engine-preview/mesh', meshPreviewPlugin],\n ['@forgeax/engine-preview/vfx', vfxPreviewPlugin],\n ['@forgeax/engine-preview/texture', texturePreviewPlugin],\n] as const;\n\nexport const nativePreviewTools = nativePreviewPlugins.flatMap(([, plugin]) => plugin.tools);\nexport const nativePreviewDescriptors: readonly ToolDescriptor[] = nativePreviewTools.map(\n ({ descriptor }) => descriptor,\n);\n\nexport function createNativePreviewCatalog(\n host: NativePreviewHost,\n selectedName?: string,\n): PluginCatalog {\n return new Map(\n nativePreviewPlugins\n .filter(([name]) => selectedName === undefined || name === selectedName)\n .map(([name, plugin]) => [\n name,\n {\n realm: 'host' as const,\n load: async () => ({\n default: bindPreviewHost(plugin as ToolPlugin, host),\n }),\n },\n ]),\n );\n}\n","import { createHash } from 'node:crypto';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport {\n capabilityUnavailableError,\n createToolRuntime,\n type ToolContribution,\n type ToolDescriptor,\n type ToolRunOptions,\n type ToolRuntime,\n type ToolSchema,\n type ToolTerminal,\n} from '@forgeax/engine-tool-runtime';\nimport type { BuildOptions, PluginInstallOptions } from '../types.js';\nimport type { OfflineAnalysisRequest, OfflineAnalysisResult } from './offline-analysis.js';\nimport { nativePreviewDescriptors } from './preview-catalog.js';\nimport type { PreviewHostRequest, PreviewHostResult } from './preview-host.js';\n\nexport interface ToolCatalogAuthority {\n readonly authorityDigest?: string;\n readonly root?: string;\n readonly read?: () => Promise<ToolCatalogAuthoritySnapshot>;\n readonly projectionPath?: string;\n}\n\nexport interface ToolCatalogAuthoritySnapshot {\n readonly authorityDigest: string;\n readonly descriptors: readonly ToolDescriptor[];\n}\n\nexport interface ToolCatalogEntry {\n readonly id: string;\n readonly title: string;\n readonly summary: string;\n readonly realm: ToolDescriptor['realm'];\n readonly evidence: ToolDescriptor['evidence'];\n readonly argsSchema?: string;\n readonly resultSchema?: string;\n}\n\nexport interface ToolCatalog {\n readonly schemaVersion: '1.0.0';\n readonly authorityDigest: string;\n readonly digest: string;\n readonly entries: readonly ToolCatalogEntry[];\n}\n\nexport type ToolCatalogLoadResult =\n | {\n readonly ok: true;\n readonly value: ToolCatalog;\n }\n | {\n readonly ok: false;\n readonly error: {\n readonly code: 'tool-catalog-authority-unreadable' | 'tool-catalog-projection-invalid';\n readonly expected: string;\n readonly hint: string;\n readonly detail: Readonly<Record<string, string>>;\n };\n };\n\nconst buildArgsSchema: ToolSchema<BuildOptions> = {\n parse(value) {\n if (value === null || typeof value !== 'object')\n return { ok: false, error: 'expected an options object' };\n return { ok: true, value: value as BuildOptions };\n },\n describe: '{\"type\":\"object\",\"properties\":{\"root\":{\"type\":\"string\"},\"base\":{\"type\":\"string\"}}}',\n};\n\nconst pluginInstallArgsSchema: ToolSchema<PluginInstallOptions> = {\n parse(value) {\n if (value === null || typeof value !== 'object')\n return { ok: false, error: 'expected a plugin install options object' };\n return { ok: true, value: value as PluginInstallOptions };\n },\n describe:\n '{\"type\":\"object\",\"required\":[\"id\",\"module\"],\"properties\":{\"id\":{\"type\":\"string\"},\"module\":{\"type\":\"string\"},\"realm\":{\"enum\":[\"host\",\"engine\",\"build\"]},\"dependency\":{\"type\":\"string\"},\"root\":{\"type\":\"string\"}}}',\n};\n\nconst previewArgsSchema: ToolSchema<PreviewHostRequest> = {\n parse(value) {\n if (value === null || typeof value !== 'object')\n return { ok: false, error: 'expected a preview request object' };\n const request = value as { readonly recipe?: unknown };\n if (request.recipe === undefined || typeof request.recipe !== 'object')\n return { ok: false, error: 'expected recipe in the preview request' };\n return { ok: true, value: value as PreviewHostRequest };\n },\n describe:\n '{\"type\":\"object\",\"required\":[\"recipe\"],\"properties\":{\"recipe\":{\"type\":\"object\",\"required\":[\"snapshot\"],\"properties\":{\"snapshot\":{\"type\":\"object\",\"required\":[\"revision\",\"digest\"]},\"backend\":{\"const\":\"webgpu\"},\"presentation\":{\"enum\":[\"hidden\",\"visible\"]},\"viewport\":{\"type\":\"object\",\"properties\":{\"width\":{\"type\":\"integer\",\"minimum\":1},\"height\":{\"type\":\"integer\",\"minimum\":1}}},\"actions\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"required\":[\"frame\",\"name\"],\"properties\":{\"frame\":{\"type\":\"integer\",\"minimum\":0},\"name\":{\"type\":\"string\",\"minLength\":1},\"value\":{}}}},\"deltaSeconds\":{\"type\":\"number\",\"minimum\":0},\"frames\":{\"type\":\"integer\",\"minimum\":1}}}}}',\n};\n\nconst resultSchema: ToolSchema<unknown> = {\n parse: (value) => ({ ok: true, value }),\n describe: '{\"type\":\"object\"}',\n};\n\nconst offlineAnalysisArgsSchema: ToolSchema<OfflineAnalysisRequest> = {\n parse(value) {\n if (value === null || typeof value !== 'object')\n return { ok: false, error: 'expected an offline analysis request object' };\n const request = value as { readonly manifest?: unknown };\n if (request.manifest === undefined || typeof request.manifest !== 'object')\n return { ok: false, error: 'expected manifest in the offline analysis request' };\n return { ok: true, value: value as OfflineAnalysisRequest };\n },\n describe:\n '{\"type\":\"object\",\"required\":[\"manifest\"],\"properties\":{\"manifest\":{\"type\":\"object\",\"required\":[\"schemaVersion\",\"identity\",\"artifacts\"]},\"required\":{\"type\":\"array\",\"items\":{\"enum\":[\"rhi-tape\",\"png\",\"profile-capture\"]}}}}',\n};\n\nexport const projectBuildDescriptor: ToolDescriptor<BuildOptions, unknown> = {\n id: 'project.build',\n title: 'Build project',\n summary: 'Builds the project through the existing Vite and Pack authorities.',\n realm: 'build',\n argsSchema: buildArgsSchema,\n resultSchema,\n evidence: [],\n};\nexport const authorPluginInstallDescriptor: ToolDescriptor<PluginInstallOptions, unknown> = {\n id: 'author.plugin-install',\n title: 'Install project plugin',\n summary: 'Writes one plugin Entry through the project authoring authority.',\n realm: 'build',\n argsSchema: pluginInstallArgsSchema,\n resultSchema,\n evidence: [],\n};\nexport const previewRunDescriptor: ToolDescriptor<PreviewHostRequest, PreviewHostResult> = {\n id: 'preview.run',\n title: 'Run hidden WebGPU preview',\n summary: 'Runs one fixed real-WebGPU preview recipe and returns structured evidence refs.',\n realm: 'host',\n argsSchema: previewArgsSchema,\n resultSchema: resultSchema as ToolDescriptor<\n PreviewHostRequest,\n PreviewHostResult\n >['resultSchema'],\n evidence: ['rhi-tape', 'png', 'profile-capture'],\n};\nexport const previewOfflineAnalysisDescriptor: ToolDescriptor<\n OfflineAnalysisRequest,\n OfflineAnalysisResult\n> = {\n id: 'preview.offline-analysis',\n title: 'Analyze preview artifacts',\n summary: 'Validates owner-separated evidence identity before offline consumption.',\n realm: 'build',\n argsSchema: offlineAnalysisArgsSchema,\n resultSchema: resultSchema as ToolSchema<OfflineAnalysisResult>,\n evidence: ['rhi-tape', 'png', 'profile-capture'],\n};\n\nexport const defaultToolDescriptors: readonly ToolDescriptor[] = [\n projectBuildDescriptor,\n authorPluginInstallDescriptor,\n ...nativePreviewDescriptors,\n];\n\nfunction projectDescriptor(descriptor: ToolDescriptor): ToolCatalogEntry {\n return {\n id: descriptor.id,\n title: descriptor.title,\n summary: descriptor.summary,\n realm: descriptor.realm,\n evidence: [...descriptor.evidence],\n ...(descriptor.argsSchema.describe === undefined\n ? {}\n : { argsSchema: descriptor.argsSchema.describe }),\n ...(descriptor.resultSchema.describe === undefined\n ? {}\n : { resultSchema: descriptor.resultSchema.describe }),\n };\n}\n\nexport interface ToolRealmOwner {\n readonly realm: ToolDescriptor['realm'];\n readonly contributions: readonly ToolContribution[];\n}\n\nexport interface ToolRealmDispatch {\n readonly list: () => readonly ToolDescriptor[];\n readonly describe: (id: string) => ToolDescriptor | undefined;\n readonly run: <TResult = unknown>(\n id: string,\n args: unknown,\n options?: ToolRunOptions,\n ) => Promise<ToolTerminal<TResult>>;\n}\n\nfunction missingRealmOwner<TResult>(\n descriptor: ToolDescriptor | undefined,\n id: string,\n): ToolTerminal<TResult> {\n const realm = descriptor?.realm ?? 'build';\n return {\n outcome: 'failed',\n failure: capabilityUnavailableError(`realm:${realm}:tool:${id}`, realm),\n artifacts: [],\n } as ToolTerminal<TResult>;\n}\n\n/** Dispatches a descriptor to the one physical owner for its declared realm. */\nexport function createRealmDispatch(\n contributions: readonly ToolContribution[],\n owners: readonly ToolRealmOwner[],\n): ToolRealmDispatch {\n const contributionById = new Map(\n contributions.map((contribution) => [contribution.descriptor.id, contribution]),\n );\n const ownerByRealm = new Map<ToolDescriptor['realm'], ToolRuntime>();\n for (const owner of owners) {\n if (ownerByRealm.has(owner.realm)) throw new TypeError(`Duplicate realm owner: ${owner.realm}`);\n const invalid = owner.contributions.find(\n (contribution) => contribution.descriptor.realm !== owner.realm,\n );\n if (invalid !== undefined) {\n throw new TypeError(\n `Tool ${invalid.descriptor.id} declares ${invalid.descriptor.realm} but owner is ${owner.realm}`,\n );\n }\n ownerByRealm.set(owner.realm, createToolRuntime(owner.contributions));\n }\n return {\n list: () => contributions.map((contribution) => contribution.descriptor),\n describe: (id) => contributionById.get(id)?.descriptor,\n async run<TResult = unknown>(id: string, args: unknown, options: ToolRunOptions = {}) {\n const contribution = contributionById.get(id);\n if (contribution === undefined)\n return missingRealmOwner(undefined, id) as ToolTerminal<TResult>;\n const owner = ownerByRealm.get(contribution.descriptor.realm);\n if (owner === undefined) return missingRealmOwner(contribution.descriptor, id);\n const bound = owner.get(id);\n if (bound === undefined) return missingRealmOwner(contribution.descriptor, id);\n return (await owner.run(bound, args, options).terminal) as ToolTerminal<TResult>;\n },\n };\n}\n\nfunction requiredAuthorityDigest(authority: ToolCatalogAuthority): string {\n if (authority.authorityDigest === undefined) {\n throw new TypeError('Catalog materialization requires an authority digest');\n }\n return authority.authorityDigest;\n}\n\nfunction digestCatalog(authorityDigest: string, entries: readonly ToolCatalogEntry[]): string {\n return `sha256:${createHash('sha256')\n .update(JSON.stringify({ authorityDigest, entries }))\n .digest('hex')}`;\n}\n\nfunction digestAuthority(bytes: readonly Uint8Array[]): string {\n const hash = createHash('sha256');\n for (const value of bytes) hash.update(value);\n return `sha256:${hash.digest('hex')}`;\n}\n\nfunction projectionValid(\n catalog: unknown,\n authorityDigest: string,\n descriptors: readonly ToolDescriptor[] = defaultToolDescriptors,\n): catalog is ToolCatalog {\n if (catalog === null || typeof catalog !== 'object') return false;\n const value = catalog as Partial<ToolCatalog>;\n const expectedEntries = descriptors\n .map(projectDescriptor)\n .sort((left, right) => left.id.localeCompare(right.id));\n return (\n value.schemaVersion === '1.0.0' &&\n value.authorityDigest === authorityDigest &&\n Array.isArray(value.entries) &&\n JSON.stringify(value.entries) === JSON.stringify(expectedEntries) &&\n value.digest === digestCatalog(authorityDigest, value.entries as ToolCatalogEntry[])\n );\n}\n\nexport function createProjectToolCatalogAuthority(\n rootInput: string,\n descriptors: readonly ToolDescriptor[] = defaultToolDescriptors,\n): ToolCatalogAuthority {\n const root = resolve(rootInput);\n return {\n root,\n projectionPath: resolve(root, '.forgeax/generated/tool-catalog.json'),\n async read() {\n const [forge, packageJson] = await Promise.all([\n readFile(resolve(root, 'forge.json')),\n readFile(resolve(root, 'package.json')),\n ]);\n return { authorityDigest: digestAuthority([forge, packageJson]), descriptors };\n },\n };\n}\n\nexport async function loadToolCatalog(\n authority: ToolCatalogAuthority,\n descriptors: readonly ToolDescriptor[] = defaultToolDescriptors,\n): Promise<ToolCatalogLoadResult> {\n const read = authority.read;\n if (read === undefined) {\n if (authority.authorityDigest === undefined) {\n return {\n ok: false,\n error: {\n code: 'tool-catalog-authority-unreadable',\n expected: 'an injectable project authority reader',\n hint: 'Create a project authority from a real project root before listing tools.',\n detail: { reason: 'authority reader is missing' },\n },\n };\n }\n return { ok: true, value: materializeToolDescriptorCatalog(descriptors, authority) };\n }\n let snapshot: ToolCatalogAuthoritySnapshot;\n try {\n snapshot = await read();\n } catch (cause) {\n return {\n ok: false,\n error: {\n code: 'tool-catalog-authority-unreadable',\n expected: 'project authority files to be readable',\n hint: 'Repair forge.json and package.json, then retry catalog rebuild.',\n detail: { reason: cause instanceof Error ? cause.message : String(cause) },\n },\n };\n }\n const projectionPath = authority.projectionPath;\n if (projectionPath !== undefined) {\n try {\n const current = JSON.parse(await readFile(projectionPath, 'utf8')) as unknown;\n if (projectionValid(current, snapshot.authorityDigest, snapshot.descriptors)) {\n return { ok: true, value: current };\n }\n } catch {\n // Missing or corrupt projections are rebuilt from the authority below.\n }\n }\n const catalog = materializeToolDescriptorCatalog(snapshot.descriptors, {\n authorityDigest: snapshot.authorityDigest,\n });\n if (projectionPath !== undefined) {\n try {\n await mkdir(resolve(projectionPath, '..'), { recursive: true });\n await writeFile(projectionPath, `${JSON.stringify(catalog, null, 2)}\\n`, 'utf8');\n } catch (cause) {\n return {\n ok: false,\n error: {\n code: 'tool-catalog-projection-invalid',\n expected: 'the generated catalog projection to be writable',\n hint: 'Restore write access to .forgeax/generated and retry cold rebuild.',\n detail: { reason: cause instanceof Error ? cause.message : String(cause) },\n },\n };\n }\n }\n return { ok: true, value: catalog };\n}\n\nexport function materializeToolCatalog<TArgs, TResult>(\n contributions: readonly ToolContribution<TArgs, TResult>[],\n authority: ToolCatalogAuthority,\n): ToolCatalog;\nexport function materializeToolCatalog(\n contributions: readonly unknown[],\n authority: ToolCatalogAuthority,\n): ToolCatalog;\nexport function materializeToolCatalog(\n contributions: readonly unknown[],\n authority: ToolCatalogAuthority,\n): ToolCatalog {\n const entries = contributions\n .map((candidate) => {\n if (typeof candidate !== 'object' || candidate === null)\n throw new TypeError('Invalid tool contribution');\n return projectDescriptor((candidate as ToolContribution<unknown, unknown>).descriptor);\n })\n .sort((left, right) => left.id.localeCompare(right.id));\n const authorityDigest = requiredAuthorityDigest(authority);\n return {\n schemaVersion: '1.0.0',\n authorityDigest,\n digest: digestCatalog(authorityDigest, entries),\n entries,\n };\n}\n\nexport function materializeToolDescriptorCatalog(\n descriptors: readonly ToolDescriptor[],\n authority: ToolCatalogAuthority,\n): ToolCatalog {\n const entries = descriptors\n .map(projectDescriptor)\n .sort((left, right) => left.id.localeCompare(right.id));\n const authorityDigest = requiredAuthorityDigest(authority);\n return {\n schemaVersion: '1.0.0',\n authorityDigest,\n digest: digestCatalog(authorityDigest, entries),\n entries,\n };\n}\n\nexport function rebuildToolCatalog<TArgs, TResult>(\n contributions: readonly ToolContribution<TArgs, TResult>[],\n current: ToolCatalog | undefined,\n authority: ToolCatalogAuthority,\n): ToolCatalog;\nexport function rebuildToolCatalog(\n contributions: readonly unknown[],\n current: ToolCatalog | undefined,\n authority: ToolCatalogAuthority,\n): ToolCatalog {\n if (\n current !== undefined &&\n authority.authorityDigest !== undefined &&\n current.authorityDigest === authority.authorityDigest &&\n projectionValid(current, authority.authorityDigest)\n )\n return current;\n if (authority.authorityDigest === undefined) {\n throw new TypeError('Catalog rebuild requires an authority digest');\n }\n return materializeToolCatalog(contributions, authority);\n}\n\nexport function listTools(catalog: ToolCatalog): readonly ToolCatalogEntry[] {\n return catalog.entries;\n}\n\nexport function describeTool(catalog: ToolCatalog, id: string): ToolCatalogEntry | undefined {\n return catalog.entries.find((entry) => entry.id === id);\n}\n","import {\n domainFailureError,\n type ToolDomainFailure,\n type ToolTerminal,\n} from '@forgeax/engine-tool-runtime';\n\nexport const retiredPreviewOperationFailure: ToolDomainFailure = {\n code: 'preview-operation-migrated',\n expected: 'a domain-specific preview contribution selected from the project catalog',\n hint: 'Use material.preview, mesh.preview, vfx.preview, or texture.preview with a Project GUID.',\n detail: {\n operation: 'preview.run',\n replacements: ['material.preview', 'mesh.preview', 'vfx.preview', 'texture.preview'],\n },\n};\n\nexport function retiredPreviewTool(): ToolTerminal<never> {\n return {\n outcome: 'failed',\n failure: domainFailureError(\n retiredPreviewOperationFailure.code,\n retiredPreviewOperationFailure.expected,\n retiredPreviewOperationFailure.hint,\n retiredPreviewOperationFailure.detail,\n ),\n artifacts: [],\n };\n}\n","import { readFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { Context, isToolPlugin, type ToolPlugin } from '@forgeax/engine-plugin';\nimport {\n type GamePluginEntry,\n installCatalogLoader,\n type PluginCatalog,\n type PluginRealm,\n projectPluginEntries,\n} from '@forgeax/engine-plugin/loader';\nimport { type GameProjectPluginEntry, GameProjectSchema } from '@forgeax/engine-project';\nimport type {\n ToolContribution,\n ToolEvidenceKind,\n ToolRunOptions,\n ToolTerminal,\n} from '@forgeax/engine-tool-runtime';\nimport { createServer, type ViteDevServer } from 'vite';\n\nexport interface ProjectToolBinding {\n readonly contribution: ToolContribution<unknown, unknown>;\n readonly entry: GameProjectPluginEntry;\n readonly moduleName: string;\n readonly realm: PluginRealm;\n readonly toolPlugin?: ToolPlugin;\n readonly loadToolPlugin: () => Promise<ToolPlugin>;\n}\n\nexport interface ProjectToolModuleLoader {\n readonly load: (name: string) => Promise<unknown>;\n readonly close: () => Promise<void>;\n}\n\nexport interface ProjectToolDiscoveryOptions {\n readonly moduleLoader?: ProjectToolModuleLoader;\n readonly loadModules?: boolean;\n}\n\ninterface ProjectPluginLeaf {\n readonly entry: GameProjectPluginEntry;\n readonly moduleName: string;\n readonly realm: PluginRealm;\n}\n\ninterface StaticToolDeclaration {\n readonly id: string;\n readonly title: string;\n readonly summary: string;\n readonly realm: PluginRealm;\n readonly argsSchema?: string;\n readonly resultSchema?: string;\n readonly evidence?: readonly ToolEvidenceKind[];\n}\n\nfunction projectLeaves(\n entries: readonly GameProjectPluginEntry[],\n inheritedRealm: PluginRealm = 'engine',\n): ProjectPluginLeaf[] {\n const leaves: ProjectPluginLeaf[] = [];\n for (const entry of entries) {\n const realm = entry.realm ?? inheritedRealm;\n if (entry.disabled === true) continue;\n if (entry.group === true) {\n leaves.push(...projectLeaves(entry.config as readonly GameProjectPluginEntry[], realm));\n continue;\n }\n if (!entry.name.startsWith('cordis:')) {\n leaves.push({ entry, moduleName: entry.name, realm });\n }\n }\n return leaves;\n}\n\nfunction exportedToolPlugin(module: unknown): ToolPlugin | undefined {\n if (isToolPlugin(module)) return module;\n if (typeof module !== 'object' || module === null) return undefined;\n const value = Reflect.get(module, 'default');\n return isToolPlugin(value) ? value : undefined;\n}\n\nfunction staticContributions(\n entry: GameProjectPluginEntry,\n): readonly ToolContribution<unknown, unknown>[] {\n if (entry.config === null || typeof entry.config !== 'object') return [];\n const tools = Reflect.get(entry.config, 'tools');\n if (!Array.isArray(tools)) return [];\n return tools.flatMap((candidate: unknown) => {\n if (candidate === null || typeof candidate !== 'object') return [];\n const declaration = candidate as Partial<StaticToolDeclaration>;\n if (\n typeof declaration.id !== 'string' ||\n typeof declaration.title !== 'string' ||\n typeof declaration.summary !== 'string' ||\n (declaration.realm !== 'build' &&\n declaration.realm !== 'host' &&\n declaration.realm !== 'engine')\n )\n return [];\n const descriptor = {\n id: declaration.id,\n title: declaration.title,\n summary: declaration.summary,\n realm: declaration.realm,\n argsSchema: {\n parse: (value: unknown) => ({ ok: true as const, value }),\n ...(declaration.argsSchema === undefined ? {} : { describe: declaration.argsSchema }),\n },\n resultSchema: {\n parse: (value: unknown) => ({ ok: true as const, value }),\n ...(declaration.resultSchema === undefined ? {} : { describe: declaration.resultSchema }),\n },\n evidence: declaration.evidence ?? [],\n };\n return [\n {\n descriptor,\n execute: async () => ({\n ok: false as const,\n error: { code: 'tool-static-descriptor', detail: {} },\n }),\n },\n ];\n });\n}\n\nfunction hasStaticToolDeclarations(entry: GameProjectPluginEntry): boolean {\n if (entry.config === null || typeof entry.config !== 'object') return false;\n return Array.isArray(Reflect.get(entry.config, 'tools'));\n}\n\nasync function createViteModuleLoader(root: string): Promise<ProjectToolModuleLoader> {\n const server: ViteDevServer = await createServer({\n root,\n appType: 'custom',\n configFile: false,\n logLevel: 'silent',\n server: { middlewareMode: true },\n });\n return {\n load(name) {\n const id = name.startsWith('.') ? `/@fs/${resolve(root, name)}` : name;\n return server.ssrLoadModule(id);\n },\n close: () => server.close(),\n };\n}\n\nasync function readProjectEntries(root: string): Promise<readonly GameProjectPluginEntry[]> {\n const raw = JSON.parse(await readFile(resolve(root, 'forge.json'), 'utf8')) as unknown;\n const parsed = GameProjectSchema.safeParse(raw);\n if (!parsed.success) {\n throw new TypeError(`Invalid forge.json: ${parsed.error.message}`);\n }\n return parsed.data.plugins ?? [];\n}\n\nexport async function discoverProjectTools(\n rootInput: string,\n options: ProjectToolDiscoveryOptions = {},\n): Promise<readonly ProjectToolBinding[]> {\n const root = resolve(rootInput);\n const loadModules = options.loadModules ?? true;\n const loader = loadModules\n ? (options.moduleLoader ?? (await createViteModuleLoader(root)))\n : undefined;\n try {\n const bindings: ProjectToolBinding[] = [];\n const ids = new Map<string, string>();\n for (const leaf of projectLeaves(await readProjectEntries(root))) {\n if (leaf.realm !== 'build' && leaf.realm !== 'host' && leaf.realm !== 'engine') continue;\n // Gameplay entries are part of the engine closure, not the tool catalog. They\n // are only evaluated when they explicitly publish static tool declarations;\n // this keeps discovery from importing an unrelated gameplay module.\n if (leaf.realm === 'engine' && !hasStaticToolDeclarations(leaf.entry)) continue;\n const toolPlugin = loadModules\n ? exportedToolPlugin(await (loader as ProjectToolModuleLoader).load(leaf.moduleName))\n : undefined;\n const contributions = toolPlugin?.tools ?? staticContributions(leaf.entry);\n for (const contribution of contributions) {\n if (contribution.descriptor.realm !== leaf.realm) {\n throw new TypeError(\n `Tool ${contribution.descriptor.id} declares ${contribution.descriptor.realm} but Entry ${leaf.entry.id} owns ${leaf.realm}`,\n );\n }\n const existing = ids.get(contribution.descriptor.id);\n if (existing !== undefined) {\n throw new TypeError(\n `Duplicate project tool id ${contribution.descriptor.id} from ${existing} and ${leaf.entry.id}`,\n );\n }\n ids.set(contribution.descriptor.id, leaf.entry.id);\n bindings.push({\n contribution,\n entry: leaf.entry,\n moduleName: leaf.moduleName,\n realm: leaf.realm,\n ...(toolPlugin === undefined ? {} : { toolPlugin }),\n loadToolPlugin: async () => {\n if (toolPlugin !== undefined) return toolPlugin;\n const selectedLoader = options.moduleLoader ?? (await createViteModuleLoader(root));\n try {\n const loaded = exportedToolPlugin(await selectedLoader.load(leaf.moduleName));\n if (loaded === undefined)\n throw new TypeError(`Entry ${leaf.entry.id} does not export a ToolPlugin`);\n return loaded;\n } finally {\n await selectedLoader.close();\n }\n },\n });\n }\n }\n return bindings;\n } finally {\n if (loader !== undefined) await loader.close();\n }\n}\n\nfunction activationFailure(cause: unknown): ToolTerminal<never> {\n const message = cause instanceof Error ? cause.message : String(cause);\n return {\n outcome: 'failed',\n failure: {\n code: 'tool-domain-failed',\n expected: 'the owning project plugin Fiber to become ready',\n hint: 'Repair the project Entry, plugin dependencies, or plugin apply failure before retrying.',\n detail: { code: 'tool-plugin-activation-failed', payload: message },\n },\n artifacts: [],\n };\n}\n\nexport async function runProjectTool(\n binding: ProjectToolBinding,\n args: unknown,\n options: ToolRunOptions,\n): Promise<ToolTerminal<unknown>> {\n const ctx = new Context();\n try {\n const toolPlugin = await binding.loadToolPlugin();\n const contribution = toolPlugin.tools.find(\n (candidate) => candidate.descriptor.id === binding.contribution.descriptor.id,\n );\n if (contribution === undefined)\n return activationFailure(new Error('selected tool is absent from Entry'));\n const catalog: PluginCatalog = new Map([\n [\n binding.moduleName,\n {\n realm: binding.realm,\n load: async () => ({ default: toolPlugin }),\n },\n ],\n ]);\n const { loader } = await installCatalogLoader(ctx, catalog, binding.realm);\n const entries = projectPluginEntries(\n [binding.entry as GamePluginEntry],\n binding.realm,\n binding.realm,\n );\n await loader.root.update(entries);\n await loader.await();\n const { createToolRuntime } = await import('@forgeax/engine-tool-runtime');\n const { createContextCapabilityResolver } = await import('@forgeax/engine-plugin');\n return await createToolRuntime([contribution]).run(contribution, args, {\n ...options,\n capabilityResolver: createContextCapabilityResolver(ctx),\n }).terminal;\n } catch (cause) {\n return activationFailure(cause);\n } finally {\n await ctx.fiber.dispose();\n }\n}\n","import {\n defineTool,\n type JsonValue,\n type ToolContribution,\n type ToolDomainFailure,\n} from '@forgeax/engine-tool-runtime';\nimport type { BuildOptions, PluginInstallOptions } from '../types.js';\nimport { authorPluginInstallDescriptor, projectBuildDescriptor } from './catalog.js';\nimport { nativePreviewTools } from './preview-catalog.js';\n\n// The historical createPreviewContributions helper is private proof code; the\n// discoverable default path uses the native domain preview owners.\n\nfunction commandFailure(error: {\n readonly code: string;\n readonly expected: string;\n readonly hint: string;\n readonly detail: Record<string, unknown>;\n}): { readonly ok: false; readonly error: ToolDomainFailure } {\n return { ok: false, error: { ...error, detail: error.detail as unknown as JsonValue } };\n}\n\nexport function createBuildContribution(\n projectRoot = process.cwd(),\n): ToolContribution<BuildOptions, unknown> {\n return defineTool(\n projectBuildDescriptor as typeof projectBuildDescriptor & {\n readonly argsSchema: import('@forgeax/engine-tool-runtime').ToolSchema<BuildOptions>;\n },\n async (options) => {\n const { buildCommand } = await import('../commands.js');\n const result = await buildCommand({ ...options, root: options.root ?? projectRoot });\n return result.ok ? result.value : commandFailure(result.error);\n },\n );\n}\n\nexport function createAuthorContribution(\n projectRoot = process.cwd(),\n): ToolContribution<PluginInstallOptions, unknown> {\n return defineTool(\n authorPluginInstallDescriptor as typeof authorPluginInstallDescriptor & {\n readonly argsSchema: import('@forgeax/engine-tool-runtime').ToolSchema<PluginInstallOptions>;\n },\n async (options) => {\n const { pluginInstallCommand } = await import('../plugin-authoring.js');\n const result = await pluginInstallCommand({ ...options, root: options.root ?? projectRoot });\n return result.ok ? result.value : commandFailure(result.error);\n },\n );\n}\n\nexport function createDefaultContributions(\n projectRoot = process.cwd(),\n): readonly (\n | ToolContribution<BuildOptions, unknown>\n | ToolContribution<PluginInstallOptions, unknown>\n | ToolContribution<unknown, unknown>\n)[] {\n return [\n createBuildContribution(projectRoot),\n createAuthorContribution(projectRoot),\n ...nativePreviewTools,\n ];\n}\n","import {\n type PreviewArtifactManifest,\n type PreviewArtifactRole,\n validatePreviewArtifactManifest,\n} from '@forgeax/engine-preview';\nimport {\n type ToolArtifactManifest,\n type ToolDomainFailure,\n type ToolEvidenceKind,\n validateArtifactManifest,\n} from '@forgeax/engine-tool-runtime';\n\nexport interface OfflineAnalysisRequest {\n readonly manifest: PreviewArtifactManifest | ToolArtifactManifest;\n readonly required?: readonly (PreviewArtifactRole | ToolEvidenceKind)[];\n}\n\nexport interface OfflineAnalysisResult {\n readonly runId: string;\n readonly captureId: string;\n readonly artifacts: readonly { readonly kind: string; readonly digest: string }[];\n}\n\nexport function analyzePreviewArtifacts(\n request: OfflineAnalysisRequest,\n):\n | { readonly ok: true; readonly value: OfflineAnalysisResult }\n | { readonly ok: false; readonly error: ToolDomainFailure } {\n const required = request.required ?? [];\n const validated =\n request.manifest.schemaVersion === '1.0.0'\n ? required.some((kind) => kind !== 'rhi-tape' && kind !== 'png' && kind !== 'profile-capture')\n ? {\n ok: false as const,\n error: {\n code: 'tool-artifact-manifest-invalid',\n expected: 'requested evidence kinds to belong to the v1 artifact manifest',\n hint: 'Request one of rhi-tape, png, or profile-capture for a v1 manifest.',\n detail: { reason: 'unsupported required evidence kind' },\n },\n }\n : validateArtifactManifest(request.manifest, required as readonly ToolEvidenceKind[])\n : validatePreviewArtifactManifest(\n request.manifest,\n (request.required ?? []).filter(\n (role): role is PreviewArtifactRole =>\n role === 'report' ||\n role === 'rhi-tape' ||\n role === 'capture' ||\n role === 'fresh-replay' ||\n role === 'profile-capture' ||\n role === 'contact-sheet',\n ),\n );\n if (!validated.ok) return { ok: false, error: validated.error as ToolDomainFailure };\n return {\n ok: true,\n value: {\n runId: request.manifest.identity.runId,\n captureId: request.manifest.identity.captureId,\n artifacts: request.manifest.artifacts.map(({ kind, digest }) => ({ kind, digest })),\n },\n };\n}\n","import { defineTool, type ToolContribution } from '@forgeax/engine-tool-runtime';\nimport { previewOfflineAnalysisDescriptor, previewRunDescriptor } from './catalog.js';\nimport {\n analyzePreviewArtifacts,\n type OfflineAnalysisRequest,\n type OfflineAnalysisResult,\n} from './offline-analysis.js';\nimport type { PreviewHostRequest, PreviewHostResult } from './preview-host.js';\nimport { retiredPreviewOperationFailure } from './preview-migration.js';\n\nexport function createPreviewContribution(): ToolContribution<\n PreviewHostRequest,\n PreviewHostResult\n> {\n return defineTool(previewRunDescriptor, async () => ({\n ok: false as const,\n error: retiredPreviewOperationFailure,\n }));\n}\n\nexport function createOfflineAnalysisContribution(): ToolContribution<\n OfflineAnalysisRequest,\n OfflineAnalysisResult\n> {\n return defineTool(\n {\n ...previewOfflineAnalysisDescriptor,\n },\n (request) => analyzePreviewArtifacts(request),\n );\n}\n\nexport function createPreviewContributions(): readonly ToolContribution<unknown, unknown>[] {\n return [\n createPreviewContribution() as ToolContribution<unknown, unknown>,\n createOfflineAnalysisContribution() as ToolContribution<unknown, unknown>,\n ];\n}\n","import {\n createToolRuntime,\n type ToolContribution,\n type ToolRuntime,\n} from '@forgeax/engine-tool-runtime';\nimport { createPreviewContributions } from './preview-contributions.js';\n\nexport function createDevkitToolRuntime<TArgs, TResult>(\n contributions: readonly ToolContribution<TArgs, TResult>[],\n): ToolRuntime;\nexport function createDevkitToolRuntime(contributions: readonly unknown[]): ToolRuntime;\nexport function createDevkitToolRuntime(contributions: readonly unknown[]): ToolRuntime {\n return createToolRuntime(contributions);\n}\n\nexport function createPreviewToolRuntime(): ToolRuntime {\n return createToolRuntime(createPreviewContributions());\n}\n","import { createHash } from 'node:crypto';\nimport { mkdir, mkdtemp, rename, rm, writeFile } from 'node:fs/promises';\nimport { type AddressInfo, createServer as createTcpServer } from 'node:net';\nimport { join, relative, sep } from 'node:path';\nimport type {\n ToolPreviewCaptureResult,\n ToolPreviewRecipe,\n ToolPreviewResourceRequest,\n} from '@forgeax/engine-app';\nimport { createResourcePreviewReport, type ResourcePreviewReport } from '@forgeax/engine-preview';\nimport {\n createPreviewArtifactManifest,\n type JsonValue,\n type PreviewArtifactManifestEntry,\n type SnapshotRef,\n type ToolDomainFailure,\n validatePreviewArtifactManifest,\n} from '@forgeax/engine-tool-runtime';\nimport { type Browser, chromium, type Page } from 'playwright';\nimport { createServer, type ViteDevServer } from 'vite';\nimport type { BootstrapRoot } from '../host/base-host.js';\nimport { createViteConfig } from '../host.js';\nimport { readProjectFacts } from '../project.js';\nimport type { PreviewHostResult } from './preview-host.js';\n\nexport type BrowserHostResult =\n | { readonly ok: true; readonly value: PreviewHostResult }\n | { readonly ok: false; readonly error: ToolDomainFailure };\n\nfunction transportCause(cause: unknown): JsonValue {\n if (cause instanceof Error) {\n return {\n name: cause.name,\n message: cause.message,\n ...(cause.stack === undefined ? {} : { stack: cause.stack }),\n };\n }\n if (cause === undefined) return 'undefined';\n try {\n return JSON.parse(JSON.stringify(cause)) as JsonValue;\n } catch {\n return String(cause);\n }\n}\n\nfunction dataUriBytes(uri: string): Uint8Array {\n const separator = uri.indexOf(',');\n if (separator < 0) throw new TypeError('preview artifact must be a data URI before publication');\n return Buffer.from(uri.slice(separator + 1), 'base64');\n}\n\nfunction projectUri(projectRoot: string, path: string): string {\n return relative(projectRoot, path).split(sep).join('/');\n}\n\nexport interface ResourcePreviewReportInput {\n readonly snapshot: SnapshotRef;\n readonly subject: ResourcePreviewReport['subject'];\n readonly presentation: ResourcePreviewReport['presentation'];\n readonly oracle: ResourcePreviewReport['oracle'];\n}\n\nexport interface BrowserHostOptions {\n readonly publish?: boolean;\n}\n\n/** @internal Vite treats port 0 as its default 5173, not as an OS-assigned port. */\nexport async function allocateLoopbackPort(): Promise<number> {\n const probe = createTcpServer();\n try {\n await new Promise<void>((resolve, reject) => {\n const onError = (error: Error): void => {\n probe.off('listening', onListening);\n reject(error);\n };\n const onListening = (): void => {\n probe.off('error', onError);\n resolve();\n };\n probe.once('error', onError);\n probe.once('listening', onListening);\n probe.listen(0, '127.0.0.1');\n });\n const address = probe.address();\n if (address === null || typeof address === 'string') {\n throw new Error('loopback port probe did not expose a TCP address');\n }\n return address.port;\n } finally {\n if (probe.listening) {\n await new Promise<void>((resolve) => probe.close(() => resolve()));\n }\n }\n}\n\nfunction sha256(bytes: Uint8Array): string {\n return `sha256:${createHash('sha256').update(bytes).digest('hex')}`;\n}\n\nfunction artifactRef(artifact: PreviewArtifactManifestEntry) {\n const kind =\n artifact.kind === 'report' || artifact.kind === 'contact-sheet'\n ? ('tool-result' as const)\n : artifact.kind;\n return {\n kind,\n digest: artifact.digest,\n uri: artifact.uri,\n mediaType: artifact.mediaType,\n sizeBytes: artifact.byteLength,\n };\n}\n\nexport async function publishPreviewArtifacts(\n projectRoot: string,\n runId: string,\n result: PreviewHostResult,\n reportInput?: ResourcePreviewReportInput,\n): Promise<PreviewHostResult> {\n if (result.manifest.identity.runId !== runId) {\n throw new Error(\n `preview artifact run identity mismatch: manifest=${result.manifest.identity.runId} requested=${runId}`,\n );\n }\n const runsRoot = join(projectRoot, '.forgeax', 'tool-runs');\n await mkdir(runsRoot, { recursive: true });\n const directoryName = runId.replace(/[^a-zA-Z0-9._-]/g, '_');\n const published = join(runsRoot, directoryName);\n const finalPaths = {\n tapeJson: join(published, 'rhi-tape.json'),\n tapeBlob: join(published, 'rhi-tape.bin'),\n capturePng: join(published, 'capture.png'),\n freshReplayPng: join(published, 'fresh-replay.png'),\n profile: join(published, 'profile.json'),\n manifest: join(published, 'manifest.json'),\n report: join(published, 'report.json'),\n };\n const tapeJson = dataUriBytes(result.tape.jsonUri);\n const tapeBlob = dataUriBytes(result.tape.blobUri);\n const capturePng = dataUriBytes(result.capturePng.uri);\n const freshReplayPng = dataUriBytes(result.png.uri);\n const profile = dataUriBytes(result.profile.uri);\n const bytesByRole = {\n 'rhi-tape': tapeJson,\n capture: capturePng,\n 'fresh-replay': freshReplayPng,\n 'profile-capture': profile,\n } as const;\n const uriByRole = {\n 'rhi-tape': projectUri(projectRoot, finalPaths.tapeJson),\n capture: projectUri(projectRoot, finalPaths.capturePng),\n 'fresh-replay': projectUri(projectRoot, finalPaths.freshReplayPng),\n 'profile-capture': projectUri(projectRoot, finalPaths.profile),\n } as const;\n const mediaTypeByRole = {\n 'rhi-tape': 'application/vnd.forgeax.rhi-tape+json',\n capture: 'image/png',\n 'fresh-replay': 'image/png',\n 'profile-capture': 'application/vnd.forgeax.profile+json',\n } as const;\n const requiredRoles = ['rhi-tape', 'capture', 'fresh-replay', 'profile-capture'] as const;\n const nonReportArtifacts = result.manifest.artifacts\n .filter((artifact) => artifact.role !== 'report')\n .map((artifact) => {\n if (!(artifact.role in bytesByRole)) {\n return artifact;\n }\n const role = artifact.role as keyof typeof bytesByRole;\n const bytes = bytesByRole[role];\n const digest = sha256(bytes);\n if (artifact.digest !== digest) {\n throw new Error(`preview artifact digest mismatch for ${artifact.role}`);\n }\n return {\n ...artifact,\n uri: uriByRole[role],\n digest,\n byteLength: bytes.byteLength,\n mediaType: mediaTypeByRole[role],\n };\n });\n if (\n requiredRoles.some((role) => !nonReportArtifacts.some((artifact) => artifact.role === role))\n ) {\n throw new Error(\n 'preview publication is missing capture, fresh-replay, tape, or profile artifact',\n );\n }\n let report: ResourcePreviewReport | undefined;\n let reportBytes: Uint8Array | undefined;\n if (reportInput !== undefined) {\n if (reportInput.snapshot.digest !== result.manifest.identity.snapshotDigest) {\n throw new Error('preview report snapshot identity does not match the artifact manifest');\n }\n report = createResourcePreviewReport({\n runId,\n snapshot: reportInput.snapshot,\n subject: reportInput.subject,\n presentation: reportInput.presentation,\n oracle: reportInput.oracle,\n artifacts: nonReportArtifacts,\n });\n reportBytes = new TextEncoder().encode(JSON.stringify(report));\n }\n const reportArtifact: PreviewArtifactManifestEntry | undefined =\n reportBytes === undefined\n ? undefined\n : {\n owner: 'resource-preview',\n kind: 'report',\n role: 'report',\n uri: projectUri(projectRoot, finalPaths.report),\n digest: sha256(reportBytes),\n byteLength: reportBytes.byteLength,\n mediaType: 'application/vnd.forgeax.resource-preview+json',\n derivedFrom: nonReportArtifacts.map((artifact) => artifact.digest),\n };\n const manifest = createPreviewArtifactManifest({\n ...result.manifest,\n artifacts:\n reportArtifact === undefined ? nonReportArtifacts : [reportArtifact, ...nonReportArtifacts],\n });\n const validated = validatePreviewArtifactManifest(\n manifest,\n reportArtifact === undefined ? requiredRoles : ['report', ...requiredRoles],\n );\n if (!validated.ok) throw new Error(JSON.stringify(validated.error.detail));\n const staging = await mkdtemp(join(runsRoot, '.staging-'));\n const paths = {\n tapeJson: join(staging, 'rhi-tape.json'),\n tapeBlob: join(staging, 'rhi-tape.bin'),\n capturePng: join(staging, 'capture.png'),\n freshReplayPng: join(staging, 'fresh-replay.png'),\n profile: join(staging, 'profile.json'),\n manifest: join(staging, 'manifest.json'),\n report: join(staging, 'report.json'),\n };\n try {\n await Promise.all([\n writeFile(paths.tapeJson, tapeJson),\n writeFile(paths.tapeBlob, tapeBlob),\n writeFile(paths.capturePng, capturePng),\n writeFile(paths.freshReplayPng, freshReplayPng),\n writeFile(paths.profile, profile),\n ...(reportBytes === undefined ? [] : [writeFile(paths.report, reportBytes)]),\n ]);\n await writeFile(paths.manifest, `${JSON.stringify(manifest, null, 2)}\\n`);\n await rename(staging, published);\n } catch (cause) {\n await rm(staging, { recursive: true, force: true });\n throw cause;\n }\n return {\n ...result,\n tape: {\n ...result.tape,\n jsonUri: projectUri(projectRoot, finalPaths.tapeJson),\n blobUri: projectUri(projectRoot, finalPaths.tapeBlob),\n },\n profile: { ...result.profile, uri: projectUri(projectRoot, finalPaths.profile) },\n capturePng: { ...result.capturePng, uri: projectUri(projectRoot, finalPaths.capturePng) },\n png: { ...result.png, uri: projectUri(projectRoot, finalPaths.freshReplayPng) },\n manifest,\n artifacts: manifest.artifacts.map(artifactRef),\n };\n}\n\nfunction browserFailure(\n phase: string,\n cause: unknown,\n pageErrors: readonly string[] = [],\n): BrowserHostResult {\n return {\n ok: false,\n error: {\n code: 'tool-preview-browser-host-failed',\n expected: 'a real Chromium page, project bootstrap, WebGPU device, and bounded preview run',\n hint: 'Inspect the Browser Host phase and repair the project or local WebGPU capability.',\n detail: {\n phase,\n cause: transportCause(cause),\n pageErrors,\n },\n },\n };\n}\n\nexport async function runBrowserPreviewHost(\n projectRoot: string,\n recipe: ToolPreviewRecipe,\n snapshot: SnapshotRef,\n runId: string,\n signal: AbortSignal,\n bootstrapRoot: BootstrapRoot = 'project-bootstrap',\n resource?: ToolPreviewResourceRequest,\n options: BrowserHostOptions = {},\n): Promise<BrowserHostResult> {\n const facts = await readProjectFacts(projectRoot);\n if (!facts.ok)\n return { ok: false, error: { ...facts.error, detail: facts.error.detail as never } };\n const config = await createViteConfig(facts.value, 'serve', '/', { bootstrapRoot });\n // A Browser Host is a disposable Vite realm. A shared cache lets adjacent\n // coverage groups observe a partially-written optimized dependency graph.\n // Keep the cache inside the project lifecycle and remove it with the Host.\n const cacheDir = await mkdtemp(join(facts.value.root, '.forgeax', '.browser-host-vite-'));\n let server: ViteDevServer;\n try {\n const port = await allocateLoopbackPort();\n server = await createServer({\n ...config,\n cacheDir,\n logLevel: 'silent',\n optimizeDeps: {\n ...config.optimizeDeps,\n // Tool runs must observe the current workspace build, even when a\n // persistent runner retains Vite's optimized-dependency cache.\n force: true,\n },\n server: {\n ...config.server,\n host: '127.0.0.1',\n port,\n // Vite's port 0 means its default 5173. Bind the probed port exactly so\n // another project or runner cannot be mistaken for this Browser Host.\n strictPort: true,\n },\n });\n } catch (cause) {\n await rm(cacheDir, { recursive: true, force: true });\n throw cause;\n }\n const hostStartedAtMs = performance.now();\n let phase = 'server-listen';\n let browser: Browser | undefined;\n let page: Page | undefined;\n let pageErrors: string[] = [];\n let responseDiagnostics: Promise<void>[] = [];\n const launchBrowser = (headless: boolean): Promise<Browser> =>\n chromium.launch({\n channel: process.env.FORGEAX_CHROME_CHANNEL ?? 'chrome',\n headless,\n args: [\n '--enable-unsafe-webgpu',\n '--enable-features=Vulkan,UseSkiaRenderer,SharedArrayBuffer',\n '--use-vulkan=swiftshader',\n '--use-angle=swiftshader',\n '--disable-vulkan-surface',\n '--ignore-gpu-blocklist',\n '--disable-gpu-driver-bug-workarounds',\n '--disable-dawn-features=disallow_unsafe_apis',\n '--autoplay-policy=no-user-gesture-required',\n ],\n });\n const observePage = (target: Page): void => {\n target.on('pageerror', (error) => pageErrors.push(error.message));\n target.on('console', (message) => {\n if (message.type() === 'error' || message.type() === 'warning') {\n pageErrors.push(`${message.type()}: ${message.text()}`);\n }\n });\n target.on('response', (response) => {\n if (response.status() >= 400) {\n responseDiagnostics.push(\n response\n .text()\n .then((body) => {\n pageErrors.push(`HTTP ${response.status()}: ${response.url()} ${body}`);\n })\n .catch(() => {\n pageErrors.push(`HTTP ${response.status()}: ${response.url()}`);\n }),\n );\n }\n });\n };\n const closeBrowserProcess = async (): Promise<void> => {\n await page?.close().catch(() => undefined);\n page = undefined;\n await browser?.close().catch(() => undefined);\n browser = undefined;\n };\n const abort = (): void => {\n void closeBrowserProcess();\n void server.close();\n };\n signal.addEventListener('abort', abort, { once: true });\n try {\n if (signal.aborted) throw new Error('Browser Host aborted before launch');\n await server.listen();\n const address = server.httpServer?.address() as AddressInfo | null | undefined;\n if (address === null || address === undefined || typeof address === 'string') {\n throw new Error('Vite Browser Host did not expose a loopback TCP address');\n }\n\n phase = 'server-transform';\n const entryTransform = await server.transformRequest('/main.ts');\n if (entryTransform === null) {\n throw new Error('Vite Browser Host entry transform returned no module');\n }\n\n phase = 'capture-browser-launch';\n browser = await launchBrowser(recipe.presentation === 'hidden');\n phase = 'capture-page-bootstrap';\n page = await browser.newPage({\n viewport: recipe.viewport,\n deviceScaleFactor: 1,\n });\n observePage(page);\n const captureUrl = new URL(`http://127.0.0.1:${address.port}/`);\n captureUrl.searchParams.set('forgeax-tool-recipe', JSON.stringify(recipe));\n captureUrl.searchParams.set('forgeax-tool-snapshot', JSON.stringify(snapshot));\n captureUrl.searchParams.set('forgeax-tool-run-id', runId);\n if (resource !== undefined)\n captureUrl.searchParams.set('forgeax-resource-preview', JSON.stringify(resource));\n await page.goto(captureUrl.href, { waitUntil: 'networkidle', timeout: 45_000 });\n await page.waitForFunction(\n () =>\n (\n globalThis as unknown as {\n __forgeaxToolHost?: { readonly ready?: boolean };\n }\n ).__forgeaxToolHost?.ready === true,\n undefined,\n { timeout: 45_000 },\n );\n phase = 'capture-run';\n const captured = await page.evaluate(async () => {\n const host = (\n globalThis as unknown as {\n __forgeaxToolHost: {\n capture(): Promise<\n | { readonly ok: true; readonly result: ToolPreviewCaptureResult }\n | { readonly ok: false; readonly error: ToolDomainFailure }\n >;\n };\n }\n ).__forgeaxToolHost;\n const value = await host.capture();\n return JSON.parse(\n JSON.stringify(value, (_key, nested) =>\n nested instanceof Error\n ? {\n ...nested,\n name: nested.name,\n message: nested.message,\n stack: nested.stack,\n }\n : nested,\n ),\n ) as Awaited<ReturnType<typeof host.capture>>;\n });\n await Promise.all(responseDiagnostics);\n if (!captured.ok) return browserFailure('capture-run', captured.error, pageErrors);\n if (pageErrors.length > 0)\n return browserFailure('capture-page-runtime', pageErrors[0], pageErrors);\n const capturePng = await page.screenshot({ type: 'png' });\n const capturedResult: ToolPreviewCaptureResult = {\n ...captured.result,\n capturePng: {\n uri: `data:image/png;base64,${capturePng.toString('base64')}`,\n width: recipe.viewport.width,\n height: recipe.viewport.height,\n },\n };\n\n await closeBrowserProcess();\n pageErrors = [];\n responseDiagnostics = [];\n\n phase = 'replay-browser-launch';\n browser = await launchBrowser(true);\n phase = 'replay-page-bootstrap';\n page = await browser.newPage({\n viewport: recipe.viewport,\n deviceScaleFactor: 1,\n });\n observePage(page);\n const replayUrl = new URL(`http://127.0.0.1:${address.port}/`);\n replayUrl.searchParams.set('forgeax-tool-replay', '1');\n await page.goto(replayUrl.href, { waitUntil: 'networkidle', timeout: 45_000 });\n await page.waitForFunction(\n () =>\n (\n globalThis as unknown as {\n __forgeaxToolReplayHost?: { readonly ready?: boolean };\n }\n ).__forgeaxToolReplayHost?.ready === true,\n undefined,\n { timeout: 45_000 },\n );\n phase = 'replay-run';\n const result = (await page.evaluate(async (serializedCapture: string): Promise<unknown> => {\n const host = (\n globalThis as unknown as {\n __forgeaxToolReplayHost: {\n run(value: ToolPreviewCaptureResult): Promise<unknown>;\n };\n }\n ).__forgeaxToolReplayHost;\n const value = await host.run(JSON.parse(serializedCapture) as ToolPreviewCaptureResult);\n return JSON.parse(\n JSON.stringify(value, (_key, nested) =>\n nested instanceof Error\n ? {\n ...nested,\n name: nested.name,\n message: nested.message,\n stack: nested.stack,\n }\n : nested,\n ),\n ) as unknown;\n }, JSON.stringify(capturedResult))) as\n | { readonly ok: true; readonly result: PreviewHostResult }\n | { readonly ok: false; readonly error: ToolDomainFailure };\n await Promise.all(responseDiagnostics);\n if (!result.ok) return browserFailure('replay-run', result.error, pageErrors);\n if (pageErrors.length > 0)\n return browserFailure('replay-page-runtime', pageErrors[0], pageErrors);\n\n const endedAtMs = performance.now();\n const phases = result.result.operationTiming.phases;\n const observedDurationMs =\n phases === undefined\n ? 0\n : Object.values(phases).reduce(\n (total, observation) =>\n total + (observation.status === 'observed' ? observation.durationMs : 0),\n 0,\n );\n const durationMs = endedAtMs - hostStartedAtMs;\n const value: PreviewHostResult = {\n ...result.result,\n operationTiming: {\n ...result.result.operationTiming,\n startedAtMs: hostStartedAtMs,\n endedAtMs,\n durationMs,\n ...(phases === undefined\n ? { unattributedMs: durationMs }\n : {\n phases: {\n ...phases,\n transport: {\n status: 'observed',\n durationMs: Math.max(0, durationMs - observedDurationMs),\n },\n },\n unattributedMs: 0,\n }),\n },\n actualCarrier: recipe.presentation === 'hidden' ? 'headless-private' : 'headed-private',\n };\n phase = 'artifact-publish';\n return {\n ok: true,\n value:\n options.publish === false\n ? value\n : await publishPreviewArtifacts(projectRoot, runId, value),\n };\n } catch (cause) {\n await Promise.all(responseDiagnostics);\n return browserFailure(phase, cause, pageErrors);\n } finally {\n signal.removeEventListener('abort', abort);\n await closeBrowserProcess();\n await server.close().catch(() => undefined);\n await rm(cacheDir, { recursive: true, force: true });\n }\n}\n\nexport function runBrowserResourcePreviewHost(\n projectRoot: string,\n recipe: ToolPreviewRecipe,\n snapshot: SnapshotRef,\n runId: string,\n signal: AbortSignal,\n resource: ToolPreviewResourceRequest,\n options: BrowserHostOptions = {},\n): Promise<BrowserHostResult> {\n return runBrowserPreviewHost(\n projectRoot,\n recipe,\n snapshot,\n runId,\n signal,\n 'resource-bootstrap',\n resource,\n options,\n );\n}\n","import { createToolPreviewRecipe } from '@forgeax/engine-app';\nimport { Context } from '@forgeax/engine-plugin';\nimport {\n createContextCapabilityResolver,\n installCatalogLoader,\n projectPluginEntries,\n} from '@forgeax/engine-plugin/loader';\nimport { createNativePreviewHost, RESOURCE_PREVIEW_DEFAULT_SIZE } from '@forgeax/engine-preview';\nimport {\n createToolRuntime,\n type ToolContribution,\n type ToolRunOptions,\n type ToolTerminal,\n} from '@forgeax/engine-tool-runtime';\nimport {\n publishPreviewArtifacts,\n type ResourcePreviewReportInput,\n runBrowserResourcePreviewHost,\n} from './browser-host.js';\nimport {\n createNativePreviewCatalog,\n nativePreviewPlugins,\n nativePreviewTools,\n} from './preview-catalog.js';\n\nconst previewPluginEntries = nativePreviewPlugins.map(([name]) => ({\n id: `forgeax-preview-${name.slice(name.lastIndexOf('/') + 1)}`,\n name,\n realm: 'host' as const,\n}));\nconst previewToolIds = new Set(nativePreviewTools.map(({ descriptor }) => descriptor.id));\n\nexport function isNativePreviewTool(id: string): boolean {\n return previewToolIds.has(id);\n}\n\nexport async function runNativePreviewTool(\n contribution: ToolContribution<unknown, unknown>,\n args: unknown,\n options: ToolRunOptions,\n projectRoot: string,\n): Promise<ToolTerminal<unknown>> {\n const kind = contribution.descriptor.id.split('.')[0];\n if (kind !== 'material' && kind !== 'mesh' && kind !== 'texture' && kind !== 'vfx') {\n throw new Error(`unsupported native preview operation ${contribution.descriptor.id}`);\n }\n const parsed = contribution.descriptor.argsSchema.parse(args);\n if (!parsed.ok) {\n return {\n outcome: 'failed',\n failure: {\n code: 'tool-invalid-args',\n expected: 'preview arguments to match the operation argsSchema',\n hint: 'Pass { guid } and an optional power-of-two size from AssetRegistry catalog identity.',\n detail: { message: parsed.error, value: null },\n },\n artifacts: [],\n };\n }\n const request = parsed.value as { readonly guid: string; readonly size?: number };\n const { guid, size = RESOURCE_PREVIEW_DEFAULT_SIZE } = request;\n const selectedPreviewPlugin = nativePreviewPlugins.find(([, plugin]) =>\n plugin.tools.some(\n (tool: ToolContribution<unknown, unknown>) =>\n tool.descriptor.id === contribution.descriptor.id,\n ),\n );\n if (selectedPreviewPlugin === undefined) {\n throw new Error(`native preview plugin does not export ${contribution.descriptor.id}`);\n }\n const selectedPluginName = selectedPreviewPlugin[0];\n const snapshot = options.snapshot ?? { revision: 0, digest: `sha256:project:${projectRoot}` };\n const previewRunId = `${contribution.descriptor.id}:${crypto.randomUUID()}`;\n const browser = await runBrowserResourcePreviewHost(\n projectRoot,\n createToolPreviewRecipe({\n presentation: 'hidden',\n viewport: { width: size, height: size },\n frames: 32,\n }),\n snapshot,\n previewRunId,\n options.signal ?? new AbortController().signal,\n { kind, guid, size },\n { publish: false },\n );\n if (!browser.ok || browser.value.resource === undefined) {\n const failure = browser.ok\n ? {\n code: 'tool-preview-bootstrap-failed',\n expected: 'the Browser resource bootstrap to return AssetRegistry owner facts',\n hint: 'Inspect resource-bootstrap and retry after the owner publishes the GUID payload.',\n detail: { phase: 'resource-owner' },\n }\n : browser.error;\n return {\n outcome: 'failed',\n failure: {\n code: 'tool-domain-failed',\n expected: failure.expected ?? 'the Browser resource bootstrap to succeed',\n hint: failure.hint ?? 'Inspect the Browser resource bootstrap failure and retry.',\n detail: {\n code: failure.code,\n ...(failure.detail === undefined ? {} : { payload: failure.detail }),\n },\n },\n artifacts: [],\n };\n }\n const resource = browser.value.resource;\n const subjectDrawn =\n kind === 'texture' ? browser.value.drawCalls > 0 : browser.value.drawCalls > 2;\n if (!subjectDrawn) {\n return {\n outcome: 'failed',\n failure: {\n code: 'tool-domain-failed',\n expected:\n 'the captured resource frame to contain a subject draw in addition to canonical presentation passes',\n hint: 'Inspect material readiness and the RHI tape before retrying the same GUID preview.',\n detail: {\n code: 'tool-preview-subject-not-rendered',\n payload: { kind, drawCalls: browser.value.drawCalls },\n },\n },\n artifacts: [],\n };\n }\n const ctx = new Context();\n try {\n const host = createNativePreviewHost({\n runId: `${contribution.descriptor.id}:native`,\n snapshot,\n projectRoot,\n backend: 'webgpu',\n signal: options.signal ?? new AbortController().signal,\n assets: {\n loadByGuid: async <TAsset>() => ({\n ok: true as const,\n value: resource.asset as TAsset,\n ...(resource.digest === undefined ? {} : { digest: resource.digest }),\n ...(resource.ownerFacts === undefined ? {} : { ownerFacts: resource.ownerFacts }),\n }),\n },\n renderer: {\n rendererReady: browser.value.trace.events.includes('renderer-created'),\n worldReady: browser.value.trace.events.includes('world-updated'),\n drawCalls: browser.value.drawCalls,\n nonBlackPixels: browser.value.nonBlackPixels,\n ...(resource.observation === undefined ? {} : { observation: resource.observation }),\n ...(kind === 'vfx' && resource.observation !== undefined\n ? {\n vfx: {\n dispatches:\n typeof resource.observation.dispatches === 'number'\n ? resource.observation.dispatches\n : 0,\n indirectDraws:\n typeof resource.observation.indirectDraws === 'number'\n ? resource.observation.indirectDraws\n : 0,\n subjectOutputs:\n typeof resource.observation.subjectOutputs === 'number'\n ? resource.observation.subjectOutputs\n : 0,\n },\n }\n : {}),\n texture: { drawCalls: browser.value.drawCalls },\n },\n artifacts: browser.value.artifacts,\n });\n const { loader } = await installCatalogLoader(\n ctx,\n createNativePreviewCatalog(host, selectedPluginName),\n 'host',\n );\n await loader.root.update(\n projectPluginEntries(\n previewPluginEntries.filter(({ name }) => name === selectedPluginName),\n 'host',\n 'host',\n ),\n );\n await loader.await();\n const nativeContribution = nativePreviewTools.find(\n (candidate) => candidate.descriptor.id === contribution.descriptor.id,\n );\n if (nativeContribution === undefined) {\n throw new Error(`native preview plugin does not export ${contribution.descriptor.id}`);\n }\n const terminal = await createToolRuntime([nativeContribution]).run(nativeContribution, args, {\n ...options,\n snapshot,\n capabilityResolver: createContextCapabilityResolver(ctx),\n }).terminal;\n if (terminal.outcome !== 'succeeded') return terminal;\n const domainResult = terminal.result as {\n readonly subject: ResourcePreviewReportInput['subject'];\n readonly presentation: ResourcePreviewReportInput['presentation'];\n readonly oracle: ResourcePreviewReportInput['oracle'];\n };\n let published: Awaited<ReturnType<typeof publishPreviewArtifacts>>;\n try {\n published = await publishPreviewArtifacts(projectRoot, previewRunId, browser.value, {\n snapshot,\n subject: domainResult.subject,\n presentation: domainResult.presentation,\n oracle: domainResult.oracle,\n });\n } catch (cause) {\n return {\n outcome: 'failed',\n failure: {\n code: 'tool-domain-failed',\n expected: 'the preview report and all capture artifacts to publish atomically',\n hint: 'Inspect the artifact manifest identity or digest failure and retry the same ToolRun.',\n detail: {\n code: 'tool-artifact-manifest-invalid',\n payload: cause instanceof Error ? cause.message : String(cause),\n },\n },\n artifacts: [],\n };\n }\n const report = published.manifest.artifacts.find((artifact) => artifact.role === 'report');\n if (report === undefined) {\n throw new Error('resource preview publisher returned no report artifact');\n }\n return {\n ...terminal,\n result: {\n ...(terminal.result as Record<string, unknown>),\n actualCarrier: browser.value.actualCarrier,\n report: {\n kind: 'tool-result' as const,\n digest: report.digest,\n uri: report.uri,\n mediaType: report.mediaType,\n sizeBytes: report.byteLength,\n },\n artifacts: published.artifacts,\n },\n artifacts: published.artifacts,\n };\n } finally {\n await ctx.fiber.dispose();\n }\n}\n","export {\n assetAddCommand,\n assetInspectCommand,\n assetListCommand,\n assetVerifyCommand,\n browserCaptureCommand,\n buildCommand,\n createCliRhiDebugOperationContext,\n devCommand,\n doctorCommand,\n engineDoctorCommand,\n engineStatusCommand,\n engineUnlinkCommand,\n engineUseLocalCommand,\n initCommand,\n newCommand,\n packageCommand,\n pluginInstallCommand,\n pluginUninstallCommand,\n previewCommand,\n runRhiDebugCommand,\n sdkInstallCommand,\n shaderCheckCommand,\n skillInstallCommand,\n skillVerifyCommand,\n softwareCaptureCommand,\n testCommand,\n} from './commands.js';\nexport { verifyDist, writeDistManifest } from './dist.js';\nexport type {\n EngineBinding,\n EngineBindingCommandOptions,\n EngineBindingMode,\n EnginePackageStatus,\n EngineStatusReport,\n EngineWorkspaceStatus,\n} from './engine-binding.js';\nexport {\n ENGINE_BINDING_SCHEMA_VERSION,\n engineBindingFilePath,\n inspectEngineWorkspace,\n readEngineBinding,\n} from './engine-binding.js';\nexport type { BootstrapRoot } from './host/base-host.js';\nexport type { ProjectBootstrapPlan } from './host/project-bootstrap.js';\nexport type {\n ResourceBootstrapPlan,\n ResourceBootstrapTrace,\n} from './host/resource-bootstrap.js';\nexport { createInitPlan } from './init.js';\nexport { readProjectFacts } from './project.js';\nexport type {\n ArtifactRef,\n CapturedRhiTape,\n RhiCaptureFrameValue,\n RhiDebugOperationContext,\n RhiDebugOperationDescriptor,\n RhiDebugOperationInput,\n RhiDebugOperationName,\n RhiDebugOperationOutput,\n RhiInspectInput,\n RhiInspectOutput,\n RhiSummaryInput,\n RhiSummaryOutput,\n} from './rhi-debug/operations.js';\nexport {\n createRhiDebugOperationContext,\n discoverRhiDebugOperations,\n RHI_DEBUG_OPERATION_MANIFEST,\n recoverRhiDebugError,\n renderRhiDebugHelp,\n runRhiDebugOperation,\n} from './rhi-debug/operations.js';\nexport type {\n SingleHtmlBundle,\n SingleHtmlBundleArtifact,\n SingleHtmlPackageOptions,\n SingleHtmlPackageResult,\n} from './single-html.js';\nexport {\n bundleSingleHtmlEntry,\n packageFormatError,\n packageOutputError,\n writeSingleHtml,\n} from './single-html.js';\nexport type {\n BrowserCapture,\n BrowserCaptureCheckpointOptions,\n BrowserCaptureOpenOptions,\n BrowserCaptureRecord,\n BrowserCaptureRequestReport,\n BrowserCaptureRequestWitness,\n BrowserCaptureRunReport,\n BrowserCaptureRuntimeWitness,\n BrowserCaptureTarget,\n BrowserLaunchProfile,\n CapturePixelWitness,\n SoftwareBrowser,\n SoftwareBrowserOpenOptions,\n SoftwareBrowserSession,\n SoftwareCaptureCheckpointOptions,\n SoftwareCaptureRecord,\n SoftwareCaptureRequestReport,\n SoftwareCaptureRequestWitness,\n SoftwareCaptureRunReport,\n SoftwareCaptureRuntimeWitness,\n} from './software-capture.js';\nexport { createBrowserCapture, createSoftwareBrowser } from './software-capture.js';\nexport {\n type AdmissionThresholds,\n type BenchmarkAdmissionReport,\n type BenchmarkMeasurement,\n type BenchmarkRecipe,\n type BenchmarkSample,\n createAdmissionReport,\n DEFAULT_ADMISSION_THRESHOLDS,\n runBenchmarkAdmission,\n summarizeBenchmarkSamples,\n} from './tools/benchmark/index.js';\nexport {\n bootstrapRealm,\n type RealmBootstrapInput,\n type RealmBootstrapResult,\n type RealmLifecycleAdapter,\n type RealmLifecycleHandle,\n} from './tools/bootstrap.js';\nexport { createServiceCache, type ServiceCache, type ServiceCacheEntry } from './tools/cache.js';\nexport {\n createServiceCapability,\n type ServiceAdmissionExpectation,\n type ServiceAdmissionRef,\n type ServiceCapability,\n} from './tools/capability.js';\nexport {\n type CarrierProvider,\n type CarrierProviderService,\n type CarrierProviderServiceOptions,\n createCarrierProvider,\n createCarrierProviderService,\n} from './tools/carrier-provider.js';\nexport {\n type CarrierRendezvous,\n type CarrierRendezvousOptions,\n createCarrierRendezvous,\n} from './tools/carrier-rendezvous.js';\nexport {\n describeTool,\n listTools,\n materializeToolCatalog,\n rebuildToolCatalog,\n} from './tools/catalog.js';\nexport { runGenericTool, runNamedTool } from './tools/cli-adapter.js';\nexport {\n createToolClient,\n type ToolClient,\n type ToolClientOptions,\n} from './tools/client.js';\nexport type { ForgeaXExecContext } from './tools/commands.js';\nexport {\n createAuthorContribution,\n createBuildContribution,\n createDefaultContributions,\n} from './tools/contributions.js';\nexport { runLibraryTool } from './tools/library.js';\nexport {\n createCapabilityToken,\n createMigrationRecipe,\n createMigrationRoster,\n type MigrationCapabilityProbe,\n type MigrationOperation,\n type MigrationPath,\n type MigrationRecipe,\n type MigrationResolution,\n type MigrationResolutionResult,\n type MigrationRosterEntry,\n type MigrationTarget,\n probeMigrationTarget,\n resolveMigration,\n} from './tools/migration.js';\nexport {\n analyzePreviewArtifacts,\n type OfflineAnalysisRequest,\n type OfflineAnalysisResult,\n} from './tools/offline-analysis.js';\nexport {\n createOfflineAnalysisContribution,\n createPreviewContribution,\n createPreviewContributions,\n} from './tools/preview-contributions.js';\nexport {\n type PreviewCarrierRoute,\n type PreviewHostRequest,\n type PreviewHostResult,\n type PreviewHostRunner,\n runCarrierPreviewRoute,\n runPreviewHost,\n} from './tools/preview-host.js';\nexport { runPrivateTool } from './tools/private-executor.js';\nexport {\n createRealmCapabilityMatrix,\n createResourceProbe,\n type RealmCapability,\n type RealmCapabilityInput,\n type RealmCapabilityMatrix,\n type ResourceOwner,\n resolveRealmCapability,\n} from './tools/realms.js';\nexport { createDevkitToolRuntime, createPreviewToolRuntime } from './tools/runtime.js';\nexport {\n createServiceExecutor,\n type ServiceExecutor,\n type ServiceExecutorOptions,\n} from './tools/service.js';\nexport {\n type AuthenticatedLoopbackService,\n type AuthenticatedLoopbackServiceOptions,\n type AuthenticatedLoopbackTransport,\n type AuthenticatedLoopbackTransportOptions,\n createAuthenticatedLoopbackService,\n createAuthenticatedLoopbackTransport,\n type ServiceWireHandler,\n type ServiceWireRequest,\n} from './tools/service-transport.js';\nexport type {\n AssetAddOptions,\n AssetInspectOptions,\n BrowserCaptureOptions,\n BuildOptions,\n CaptureBackend,\n CommandEnvelope,\n CommandError,\n CommandResult,\n ForgeaXCommand,\n InitOptions,\n NewOptions,\n PackageFormat,\n PackageOptions,\n PluginInstallOptions,\n PluginUninstallOptions,\n ProjectCommandOptions,\n ProjectFacts,\n ShaderCheckOptions,\n SoftwareCaptureOptions,\n} from './types.js';\nexport { resolveProjectPort } from './types.js';\n","export interface SampleStatistics {\n readonly count: number;\n readonly median: number;\n readonly p95: number;\n readonly max: number;\n}\n\nexport function calculateSampleStatistics(samples: readonly number[]): SampleStatistics {\n if (samples.length === 0) throw new RangeError('benchmark samples must not be empty');\n const sorted = [...samples].sort((left, right) => left - right);\n const medianIndex = (sorted.length - 1) / 2;\n const median = interpolate(sorted, medianIndex);\n const p95 = interpolate(sorted, Math.ceil(sorted.length * 0.95) - 1);\n const max = sorted[sorted.length - 1];\n if (max === undefined) throw new RangeError('benchmark samples must not be empty');\n return { count: sorted.length, median, p95, max };\n}\n\nfunction interpolate(values: readonly number[], index: number): number {\n const lower = Math.floor(index);\n const upper = Math.ceil(index);\n const lowerValue = values[lower];\n const upperValue = values[upper];\n if (lowerValue === undefined || upperValue === undefined) {\n throw new RangeError('benchmark percentile index is out of range');\n }\n return lower === upper ? lowerValue : lowerValue + (upperValue - lowerValue) * (index - lower);\n}\n","import { calculateSampleStatistics, type SampleStatistics } from './statistics.js';\n\nexport interface BenchmarkRecipe {\n readonly snapshotDigest: string;\n readonly backend: string;\n readonly viewport: readonly [number, number];\n readonly inputDigest: string;\n readonly frameCount: number;\n readonly rhiDebug: boolean;\n readonly profiler: boolean;\n readonly carrierRendezvous: boolean;\n readonly digest: string;\n}\n\nexport interface BenchmarkSample {\n readonly mode: 'private' | 'service';\n readonly phase: 'cold' | 'warm';\n readonly durationMs: number;\n readonly peakRssBytes: number;\n readonly exclusivePhasesMs: Readonly<Record<string, number>>;\n readonly rhiDebugOverheadMs: number;\n readonly carrierRendezvousMs: number;\n readonly cleanupPassed: boolean;\n readonly evictionPassed: boolean;\n readonly recipeDigest: string;\n}\n\nexport interface BenchmarkModeReport {\n readonly samples: number;\n readonly durationMs: SampleStatistics;\n readonly peakRssBytes: SampleStatistics;\n readonly cleanupPassed: boolean;\n readonly evictionPassed: boolean;\n readonly exclusivePhasesMs: Readonly<Record<string, SampleStatistics>>;\n}\n\nexport interface AdmissionThresholds {\n readonly sampleCountPerPhase: number;\n readonly medianImprovement: number;\n readonly p95Improvement: number;\n readonly maxRegression: number;\n readonly peakRssMultiplier: number;\n}\n\nexport const DEFAULT_ADMISSION_THRESHOLDS: AdmissionThresholds = {\n sampleCountPerPhase: 30,\n medianImprovement: 0.2,\n p95Improvement: 0.1,\n maxRegression: 0.1,\n peakRssMultiplier: 1.25,\n};\n\nexport interface BenchmarkAdmissionReport {\n readonly schema: 'forgeax.tool-service-admission.v1';\n readonly recipe: BenchmarkRecipe;\n readonly thresholds: AdmissionThresholds;\n readonly order: readonly BenchmarkSample['mode'][];\n readonly private: BenchmarkModeReport;\n readonly service: BenchmarkModeReport;\n readonly valid: boolean;\n readonly admitted: boolean;\n readonly reasons: readonly string[];\n}\n\nexport function summarizeBenchmarkSamples(\n samples: readonly BenchmarkSample[],\n): BenchmarkModeReport {\n if (samples.length === 0) {\n return {\n samples: 0,\n durationMs: { count: 0, median: 0, p95: 0, max: 0 },\n peakRssBytes: { count: 0, median: 0, p95: 0, max: 0 },\n cleanupPassed: false,\n evictionPassed: false,\n exclusivePhasesMs: {},\n };\n }\n const durations = samples.map((sample) => sample.durationMs);\n const rss = samples.map((sample) => sample.peakRssBytes);\n const phaseNames = [\n ...new Set(samples.flatMap((sample) => Object.keys(sample.exclusivePhasesMs))),\n ];\n const exclusivePhasesMs = Object.fromEntries(\n phaseNames.map((phase) => [\n phase,\n calculateSampleStatistics(samples.map((sample) => sample.exclusivePhasesMs[phase] ?? 0)),\n ]),\n );\n return {\n samples: samples.length,\n durationMs: calculateSampleStatistics(durations),\n peakRssBytes: calculateSampleStatistics(rss),\n cleanupPassed: samples.every((sample) => sample.cleanupPassed),\n evictionPassed: samples.every((sample) => sample.evictionPassed),\n exclusivePhasesMs,\n };\n}\n\nexport function createAdmissionReport(\n recipe: BenchmarkRecipe,\n samples: readonly BenchmarkSample[],\n thresholds: AdmissionThresholds = DEFAULT_ADMISSION_THRESHOLDS,\n): BenchmarkAdmissionReport {\n const privateSamples = samples.filter((sample) => sample.mode === 'private');\n const serviceSamples = samples.filter((sample) => sample.mode === 'service');\n const order = samples.map((sample) => sample.mode);\n const privateReport = summarizeBenchmarkSamples(privateSamples);\n const serviceReport = summarizeBenchmarkSamples(serviceSamples);\n const reasons: string[] = [];\n const expectedSamples = thresholds.sampleCountPerPhase * 2;\n const complete =\n privateSamples.length === expectedSamples && serviceSamples.length === expectedSamples;\n if (!complete) {\n reasons.push('sample count is incomplete');\n }\n if (samples.some((sample) => sample.recipeDigest !== recipe.digest)) {\n reasons.push('recipe identity drifted');\n }\n if (!privateReport.cleanupPassed || !serviceReport.cleanupPassed) reasons.push('cleanup failed');\n if (!privateReport.evictionPassed || !serviceReport.evictionPassed)\n reasons.push('eviction failed');\n if (order.some((mode, index) => index > 0 && mode === order[index - 1])) {\n reasons.push('private and service samples were not alternated');\n }\n const medianLimit = privateReport.durationMs.median * (1 - thresholds.medianImprovement);\n const p95Limit = privateReport.durationMs.p95 * (1 - thresholds.p95Improvement);\n const maxLimit = privateReport.durationMs.max * (1 + thresholds.maxRegression);\n const rssLimit = privateReport.peakRssBytes.median * thresholds.peakRssMultiplier;\n if (complete && serviceReport.durationMs.median > medianLimit)\n reasons.push('median improvement threshold missed');\n if (complete && serviceReport.durationMs.p95 > p95Limit)\n reasons.push('p95 improvement threshold missed');\n if (complete && serviceReport.durationMs.max > maxLimit)\n reasons.push('max regression threshold exceeded');\n if (complete && serviceReport.peakRssBytes.median > rssLimit)\n reasons.push('peak RSS threshold exceeded');\n return {\n schema: 'forgeax.tool-service-admission.v1',\n recipe,\n thresholds,\n order,\n private: privateReport,\n service: serviceReport,\n valid:\n complete &&\n !reasons.some((reason) =>\n [\n 'recipe identity drifted',\n 'cleanup failed',\n 'eviction failed',\n 'private and service samples were not alternated',\n ].includes(reason),\n ),\n admitted: reasons.length === 0,\n reasons,\n };\n}\n","import {\n type AdmissionThresholds,\n type BenchmarkAdmissionReport,\n type BenchmarkRecipe,\n type BenchmarkSample,\n createAdmissionReport,\n} from './report.js';\n\nexport interface BenchmarkMeasurement {\n readonly durationMs: number;\n readonly peakRssBytes: number;\n readonly exclusivePhasesMs?: Readonly<Record<string, number>>;\n readonly rhiDebugOverheadMs?: number;\n readonly carrierRendezvousMs?: number;\n readonly cleanupPassed: boolean;\n readonly evictionPassed: boolean;\n}\n\nexport interface BenchmarkHarnessOptions {\n readonly recipe: BenchmarkRecipe;\n readonly measure: (\n mode: BenchmarkSample['mode'],\n phase: BenchmarkSample['phase'],\n index: number,\n ) => Promise<BenchmarkMeasurement> | BenchmarkMeasurement;\n readonly thresholds?: AdmissionThresholds;\n}\n\nexport async function runBenchmarkAdmission(\n options: BenchmarkHarnessOptions,\n): Promise<BenchmarkAdmissionReport> {\n const sampleCount = options.thresholds?.sampleCountPerPhase ?? 30;\n const samples: BenchmarkSample[] = [];\n const phases = ['cold', 'warm'] as const satisfies readonly BenchmarkSample['phase'][];\n const modes = ['private', 'service'] as const satisfies readonly BenchmarkSample['mode'][];\n for (const phase of phases) {\n for (let index = 0; index < sampleCount; index += 1) {\n for (const mode of modes) {\n const measurement = await options.measure(mode, phase, index);\n samples.push({\n mode,\n phase,\n durationMs: measurement.durationMs,\n peakRssBytes: measurement.peakRssBytes,\n exclusivePhasesMs: measurement.exclusivePhasesMs ?? {},\n rhiDebugOverheadMs: measurement.rhiDebugOverheadMs ?? 0,\n carrierRendezvousMs: measurement.carrierRendezvousMs ?? 0,\n cleanupPassed: measurement.cleanupPassed,\n evictionPassed: measurement.evictionPassed,\n recipeDigest: options.recipe.digest,\n });\n }\n }\n }\n return createAdmissionReport(options.recipe, samples, options.thresholds);\n}\n","import type { Context } from '@forgeax/engine-plugin';\nimport {\n bootstrapCatalogLoader,\n type CatalogLoaderBootstrapValue,\n type GamePluginEntry,\n type PluginCatalog,\n type PluginRealm,\n projectPluginEntries,\n} from '@forgeax/engine-plugin/loader';\nimport {\n type RealmCapabilityMatrix,\n validateRealmBootstrapPayload,\n} from '@forgeax/engine-tool-runtime';\nimport {\n createProjectBootstrapPlan,\n type ProjectBootstrapPlan,\n} from '../host/project-bootstrap.js';\nimport {\n createResourceBootstrapPlan,\n type ResourceBootstrapPlan,\n} from '../host/resource-bootstrap.js';\nimport type { ProjectFacts } from '../types.js';\n\nexport interface PreviewBootstrapRoots {\n readonly project: ProjectBootstrapPlan;\n readonly resource: (guid: string) => ResourceBootstrapPlan;\n}\n\n/** Derives both physical roots without sharing project gameplay closure. */\nexport function createPreviewBootstrapRoots(facts: ProjectFacts): PreviewBootstrapRoots {\n return {\n project: createProjectBootstrapPlan(facts),\n resource: (guid) => createResourceBootstrapPlan(facts, guid),\n };\n}\n\nexport interface RealmBootstrapInput {\n readonly realm: PluginRealm;\n readonly catalog: PluginCatalog;\n readonly catalogDigest: string;\n readonly supportedRealms: readonly PluginRealm[];\n readonly entries: readonly GamePluginEntry[];\n readonly payload?: unknown;\n readonly lifecycle?: RealmLifecycleAdapter;\n}\n\nexport interface RealmLifecycleHandle {\n readonly stop: () => Promise<void>;\n}\n\nexport interface RealmLifecycleAdapter {\n readonly start: (input: {\n readonly realm: PluginRealm;\n readonly entries: readonly ReturnType<typeof projectPluginEntries>[number][];\n readonly catalog: PluginCatalog;\n readonly catalogDigest: string;\n }) => Promise<RealmLifecycleHandle>;\n}\n\nexport type RealmBootstrapResult =\n | {\n readonly ok: true;\n readonly value: {\n readonly realm: PluginRealm;\n readonly catalogDigest: string;\n readonly entries: readonly ReturnType<typeof projectPluginEntries>[number][];\n readonly loader?: CatalogLoaderBootstrapValue;\n readonly lifecycle?: RealmLifecycleHandle;\n };\n }\n | { readonly ok: false; readonly error: unknown };\n\n/** Bootstrap one declared realm from the same static Catalog and clone-safe input. */\nexport async function bootstrapRealm(\n ctx: Context | undefined,\n input: RealmBootstrapInput,\n): Promise<RealmBootstrapResult> {\n const cloneSafe = validateRealmBootstrapPayload(input.payload);\n if (!cloneSafe.ok) return cloneSafe;\n if (!input.supportedRealms.includes(input.realm)) {\n return {\n ok: false,\n error: {\n code: 'realm-capability-unavailable',\n realm: input.realm,\n supportedRealms: input.supportedRealms,\n },\n };\n }\n const entries = projectPluginEntries(input.entries, input.realm, input.realm);\n if (input.realm === 'build') {\n if (input.lifecycle === undefined) {\n return {\n ok: false,\n error: {\n code: 'realm-lifecycle-adapter-missing',\n realm: input.realm,\n hint: 'Inject a build lifecycle adapter that owns execution and stop cleanup.',\n },\n };\n }\n const lifecycle = await input.lifecycle.start({\n realm: input.realm,\n entries,\n catalog: input.catalog,\n catalogDigest: input.catalogDigest,\n });\n return {\n ok: true,\n value: { realm: input.realm, catalogDigest: input.catalogDigest, entries, lifecycle },\n };\n }\n if (ctx === undefined) {\n return {\n ok: false,\n error: { code: 'realm-context-missing', realm: input.realm },\n };\n }\n const loaded = await bootstrapCatalogLoader(ctx, input.catalog, input.realm, {\n catalogDigest: input.catalogDigest,\n supportedRealms: input.supportedRealms,\n });\n if (!loaded.ok) return loaded;\n return {\n ok: true,\n value: {\n realm: input.realm,\n catalogDigest: input.catalogDigest,\n entries,\n loader: loaded.value,\n },\n };\n}\n\nexport function assertRealmCapability(matrix: RealmCapabilityMatrix, realm: PluginRealm): void {\n const capability = matrix.realms[realm];\n if (!capability.supported) {\n throw new Error(`realm-capability-unavailable:${realm}`);\n }\n}\n","import type { JsonValue } from '@forgeax/engine-tool-runtime';\n\nexport interface ServiceCacheEntry {\n readonly artifactDigest: string;\n readonly value?: JsonValue;\n}\n\nexport interface ServiceCache {\n readonly get: (key: string) => ServiceCacheEntry | undefined;\n readonly set: (key: string, entry: ServiceCacheEntry) => void;\n readonly evict: (key: string) => boolean;\n readonly clear: () => void;\n readonly size: () => number;\n}\n\nexport function createServiceCache(): ServiceCache {\n const entries = new Map<string, ServiceCacheEntry>();\n return {\n get: (key) => entries.get(key),\n set: (key, entry) => entries.set(key, entry),\n evict: (key) => entries.delete(key),\n clear: () => entries.clear(),\n size: () => entries.size,\n };\n}\n","import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';\nimport type {\n CarrierLeaseRequest,\n CarrierOffer,\n CarrierResult,\n CarrierState,\n CarrierStateMachine,\n ToolTerminal,\n} from '@forgeax/engine-tool-runtime';\n\nexport interface CarrierProvider {\n readonly offer: CarrierOffer;\n readonly accept: (request: CarrierLeaseRequest) => CarrierResult<{ readonly leaseId: string }>;\n readonly started: (leaseId: string) => CarrierResult<CarrierState>;\n readonly exit: (leaseId: string) => CarrierResult<CarrierState>;\n}\n\nexport interface CarrierProviderServiceOptions {\n readonly machine: CarrierStateMachine;\n readonly descriptorDigest: string;\n readonly recipeDigest: string;\n readonly execute: (\n request: CarrierExecutionRequest,\n ) => Promise<ToolTerminal<unknown>> | ToolTerminal<unknown>;\n readonly host?: '127.0.0.1' | 'localhost';\n}\n\n/** Local structural view keeps DevKit source-compatible with an unbuilt runtime dist. */\nexport interface CarrierExecutionRequest {\n readonly leaseId: string;\n readonly descriptorDigest: string;\n readonly recipeDigest: string;\n readonly args: unknown;\n}\n\nexport interface CarrierProviderService {\n readonly endpoint: string;\n readonly offer: CarrierOffer;\n readonly close: () => Promise<void>;\n}\n\ntype WireResult =\n | { readonly ok: true; readonly value: unknown; readonly state: string }\n | { readonly ok: false; readonly error: unknown };\n\nfunction errorResult(\n code: string,\n expected: string,\n hint: string,\n detail: Record<string, unknown> = {},\n): WireResult {\n return { ok: false, error: { code, expected, hint, detail } };\n}\n\nasync function readBody(request: IncomingMessage): Promise<Record<string, unknown>> {\n const chunks: Buffer[] = [];\n for await (const chunk of request) chunks.push(Buffer.from(chunk));\n const value: unknown = JSON.parse(Buffer.concat(chunks).toString('utf8'));\n if (typeof value !== 'object' || value === null || Array.isArray(value))\n throw new Error('carrier request must be an object');\n return value as Record<string, unknown>;\n}\n\nfunction reply(response: ServerResponse, status: number, payload: WireResult): void {\n response.statusCode = status;\n response.setHeader('content-type', 'application/json');\n response.end(JSON.stringify(payload));\n}\n\nexport async function createCarrierProviderService(\n options: CarrierProviderServiceOptions,\n): Promise<CarrierProviderService> {\n const host = options.host ?? '127.0.0.1';\n const bearerToken = options.machine.offer.bearerToken;\n const server = createServer(async (request, response) => {\n if (request.method !== 'POST' || !request.url?.startsWith('/carrier/')) {\n reply(\n response,\n 404,\n errorResult(\n 'carrier-provider-exit',\n 'a carrier protocol route',\n 'Request a fresh visible offer from the provider.',\n ),\n );\n return;\n }\n if (request.headers.authorization !== `Bearer ${bearerToken}`) {\n reply(\n response,\n 401,\n errorResult(\n 'carrier-token-invalid',\n 'the ephemeral bearer token',\n 'Request a fresh authenticated offer; never guess or persist bearer tokens.',\n ),\n );\n return;\n }\n try {\n const body = await readBody(request);\n const route = request.url.slice('/carrier/'.length);\n if (route === 'lease') {\n const result = options.machine.lease({\n consumerId: String(body.consumerId ?? ''),\n bearerToken,\n now: Number(body.now),\n descriptorDigest:\n typeof body.descriptorDigest === 'string' ? body.descriptorDigest : undefined,\n recipeDigest: typeof body.recipeDigest === 'string' ? body.recipeDigest : undefined,\n } as CarrierLeaseRequest);\n reply(response, result.ok ? 200 : 409, result.ok ? result : result);\n return;\n }\n const leaseId = typeof body.leaseId === 'string' ? body.leaseId : '';\n if (route === 'start') {\n const result = options.machine.started(leaseId);\n reply(response, result.ok ? 200 : 409, result.ok ? result : result);\n return;\n }\n if (route === 'exit') {\n const result = options.machine.exit(leaseId);\n reply(response, result.ok ? 200 : 409, result.ok ? result : result);\n return;\n }\n if (route === 'execute') {\n const snapshot = options.machine.snapshot();\n if (snapshot.leaseId !== leaseId || snapshot.state !== 'started') {\n reply(\n response,\n 409,\n errorResult(\n snapshot.state === 'exited' ? 'carrier-exited' : 'carrier-lease-required',\n 'a started carrier lease',\n 'Do not fallback after started; report the structured terminal error and offer a new carrier.',\n ),\n );\n return;\n }\n if (body.descriptorDigest !== options.descriptorDigest) {\n reply(\n response,\n 409,\n errorResult(\n 'carrier-descriptor-mismatch',\n 'the offered descriptor digest',\n 'Rebuild the offer from the current descriptor before retrying.',\n ),\n );\n return;\n }\n if (body.recipeDigest !== options.recipeDigest) {\n reply(\n response,\n 409,\n errorResult(\n 'carrier-recipe-mismatch',\n 'the offered recipe digest',\n 'Serialize a fresh snapshot and request a new carrier before retrying.',\n ),\n );\n return;\n }\n const terminal = await options.execute({\n leaseId,\n descriptorDigest: options.descriptorDigest,\n recipeDigest: options.recipeDigest,\n args: body.args,\n });\n reply(response, 200, { ok: true, value: terminal, state: 'started' });\n return;\n }\n reply(\n response,\n 404,\n errorResult(\n 'carrier-provider-exit',\n 'a carrier protocol route',\n 'Request a fresh visible offer from the provider.',\n ),\n );\n } catch (cause) {\n reply(\n response,\n 400,\n errorResult(\n 'carrier-provider-exit',\n 'a valid carrier request',\n 'Serialize POD only and retry from the last safe snapshot.',\n { cause: cause instanceof Error ? cause.message : String(cause) },\n ),\n );\n }\n });\n await new Promise<void>((resolve, reject) => {\n const onError = (error: Error) => {\n server.off('listening', onListening);\n reject(error);\n };\n const onListening = () => {\n server.off('error', onError);\n resolve();\n };\n server.once('error', onError);\n server.once('listening', onListening);\n server.listen(0, host);\n });\n const address = server.address();\n if (address === null || typeof address === 'string')\n throw new Error('carrier provider did not expose a loopback port');\n const endpoint = `http://${host}:${address.port}/carrier`;\n let closed = false;\n return {\n endpoint,\n offer: options.machine.offer,\n async close() {\n if (closed) return;\n closed = true;\n await new Promise<void>((resolve, reject) =>\n server.close((error) => (error === undefined ? resolve() : reject(error))),\n );\n },\n };\n}\n\nexport function createCarrierProvider(machine: CarrierStateMachine): CarrierProvider {\n return {\n offer: machine.offer,\n accept(request) {\n const result = machine.lease(request);\n if (!result.ok) return result;\n return { ok: true, value: { leaseId: result.value.leaseId }, state: result.state };\n },\n started: machine.started,\n exit: machine.exit,\n };\n}\n","import {\n type CarrierOffer,\n type CarrierStateMachine,\n createCarrierStateMachine,\n} from '@forgeax/engine-tool-runtime';\n\nexport { type CarrierProvider, createCarrierProvider } from './carrier-provider.js';\n\nexport interface CarrierRendezvousOptions {\n readonly presentation: 'hidden' | 'visible';\n readonly projectId: string;\n readonly consumerId: string;\n readonly now: number;\n readonly endpoint?: string;\n readonly ttlMs?: number;\n}\n\nexport interface CarrierRendezvous extends CarrierStateMachine {\n readonly lookup: () => CarrierOffer | undefined;\n readonly lookupCount: number;\n}\n\nexport function createCarrierRendezvous(options: CarrierRendezvousOptions): CarrierRendezvous {\n const machine = createCarrierStateMachine({\n projectId: options.projectId,\n consumerId: options.consumerId,\n endpoint: options.endpoint ?? 'http://127.0.0.1:5740/carrier',\n now: options.now,\n ttlMs: options.ttlMs ?? 30_000,\n });\n let lookupCount = 0;\n const lookup = (): CarrierOffer | undefined => {\n if (options.presentation !== 'visible' || machine.snapshot().state !== 'offered') return;\n lookupCount += 1;\n return machine.offer;\n };\n return {\n ...machine,\n lookup,\n get lookupCount() {\n return lookupCount;\n },\n };\n}\n","import { describeResourcePreviewFailure } from '@forgeax/engine-preview';\nimport {\n capabilityUnavailableError,\n type JsonValue,\n type ToolRuntime,\n type ToolTerminal,\n} from '@forgeax/engine-tool-runtime';\n\nexport function decorateResourcePreviewTerminal<TResult>(\n terminal: ToolTerminal<TResult>,\n): ToolTerminal<TResult> {\n if (terminal.outcome === 'succeeded') return terminal;\n const recovery = describeResourcePreviewFailure(terminal.failure);\n if (recovery === undefined) return terminal;\n if (terminal.failure.code !== 'tool-domain-failed') return terminal;\n return {\n ...terminal,\n failure: {\n ...terminal.failure,\n detail: {\n ...terminal.failure.detail,\n ...(recovery.suggestedOperation === undefined\n ? {}\n : { suggestedOperation: recovery.suggestedOperation }),\n recovery: recovery.actions,\n },\n },\n };\n}\n\nfunction missingTool(id: string): ToolTerminal<never> {\n return {\n outcome: 'failed',\n failure: capabilityUnavailableError(`tool:${id}`, 'build'),\n artifacts: [],\n };\n}\n\nexport function runNamedTool(\n runtime: ToolRuntime,\n id: string,\n args: unknown,\n): Promise<ToolTerminal<unknown>> {\n const contribution = runtime.get(id);\n if (contribution === undefined) return Promise.resolve(missingTool(id));\n return runtime.run(contribution, args).terminal.then(decorateResourcePreviewTerminal);\n}\n\nexport function runGenericTool(\n runtime: ToolRuntime,\n id: string,\n encodedArgs: string,\n): Promise<ToolTerminal<unknown>> {\n let args: JsonValue;\n try {\n args = JSON.parse(encodedArgs) as JsonValue;\n } catch {\n return Promise.resolve({\n outcome: 'failed',\n failure: {\n code: 'tool-invalid-args',\n expected: 'generic CLI arguments to be valid JSON',\n hint: 'Encode one JSON value that conforms to the descriptor argsSchema.',\n detail: { message: 'Invalid JSON', value: null },\n },\n artifacts: [],\n });\n }\n return runNamedTool(runtime, id, args);\n}\n","import {\n createToolRuntime,\n type ToolContribution,\n type ToolRunOptions,\n type ToolTerminal,\n} from '@forgeax/engine-tool-runtime';\nimport {\n createProjectToolCatalogAuthority,\n createRealmDispatch,\n describeTool,\n listTools,\n loadToolCatalog,\n type ToolCatalogEntry,\n type ToolRealmOwner,\n} from './catalog.js';\nimport { decorateResourcePreviewTerminal } from './cli-adapter.js';\nimport { retiredPreviewTool } from './preview-migration.js';\nimport type { ProjectToolBinding, ProjectToolDiscoveryOptions } from './project-tools.js';\n\nexport interface ToolClientOptions extends ProjectToolDiscoveryOptions {\n readonly projectRoot: string;\n /** Optional physical realm owners used by a host/carrier integration. */\n readonly realmOwners?: readonly ToolRealmOwner[];\n /** Injectable builtins for physical host tests and alternate Engine adapters. */\n readonly baseContributions?: readonly ToolContribution[];\n readonly projectDiscovery?: (projectRoot: string) => Promise<readonly ProjectToolBinding[]>;\n}\n\nexport interface ToolClient {\n readonly list: () => readonly ToolCatalogEntry[];\n readonly describe: (id: string) => ToolCatalogEntry | undefined;\n readonly run: <TResult = unknown>(\n id: string,\n args: unknown,\n options?: ToolRunOptions,\n ) => Promise<ToolTerminal<TResult>>;\n}\n\nfunction missingTool(id: string): ToolTerminal<never> {\n return {\n outcome: 'failed',\n failure: {\n code: 'tool-capability-unavailable',\n expected: `tool ${id} to exist in the project-derived catalog`,\n hint: 'Run tool list and choose one of the discovered operation ids.',\n detail: { capability: `tool:${id}`, realm: 'build' },\n },\n artifacts: [],\n };\n}\n\nexport async function createToolClient(options: ToolClientOptions): Promise<ToolClient> {\n const projectDiscovery = options.projectDiscovery;\n const runProjectTool =\n projectDiscovery === undefined\n ? (await import('./project-tools.js')).runProjectTool\n : undefined;\n const builtins =\n options.baseContributions ??\n (await import('./contributions.js')).createDefaultContributions(options.projectRoot);\n const project =\n projectDiscovery === undefined\n ? await (await import('./project-tools.js')).discoverProjectTools(\n options.projectRoot,\n options,\n )\n : await projectDiscovery(options.projectRoot);\n const contributions = [...builtins, ...project.map(({ contribution }) => contribution)];\n const runtime =\n options.baseContributions === undefined\n ? (await import('./runtime.js')).createDevkitToolRuntime(contributions as readonly unknown[])\n : createToolRuntime(contributions as readonly unknown[]);\n const realmDispatch =\n options.realmOwners === undefined\n ? undefined\n : createRealmDispatch(contributions as readonly ToolContribution[], options.realmOwners);\n const bindingById = new Map<string, ProjectToolBinding>(\n project.map((binding) => [binding.contribution.descriptor.id, binding]),\n );\n const descriptors = runtime.list();\n const loaded = await loadToolCatalog(\n createProjectToolCatalogAuthority(options.projectRoot, descriptors),\n descriptors,\n );\n if (!loaded.ok) throw loaded.error;\n return {\n list: () => listTools(loaded.value),\n describe: (id) => describeTool(loaded.value, id),\n async run<TResult = unknown>(id: string, args: unknown, runOptions: ToolRunOptions = {}) {\n if (id === 'preview.run') return retiredPreviewTool() as ToolTerminal<TResult>;\n const contribution = runtime.get(id);\n if (contribution === undefined) return missingTool(id) as ToolTerminal<TResult>;\n const binding = bindingById.get(id);\n const nativePreview =\n binding === undefined && id.endsWith('.preview')\n ? await import('./native-preview.js')\n : undefined;\n const terminal =\n nativePreview?.isNativePreviewTool(id) === true\n ? await nativePreview.runNativePreviewTool(\n contribution as ToolContribution<unknown, unknown>,\n args,\n runOptions,\n options.projectRoot,\n )\n : binding !== undefined && runProjectTool !== undefined\n ? await runProjectTool(binding, args, runOptions)\n : realmDispatch === undefined\n ? await runtime.run(contribution, args, runOptions).terminal\n : await realmDispatch.run(id, args, runOptions);\n return decorateResourcePreviewTerminal(terminal as ToolTerminal<TResult>);\n },\n };\n}\n","import {\n createToolRuntime,\n type ToolContribution,\n type ToolRunOptions,\n type ToolTerminal,\n} from '@forgeax/engine-tool-runtime';\n\nexport function runLibraryTool<TArgs, TResult>(\n contribution: ToolContribution<TArgs, TResult>,\n args: TArgs,\n options?: ToolRunOptions,\n): Promise<ToolTerminal<TResult>> {\n return createToolRuntime([contribution]).run(contribution, args, options).terminal;\n}\n","import type { MigrationCapabilityProbe, MigrationOperation } from '@forgeax/engine-tool-runtime';\nimport {\n type ArtifactRef,\n capabilityUnavailableError,\n createServiceCapability,\n type ServiceCapability,\n type ToolEvidenceKind,\n type ToolRealm,\n} from '@forgeax/engine-tool-runtime';\n\nexport {\n createCapabilityToken,\n createMigrationRecipe,\n type MigrationCapabilityProbe,\n type MigrationOperation,\n type MigrationRecipe,\n probeMigrationTarget,\n} from '@forgeax/engine-tool-runtime';\n\nexport type MigrationPath = 'private' | 'service';\n\nexport interface MigrationTarget extends MigrationCapabilityProbe {}\n\nexport interface MigrationRosterEntry {\n readonly operation: MigrationOperation;\n readonly owner: string;\n readonly realm: ToolRealm;\n readonly artifacts: readonly MigrationEvidence[];\n readonly benefit: string;\n readonly fallback: 'private';\n}\n\nexport interface MigrationEvidence {\n readonly owner: string;\n readonly source: 'M3';\n readonly ref: ArtifactRef;\n}\n\nexport interface MigrationResolution {\n readonly path: MigrationPath;\n readonly operation: MigrationOperation;\n readonly owner: string;\n readonly artifacts: readonly MigrationEvidence[];\n readonly service: ServiceCapability;\n}\n\nexport type MigrationResolutionResult =\n | { readonly ok: true; readonly value: MigrationResolution }\n | { readonly ok: false; readonly error: ReturnType<typeof capabilityUnavailableError> };\n\nconst roster: readonly MigrationRosterEntry[] = [\n {\n operation: 'project.preview',\n owner: 'devkit/preview-host',\n realm: 'host',\n artifacts: previewArtifacts(),\n benefit: 'reuse the real WebGPU hidden preview recipe',\n fallback: 'private',\n },\n {\n operation: 'material.preview',\n owner: 'engine-preview/material',\n realm: 'host',\n artifacts: previewArtifacts(),\n benefit: 'preview one material subject through the canonical lit rig',\n fallback: 'private',\n },\n {\n operation: 'mesh.preview',\n owner: 'engine-preview/mesh',\n realm: 'host',\n artifacts: previewArtifacts(),\n benefit: 'preview one mesh subject with every submesh and AABB evidence',\n fallback: 'private',\n },\n {\n operation: 'vfx.preview',\n owner: 'engine-preview/vfx',\n realm: 'host',\n artifacts: previewArtifacts(),\n benefit: 'preview one bounded VFX timeline with compute evidence',\n fallback: 'private',\n },\n {\n operation: 'texture.preview',\n owner: 'engine-preview/texture',\n realm: 'host',\n artifacts: previewArtifacts(),\n benefit: 'preview one texture on the aspect-preserving unlit quad',\n fallback: 'private',\n },\n];\n\nfunction previewArtifacts(): readonly MigrationEvidence[] {\n return [\n {\n owner: 'preview-tool-proof',\n source: 'M3',\n ref: {\n kind: 'rhi-tape',\n digest: 'sha256:e62a302dd29e302e1d0928306fe9c90c47ee336aa2e9e35fdc1d75586ae0018d',\n uri: 'repo:apps/preview/__tests__/tool-proof.recipe.integration.test.ts',\n },\n },\n {\n owner: 'preview-tool-proof',\n source: 'M3',\n ref: {\n kind: 'profile-capture',\n digest: 'sha256:11ec9024e1ea08b38f0901db272847ac402d2dce0c757efe744315608e889c5c',\n uri: 'repo:packages/profiler/src/__tests__/fixtures/profile-capture/model-input.json',\n },\n },\n ];\n}\n\nfunction validEvidence(entry: MigrationRosterEntry): boolean {\n return (\n entry.owner.length > 0 &&\n entry.artifacts.length > 0 &&\n entry.artifacts.every(\n ({ owner, source, ref }) =>\n owner.length > 0 &&\n source === 'M3' &&\n /^sha256:[0-9a-f]{64}$/.test(ref.digest) &&\n typeof ref.uri === 'string' &&\n ref.uri.startsWith('repo:') &&\n isSupportedEvidenceKind(ref.kind),\n )\n );\n}\n\nfunction isSupportedEvidenceKind(kind: ArtifactRef['kind']): kind is ToolEvidenceKind {\n return kind === 'rhi-tape' || kind === 'profile-capture' || kind === 'png';\n}\n\nexport function createMigrationRoster(): readonly MigrationRosterEntry[] {\n return roster.filter(validEvidence).map((entry) => ({\n ...entry,\n artifacts: entry.artifacts.map((artifact) => ({ ...artifact, ref: { ...artifact.ref } })),\n }));\n}\n\nexport function resolveMigration(\n entries: readonly MigrationRosterEntry[],\n operation: MigrationOperation,\n target: MigrationTarget,\n): MigrationResolutionResult {\n const entry = entries.find((candidate) => candidate.operation === operation);\n if (entry === undefined || !validEvidence(entry)) {\n return {\n ok: false,\n error: capabilityUnavailableError(`migration:${operation}`, target.realm),\n };\n }\n if (entry.realm !== target.realm || target.catalogDigest.length === 0) {\n return { ok: false, error: capabilityUnavailableError(`migration:${operation}`, target.realm) };\n }\n if (entry.realm === 'host' && target.rhiBackend !== 'webgpu') {\n return { ok: false, error: capabilityUnavailableError(`rhi:${operation}`, target.realm) };\n }\n const evidenceKinds = entry.artifacts.map(({ ref }) => ref.kind).filter(isSupportedEvidenceKind);\n if (!evidenceKinds.every((kind) => target.evidence.includes(kind))) {\n return { ok: false, error: capabilityUnavailableError(`evidence:${operation}`, target.realm) };\n }\n const service: ServiceCapability = createServiceCapability(undefined, {\n toolId: operation,\n descriptorDigest: entry.artifacts[0]?.ref.digest ?? '',\n recipeDigest: entry.artifacts[0]?.ref.digest ?? '',\n workloadClass: `migration:${operation}`,\n codeDigest: target.catalogDigest,\n browserVersion: 'unavailable',\n backend: 'webgpu',\n });\n return {\n ok: true,\n value: {\n path: service.available ? 'service' : 'private',\n operation,\n owner: entry.owner,\n artifacts: entry.artifacts.map((artifact) => ({ ...artifact, ref: { ...artifact.ref } })),\n service,\n },\n };\n}\n","import {\n createToolPreviewHost,\n createToolPreviewRecipe,\n type ToolPreviewRecipeOptions,\n type ToolPreviewRunResult,\n type ToolPreviewTrace,\n} from '@forgeax/engine-app';\nimport type {\n CarrierLeaseRequest,\n CarrierOffer,\n CarrierResult,\n CarrierState,\n ToolDomainFailure,\n ToolExecutionContext,\n} from '@forgeax/engine-tool-runtime';\nimport { runBrowserPreviewHost } from './browser-host.js';\n\nexport interface PreviewHostRequest {\n readonly recipe: ToolPreviewRecipeOptions;\n readonly projectRoot?: string;\n readonly carrier?: PreviewCarrierRoute;\n}\n\nexport interface PreviewHostMechanisms {\n readonly runId: string;\n readonly projectRoot: string;\n readonly backend: 'webgpu';\n readonly signal: AbortSignal;\n}\n\nexport interface PreviewHostSession {\n readonly withSession: <T>(\n execute: (mechanisms: PreviewHostMechanisms) => Promise<T>,\n ) => Promise<T>;\n}\n\n/**\n * Creates the physical host lease. Domain identity stays in the executor;\n * this seam carries only browser, backend, and lexical run ownership.\n */\nexport function createPreviewHostSession(input: {\n readonly runId: string;\n readonly projectRoot: string;\n readonly signal: AbortSignal;\n}): PreviewHostSession {\n let active = true;\n return {\n async withSession(execute) {\n if (!active || input.signal.aborted) throw new Error('preview-host-session-terminal');\n try {\n return await execute({\n runId: input.runId,\n projectRoot: input.projectRoot,\n backend: 'webgpu',\n signal: input.signal,\n });\n } finally {\n active = false;\n }\n },\n };\n}\n\nexport interface PreviewCarrierRoute {\n readonly lookup: () => CarrierOffer | undefined;\n readonly lease: (request: CarrierLeaseRequest) => CarrierResult<{ readonly leaseId: string }>;\n readonly started: (leaseId: string) => CarrierResult<CarrierState>;\n readonly execute: (\n leaseId: string,\n request: Omit<PreviewHostRequest, 'carrier'>,\n context: Pick<ToolExecutionContext, 'runId' | 'signal'>,\n ) => Promise<PreviewRouteResult<PreviewHostResult>>;\n readonly exit: (leaseId: string) => CarrierResult<CarrierState>;\n readonly now?: () => number;\n}\n\nexport interface PreviewHostResult {\n readonly actualCarrier: 'headless-private' | 'headed-private' | 'visible-consumer';\n readonly trace: ToolPreviewTrace;\n readonly captureId: string;\n readonly drawCalls: number;\n readonly committedDrawIndex: number;\n readonly nonBlackPixels: number;\n readonly actionTrace: ToolPreviewRunResult['actionTrace'];\n readonly tape: ToolPreviewRunResult['tape'];\n readonly profile: ToolPreviewRunResult['profile'];\n readonly capturePng: ToolPreviewRunResult['capturePng'];\n readonly png: ToolPreviewRunResult['png'];\n readonly manifest: ToolPreviewRunResult['manifest'];\n readonly artifacts: ToolPreviewRunResult['artifacts'];\n readonly operationTiming: ToolPreviewRunResult['operationTiming'];\n readonly resource?: import('@forgeax/engine-app').ToolPreviewResourceFacts;\n}\n\nexport type PreviewHostRunner = (\n request: PreviewHostRequest,\n context: ToolExecutionContext,\n) => Promise<\n | { readonly ok: true; readonly value: PreviewHostResult }\n | { readonly ok: false; readonly error: ToolDomainFailure }\n>;\n\ntype PreviewRouteResult<T> =\n | { readonly ok: true; readonly value: T }\n | { readonly ok: false; readonly error: ToolDomainFailure };\n\nexport interface CarrierCleanupTrace {\n readonly actualCarrier: 'headless-private' | 'headed-private' | 'visible-consumer';\n readonly backend: 'webgpu';\n readonly cleanup: readonly ['gpu', 'canvas', 'page', 'carrier'];\n readonly failure: {\n readonly code: 'tool-preview-carrier-exit';\n readonly detail: { readonly carrier: CarrierCleanupTrace['actualCarrier'] };\n };\n}\n\nexport function createCarrierCleanupTrace(input: {\n readonly actualCarrier: CarrierCleanupTrace['actualCarrier'];\n readonly backend: 'webgpu';\n}): CarrierCleanupTrace {\n return {\n actualCarrier: input.actualCarrier,\n backend: input.backend,\n cleanup: ['gpu', 'canvas', 'page', 'carrier'],\n failure: {\n code: 'tool-preview-carrier-exit',\n detail: { carrier: input.actualCarrier },\n },\n };\n}\n\nfunction carrierRouteFailure(\n code: string,\n expected: string,\n hint: string,\n detail: Readonly<Record<string, unknown>>,\n): PreviewRouteResult<never> {\n return { ok: false, error: { code, expected, hint, detail: detail as never } };\n}\n\nexport async function runCarrierPreviewRoute<T>(\n presentation: ToolPreviewRecipeOptions['presentation'],\n carrier: PreviewCarrierRoute | undefined,\n executePrivate: () => Promise<PreviewRouteResult<T>>,\n executeConsumer: (leaseId: string) => Promise<PreviewRouteResult<T>> = executePrivate,\n): Promise<PreviewRouteResult<T>> {\n if (presentation === 'hidden' || carrier === undefined) return executePrivate();\n const offer = carrier.lookup();\n if (offer === undefined) return executePrivate();\n const leased = carrier.lease({\n consumerId: offer.consumerId,\n bearerToken: offer.bearerToken,\n now: carrier.now?.() ?? Date.now(),\n });\n if (!leased.ok) return executePrivate();\n const started = carrier.started(leased.value.leaseId);\n if (!started.ok) return executePrivate();\n const result = await executeConsumer(leased.value.leaseId);\n const exited = carrier.exit(leased.value.leaseId);\n if (!exited.ok)\n return carrierRouteFailure(\n exited.error.code,\n exited.error.expected,\n exited.error.hint,\n exited.error.detail,\n );\n return result;\n}\n\nexport const runPreviewHost: PreviewHostRunner = async (request, context) => {\n if (context.snapshot === undefined) {\n return carrierRouteFailure(\n 'tool-snapshot-missing',\n 'ToolExecutionContext.snapshot before Browser or Renderer creation',\n 'Start the operation with an authority snapshot and retry the lexical ToolRun.',\n { phase: 'snapshot' },\n );\n }\n const snapshot = context.snapshot;\n const recipe = createToolPreviewRecipe(request.recipe);\n return runCarrierPreviewRoute(\n recipe.presentation,\n request.carrier,\n async () => {\n if (typeof document === 'undefined') {\n if (request.projectRoot === undefined) {\n return carrierRouteFailure(\n 'tool-preview-project-root-missing',\n 'the Browser Host to receive a real ForgeaX project root',\n 'Create the ToolClient with projectRoot or pass projectRoot in the preview request.',\n { phase: 'project-authority' },\n );\n }\n return runBrowserPreviewHost(\n request.projectRoot,\n recipe,\n snapshot,\n context.runId,\n context.signal,\n );\n }\n const host = await createToolPreviewHost({ recipe, snapshot });\n if (!host.ok) {\n return {\n ok: false,\n error: {\n code: host.error.code,\n expected: host.error.expected,\n hint: host.error.hint,\n detail: host.error.detail as never,\n },\n };\n }\n try {\n const result = await host.value.run();\n if (!result.ok) {\n return {\n ok: false,\n error: {\n code: result.error.code,\n expected: result.error.expected,\n hint: result.error.hint,\n detail: result.error.detail as never,\n },\n };\n }\n return {\n ok: true,\n value: {\n ...result.value,\n actualCarrier: recipe.presentation === 'hidden' ? 'headless-private' : 'headed-private',\n },\n };\n } finally {\n await host.value.dispose();\n }\n },\n async (leaseId) => {\n const carrier = request.carrier;\n if (carrier === undefined) {\n return carrierRouteFailure(\n 'tool-preview-carrier-unavailable',\n 'a leased Consumer provider',\n 'Retry the ordinary private visible carrier.',\n { phase: 'consumer-execute' },\n );\n }\n const { carrier: _carrier, ...consumerRequest } = request;\n return carrier.execute(leaseId, consumerRequest, context);\n },\n );\n};\n","import type {\n ToolContribution,\n ToolRunOptions,\n ToolRuntime,\n ToolTerminal,\n} from '@forgeax/engine-tool-runtime';\n\nexport function runPrivateTool<TArgs, TResult>(\n runtime: ToolRuntime,\n contribution: ToolContribution<TArgs, TResult>,\n args: TArgs,\n options?: ToolRunOptions,\n): Promise<ToolTerminal<TResult>> {\n return runtime.run(contribution, args, options).terminal;\n}\n","import type { ToolRealm } from '@forgeax/engine-tool-runtime';\nimport {\n createRealmCapabilityMatrix as createRuntimeRealmCapabilityMatrix,\n type RealmCapability,\n type RealmCapabilityInput,\n type RealmCapabilityMatrix,\n} from '@forgeax/engine-tool-runtime';\n\nexport type { RealmCapability, RealmCapabilityInput, RealmCapabilityMatrix };\nexport { createRuntimeRealmCapabilityMatrix as createRealmCapabilityMatrix };\n\nexport function resolveRealmCapability(\n matrix: RealmCapabilityMatrix,\n realm: ToolRealm,\n): RealmCapability {\n return matrix.realms[realm];\n}\n\nconst RESOURCE_KINDS = ['process', 'port', 'page', 'canvas', 'fiber'] as const;\nexport type ResourceKind = (typeof RESOURCE_KINDS)[number];\n\nexport interface ResourceProbe {\n readonly observe: (kind: ResourceKind, id: string) => void;\n readonly release: (kind: ResourceKind, id: string) => void;\n readonly owner: (id: string) => ResourceOwner;\n readonly snapshot: () => Readonly<Record<ResourceKind, readonly string[]>>;\n}\n\nexport interface ResourceOwner {\n readonly id: string;\n readonly observe: (kind: ResourceKind, resourceId: string) => void;\n readonly release: (kind: ResourceKind, resourceId: string) => void;\n readonly stop: () => void;\n}\n\nexport function createResourceProbe(): ResourceProbe {\n const live = new Map<ResourceKind, Set<string>>(RESOURCE_KINDS.map((kind) => [kind, new Set()]));\n const owned = new Map<string, Set<string>>();\n const key = (kind: ResourceKind, id: string): string => `${kind}:${id}`;\n const releaseOwned = (ownerId: string, kind: ResourceKind, id: string): void => {\n live.get(kind)?.delete(id);\n owned.get(ownerId)?.delete(key(kind, id));\n };\n return {\n observe(kind, id) {\n live.get(kind)?.add(id);\n },\n release(kind, id) {\n live.get(kind)?.delete(id);\n },\n owner(id) {\n if (owned.has(id)) throw new Error(`resource-owner-duplicate:${id}`);\n owned.set(id, new Set());\n let stopped = false;\n return {\n id,\n observe(kind, resourceId) {\n if (stopped) throw new Error(`resource-owner-stopped:${id}`);\n live.get(kind)?.add(resourceId);\n owned.get(id)?.add(key(kind, resourceId));\n },\n release(kind, resourceId) {\n releaseOwned(id, kind, resourceId);\n },\n stop() {\n if (stopped) return;\n stopped = true;\n for (const resource of owned.get(id) ?? []) {\n const separator = resource.indexOf(':');\n const kind = resource.slice(0, separator) as ResourceKind;\n const resourceId = resource.slice(separator + 1);\n live.get(kind)?.delete(resourceId);\n }\n owned.delete(id);\n },\n };\n },\n snapshot() {\n return Object.fromEntries(\n [...live.entries()].map(([kind, ids]) => [kind, [...ids].sort()]),\n ) as unknown as Readonly<Record<ResourceKind, readonly string[]>>;\n },\n };\n}\n\nexport {\n createResourceBootstrapPlan,\n createResourceBootstrapTrace,\n type ResourceBootstrapPlan,\n type ResourceBootstrapTrace,\n type ResourceBootstrapTraceInput,\n} from '../host/resource-bootstrap.js';\n","import {\n type AuthenticatedLoopbackTransport,\n cancellationError,\n createServiceCapability,\n disconnectedError,\n domainFailureError,\n type JsonValue,\n type ServiceAdmissionRef,\n type ServiceCapability,\n type ToolContribution,\n type ToolTerminal,\n} from '@forgeax/engine-tool-runtime';\n\nexport interface ServiceExecutorOptions<TArgs, TResult> {\n readonly contribution: ToolContribution<TArgs, TResult>;\n readonly privateExecutor: (args: TArgs) => Promise<ToolTerminal<TResult>>;\n readonly transport: AuthenticatedLoopbackTransport;\n readonly admission?: ServiceAdmissionRef;\n readonly descriptorDigest: string;\n readonly recipeDigest: string;\n readonly workloadClass: string;\n readonly codeDigest: string;\n readonly browserVersion: string;\n readonly bearerToken?: string;\n}\n\nexport interface ServiceExecutor<TArgs, TResult> {\n readonly capability: ServiceCapability;\n readonly run: (\n args: TArgs,\n options?: { readonly recipeDigest?: string; readonly signal?: AbortSignal },\n ) => Promise<ToolTerminal<TResult>>;\n}\n\nexport function createServiceExecutor<TArgs, TResult>(\n options: ServiceExecutorOptions<TArgs, TResult>,\n): ServiceExecutor<TArgs, TResult> {\n const capability = createServiceCapability(options.admission, {\n toolId: options.contribution.descriptor.id,\n descriptorDigest: options.descriptorDigest,\n recipeDigest: options.recipeDigest,\n workloadClass: options.workloadClass,\n codeDigest: options.codeDigest,\n browserVersion: options.browserVersion,\n backend: 'webgpu',\n });\n return {\n capability,\n async run(args, runOptions = {}) {\n if (!capability.available) return options.privateExecutor(args);\n const request = {\n descriptorDigest: options.descriptorDigest,\n recipeDigest: runOptions.recipeDigest ?? options.recipeDigest,\n args: args as JsonValue,\n };\n try {\n const terminal = await options.transport.request(\n request,\n options.bearerToken ?? 'service-default-token',\n runOptions.signal === undefined ? {} : { signal: runOptions.signal },\n );\n return terminal as ToolTerminal<TResult>;\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n if (runOptions.signal?.aborted) {\n return {\n outcome: 'failed',\n failure: cancellationError(String(runOptions.signal.reason ?? 'aborted')),\n artifacts: [],\n };\n }\n const failure = message.includes('disconnected')\n ? disconnectedError(options.transport.endpoint)\n : domainFailureError(\n 'service-transport-failed',\n 'the authenticated loopback service to accept the request',\n 'Check the service token and recipe digest, then retry the private executor.',\n message,\n );\n return { outcome: 'failed', failure, artifacts: [] };\n }\n },\n };\n}\n","import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';\nimport {\n type AuthenticatedLoopbackTransport,\n createAuthenticatedLoopbackTransport,\n type ServiceWireHandler,\n type ServiceWireRequest,\n type ToolTerminal,\n} from '@forgeax/engine-tool-runtime';\n\nexport type {\n AuthenticatedLoopbackTransport,\n AuthenticatedLoopbackTransportOptions,\n ServiceWireHandler,\n ServiceWireRequest,\n} from '@forgeax/engine-tool-runtime';\nexport { createAuthenticatedLoopbackTransport } from '@forgeax/engine-tool-runtime';\n\nexport interface AuthenticatedLoopbackServiceOptions {\n readonly bearerToken: string;\n readonly handler: ServiceWireHandler;\n readonly host?: '127.0.0.1' | 'localhost';\n readonly expectedDescriptorDigest?: string;\n readonly expectedRecipeDigest?: string;\n}\n\nexport interface AuthenticatedLoopbackService {\n readonly endpoint: string;\n readonly transport: AuthenticatedLoopbackTransport;\n readonly close: () => Promise<void>;\n}\n\nasync function readJson(request: IncomingMessage): Promise<unknown> {\n const chunks: Buffer[] = [];\n for await (const chunk of request) chunks.push(Buffer.from(chunk));\n const body = Buffer.concat(chunks);\n if (body.byteLength > 1024 * 1024) throw new Error('request body is too large');\n return JSON.parse(body.toString('utf8')) as unknown;\n}\n\nfunction reply(\n response: ServerResponse,\n status: number,\n payload: ToolTerminal<unknown> | { readonly error: string },\n): void {\n response.statusCode = status;\n response.setHeader('content-type', 'application/json');\n response.end(JSON.stringify(payload));\n}\n\nfunction parseRequest(value: unknown): ServiceWireRequest {\n if (typeof value !== 'object' || value === null) throw new Error('request must be an object');\n const request = value as Record<string, unknown>;\n if (\n typeof request.descriptorDigest !== 'string' ||\n typeof request.recipeDigest !== 'string' ||\n request.args === undefined\n ) {\n throw new Error('request is missing descriptorDigest, recipeDigest, or args');\n }\n return {\n descriptorDigest: request.descriptorDigest,\n recipeDigest: request.recipeDigest,\n args: request.args as ServiceWireRequest['args'],\n };\n}\n\nfunction isAuthorized(request: IncomingMessage, bearerToken: string): boolean {\n return request.headers.authorization === `Bearer ${bearerToken}`;\n}\n\nexport async function createAuthenticatedLoopbackService(\n options: AuthenticatedLoopbackServiceOptions,\n): Promise<AuthenticatedLoopbackService> {\n if (options.bearerToken.length < 8) throw new TypeError('service bearer token is too short');\n const host = options.host ?? '127.0.0.1';\n const server = createServer(async (request, response) => {\n if (request.method !== 'POST' || request.url !== '/run') {\n reply(response, 404, { error: 'service route not found' });\n return;\n }\n if (!isAuthorized(request, options.bearerToken)) {\n reply(response, 401, { error: 'service bearer token rejected' });\n return;\n }\n try {\n const wireRequest = parseRequest(await readJson(request));\n if (\n options.expectedDescriptorDigest !== undefined &&\n wireRequest.descriptorDigest !== options.expectedDescriptorDigest\n ) {\n reply(response, 409, { error: 'service descriptor digest mismatch' });\n return;\n }\n if (\n options.expectedRecipeDigest !== undefined &&\n wireRequest.recipeDigest !== options.expectedRecipeDigest\n ) {\n reply(response, 409, { error: 'service recipe digest mismatch' });\n return;\n }\n reply(response, 200, await options.handler(wireRequest));\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n reply(response, 400, { error: message });\n }\n });\n await new Promise<void>((resolve, reject) => {\n const onError = (error: Error) => {\n server.off('listening', onListening);\n reject(error);\n };\n const onListening = () => {\n server.off('error', onError);\n resolve();\n };\n server.once('error', onError);\n server.once('listening', onListening);\n server.listen(0, host);\n });\n const address = server.address();\n if (address === null || typeof address === 'string') {\n await new Promise<void>((resolve) => server.close(() => resolve()));\n throw new Error('loopback service did not expose a TCP address');\n }\n const endpoint = `http://${host}:${address.port}/run`;\n const transport = createAuthenticatedLoopbackTransport({\n endpoint,\n bearerToken: options.bearerToken,\n });\n let closed = false;\n return {\n endpoint,\n transport,\n async close() {\n if (closed) return;\n closed = true;\n await new Promise<void>((resolve, reject) => {\n server.close((error) => (error === undefined ? resolve() : reject(error)));\n });\n transport.close();\n },\n };\n}\n"]}