oda-engine 0.0.0-stage → 0.1.1

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 +131 -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-CptQkDVX.js +1 -0
  197. package/web-dist/assets/KTX2Loader-C53LJqss.js +2 -0
  198. package/web-dist/assets/SPZLoader-BQ3tjaTv.js +1 -0
  199. package/web-dist/assets/gaussianSplat-_9tcWegB.js +1 -0
  200. package/web-dist/assets/index-Baka-ZO7.js +693 -0
  201. package/web-dist/assets/index-CcjyyQco.css +1 -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,129 @@
1
+ // The helpers the main agent can start with its Agent tool (the SDK's
2
+ // subagents): an art critic, a Blender modeller and a look developer. Each
3
+ // gets a brief the main agent writes, works with its own short list of tools
4
+ // and reports back; none of them talks to the creator.
5
+ // The PreToolUse hook in host.mjs also denies helpers the creator's computer,
6
+ // browser and nw_ask, whatever their tool list says.
7
+
8
+ import { RUBRIC } from './loop/levels.mjs'
9
+
10
+ export const ART_CRITIC_PROMPT = `You are the art critic for an Oda space build. You judge; you never edit anything and never ask the creator.
11
+
12
+ You get reference image paths (open each with Read), the brief (brief.json in numbers, brief.md in words), and what to judge: one asset, an area or the whole scene.
13
+ 1. Read the references and the brief.
14
+ 2. Take fresh views with nw_view: always a player view and a close-up of the subject, plus the brief's hero views (H1 to H6 in brief.json, each a position, a point to look at and a fov) or a view that matches the reference's composition. Check the frame counters: if they did not move between two calls, the preview is frozen; report that first and judge nothing.
15
+ 3. Compare, in this order: silhouette and proportion (measure against the 1.75 m player); palette and values (the darkest darks, the brightest lights, saturation; look_compare against the reference gives them in numbers, use it when there is one); materials and surface detail (a hero made of untextured boxes and cylinders is a difference to report); lighting and atmosphere (sun, fog depth, sky); composition from the player's eye height.
16
+ 4. Answer in English as a numbered list of concrete differences, most visible first. Each item says what is wrong, in which view, and the fix, with numbers against the reference or the brief when you can ("the brief makes the arch about <n>x the player's height; it is about <m>x"). End with one line: VERDICT: MATCHES, CLOSE or FAR.
17
+ Do not praise, and do not list what already matches unless you are asked to.`
18
+
19
+ export const BLENDER_MODELER_PROMPT = `You model one asset for an Oda space in Blender, without a window, through nw_blender. Read the nowhere:blender-modeling skill before your first script (nw_guide name "blender-modeling" when the skill is not loaded). You never ask the creator anything and never use their mouse, keyboard or browser.
20
+
21
+ You get what to make, its real size in metres, its class (small, prop, large, hero, character, building, terrain), brief.md and reference image paths (open them with Read).
22
+ 1. Decide the form before the script: from the brief and the references, write at the top of blender/<asset>.py what the asset is for, its size in metres, its silhouette from the front, side and top, its parts biggest first with their sizes, and which of the brief's materials each surface takes. There is no toolkit or kit of parts: model this asset in plain bpy and bmesh, at real size (metres, Z up, the front facing -Y, the origin at the base centre), the masses first, then the secondary forms, the edges, the materials from the brief's colours and roughness, and the detail the close-up shows.
23
+ 2. Run nw_blender with out "assets/<asset>.glb", class and expect. Look at both contact sheets, read the numbers and the rubric line (silhouette, bevel, materials, budget): what it measured, which you weigh against this brief (one colour is right when the brief asks for one, razor edges when it asks for facets).
24
+ 3. Compare with the references and the brief: the silhouette, the proportion against the 1.75 m figure, the key details, the materials. Write down the differences, then change the model in the script to fix the biggest difference from the brief and the references and run again. That is one round: a round changes the model in answer to what the sheets showed. Running an unchanged script again (only a closer camera) is a look, not a round; nw_blender says when the script did not change. At least three rounds for a hero asset; a hero is done when the silhouette, the proportions, the key details and the materials read as the brief and the references say in the close-up. A rubric score is a measurement, not a target: a low one is right when the brief asks for what it measured.
25
+ 4. Keep it glTF-safe and inside its class: Principled BSDF materials and image textures; procedural nodes do not export, so bake them or model the detail (nw_blender lists what would be dropped). A Decimate copy in its own collection is a lighter copy when the triangles are over the class's line.
26
+ 5. Report in English: the GLB path, its size in metres, its triangle count, the rubric numbers, what you checked in the sheets, what you assumed, and the scene.json placement to use, with "normalize": false so it keeps its real size.
27
+ Never download anything, and never open a .blend that came from the web.`
28
+
29
+ export const LOOK_DEV_PROMPT = `You tune the look of an Oda planet: its sky, fog, light, tone curve, grade, glow, AO, vignette and grain. You edit only through look_apply, never another file, and you never ask the creator anything.
30
+
31
+ You get the reference image paths (open them with Read), the brief (brief.json in numbers, brief.md in words) and what the look should be.
32
+ 1. Read the references and the brief, and the nowhere:look-dev skill (nw_guide name "look-dev" when it is not loaded). Note the brief's palette.
33
+ 2. Turn the brief's light, atmosphere and values into look_apply values: the sun from its elevation, azimuth and colour, the sky from its kind (an HDRI or a physical sky lights the scene itself), the fog from its colour and distances (fog null when the brief has none), the exposure and contrast from its value key, the sky and the grade from its palette. Every value comes from the brief; there is no stock mood to start from.
34
+ 3. Look with nw_view at the brief's hero views (H1 to H6 in brief.json) and the player view, then look_compare against each hero view's reference (with the brief's palette).
35
+ 4. Change one or two knobs at a time with look_apply, from the comparison's numbers and suggestions, and compare again. That is one round; at most 8 rounds. Stop when the verdict is close or matches, the palette deltaE is at most 10 and clipping is at most 2% (unless the brief wants it).
36
+ 5. Report in English: every value you set (as look_apply set values) with the brief's fact it came from, whether nw_status still lists lookWarnings, the last comparison's numbers and verdict, and what still differs and why it cannot be closed with the look alone (a material, a model, the light's direction).`
37
+
38
+ // The definitions as the SDK takes them. `skills` names a plugin skill; host.mjs
39
+ // drops it when the plugin did not ship with this build. Part of PROMPT_HASH
40
+ // (prompt.mjs), so changing a helper starts conversations afresh.
41
+ export const SUBAGENTS = {
42
+ 'art-critic': {
43
+ description: 'Judges how the space looks against the reference and the brief. Takes its own nw_view shots and returns concrete differences, most visible first. Read-only.',
44
+ prompt: ART_CRITIC_PROMPT,
45
+ tools: ['Read', 'Glob', 'Grep', 'mcp__nw__nw_view', 'mcp__nw__nw_status', 'mcp__nw__nw_logs', 'mcp__nw__look_compare'],
46
+ model: 'inherit',
47
+ effort: 'high',
48
+ maxTurns: 30,
49
+ },
50
+ 'blender-modeler': {
51
+ description: 'Models one asset in headless Blender with a bpy script written for it through nw_blender, looping on contact sheets and the rubric until it matches the brief, and reports the GLB, its size, triangles and scores.',
52
+ prompt: BLENDER_MODELER_PROMPT,
53
+ tools: ['Read', 'Write', 'Edit', 'Glob', 'Grep', 'mcp__nw__nw_blender', 'mcp__nw__nw_docs', 'mcp__nw__nw_guide'],
54
+ skills: ['nowhere:blender-modeling'],
55
+ model: 'inherit',
56
+ effort: 'xhigh',
57
+ maxTurns: 120,
58
+ },
59
+ 'look-dev': {
60
+ description: "Tunes the planet's look against the reference with look_apply and look_compare, and reports the values and the remaining differences.",
61
+ prompt: LOOK_DEV_PROMPT,
62
+ tools: ['Read', 'Glob', 'mcp__nw__look_apply', 'mcp__nw__look_compare', 'mcp__nw__nw_view', 'mcp__nw__nw_status', 'mcp__nw__nw_guide'],
63
+ skills: ['nowhere:look-dev'],
64
+ model: 'inherit',
65
+ effort: 'high',
66
+ maxTurns: 60,
67
+ },
68
+ }
69
+
70
+ // The reference loop's judge (REFERENCE_LOOP.md 2.5) is not among the
71
+ // helpers above: the main agent would brief it, and a judge that reads the
72
+ // builder's words is no longer without context. nw_round runs it itself
73
+ // (loop/judge.mjs), as its own session with no tools, from the target
74
+ // pictures, the stills at the same cameras and this rubric alone.
75
+
76
+ /** What the judge scores, one line each (loop/levels.mjs RUBRIC). */
77
+ export const JUDGE_RUBRIC = RUBRIC.map(([, line]) => `- ${line}`).join('\n')
78
+
79
+ export const JUDGE_PROMPT = `You judge how close a real-time 3D space comes to its target pictures. You get only pictures: for each hero view, its target (how the finished place should look from that camera) and its still (the space as it is now, drawn live from the same camera). You know nothing else about the work and you ask nothing.
80
+
81
+ Score each hero view from 0 to 10 for how close its still comes to its target, weighing all of this:
82
+ ${JUDGE_RUBRIC}
83
+
84
+ 10 is a still you could not tell from the target at a glance: the same place, drawn the same way; 7 is the right place with clear differences in material, light or drawing; 5 is the right layout drawn another way (a photograph where the target is a painting, a cartoon where it is an ink drawing); 2 is barely the same place; 0 is something else. Score what is in the picture, not what was meant, and be strict: a pleasant picture that is not the target scores low.
85
+
86
+ After the pairs there may be pictures of the creator's other spaces. When a still could be taken for one of them (its way of drawing, shape language and palette) where its own target is unlike them, score that view down and add a high gap whose what begins "looks like another space".
87
+
88
+ Last there may be pictures the place is modelled on, found on the web. They are not targets: hold a still to them only where its target agrees with them.
89
+
90
+ Answer with one JSON object and nothing else:
91
+ {"views":{"H1":6.5},"overall":6.5,"gaps":[{"where":"H1, the far roofs","what":"they smear into one grey band where the target has tiled roofs","severity":"high"}],"notes":"one or two sentences"}
92
+ views has every hero view you were shown. overall is your score for the space as a whole, never above its best view nor below its worst. gaps lists the biggest differences first, at most eight, each with where (the view and the part of the picture), what differs, and severity high, medium or low.`
93
+
94
+ const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max']
95
+
96
+ /** The helpers' efforts at each quality step (loop/levels.mjs QUALITY):
97
+ * a deeper step thinks harder in its helpers too. */
98
+ const STEP_EFFORTS = Object.freeze({
99
+ 'art-critic': ['high', 'high', 'xhigh', 'max', 'max'],
100
+ 'look-dev': ['high', 'high', 'xhigh', 'max', 'max'],
101
+ 'blender-modeler': ['xhigh', 'xhigh', 'xhigh', 'max', 'max'],
102
+ })
103
+
104
+ /** A helper at a quality step: its effort, and at steps 4 and 5 more room
105
+ * (look-dev up to 16 rounds and 120 turns, the critic 60 turns). */
106
+ function atStep(name, def, step) {
107
+ const effort = STEP_EFFORTS[name]?.[step - 1]
108
+ const out = effort ? { ...def, effort } : { ...def }
109
+ if (step >= 4 && name === 'look-dev') Object.assign(out, { prompt: def.prompt.replace('at most 8 rounds', 'at most 16 rounds'), maxTurns: 120 })
110
+ if (step >= 4 && name === 'art-critic') out.maxTurns = 60
111
+ return out
112
+ }
113
+
114
+ /** The definitions for a run: without the plugin, no skills to preload; on
115
+ * a model with an effort ceiling (models.json effortCeiling), no helper
116
+ * deeper than it. A blender-modeler on Claude Haiku 5.5 at xhigh thought
117
+ * 91k tokens in one call, six and a half minutes (2026-10-20). step: the
118
+ * request's quality step (1 to 5), null for today's efforts. */
119
+ export function subagentsFor(withPlugin, model = null, step = null) {
120
+ const ceiling = EFFORTS.indexOf(model?.effortCeiling)
121
+ const at = Number.isInteger(step) && step >= 1 && step <= 5 ? step : null
122
+ return Object.fromEntries(
123
+ Object.entries(SUBAGENTS).map(([name, { skills, ...base }]) => {
124
+ const def = at ? atStep(name, base, at) : base
125
+ const capped = ceiling >= 0 && EFFORTS.indexOf(def.effort) > ceiling ? { ...def, effort: EFFORTS[ceiling] } : def
126
+ return [name, withPlugin && skills ? { ...capped, skills } : capped]
127
+ }),
128
+ )
129
+ }
@@ -0,0 +1,499 @@
1
+ // The asset tools: free libraries and the creator's downloads into the game,
2
+ // through one door that checks, converts, optimises, sizes and records the
3
+ // licence of everything.
4
+ // asset_search Poly Haven, ambientCG and Poly Pizza (Kenney) in one search
5
+ // asset_fetch one item into quarantine (.nowhere/quarantine/<qid>/)
6
+ // asset_import quarantine into assets/: the only way a file from outside gets in
7
+ // asset_inspect what a model, material or texture in assets/ is made of, held
8
+ // to the space's brief (asset_import runs it on what it writes)
9
+ // asset_ledger what assets.lock.json says, and what would stop a publish
10
+ //
11
+ // Tool modules export TOOLS (ToolDefs) and RPC_METHODS; the registry
12
+ // (tools/index.mjs) makes them Claude and other-vendor tools. Handlers never
13
+ // throw, never print a key, and take fetch from ctx.fetch ?? globalThis.fetch,
14
+ // so the checks run all of it with fakes. Electron-free: the CLI vendors it.
15
+
16
+ import { z } from 'zod'
17
+ import { execFile } from 'node:child_process'
18
+ import { ASSET_CLASSES, CREDITS_SHOWN, SPLAT_LIMITS, TEXTURE_BUDGETS, TRIANGLE_BUDGETS, briefDensityFor, creditsFor, licenseVerdict } from '../../schema/dist/index.js'
19
+ import { findBlender } from '../blender/find.mjs'
20
+ import { runBlender } from '../blender/run.mjs'
21
+ import fs from 'node:fs'
22
+ import path from 'node:path'
23
+ import { readBrief } from '../assets/brief.mjs'
24
+ import { fetchIntoQuarantine } from '../assets/fetch.mjs'
25
+ import { readGltf } from '../assets/gltf.mjs'
26
+ import { createImageOps, onPath } from '../assets/imageOps.mjs'
27
+ import { importAsset } from '../assets/import.mjs'
28
+ import { densityVerdict, inspectMaterial, inspectModelDoc, inspectPicture, materialMaps, reportLines } from '../assets/inspect.mjs'
29
+ import { LEDGER, ledgerProblems, readLedgerState } from '../assets/ledger.mjs'
30
+ import { fetchOf, fetchThumbnail, mbOf, NetError, userAgentFor } from '../assets/net.mjs'
31
+ import { NOT_SOURCES, SOURCES, SOURCE_IDS, sourcesFor } from '../assets/sources/index.mjs'
32
+ import { readSplat, splatStats } from '../assets/splat.mjs'
33
+ import { POLYPIZZA_ENV } from '../assets/sources/polypizza.mjs'
34
+
35
+ export const RPC_METHODS = ['image-resize']
36
+
37
+ const fail = (text) => ({ text, isError: true })
38
+
39
+ // ---------------------------------------------------------------- consent
40
+
41
+ // The web consent, asked once per ctx (one request) however many searches
42
+ // and fetches it makes. The host's own ctx.web() remembers it per studio.
43
+ const consents = new WeakMap()
44
+ export async function webAllowed(ctx) {
45
+ if (typeof ctx?.web !== 'function') return 'unavailable'
46
+ if (consents.has(ctx)) return consents.get(ctx)
47
+ let answer
48
+ try {
49
+ answer = await ctx.web()
50
+ } catch {
51
+ answer = 'unavailable'
52
+ }
53
+ if (answer === 'allow' || answer === 'deny') consents.set(ctx, answer)
54
+ return answer
55
+ }
56
+
57
+ const NO_WEB = {
58
+ deny: 'The creator has not allowed the web, so nothing was searched.',
59
+ timeout: 'The creator did not answer the web consent card, so nothing was searched.',
60
+ cancelled: 'The request was stopped before the web was allowed, so nothing was searched.',
61
+ unavailable: 'There is no way to ask the creator about the web here, so nothing was searched.',
62
+ }
63
+ const noWeb = (answer, what = 'searched') => ({ text: (NO_WEB[answer] ?? NO_WEB.unavailable).replace('searched', what) })
64
+
65
+ const keyOf = (ctx, envVar) => {
66
+ try {
67
+ const v = ctx?.secret?.(envVar)
68
+ return typeof v === 'string' && v.trim() ? v.trim() : null
69
+ } catch {
70
+ return null
71
+ }
72
+ }
73
+
74
+ // ---------------------------------------------------------------- asset_search
75
+
76
+ const SEARCH_SHAPE = {
77
+ query: z.string().min(1).max(80).describe('What you are looking for, in English: "mossy rock", "wooden crate", "sunset sky". Add "kenney" for Kenney\'s models on Poly Pizza.'),
78
+ kind: z.enum(['model', 'material', 'hdri']).describe('model: a 3D object; material: a set of PBR texture maps; hdri: a sky that lights the scene.'),
79
+ sources: z.array(z.enum(['polyhaven', 'ambientcg', 'polypizza'])).optional().describe('Default: every source for the kind that can run.'),
80
+ license: z.enum(['cc0', 'cc0-or-by']).default('cc0').describe('cc0: only what needs no credit (the default; publishable today). cc0-or-by: also CC BY, which publishes with a credit line the planet shows its visitors (an Oda from before publish contract 4 refuses it).'),
81
+ limit: z.number().int().min(1).max(24).default(8),
82
+ thumbnails: z.boolean().default(true).describe('Attach at most 8 small previews (128 px), in the order of the list.'),
83
+ look: z.array(z.number().int().min(1).max(24)).max(4).optional().describe('Hits of this same search to look at closely, by their numbers in the list: a 512 px preview of each, instead of the small ones.'),
84
+ }
85
+
86
+ const SEARCH_DESCRIPTION =
87
+ 'Searches free asset libraries (Poly Haven and ambientCG, CC0, no key; Poly Pizza with Kenney\'s CC0 models, with the free polypizza key) for a model, a PBR material or an HDRI sky, and answers one line per hit: its id, title, licence, author, real size (a model\'s, or what one tile of a material covers), the maps it has, its 1k, 2k and 4k downloads with their sizes, a model\'s texel density at each, and its thumbnail URL, with small previews; look at chosen hits closely with look. The libraries the space\'s brief draws from are asked first. Use it before modelling something common (rocks, trees, furniture, props, ground and wall materials, skies); then asset_fetch the id at the resolution the brief\'s texel density needs and asset_import it. Needs the creator\'s web consent, asked once.'
88
+
89
+ function licenseText(l) {
90
+ if (l.spdx === 'CC0-1.0') return 'CC0'
91
+ if (l.spdx === 'LicenseRef-QAL-1.0') return 'QAL (fine inside one planet)'
92
+ return l.spdx
93
+ }
94
+
95
+ /** What each resolution of a hit gives at its real size, px/m by resolution:
96
+ * a model's from the library, a material's from its tile. Null when
97
+ * neither is known. The studio's asset browser shows the same numbers. */
98
+ export function densityOf(c) {
99
+ return c.density ?? (c.covers_m ? Object.fromEntries((c.sizes ?? []).filter((s) => s.res).map((s) => [s.res, Math.round(({ '1k': 1024, '2k': 2048, '4k': 4096 }[s.res] ?? 0) / c.covers_m[0])])) : null)
100
+ }
101
+
102
+ // The hits searched in this process, by "provider:id", for the chat's asset
103
+ // card (nw_ask_asset): it offers a few of them to the creator with their
104
+ // sizes and downloads without asking the library again. Kept half an hour,
105
+ // at most the newest 400.
106
+ const SEEN_MS = 30 * 60_000
107
+ const seen = new Map()
108
+ function remember(cards, now = Date.now()) {
109
+ for (const c of cards) {
110
+ const key = `${c.provider}:${c.id}`
111
+ seen.delete(key)
112
+ seen.set(key, { card: c, at: now })
113
+ }
114
+ while (seen.size > 400) seen.delete(seen.keys().next().value)
115
+ }
116
+ /** A hit asset_search showed in the last half hour, or null. */
117
+ export function searchedCard(id, now = Date.now()) {
118
+ const hit = seen.get(String(id))
119
+ return hit && now - hit.at < SEEN_MS ? hit.card : null
120
+ }
121
+
122
+ function cardLine(n, c) {
123
+ const bits = [`${n}. ${c.provider}:${c.id} "${c.title}" ${c.kind}`, licenseText(c.license), `by ${c.author}`]
124
+ if (c.dims_m) bits.push(`about ${c.dims_m.map((d) => Math.round(d * 100) / 100).join(' x ')} m (w x d x h)`)
125
+ if (c.covers_m) bits.push(`one tile covers about ${c.covers_m.map((d) => Math.round(d * 100) / 100).join(' x ')} m`)
126
+ if (c.triangles) bits.push(`${Number(c.triangles).toLocaleString('en-US')} triangles at full size`)
127
+ if (c.animated) bits.push('animated')
128
+ if (c.maps?.length) bits.push(`maps ${c.maps.join(', ')}`)
129
+ if (c.sizes?.length) bits.push(c.sizes.map((s) => `${s.label} ${mbOf(s.bytes || 0)} MB`).join(' / '))
130
+ const density = densityOf(c)
131
+ if (density && Object.keys(density).length) bits.push(`texel density ${Object.entries(density).map(([r, d]) => `${r} ${d} px/m`).join(', ')}`)
132
+ if (c.license.spdx.startsWith('CC-BY')) bits.push(`credit: ${c.license.credit ?? 'needed'}`)
133
+ if (c.thumbnail) bits.push(`thumbnail ${c.thumbnail}`)
134
+ return bits.join(', ')
135
+ }
136
+
137
+ async function search(args, ctx, deps) {
138
+ const why = NOT_SOURCES.filter((n) => n.name.toLowerCase().split(/[ ,]+/).some((w) => w.length > 4 && args.query.toLowerCase().includes(w.toLowerCase())))
139
+ const allowed = await webAllowed(ctx)
140
+ if (allowed !== 'allow') return noWeb(allowed)
141
+ const fetch = fetchOf(ctx)
142
+ const ua = userAgentFor(ctx)
143
+ const notes = []
144
+ let asked = args.sources ? args.sources.map((id) => deps.sources[id]).filter(Boolean) : Object.values(deps.sources).filter((s) => s.kinds.includes(args.kind))
145
+ // One space keeps to one family of sources: the brief's libraries first.
146
+ const brief = ctx?.projectRoot ? await readBrief(ctx.projectRoot) : { status: 'absent' }
147
+ const family = brief.status === 'ok' ? (brief.brief.sources?.libraries ?? []) : []
148
+ if (family.length && !args.sources) {
149
+ asked = [...asked.filter((s) => family.includes(s.id)), ...asked.filter((s) => !family.includes(s.id))]
150
+ notes.push(`This space's brief draws from ${family.join(', ')}; those are listed first.`)
151
+ }
152
+ /** Each source's hits, in its own order, and whether it is the brief's. */
153
+ const bySource = []
154
+ const ofFamily = []
155
+ for (const source of asked) {
156
+ if (!source.kinds.includes(args.kind)) {
157
+ notes.push(`${source.label} has no ${args.kind}s (it has ${source.kinds.join(', ')}).`)
158
+ continue
159
+ }
160
+ const key = source.needsKey ? keyOf(ctx, source.needsKey) : null
161
+ if (source.needsKey && !key) {
162
+ notes.push(`${source.label} was left out: it needs its free key (ask for it with nw_ask kind key, connector ${source.id}).`)
163
+ continue
164
+ }
165
+ try {
166
+ bySource.push(await source.search(args.query, { kind: args.kind, limit: args.limit, fetch, ua, key }))
167
+ ofFamily.push(!args.sources && family.includes(source.id))
168
+ } catch (err) {
169
+ notes.push(`${source.label} could not be searched: ${err instanceof NetError ? err.message : (err?.message ?? err)}`)
170
+ }
171
+ }
172
+ // Only what may be used; under 'cc0', only what needs no credit.
173
+ let leftOut = 0
174
+ const usable = bySource.map((cards) =>
175
+ cards.filter((c) => {
176
+ const v = licenseVerdict({ ...c.license, credit: c.license.credit ?? 'credit', confirmedByCreator: false })
177
+ const ok = v.ok && (args.license === 'cc0-or-by' ? true : !v.credit && c.license.spdx !== 'LicenseRef-QAL-1.0')
178
+ if (!ok) leftOut++
179
+ return ok
180
+ }),
181
+ )
182
+ // Taken in turn from each source, so the first one cannot fill every place
183
+ // (Poly Haven's six bricks hid every ambientCG one under the limit); the
184
+ // brief's libraries all before the rest.
185
+ const inTurn = (groups) => {
186
+ const out = []
187
+ for (let i = 0; groups.some((cards) => i < cards.length); i++) for (const cards of groups) if (i < cards.length) out.push(cards[i])
188
+ return out
189
+ }
190
+ const kept = [...inTurn(usable.filter((_, k) => ofFamily[k])), ...inTurn(usable.filter((_, k) => !ofFamily[k]))]
191
+ const shown = kept.slice(0, args.limit)
192
+ remember(shown, deps.now?.())
193
+ const images = []
194
+ const looked = (args.look ?? []).filter((n) => n <= shown.length)
195
+ if (looked.length) {
196
+ for (const n of looked) {
197
+ const c = shown[n - 1]
198
+ const src = deps.sources[c.provider]
199
+ const img = await fetchThumbnail(c.preview ?? c.thumbnail, { fetch, hosts: src.hosts, ua, maxBytes: 2 * 1024 * 1024 })
200
+ if (img) images.push(img)
201
+ }
202
+ } else if (args.thumbnails) {
203
+ for (const c of shown.slice(0, 8)) {
204
+ if (!c.thumbnail) continue
205
+ const src = deps.sources[c.provider]
206
+ const img = await fetchThumbnail(c.thumbnail, { fetch, hosts: src.hosts, ua })
207
+ if (img) images.push(img)
208
+ }
209
+ }
210
+ const lines = shown.length ? shown.map((c, i) => cardLine(i + 1, c)) : [`Nothing found for "${args.query}" (${args.kind}).`]
211
+ const said = lines.length
212
+ if (leftOut) lines.push(`${leftOut} more ${leftOut === 1 ? 'was' : 'were'} left out for ${args.license === 'cc0' ? 'needing a credit or a licence that is not CC0' : 'a licence that may not be used'}.`)
213
+ lines.push(...notes)
214
+ for (const n of why) lines.push(`${n.name} is not searched: ${n.why}.`)
215
+ if (shown.length) {
216
+ const previews = looked.length
217
+ ? images.length === 1
218
+ ? ` The close preview is of ${looked[0]}.`
219
+ : ` The close previews are of ${looked.join(', ')}, in that order.`
220
+ : images.length === 1
221
+ ? ' The preview is of 1.'
222
+ : images.length
223
+ ? ` The ${images.length} previews are in the order of the list.`
224
+ : ''
225
+ lines.push(`Next: asset_fetch with an id at the resolution whose texel density meets the brief's target (1k by default), then asset_import it.${previews}`)
226
+ }
227
+ // cards and notes are for the studio's asset browser, which shows the
228
+ // same hits as pictures; the model reads the text and the images only.
229
+ return { text: lines.join('\n'), ...(images.length ? { images } : {}), cards: shown, notes: lines.slice(said, shown.length ? -1 : undefined) }
230
+ }
231
+
232
+ // ---------------------------------------------------------------- asset_fetch
233
+
234
+ const FETCH_SHAPE = {
235
+ id: z.string().regex(/^(polyhaven|ambientcg|polypizza):[\w.-]{1,120}$/).describe('An id from asset_search, e.g. "polyhaven:rock_moss_set_01".'),
236
+ resolution: z.enum(['1k', '2k', '4k']).optional().describe("Texture resolution. Default 1k. Pick the one whose texel density (asset_search lists it) meets the brief's target for this surface; Poly Haven and ambientCG both go to 4k here."),
237
+ format: z.enum(['gltf', 'glb', 'fbx', 'blend', 'hdr', 'exr', 'jpg', 'png', 'zip']).optional().describe("Leave out for the best one: glTF models, JPG materials, Poly Haven's skies as .hdr (ambientCG's are EXR only)."),
238
+ }
239
+
240
+ const FETCH_DESCRIPTION =
241
+ 'Downloads one asset_search hit (every file it needs) into quarantine (.nowhere/quarantine/<qid>/), never into the project: each file within a size cap, checked against the size and checksum its library gives and against what its name says it is, archives unpacked safely. Writes source.json with its licence. Answers what landed, its size and licence, and the id to pass to asset_import. Needs the creator\'s web consent, asked once.'
242
+
243
+ async function fetchItem(args, ctx, deps) {
244
+ if (!ctx?.projectRoot) return fail('No project is open, so there is no quarantine to download into.')
245
+ const allowed = await webAllowed(ctx)
246
+ if (allowed !== 'allow') return noWeb(allowed, 'downloaded')
247
+ const [provider, id] = [args.id.slice(0, args.id.indexOf(':')), args.id.slice(args.id.indexOf(':') + 1)]
248
+ const adapter = deps.sources[provider]
249
+ if (!adapter) return fail(`${provider} is not a source (${SOURCE_IDS.join(', ')}).`)
250
+ const key = adapter.needsKey ? keyOf(ctx, adapter.needsKey) : null
251
+ if (adapter.needsKey && !key) return fail(`${adapter.label} needs its free key. Ask for it with nw_ask kind key, connector ${adapter.id}.`)
252
+ const fetch = fetchOf(ctx)
253
+ const ua = userAgentFor(ctx)
254
+ let item
255
+ try {
256
+ item = await adapter.files(id, { resolution: args.resolution ?? '1k', format: args.format, fetch, ua, key })
257
+ } catch (err) {
258
+ return fail(`${adapter.label} could not be asked about ${id}: ${err?.message ?? err}`)
259
+ }
260
+ if (item?.error) return fail(item.error)
261
+ const got = await fetchIntoQuarantine({ projectRoot: ctx.projectRoot, adapter, id, item, fetch, ua, key, now: deps.now?.() ?? Date.now() })
262
+ if (!got.ok) return fail(got.error)
263
+ const names = got.files.map((f) => f.path)
264
+ const credit = item.license.credit ? ` Credit: ${item.license.credit}.` : ''
265
+ // An HDRI keeps its own format: the .hdr when one landed, else the .exr.
266
+ const skyExt = got.files.some((f) => /\.hdr$/i.test(f.path)) ? '.hdr' : got.files.some((f) => /\.exr$/i.test(f.path)) ? '.exr' : '.hdr'
267
+ const asHint = item.kind === 'model' ? `as "assets/<name>.glb", a class (${ASSET_CLASSES.join(', ')}) and, unless it is already at real size, a size in metres` : item.kind === 'hdri' ? `as "assets/<name>${skyExt}"` : 'as "assets/<name>" (the maps become <name>_color, _normal, _rough, _ao, and _metal, _displacement, _opacity when it has them)'
268
+ const lines = [
269
+ `Fetched ${args.id} "${item.title}" (${item.kind}) into quarantine as ${got.qid}: ${got.files.length} files, ${mbOf(got.bytes)} MB (${names.slice(0, 8).join(', ')}${names.length > 8 ? `, and ${names.length - 8} more` : ''}).`,
270
+ `Licence: ${item.license.spdx}${item.author ? `, by ${item.author}` : ''}, recorded in its source.json.${credit}`,
271
+ ]
272
+ if (got.skipped.length) lines.push(`Left in the archive (executables and scripts are never unpacked): ${got.skipped.slice(0, 8).join(', ')}.`)
273
+ if (got.rejected.length) lines.push(`Removed (not a type the studio takes, or not what its name says): ${got.rejected.slice(0, 8).map((r) => r.path).join(', ')}.`)
274
+ if (item.note) lines.push(item.note)
275
+ lines.push(`Next: asset_import from "${got.qid}" ${asHint}.`)
276
+ // qid, kind and the sky's format for the studio's asset browser, which
277
+ // imports what it fetched without reading the text.
278
+ return { text: lines.join('\n'), qid: got.qid, kind: item.kind, skyExt, bytes: got.bytes }
279
+ }
280
+
281
+ // ---------------------------------------------------------------- asset_import
282
+
283
+ const IMPORT_SHAPE = {
284
+ from: z.string().describe('A quarantine id (asset_fetch, a browser download, asset_job gen-<id>, environment_job env-<id>) or a path inside .nowhere/quarantine/.'),
285
+ as: z.string().describe('model: assets/<name>.glb; material: assets/<name> (files become <name>_color.<ext>, _normal, _rough, _ao; .ktx2 where KTX2 is written); texture: assets/<name>.ktx2 (where KTX2 is written), .jpg or .png; hdri: assets/<name>.hdr; audio: assets/<name>.ogg|.mp3; lut: assets/<name>.cube; splat: assets/<name>.spz (from a .spz, a Gaussian splat .ply or a .splat; its collider becomes assets/<name>_collider.glb)'),
286
+ class: z
287
+ .enum(ASSET_CLASSES)
288
+ .optional()
289
+ .describe(`model: the most triangles and the texture size it may have (${ASSET_CLASSES.map((c) => `${c} ${TRIANGLE_BUDGETS[c].toLocaleString('en-US')}`).join(', ')}); default prop. material or texture: only the size its maps keep (${ASSET_CLASSES.map((c) => `${c} ${TEXTURE_BUDGETS[c]}`).join(', ')} px); default 2048, and a smaller picture stays as it is.`),
290
+ size: z
291
+ .object({ height: z.number().positive(), width: z.number().positive(), depth: z.number().positive(), longest: z.number().positive() })
292
+ .partial()
293
+ .optional()
294
+ .describe('model: its real size in metres, one of height, width, depth or longest; scaled uniformly to it.'),
295
+ pivot: z.enum(['base', 'center', 'keep']).default('base').describe('base: the centre of its footprint at the origin, standing on y = 0.'),
296
+ maxTexture: z.number().int().min(256).max(4096).optional().describe('Longest side of any texture, px. Default from the class (a material or texture without one: 2048).'),
297
+ simplify: z.boolean().default(true).describe('Reduce the triangles to the class\'s limit when over it.'),
298
+ license: z
299
+ .object({ spdx: z.string(), url: z.string(), author: z.string(), title: z.string(), credit: z.string() })
300
+ .partial()
301
+ .optional()
302
+ .describe('Required when the quarantine entry has no source.json (a browser download): read the licence page first.'),
303
+ confirmedShareAlike: z.boolean().optional().describe('CC BY-SA: only after the creator agreed in an nw_ask choice card.'),
304
+ replace: z.boolean().default(false).describe('Overwrite an existing file at as.'),
305
+ orientation: z.enum(['y-down', 'y-up']).optional().describe("splat: the file's up. y-down (OpenCV's frame: most captures, World Labs, three's examples) is turned upright. Default: what the source recorded, else y-down. If nw_view shows it upside down, import it again with the other."),
306
+ scale: z.number().positive().max(1000).optional().describe('splat: metres per unit of the file. Default: what the source recorded (World Labs\' metric_scale_factor), else 1.'),
307
+ ground: z.union([z.enum(['auto', 'keep']), z.number()]).optional().describe("splat: where its floor is, set to y = 0. auto: the lowest of its solid splats; keep: as the file has it; a number: that height (after turning and scaling). Default: the source's ground plane, else auto."),
308
+ center: z.boolean().optional().describe('splat: move the middle of its solid core to x = 0, z = 0, so it sits in the middle of the map. Default false.'),
309
+ collider: z.string().optional().describe('splat: the GLB it collides with, from quarantine (an id or a path): a floor and walls made in Blender, World Labs\' collider. Default: a GLB in the same quarantine folder (environment_job leaves one).'),
310
+ colliderFrame: z.enum(['splat', 'space']).optional().describe("splat: splat (default): the collider is in the splat file's own frame and gets the same turn, scale and floor; space: it was made over the imported splat, in metres with y up, and comes in as it is."),
311
+ capture: z.boolean().optional().describe("splat: the creator scanned it themselves (a phone or camera capture), recorded as theirs. Only after they said so in an nw_ask choice card, in the screen language."),
312
+ tileSize: z
313
+ .union([z.number().positive().max(200), z.tuple([z.number().positive().max(200), z.number().positive().max(200)])])
314
+ .optional()
315
+ .describe('material or texture: the metres one tile covers at its real size (width, or [width, height]). Default: what the library says, else the brief\'s tileMetres. Sets its texel density.'),
316
+ ktx2: z.enum(['auto', 'measure', 'off']).default('auto').describe("auto: textures written as KTX2 (and a model's geometry meshopt-compressed) unless the last Publish found the live server or player without them, else their GPU memory estimated. measure: then each texture encoded and measured too (slower: seconds a map), the result recorded in the ledger. off: textures stay the pictures they came as (a scanned map's JPEG can be smaller to download than its KTX2)."),
317
+ belowTarget: z.boolean().optional().describe("Import even under half the brief's texel density for it. Only when the brief's target is wrong for this surface; correct brief.json too."),
318
+ }
319
+
320
+ const IMPORT_DESCRIPTION =
321
+ "Brings a fetched, generated or downloaded file from quarantine into assets/: the only way a file from outside gets into the space. A model becomes one GLB with its textures at a real size in metres, standing on its pivot, within its class's triangle and texture limits (fbx, obj and the rest are converted with Blender), checked by the glTF validator, with contact sheets and a quality rubric when Blender is here; a material becomes its full set of maps named <name>_color, _normal, _rough, _ao (and _metal, _displacement, _opacity when it has them) with a code snippet; textures are written as KTX2, each map in the codec it holds up in, and a model's geometry meshopt-compressed, where the server and player this project publishes to decode them (the answer says when they do not); an HDRI is measured for the sky, and a 2:1 picture (image_generate's panorama) imported as .hdr becomes one; a sound and a LUT are checked; a Gaussian splat (.spz, .ply, .splat: a creator's scan or a generated world) becomes one .spz, upright, in metres, its floor at y = 0, counted against what a planet draws, with its collider baked into the same frame as <name>_collider.glb. Every model, material and texture is inspected as asset_inspect does (maps, texel density against the brief, seam, GPU memory and KTX2) and the report is in the answer; under half the brief's texel density nothing is written. Refuses NC, ND and unknown licences, CC BY without a credit, and CC BY-SA without the creator's agreement, before anything is written. Records the file, its source, licence and inspection in assets.lock.json and CREDITS.md, and a library pick in the brief's sources."
322
+
323
+ // ---------------------------------------------------------------- asset_inspect
324
+
325
+ const INSPECT_SHAPE = {
326
+ path: z.string().describe('What to inspect: a model "assets/<name>.glb", a material by its name "assets/<name>" (its maps <name>_color, _normal, ...), one texture "assets/<name>.png", or a splat "assets/<name>.spz".'),
327
+ tileSize: z
328
+ .union([z.number().positive().max(200), z.tuple([z.number().positive().max(200), z.number().positive().max(200)])])
329
+ .optional()
330
+ .describe('material or texture: the metres one tile covers. Default: what the ledger recorded at import, else the brief\'s tileMetres.'),
331
+ ktx2: z.boolean().default(false).describe('Encode every texture as KTX2 and measure it (the codec each gets, its size, the colour difference and the detail kept). Slower: seconds a map.'),
332
+ }
333
+
334
+ const INSPECT_DESCRIPTION =
335
+ "Says what an asset in assets/ is made of and whether it is good enough for this space, in numbers held to brief.json: a material's maps (colour, normal, rough, ao, metal, displacement, opacity) and which are missing, their sizes, its texel density at its real size and its 2 x 2 seam score, with the 2 x 2 sheet to look at; a model's triangles, size, every material's maps, the texel density its UVs give at its real size, untextured parts and whether shadow looks baked into its colour; a texture's size, values and seam. Each is compared with the brief's texel density for that surface (under half: refused at import; under four fifths or over two and a half times: said). GPU memory as it is and as KTX2, encoded and measured with ktx2. Reads only; changes nothing."
336
+
337
+ async function inspect(args, ctx, deps) {
338
+ if (!ctx?.projectRoot) return fail('No project is open.')
339
+ const root = ctx.projectRoot
340
+ const rel = String(args.path ?? '').replace(/\\/g, '/').replace(/^\.\//, '')
341
+ const m = /^assets\/([A-Za-z0-9][A-Za-z0-9_-]{0,63})(\.[A-Za-z0-9]+)?$/.exec(rel)
342
+ if (!m) return fail(`path "${args.path}" is not assets/<name>.glb, assets/<name> (a material) or assets/<name>.png.`)
343
+ const [, stem, ext] = m
344
+ const lock = await readLedgerState(root)
345
+ const tile = typeof args.tileSize === 'number' ? [args.tileSize, args.tileSize] : Array.isArray(args.tileSize) ? args.tileSize : null
346
+ let report
347
+ let images = []
348
+ if (!ext) {
349
+ if (!Object.keys(materialMaps(root, stem)).length) return fail(`assets/${stem} is not a material here: no assets/${stem}_color.jpg (or .png, .ktx2).`)
350
+ report = await inspectMaterial(root, stem, { tileMetres: tile, ktx2: args.ktx2, rpc: ctx.rpc, ledger: lock.lock.files })
351
+ if (report.error) return fail(report.error)
352
+ if (report.sheet) images = [{ mime: 'image/png', data: report.sheet }]
353
+ } else {
354
+ const abs = path.join(root, 'assets', `${stem}${ext}`)
355
+ if (!fs.existsSync(abs)) return fail(`${rel} is not in the project.`)
356
+ if (ext.toLowerCase() === '.glb' || ext.toLowerCase() === '.gltf') {
357
+ let doc
358
+ try {
359
+ doc = await deps.readGltf(abs)
360
+ } catch (err) {
361
+ return fail(`${rel} could not be read: ${err?.message ?? err}`)
362
+ }
363
+ const recorded = lock.lock.files[rel]?.meta?.ktx2
364
+ report = await inspectModelDoc(doc, { file: rel, projectRoot: root, ktx2: args.ktx2, rpc: ctx.rpc, recorded: recorded && typeof recorded === 'object' ? recorded : null })
365
+ } else if (['.png', '.jpg', '.jpeg', '.webp'].includes(ext.toLowerCase())) {
366
+ const meta = lock.lock.files[rel]?.meta ?? {}
367
+ const picture = await inspectPicture(abs, { role: typeof meta.role === 'string' ? meta.role : 'color', seam: true, ktx2: args.ktx2, rpc: ctx.rpc })
368
+ // What its import measured, when it is not measured again now.
369
+ if (!args.ktx2 && meta.ktx2?.mode && !meta.ktx2.written) picture.ktx2Recorded = meta.ktx2
370
+ const t = tile?.[0] ?? (Array.isArray(meta.tile_m) ? meta.tile_m[0] : null)
371
+ const brief = await readBrief(root)
372
+ report = { kind: 'texture', picture, density: t && picture.width ? densityVerdict(picture.width / t, briefDensityFor(brief.status === 'ok' ? brief.brief : null, rel)) : null, brief: brief.status === 'ok' ? 'ok' : 'none' }
373
+ if (picture.sheet) images = [{ mime: 'image/png', data: picture.sheet }]
374
+ } else if (ext.toLowerCase() === '.spz') {
375
+ let s
376
+ try {
377
+ s = await readSplat(await fs.promises.readFile(abs), rel)
378
+ } catch (err) {
379
+ return fail(`${rel} could not be read: ${err?.message ?? err}`)
380
+ }
381
+ const st = splatStats(s)
382
+ const meta = lock.lock.files[rel]?.meta ?? {}
383
+ const box = (b) => `x ${b.min[0]} to ${b.max[0]}, y ${b.min[1]} to ${b.max[1]}, z ${b.min[2]} to ${b.max[2]} m`
384
+ return {
385
+ text: [
386
+ `${rel}: a Gaussian splat, ${st.count.toLocaleString('en-US')} splats, colour detail degree ${st.shDegree}, ${(fs.statSync(abs).size / 1048576).toFixed(1)} MB.`,
387
+ `- spans ${box(st.bounds)}; its solid core (1st to 99th percentile) ${box(st.core)}; its solid splats' floor at y = ${st.floorY}.`,
388
+ `- ${st.count > SPLAT_LIMITS.phoneCount ? `past the ${SPLAT_LIMITS.phoneCount.toLocaleString('en-US')} measured for lighter devices: for desktops` : 'within what lighter devices were measured to draw'}.`,
389
+ meta.collider ? `- its collider: ${meta.collider}.` : '- no collider recorded for it.',
390
+ ].join('\n'),
391
+ }
392
+ } else return fail(`${rel} is not a model, a material, a picture or a splat asset_inspect reads (.glb, .png, .jpg, .spz).`)
393
+ }
394
+ const head = report.kind === 'material' ? `The material assets/${stem}:` : `${rel}:`
395
+ return { text: [head, ...reportLines(report).map((l) => (l.startsWith('- ') ? ` ${l}` : `- ${l}`)), ...(images.length ? ['The picture is it tiled 2 x 2: a seam shows as a cross through the middle.'] : [])].join('\n'), ...(images.length ? { images } : {}) }
396
+ }
397
+
398
+ // ---------------------------------------------------------------- asset_ledger
399
+
400
+ const LEDGER_SHAPE = {
401
+ path: z.string().optional().describe('One file, e.g. "assets/rock.glb". Default: every file.'),
402
+ problems: z.boolean().default(true).describe('Also list what would stop a publish.'),
403
+ }
404
+
405
+ const LEDGER_DESCRIPTION =
406
+ "Reads assets.lock.json, the record of every file the space carries (and the Blender inputs models were made from): each file's kind, origin, licence, credit and size, the generated credits, and what would stop a publish (a file in assets/ the ledger does not know, which publishing refuses once the scene, the config or the code names it; an imported file changed since it was recorded; a refused licence; CC BY that planets cannot show yet)."
407
+
408
+ async function ledger(args, ctx) {
409
+ if (!ctx?.projectRoot) return fail('No project is open.')
410
+ const state = await readLedgerState(ctx.projectRoot)
411
+ if (state.status === 'absent') {
412
+ return { text: `There is no ${LEDGER} yet: the first asset_import (or nw_blender export) writes it. Until then the project publishes as it always has, with only the models scene.json places.` }
413
+ }
414
+ if (state.status === 'invalid') return fail(`${state.error}.`)
415
+ const entries = Object.entries(state.lock.files).filter(([p]) => !args.path || p === args.path)
416
+ if (args.path && entries.length === 0) return fail(`${args.path} is not in ${LEDGER}.`)
417
+ const lines = entries.map(([p, e]) => {
418
+ const bits = [`${p}: ${e.kind}, ${e.origin}, ${e.license.spdx}`]
419
+ if (e.license.credit) bits.push(`credit "${e.license.credit}"`)
420
+ bits.push(`${mbOf(e.bytes)} MB`)
421
+ if (e.source?.provider) bits.push(`from ${e.source.provider}${e.source.id ? ` ${e.source.id}` : ''}`)
422
+ if (e.generation) bits.push(`generated by ${e.generation.vendor} ${e.generation.model} ($${e.generation.usd.toFixed(2)})`)
423
+ if (e.derivedFrom?.length) bits.push(`made from ${e.derivedFrom.join(', ')}`)
424
+ if (e.meta?.triangles) bits.push(`${Number(e.meta.triangles).toLocaleString('en-US')} triangles`)
425
+ if (e.kind === 'splat' && e.meta?.count) bits.push(`${Number(e.meta.count).toLocaleString('en-US')} splats${e.meta.collider ? `, collider ${e.meta.collider}` : ''}`)
426
+ if (e.meta?.role === 'collider' && e.meta.for) bits.push(`the collider of ${e.meta.for}`)
427
+ if (e.meta?.texel_density) bits.push(`${e.meta.texel_density} px/m`)
428
+ if (typeof e.meta?.seam === 'number') bits.push(`seam score ${e.meta.seam}`)
429
+ const k2 = e.meta?.ktx2
430
+ if (k2?.mode) bits.push(`KTX2 ${String(k2.mode).toUpperCase()} ${k2.written ? 'written' : `measured, ${mbOf(k2.bytes ?? 0)} MB (${k2.bytes > e.bytes ? 'more' : 'less'} than the file's ${mbOf(e.bytes)} MB)`}`)
431
+ else if (k2 && typeof k2 === 'object' && Object.values(k2).every((t) => t?.mode)) bits.push(`its textures as KTX2 measured, ${mbOf(Object.values(k2).reduce((n, t) => n + (t.bytes ?? 0), 0))} MB (${Object.values(k2).map((t) => t.mode.toUpperCase()).join(', ')})`)
432
+ if (e.meta?.meshopt?.bytes) bits.push(`meshopt would be ${mbOf(e.meta.meshopt.bytes)} MB`)
433
+ if (e.publish === false) bits.push('stays on this machine')
434
+ return bits.join(', ')
435
+ })
436
+ const out = [`${LEDGER}: ${Object.keys(state.lock.files).length} files.`, ...lines]
437
+ if (!args.path) out.push('', 'CREDITS.md (generated section):', creditsFor(state.lock).markdown)
438
+ if (args.problems) {
439
+ const problems = (await ledgerProblems(ctx.projectRoot)).filter((f) => !args.path || f.path === args.path)
440
+ out.push('', problems.length ? `Would stop a publish (${problems.length}):` : 'Nothing in it would stop a publish.')
441
+ for (const f of problems) out.push(`- ${f.message}`)
442
+ if (!CREDITS_SHOWN) out.push('(CC BY files cannot be published until planets show credits to visitors: decision D2.)')
443
+ }
444
+ return { text: out.join('\n') }
445
+ }
446
+
447
+ // ---------------------------------------------------------------- the defs
448
+
449
+ const runCmd = (cmd, args, timeoutMs = 300_000) =>
450
+ new Promise((resolve) => {
451
+ execFile(cmd, args, { timeout: timeoutMs, windowsHide: true, maxBuffer: 8 << 20 }, (err, stdout, stderr) =>
452
+ resolve({ code: err ? (typeof err.code === 'number' ? err.code : 1) : 0, stdout: String(stdout ?? ''), stderr: String(stderr ?? ''), error: err && typeof err.code !== 'number' ? err.message : null }),
453
+ )
454
+ })
455
+
456
+ let ffmpegFound
457
+ const findFfmpeg = async () => (ffmpegFound ??= (await onPath('ffmpeg', ['-version'])) ? 'ffmpeg' : null)
458
+
459
+ /** The ToolDefs, with everything outside replaceable for checks. */
460
+ export function makeAssetTools(overrides = {}) {
461
+ const deps = {
462
+ sources: SOURCES,
463
+ findBlender,
464
+ runBlender,
465
+ imageOps: null,
466
+ imageOpsFor: (ctx) => createImageOps({ rpc: ctx?.rpc }),
467
+ ffmpeg: findFfmpeg,
468
+ run: runCmd,
469
+ decoders: undefined,
470
+ readGltf,
471
+ now: () => Date.now(),
472
+ ...overrides,
473
+ }
474
+ const guarded = (name, fn) => async (args, ctx) => {
475
+ try {
476
+ return await fn(args, ctx)
477
+ } catch (err) {
478
+ return fail(`${name} failed: ${err?.message ?? err}`)
479
+ }
480
+ }
481
+ return [
482
+ { name: 'asset_search', description: SEARCH_DESCRIPTION, shape: SEARCH_SHAPE, readOnly: true, handler: guarded('asset_search', (a, c) => search(a, c, deps)) },
483
+ { name: 'asset_fetch', description: FETCH_DESCRIPTION, shape: FETCH_SHAPE, readOnly: true, handler: guarded('asset_fetch', (a, c) => fetchItem(a, c, deps)) },
484
+ {
485
+ name: 'asset_import',
486
+ description: IMPORT_DESCRIPTION,
487
+ shape: IMPORT_SHAPE,
488
+ readOnly: false,
489
+ handler: guarded('asset_import', (a, c) => importAsset(a, c, { ...deps, imageOps: deps.imageOps ?? deps.imageOpsFor(c) })),
490
+ },
491
+ { name: 'asset_inspect', description: INSPECT_DESCRIPTION, shape: INSPECT_SHAPE, readOnly: true, handler: guarded('asset_inspect', (a, c) => inspect(a, c, deps)) },
492
+ { name: 'asset_ledger', description: LEDGER_DESCRIPTION, shape: LEDGER_SHAPE, readOnly: true, handler: guarded('asset_ledger', (a, c) => ledger(a, c)) },
493
+ ]
494
+ }
495
+
496
+ export const TOOLS = makeAssetTools()
497
+
498
+ // Named for the skill and the prompt: what a texture of each class may be.
499
+ export { TEXTURE_BUDGETS, POLYPIZZA_ENV, sourcesFor }