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.
- package/README.md +151 -2
- package/bin/nowhere.mjs +352 -0
- package/lib/account.mjs +57 -0
- package/lib/agentModules.mjs +57 -0
- package/lib/devServer.mjs +351 -0
- package/lib/headless.mjs +231 -0
- package/lib/headlessPreview.mjs +212 -0
- package/lib/keys.mjs +517 -0
- package/lib/make.mjs +855 -0
- package/lib/mcp.mjs +537 -0
- package/lib/open.mjs +22 -0
- package/lib/preview.mjs +87 -0
- package/lib/previewRpc.mjs +134 -0
- package/lib/project.mjs +359 -0
- package/lib/publishFlow.mjs +90 -0
- package/lib/resources.mjs +50 -0
- package/lib/rules.mjs +60 -0
- package/lib/scaffold.mjs +42 -0
- package/lib/setup.mjs +59 -0
- package/lib/tools.mjs +668 -0
- package/package.json +51 -4
- package/template/game.config.json +9 -0
- package/template/scene.json +4 -0
- package/template/src/main.ts +11 -0
- package/vendor/DOCS.md +447 -0
- package/vendor/agent/appRun.mjs +520 -0
- package/vendor/agent/assets/brief.mjs +242 -0
- package/vendor/agent/assets/collider.mjs +531 -0
- package/vendor/agent/assets/environments/index.mjs +12 -0
- package/vendor/agent/assets/environments/worldlabs.mjs +161 -0
- package/vendor/agent/assets/fetch.mjs +168 -0
- package/vendor/agent/assets/footprint.mjs +13 -0
- package/vendor/agent/assets/gltf.mjs +547 -0
- package/vendor/agent/assets/hdr.mjs +269 -0
- package/vendor/agent/assets/imageOps.mjs +171 -0
- package/vendor/agent/assets/images/codex.mjs +307 -0
- package/vendor/agent/assets/images/fal.mjs +75 -0
- package/vendor/agent/assets/images/gemini.mjs +84 -0
- package/vendor/agent/assets/images/index.mjs +25 -0
- package/vendor/agent/assets/images/openai.mjs +75 -0
- package/vendor/agent/assets/images/stability.mjs +71 -0
- package/vendor/agent/assets/images/views.mjs +31 -0
- package/vendor/agent/assets/import.mjs +1352 -0
- package/vendor/agent/assets/inspect.mjs +465 -0
- package/vendor/agent/assets/jobs.mjs +196 -0
- package/vendor/agent/assets/ktx2.mjs +290 -0
- package/vendor/agent/assets/ledger.mjs +466 -0
- package/vendor/agent/assets/net.mjs +254 -0
- package/vendor/agent/assets/prices.json +39 -0
- package/vendor/agent/assets/providers/fal.mjs +115 -0
- package/vendor/agent/assets/providers/index.mjs +22 -0
- package/vendor/agent/assets/providers/meshy.mjs +119 -0
- package/vendor/agent/assets/providers/tripo.mjs +188 -0
- package/vendor/agent/assets/sources/ambientcg.mjs +129 -0
- package/vendor/agent/assets/sources/index.mjs +23 -0
- package/vendor/agent/assets/sources/polyhaven.mjs +237 -0
- package/vendor/agent/assets/sources/polypizza.mjs +121 -0
- package/vendor/agent/assets/splat.mjs +631 -0
- package/vendor/agent/assets/targets.mjs +122 -0
- package/vendor/agent/assets/tile.mjs +261 -0
- package/vendor/agent/assets/unzip.mjs +180 -0
- package/vendor/agent/blender/cleanup.py +360 -0
- package/vendor/agent/blender/convert.py +167 -0
- package/vendor/agent/blender/find.mjs +192 -0
- package/vendor/agent/blender/nw_export.py +104 -0
- package/vendor/agent/blender/nw_rubric.py +426 -0
- package/vendor/agent/blender/run.mjs +193 -0
- package/vendor/agent/blender/runner.py +252 -0
- package/vendor/agent/blender/sheet.py +743 -0
- package/vendor/agent/depth.mjs +134 -0
- package/vendor/agent/director/board.mjs +451 -0
- package/vendor/agent/director/contracts.mjs +663 -0
- package/vendor/agent/director/director.mjs +2365 -0
- package/vendor/agent/director/estimate.mjs +200 -0
- package/vendor/agent/director/gate.mjs +802 -0
- package/vendor/agent/director/limits.json +16 -0
- package/vendor/agent/director/methods.mjs +457 -0
- package/vendor/agent/director/policy.json +33 -0
- package/vendor/agent/director/prompts.mjs +244 -0
- package/vendor/agent/director/reading.mjs +341 -0
- package/vendor/agent/director/router.mjs +184 -0
- package/vendor/agent/director/seams.mjs +243 -0
- package/vendor/agent/director/session.mjs +643 -0
- package/vendor/agent/director/store.mjs +119 -0
- package/vendor/agent/director/taskGate.mjs +110 -0
- package/vendor/agent/director/teamLedger.mjs +118 -0
- package/vendor/agent/director/triage.mjs +63 -0
- package/vendor/agent/downloads.cjs +363 -0
- package/vendor/agent/flow.mjs +78 -0
- package/vendor/agent/guard.mjs +613 -0
- package/vendor/agent/host.mjs +1736 -0
- package/vendor/agent/language.mjs +58 -0
- package/vendor/agent/ledger.mjs +360 -0
- package/vendor/agent/locale.cjs +186 -0
- package/vendor/agent/loop/capacity.mjs +74 -0
- package/vendor/agent/loop/compose.mjs +127 -0
- package/vendor/agent/loop/gate.mjs +205 -0
- package/vendor/agent/loop/judge.mjs +189 -0
- package/vendor/agent/loop/levels.mjs +273 -0
- package/vendor/agent/loop/state.mjs +358 -0
- package/vendor/agent/notes.cjs +278 -0
- package/vendor/agent/pace.mjs +258 -0
- package/vendor/agent/panels.mjs +431 -0
- package/vendor/agent/prompt.mjs +342 -0
- package/vendor/agent/reference/board.mjs +410 -0
- package/vendor/agent/reference/compose.mjs +364 -0
- package/vendor/agent/reference/decode.mjs +56 -0
- package/vendor/agent/reference/facts.mjs +1874 -0
- package/vendor/agent/reference/png.mjs +107 -0
- package/vendor/agent/reference/records.mjs +63 -0
- package/vendor/agent/reference/web.mjs +252 -0
- package/vendor/agent/roles/artist.mjs +69 -0
- package/vendor/agent/roles/builder.mjs +79 -0
- package/vendor/agent/roles/checks.mjs +223 -0
- package/vendor/agent/roles/common.mjs +188 -0
- package/vendor/agent/roles/critic.mjs +171 -0
- package/vendor/agent/roles/index.mjs +39 -0
- package/vendor/agent/roles/modeller.mjs +142 -0
- package/vendor/agent/roles/qa.mjs +58 -0
- package/vendor/agent/roles/rubrics.mjs +79 -0
- package/vendor/agent/roles/sound.mjs +69 -0
- package/vendor/agent/rounds.cjs +333 -0
- package/vendor/agent/shared.mjs +284 -0
- package/vendor/agent/stopGate.mjs +574 -0
- package/vendor/agent/subagents.mjs +129 -0
- package/vendor/agent/tools/assets.mjs +499 -0
- package/vendor/agent/tools/blender.mjs +754 -0
- package/vendor/agent/tools/cards.mjs +479 -0
- package/vendor/agent/tools/choices.mjs +479 -0
- package/vendor/agent/tools/compose.mjs +74 -0
- package/vendor/agent/tools/environment.mjs +488 -0
- package/vendor/agent/tools/eyes.mjs +733 -0
- package/vendor/agent/tools/generate.mjs +338 -0
- package/vendor/agent/tools/guide.mjs +46 -0
- package/vendor/agent/tools/harness.mjs +193 -0
- package/vendor/agent/tools/image.mjs +643 -0
- package/vendor/agent/tools/index.mjs +162 -0
- package/vendor/agent/tools/look.mjs +578 -0
- package/vendor/agent/tools/loop.mjs +858 -0
- package/vendor/agent/tools/others.mjs +123 -0
- package/vendor/agent/tools/pictures.mjs +535 -0
- package/vendor/agent/tools/reference.mjs +366 -0
- package/vendor/agent/transcripts.mjs +118 -0
- package/vendor/agent-loop.mjs +602 -0
- package/vendor/agent-plugin/.claude-plugin/plugin.json +5 -0
- package/vendor/agent-plugin/skills/art-direction/SKILL.md +82 -0
- package/vendor/agent-plugin/skills/asset-legality/SKILL.md +101 -0
- package/vendor/agent-plugin/skills/asset-sources/SKILL.md +111 -0
- package/vendor/agent-plugin/skills/blender-modeling/SKILL.md +97 -0
- package/vendor/agent-plugin/skills/look-dev/SKILL.md +104 -0
- package/vendor/agent-plugin/skills/playtesting/SKILL.md +74 -0
- package/vendor/agent-plugin/skills/reference-loop/SKILL.md +102 -0
- package/vendor/agent-plugin/skills/sound-design/SKILL.md +60 -0
- package/vendor/agent-plugin/skills/style/SKILL.md +35 -0
- package/vendor/agent-plugin/skills/tsl-r185/SKILL.md +107 -0
- package/vendor/auth.cjs +570 -0
- package/vendor/build.cjs +953 -0
- package/vendor/catalog.json +455 -0
- package/vendor/connectors.cjs +688 -0
- package/vendor/eyes.mjs +733 -0
- package/vendor/gameExports.json +1390 -0
- package/vendor/git.cjs +222 -0
- package/vendor/models.json +57 -0
- package/vendor/publish.cjs +1018 -0
- package/vendor/refBoard.cjs +301 -0
- package/vendor/schema/dist/assets.d.ts +335 -0
- package/vendor/schema/dist/assets.js +439 -0
- package/vendor/schema/dist/brief.d.ts +357 -0
- package/vendor/schema/dist/brief.js +302 -0
- package/vendor/schema/dist/common.d.ts +9 -0
- package/vendor/schema/dist/common.js +13 -0
- package/vendor/schema/dist/config.d.ts +406 -0
- package/vendor/schema/dist/config.js +355 -0
- package/vendor/schema/dist/contract.d.ts +599 -0
- package/vendor/schema/dist/contract.js +1146 -0
- package/vendor/schema/dist/index.d.ts +14 -0
- package/vendor/schema/dist/index.js +21 -0
- package/vendor/schema/dist/look.d.ts +463 -0
- package/vendor/schema/dist/look.js +681 -0
- package/vendor/schema/dist/lookStats.d.ts +230 -0
- package/vendor/schema/dist/lookStats.js +768 -0
- package/vendor/schema/dist/pilot.d.ts +32 -0
- package/vendor/schema/dist/pilot.js +44 -0
- package/vendor/schema/dist/publish.d.ts +214 -0
- package/vendor/schema/dist/publish.js +291 -0
- package/vendor/schema/dist/scene.d.ts +75 -0
- package/vendor/schema/dist/scene.js +120 -0
- package/vendor/schema/dist/skyLight.d.ts +141 -0
- package/vendor/schema/dist/skyLight.js +436 -0
- package/vendor/schema/dist/style.d.ts +131 -0
- package/vendor/schema/dist/style.js +155 -0
- package/vendor/schema/package.json +1 -0
- package/vendor/selectionPrompt.mjs +51 -0
- package/vendor/useTools.mjs +195 -0
- package/vendor/userMessage.mjs +26 -0
- package/web-dist/assets/GaussianSplatUtils-CB77cP9U.js +1 -0
- package/web-dist/assets/KTX2Loader-6OIWUF7s.js +2 -0
- package/web-dist/assets/SPZLoader-zYj0Alfv.js +1 -0
- package/web-dist/assets/gaussianSplat-CJTI1sEh.js +1 -0
- package/web-dist/assets/index-CcjyyQco.css +1 -0
- package/web-dist/assets/index-DMyJcoZJ.js +693 -0
- package/web-dist/assets/meshopt_decoder.module-BvwdjiD3.js +1 -0
- package/web-dist/assets/zstddec.module-CfFeQW7d.js +1 -0
- package/web-dist/index.html +34 -0
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
// The local preview: a small server on 127.0.0.1 that serves the preview page
|
|
2
|
+
// (web/, the studio's own 3D view in a browser tab), rebuilds the game as its
|
|
3
|
+
// files change and pushes each new build, config and scene to the page, and
|
|
4
|
+
// lets the CLI and the MCP server ask the page things (mount this and say what
|
|
5
|
+
// it threw, take a picture, play for three seconds).
|
|
6
|
+
//
|
|
7
|
+
// The page talks back over plain HTTP: the server pushes with Server-Sent
|
|
8
|
+
// Events, the page answers with POSTs. Every route but the page itself needs
|
|
9
|
+
// the session's token, which only the URL the server opens carries, so no
|
|
10
|
+
// other site in the browser can drive it.
|
|
11
|
+
//
|
|
12
|
+
// While it runs, <project>/.nowhere/dev.json says where it is, so a second
|
|
13
|
+
// process (nowhere check, nowhere publish, the MCP server) uses this one
|
|
14
|
+
// rather than starting its own.
|
|
15
|
+
|
|
16
|
+
import crypto from 'node:crypto'
|
|
17
|
+
import fs from 'node:fs'
|
|
18
|
+
import fsp from 'node:fs/promises'
|
|
19
|
+
import http from 'node:http'
|
|
20
|
+
import path from 'node:path'
|
|
21
|
+
import { WEB, schema } from './resources.mjs'
|
|
22
|
+
import { buildBundle, readDocs } from './project.mjs'
|
|
23
|
+
|
|
24
|
+
const MIME = {
|
|
25
|
+
'.html': 'text/html; charset=utf-8',
|
|
26
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
27
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
28
|
+
'.css': 'text/css; charset=utf-8',
|
|
29
|
+
'.json': 'application/json',
|
|
30
|
+
'.svg': 'image/svg+xml',
|
|
31
|
+
'.png': 'image/png',
|
|
32
|
+
'.jpg': 'image/jpeg',
|
|
33
|
+
'.jpeg': 'image/jpeg',
|
|
34
|
+
'.webp': 'image/webp',
|
|
35
|
+
'.glb': 'model/gltf-binary',
|
|
36
|
+
'.gltf': 'model/gltf+json',
|
|
37
|
+
'.bin': 'application/octet-stream',
|
|
38
|
+
'.ktx2': 'image/ktx2',
|
|
39
|
+
'.hdr': 'application/octet-stream',
|
|
40
|
+
// The other kinds a planet carries (@nowhere/schema ASSET_KINDS): an EXR
|
|
41
|
+
// sky, a LUT and a splat are bytes to the page, which decodes them itself.
|
|
42
|
+
'.exr': 'application/octet-stream',
|
|
43
|
+
'.cube': 'text/plain; charset=utf-8',
|
|
44
|
+
'.spz': 'application/octet-stream',
|
|
45
|
+
'.wasm': 'application/wasm',
|
|
46
|
+
'.mp3': 'audio/mpeg',
|
|
47
|
+
'.ogg': 'audio/ogg',
|
|
48
|
+
'.opus': 'audio/ogg',
|
|
49
|
+
'.wav': 'audio/wav',
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const IGNORED = /(^|[\\/])(node_modules|\.git|\.nowhere|dist)([\\/]|$)/
|
|
53
|
+
const MAX_BODY = 256 * 1024 * 1024
|
|
54
|
+
|
|
55
|
+
export const devFile = (root) => path.join(root, '.nowhere', 'dev.json')
|
|
56
|
+
|
|
57
|
+
/** A running preview for `root` in another process, or null. */
|
|
58
|
+
export async function findRunning(root) {
|
|
59
|
+
let info
|
|
60
|
+
try {
|
|
61
|
+
info = JSON.parse(await fsp.readFile(devFile(root), 'utf8'))
|
|
62
|
+
} catch {
|
|
63
|
+
return null
|
|
64
|
+
}
|
|
65
|
+
try {
|
|
66
|
+
const res = await fetch(`http://127.0.0.1:${info.port}/api/ping?t=${info.token}`, { signal: AbortSignal.timeout(1500) })
|
|
67
|
+
if (!res.ok) return null
|
|
68
|
+
const body = await res.json()
|
|
69
|
+
if (body.root !== root) return null
|
|
70
|
+
} catch {
|
|
71
|
+
return null
|
|
72
|
+
}
|
|
73
|
+
return {
|
|
74
|
+
url: `http://127.0.0.1:${info.port}/?t=${info.token}`,
|
|
75
|
+
async request(method, params = {}, timeoutMs = 30_000) {
|
|
76
|
+
const res = await fetch(`http://127.0.0.1:${info.port}/api/control?t=${info.token}`, {
|
|
77
|
+
method: 'POST',
|
|
78
|
+
headers: { 'content-type': 'application/json' },
|
|
79
|
+
body: JSON.stringify({ method, params, timeoutMs }),
|
|
80
|
+
signal: AbortSignal.timeout(timeoutMs + 5000),
|
|
81
|
+
})
|
|
82
|
+
return res.json()
|
|
83
|
+
},
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function readBody(req) {
|
|
88
|
+
return new Promise((resolve, reject) => {
|
|
89
|
+
const chunks = []
|
|
90
|
+
let size = 0
|
|
91
|
+
req.on('data', (c) => {
|
|
92
|
+
size += c.length
|
|
93
|
+
if (size > MAX_BODY) {
|
|
94
|
+
reject(new Error('too large'))
|
|
95
|
+
req.destroy()
|
|
96
|
+
return
|
|
97
|
+
}
|
|
98
|
+
chunks.push(c)
|
|
99
|
+
})
|
|
100
|
+
req.on('end', () => resolve(Buffer.concat(chunks)))
|
|
101
|
+
req.on('error', reject)
|
|
102
|
+
})
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const json = (res, status, value) => {
|
|
106
|
+
res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' })
|
|
107
|
+
res.end(JSON.stringify(value))
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** A path inside `base` for `rel`, or null when it would leave it or names a
|
|
111
|
+
* hidden or dependency folder. */
|
|
112
|
+
function inside(base, rel) {
|
|
113
|
+
const clean = decodeURIComponent(rel).replace(/\\/g, '/')
|
|
114
|
+
if (clean.split('/').some((part) => part === '..' || part.startsWith('.') || part === 'node_modules')) return null
|
|
115
|
+
const abs = path.resolve(base, clean)
|
|
116
|
+
return abs === base || abs.startsWith(base + path.sep) ? abs : null
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Starts the preview for the project at `root`. Resolves once it listens:
|
|
121
|
+
* { url, port, token, connected(), waitForPage(ms), request(method, params,
|
|
122
|
+
* timeoutMs), runtime(), rebuild(), close() }.
|
|
123
|
+
*/
|
|
124
|
+
export async function startDevServer({ root, port = 0, log = () => {} }) {
|
|
125
|
+
const token = crypto.randomBytes(18).toString('base64url')
|
|
126
|
+
const clients = new Set()
|
|
127
|
+
const pending = new Map()
|
|
128
|
+
const waiters = new Set()
|
|
129
|
+
let seq = 0
|
|
130
|
+
let latest = { bundle: null }
|
|
131
|
+
// What the page last said about the game it runs.
|
|
132
|
+
let runtime = { mounted: false, errors: [], status: null, at: 0 }
|
|
133
|
+
|
|
134
|
+
const push = (msg) => {
|
|
135
|
+
const line = `data: ${JSON.stringify(msg)}\n\n`
|
|
136
|
+
for (const res of clients) res.write(line)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async function rebuild({ send = true } = {}) {
|
|
140
|
+
const built = await buildBundle(root)
|
|
141
|
+
latest.bundle = built
|
|
142
|
+
if (send) push({ type: 'bundle', ok: built.ok, code: built.ok ? built.code : undefined, error: built.ok ? undefined : built.error, warnings: built.ok ? built.warnings : undefined })
|
|
143
|
+
if (!built.ok) log(`build failed: ${built.error.split('\n')[0]}`)
|
|
144
|
+
return built
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Asks the page; rejects when no page is open or it does not answer. */
|
|
148
|
+
function request(method, params = {}, timeoutMs = 30_000) {
|
|
149
|
+
if (clients.size === 0) return Promise.reject(new Error('The preview page is not open.'))
|
|
150
|
+
return new Promise((resolve, reject) => {
|
|
151
|
+
const id = ++seq
|
|
152
|
+
const timer = setTimeout(() => {
|
|
153
|
+
pending.delete(id)
|
|
154
|
+
reject(new Error(`The preview page did not answer (${method}).`))
|
|
155
|
+
}, timeoutMs)
|
|
156
|
+
pending.set(id, { resolve, reject, timer })
|
|
157
|
+
push({ type: 'request', id, method, params })
|
|
158
|
+
})
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function waitForPage(ms) {
|
|
162
|
+
if (clients.size > 0) return Promise.resolve(true)
|
|
163
|
+
return new Promise((resolve) => {
|
|
164
|
+
const done = (ok) => {
|
|
165
|
+
waiters.delete(done)
|
|
166
|
+
clearTimeout(timer)
|
|
167
|
+
resolve(ok)
|
|
168
|
+
}
|
|
169
|
+
const timer = setTimeout(() => done(false), ms)
|
|
170
|
+
waiters.add(done)
|
|
171
|
+
})
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async function writePreview(dataUrl) {
|
|
175
|
+
const m = /^data:image\/png;base64,([A-Za-z0-9+/=]+)$/.exec(String(dataUrl ?? ''))
|
|
176
|
+
if (!m) return false
|
|
177
|
+
await fsp.mkdir(path.join(root, '.nowhere'), { recursive: true })
|
|
178
|
+
await fsp.writeFile(path.join(root, '.nowhere', 'preview.png'), Buffer.from(m[1], 'base64'))
|
|
179
|
+
return true
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async function writeScene(doc) {
|
|
183
|
+
const s = await schema()
|
|
184
|
+
const checked = s.validateScene(doc)
|
|
185
|
+
if (!checked.ok) return { ok: false, error: (checked.findings ?? []).map((f) => f.message).join('; ') }
|
|
186
|
+
const file = path.join(root, 'scene.json')
|
|
187
|
+
const tmp = `${file}.${process.pid}.tmp`
|
|
188
|
+
await fsp.writeFile(tmp, `${JSON.stringify(doc, null, 2)}\n`)
|
|
189
|
+
await fsp.rename(tmp, file)
|
|
190
|
+
return { ok: true }
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const server = http.createServer(async (req, res) => {
|
|
194
|
+
const url = new URL(req.url ?? '/', 'http://127.0.0.1')
|
|
195
|
+
const authed = url.searchParams.get('t') === token
|
|
196
|
+
try {
|
|
197
|
+
// The page and its built files: harmless without the token, and the
|
|
198
|
+
// page reads the token from its own address.
|
|
199
|
+
if (req.method === 'GET' && !url.pathname.startsWith('/api/') && !url.pathname.startsWith('/project/')) {
|
|
200
|
+
// The page names its icon itself (index.html); a browser that asks
|
|
201
|
+
// anyway gets nothing, not a 404 in its console.
|
|
202
|
+
if (url.pathname === '/favicon.ico') {
|
|
203
|
+
res.writeHead(204, { 'cache-control': 'no-store' })
|
|
204
|
+
return res.end()
|
|
205
|
+
}
|
|
206
|
+
const file = url.pathname === '/' ? path.join(WEB, 'index.html') : inside(WEB, url.pathname.slice(1))
|
|
207
|
+
if (!file || !fs.existsSync(file) || fs.statSync(file).isDirectory()) return json(res, 404, { error: 'not found' })
|
|
208
|
+
res.writeHead(200, { 'content-type': MIME[path.extname(file)] ?? 'application/octet-stream', 'cache-control': 'no-store' })
|
|
209
|
+
return fs.createReadStream(file).pipe(res)
|
|
210
|
+
}
|
|
211
|
+
if (!authed) return json(res, 403, { error: 'forbidden' })
|
|
212
|
+
|
|
213
|
+
if (url.pathname === '/api/ping') return json(res, 200, { ok: true, root, connected: clients.size })
|
|
214
|
+
|
|
215
|
+
if (url.pathname === '/api/events') {
|
|
216
|
+
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' })
|
|
217
|
+
res.write(': Oda\n\n')
|
|
218
|
+
clients.add(res)
|
|
219
|
+
const docs = await readDocs(root)
|
|
220
|
+
const bundle = latest.bundle ?? (await rebuild({ send: false }))
|
|
221
|
+
res.write(
|
|
222
|
+
`data: ${JSON.stringify({
|
|
223
|
+
type: 'hello',
|
|
224
|
+
project: { name: path.basename(root) },
|
|
225
|
+
config: docs.config,
|
|
226
|
+
scene: docs.scene,
|
|
227
|
+
bundle: { ok: bundle.ok, code: bundle.ok ? bundle.code : undefined, error: bundle.ok ? undefined : bundle.error },
|
|
228
|
+
})}\n\n`,
|
|
229
|
+
)
|
|
230
|
+
for (const done of [...waiters]) done(true)
|
|
231
|
+
const keepAlive = setInterval(() => res.write(': ping\n\n'), 15_000)
|
|
232
|
+
req.on('close', () => {
|
|
233
|
+
clearInterval(keepAlive)
|
|
234
|
+
clients.delete(res)
|
|
235
|
+
})
|
|
236
|
+
return
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
if (url.pathname.startsWith('/project/')) {
|
|
240
|
+
const file = inside(root, url.pathname.slice('/project/'.length))
|
|
241
|
+
if (!file || !fs.existsSync(file) || fs.statSync(file).isDirectory()) return json(res, 404, { error: 'not found' })
|
|
242
|
+
res.writeHead(200, { 'content-type': MIME[path.extname(file).toLowerCase()] ?? 'application/octet-stream', 'cache-control': 'no-store' })
|
|
243
|
+
return fs.createReadStream(file).pipe(res)
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
if (req.method !== 'POST') return json(res, 405, { error: 'method' })
|
|
247
|
+
const body = JSON.parse((await readBody(req)).toString('utf8') || '{}')
|
|
248
|
+
|
|
249
|
+
if (url.pathname === '/api/reply') {
|
|
250
|
+
const entry = pending.get(body.id)
|
|
251
|
+
if (entry) {
|
|
252
|
+
pending.delete(body.id)
|
|
253
|
+
clearTimeout(entry.timer)
|
|
254
|
+
entry.resolve(body.result)
|
|
255
|
+
}
|
|
256
|
+
return json(res, 200, { ok: true })
|
|
257
|
+
}
|
|
258
|
+
if (url.pathname === '/api/runtime') {
|
|
259
|
+
runtime = { mounted: !!body.mounted, errors: Array.isArray(body.errors) ? body.errors.slice(0, 50).map(String) : [], status: body.status ?? null, at: Date.now() }
|
|
260
|
+
return json(res, 200, { ok: true })
|
|
261
|
+
}
|
|
262
|
+
if (url.pathname === '/api/preview') return json(res, 200, { ok: await writePreview(body.png) })
|
|
263
|
+
if (url.pathname === '/api/scene') return json(res, 200, await writeScene(body.doc))
|
|
264
|
+
if (url.pathname === '/api/control') {
|
|
265
|
+
// Another process's request, passed on to the page.
|
|
266
|
+
try {
|
|
267
|
+
if (body.method === 'rebuild') return json(res, 200, { ok: true, result: await rebuild() })
|
|
268
|
+
if (body.method === 'runtime') return json(res, 200, { ok: true, result: runtime })
|
|
269
|
+
const result = await request(body.method, body.params ?? {}, Math.min(Number(body.timeoutMs) || 30_000, 180_000))
|
|
270
|
+
return json(res, 200, { ok: true, result })
|
|
271
|
+
} catch (err) {
|
|
272
|
+
return json(res, 200, { ok: false, error: err.message })
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
return json(res, 404, { error: 'not found' })
|
|
276
|
+
} catch (err) {
|
|
277
|
+
if (!res.headersSent) json(res, 500, { error: err.message })
|
|
278
|
+
}
|
|
279
|
+
})
|
|
280
|
+
|
|
281
|
+
await new Promise((resolve, reject) => {
|
|
282
|
+
server.once('error', reject)
|
|
283
|
+
server.listen(port, '127.0.0.1', resolve)
|
|
284
|
+
})
|
|
285
|
+
const actual = server.address().port
|
|
286
|
+
const url = `http://127.0.0.1:${actual}/?t=${token}`
|
|
287
|
+
|
|
288
|
+
// Saves, pushed as they land. A burst of writes (an editor's save, an agent
|
|
289
|
+
// writing three files) becomes one rebuild.
|
|
290
|
+
let timer = null
|
|
291
|
+
const changed = new Set()
|
|
292
|
+
const flush = async () => {
|
|
293
|
+
timer = null
|
|
294
|
+
const files = [...changed]
|
|
295
|
+
changed.clear()
|
|
296
|
+
if (files.some((f) => f.startsWith('src/') || /\.(ts|tsx|js|mjs|json)$/.test(f) && !['game.config.json', 'scene.json'].includes(f))) await rebuild()
|
|
297
|
+
if (files.includes('game.config.json') || files.includes('scene.json')) {
|
|
298
|
+
const docs = await readDocs(root)
|
|
299
|
+
if (files.includes('game.config.json')) push({ type: 'config', config: docs.config })
|
|
300
|
+
if (files.includes('scene.json')) push({ type: 'scene', scene: docs.scene })
|
|
301
|
+
}
|
|
302
|
+
for (const f of files.filter((f) => f.startsWith('assets/'))) push({ type: 'asset', path: f })
|
|
303
|
+
}
|
|
304
|
+
let watcher = null
|
|
305
|
+
try {
|
|
306
|
+
watcher = fs.watch(root, { recursive: true }, (_event, filename) => {
|
|
307
|
+
if (!filename) return
|
|
308
|
+
const rel = filename.replace(/\\/g, '/')
|
|
309
|
+
if (IGNORED.test(rel) || rel.endsWith('.tmp')) return
|
|
310
|
+
changed.add(rel)
|
|
311
|
+
clearTimeout(timer)
|
|
312
|
+
timer = setTimeout(flush, 120)
|
|
313
|
+
})
|
|
314
|
+
} catch (err) {
|
|
315
|
+
log(`file watching is not available here (${err.message}); reload the page to see changes`)
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
await fsp.mkdir(path.join(root, '.nowhere'), { recursive: true })
|
|
319
|
+
await fsp.writeFile(devFile(root), JSON.stringify({ port: actual, token, pid: process.pid }))
|
|
320
|
+
|
|
321
|
+
let closed = false
|
|
322
|
+
const close = async () => {
|
|
323
|
+
if (closed) return
|
|
324
|
+
closed = true
|
|
325
|
+
watcher?.close()
|
|
326
|
+
for (const res of clients) res.end()
|
|
327
|
+
for (const { reject, timer: t } of pending.values()) {
|
|
328
|
+
clearTimeout(t)
|
|
329
|
+
reject(new Error('The preview closed.'))
|
|
330
|
+
}
|
|
331
|
+
server.close()
|
|
332
|
+
try {
|
|
333
|
+
const info = JSON.parse(fs.readFileSync(devFile(root), 'utf8'))
|
|
334
|
+
if (info.token === token) fs.rmSync(devFile(root), { force: true })
|
|
335
|
+
} catch {
|
|
336
|
+
// already gone
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
return {
|
|
341
|
+
url,
|
|
342
|
+
port: actual,
|
|
343
|
+
token,
|
|
344
|
+
connected: () => clients.size > 0,
|
|
345
|
+
waitForPage,
|
|
346
|
+
request,
|
|
347
|
+
runtime: () => runtime,
|
|
348
|
+
rebuild,
|
|
349
|
+
close,
|
|
350
|
+
}
|
|
351
|
+
}
|
package/lib/headless.mjs
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
// Headless Chrome for `nowhere make`: the runner's eyes on the game, on the
|
|
2
|
+
// machine's real GPU (WebGPU through Metal, D3D or Vulkan) and with no window.
|
|
3
|
+
// Chrome is only ever started here, and only with --headless=new: the
|
|
4
|
+
// argument list is checked before anything is spawned, so no code path can
|
|
5
|
+
// open a window on the creator's screen.
|
|
6
|
+
//
|
|
7
|
+
// The flags are the ones the real-GPU checks ran with on 2026-10-21 (Chrome
|
|
8
|
+
// 155 on Apple metal-3): WebGPU switched on, the GPU sandbox off (headless
|
|
9
|
+
// Chrome on a Mac has no GPU without it), and nothing that slows a page no one
|
|
10
|
+
// is looking at (background timers, renderer backgrounding, occlusion).
|
|
11
|
+
|
|
12
|
+
import { execFileSync, spawn as spawnProcess } from 'node:child_process'
|
|
13
|
+
import fs from 'node:fs'
|
|
14
|
+
import os from 'node:os'
|
|
15
|
+
import path from 'node:path'
|
|
16
|
+
|
|
17
|
+
export const HEADLESS = '--headless=new'
|
|
18
|
+
|
|
19
|
+
/** Chrome's environment: the caller's, without its keys. Chrome needs none
|
|
20
|
+
* of them, and a crash report or a child of its own never sees them. The
|
|
21
|
+
* runner (make.mjs) and the tools' headless preview (headlessPreview.mjs)
|
|
22
|
+
* both start Chrome with this. */
|
|
23
|
+
export function chromeEnv(env) {
|
|
24
|
+
return Object.fromEntries(Object.entries(env ?? {}).filter(([name]) => !/^(ANTHROPIC|CLAUDE)|KEY|TOKEN|SECRET|PASSWORD/i.test(name)))
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Where Chrome or Chromium usually lives, per platform. */
|
|
28
|
+
function candidates({ env, platform, home }) {
|
|
29
|
+
if (platform === 'darwin') {
|
|
30
|
+
return [
|
|
31
|
+
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
|
|
32
|
+
path.join(home, 'Applications', 'Google Chrome.app', 'Contents', 'MacOS', 'Google Chrome'),
|
|
33
|
+
'/Applications/Chromium.app/Contents/MacOS/Chromium',
|
|
34
|
+
path.join(home, 'Applications', 'Chromium.app', 'Contents', 'MacOS', 'Chromium'),
|
|
35
|
+
]
|
|
36
|
+
}
|
|
37
|
+
if (platform === 'win32') {
|
|
38
|
+
const roots = [env.PROGRAMFILES, env['PROGRAMFILES(X86)'], env.LOCALAPPDATA].filter(Boolean)
|
|
39
|
+
return roots.flatMap((root) => [path.join(root, 'Google', 'Chrome', 'Application', 'chrome.exe'), path.join(root, 'Chromium', 'Application', 'chrome.exe')])
|
|
40
|
+
}
|
|
41
|
+
// Linux and the rest: the usual names, wherever PATH has them.
|
|
42
|
+
const names = ['google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser']
|
|
43
|
+
const dirs = String(env.PATH ?? '').split(path.delimiter).filter(Boolean)
|
|
44
|
+
return names.flatMap((name) => dirs.map((dir) => path.join(dir, name)))
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The Chrome to start: NOWHERE_CHROME when it names a file, else the first
|
|
48
|
+
* usual place that has one. Null when there is none. */
|
|
49
|
+
export function findChrome({ env = process.env, platform = process.platform, exists = fs.existsSync, home = os.homedir() } = {}) {
|
|
50
|
+
const own = typeof env.NOWHERE_CHROME === 'string' ? env.NOWHERE_CHROME.trim() : ''
|
|
51
|
+
if (own) return exists(own) ? own : null
|
|
52
|
+
return candidates({ env, platform, home }).find((file) => exists(file)) ?? null
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export const NO_CHROME = 'oda make needs Google Chrome or Chromium to see the game (it runs headless, with no window), and found neither. Install Chrome, or set NOWHERE_CHROME to its executable.'
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Chrome's name and version, read without starting a browser where that is
|
|
59
|
+
* possible: on a Mac from the app's Info.plist, on Windows from the version
|
|
60
|
+
* folder beside chrome.exe. Elsewhere `--version`, which prints and exits,
|
|
61
|
+
* and is headless too, as every Chrome this starts is. Null when it cannot
|
|
62
|
+
* be told.
|
|
63
|
+
*/
|
|
64
|
+
export function chromeVersion(file, { platform = process.platform } = {}) {
|
|
65
|
+
try {
|
|
66
|
+
if (platform === 'darwin') {
|
|
67
|
+
const plist = fs.readFileSync(path.resolve(path.dirname(file), '..', 'Info.plist'), 'utf8')
|
|
68
|
+
const field = (key) => new RegExp(`<key>${key}</key>\\s*<string>([^<]+)</string>`).exec(plist)?.[1]?.trim()
|
|
69
|
+
const version = field('CFBundleShortVersionString')
|
|
70
|
+
return version ? `${field('CFBundleName') ?? 'Chrome'} ${version}` : null
|
|
71
|
+
}
|
|
72
|
+
if (platform === 'win32') {
|
|
73
|
+
const version = fs.readdirSync(path.dirname(file)).filter((n) => /^\d+\.\d+\.\d+\.\d+$/.test(n)).sort().pop()
|
|
74
|
+
return version ? `Chrome ${version}` : null
|
|
75
|
+
}
|
|
76
|
+
return execFileSync(file, [HEADLESS, '--version'], { encoding: 'utf8', timeout: 10_000, stdio: ['ignore', 'pipe', 'ignore'] }).trim() || null
|
|
77
|
+
} catch {
|
|
78
|
+
return null
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The whole argument list `launch` starts Chrome with, the page last. */
|
|
83
|
+
export function chromeArgs({ url, profileDir }) {
|
|
84
|
+
return [
|
|
85
|
+
HEADLESS,
|
|
86
|
+
'--enable-unsafe-webgpu',
|
|
87
|
+
'--disable-gpu-sandbox',
|
|
88
|
+
`--user-data-dir=${profileDir}`,
|
|
89
|
+
'--no-first-run',
|
|
90
|
+
'--no-default-browser-check',
|
|
91
|
+
'--mute-audio',
|
|
92
|
+
'--disable-background-timer-throttling',
|
|
93
|
+
'--disable-renderer-backgrounding',
|
|
94
|
+
'--disable-backgrounding-occluded-windows',
|
|
95
|
+
'--window-size=1280,800',
|
|
96
|
+
url,
|
|
97
|
+
]
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Throws unless the argument list starts Chrome headless. */
|
|
101
|
+
export function assertHeadless(args) {
|
|
102
|
+
if (!Array.isArray(args) || !args.includes(HEADLESS)) {
|
|
103
|
+
throw new Error(`Refused to start Chrome: its arguments lack ${HEADLESS}, and Oda never opens a window.`)
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Spawns Chrome with `args`, after checking them (assertHeadless): the one
|
|
109
|
+
* place a Chrome process is made. On macOS and Linux it gets a process group
|
|
110
|
+
* of its own, so a kill takes its GPU and renderer helpers too, and a Ctrl+C
|
|
111
|
+
* in the terminal reaches the runner first rather than Chrome.
|
|
112
|
+
*/
|
|
113
|
+
export function spawnChrome(file, args, { spawn = spawnProcess, env = process.env } = {}) {
|
|
114
|
+
assertHeadless(args)
|
|
115
|
+
return spawn(file, args, { stdio: ['ignore', 'pipe', 'pipe'], env, detached: process.platform !== 'win32', windowsHide: true })
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const TAIL_LINES = 200
|
|
119
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Starts headless Chrome on `url`. The profile is a fresh temp folder unless
|
|
123
|
+
* one is given, and the one made here is removed once Chrome has gone.
|
|
124
|
+
* Resolves once the process is running: { pid, path, version, args,
|
|
125
|
+
* profileDir, alive(), exited, kill(), tail(n) }, where `exited` resolves
|
|
126
|
+
* with { code, signal } and `kill()` with the same once Chrome is gone.
|
|
127
|
+
*/
|
|
128
|
+
export async function launch({ url, profileDir, chrome, spawn, env = process.env } = {}) {
|
|
129
|
+
if (typeof url !== 'string' || !url) throw new Error('launch needs the page to open (url).')
|
|
130
|
+
const file = chrome ?? findChrome({ env })
|
|
131
|
+
if (!file) throw new Error(NO_CHROME)
|
|
132
|
+
const own = !profileDir
|
|
133
|
+
const profile = profileDir ?? fs.mkdtempSync(path.join(os.tmpdir(), 'nowhere-chrome-'))
|
|
134
|
+
const args = chromeArgs({ url, profileDir: profile })
|
|
135
|
+
const version = chromeVersion(file)
|
|
136
|
+
|
|
137
|
+
let child
|
|
138
|
+
try {
|
|
139
|
+
child = spawnChrome(file, args, { spawn, env })
|
|
140
|
+
} catch (err) {
|
|
141
|
+
if (own) fs.rmSync(profile, { recursive: true, force: true })
|
|
142
|
+
throw err
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// What Chrome says, for the sentence that explains a failed start.
|
|
146
|
+
const lines = []
|
|
147
|
+
const keep = (chunk) => {
|
|
148
|
+
for (const line of String(chunk).split('\n')) {
|
|
149
|
+
if (!line.trim()) continue
|
|
150
|
+
lines.push(line)
|
|
151
|
+
if (lines.length > TAIL_LINES) lines.shift()
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
child.stdout?.on('data', keep)
|
|
155
|
+
child.stderr?.on('data', keep)
|
|
156
|
+
|
|
157
|
+
let gone = null
|
|
158
|
+
const exited = new Promise((resolve) => {
|
|
159
|
+
child.once('exit', (code, signal) => {
|
|
160
|
+
gone = { code, signal }
|
|
161
|
+
resolve(gone)
|
|
162
|
+
})
|
|
163
|
+
})
|
|
164
|
+
await new Promise((resolve, reject) => {
|
|
165
|
+
child.once('spawn', resolve)
|
|
166
|
+
child.once('error', (err) => {
|
|
167
|
+
if (own) fs.rmSync(profile, { recursive: true, force: true })
|
|
168
|
+
reject(new Error(`Chrome did not start (${file}): ${err.message}`))
|
|
169
|
+
})
|
|
170
|
+
})
|
|
171
|
+
|
|
172
|
+
const signalAll = (signal) => {
|
|
173
|
+
try {
|
|
174
|
+
// The group first (its helpers), then the process itself.
|
|
175
|
+
if (process.platform !== 'win32') process.kill(-child.pid, signal)
|
|
176
|
+
else child.kill(signal)
|
|
177
|
+
} catch {
|
|
178
|
+
try {
|
|
179
|
+
child.kill(signal)
|
|
180
|
+
} catch {
|
|
181
|
+
// already gone
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
let killing = null
|
|
187
|
+
async function kill() {
|
|
188
|
+
killing ??= (async () => {
|
|
189
|
+
if (!gone) {
|
|
190
|
+
signalAll('SIGTERM')
|
|
191
|
+
const ended = await Promise.race([exited, sleep(5000).then(() => null)])
|
|
192
|
+
if (!ended) {
|
|
193
|
+
signalAll('SIGKILL')
|
|
194
|
+
await Promise.race([exited, sleep(3000)])
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
// A helper that outlived the browser (a GPU process mid-frame) goes too.
|
|
198
|
+
if (process.platform !== 'win32') {
|
|
199
|
+
try {
|
|
200
|
+
process.kill(-child.pid, 'SIGKILL')
|
|
201
|
+
} catch {
|
|
202
|
+
// the group is already empty
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
// Chrome's helpers may still hold the profile for a moment.
|
|
206
|
+
if (own) {
|
|
207
|
+
for (let i = 0; i < 10 && fs.existsSync(profile); i++) {
|
|
208
|
+
try {
|
|
209
|
+
fs.rmSync(profile, { recursive: true, force: true })
|
|
210
|
+
} catch {
|
|
211
|
+
await sleep(200)
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return gone ?? { code: null, signal: 'SIGKILL' }
|
|
216
|
+
})()
|
|
217
|
+
return killing
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
return {
|
|
221
|
+
pid: child.pid,
|
|
222
|
+
path: file,
|
|
223
|
+
version,
|
|
224
|
+
args,
|
|
225
|
+
profileDir: profile,
|
|
226
|
+
alive: () => gone === null,
|
|
227
|
+
exited,
|
|
228
|
+
kill,
|
|
229
|
+
tail: (n = 20) => lines.slice(-n),
|
|
230
|
+
}
|
|
231
|
+
}
|