oda-engine 0.0.0-stage → 0.1.0

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 (204) hide show
  1. package/README.md +151 -2
  2. package/bin/nowhere.mjs +352 -0
  3. package/lib/account.mjs +57 -0
  4. package/lib/agentModules.mjs +57 -0
  5. package/lib/devServer.mjs +351 -0
  6. package/lib/headless.mjs +231 -0
  7. package/lib/headlessPreview.mjs +212 -0
  8. package/lib/keys.mjs +517 -0
  9. package/lib/make.mjs +855 -0
  10. package/lib/mcp.mjs +537 -0
  11. package/lib/open.mjs +22 -0
  12. package/lib/preview.mjs +87 -0
  13. package/lib/previewRpc.mjs +134 -0
  14. package/lib/project.mjs +359 -0
  15. package/lib/publishFlow.mjs +90 -0
  16. package/lib/resources.mjs +50 -0
  17. package/lib/rules.mjs +60 -0
  18. package/lib/scaffold.mjs +42 -0
  19. package/lib/setup.mjs +59 -0
  20. package/lib/tools.mjs +668 -0
  21. package/package.json +51 -4
  22. package/template/game.config.json +9 -0
  23. package/template/scene.json +4 -0
  24. package/template/src/main.ts +11 -0
  25. package/vendor/DOCS.md +447 -0
  26. package/vendor/agent/appRun.mjs +520 -0
  27. package/vendor/agent/assets/brief.mjs +242 -0
  28. package/vendor/agent/assets/collider.mjs +531 -0
  29. package/vendor/agent/assets/environments/index.mjs +12 -0
  30. package/vendor/agent/assets/environments/worldlabs.mjs +161 -0
  31. package/vendor/agent/assets/fetch.mjs +168 -0
  32. package/vendor/agent/assets/footprint.mjs +13 -0
  33. package/vendor/agent/assets/gltf.mjs +547 -0
  34. package/vendor/agent/assets/hdr.mjs +269 -0
  35. package/vendor/agent/assets/imageOps.mjs +171 -0
  36. package/vendor/agent/assets/images/codex.mjs +307 -0
  37. package/vendor/agent/assets/images/fal.mjs +75 -0
  38. package/vendor/agent/assets/images/gemini.mjs +84 -0
  39. package/vendor/agent/assets/images/index.mjs +25 -0
  40. package/vendor/agent/assets/images/openai.mjs +75 -0
  41. package/vendor/agent/assets/images/stability.mjs +71 -0
  42. package/vendor/agent/assets/images/views.mjs +31 -0
  43. package/vendor/agent/assets/import.mjs +1352 -0
  44. package/vendor/agent/assets/inspect.mjs +465 -0
  45. package/vendor/agent/assets/jobs.mjs +196 -0
  46. package/vendor/agent/assets/ktx2.mjs +290 -0
  47. package/vendor/agent/assets/ledger.mjs +466 -0
  48. package/vendor/agent/assets/net.mjs +254 -0
  49. package/vendor/agent/assets/prices.json +39 -0
  50. package/vendor/agent/assets/providers/fal.mjs +115 -0
  51. package/vendor/agent/assets/providers/index.mjs +22 -0
  52. package/vendor/agent/assets/providers/meshy.mjs +119 -0
  53. package/vendor/agent/assets/providers/tripo.mjs +188 -0
  54. package/vendor/agent/assets/sources/ambientcg.mjs +129 -0
  55. package/vendor/agent/assets/sources/index.mjs +23 -0
  56. package/vendor/agent/assets/sources/polyhaven.mjs +237 -0
  57. package/vendor/agent/assets/sources/polypizza.mjs +121 -0
  58. package/vendor/agent/assets/splat.mjs +631 -0
  59. package/vendor/agent/assets/targets.mjs +122 -0
  60. package/vendor/agent/assets/tile.mjs +261 -0
  61. package/vendor/agent/assets/unzip.mjs +180 -0
  62. package/vendor/agent/blender/cleanup.py +360 -0
  63. package/vendor/agent/blender/convert.py +167 -0
  64. package/vendor/agent/blender/find.mjs +192 -0
  65. package/vendor/agent/blender/nw_export.py +104 -0
  66. package/vendor/agent/blender/nw_rubric.py +426 -0
  67. package/vendor/agent/blender/run.mjs +193 -0
  68. package/vendor/agent/blender/runner.py +252 -0
  69. package/vendor/agent/blender/sheet.py +743 -0
  70. package/vendor/agent/depth.mjs +134 -0
  71. package/vendor/agent/director/board.mjs +451 -0
  72. package/vendor/agent/director/contracts.mjs +663 -0
  73. package/vendor/agent/director/director.mjs +2365 -0
  74. package/vendor/agent/director/estimate.mjs +200 -0
  75. package/vendor/agent/director/gate.mjs +802 -0
  76. package/vendor/agent/director/limits.json +16 -0
  77. package/vendor/agent/director/methods.mjs +457 -0
  78. package/vendor/agent/director/policy.json +33 -0
  79. package/vendor/agent/director/prompts.mjs +244 -0
  80. package/vendor/agent/director/reading.mjs +341 -0
  81. package/vendor/agent/director/router.mjs +184 -0
  82. package/vendor/agent/director/seams.mjs +243 -0
  83. package/vendor/agent/director/session.mjs +643 -0
  84. package/vendor/agent/director/store.mjs +119 -0
  85. package/vendor/agent/director/taskGate.mjs +110 -0
  86. package/vendor/agent/director/teamLedger.mjs +118 -0
  87. package/vendor/agent/director/triage.mjs +63 -0
  88. package/vendor/agent/downloads.cjs +363 -0
  89. package/vendor/agent/flow.mjs +78 -0
  90. package/vendor/agent/guard.mjs +613 -0
  91. package/vendor/agent/host.mjs +1736 -0
  92. package/vendor/agent/language.mjs +58 -0
  93. package/vendor/agent/ledger.mjs +360 -0
  94. package/vendor/agent/locale.cjs +186 -0
  95. package/vendor/agent/loop/capacity.mjs +74 -0
  96. package/vendor/agent/loop/compose.mjs +127 -0
  97. package/vendor/agent/loop/gate.mjs +205 -0
  98. package/vendor/agent/loop/judge.mjs +189 -0
  99. package/vendor/agent/loop/levels.mjs +273 -0
  100. package/vendor/agent/loop/state.mjs +358 -0
  101. package/vendor/agent/notes.cjs +278 -0
  102. package/vendor/agent/pace.mjs +258 -0
  103. package/vendor/agent/panels.mjs +431 -0
  104. package/vendor/agent/prompt.mjs +342 -0
  105. package/vendor/agent/reference/board.mjs +410 -0
  106. package/vendor/agent/reference/compose.mjs +364 -0
  107. package/vendor/agent/reference/decode.mjs +56 -0
  108. package/vendor/agent/reference/facts.mjs +1874 -0
  109. package/vendor/agent/reference/png.mjs +107 -0
  110. package/vendor/agent/reference/records.mjs +63 -0
  111. package/vendor/agent/reference/web.mjs +252 -0
  112. package/vendor/agent/roles/artist.mjs +69 -0
  113. package/vendor/agent/roles/builder.mjs +79 -0
  114. package/vendor/agent/roles/checks.mjs +223 -0
  115. package/vendor/agent/roles/common.mjs +188 -0
  116. package/vendor/agent/roles/critic.mjs +171 -0
  117. package/vendor/agent/roles/index.mjs +39 -0
  118. package/vendor/agent/roles/modeller.mjs +142 -0
  119. package/vendor/agent/roles/qa.mjs +58 -0
  120. package/vendor/agent/roles/rubrics.mjs +79 -0
  121. package/vendor/agent/roles/sound.mjs +69 -0
  122. package/vendor/agent/rounds.cjs +333 -0
  123. package/vendor/agent/shared.mjs +284 -0
  124. package/vendor/agent/stopGate.mjs +574 -0
  125. package/vendor/agent/subagents.mjs +129 -0
  126. package/vendor/agent/tools/assets.mjs +499 -0
  127. package/vendor/agent/tools/blender.mjs +754 -0
  128. package/vendor/agent/tools/cards.mjs +479 -0
  129. package/vendor/agent/tools/choices.mjs +479 -0
  130. package/vendor/agent/tools/compose.mjs +74 -0
  131. package/vendor/agent/tools/environment.mjs +488 -0
  132. package/vendor/agent/tools/eyes.mjs +733 -0
  133. package/vendor/agent/tools/generate.mjs +338 -0
  134. package/vendor/agent/tools/guide.mjs +46 -0
  135. package/vendor/agent/tools/harness.mjs +193 -0
  136. package/vendor/agent/tools/image.mjs +643 -0
  137. package/vendor/agent/tools/index.mjs +162 -0
  138. package/vendor/agent/tools/look.mjs +578 -0
  139. package/vendor/agent/tools/loop.mjs +858 -0
  140. package/vendor/agent/tools/others.mjs +123 -0
  141. package/vendor/agent/tools/pictures.mjs +535 -0
  142. package/vendor/agent/tools/reference.mjs +366 -0
  143. package/vendor/agent/transcripts.mjs +118 -0
  144. package/vendor/agent-loop.mjs +602 -0
  145. package/vendor/agent-plugin/.claude-plugin/plugin.json +5 -0
  146. package/vendor/agent-plugin/skills/art-direction/SKILL.md +82 -0
  147. package/vendor/agent-plugin/skills/asset-legality/SKILL.md +101 -0
  148. package/vendor/agent-plugin/skills/asset-sources/SKILL.md +111 -0
  149. package/vendor/agent-plugin/skills/blender-modeling/SKILL.md +97 -0
  150. package/vendor/agent-plugin/skills/look-dev/SKILL.md +104 -0
  151. package/vendor/agent-plugin/skills/playtesting/SKILL.md +74 -0
  152. package/vendor/agent-plugin/skills/reference-loop/SKILL.md +102 -0
  153. package/vendor/agent-plugin/skills/sound-design/SKILL.md +60 -0
  154. package/vendor/agent-plugin/skills/style/SKILL.md +35 -0
  155. package/vendor/agent-plugin/skills/tsl-r185/SKILL.md +107 -0
  156. package/vendor/auth.cjs +570 -0
  157. package/vendor/build.cjs +953 -0
  158. package/vendor/catalog.json +455 -0
  159. package/vendor/connectors.cjs +688 -0
  160. package/vendor/eyes.mjs +733 -0
  161. package/vendor/gameExports.json +1390 -0
  162. package/vendor/git.cjs +222 -0
  163. package/vendor/models.json +57 -0
  164. package/vendor/publish.cjs +1018 -0
  165. package/vendor/refBoard.cjs +301 -0
  166. package/vendor/schema/dist/assets.d.ts +335 -0
  167. package/vendor/schema/dist/assets.js +439 -0
  168. package/vendor/schema/dist/brief.d.ts +357 -0
  169. package/vendor/schema/dist/brief.js +302 -0
  170. package/vendor/schema/dist/common.d.ts +9 -0
  171. package/vendor/schema/dist/common.js +13 -0
  172. package/vendor/schema/dist/config.d.ts +406 -0
  173. package/vendor/schema/dist/config.js +355 -0
  174. package/vendor/schema/dist/contract.d.ts +599 -0
  175. package/vendor/schema/dist/contract.js +1146 -0
  176. package/vendor/schema/dist/index.d.ts +14 -0
  177. package/vendor/schema/dist/index.js +21 -0
  178. package/vendor/schema/dist/look.d.ts +463 -0
  179. package/vendor/schema/dist/look.js +681 -0
  180. package/vendor/schema/dist/lookStats.d.ts +230 -0
  181. package/vendor/schema/dist/lookStats.js +768 -0
  182. package/vendor/schema/dist/pilot.d.ts +32 -0
  183. package/vendor/schema/dist/pilot.js +44 -0
  184. package/vendor/schema/dist/publish.d.ts +214 -0
  185. package/vendor/schema/dist/publish.js +291 -0
  186. package/vendor/schema/dist/scene.d.ts +75 -0
  187. package/vendor/schema/dist/scene.js +120 -0
  188. package/vendor/schema/dist/skyLight.d.ts +141 -0
  189. package/vendor/schema/dist/skyLight.js +436 -0
  190. package/vendor/schema/dist/style.d.ts +131 -0
  191. package/vendor/schema/dist/style.js +155 -0
  192. package/vendor/schema/package.json +1 -0
  193. package/vendor/selectionPrompt.mjs +51 -0
  194. package/vendor/useTools.mjs +195 -0
  195. package/vendor/userMessage.mjs +26 -0
  196. package/web-dist/assets/GaussianSplatUtils-CB77cP9U.js +1 -0
  197. package/web-dist/assets/KTX2Loader-6OIWUF7s.js +2 -0
  198. package/web-dist/assets/SPZLoader-zYj0Alfv.js +1 -0
  199. package/web-dist/assets/gaussianSplat-CJTI1sEh.js +1 -0
  200. package/web-dist/assets/index-CcjyyQco.css +1 -0
  201. package/web-dist/assets/index-DMyJcoZJ.js +693 -0
  202. package/web-dist/assets/meshopt_decoder.module-BvwdjiD3.js +1 -0
  203. package/web-dist/assets/zstddec.module-CfFeQW7d.js +1 -0
  204. package/web-dist/index.html +34 -0
