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,479 @@
1
+ // The agent's side of the chat cards (agent/cards.cjs) and of the download
2
+ // quarantine (agent/downloads.cjs):
3
+ // nw_ask shows a card in the chat and waits for the creator's answer
4
+ // nw_take_download moves a checked download out of quarantine into blender/,
5
+ // for nw_blender; files for the game go through asset_import
6
+ //
7
+ // Tool modules export TOOLS (ToolDefs, phase1 spec 2.2) and RPC_METHODS; the
8
+ // registry (tools/index.mjs) turns them into Claude and other-vendor tools.
9
+ // Handlers never throw and are testable with a stub ctx.
10
+
11
+ import { z } from 'zod'
12
+ import { createRequire } from 'node:module'
13
+ import fs from 'node:fs'
14
+ import fsp from 'node:fs/promises'
15
+ import path from 'node:path'
16
+ import { webLookOnlyAmong } from '../reference/web.mjs'
17
+
18
+ const require = createRequire(import.meta.url)
19
+ const { QUARANTINE, readManifest, writeManifest, checkFile, blockedHost, DOWNLOAD_TYPES } = require('../downloads.cjs')
20
+ let localeModule
21
+ try {
22
+ localeModule = require('../locale.cjs')
23
+ } catch {
24
+ localeModule = null
25
+ }
26
+
27
+ export const RPC_METHODS = ['ask']
28
+
29
+ // cards.cjs gives up after 30 minutes and answers "timeout"; the rpc waits a
30
+ // minute longer so that answer, not a bare rpc timeout, is what comes back.
31
+ export const ASK_TIMEOUT_MS = 31 * 60_000
32
+
33
+ const MB = 1024 * 1024
34
+ const schema = await import('../../schema/dist/index.js').catch(() => null)
35
+ // What nw_blender reads from blender/. Nothing goes into assets/ this way:
36
+ // asset_import is the one way a file from outside comes into the game, so
37
+ // every such file is checked, optimised and recorded in the ledger.
38
+ const INTO = {
39
+ blender: new Set(['model', 'image', 'hdri', 'blend']),
40
+ }
41
+ const ASSETS_REFUSAL = 'Files for the game come in through asset_import, which checks, optimises and records the licence.'
42
+
43
+ // The ledger (assets/ledger.mjs) is loaded when a move records into it, so a
44
+ // tree without it (or without the schema it needs) still has nw_ask.
45
+ let ledgerModule
46
+ const ledgerOf = async () => (ledgerModule ??= await import('../assets/ledger.mjs').catch(() => null))
47
+
48
+ // The catalog is read through the main process's connector module, which is
49
+ // Electron-free; loaded on first use so a broken catalog only fails key cards.
50
+ let connectorsModule
51
+ function catalogEntry(id) {
52
+ try {
53
+ connectorsModule ??= require('../../connectors.cjs')
54
+ return connectorsModule.entryFor(id)
55
+ } catch {
56
+ return null
57
+ }
58
+ }
59
+ function keyServices() {
60
+ try {
61
+ connectorsModule ??= require('../../connectors.cjs')
62
+ return connectorsModule
63
+ .loadCatalog()
64
+ .filter((e) => e.auth.type === 'apiKey' && e.id !== 'anthropic')
65
+ .map((e) => e.id)
66
+ } catch {
67
+ return []
68
+ }
69
+ }
70
+
71
+ const fail = (text) => ({ text, isError: true })
72
+ const issues = (error) =>
73
+ error.issues
74
+ .slice(0, 6)
75
+ .map((i) => `${i.path.join('.') || 'input'}: ${i.message}`)
76
+ .join('; ')
77
+ const money = (usd) => (usd > 0 && usd < 0.01 ? '<$0.01' : `$${usd.toFixed(2)}`)
78
+
79
+ // ---------------------------------------------------------------- nw_ask
80
+
81
+ const ASK_SHAPE = {
82
+ kind: z.enum(['consent', 'key', 'choice', 'cost']),
83
+ title: z.string().min(1).max(80),
84
+ body: z.string().max(600).optional(),
85
+ topic: z
86
+ .string()
87
+ .regex(/^[a-z][a-z0-9-]{1,30}$/)
88
+ .optional()
89
+ .describe('consent: what is being allowed, e.g. "web".'),
90
+ connector: z
91
+ .string()
92
+ .regex(/^[a-z][a-z0-9]*$/)
93
+ .optional()
94
+ .describe('key: the service id from the studio context, e.g. "meshy".'),
95
+ options: z
96
+ .array(
97
+ z.object({
98
+ id: z.string().regex(/^[a-z0-9-]{1,30}$/),
99
+ label: z.string().min(1).max(60),
100
+ detail: z.string().max(160).optional(),
101
+ }),
102
+ )
103
+ .min(2)
104
+ .max(6)
105
+ .optional()
106
+ .describe('choice: 2 to 6 concrete options.'),
107
+ multiple: z.boolean().optional().describe('choice: the creator may pick several.'),
108
+ other: z.boolean().optional().describe('choice: the creator may type their own answer.'),
109
+ estimate: z
110
+ .object({
111
+ items: z
112
+ .array(z.object({ label: z.string().max(80), usd: z.number().min(0).max(10000) }))
113
+ .min(1)
114
+ .max(12),
115
+ note: z.string().max(200).optional(),
116
+ })
117
+ .optional()
118
+ .describe('cost: one line per part of the job, in US dollars.'),
119
+ remember: z
120
+ .object({ key: z.string().regex(/^[a-z0-9-]{2,40}$/), scope: z.enum(['project', 'studio']) })
121
+ .optional()
122
+ .describe('choice and consent: save the answer under this key so the same question is answered from it next time.'),
123
+ }
124
+
125
+ const ASK_DESCRIPTION =
126
+ 'Shows a card in the chat and waits for the creator\'s answer. Write title and body in the screen language (the studio context names it), short and concrete. kind "cost": before a big job, the estimate as lines (the LLM work and each paid generation call, in US dollars); do not build until it is approved. kind "key": a paid service is not connected; connector is its id from the studio context; the creator types the key into the card and you never see it; afterwards it is in the service\'s environment variable for your Bash commands. kind "choice": 2 to 6 concrete options (id, label, detail), when the request is ambiguous in a way that changes the result. kind "consent": permission for something not yet allowed (topic, e.g. "web"). remember (choice and consent) saves the answer under a key, for this project or the whole studio, so the same question is answered from it next time.'
127
+
128
+ /** What a kind still needs, said so the model can add it; null when complete. */
129
+ function missingFor(a) {
130
+ if (a.remember && (a.kind === 'key' || a.kind === 'cost')) {
131
+ return 'remember is only for choice and consent cards: a key is stored by the studio itself, and every job asks for its own cost.'
132
+ }
133
+ if (a.kind === 'consent' && !a.topic) return 'A consent card needs topic: what is being allowed, e.g. "web".'
134
+ if (a.kind === 'key') {
135
+ if (!a.connector) return 'A key card needs connector: the service\'s id from the studio context, e.g. "meshy".'
136
+ const entry = catalogEntry(a.connector)
137
+ if (!entry || entry.auth.type !== 'apiKey' || entry.id === 'anthropic') {
138
+ const ids = keyServices()
139
+ return `"${a.connector}" is not a service that takes an API key.${ids.length ? ` Use one of: ${ids.join(', ')}.` : ''}`
140
+ }
141
+ }
142
+ if (a.kind === 'choice') {
143
+ if (!a.options) return 'A choice card needs options: 2 to 6 of { id, label, detail }.'
144
+ if (new Set(a.options.map((o) => o.id)).size !== a.options.length) return 'Option ids must be unique.'
145
+ }
146
+ if (a.kind === 'cost' && !a.estimate) return 'A cost card needs estimate: { items: [{ label, usd }, ...], note }.'
147
+ return null
148
+ }
149
+
150
+ /** A card that would mix two languages: its words not in the screen
151
+ * language its labels are drawn in, where the script tells (locale.cjs
152
+ * writtenIn). Null when they are, or it cannot tell. */
153
+ function languageProblem(a, locale) {
154
+ const writtenIn = localeModule?.writtenIn
155
+ if (typeof writtenIn !== 'function' || !locale) return null
156
+ const words = [a.title, a.body, ...(a.options ?? []).flatMap((o) => [o.label, o.detail]), ...(a.estimate?.items ?? []).map((i) => i.label), a.estimate?.note]
157
+ if (writtenIn(words.filter((w) => typeof w === 'string').join('\n'), locale) !== false) return null
158
+ const name = localeModule.LANGUAGE_NAMES?.[localeModule.languageOf?.(locale) ?? locale] ?? locale
159
+ return `Cards are in the screen language, ${name}, and this card is not in it. Write its title, body, options and estimate lines in ${name} (the screen language, not the one the creator writes in), then call nw_ask again.`
160
+ }
161
+
162
+ /** One plain sentence for the model beside the JSON answer. */
163
+ function sentenceFor(a, r) {
164
+ const remembered = r.remembered ? ' (remembered from an earlier answer)' : ''
165
+ switch (r.answer) {
166
+ case 'timeout':
167
+ return 'The creator did not answer within 30 minutes. Carry on without it, or stop and say what you need.'
168
+ case 'cancelled':
169
+ return 'The request was stopped.'
170
+ case 'unavailable':
171
+ return 'There is no studio window to ask in.'
172
+ }
173
+ if (a.kind === 'consent') {
174
+ return r.answer === 'allow'
175
+ ? `The creator allowed it (${a.topic})${remembered}.`
176
+ : `The creator did not allow it (${a.topic})${remembered}. Work without it.`
177
+ }
178
+ if (a.kind === 'key') {
179
+ const name = catalogEntry(a.connector)?.name ?? a.connector
180
+ return r.answer === 'saved'
181
+ ? `The creator saved a key for ${name}. It is in $${r.envVar} for your Bash commands from now on. Never print it or write it to a file.`
182
+ : `The creator did not add a key for ${name}. Do without it or offer another way.`
183
+ }
184
+ if (a.kind === 'cost') {
185
+ return r.answer === 'approve'
186
+ ? `The creator approved ${money(r.approvedUsd ?? 0)}. Go ahead, and ask again with a new estimate if the spend will clearly pass it.`
187
+ : 'The creator cancelled. Change nothing more, and say what a smaller version would cost.'
188
+ }
189
+ // choice
190
+ if (r.answer === 'skip') return 'The creator skipped the question. Decide yourself, and say what you chose.'
191
+ if (Array.isArray(r.answer)) {
192
+ const labels = r.answer.map((id) => a.options?.find((o) => o.id === id)?.label ?? id)
193
+ return `The creator chose: ${labels.join(', ')}${remembered}.`
194
+ }
195
+ if (r.answer && typeof r.answer.other === 'string') return `The creator wrote their own answer${remembered}: ${JSON.stringify(r.answer.other)}.`
196
+ return 'The creator answered.'
197
+ }
198
+
199
+ async function ask(args, ctx) {
200
+ const parsed = z.object(ASK_SHAPE).safeParse(args ?? {})
201
+ if (!parsed.success) return fail(`nw_ask: ${issues(parsed.error)}`)
202
+ const a = parsed.data
203
+ const missing = missingFor(a)
204
+ if (missing) return fail(missing)
205
+ const unreadable = languageProblem(a, ctx?.locale)
206
+ if (unreadable) return fail(unreadable)
207
+
208
+ const card = { origin: 'agent' }
209
+ for (const field of ['kind', 'title', 'body', 'topic', 'connector', 'options', 'multiple', 'other', 'estimate', 'remember']) {
210
+ if (a[field] !== undefined) card[field] = a[field]
211
+ }
212
+ let spentUsd
213
+ try {
214
+ const spent = ctx.ledger?.spentUsd?.()
215
+ if (Number.isFinite(spent)) spentUsd = spent
216
+ } catch {
217
+ spentUsd = undefined
218
+ }
219
+
220
+ let result
221
+ try {
222
+ result = await ctx.rpc('ask', { runId: ctx.runId, locale: ctx.locale, spentUsd, card }, ASK_TIMEOUT_MS)
223
+ } catch (err) {
224
+ result = { ok: false, error: err?.message ?? String(err) }
225
+ }
226
+ if (!result || typeof result !== 'object' || result.ok === false || result.answer === undefined) {
227
+ return fail(`The card could not be shown: ${result?.error ?? 'the studio did not answer'}.`)
228
+ }
229
+ if (a.kind === 'cost' && (result.answer === 'timeout' || result.answer === 'unavailable')) ctx.loop?.noteCostUnanswered?.()
230
+ if (a.kind === 'cost' && result.answer === 'approve' && Number.isFinite(result.approvedUsd)) {
231
+ try {
232
+ ctx.ledger?.approve?.(result.approvedUsd)
233
+ // A space's loop keeps the cost cards answered after its kickoff: a
234
+ // paid environment goes only on one of its own (tools/environment.mjs).
235
+ ctx.loop?.noteCostCard?.(result.approvedUsd)
236
+ } catch (err) {
237
+ ctx.log?.(`[cards] ledger.approve failed: ${err?.message ?? err}`)
238
+ }
239
+ }
240
+ return { text: `${JSON.stringify(result)}\n${sentenceFor(a, result)}` }
241
+ }
242
+
243
+ // ---------------------------------------------------------------- nw_take_download
244
+
245
+ const TAKE_SHAPE = {
246
+ from: z
247
+ .string()
248
+ .min(1)
249
+ .describe('The download\'s id from the browser\'s note, or a path inside .nowhere/quarantine/ for a file you unzipped there.'),
250
+ to: z.string().min(1).describe('Where it goes, project-relative, under blender/: a model, texture, HDRI or .blend for nw_blender (e.g. blender/textures/bark.png).'),
251
+ license: z
252
+ .object({ spdx: z.string(), url: z.string(), author: z.string(), title: z.string(), credit: z.string() })
253
+ .partial()
254
+ .optional()
255
+ .describe('Required: the licence you read on its page, as an SPDX id ("CC0-1.0", "CC-BY-4.0") with its url, author, title and, for CC BY, the credit line. It goes into assets.lock.json, and every model built from it inherits it.'),
256
+ confirmedShareAlike: z.boolean().optional().describe('CC BY-SA: only after the creator agreed in an nw_ask choice card.'),
257
+ replace: z.boolean().default(false).describe('Overwrite a file already at `to`.'),
258
+ }
259
+
260
+ const TAKE_DESCRIPTION =
261
+ 'Moves a downloaded file out of quarantine (.nowhere/quarantine/) into blender/ (e.g. blender/textures/), for nw_blender to build from, once its check passed and you have read its licence: pass license (spdx, url, author, title, and the credit for CC BY). from is the id the browser gave the download, or a path inside .nowhere/quarantine/ for a file you unzipped there with Bash. Models, textures, HDRIs and .blend files only; the extension stays the same; archives are unzipped inside quarantine first. The file and its licence are recorded in assets.lock.json, and a GLB nw_blender makes from it inherits that licence. Files for the space itself (models, textures, HDRIs, sounds under assets/) come in through asset_import instead.'
262
+
263
+ // Both sides real paths, as the harness's containment checks do: on macOS the
264
+ // temp and home trees are symlinked, and a raw comparison refuses real children.
265
+ function realOrSelf(p) {
266
+ let head = path.resolve(p)
267
+ const rest = []
268
+ for (;;) {
269
+ try {
270
+ return path.join(fs.realpathSync(head), ...rest)
271
+ } catch {
272
+ const up = path.dirname(head)
273
+ if (up === head) return path.resolve(p)
274
+ rest.unshift(path.basename(head))
275
+ head = up
276
+ }
277
+ }
278
+ }
279
+ const inside = (root, target) => {
280
+ const rel = path.relative(root, target)
281
+ return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel)
282
+ }
283
+ const sameExt = (a, b) => {
284
+ const n = (e) => (e === '.jpeg' ? '.jpg' : e)
285
+ return n(a) === n(b)
286
+ }
287
+ const mbOf = (bytes) => (bytes / MB).toFixed(bytes < MB ? 2 : 1)
288
+
289
+ async function move(from, to) {
290
+ try {
291
+ await fsp.rename(from, to)
292
+ } catch (err) {
293
+ // Quarantine and the project share a disk almost always; a project on
294
+ // another volume than its own .nowhere folder (a symlink) needs a copy.
295
+ if (err.code !== 'EXDEV') throw err
296
+ await fsp.copyFile(from, to)
297
+ await fsp.rm(from, { force: true })
298
+ }
299
+ }
300
+
301
+ async function take(args, ctx) {
302
+ const parsed = z.object(TAKE_SHAPE).safeParse(args ?? {})
303
+ if (!parsed.success) return fail(`nw_take_download: ${issues(parsed.error)}`)
304
+ const { from, to, replace, license, confirmedShareAlike } = parsed.data
305
+ // Into the game itself: never this way.
306
+ if (/^(\.\/)?assets(\/|$)/.test(to.replace(/\\/g, '/'))) return fail(ASSETS_REFUSAL)
307
+
308
+ const root = realOrSelf(ctx.projectRoot)
309
+ const quarantine = path.join(root, QUARANTINE)
310
+ if (!fs.existsSync(quarantine)) return fail('Nothing is in quarantine yet: download a file in your browser first.')
311
+ const q = realOrSelf(quarantine)
312
+ const manifest = readManifest(root)
313
+ const listIds = () => {
314
+ const ids = manifest.files.map((f) => `${f.id} (${f.name})`).slice(0, 20)
315
+ return ids.length ? ` In quarantine: ${ids.join(', ')}.` : ' The quarantine manifest is empty.'
316
+ }
317
+
318
+ // from: a manifest id, or a path inside quarantine.
319
+ let entry = manifest.files.find((f) => f.id === from) ?? null
320
+ let file
321
+ if (entry) {
322
+ file = realOrSelf(path.join(q, entry.file))
323
+ // The manifest sits where Bash may write (the agent unzips in quarantine),
324
+ // so an entry is trusted no further than a path: a move must never take a
325
+ // file from outside quarantine.
326
+ if (!inside(q, file)) return fail(`The quarantine entry ${from} points outside .nowhere/quarantine/, so it is not moved.`)
327
+ } else {
328
+ const plain = from.replace(/\\/g, '/')
329
+ const candidate = path.isAbsolute(from)
330
+ ? from
331
+ : plain.startsWith('.nowhere/')
332
+ ? path.join(root, plain)
333
+ : path.join(q, plain)
334
+ file = realOrSelf(candidate)
335
+ if (!inside(q, file)) return fail(`"${from}" is not inside .nowhere/quarantine/: only a download can be taken in this way.${listIds()}`)
336
+ const rel = path.relative(q, file).split(path.sep).join('/')
337
+ if (rel === 'index.json' || rel.endsWith('.part')) return fail(`"${from}" is not a finished download.`)
338
+ entry = manifest.files.find((f) => f.file === rel) ?? null
339
+ }
340
+ let size
341
+ try {
342
+ const st = await fsp.stat(file)
343
+ if (!st.isFile()) return fail(`"${from}" is a folder. Name the file inside it you need.`)
344
+ size = st.size
345
+ } catch {
346
+ return fail(`Nothing in quarantine is called "${from}".${listIds()}`)
347
+ }
348
+ const name = entry?.name ?? path.basename(file)
349
+ if (entry && !entry.ok) return fail(`${name} failed its check (${entry.problem}), so it stays in quarantine.`)
350
+ // Checked again now: the file may have changed since it was downloaded.
351
+ const check = await checkFile(file)
352
+ if (!check.ok) return fail(`${name} failed its check (${check.problem}), so it stays in quarantine.`)
353
+ const relFrom = path.relative(root, file).split(path.sep).join('/')
354
+ if (check.kind === 'archive') {
355
+ const id = entry?.id ?? path.basename(file, path.extname(file))
356
+ return fail(`Unzip it inside .nowhere/quarantine with Bash (unzip -q ${relFrom} -d ${QUARANTINE}/${id}), then take the file you need.`)
357
+ }
358
+
359
+ // to: project-relative, under assets/ or blender/, same extension.
360
+ const dest = to.replace(/\\/g, '/').replace(/^\.\//, '')
361
+ const parts = dest.split('/')
362
+ if (path.isAbsolute(to) || /^[A-Za-z]:/.test(dest) || parts.some((p) => p === '..' || p === '')) {
363
+ return fail(`"${to}" is not a plain project-relative path. Use one like assets/tree.glb or blender/textures/bark.png.`)
364
+ }
365
+ const top = parts[0]
366
+ if (!INTO[top] || parts.length < 2) return fail(`"${to}" is not under blender/. Models, textures, HDRIs and .blend files for nw_blender go under blender/; ${ASSETS_REFUSAL}`)
367
+ const fromExt = path.extname(file).toLowerCase()
368
+ const toExt = path.extname(dest).toLowerCase()
369
+ if (!DOWNLOAD_TYPES[toExt] || !sameExt(fromExt, toExt)) return fail(`"${to}" must keep the file's extension (${fromExt}).`)
370
+ if (!INTO[top].has(check.kind)) {
371
+ return fail(`${name} is a ${check.kind} file, which nw_blender cannot use. ${check.kind === 'audio' ? `A sound for the game: ${ASSETS_REFUSAL}` : ''}`.trim())
372
+ }
373
+ // Where it came from, and under which licence, before it moves: a file that
374
+ // may not be used must not become an input every later model inherits from.
375
+ const sourceEntry = entry ?? manifest.files.find((f) => relFrom.startsWith(`${QUARANTINE}/${f.id}/`))
376
+ if ([sourceEntry?.url, sourceEntry?.referrer].some((u) => u && blockedHost(u))) {
377
+ return fail(`${name} came from ArtStation, Pinterest or Behance, whose terms forbid feeding their images to AI tools, so it stays in quarantine.`)
378
+ }
379
+ const web = await webLookOnlyAmong(root, [file])
380
+ if (web) return fail(`${name} is a web reference kept to look at only (${web.why}), so it stays in quarantine.`)
381
+ if (!license?.spdx?.trim()) {
382
+ return fail(`Pass license: the licence on ${sourceEntry?.url ? `its page (${sourceEntry.url})` : 'its page'}, as { "spdx": "CC0-1.0", "url": "...", "author": "...", "title": "..." } (and "credit" for CC BY). It is recorded in assets.lock.json.`)
383
+ }
384
+ const owned = (await ledgerOf())?.ownedLicenseRefusal?.(license.spdx)
385
+ if (owned) return fail(`${name} stays in quarantine: ${owned}`)
386
+ const recorded = {
387
+ spdx: license.spdx.trim(),
388
+ ...(license.url && /^https?:\/\//.test(license.url) ? { url: license.url } : {}),
389
+ ...(license.credit ? { credit: license.credit.slice(0, 300) } : {}),
390
+ ...(confirmedShareAlike === true ? { confirmedByCreator: true } : {}),
391
+ }
392
+ const verdict = schema?.licenseVerdict?.(recorded)
393
+ if (verdict && !verdict.ok) {
394
+ return fail(`${name} stays in quarantine: ${verdict.reason}.${verdict.code === 'ledger:sa-unconfirmed' ? ' Ask the creator with nw_ask (kind choice) first; after a yes, pass confirmedShareAlike: true.' : verdict.code === 'ledger:credit' ? ' Pass license.credit too.' : ''}`)
395
+ }
396
+ const target = realOrSelf(path.join(root, ...parts))
397
+ if (!inside(root, target) || !target.startsWith(path.join(root, top) + path.sep)) {
398
+ return fail(`"${to}" leads outside the project's ${top}/ folder.`)
399
+ }
400
+ if (fs.existsSync(target) && !replace) return fail(`${to} already exists. Pass replace: true to overwrite it, or pick another name.`)
401
+
402
+ try {
403
+ await fsp.mkdir(path.dirname(target), { recursive: true })
404
+ await move(file, target)
405
+ } catch (err) {
406
+ return fail(`${name} could not be moved (${err.code ?? err.message}).`)
407
+ }
408
+ if (entry) {
409
+ try {
410
+ const doc = readManifest(root)
411
+ doc.files = doc.files.filter((f) => f.id !== entry.id)
412
+ writeManifest(root, doc)
413
+ } catch (err) {
414
+ ctx.log?.(`[cards] manifest update failed: ${err?.message ?? err}`)
415
+ }
416
+ }
417
+ // A file unzipped from an archive keeps the archive's source: the folder it
418
+ // came out of is named after the archive's id.
419
+ const source = sourceEntry
420
+ const where = source?.url ? ` with its source (${source.url})` : ''
421
+ let note = `recorded in assets.lock.json${where} and its licence (${recorded.spdx})`
422
+ const ledger = await ledgerOf()
423
+ if (!ledger) {
424
+ note = 'not recorded: the ledger module is not there'
425
+ } else {
426
+ let url
427
+ try {
428
+ url = source?.url && /^https?:/.test(new URL(source.url).protocol) ? source.url : undefined
429
+ } catch {
430
+ url = undefined
431
+ }
432
+ const r = await ledger.recordAsset(root, dest, {
433
+ origin: 'download',
434
+ license: recorded,
435
+ source: {
436
+ provider: 'web',
437
+ ...(url ? { url } : {}),
438
+ ...(source?.host ? { host: String(source.host).slice(0, 200) } : {}),
439
+ ...(license.title || source?.name ? { title: String(license.title ?? source.name).slice(0, 200) } : {}),
440
+ ...(license.author ? { author: String(license.author).slice(0, 120) } : {}),
441
+ ...(source?.at ? { fetchedAt: String(source.at) } : {}),
442
+ },
443
+ steps: [{ op: 'nw_take_download', at: new Date().toISOString(), detail: `from ${relFrom}` }],
444
+ })
445
+ if (!r.ok) note = `moved, but the ledger could not record it: ${r.error}`
446
+ }
447
+ return { text: `Moved ${name} to ${dest} (${mbOf(size)} MB), ${note}. nw_blender can use it now; a GLB built from it inherits that licence.` }
448
+ }
449
+
450
+ export const TOOLS = [
451
+ {
452
+ name: 'nw_ask',
453
+ description: ASK_DESCRIPTION,
454
+ shape: ASK_SHAPE,
455
+ handler: async (args, ctx) => {
456
+ try {
457
+ return await ask(args, ctx)
458
+ } catch (err) {
459
+ return fail(`nw_ask failed: ${err?.message ?? err}`)
460
+ }
461
+ },
462
+ readOnly: true,
463
+ mainOnly: true,
464
+ },
465
+ {
466
+ name: 'nw_take_download',
467
+ description: TAKE_DESCRIPTION,
468
+ shape: TAKE_SHAPE,
469
+ handler: async (args, ctx) => {
470
+ try {
471
+ return await take(args, ctx)
472
+ } catch (err) {
473
+ return fail(`nw_take_download failed: ${err?.message ?? err}`)
474
+ }
475
+ },
476
+ readOnly: false,
477
+ mainOnly: false,
478
+ },
479
+ ]