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
@@ -0,0 +1,363 @@
1
+ // Downloads in the agent's browser land in quarantine, never straight in the
2
+ // project: <project>/.nowhere/quarantine/, outside git and the watcher, with a
3
+ // manifest of where each file came from and whether it is what its name says.
4
+ // The agent reads the license, then brings a checked file into the game with
5
+ // asset_import (tools/assets.mjs), or into blender/ with nw_take_download
6
+ // (tools/cards.mjs): those are the only ways out.
7
+ //
8
+ // The first download, like the first web search, needs the creator's consent;
9
+ // it is asked in a chat card (cards.cjs) and remembered. Electron-free: the
10
+ // browser hands willDownload() its DownloadItem, and the check hands it a fake.
11
+
12
+ const crypto = require('node:crypto')
13
+ const fs = require('node:fs')
14
+ const fsp = require('node:fs/promises')
15
+ const path = require('node:path')
16
+
17
+ // Forward slashes on every system: it is also how tool results name the folder,
18
+ // and path.join takes them on Windows too.
19
+ const QUARANTINE = '.nowhere/quarantine'
20
+ const MANIFEST = 'index.json'
21
+ const MB = 1024 * 1024
22
+
23
+ /** The most one download may weigh, by what it is: a browser download
24
+ * (createDownloads' default), and asset_fetch's caps for a library item
25
+ * (all of its files together). A material zip is the heaviest honest case:
26
+ * ambientCG's 2K sets reach tens of megabytes, its 8K sets over a gigabyte. */
27
+ const QUARANTINE_LIMITS = Object.freeze({
28
+ browser: 300 * MB,
29
+ model: 200 * MB,
30
+ material: 300 * MB,
31
+ hdri: 100 * MB,
32
+ generated: 200 * MB,
33
+ })
34
+
35
+ // Hosts whose terms forbid feeding their images to AI tools (phase1 spec 2.11):
36
+ // the creator may look at them, the agent may not fetch from them.
37
+ const BLOCKED_HOSTS = [/(^|\.)artstation\.com$/, /(^|\.)pinterest\.[a-z.]+$/, /(^|\.)pinimg\.com$/, /(^|\.)behance\.net$/]
38
+
39
+ const startsWith = (buf, bytes) => bytes.every((b, i) => buf[i] === b)
40
+ const ascii = (s) => [...Buffer.from(s, 'latin1')]
41
+ const text = (buf, n = buf.length) => buf.subarray(0, n).toString('latin1')
42
+ const riff = (form) => (buf) => startsWith(buf, ascii('RIFF')) && text(buf.subarray(8, 12)) === form
43
+
44
+ /**
45
+ * What may be downloaded, by extension, and how to tell the file is really
46
+ * one. `magic(head, file, size)` gets the first 64 KB; the few checks that
47
+ * need the whole file (a .gltf's JSON) read it themselves.
48
+ */
49
+ const DOWNLOAD_TYPES = Object.freeze({
50
+ '.glb': { kind: 'model', magic: (h) => startsWith(h, ascii('glTF')) },
51
+ '.gltf': { kind: 'model', magic: (h, file, size) => gltfLooksRight(h, file, size) },
52
+ '.obj': { kind: 'model', magic: (h) => !h.includes(0) && /^v\s/m.test(text(h)) },
53
+ '.fbx': { kind: 'model', magic: (h) => startsWith(h, ascii('Kaydara FBX Binary')) || text(h).includes('FBXHeaderExtension') },
54
+ '.stl': { kind: 'model', magic: (h, _file, size) => stlLooksRight(h, size) },
55
+ '.ply': { kind: 'model', magic: (h) => startsWith(h, ascii('ply')) },
56
+ '.dae': { kind: 'model', magic: (h) => text(h, 4096).includes('COLLADA') },
57
+ '.3mf': { kind: 'model', magic: (h) => startsWith(h, [0x50, 0x4b, 0x03, 0x04]) },
58
+ '.usdz': { kind: 'model', magic: (h) => startsWith(h, ascii('PK')) },
59
+ '.png': { kind: 'image', magic: (h) => startsWith(h, [0x89, 0x50, 0x4e, 0x47]) },
60
+ '.jpg': { kind: 'image', magic: (h) => startsWith(h, [0xff, 0xd8, 0xff]) },
61
+ '.jpeg': { kind: 'image', magic: (h) => startsWith(h, [0xff, 0xd8, 0xff]) },
62
+ '.webp': { kind: 'image', magic: riff('WEBP') },
63
+ '.ktx2': { kind: 'image', magic: (h) => startsWith(h, [0xab, 0x4b, 0x54, 0x58, 0x20, 0x32, 0x30, 0xbb]) },
64
+ '.hdr': { kind: 'hdri', magic: (h) => startsWith(h, ascii('#?RADIANCE')) || startsWith(h, ascii('#?RGBE')) },
65
+ '.exr': { kind: 'hdri', magic: (h) => startsWith(h, [0x76, 0x2f, 0x31, 0x01]) },
66
+ '.wav': { kind: 'audio', magic: riff('WAVE') },
67
+ '.ogg': { kind: 'audio', magic: (h) => startsWith(h, ascii('OggS')) },
68
+ '.mp3': { kind: 'audio', magic: (h) => startsWith(h, ascii('ID3')) || (h[0] === 0xff && (h[1] & 0xe0) === 0xe0) },
69
+ '.flac': { kind: 'audio', magic: (h) => startsWith(h, ascii('fLaC')) },
70
+ '.zip': { kind: 'archive', magic: (h) => startsWith(h, [0x50, 0x4b, 0x03, 0x04]) },
71
+ // Blender writes compressed .blend files too (zstd since 3.0, gzip before),
72
+ // and many on the web are, so both wrappers count as well as the plain header.
73
+ '.blend': {
74
+ kind: 'blend',
75
+ magic: (h) => startsWith(h, ascii('BLENDER')) || startsWith(h, [0x28, 0xb5, 0x2f, 0xfd]) || startsWith(h, [0x1f, 0x8b]),
76
+ },
77
+ })
78
+
79
+ function stlLooksRight(head, size) {
80
+ // Binary: an 80-byte header, a triangle count, 50 bytes per triangle. Some
81
+ // binary files start their header with "solid" too, so the size test goes first.
82
+ if (size >= 84 && head.length >= 84 && 84 + head.readUInt32LE(80) * 50 === size) return true
83
+ return /^\s*solid/.test(text(head, 512))
84
+ }
85
+
86
+ function gltfLooksRight(head, file, size) {
87
+ if (!/^\s*\{/.test(text(head, 64))) return false
88
+ // A .gltf can carry its buffers inline as base64, so a big one is judged by
89
+ // its start rather than parsed whole.
90
+ if (size > 64 * MB) return text(head).includes('"asset"')
91
+ try {
92
+ const doc = JSON.parse(fs.readFileSync(file, 'utf8'))
93
+ return !!doc && typeof doc === 'object' && 'asset' in doc
94
+ } catch {
95
+ return false
96
+ }
97
+ }
98
+
99
+ const extOf = (name) => path.extname(String(name ?? '')).toLowerCase()
100
+
101
+ /** True when the URL's host is one the agent must not fetch from. */
102
+ function blockedHost(url) {
103
+ let host
104
+ try {
105
+ host = new URL(String(url)).hostname.toLowerCase()
106
+ } catch {
107
+ return false
108
+ }
109
+ return BLOCKED_HOSTS.some((re) => re.test(host))
110
+ }
111
+
112
+ const hostOf = (url) => {
113
+ try {
114
+ return new URL(String(url)).hostname
115
+ } catch {
116
+ return 'an unknown site'
117
+ }
118
+ }
119
+
120
+ /** The file is what its extension says: { ok, kind } or { ok: false, problem }. */
121
+ async function checkFile(file) {
122
+ const type = DOWNLOAD_TYPES[extOf(file)]
123
+ if (!type) return { ok: false, problem: `${extOf(file) || 'a file without an extension'} is not a type the studio takes` }
124
+ let size
125
+ let head
126
+ try {
127
+ size = (await fsp.stat(file)).size
128
+ const handle = await fsp.open(file, 'r')
129
+ try {
130
+ const buf = Buffer.alloc(Math.min(size, 64 * 1024))
131
+ const { bytesRead } = await handle.read(buf, 0, buf.length, 0)
132
+ head = buf.subarray(0, bytesRead)
133
+ } finally {
134
+ await handle.close()
135
+ }
136
+ } catch (err) {
137
+ return { ok: false, problem: `it could not be read (${err.code ?? 'unknown error'})` }
138
+ }
139
+ if (size === 0) return { ok: false, problem: 'the file is empty' }
140
+ // A site that wants a sign-in or a click-through answers with a page, saved
141
+ // under the name of the file the agent asked for.
142
+ const start = text(head, 512).toLowerCase()
143
+ if (start.includes('<!doctype') || start.includes('<html')) {
144
+ return { ok: false, problem: `this is a web page, not a ${type.kind} file` }
145
+ }
146
+ let fits = false
147
+ try {
148
+ fits = type.magic(head, file, size)
149
+ } catch {
150
+ fits = false
151
+ }
152
+ if (!fits) return { ok: false, problem: `this is not a real ${extOf(file)} file: its contents do not match the type` }
153
+ return { ok: true, kind: type.kind }
154
+ }
155
+
156
+ function emptyManifest() {
157
+ return { version: 1, files: [] }
158
+ }
159
+
160
+ function readManifest(root) {
161
+ try {
162
+ const doc = JSON.parse(fs.readFileSync(path.join(root, QUARANTINE, MANIFEST), 'utf8'))
163
+ if (!doc || doc.version !== 1 || !Array.isArray(doc.files)) return emptyManifest()
164
+ return { version: 1, files: doc.files.filter((f) => f && typeof f.id === 'string' && typeof f.file === 'string') }
165
+ } catch {
166
+ return emptyManifest()
167
+ }
168
+ }
169
+
170
+ function writeManifest(root, doc) {
171
+ const dir = path.join(root, QUARANTINE)
172
+ fs.mkdirSync(dir, { recursive: true })
173
+ const target = path.join(dir, MANIFEST)
174
+ const tmp = `${target}.${process.pid}.tmp`
175
+ fs.writeFileSync(tmp, `${JSON.stringify({ version: 1, files: doc?.files ?? [] }, null, 2)}\n`)
176
+ fs.renameSync(tmp, target)
177
+ }
178
+
179
+ /** The name a download is kept under: lowercased, [a-z0-9._-] only, extension kept. */
180
+ function safeName(name) {
181
+ const ext = extOf(name)
182
+ const stem = path
183
+ .basename(String(name ?? ''), path.extname(String(name ?? '')))
184
+ .toLowerCase()
185
+ .replace(/[^a-z0-9._-]+/g, '-')
186
+ .replace(/-{2,}/g, '-')
187
+ .replace(/^[-.]+|[-.]+$/g, '')
188
+ .slice(0, 100)
189
+ return `${stem || 'download'}${ext}`
190
+ }
191
+
192
+ function stamp(at) {
193
+ const d = new Date(at)
194
+ const p = (n) => String(n).padStart(2, '0')
195
+ return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`
196
+ }
197
+
198
+ const sizeMb = (bytes) => (bytes / MB).toFixed(bytes < MB ? 2 : 1)
199
+
200
+ async function sha256(file) {
201
+ const hash = crypto.createHash('sha256')
202
+ for await (const chunk of fs.createReadStream(file)) hash.update(chunk)
203
+ return hash.digest('hex')
204
+ }
205
+
206
+ function createDownloads({ projectRoot, consent, maxBytes = QUARANTINE_LIMITS.browser, now = Date.now }) {
207
+ // Manifest writes from downloads that finish together go one after another.
208
+ let writes = Promise.resolve()
209
+ const limit = `${Math.round(maxBytes / MB)} MB`
210
+
211
+ /**
212
+ * Electron's will-download handler. The save path has to be set inside the
213
+ * event or Electron shows a save dialog, so the file starts into quarantine
214
+ * at once, paused, and goes on only once the creator has allowed downloads.
215
+ * `context.pageUrl` is the tab's page, since a DownloadItem has no referrer.
216
+ */
217
+ function willDownload(item, note, context = {}) {
218
+ const name = item.getFilename() || 'a file'
219
+ const say = (line) => {
220
+ try {
221
+ note(line)
222
+ } catch {
223
+ // the tab is gone; nobody to tell
224
+ }
225
+ }
226
+ const refuse = (why) => {
227
+ item.cancel()
228
+ say(`A download (${name}) was refused: ${why}`)
229
+ }
230
+
231
+ let root = null
232
+ try {
233
+ root = projectRoot()
234
+ } catch {
235
+ root = null
236
+ }
237
+ const url = item.getURL()
238
+ const referrer = (typeof item.getReferrer === 'function' ? item.getReferrer() : '') || context.pageUrl || ''
239
+ const chain = typeof item.getURLChain === 'function' ? item.getURLChain() : []
240
+ if (!root) return refuse('no project is open to keep it in.')
241
+ if ([url, referrer, ...chain].some(blockedHost)) {
242
+ return refuse('ArtStation, Pinterest and Behance are for the creator\'s eyes only; their terms forbid feeding their images to AI tools.')
243
+ }
244
+ const ext = extOf(name)
245
+ if (!DOWNLOAD_TYPES[ext]) {
246
+ return refuse(`${ext || 'a file without an extension'} is not a model, texture, HDRI, sound, .zip or .blend file.`)
247
+ }
248
+ const total = item.getTotalBytes()
249
+ if (total > maxBytes) return refuse(`it is ${sizeMb(total)} MB, over the ${limit} a download may be.`)
250
+
251
+ const at = now()
252
+ const id = `${stamp(at)}-${crypto.randomBytes(3).toString('hex')}`
253
+ const dir = path.join(root, QUARANTINE)
254
+ const part = path.join(dir, `${id}.part`)
255
+ try {
256
+ fs.mkdirSync(dir, { recursive: true })
257
+ } catch (err) {
258
+ return refuse(`the quarantine folder could not be made (${err.code ?? 'unknown error'}).`)
259
+ }
260
+ item.setSavePath(part)
261
+ item.pause()
262
+
263
+ // Set when this module ended the download, so its own note is the only one.
264
+ let stopped = false
265
+ const removePart = () => fsp.rm(part, { force: true }).catch(() => {})
266
+
267
+ item.on('updated', () => {
268
+ if (stopped || item.getReceivedBytes() <= maxBytes) return
269
+ stopped = true
270
+ item.cancel()
271
+ void removePart()
272
+ say(`A download (${name}) was stopped: it passed the ${limit} a download may be.`)
273
+ })
274
+
275
+ item.on('done', (_event, state) => {
276
+ if (state !== 'completed') {
277
+ void removePart()
278
+ if (!stopped) say(`A download (${name}) did not finish (${state}).`)
279
+ return
280
+ }
281
+ void finish(item, { id, at, name, part, dir, url, referrer, root, say })
282
+ })
283
+
284
+ void Promise.resolve()
285
+ .then(() => consent('web'))
286
+ .catch(() => 'deny')
287
+ .then((answer) => {
288
+ if (stopped) return
289
+ if (answer === 'allow') {
290
+ item.resume()
291
+ return
292
+ }
293
+ stopped = true
294
+ item.cancel()
295
+ void removePart()
296
+ say(`A download (${name}) was refused: the creator has not allowed downloads.`)
297
+ })
298
+ }
299
+
300
+ async function finish(item, { id, at, name, part, dir, url, referrer, root, say }) {
301
+ const file = `${id}-${safeName(name)}`
302
+ const target = path.join(dir, file)
303
+ try {
304
+ await fsp.rename(part, target)
305
+ } catch (err) {
306
+ await fsp.rm(part, { force: true }).catch(() => {})
307
+ say(`A download (${name}) finished but could not be kept (${err.code ?? 'unknown error'}).`)
308
+ return
309
+ }
310
+ const check = await checkFile(target)
311
+ let bytes = 0
312
+ let digest = ''
313
+ try {
314
+ bytes = (await fsp.stat(target)).size
315
+ digest = await sha256(target)
316
+ } catch {
317
+ // The entry is written all the same, without the numbers.
318
+ }
319
+ const entry = {
320
+ id,
321
+ file,
322
+ name,
323
+ url,
324
+ referrer,
325
+ host: hostOf(url),
326
+ bytes,
327
+ sha256: digest,
328
+ kind: check.ok ? check.kind : (DOWNLOAD_TYPES[extOf(name)]?.kind ?? 'unknown'),
329
+ ok: check.ok,
330
+ problem: check.ok ? null : check.problem,
331
+ at: new Date(at).toISOString(),
332
+ }
333
+ writes = writes
334
+ .then(() => {
335
+ const doc = readManifest(root)
336
+ doc.files = [...doc.files.filter((f) => f.id !== id), entry]
337
+ writeManifest(root, doc)
338
+ })
339
+ .catch(() => {})
340
+ await writes
341
+ const verdict = check.ok ? `${check.kind} ok` : check.problem
342
+ say(
343
+ `Downloaded ${name} (${sizeMb(bytes)} MB) from ${entry.host} into quarantine as ${id}. Check: ${verdict}. Read its license before you use it, then bring it into the game with asset_import (from "${id}", with that license), or move it into blender/ for nw_blender with nw_take_download.`,
344
+ )
345
+ }
346
+
347
+ /** Resolves when every manifest write so far has landed (for checks). */
348
+ const idle = () => writes
349
+
350
+ return { willDownload, idle }
351
+ }
352
+
353
+ module.exports = {
354
+ createDownloads,
355
+ checkFile,
356
+ readManifest,
357
+ writeManifest,
358
+ blockedHost,
359
+ safeName,
360
+ QUARANTINE,
361
+ QUARANTINE_LIMITS,
362
+ DOWNLOAD_TYPES,
363
+ }
@@ -0,0 +1,78 @@
1
+ // The order for a space, as the run goes (SPACE_FIRST.md W5). The system
2
+ // prompt gives the order (references, measured over the whole board, the
3
+ // brief, then the environment, props, materials, the look and the hero
4
+ // views), and the stop gate holds the end of it (stopGate.mjs: a space ends
5
+ // with a brief.json, and the look set from it). Between the two, a model
6
+ // that starts building before it has written the brief hears the order once,
7
+ // in the next tool result, while there is still time to keep to it: a brief
8
+ // written after the space is built only describes what was built.
9
+ //
10
+ // Only for a request that builds a space (depth.space), only for edits of the
11
+ // space itself (its source, its config and scene, an import, a look, a
12
+ // Blender model), and only once a request. Writing the brief, or anything
13
+ // outside the space, is never noted.
14
+ //
15
+ // The reference loop (REFERENCE_LOOP.md 3) starts earlier still: its kickoff
16
+ // card comes before the first tool that builds, and its targets before the
17
+ // brief. A space built before any kickoff hears that once too, beside the
18
+ // brief's note (the host refuses a brief.json written before the targets
19
+ // once the kickoff stands, and a big job's first change waits for the
20
+ // kickoff's cost approval anyway).
21
+
22
+ import fs from 'node:fs'
23
+ import path from 'node:path'
24
+
25
+ const BRIEF = 'brief.json'
26
+ /** The tools that change the space whatever file they name. */
27
+ const SPACE_TOOLS = new Set(['mcp__nw__look_apply', 'look_apply', 'mcp__nw__asset_import', 'asset_import', 'mcp__nw__nw_blender', 'nw_blender'])
28
+ const SPACE_FILES = new Set(['game.config.json', 'scene.json'])
29
+
30
+ export const FLOW_NOTE =
31
+ 'This request builds a space, and there is no brief.json yet. The order for a space puts the brief before anything visual: the kickoff (nw_ask_kickoff), style.json (how the space is drawn: nw_guide "style"), the target pictures (image_generate kind "target" in that style, or four or more photos from the creator) settled with nw_ask_targets, then nw_reference with board true over the reference board, then brief.json (nw_schema kind "brief") and brief.md from those numbers, its hero views citing the targets. Write the brief now, then build to it: code first (procedural geometry and TSL), scanned CC0 libraries for what code cannot bring to the targets (or a splat: the creator\'s file, or Marble when the kickoff chose it), the props (a generated one only for a prop, delit), asset_inspect against its texel density, look_apply from the brief\'s numbers until lookWarnings is empty, rounds at the hero views H1 to H6 with nw_round (look_compare and the judge), the approval card, and the stop gate.'
32
+
33
+ export const KICKOFF_NOTE =
34
+ 'This request builds a space, and its kickoff card has not been shown. The reference loop starts with it: nw_ask_kickoff now (the questions, how the environment is made, the speed level and its cost), then style.json (how the space is drawn), then the target pictures (image_generate kind "target", nw_ask_targets), then brief.json, then rounds of building judged with nw_round, then the approval card (nw_ask_approval).'
35
+
36
+ /** Whether a tool call edits the space itself (not the brief, not a note of the agent's). */
37
+ export function editsSpace(projectRoot, toolName, input) {
38
+ if (SPACE_TOOLS.has(toolName)) return true
39
+ const file = input?.file_path ?? input?.path ?? input?.notebook_path
40
+ if (typeof file !== 'string' || !file) return false
41
+ const rel = path.relative(projectRoot, path.resolve(projectRoot, file)).split(path.sep).join('/')
42
+ if (rel.startsWith('..') || path.isAbsolute(rel)) return false
43
+ return rel.startsWith('src/') || SPACE_FILES.has(rel)
44
+ }
45
+
46
+ /**
47
+ * @param {{ projectRoot: string, building: boolean, loop?: { kickoff: object | null } | null }} options
48
+ * building: the request builds a space (host.mjs: depth.space, not every
49
+ * big request). loop: the request's reference loop (loop/state.mjs), when
50
+ * the host runs one; its kickoff is what the kickoff note waits for.
51
+ */
52
+ export function createFlowWatch({ projectRoot, building, loop = null }) {
53
+ let said = false
54
+ let kickoffSaid = false
55
+ let pending = []
56
+ return {
57
+ /** A tool that may edit ran (host.mjs EDITS). Synchronous, for the other vendors' afterTool too. */
58
+ noteEdit(toolName, input) {
59
+ if (!building || !editsSpace(projectRoot, toolName, input)) return
60
+ if (loop && !kickoffSaid && !loop.kickoff) {
61
+ kickoffSaid = true
62
+ pending.push(KICKOFF_NOTE)
63
+ }
64
+ if (said) return
65
+ said = true
66
+ if (!fs.existsSync(path.join(projectRoot, BRIEF))) pending.push(FLOW_NOTE)
67
+ },
68
+ /** The note due now, once; null for none. */
69
+ note() {
70
+ const n = pending.length ? pending.join('\n\n') : null
71
+ pending = []
72
+ return n
73
+ },
74
+ get said() {
75
+ return said
76
+ },
77
+ }
78
+ }