package/lib/mcp.mjs ADDED
@@ -0,0 +1,537 @@
1
+ // `nowhere mcp`: the studio agent's tools for any MCP client, over stdio.
2
+ // Claude Code, Codex, Cursor and the rest then make, check, see, walk and
3
+ // publish a nowhere space the way the studio's own agent does (apps/studio/
4
+ // electron/agent), against the project in the folder they run in (or the one
5
+ // given with --project).
6
+ //
7
+ // The tools that run the space (check, view, play, eval, logs, status,
8
+ // screenshot) open the preview page in the browser the first time they need
9
+ // it, or use the one `nowhere dev` already has open. Logs go to stderr:
10
+ // stdout is the protocol.
11
+ //
12
+ // The eyes (nw_view, nw_play, nw_eval, nw_logs, nw_status) are the studio
13
+ // agent's own tool definitions (vendor/eyes.mjs, from apps/studio/electron/
14
+ // agent/tools/eyes.mjs). Their calls to the studio (ctx.rpc) are answered
15
+ // here instead: the build by the same check as nw_check, the rest by the
16
+ // preview page's probe (the studio viewport's agentProbe.ts), as `probe:*`
17
+ // requests.
18
+ //
19
+ // So are the quality tools (vendor/agent/tools, the studio's own modules):
20
+ // the look (look_apply, look_compare), the reference tools where this copy
21
+ // carries them (nw_reference, nw_compare), the asset libraries, the inspection
22
+ // and the ledger (asset_search, asset_fetch, asset_import, asset_inspect,
23
+ // asset_ledger), paid generation
24
+ // (asset_generate, asset_job), nw_blender (the agent's own bpy), and the guides
25
+ // (nw_guide). Their context here: the web is allowed (the MCP
26
+ // client's own permission prompt is the gate, so the tools that reach it are
27
+ // never announced read-only), a key is the environment variable of that name,
28
+ // and a paid generation needs the estimate's id back (confirm) once the
29
+ // creator agreed in the conversation, and then the creator's own yes, asked
30
+ // by this server through the client (elicitation), as no cost card exists
31
+ // here.
32
+ //
33
+ // The same server runs inside `nowhere tool <name>` and its short forms
34
+ // (tools.mjs): the client is in the process, the preview is headless Chrome
35
+ // (headlessPreview.mjs, also `nowhere mcp --headless`), and the yes is typed
36
+ // at the terminal.
37
+
38
+ import fs from 'node:fs'
39
+ import path from 'node:path'
40
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
41
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
42
+ import { z } from 'zod'
43
+ import { account } from './account.mjs'
44
+ import { connectHeadless } from './headlessPreview.mjs'
45
+ import { connectPreview } from './preview.mjs'
46
+ import { createPreviewRpc } from './previewRpc.mjs'
47
+ import { findProject } from './project.mjs'
48
+ import { describeOutcome, publishProject } from './publishFlow.mjs'
49
+ import { DOCS, schema, vendorModule, VERSION } from './resources.mjs'
50
+ import { MCP_INSTRUCTIONS } from './rules.mjs'
51
+ import { createProject } from './scaffold.mjs'
52
+ import { VENDOR } from './resources.mjs'
53
+
54
+ const log = (...a) => console.error('[Oda]', ...a)
55
+
56
+ /** The studio's eyes this server offers: all but the capture of the studio's
57
+ * own window, which has no counterpart here. */
58
+ const EYES = new Set(['nw_view', 'nw_play', 'nw_eval', 'nw_logs', 'nw_status'])
59
+
60
+ /** The studio agent's quality tool modules, vendored with their imports. */
61
+ const QUALITY_MODULES = ['agent/tools/look.mjs', 'agent/tools/assets.mjs', 'agent/tools/generate.mjs', 'agent/tools/environment.mjs', 'agent/tools/blender.mjs']
62
+ /** The reading of a reference picture and the comparison of a view with it
63
+ * (nw_reference, nw_compare), a picture for one asset before image-to-3D
64
+ * (image_generate), and a round's "target | now" picture (nw_compose):
65
+ * offered once the build vendors them. */
66
+ const OPTIONAL_MODULES = ['agent/tools/reference.mjs', 'agent/tools/image.mjs', 'agent/tools/compose.mjs']
67
+
68
+ /** The quality tools that reach the network: they download into quarantine
69
+ * or poll a paid vendor, so they are never announced as read-only, whatever
70
+ * the studio's cost gate calls them. The client's prompt for them is the
71
+ * consent the studio's web card asks for. */
72
+ const OPEN_WORLD = new Set(['asset_search', 'asset_fetch', 'asset_job', 'asset_generate', 'image_generate', 'environment_generate', 'environment_job'])
73
+
74
+ /** The environment variable that lets a paid generation start on the
75
+ * conversation's word alone, for a client that cannot ask the creator. */
76
+ export const ALLOW_PAID_VAR = 'NOWHERE_ALLOW_PAID'
77
+ /** The environment variable that is the creator's consent to Codex making
78
+ * pictures on their ChatGPT plan (image_generate provider codex): there is
79
+ * no consent card here. */
80
+ export const ALLOW_CODEX_VAR = 'NOWHERE_ALLOW_CODEX'
81
+ /** The tools that spend money: an estimate first, its id back, then the
82
+ * creator's own yes (creatorAgrees). */
83
+ const PAID = new Set(['asset_generate', 'image_generate', 'environment_generate'])
84
+
85
+ /** A tool's MCP annotations: read-only only for what touches nothing
86
+ * outside the project and changes nothing in it. */
87
+ export function annotationsFor(def) {
88
+ if (OPEN_WORLD.has(def.name)) return { readOnlyHint: false, openWorldHint: true }
89
+ return def.readOnly ? { readOnlyHint: true } : {}
90
+ }
91
+
92
+ /** The environment variable of each connector the asset tools ask for. */
93
+ const KEY_VARS = { meshy: 'MESHY_API_KEY', fal: 'FAL_KEY', tripo: 'TRIPO_API_KEY', polypizza: 'POLYPIZZA_API_KEY', worldlabs: 'WORLDLABS_API_KEY' }
94
+
95
+ /** asset_generate as this server offers it: the same tool, with the cost
96
+ * agreed in the conversation (there are no chat cards here). */
97
+ const GENERATE_HERE =
98
+ "Generates a 3D model with a paid service (Meshy or Tripo: text, image or several views to 3D; fal TRELLIS.2: image to 3D). action estimate answers the cost lines and an estimate id; show the creator the lines and the total, and only once they agree in the conversation call action submit with the same request and confirm set to that id (one agreement starts one job). submit then asks the creator itself, with the cost, before anything is sent (a client that cannot ask needs NOWHERE_ALLOW_PAID=1 in this server's environment). It refuses without the vendor's key (MESHY_API_KEY, FAL_KEY or TRIPO_API_KEY, stored with oda keys set or in this server's environment), without both agreements, and for Hunyuan3D. It starts the job and answers its id; follow it with asset_job, then asset_import what it made. Prefer a CC0 library (asset_search) or Blender for anything common; generate only a prop this space alone has, never its ground, walls or architecture, and delit (Meshy and Tripo are asked to remove the lighting, fal is not; asset_inspect says when shadow is baked in)."
99
+
100
+ /** image_generate as this server offers it: the same tool, with the cost
101
+ * agreed in the conversation and Codex's consent an environment variable. */
102
+ const IMAGE_HERE =
103
+ "Makes a picture: kind object (the default) is one asset's view before image-to-3D makes the model from it, one clean view of the object alone, or 2 to 4 views of it (in this order: the front, its right side, the back, its left side), written under blender/<asset>/ and recorded in assets.lock.json (vendor, model, the prompt's hash and the pictures it started from); then asset_generate image-to-3d (one view) or multi-image-to-3d (several) with their paths. kind texture is a surface that tiles (made seamless here, its 2 x 2 seam score before and after, with the 2 x 2 sheet to look at), panorama a 2:1 equirectangular sky (its left edge made to meet its right; asset_import as assets/<name>.hdr makes it the sky), card a cut-out with an alpha channel (made on a flat key colour and cut out here); these land in quarantine with the same record, for asset_import into assets/. kind target draws the finished space from each of 4 to 6 hero views (heroes, each with the camera brief.json will take) as a real photograph would show it, leaving out the slop list, into .nowhere/targets/<n>/, outside the space's files: show them to the creator before you write the brief, and draw again by their notes (nw_guide name reference-loop). A scanned CC0 library (asset_search) comes first for a realistic space; a made texture or sky is the fallback. Codex runs on the creator's ChatGPT plan once they allowed it (NOWHERE_ALLOW_CODEX=1 in this server's environment); OpenAI, Gemini, fal and Stability are paid, with their keys (OPENAI_API_KEY, GEMINI_API_KEY, FAL_KEY, STABILITY_API_KEY, stored with oda keys set or in this server's environment). action estimate answers the cost lines and an estimate id; show the creator the lines and the total, and only once they agree in the conversation call action submit with the same request and confirm set to that id (one agreement starts one job). submit then asks the creator itself, with the cost, before anything is sent. Look at the pictures before you go on: the whole object alone, or the surface, sky or card, in the brief's form and materials."
104
+
105
+ /** environment_generate as this server offers it: the cost agreed in the
106
+ * conversation, as asset_generate's is. */
107
+ const ENVIRONMENT_HERE =
108
+ "Generates a whole explorable environment with a paid world model (World Labs Marble): Gaussian splats of the place, a collider to walk on and the panorama it was made from, from a sentence, a picture or a panorama. Only when the creator asked for a generated world or a splat environment: a space's ground, walls and props come from scans first (asset_search). action estimate answers the cost lines and an estimate id (about $1.26 for a world from text with marble-1.1, up to $2.46 with 1.1 Plus); show the creator the lines and the total, and only once they agree in the conversation call action submit with the same request and confirm set to that id (one agreement starts one world). submit then asks the creator itself, with the cost, before anything is sent (a client that cannot ask needs NOWHERE_ALLOW_PAID=1 in this server's environment). It refuses without WORLDLABS_API_KEY (stored with oda keys set or in this server's environment), without both agreements, and when the account's API credits do not cover it. It starts the world (about five minutes) and answers its job id; follow it with environment_job, then asset_import what it made as a splat."
109
+
110
+ /** A tool's words as this server's client reads them: there are no chat
111
+ * cards here, so a cost or a share-alike licence is agreed in the
112
+ * conversation and a key is stored with nowhere keys or set in the
113
+ * environment; and no studio screen, so what the studio puts in its
114
+ * screen language is in the creator's here, the language of the
115
+ * conversation. */
116
+ export function cliWords(text) {
117
+ const keyVar = (id) => KEY_VARS[id] ?? `${id.toUpperCase()}_API_KEY`
118
+ return String(text ?? '')
119
+ .replace(/Ask with nw_ask kind cost, in the screen language, then submit\./g, 'Show the creator the lines and the total; once they agree in the conversation, submit with confirm set to the estimate id.')
120
+ .replace(/ask the creator with nw_ask kind cost \(([^)]*)\), and submit after they approve\./g, 'show the creator the cost ($1) in the conversation, and once they agree, submit with confirm set to the estimate id.')
121
+ .replace(/Ask again with nw_ask kind cost for the new total\./g, 'Estimate again and ask the creator in the conversation for the new total.')
122
+ .replace(/[Aa]sk for it with nw_ask kind key, connector ([\w-]+)\.?/g, (_m, id) => `Ask the creator to store it with oda keys set ${id}, or to set ${keyVar(id)} in the environment this server runs in, and to restart it.`)
123
+ .replace(/\(ask for it with nw_ask kind key, connector ([\w-]+)\)/g, (_m, id) => `(${keyVar(id)}, stored with oda keys set ${id} or in this server's environment)`)
124
+ .replace(/Ask the creator with nw_ask \(kind choice\), in the screen language, whether/g, 'Ask the creator in the conversation whether')
125
+ .replace(/an nw_ask choice card, in the screen language/g, 'the conversation')
126
+ .replace(/an nw_ask choice card/g, 'the conversation')
127
+ // The reference loop's targets card is the studio's: here the creator sees them in the conversation.
128
+ .replace(/Next: nw_ask_targets with images (\[.*?\]) \(each with what it shows\), so the creator keeps, drops or sends them back with notes\./g, 'Next: show the creator these pictures ($1) in the conversation, so they keep, drop or send them back with notes, before you write the brief.')
129
+ .replace(/[Uu]se a paid generator after a cost card/g, 'use a paid generator once the creator agreed to its cost in the conversation')
130
+ .replace(/has not allowed Codex to make pictures on their ChatGPT plan/g, `has not allowed Codex to make pictures on their ChatGPT plan (${ALLOW_CODEX_VAR}=1 in this server's environment allows it)`)
131
+ .replace(/ once \(a card\); submit asks for it when it was not given yet\./g, `: ${ALLOW_CODEX_VAR}=1 in this server's environment is that consent, and submit refuses without it.`)
132
+ .replace(/Ask the creator first, on a card in the screen language;/g, 'Ask the creator first, in the conversation;')
133
+ // The studio's own picture search is not offered here.
134
+ .replace(/Look references up with nw_find_pictures and keep those you build from with nw_keep_pictures \(after the web consent card\)/g, 'Gather references (CC0 or public domain, saved under refs/)')
135
+ .replace(/ in the screen language \(the studio context names it\)/g, " in the creator's language")
136
+ // Last, whatever is left: the studio's screen language is the conversation's here.
137
+ .replace(/the screen language/g, "the creator's language")
138
+ }
139
+
140
+ /** A tool's input fields as this server offers them: each field's own
141
+ * description in this server's words (cliWords), as its description is.
142
+ * Fields inside a list or an object keep theirs. */
143
+ function cliShape(shape) {
144
+ if (!shape || typeof shape !== 'object') return shape
145
+ return Object.fromEntries(
146
+ Object.entries(shape).map(([key, field]) => {
147
+ const said = typeof field?.description === 'string' ? field.description : null
148
+ return [key, said && cliWords(said) !== said && typeof field.describe === 'function' ? field.describe(cliWords(said)) : field]
149
+ }),
150
+ )
151
+ }
152
+
153
+ /**
154
+ * A stand-in for the studio's cost ledger: approvedUsd() is what the creator
155
+ * agreed to, which here is an estimate this server answered (offer) whose id
156
+ * came back as confirm. Each estimate answered can be confirmed once, and
157
+ * what the job costs is counted against it, so one agreement starts one job
158
+ * and the next job needs an estimate of its own.
159
+ */
160
+ export function cliLedger() {
161
+ let approved = null
162
+ let spent = 0
163
+ const offered = new Map()
164
+ return {
165
+ /** An estimate this server answered, which a submit may now confirm,
166
+ * with its cost lines for the creator to read. */
167
+ offer(id, lines = '') {
168
+ if (typeof id === 'string' && id) offered.set(id, String(lines ?? ''))
169
+ },
170
+ /** The cost lines an estimate answered, or null for one never offered
171
+ * (or already confirmed). */
172
+ offerOf: (id) => (offered.has(id) ? offered.get(id) : null),
173
+ confirmEstimate({ id, usd, matches }) {
174
+ if (!matches || !offered.has(id) || !Number.isFinite(usd) || usd < 0) return
175
+ offered.delete(id)
176
+ approved = spent + usd
177
+ },
178
+ approvedUsd: () => approved,
179
+ spentUsd: () => spent,
180
+ addGeneration(usd) {
181
+ if (Number.isFinite(usd) && usd > 0) spent += usd
182
+ },
183
+ }
184
+ }
185
+
186
+ /** A tool result (the studio's ToolResult) as MCP content. */
187
+ const asContent = (result) => ({
188
+ content: [
189
+ { type: 'text', text: result?.text ?? '' },
190
+ ...(result?.images ?? []).map((i) => ({ type: 'image', data: i.data, mimeType: i.mime })),
191
+ ],
192
+ ...(result?.isError ? { isError: true } : {}),
193
+ })
194
+
195
+ /**
196
+ * The server and its tools, not yet connected to a transport. `connect` is
197
+ * how the preview is reached (a check passes a stand-in).
198
+ * @returns {Promise<{ server: McpServer, root: () => string | null, close: () => Promise<void> }>}
199
+ */
200
+ export async function createServer({ project, connect = connectPreview, fetch: fetchFor } = {}) {
201
+ const base = path.resolve(project ?? process.cwd())
202
+ let root = findProject(base)
203
+ let preview = null
204
+ const { TOOLS: STUDIO_EYES, untexturedNote, perfFor, perfLines } = await vendorModule('eyes.mjs')
205
+
206
+ const needRoot = () => {
207
+ if (!root) throw new Error(`There is no Oda project in ${base}. Make one with nw_new, or open the agent in a project folder.`)
208
+ return root
209
+ }
210
+ // A preview still connecting is kept too, so close() can wait for it and
211
+ // stop what it started.
212
+ let connecting = null
213
+ const getPreview = async () => {
214
+ const r = needRoot()
215
+ if (!preview) {
216
+ connecting ??= Promise.resolve(connect(r, { log })).finally(() => {
217
+ connecting = null
218
+ })
219
+ preview = await connecting
220
+ }
221
+ return preview
222
+ }
223
+ const text = (t, isError = false) => ({ content: [{ type: 'text', text: t }], ...(isError ? { isError: true } : {}) })
224
+ const image = (dataUrl) => {
225
+ const m = /^data:(image\/\w+);base64,(.+)$/.exec(dataUrl ?? '')
226
+ return m ? [{ type: 'image', data: m[2], mimeType: m[1] }] : []
227
+ }
228
+ const guard = (fn) => async (args) => {
229
+ try {
230
+ return await fn(args ?? {})
231
+ } catch (err) {
232
+ return text(err?.message ?? String(err), true)
233
+ }
234
+ }
235
+
236
+ // The eyes' rpc (previewRpc.mjs), as the studio's main answers it: the
237
+ // build checked as publishing checks it and mounted in the preview page,
238
+ // the rest by the page's probe. The runner (make.mjs) answers the same way.
239
+ const eyes = createPreviewRpc({
240
+ root: () => root,
241
+ preview: getPreview,
242
+ noProject: () => `There is no Oda project in ${base}. Make one with nw_new, or open the agent in a project folder.`,
243
+ })
244
+ const { checkAndMount, livePage } = eyes
245
+ const eyesRpc = eyes.rpc
246
+
247
+ const eyesCtx = () => ({
248
+ runId: 'nowhere-mcp',
249
+ projectRoot: root,
250
+ runDir: null,
251
+ locale: 'en',
252
+ rpc: eyesRpc,
253
+ run: { needsBuild: eyes.needsBuild },
254
+ log,
255
+ })
256
+ // The quality tools' context: the eyes' own, and what the asset tools ask
257
+ // the host for. The ledger lives as long as the server.
258
+ const ledger = cliLedger()
259
+ const toolCtx = () => ({
260
+ ...eyesCtx(),
261
+ projectRoot: needRoot(),
262
+ // The MCP client's own permission prompt for each call is the consent.
263
+ web: async () => 'allow',
264
+ // Codex on the creator's own ChatGPT plan: only where they said so in
265
+ // this server's environment.
266
+ codex: async () => (process.env[ALLOW_CODEX_VAR] === '1' ? 'allow' : 'deny'),
267
+ secret: (name) => (typeof process.env[name] === 'string' && process.env[name] ? process.env[name] : undefined),
268
+ host: 'cli',
269
+ version: VERSION,
270
+ ledger,
271
+ // A check's stand-in for the network; the tools use the real fetch otherwise.
272
+ ...(fetchFor ? { fetch: fetchFor } : {}),
273
+ })
274
+
275
+ const server = new McpServer({ name: 'oda', version: VERSION }, { instructions: MCP_INSTRUCTIONS })
276
+
277
+ server.registerTool(
278
+ 'nw_new',
279
+ {
280
+ description:
281
+ 'Makes a new Oda project in a folder (relative to where the agent runs) and works in it from then on: the empty starter space, its config, the agent rules (AGENTS.md, CLAUDE.md) and a git repository. Use it when there is no project yet.',
282
+ inputSchema: {
283
+ folder: z.string().describe('The folder to make, e.g. "my-space". It must not exist yet, or be empty.'),
284
+ title: z.string().optional().describe('The space\'s title; the folder name if left out.'),
285
+ },
286
+ },
287
+ guard(async ({ folder, title }) => {
288
+ const made = await createProject(path.resolve(base, folder), title)
289
+ await preview?.close?.()
290
+ preview = null
291
+ root = made
292
+ eyes.reset()
293
+ return text(`Made an Oda project at ${made}. Read nw_docs, then write the space in src/main.ts and check it with nw_check.`)
294
+ }),
295
+ )
296
+
297
+ server.registerTool(
298
+ 'nw_docs',
299
+ {
300
+ description:
301
+ 'The @nowhere/sdk guide: the World API (objects, rules, the visitor and how it moves), the createGame contract, the Oda platform rules, and a closing section on visitor health, hazards and items. Read it before writing code for the first time.',
302
+ inputSchema: {},
303
+ },
304
+ guard(async () => text(fs.readFileSync(DOCS, 'utf8'))),
305
+ )
306
+
307
+ server.registerTool(
308
+ 'nw_schema',
309
+ {
310
+ description:
311
+ 'The exact JSON Schema for a project document: "config" is game.config.json (planet size, sky, fog, lighting, ground, bloom), "scene" is scene.json (the models placed by hand), "brief" is brief.json (the space brief: references and their measurements, palette, light, scale, materials with their texel density, hero views, what its files may weigh, its sources), "style" is style.json (how the space is drawn: medium, the works it is read from, shape, line, shading, surface, palette, rules and the look\'s drawing techniques, written before any target picture). Read it before editing any of them.',
312
+ inputSchema: { kind: z.enum(['config', 'scene', 'brief', 'style']).default('config') },
313
+ },
314
+ guard(async ({ kind }) => text(JSON.stringify((await schema()).jsonSchemaFor(kind ?? 'config'), null, 2))),
315
+ )
316
+
317
+ server.registerTool(
318
+ 'nw_check',
319
+ {
320
+ description:
321
+ 'Checks the space the way publishing does and runs it: the config against its schema, the build, the planet contract and the planet\'s size limits, then mounts it in the preview page (opened in the browser the first time) and reports anything it threw while running, every material that failed to build (drawn flat black, with its mesh and the line), every file it loads through ctx.assets that failed, and, as a warning, the large surfaces in the player\'s view whose colour carries no texture. It ends with perf: the frame time at each tier against its limit (high 16.7 ms, low 33 ms at p95), the worst of the spawn view and each hero view of brief.json, measured only when the project changed since the last one (about 10 to 30 seconds, longer while the space is still loading). Call it after every batch of edits; never say you are done while it fails.',
322
+ inputSchema: {},
323
+ },
324
+ guard(async () => {
325
+ const { checked, ran, live, failure } = await checkAndMount()
326
+ if (!checked.bundle) return text(`CHECK FAILED:\n${checked.problems.join('\n')}`, true)
327
+ const problems = [...checked.problems]
328
+ if (failure) problems.push(failure)
329
+ // The build's own warnings go with a failure too: they carry the file
330
+ // and line (a ShaderMaterial at src/x.ts:5) that the page's finding has not.
331
+ if (problems.length) return text(`CHECK FAILED:\n${[...problems, ...checked.notes].join('\n\n')}`, true)
332
+ const note = ran ? 'It builds, passes the planet checks, mounts and runs without throwing.' : `It builds and passes the planet checks. ${live.reason}`
333
+ // The WebGL habits the material watch found (they do nothing here).
334
+ const habits = Array.isArray(ran?.materials?.warnings) ? ran.materials.warnings.map((w) => `Warning: ${w}`) : []
335
+ // Untextured surfaces in the player's view (eyes.mjs), once the files have arrived.
336
+ const flat = ran && typeof untexturedNote === 'function' ? await untexturedNote(eyesRpc) : ''
337
+ // Frame time at each tier (eyes.mjs perfFor), kept until the project changes.
338
+ const timed = ran && typeof perfFor === 'function' ? await perfFor(eyesCtx()) : null
339
+ const unkept = timed?.unkept ? `\n- not kept, so the next nw_check measures again: ${timed.unkept}` : ''
340
+ const perfText = timed?.perf ? [`Frame time (perf):\n${perfLines(timed.perf).map((l) => `- ${l}`).join('\n')}${unkept}`, `perf: ${JSON.stringify(timed.perf)}`] : timed ? [`Frame time was not measured: ${timed.error}`] : []
341
+ return text([note, ...checked.notes, ...habits, ...(flat ? [flat] : []), ...perfText].join('\n'))
342
+ }),
343
+ )
344
+
345
+ // The eyes: the studio agent's own definitions, answered by the page's probe.
346
+ for (const def of STUDIO_EYES.filter((d) => EYES.has(d.name))) {
347
+ server.registerTool(
348
+ def.name,
349
+ {
350
+ description: def.description.replace('a snippet that never returns hangs the studio', 'a snippet that never returns hangs the preview page'),
351
+ inputSchema: def.shape,
352
+ ...(def.readOnly ? { annotations: { readOnlyHint: true } } : {}),
353
+ },
354
+ guard(async (args) => asContent(await def.handler(args, eyesCtx()))),
355
+ )
356
+ }
357
+
358
+ // The quality tools: the studio's own definitions with a CLI context.
359
+ for (const rel of QUALITY_MODULES) {
360
+ const { TOOLS } = await vendorModule(rel)
361
+ for (const def of TOOLS) registerDef(cliDef(def))
362
+ }
363
+ for (const rel of OPTIONAL_MODULES.filter((r) => fs.existsSync(path.join(VENDOR, r)))) {
364
+ const { TOOLS } = await vendorModule(rel)
365
+ for (const def of TOOLS) registerDef(cliDef(def))
366
+ }
367
+ // The guides, from the skills beside this package; they need no project.
368
+ const { guideDef } = await vendorModule('agent/tools/guide.mjs')
369
+ const { SKILL_NAMES } = await vendorModule('agent/shared.mjs')
370
+ registerDef(guideDef({ skillsDir: path.join(VENDOR, 'agent-plugin', 'skills'), names: SKILL_NAMES.map((n) => n.replace(/^nowhere:/, '')) }), { project: false })
371
+
372
+ /** A studio tool as this server offers it, where the studio's words or
373
+ * its cost card do not fit here. */
374
+ function cliDef(def) {
375
+ if (def.name === 'asset_import') {
376
+ return {
377
+ ...def,
378
+ shape: {
379
+ ...def.shape,
380
+ confirmedShareAlike: def.shape.confirmedShareAlike.describe('CC BY-SA: only after the creator agreed in the conversation.'),
381
+ capture: def.shape.capture.describe('splat: the creator scanned it themselves (a phone or camera capture), recorded as theirs. Only after they said so in the conversation.'),
382
+ },
383
+ }
384
+ }
385
+ if (!PAID.has(def.name)) return def
386
+ const picture = def.name === 'image_generate'
387
+ return {
388
+ ...def,
389
+ description: picture ? IMAGE_HERE : def.name === 'environment_generate' ? ENVIRONMENT_HERE : GENERATE_HERE,
390
+ shape: {
391
+ ...def.shape,
392
+ action: def.shape.action.describe(`estimate first; submit only once the creator agreed to that estimate in the conversation${picture ? ' (Codex: once they allowed it)' : ''}.`),
393
+ confirm: def.shape.confirm.describe("submit: the id the estimate answered, once the creator agreed to it. Each estimate starts one job."),
394
+ },
395
+ // Each estimate answered may be confirmed once (cliLedger), and only
396
+ // after the creator agreed outside the model (creatorAgrees). Codex is
397
+ // not paid: its gate is the consent in ctx.codex.
398
+ handler: async (args, ctx) => {
399
+ if (args?.action === 'submit' && args.confirm && ctx.ledger?.offerOf?.(args.confirm) != null && !(picture && args.provider === 'codex')) {
400
+ const refused = await creatorAgrees(ctx.ledger.offerOf(args.confirm), picture ? 'A paid picture' : def.name === 'environment_generate' ? 'A paid world' : 'A paid 3D generation')
401
+ if (refused) return { text: refused, isError: true }
402
+ }
403
+ const result = await def.handler(args, ctx)
404
+ if (args?.action === 'estimate' && !result?.isError) {
405
+ const m = /^Estimate ([0-9a-f]{12}): (.*)$/m.exec(result?.text ?? '')
406
+ ctx.ledger?.offer?.(m?.[1], m?.[2])
407
+ }
408
+ return result
409
+ },
410
+ }
411
+ }
412
+
413
+ /** The creator's own yes to a cost, asked by this server through the
414
+ * client (MCP elicitation), so the model's word is never the only gate on
415
+ * money. A client that cannot ask passes only where the creator set
416
+ * ALLOW_PAID_VAR for this server. Answers null on a yes, else why not. */
417
+ async function creatorAgrees(lines, what = 'A paid 3D generation') {
418
+ if (!server.server.getClientCapabilities()?.elicitation) {
419
+ if (process.env[ALLOW_PAID_VAR] === '1') return null
420
+ return `Nothing was sent: this client cannot ask the creator for the cost itself, so paid generation is off here. Use a CC0 library (asset_search) or Blender instead, or ask the creator to set ${ALLOW_PAID_VAR}=1 in the environment this server runs in (and restart it) if they want a yes in the conversation to be enough.`
421
+ }
422
+ let answer
423
+ try {
424
+ // Ten minutes for a person to read the cost and answer, at a terminal
425
+ // or in a client; the SDK's own minute is for machines.
426
+ answer = await server.server.elicitInput(
427
+ {
428
+ message: `${what}: ${lines}\nStart it?`,
429
+ requestedSchema: {
430
+ type: 'object',
431
+ properties: { start: { type: 'boolean', title: 'Start this paid generation', description: 'Yes spends up to the total above.' } },
432
+ required: ['start'],
433
+ },
434
+ },
435
+ { timeout: 10 * 60_000 },
436
+ )
437
+ } catch (err) {
438
+ return `Nothing was sent: the creator could not be asked for the cost (${err?.message ?? err}).`
439
+ }
440
+ if (answer?.action === 'accept' && answer.content?.start === true) return null
441
+ return `Nothing was sent: the creator did not agree to the cost (${answer?.action === 'accept' ? 'they said no' : `they chose ${answer?.action ?? 'nothing'}`}). Do not start it again unless they ask for it.`
442
+ }
443
+
444
+ function registerDef(def, { project = true } = {}) {
445
+ const annotations = annotationsFor(def)
446
+ server.registerTool(
447
+ def.name,
448
+ {
449
+ description: cliWords(def.description),
450
+ inputSchema: cliShape(def.shape),
451
+ ...(Object.keys(annotations).length ? { annotations } : {}),
452
+ },
453
+ guard(async (args) => {
454
+ const result = await def.handler(args, project ? toolCtx() : { ...eyesCtx(), host: 'cli' })
455
+ return asContent({ ...result, text: cliWords(result?.text) })
456
+ }),
457
+ )
458
+ }
459
+
460
+ // From before nw_view, for the projects whose rules still name it.
461
+ server.registerTool(
462
+ 'nw_screenshot',
463
+ {
464
+ description: 'A picture of the space in the preview, from the map\'s standard view (nw_view\'s "overview"). nw_view also shows the visitor\'s view, close-ups and any camera you choose; prefer it.',
465
+ inputSchema: {},
466
+ annotations: { readOnlyHint: true },
467
+ },
468
+ guard(async () => {
469
+ const live = await livePage()
470
+ if (!live.p) return text(live.reason, true)
471
+ const { png, error } = await live.p.request('screenshot', { longEdge: 1280 }, 30_000)
472
+ if (!png) return text(error ?? 'Nothing is mounted to take a picture of. Run nw_check first.', true)
473
+ return { content: [{ type: 'text', text: 'The space in the preview.' }, ...image(png)] }
474
+ }),
475
+ )
476
+
477
+ server.registerTool(
478
+ 'nw_login',
479
+ {
480
+ description:
481
+ 'Signs the creator in to Oda, which publishing needs: it opens their browser on Google sign-in and waits (up to five minutes) for them to finish it there. Never type anything into that page yourself.',
482
+ inputSchema: {},
483
+ },
484
+ guard(async () => {
485
+ const auth = account()
486
+ const now = await auth.status()
487
+ if (now.signedIn) return text(`Already signed in as ${now.email ?? now.name ?? 'someone'}.`)
488
+ const r = await auth.signIn()
489
+ if (!r.ok) return text(`Sign-in did not finish: ${r.error}`, true)
490
+ return text(`Signed in as ${r.status.email ?? r.status.name ?? 'someone'}.`)
491
+ }),
492
+ )
493
+
494
+ server.registerTool(
495
+ 'nw_publish',
496
+ {
497
+ description:
498
+ 'Publishes the space as a planet in the Oda universe, or updates the planet it already is: the same checks as nw_check, a commit of the project, and an upload. Only when the creator has asked for it to be published. Needs the creator signed in (nw_login).',
499
+ inputSchema: {},
500
+ },
501
+ guard(async () => {
502
+ const r = needRoot()
503
+ const p = await getPreview()
504
+ const lines = []
505
+ const outcome = await publishProject(r, { preview: p, say: (l) => lines.push(l) })
506
+ const said = describeOutcome(outcome)
507
+ return text(said.text, !said.ok)
508
+ }),
509
+ )
510
+
511
+ return {
512
+ server,
513
+ root: () => root,
514
+ close: async () => {
515
+ await connecting?.catch(() => {})
516
+ await preview?.close?.()
517
+ preview = null
518
+ },
519
+ }
520
+ }
521
+
522
+ /** `nowhere mcp`: over stdio, with the preview in the creator's browser, or
523
+ * with headless Chrome as the preview's page (headless). */
524
+ export async function runMcp({ project, headless = false } = {}) {
525
+ const { server, root, close } = await createServer({ project, connect: headless ? connectHeadless : connectPreview })
526
+ const transport = new StdioServerTransport()
527
+ await server.connect(transport)
528
+ log(`MCP server ready for ${root() ?? `${path.resolve(project ?? process.cwd())} (no project yet)`}`)
529
+
530
+ const shutdown = async () => {
531
+ await close()
532
+ process.exit(0)
533
+ }
534
+ process.stdin.on('close', shutdown)
535
+ // A closed terminal too: the headless Chrome never outlives the server.
536
+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, shutdown)
537
+ }
package/lib/open.mjs ADDED
@@ -0,0 +1,22 @@
1
+ // Opens a page in the user's own browser. NOWHERE_NO_OPEN=1 only prints it
2
+ // (a remote machine, a test).
3
+
4
+ import { spawn } from 'node:child_process'
5
+
6
+ export function openUrl(url) {
7
+ if (process.env.NOWHERE_NO_OPEN) return false
8
+ const [cmd, args] =
9
+ process.platform === 'darwin'
10
+ ? ['open', [url]]
11
+ : process.platform === 'win32'
12
+ ? ['cmd', ['/c', 'start', '""', url.replace(/&/g, '^&')]]
13
+ : ['xdg-open', [url]]
14
+ try {
15
+ const child = spawn(cmd, args, { stdio: 'ignore', detached: true, windowsHide: true })
16
+ child.on('error', () => {})
17
+ child.unref()
18
+ return true
19
+ } catch {
20
+ return false
21
+ }
22
+ }
@@ -0,0 +1,87 @@
1
+ // One way to reach a project's preview page, whoever runs it: a `nowhere dev`
2
+ // already running for the project (found through .nowhere/dev.json), or one
3
+ // started here. Either way: request(method, params, timeoutMs), rebuild(),
4
+ // runtime(), ensurePage(ms), url, close().
5
+
6
+ import { findRunning, startDevServer } from './devServer.mjs'
7
+ import { openUrl } from './open.mjs'
8
+
9
+ /**
10
+ * What is wrong with a game the preview page mounted, from its answer to
11
+ * 'mount' ({ mounted, error, errors, materials, assets }), or null when
12
+ * nothing is: it failed to mount, it threw while running, a material failed
13
+ * to build (the SDK's material watch), or a file it loads through
14
+ * ctx.assets failed. One sentence block for nw_check and `nowhere check`
15
+ * alike, so the command never passes what the agent's check fails.
16
+ */
17
+ export function mountFailure(ran) {
18
+ if (!ran) return null
19
+ if (!ran.mounted) return `It builds, but the game failed to mount:\n${ran.error ?? ''}`
20
+ if (ran.errors?.length) return `It threw while running:\n${ran.errors.join('\n')}`
21
+ const broken = Array.isArray(ran.materials?.errors) ? ran.materials.errors : []
22
+ if (broken.length) {
23
+ return `It builds and runs, but ${broken.length} material${broken.length === 1 ? '' : 's'} failed to build and ${broken.length === 1 ? 'is' : 'are'} drawn flat black:\n${broken.join('\n')}`
24
+ }
25
+ // A placeholder where a tree or a texture should be, with nothing thrown.
26
+ const files = (Array.isArray(ran.assets) ? ran.assets : []).filter((a) => a && typeof a.path === 'string').map((a) => `${a.path}: ${a.error ?? 'it failed to load'}`)
27
+ if (files.length) {
28
+ return `It builds and runs, but ${files.length} file${files.length === 1 ? '' : 's'} the game loads failed and ${files.length === 1 ? 'shows' : 'show'} as a placeholder:\n${files.join('\n')}`
29
+ }
30
+ return null
31
+ }
32
+
33
+ export async function connectPreview(root, { start = true, open = true, port = 0, log = () => {} } = {}) {
34
+ const running = await findRunning(root)
35
+ if (running) {
36
+ const call = async (method, params, timeoutMs) => {
37
+ const reply = await running.request(method, params, timeoutMs)
38
+ if (!reply.ok) throw new Error(reply.error ?? `${method} failed`)
39
+ return reply.result
40
+ }
41
+ let opened = false
42
+ return {
43
+ url: running.url,
44
+ own: false,
45
+ request: (method, params = {}, timeoutMs = 30_000) => call(method, params, timeoutMs),
46
+ rebuild: () => call('rebuild', {}, 60_000),
47
+ runtime: () => call('runtime', {}, 5000),
48
+ async ensurePage(ms) {
49
+ const until = Date.now() + ms
50
+ for (;;) {
51
+ try {
52
+ const res = await fetch(running.url.replace('/?t=', '/api/ping?t='), { signal: AbortSignal.timeout(1500) })
53
+ if ((await res.json()).connected > 0) return true
54
+ } catch {
55
+ // keep waiting
56
+ }
57
+ if (!opened && open) {
58
+ opened = true
59
+ openUrl(running.url)
60
+ }
61
+ if (Date.now() > until) return false
62
+ await new Promise((r) => setTimeout(r, 400))
63
+ }
64
+ },
65
+ close: async () => {},
66
+ }
67
+ }
68
+ if (!start) return null
69
+ const dev = await startDevServer({ root, port, log })
70
+ let opened = false
71
+ return {
72
+ url: dev.url,
73
+ own: true,
74
+ request: dev.request,
75
+ rebuild: () => dev.rebuild(),
76
+ runtime: async () => dev.runtime(),
77
+ async ensurePage(ms) {
78
+ if (dev.connected()) return true
79
+ if (!opened && open) {
80
+ opened = true
81
+ openUrl(dev.url)
82
+ }
83
+ return dev.waitForPage(ms)
84
+ },
85
+ close: dev.close,
86
+ }
87
+ }