topotopo 0.3.0 → 0.5.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 (354) hide show
  1. package/NOTICE +40 -10
  2. package/README.md +475 -111
  3. package/dist/cli.js +328 -133
  4. package/dist/config.d.ts +48 -0
  5. package/dist/config.js +170 -0
  6. package/dist/core/analysis.d.ts +5 -1
  7. package/dist/core/analysis.js +8 -3
  8. package/dist/core/bake.d.ts +16 -8
  9. package/dist/core/bake.js +165 -29
  10. package/dist/core/bevel.d.ts +3 -1
  11. package/dist/core/bevel.js +238 -97
  12. package/dist/core/decimate.d.ts +65 -0
  13. package/dist/core/decimate.js +409 -3
  14. package/dist/core/erosion.d.ts +37 -0
  15. package/dist/core/erosion.js +41 -1
  16. package/dist/core/geometry.d.ts +5 -1
  17. package/dist/core/geometry.js +204 -4
  18. package/dist/core/heightfield.d.ts +27 -4
  19. package/dist/core/heightfield.js +54 -16
  20. package/dist/core/imageops.d.ts +6 -0
  21. package/dist/core/imageops.js +51 -0
  22. package/dist/core/intrinsics.d.ts +7 -0
  23. package/dist/core/intrinsics.js +94 -0
  24. package/dist/core/manifold.d.ts +12 -1
  25. package/dist/core/manifold.js +78 -6
  26. package/dist/core/materials.d.ts +11 -0
  27. package/dist/core/materials.js +56 -0
  28. package/dist/core/noise.d.ts +9 -0
  29. package/dist/core/noise.js +10 -1
  30. package/dist/core/packed.js +11 -0
  31. package/dist/core/particles.d.ts +1 -1
  32. package/dist/core/particles.js +1 -1
  33. package/dist/core/polymerge.d.ts +21 -0
  34. package/dist/core/polymerge.js +327 -0
  35. package/dist/core/rbd.js +13 -1
  36. package/dist/core/repair.d.ts +2 -0
  37. package/dist/core/repair.js +2 -0
  38. package/dist/core/report.d.ts +70 -0
  39. package/dist/core/report.js +275 -0
  40. package/dist/core/scatter.d.ts +1 -1
  41. package/dist/core/scatter.js +1 -1
  42. package/dist/core/scene.d.ts +20 -0
  43. package/dist/core/scene.js +72 -0
  44. package/dist/core/sha256.d.ts +4 -0
  45. package/dist/core/sha256.js +69 -0
  46. package/dist/core/shapes.d.ts +3 -0
  47. package/dist/core/shapes.js +34 -0
  48. package/dist/core/snippet-lib.d.ts +15 -2
  49. package/dist/core/snippet-lib.js +40 -14
  50. package/dist/core/solidify.d.ts +38 -0
  51. package/dist/core/solidify.js +356 -0
  52. package/dist/core/tangents.d.ts +54 -0
  53. package/dist/core/tangents.js +218 -0
  54. package/dist/core/texcoord.d.ts +4 -0
  55. package/dist/core/texcoord.js +14 -0
  56. package/dist/core/texnoise.d.ts +6 -1
  57. package/dist/core/texnoise.js +6 -2
  58. package/dist/core/texsdf.d.ts +131 -0
  59. package/dist/core/texsdf.js +637 -0
  60. package/dist/core/texture.d.ts +163 -9
  61. package/dist/core/texture.js +844 -20
  62. package/dist/core/topology.d.ts +32 -0
  63. package/dist/core/topology.js +238 -7
  64. package/dist/core/traceimage.d.ts +7 -0
  65. package/dist/core/traceimage.js +221 -0
  66. package/dist/core/tritri.d.ts +5 -0
  67. package/dist/core/tritri.js +120 -0
  68. package/dist/core/unwrap.d.ts +72 -0
  69. package/dist/core/unwrap.js +800 -0
  70. package/dist/core/usercode.d.ts +27 -0
  71. package/dist/core/usercode.js +87 -0
  72. package/dist/core/uv.d.ts +15 -16
  73. package/dist/core/uv.js +36 -189
  74. package/dist/core/uvislands.d.ts +62 -0
  75. package/dist/core/uvislands.js +574 -0
  76. package/dist/core/uvoverlap.d.ts +58 -0
  77. package/dist/core/uvoverlap.js +220 -0
  78. package/dist/core/uvpack.d.ts +64 -0
  79. package/dist/core/uvpack.js +628 -0
  80. package/dist/core/uvreport.d.ts +127 -0
  81. package/dist/core/uvreport.js +372 -0
  82. package/dist/core/wrangle.d.ts +6 -1
  83. package/dist/core/wrangle.js +27 -16
  84. package/dist/core/xatlas.d.ts +16 -1
  85. package/dist/core/xatlas.js +95 -61
  86. package/dist/engines.d.ts +63 -0
  87. package/dist/engines.js +180 -0
  88. package/dist/explain.d.ts +4 -3
  89. package/dist/explain.js +129 -12
  90. package/dist/graph/engine.d.ts +92 -29
  91. package/dist/graph/engine.js +298 -148
  92. package/dist/graph/expr.d.ts +6 -3
  93. package/dist/graph/expr.js +18 -8
  94. package/dist/graph/outputs.d.ts +23 -0
  95. package/dist/graph/outputs.js +41 -0
  96. package/dist/graph/packages.d.ts +72 -0
  97. package/dist/graph/packages.js +261 -0
  98. package/dist/graph/parallel.d.ts +3 -1
  99. package/dist/graph/parallel.js +4 -1
  100. package/dist/graph/params.d.ts +6 -0
  101. package/dist/graph/params.js +34 -7
  102. package/dist/graph/scope.d.ts +55 -0
  103. package/dist/graph/scope.js +14 -0
  104. package/dist/graph/types.d.ts +75 -12
  105. package/dist/graph/types.js +4 -2
  106. package/dist/graph/vars.d.ts +16 -0
  107. package/dist/graph/vars.js +80 -0
  108. package/dist/host/artifacts.d.ts +10 -1
  109. package/dist/host/artifacts.js +37 -6
  110. package/dist/host/cook.d.ts +241 -0
  111. package/dist/host/cook.js +844 -0
  112. package/dist/host/export-targets.d.ts +42 -5
  113. package/dist/host/export-targets.js +72 -13
  114. package/dist/host/godot-commands.d.ts +4 -0
  115. package/dist/host/godot-commands.js +21 -0
  116. package/dist/host/godot.d.ts +183 -0
  117. package/dist/host/godot.js +916 -0
  118. package/dist/host/node.d.ts +12 -7
  119. package/dist/host/node.js +27 -9
  120. package/dist/host/pool.js +51 -2
  121. package/dist/host/sidecars.d.ts +8 -0
  122. package/dist/host/sidecars.js +50 -0
  123. package/dist/host/types.d.ts +19 -6
  124. package/dist/host/version.d.ts +1 -0
  125. package/dist/host/version.js +3 -0
  126. package/dist/host/worker.js +5 -2
  127. package/dist/index.d.ts +5 -3
  128. package/dist/index.js +3 -2
  129. package/dist/inspect.d.ts +84 -1
  130. package/dist/inspect.js +271 -24
  131. package/dist/io/common.d.ts +33 -5
  132. package/dist/io/export.js +2 -1
  133. package/dist/io/files.d.ts +23 -4
  134. package/dist/io/files.js +60 -8
  135. package/dist/io/gltf.js +355 -51
  136. package/dist/io/heightmap.d.ts +3 -0
  137. package/dist/io/heightmap.js +1 -0
  138. package/dist/io/import.js +10 -0
  139. package/dist/io/inspect-scene.d.ts +55 -0
  140. package/dist/io/inspect-scene.js +155 -0
  141. package/dist/io/kinds.d.ts +81 -0
  142. package/dist/io/kinds.js +163 -0
  143. package/dist/io/points.d.ts +2 -1
  144. package/dist/io/points.js +3 -1
  145. package/dist/io/sidecars.d.ts +24 -0
  146. package/dist/io/sidecars.js +57 -0
  147. package/dist/io/source.d.ts +65 -0
  148. package/dist/io/source.js +112 -0
  149. package/dist/io/targets.d.ts +47 -3
  150. package/dist/io/targets.js +149 -14
  151. package/dist/io/textures.js +21 -1
  152. package/dist/io/unreal.js +5 -1
  153. package/dist/mcp/docs.d.ts +10 -1
  154. package/dist/mcp/docs.js +816 -119
  155. package/dist/mcp/inputs.d.ts +12 -5
  156. package/dist/mcp/inputs.js +50 -13
  157. package/dist/mcp/server.js +70 -24
  158. package/dist/mcp/tools.d.ts +14 -7
  159. package/dist/mcp/tools.js +207 -108
  160. package/dist/mcp/verify.d.ts +2 -2
  161. package/dist/mcp/verify.js +1 -1
  162. package/dist/mcp/workspace.d.ts +15 -0
  163. package/dist/mcp/workspace.js +349 -0
  164. package/dist/nodes/attributes.js +198 -1
  165. package/dist/nodes/bake.js +207 -83
  166. package/dist/nodes/beam.d.ts +1 -0
  167. package/dist/nodes/beam.js +201 -0
  168. package/dist/nodes/bevel.js +54 -5
  169. package/dist/nodes/cloth.js +2 -0
  170. package/dist/nodes/code.js +22 -10
  171. package/dist/nodes/curves.js +440 -93
  172. package/dist/nodes/flow.js +53 -33
  173. package/dist/nodes/generate.js +13 -39
  174. package/dist/nodes/heightfield.js +248 -77
  175. package/dist/nodes/imageops.d.ts +1 -0
  176. package/dist/nodes/imageops.js +203 -0
  177. package/dist/nodes/index.d.ts +4 -0
  178. package/dist/nodes/index.js +4 -0
  179. package/dist/nodes/material.js +91 -23
  180. package/dist/nodes/measure.js +45 -18
  181. package/dist/nodes/particles.js +2 -0
  182. package/dist/nodes/pcg.js +6 -5
  183. package/dist/nodes/procedural.js +4 -3
  184. package/dist/nodes/rbd.js +1 -1
  185. package/dist/nodes/remesh.js +71 -15
  186. package/dist/nodes/scene.d.ts +1 -0
  187. package/dist/nodes/scene.js +55 -0
  188. package/dist/nodes/sdf.js +10 -5
  189. package/dist/nodes/solid.js +20 -5
  190. package/dist/nodes/solidify.d.ts +1 -0
  191. package/dist/nodes/solidify.js +52 -0
  192. package/dist/nodes/splines.d.ts +15 -1
  193. package/dist/nodes/splines.js +112 -105
  194. package/dist/nodes/texture.d.ts +21 -6
  195. package/dist/nodes/texture.js +1318 -185
  196. package/dist/nodes/topology.d.ts +7 -0
  197. package/dist/nodes/topology.js +133 -6
  198. package/dist/nodes/transform.js +11 -3
  199. package/dist/nodes/util.d.ts +1 -1
  200. package/dist/nodes/uv.js +192 -174
  201. package/dist/nodes/wasmcall.js +6 -2
  202. package/dist/open.d.ts +19 -0
  203. package/dist/open.js +12 -0
  204. package/dist/package.d.ts +288 -0
  205. package/dist/package.js +772 -0
  206. package/dist/packages/check.d.ts +32 -0
  207. package/dist/packages/check.js +169 -0
  208. package/dist/packages/commands.d.ts +57 -0
  209. package/dist/packages/commands.js +537 -0
  210. package/dist/packages/registry.d.ts +796 -0
  211. package/dist/packages/registry.js +2998 -0
  212. package/dist/packages/update.d.ts +124 -0
  213. package/dist/packages/update.js +476 -0
  214. package/dist/render/options.d.ts +2 -0
  215. package/dist/render/options.js +44 -5
  216. package/dist/render/pbr.d.ts +28 -0
  217. package/dist/render/pbr.js +378 -0
  218. package/dist/render/preview.d.ts +69 -0
  219. package/dist/render/preview.js +26 -0
  220. package/dist/render/raster.d.ts +78 -7
  221. package/dist/render/raster.js +600 -145
  222. package/dist/render/texview.d.ts +7 -1
  223. package/dist/render/texview.js +34 -2
  224. package/dist/scan.d.ts +61 -0
  225. package/dist/scan.js +228 -0
  226. package/dist/session.d.ts +311 -0
  227. package/dist/session.js +849 -0
  228. package/dist/viewer/app/api.js +48 -6
  229. package/dist/viewer/app/camera.js +1 -1
  230. package/dist/viewer/app/cooking.js +78 -0
  231. package/dist/viewer/app/embed.js +100 -0
  232. package/dist/viewer/app/export-popover.js +118 -16
  233. package/dist/viewer/app/grid.js +6 -2
  234. package/dist/viewer/app/guides.js +123 -1
  235. package/dist/viewer/app/keymap.js +7 -4
  236. package/dist/viewer/app/layers.js +5 -5
  237. package/dist/viewer/app/main.js +186 -53
  238. package/dist/viewer/app/markers.js +61 -1
  239. package/dist/viewer/app/outliner.js +72 -27
  240. package/dist/viewer/app/output-info.js +45 -0
  241. package/dist/viewer/app/outputs.css +147 -8
  242. package/dist/viewer/app/outputs.js +168 -54
  243. package/dist/viewer/app/packages.js +614 -0
  244. package/dist/viewer/app/props.js +177 -53
  245. package/dist/viewer/app/scene.js +35 -6
  246. package/dist/viewer/app/select.js +5 -4
  247. package/dist/viewer/app/selection.js +1 -1
  248. package/dist/viewer/app/status.js +12 -15
  249. package/dist/viewer/app/style.css +66 -8
  250. package/dist/viewer/app/units.js +1 -1
  251. package/dist/viewer/app/vars.js +48 -1
  252. package/dist/viewer/app/welcome.js +72 -0
  253. package/dist/viewer/graph-file.d.ts +62 -0
  254. package/dist/viewer/graph-file.js +175 -0
  255. package/dist/viewer/index.html +24 -11
  256. package/dist/viewer/json-edit.d.ts +13 -0
  257. package/dist/viewer/json-edit.js +274 -0
  258. package/dist/viewer/outputs.d.ts +49 -5
  259. package/dist/viewer/outputs.js +264 -56
  260. package/dist/viewer/packages.d.ts +121 -0
  261. package/dist/viewer/packages.js +584 -0
  262. package/dist/viewer/server.d.ts +24 -7
  263. package/dist/viewer/server.js +289 -31
  264. package/dist/web/app/web.css +419 -0
  265. package/dist/web/app/web.js +188 -0
  266. package/dist/web/bake.d.ts +34 -0
  267. package/dist/web/bake.js +153 -0
  268. package/dist/web/folder-page.d.ts +101 -0
  269. package/dist/web/folder-page.js +146 -0
  270. package/dist/web/folders.d.ts +280 -0
  271. package/dist/web/folders.js +970 -0
  272. package/dist/web/library.d.ts +91 -0
  273. package/dist/web/library.js +228 -0
  274. package/dist/web/markdown.d.ts +45 -0
  275. package/dist/web/markdown.js +677 -0
  276. package/dist/web/pages.d.ts +258 -0
  277. package/dist/web/pages.js +301 -0
  278. package/dist/web/server.d.ts +24 -0
  279. package/dist/web/server.js +1068 -0
  280. package/dist/workspace.d.ts +88 -105
  281. package/dist/workspace.js +359 -375
  282. package/integrations/godot/addons/topotopo/LICENSE +202 -0
  283. package/integrations/godot/addons/topotopo/README.md +57 -0
  284. package/integrations/godot/addons/topotopo/context_menu.gd +43 -0
  285. package/integrations/godot/addons/topotopo/dock.gd +266 -0
  286. package/integrations/godot/addons/topotopo/dock.tscn +72 -0
  287. package/integrations/godot/addons/topotopo/export_filter.gd +72 -0
  288. package/integrations/godot/addons/topotopo/gltf_instancing.gd +131 -0
  289. package/integrations/godot/addons/topotopo/icons/topotopo.svg +1 -0
  290. package/integrations/godot/addons/topotopo/inspector.gd +38 -0
  291. package/integrations/godot/addons/topotopo/instances_post_import.gd +111 -0
  292. package/integrations/godot/addons/topotopo/package.gd +23 -0
  293. package/integrations/godot/addons/topotopo/package_importer.gd +187 -0
  294. package/integrations/godot/addons/topotopo/plugin.cfg +7 -0
  295. package/integrations/godot/addons/topotopo/plugin.gd +970 -0
  296. package/integrations/godot/addons/topotopo/record.gd +435 -0
  297. package/integrations/godot/addons/topotopo/runner.gd +458 -0
  298. package/integrations/godot/addons/topotopo/tools/check.gd +42 -0
  299. package/integrations/godot/addons/topotopo/watcher.gd +199 -0
  300. package/kernels/pkg/README.md +23 -29
  301. package/kernels/pkg-simd/README.md +23 -29
  302. package/library/architecture/versions/1.0/architecture.topo +12 -0
  303. package/{shelf → library/architecture/versions/1.0/graphs}/arch.json +3 -3
  304. package/{shelf → library/architecture/versions/1.0/graphs}/beam_truss.json +6 -6
  305. package/{shelf → library/architecture/versions/1.0/graphs}/brick_wall.json +8 -8
  306. package/{shelf → library/architecture/versions/1.0/graphs}/door_frame.json +3 -3
  307. package/{shelf → library/architecture/versions/1.0/graphs}/hex_grid_floor.json +3 -2
  308. package/{shelf → library/architecture/versions/1.0/graphs}/house.json +8 -8
  309. package/library/architecture/versions/1.0/graphs/lineup.json +42 -0
  310. package/{shelf → library/architecture/versions/1.0/graphs}/pillar.json +3 -2
  311. package/{shelf → library/architecture/versions/1.0/graphs}/railing.json +5 -5
  312. package/{shelf → library/architecture/versions/1.0/graphs}/roof_gable.json +2 -2
  313. package/{shelf → library/architecture/versions/1.0/graphs}/roof_hip.json +2 -2
  314. package/{shelf → library/architecture/versions/1.0/graphs}/roof_skeleton.json +2 -1
  315. package/{shelf → library/architecture/versions/1.0/graphs}/scaffold.json +4 -4
  316. package/{shelf → library/architecture/versions/1.0/graphs}/spiral_stairs.json +3 -2
  317. package/{shelf → library/architecture/versions/1.0/graphs}/stairs.json +6 -6
  318. package/{shelf → library/architecture/versions/1.0/graphs}/tile_floor.json +3 -2
  319. package/{shelf → library/architecture/versions/1.0/graphs}/wall_segment.json +10 -10
  320. package/{shelf → library/architecture/versions/1.0/graphs}/window_frame.json +2 -2
  321. package/library/architecture/versions/1.0/version.json +1119 -0
  322. package/{shelf → library/nature/versions/1.0/graphs}/bush.json +2 -2
  323. package/{shelf → library/nature/versions/1.0/graphs}/cliff_block.json +4 -3
  324. package/{shelf → library/nature/versions/1.0/graphs}/forest_patch.json +5 -5
  325. package/{shelf → library/nature/versions/1.0/graphs}/grass_clumps.json +2 -2
  326. package/library/nature/versions/1.0/graphs/lineup.json +24 -0
  327. package/{shelf → library/nature/versions/1.0/graphs}/log.json +6 -6
  328. package/{shelf → library/nature/versions/1.0/graphs}/rock.json +5 -4
  329. package/{shelf → library/nature/versions/1.0/graphs}/scatter_rocks.json +5 -5
  330. package/{shelf → library/nature/versions/1.0/graphs}/tree_lowpoly.json +3 -2
  331. package/library/nature/versions/1.0/nature.topo +12 -0
  332. package/library/nature/versions/1.0/version.json +534 -0
  333. package/{shelf → library/props/versions/1.0/graphs}/barrel.json +5 -4
  334. package/{shelf → library/props/versions/1.0/graphs}/crate.json +3 -3
  335. package/library/props/versions/1.0/graphs/lineup.json +18 -0
  336. package/{shelf → library/props/versions/1.0/graphs}/pallet.json +4 -3
  337. package/{shelf → library/props/versions/1.0/graphs}/pipe_run.json +3 -3
  338. package/{shelf → library/props/versions/1.0/graphs}/sandbag_wall.json +5 -5
  339. package/library/props/versions/1.0/props.topo +12 -0
  340. package/library/props/versions/1.0/version.json +336 -0
  341. package/{shelf → library/street/versions/1.0/graphs}/bench.json +5 -5
  342. package/{shelf → library/street/versions/1.0/graphs}/bollard.json +2 -1
  343. package/{shelf → library/street/versions/1.0/graphs}/cable.json +4 -4
  344. package/{shelf → library/street/versions/1.0/graphs}/fence.json +7 -7
  345. package/{shelf → library/street/versions/1.0/graphs}/lamp_post.json +2 -2
  346. package/library/street/versions/1.0/graphs/lineup.json +22 -0
  347. package/{shelf → library/street/versions/1.0/graphs}/road_strip.json +2 -2
  348. package/{shelf → library/street/versions/1.0/graphs}/sign_post.json +1 -1
  349. package/library/street/versions/1.0/street.topo +12 -0
  350. package/library/street/versions/1.0/version.json +421 -0
  351. package/package.json +23 -8
  352. package/dist/graph/migrate.d.ts +0 -23
  353. package/dist/graph/migrate.js +0 -58
  354. package/shelf/index.json +0 -190
package/dist/mcp/tools.js CHANGED
@@ -2,19 +2,23 @@
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import zlib from 'node:zlib';
5
- import { Workspace, EditRejected } from '../workspace.js';
5
+ import { Session, EditRejected } from '../session.js';
6
6
  import { allNodeDefs } from '../graph/registry.js';
7
7
  import { didYouMean } from '../graph/params.js';
8
- import { migrateGraph } from '../graph/migrate.js';
9
- import { catalogText, nodeDoc, TOPICS, topicList, INSTRUCTIONS } from './docs.js';
10
- import { summarize, inspect } from '../inspect.js';
11
- import { renderGeometry } from '../render/raster.js';
8
+ import { catalogText, nodeDoc, topicList, topicText, INSTRUCTIONS } from './docs.js';
9
+ import { nodeBudgetInput, summarize, inspect } from '../inspect.js';
10
+ import { glbSceneReport, sceneReportText } from '../io/inspect-scene.js';
11
+ import { renderGeometryAsync } from '../render/raster.js';
12
12
  import { renderArgs } from '../render/options.js';
13
13
  import { encodePNG } from '../render/png.js';
14
14
  import { EXPORT_FORMATS, exportFormatFromPath } from '../io/export.js';
15
- import { publishedOutputs } from '../io/targets.js';
15
+ import { exportToolOptions, publishedOutputs } from '../io/targets.js';
16
+ import { kindMismatch, outputKind } from '../io/kinds.js';
17
+ import { exportSource } from '../io/source.js';
18
+ import { packageAt, packagesUsed } from '../graph/packages.js';
16
19
  import { ArtifactStore } from '../host/artifacts.js';
17
20
  import { prepareTarget, serializeExport, writeExportFiles, writeTargets } from '../host/export-targets.js';
21
+ import { TOPOTOPO_VERSION } from '../host/version.js';
18
22
  import { evalGroup } from '../core/groups.js';
19
23
  import { Geometry } from '../core/geometry.js';
20
24
  import { verifyTools } from './verify.js';
@@ -22,7 +26,7 @@ import { inputsTool } from './inputs.js';
22
26
  const text = (t, isError = false) => ({ content: [{ type: 'text', text: t }], ...(isError ? { isError } : {}) });
23
27
  /** " at frame N" when the cook was not at frame 1. */
24
28
  const atFrame = (r) => (r.frame !== 1 ? ` at frame ${r.frame}` : '');
25
- function reportText(name, r, extraNotes = []) {
29
+ function reportText(name, r, extraNotes = [], extraWarnings = []) {
26
30
  const lines = [];
27
31
  const nodes = [...r.results.values()];
28
32
  const cooked = nodes.filter((n) => !n.cached && !n.error).length;
@@ -34,8 +38,10 @@ function reportText(name, r, extraNotes = []) {
34
38
  lines.push(` [${e.node}] ${e.message}${e.hint ? `\n hint: ${e.hint}` : ''}`);
35
39
  for (const n of [...r.notes, ...extraNotes])
36
40
  lines.push(`note: ${n}`);
37
- if (r.warnings.length) {
41
+ if (r.warnings.length || extraWarnings.length) {
38
42
  lines.push('warnings:');
43
+ for (const w of extraWarnings)
44
+ lines.push(` ${w}`);
39
45
  for (const w of r.warnings.slice(0, 15))
40
46
  lines.push(` [${w.node}] ${w.message}`);
41
47
  if (r.warnings.length > 15)
@@ -57,32 +63,41 @@ function reportText(name, r, extraNotes = []) {
57
63
  const FRAME_PROP = {
58
64
  frame: { type: 'number', description: 'frame to cook at (default 1; frame 1 = time 0, 24 fps). Only time-dependent nodes (solver, @Frame wrangles, "=frame" params) change between frames.' },
59
65
  };
60
- function pngContent(g, o) {
61
- const r = renderGeometry(g, o);
66
+ /** Render to a PNG content block; shading "pbr" reads texture files through the host. */
67
+ async function pngContent(g, o, host) {
68
+ const r = await renderGeometryAsync(g, o, (t) => host.readFile(t));
62
69
  const png = encodePNG(r.rgba, r.width, r.height, (d) => zlib.deflateSync(d, { level: 6 }));
63
70
  return { img: { type: 'image', data: Buffer.from(png).toString('base64'), mimeType: 'image/png' }, notes: r.notes, png };
64
71
  }
65
72
  /**
66
73
  * Write every file of an export (heightmap sidecars and layers, instance-stream sidecar and mesh GLBs, the Unreal
67
- * Landscape bundle, or the single file of other formats). Textures are read through the host; USD texture paths are
68
- * written relative to the output file. Returns the report text.
74
+ * Landscape bundle, or the single file of other formats) and the record of how it was made (`source`, io/source.ts).
75
+ * Textures are read through the host; USD texture paths are written relative to the output file. Returns the report
76
+ * text.
69
77
  */
70
- export async function writeExport(geo, format, p, a, host, record) {
71
- const res = await serializeExport(geo, format, p, a, host);
78
+ export async function writeExport(geo, format, p, a, host, record, source) {
79
+ const res = await serializeExport(geo, format, p, a, host, source);
72
80
  writeExportFiles(res.files);
73
81
  if (res.files.length)
74
82
  record?.(res.files.map((f) => f.path));
75
- return exportReport(res.files, res.outDir, format, res.summary, res.warnings);
83
+ return exportReport(res.files, res.outDir, format, res.summary, res.warnings, res.sourceFile, res.sourceManifest);
76
84
  }
77
- /** "wrote <file or N files in dir> (format, KB): summary", then any warnings. */
78
- function exportReport(files, outDir, format, summary, warnings) {
85
+ /**
86
+ * "wrote <file or N files in dir> (format, KB): summary", where the export's source is recorded, then any warnings. A
87
+ * standalone <file>.source.json is named on its own line, not in the file list.
88
+ */
89
+ function exportReport(all, outDir, format, summary, warnings, sourceFile, sourceManifest) {
90
+ const files = all.filter((f) => f.path !== sourceManifest);
79
91
  const total = files.reduce((s, f) => s + f.bytes.byteLength, 0);
80
92
  const rel = (f) => path.relative(outDir, f).split(path.sep).join('/');
81
93
  const list = files.length === 1 ? files[0].path : `${files.length} files in ${outDir}: ${files.slice(0, 12).map((f) => rel(f.path)).join(', ')}${files.length > 12 ? ', …' : ''}`;
82
- return `wrote ${list} (${format}, ${(total / 1024).toFixed(1)} KB): ${summary}${warnings.length ? '\nwarnings:\n ' + warnings.join('\n ') : ''}`;
94
+ return `wrote ${list} (${format}, ${(total / 1024).toFixed(1)} KB): ${summary}${sourceFile ? `\nsource recorded in ${rel(sourceFile)} (graph, vars, seeds, frame; help topic "export")` : ''}${warnings.length ? '\nwarnings:\n ' + warnings.join('\n ') : ''}`;
83
95
  }
84
- function renderOpts(a, g, label) {
96
+ function renderOpts(a, g, label, dir) {
85
97
  const ro = renderArgs(a); // views (presets, persp@az, section), overlays, shading, labels … (src/render/options.ts)
98
+ // a reference image is a path relative to the package, as save_to is
99
+ if (ro.underlay)
100
+ ro.underlay = path.resolve(dir, ro.underlay);
86
101
  let highlight = null;
87
102
  if (a.highlight) {
88
103
  const cls = a.highlight_class === 'point' ? 'point' : 'prim';
@@ -92,22 +107,28 @@ function renderOpts(a, g, label) {
92
107
  }
93
108
  return {
94
109
  ...ro, wireframe: ro.wireframe ?? 'auto', colorBy: ro.colorBy ?? null, highlight,
95
- points: ro.points ?? 'auto', grid: ro.grid ?? true, target: ro.target ?? null, title: label, checker: !!ro.checker,
110
+ points: ro.points ?? 'auto', target: ro.target ?? null, title: label, checker: !!ro.checker,
96
111
  };
97
112
  }
98
113
  const RENDER_PROPS = {
99
- views: { description: 'views: "quad" (persp+front+right+top, default), "quad_uv" (persp + uv side by side), "turntable" (persp at azimuth 0/90/180/270), a single view, or a list of persp/front/back/left/right/top/bottom/uv/section/texture/persp@<azimuth>. "texture" draws images flat (see texture). "uv" draws the 0..1 UV square (UDIM tiles, 0.1 grid): polygons filled by chart/island colour, island borders yellow, overlaps red. "section" slices along section_axis and looks along it: the cut filled red (blue = inside-out solid), open sheets as yellow lines, the far half ghosted', anyOf: [{ type: 'string' }, { type: 'array', items: { type: 'string' } }] },
114
+ views: { description: 'views: "quad" (persp+front+right+top, default), "quad_uv" (persp + uv side by side), "turntable" (persp at azimuth 0/90/180/270), a single view, or a list of persp/front/back/left/right/top/bottom/front_left/front_right/back_left/back_right/uv/section/texture/persp@<azimuth> (front_left … are persp views at azimuth -45/45/-135/135). Every 3D view fits the bounds. "texture" draws images flat (see texture). "uv" draws the 0..1 UV square (UDIM tiles, 0.1 grid): polygons filled by chart/island colour, island borders yellow, overlaps red. "section" slices along section_axis and looks along it: the cut filled red (blue = inside-out solid), open sheets as yellow lines, the far half ghosted', anyOf: [{ type: 'string' }, { type: 'array', items: { type: 'string' } }] },
100
115
  checker: { type: 'boolean', description: 'shade 3D views with an 8×8 uv checker (light cells tinted red along u, green along v) to see stretch, seams and flips' },
101
- size: { type: 'number', description: 'pixels per view tile (default 512 for multi-view, 800 single); scale 2 doubles it' },
102
- color_by: { type: 'string', description: 'colour by attribute (e.g. "height", "class", "N", "P.y"); ints/strings get categorical colours' },
116
+ size: { description: 'pixels per view: n (square; default 512 for several views, 800 for one) or "WxH" / [w, h] (e.g. "1600x600" for a long prop: the views fit the bounds to that aspect); scale 2 doubles it', anyOf: [{ type: 'number' }, { type: 'string' }, { type: 'array', items: { type: 'number' } }] },
117
+ transparent: { type: 'boolean', description: 'transparent background: pixels without surface, line or point get alpha 0 (PNG with alpha); no ground grid or axis gizmo; the footer stays opaque' },
118
+ grid: { type: 'boolean', description: 'the persp ground grid on y = 0 (default true, false with transparent)' },
119
+ underlay: { type: 'string', description: 'a reference image (PNG, path relative to the package) drawn behind the 3D views, e.g. a side photo behind views:"front"' },
120
+ underlay_opacity: { type: 'number', description: 'underlay opacity 0..1 (default 0.5)' },
121
+ underlay_fit: { type: 'string', enum: ['bounds', 'width', 'height', 'view'], description: 'where the underlay goes: "bounds" (default: fitted into the rectangle the bounds cover in each view, keeping its aspect, so a reference cropped to the object lines up with it), "width" (its width spans the width of the bounds), "height" (its height spans their height), "view" (the whole view)' },
122
+ sockets: { type: 'boolean', description: 'draw scene empties (scene_null sockets) as dots with their name and orient axes (X red, Y green, Z blue), through surfaces; without it pbr renders hide them' },
123
+ color_by: { type: 'string', description: 'colour by attribute (e.g. "height", "class", "N", "P.y"); ints/strings get categorical colours; under shading "pbr" the colours tint the shaded material' },
103
124
  highlight: { type: 'string', description: 'group pattern to highlight in orange (e.g. "front", "@P.y>1")' },
104
125
  highlight_class: { type: 'string', enum: ['prim', 'point'] },
105
- wireframe: { description: 'true/false/"auto" (polygon edges, auto = on below 6000 polys), or a crisp 1 px edge overlay: "all" (every edge: topology density), "hard" (dihedral > hard_angle in cyan + crease/hard/sharp edge groups), "boundary" (open edges pink, non-manifold yellow, winding flips violet), "groups" (each edge group in its colour, with legend), "none"', anyOf: [{ type: 'boolean' }, { type: 'string', enum: ['auto', 'none', 'all', 'hard', 'boundary', 'groups'] }] },
126
+ wireframe: { description: 'true/false/"auto" (polygon edges; auto, the default, draws them below 6,000 polygons but never under shading "pbr" or textures:true, and the footer says EDGES AUTO when it does), or a crisp 1 px edge overlay: "all" (every edge: topology density), "hard" (dihedral > hard_angle in cyan + crease/hard/sharp edge groups), "boundary" (open edges pink, non-manifold yellow, winding flips violet), "groups" (each edge group in its colour, with legend), "none"', anyOf: [{ type: 'boolean' }, { type: 'string', enum: ['auto', 'none', 'all', 'hard', 'boundary', 'groups'] }] },
106
127
  points: { type: 'boolean', description: 'draw all points, sized by pscale when present (default: only loose points)' },
107
- azimuth: { type: 'number', description: 'persp camera azimuth degrees (default 35)' },
108
- elevation: { type: 'number', description: 'persp camera elevation degrees (default 25)' },
109
- zoom: { type: 'number', description: 'zoom factor (1 = fit bbox)' },
110
- target: { type: 'array', items: { type: 'number' }, description: 'look-at point override [x,y,z]' },
128
+ azimuth: { type: 'number', description: 'persp camera azimuth in degrees around +Y (default 35): 0 = camera on +Z looking at the front, 90 = on +X (right side), 180 = back, -90 = left' },
129
+ elevation: { type: 'number', description: 'persp camera elevation in degrees above the horizon (default 25; 90 looks straight down)' },
130
+ zoom: { type: 'number', description: 'relative to the fit: 1 (default) = the bounds fill the view with a small margin, 0.5 = half that size. Above 1 it magnifies around look_at and crops: only with look_at or ortho_scale, else it is held at 1 (a note says so)' },
131
+ target: { type: 'array', items: { type: 'number' }, description: 'look-at point [x,y,z] (same as look_at)' },
111
132
  hard_angle: { type: 'number', description: 'wireframe "hard": dihedral angle threshold in degrees (default 30)' },
112
133
  point_numbers: { type: 'boolean', description: 'label visible point numbers (the first max_labels points)' },
113
134
  prim_numbers: { type: 'boolean', description: 'label visible prim numbers at prim centroids (the first max_labels prims)' },
@@ -124,14 +145,17 @@ const RENDER_PROPS = {
124
145
  glyph_scale: { type: 'number', description: 'glyph length in world units (default 5% of the bbox diagonal)' },
125
146
  max_glyphs: { type: 'number', description: 'evenly subsample to at most this many glyphs (default 400)' },
126
147
  max_triangles: { type: 'number', description: 'packed instances: draw up to this many expanded triangles (default 600000, max 50M); above it an evenly spread subset is drawn and a note says so' },
148
+ heightfield_res: { description: 'heightfields: the most quads drawn per side (default 256: a 513 × 513 field draws at 257 × 257, and the footer and a note say so), or "full" for every sample', anyOf: [{ type: 'number', minimum: 1 }, { type: 'string', enum: ['full'] }] },
149
+ heightfield_layer: { type: 'string', description: 'heightfields: the layer drawn in red over the shaded terrain (default "mask"; e.g. "flow", "sediment", "path"; "none" for none). 0..1 layers show as they are, others from their min to their max; the footer legend names it, and a note says when a field has no such layer' },
127
150
  label_groups: { type: 'boolean', description: 'name each point/prim group on a visible member near its centroid, outline prim groups / mark group points in the label colour, legend with counts' },
128
151
  label_pieces: { type: 'boolean', description: 'number connected pieces (#0, #1, … in connectivity order)' },
129
152
  label_attrib: { type: 'string', description: 'label each distinct value of a string/int attribute (e.g. "name") on its elements; colours match color_by' },
130
153
  legend: { type: 'boolean', description: 'legend for color_by (gradient bar with min/max, or categorical swatches) and highlight' },
131
- shading: { type: 'string', enum: ['default', 'flat', 'matcap', 'ao'], description: 'flat: facets (ignores N); matcap: clay that reads form; ao: screen-space ambient occlusion darkens creases and cavities' },
154
+ shading: { type: 'string', enum: ['default', 'flat', 'matcap', 'ao', 'pbr'], description: 'flat: facets (ignores N); matcap: clay that reads form; ao: screen-space ambient occlusion darkens creases and cavities; pbr: the exported metallic-roughness material (base colour, normal, orm/roughness maps, emissive, unlit) under a fixed studio light rig, deterministic' },
155
+ exposure: { type: 'number', description: 'shading "pbr": exposure in stops (default 0)' },
132
156
  ao_radius: { type: 'number', description: 'shading "ao": sample radius in pixels (default 10)' },
133
- look_at: { type: 'array', items: { type: 'number' }, description: 'look-at point [x,y,z] (same as target)' },
134
- ortho_scale: { type: 'number', description: 'ortho/section views: world width across a view (default: fit the bbox)' },
157
+ look_at: { type: 'array', items: { type: 'number' }, description: 'look-at point [x, y, z] in world metres (x right, y up, z towards the front; default the bbox centre): the view centres on it and still fits the bounds; with zoom > 1 it zooms into that point' },
158
+ ortho_scale: { type: 'number', description: 'ortho and section views: the world width in metres across a view (default: fit the bounds), e.g. 0.5 shows 50 cm across' },
135
159
  scale: { type: 'number', description: '2 (up to 4) for a 2× image: tiles, text, lines and markers scaled' },
136
160
  annotate: { type: 'boolean', description: 'second footer line naming the active overlays plus geometry notes (pieces, open edges, back-facing %); default on whenever an overlay option is used' },
137
161
  view_labels: { type: 'boolean', description: 'false hides the name label of every view and the persp axis gizmo (clean thumbnails); default true' },
@@ -143,12 +167,33 @@ export function makeTools(ws, opts = {}) {
143
167
  // would pile up in exports/renders (save_to keeps a copy elsewhere).
144
168
  const renderDestination = (name, node) => path.join(ws.exportDir, 'renders', `${name}-${node}`.replace(/[^A-Za-z0-9_.-]/g, '_') + '.png');
145
169
  const engine = ws.engine;
170
+ /**
171
+ * The named outputs of a cooked graph that cook to another kind than their author pinned ("kind" in its outputs, help
172
+ * topic "packages"), each said as a warning: publishing the package would block on them.
173
+ */
174
+ const kindWarnings = async (name, r, frame) => {
175
+ const out = [];
176
+ if (!r.ok)
177
+ return out;
178
+ for (const [id, o] of Object.entries(ws.graphs.get(name)?.outputs ?? {})) {
179
+ if (!o || typeof o.kind !== 'string')
180
+ continue;
181
+ const c = o.node === r.target ? r : await ws.cook(name, o.node, frame);
182
+ // an output that does not cook says so when it is cooked
183
+ if (!c.ok || !c.geo)
184
+ continue;
185
+ const said = kindMismatch(o.kind, outputKind(c.geo));
186
+ if (said)
187
+ out.push(`[output "${id}"] ${said}`);
188
+ }
189
+ return out;
190
+ };
146
191
  /** The text (+ optional render) of a cook report. */
147
- const reportResult = (name, r, a, extraNotes = []) => {
148
- const content = [{ type: 'text', text: reportText(name, r, extraNotes) }];
192
+ const reportResult = async (name, r, a, extraNotes = []) => {
193
+ const content = [{ type: 'text', text: reportText(name, r, extraNotes, await kindWarnings(name, r, a.frame)) }];
149
194
  if (r.geo && a.render) {
150
- const ro = renderOpts(typeof a.render === 'object' ? a.render : {}, r.geo, `${name}/${r.target}${atFrame(r)}`);
151
- const { img, notes, png } = pngContent(r.geo, ro);
195
+ const ro = renderOpts(typeof a.render === 'object' ? a.render : {}, r.geo, `${name}/${r.target}${atFrame(r)}`, ws.dir);
196
+ const { img, notes, png } = await pngContent(r.geo, ro, engine.host);
152
197
  const renderPath = renderDestination(name, r.target);
153
198
  fs.mkdirSync(path.dirname(renderPath), { recursive: true });
154
199
  fs.writeFileSync(renderPath, png);
@@ -164,15 +209,19 @@ export function makeTools(ws, opts = {}) {
164
209
  ws.bump(name);
165
210
  return reportResult(name, r, a, extraNotes);
166
211
  };
167
- const resolveNodeGeo = async (a) => {
212
+ const resolveNodeGeo = async (a, forExport = false) => {
168
213
  const name = a.graph ?? a.name ?? 'main'; // `name` is what build/edit call it; accept both
169
214
  const g = ws.getGraph(name);
170
215
  const target = a.node || undefined;
171
- const r = await engine.cook(g, { target, frame: a.frame });
216
+ // an export uses the published copies of the packages the session shows live (following is for looking)
217
+ const scope = forExport && ws.packages?.publishedNote?.(g) ? ws.packages.published?.() : null;
218
+ const r = await engine.cook(g, { target, frame: a.frame, ...(scope ? { scope } : {}) });
172
219
  if (!r.ok || !r.geo)
173
220
  throw new Error(reportText(name, r));
174
- return { r, name, geo: r.geo };
221
+ return { r, name, geo: r.geo, scope };
175
222
  };
223
+ /** What an export of a graph made while following says (the published versions it used), on a line of its own. */
224
+ const publishedLine = (spec) => { const n = ws.packages?.publishedNote?.(spec); return n ? `\n${n}` : ''; };
176
225
  /** export without a path: the graph's targets (the default output's, a named one's, or all), inside exports/ */
177
226
  const exportTargets = async (a) => {
178
227
  const name = a.graph ?? a.name ?? 'main', spec = ws.getGraph(name);
@@ -182,7 +231,7 @@ export function makeTools(ws, opts = {}) {
182
231
  if (!a.all) {
183
232
  const p = a.output === undefined ? published[0] : published.find((x) => x.output === a.output);
184
233
  if (!p)
185
- return text(`graph "${name}" publishes no output "${a.output}" (outputs: ${published.slice(1).map((x) => x.output).join(', ') || 'none'})`, true);
234
+ return text(`graph "${name}" publishes no output "${a.output}" (outputs: ${published.filter((x) => x.output !== null).map((x) => `${x.output}${x.default ? ' (default)' : ''}`).join(', ') || 'none'})`, true);
186
235
  if (!p.target)
187
236
  return text(`${a.output === undefined ? 'the default output' : `output "${a.output}"`} of "${name}" has no export target: set one with ${hint(a.output)}, or pass path`, true);
188
237
  chosen = [p];
@@ -192,20 +241,20 @@ export function makeTools(ws, opts = {}) {
192
241
  return text(`no output of "${name}" has an export target: set one with ${hint(undefined)}, or pass path`, true);
193
242
  const prepared = [];
194
243
  for (const p of targets) {
195
- const r = await ws.cook(name, p.node, a.frame);
244
+ const r = await ws.cook(name, p.node, a.frame, { kind: 'export' });
196
245
  if (!r.ok || !r.geo)
197
246
  return text(reportText(name, r), true);
198
- prepared.push(await prepareTarget(r.geo, name, p, ws.exportDir, engine.host));
247
+ prepared.push(await prepareTarget(r.geo, name, p, ws.exportDir, engine.host, { frame: r.frame, fps: r.fps, packages: packagesUsed(engine, spec, ws.packages?.published?.() ?? engine.root) }));
199
248
  }
200
249
  writeTargets(prepared, ws.exportDir);
201
250
  const skipped = chosen.filter((p) => !p.target).map((p) => p.label);
202
- return text(prepared.map((p) => exportReport(p.files, ws.exportDir, p.target.format, `${p.label}: ${p.summary}`, p.warnings)).join('\n')
203
- + (skipped.length ? `\nno export target (skipped): ${skipped.join(', ')}` : ''));
251
+ return text(prepared.map((p) => exportReport(p.files, p.root, p.target.format, `${p.label}: ${p.summary}`, p.warnings, p.sourceFile, p.sourceManifest)).join('\n')
252
+ + (skipped.length ? `\nno export target (skipped): ${skipped.join(', ')}` : '') + publishedLine(spec));
204
253
  };
205
254
  const tools = [
206
255
  {
207
256
  name: 'catalog',
208
- description: 'List available node types grouped by category (generate, curve, transform, deform, attribute, measure, group, topology, copy, solid, sdf, heightfield, uv, code, flow, io, pcg, shelf = shipped graph assets such as stairs or fence, asset = workspace assets). Optional filter by category or search text. Building a landscape or scene for a person? Call inputs {action:"list"} first: the meshes, guide curves and masks they dropped into the workspace.',
257
+ description: 'List available node types grouped by category (generate, curve, transform, deform, attribute, measure, group, topology, copy, solid, sdf, heightfield, uv, code, flow, io, pcg, asset = package assets, package = package outputs, "owner/name/output": those the package uses, and TopoTopo\'s own, ready-made walls, houses, roofs, stairs, rocks, trees, props and roads such as "topotopo/architecture/house" or "topotopo/nature/rock", which a graph\'s first use adds to the package). Optional filter by category or search text. Building a landscape or scene for a person? Call inputs {action:"list"} first: the meshes, guide curves and masks they dropped into the package.',
209
258
  inputSchema: {
210
259
  type: 'object',
211
260
  properties: {
@@ -215,27 +264,31 @@ export function makeTools(ws, opts = {}) {
215
264
  },
216
265
  },
217
266
  run: async (a) => {
218
- const cat = catalogText([...allNodeDefs(), ...[...engine.assets.values()].map((x) => x.def)], { category: a.category, search: a.search, deprecated: a.include_deprecated });
267
+ const cat = catalogText([...allNodeDefs(), ...engine.assetsIn().map((x) => x.def), ...engine.packageDefs()], { category: a.category, search: a.search, deprecated: a.include_deprecated });
219
268
  const nIn = ws.listInputs().length;
220
- return text(`${cat}\nHUMAN INPUT: ${nIn ? `${nIn} file${nIn === 1 ? '' : 's'} in` : 'nothing yet in'} the workspace inputs/ folder (meshes, guide curves and points, blockouts, PNG masks people drop in). Building a landscape or scene: inputs {action:"list"} first, then read them with file nodes (help topic "inputs").`);
269
+ // the package outputs listed cannot be used where the server's folder is in no package: say why, and how that changes
270
+ const notice = (!a.category || a.category === 'package') ? ws.packages?.notice() : null;
271
+ return text(`${cat}${notice ? `\nPACKAGES: ${notice}` : ''}\nHUMAN INPUT: ${nIn ? `${nIn} file${nIn === 1 ? '' : 's'} in` : 'nothing yet in'} the package inputs/ folder (meshes, guide curves and points, blockouts, PNG masks people drop in). Building a landscape or scene: inputs {action:"list"} first, then read them with file nodes (help topic "inputs").`);
221
272
  },
222
273
  },
223
274
  {
224
275
  name: 'help',
225
- description: `Exact docs for node types (params with types, defaults, ranges, aliases; inputs; examples) and concept topics: ${topicList().join(', ')}. Call before using unfamiliar nodes.`,
276
+ description: `Exact docs for node types (params with types, defaults, ranges, aliases; inputs; examples; a package output "owner/name/output": its params, inputs, version and note, also one search found that the package does not use yet) and concept topics: ${topicList().join(', ')}. Call before using unfamiliar nodes.`,
226
277
  inputSchema: { type: 'object', properties: { nodes: { type: 'array', items: { type: 'string' }, description: 'node type names' }, topic: { type: 'string', description: `one of: ${topicList().join(', ')}, overview` } } },
227
278
  run: async (a) => {
228
279
  const out = [];
229
- if (a.topic) {
230
- if (a.topic === 'overview' || a.topic === 'instructions')
231
- out.push(INSTRUCTIONS);
232
- else if (TOPICS[a.topic])
233
- out.push(TOPICS[a.topic]);
234
- else
235
- out.push(`unknown topic "${a.topic}". Topics: overview, ${topicList().join(', ')}`);
236
- }
280
+ if (a.topic)
281
+ out.push(topicText(String(a.topic)) ?? `unknown topic "${a.topic}". Topics: overview, ${topicList().join(', ')}`);
237
282
  for (const n of a.nodes ?? []) {
238
283
  const d = engine.resolveDef(n);
284
+ if (!d && String(n).includes('/')) {
285
+ const p = engine.packageIssue(String(n));
286
+ // a package this package does not use yet (TopoTopo's own, or one search found in a library it lists): its
287
+ // docs, read where its library holds it, and what naming it does here
288
+ const offered = engine.packageDefs().find((x) => x.type === n) ?? ws.packages?.describe(String(n)) ?? undefined;
289
+ out.push(offered ? `${nodeDoc(offered)}\nin this package: ${p.error}${p.hint ? ` (hint: ${p.hint})` : ''}` : `${p.error}${p.hint ? `\n hint: ${p.hint}` : ''}`);
290
+ continue;
291
+ }
239
292
  if (!d) {
240
293
  const s = didYouMean(n, engine.allTypeNames());
241
294
  out.push(`unknown node "${n}"${s.length ? ` — did you mean ${s.join(', ')}?` : ''}`);
@@ -255,7 +308,7 @@ export function makeTools(ws, opts = {}) {
255
308
  type: 'object',
256
309
  required: ['graph'],
257
310
  properties: {
258
- graph: { type: 'object', description: '{"nodes": {name: {"type", "in", "params"}}, "output": name, "outputs": {id: {"node": name, "label": "Published result", "export": "glb"}}, "export": "glb", "vars": {...}, "params": {var: {"type", "desc", "min", "max", "options", "label", "step"}}}. Publish intended deliverables in outputs; output remains the default. "export" (on the graph for the default output, or on a named output) is where it exports: a format, or {format, path?, ...export options}, written inside exports/ by the viewer\'s Export buttons and export {output} / {all:true}.' },
311
+ graph: { type: 'object', description: '{"nodes": {name: {"type", "in", "params"}}, "output": name, "outputs": {id: {"node": name, "label": "Published result", "export": "glb", "publish": false (not published), "kind": "mesh" (pinned: build warns and publishing blocks when it cooks to another kind), "tags": ["conifer", "low-poly"], "description": "what it is"}}, "export": "glb", "vars": {...}, "params": {var: {"type", "desc", "min", "max", "options", "label", "step"}}}. Publish intended deliverables in outputs; output remains the default. A node "type" "owner/name/output" is an output of a package (help topic "packages"). "export" (on the graph for the default output, or on a named output) is where it exports: a format, or {format, path?, ...export options}, written inside exports/ by the viewer\'s Export buttons and export {output} / {all:true}.' },
259
312
  name: { type: 'string', description: 'graph name (default "main")' },
260
313
  mode: { type: 'string', enum: ['replace', 'merge'] },
261
314
  dry_run: { type: 'boolean' },
@@ -268,20 +321,26 @@ export function makeTools(ws, opts = {}) {
268
321
  let spec = a.graph;
269
322
  if (typeof spec === 'string')
270
323
  spec = JSON.parse(spec);
271
- spec = migrateGraph(spec);
324
+ spec = spec;
272
325
  if (a.mode === 'merge' && ws.graphs.has(name))
273
326
  spec = ws.mergeGraph(name, spec);
274
327
  if (a.dry_run) {
275
- const d = engine.dryRun(spec);
328
+ // a package the graph names for the first time: checked against the version a build adds, nothing copied
329
+ const dry = ws.dryScope(spec);
330
+ const d = engine.dryRun(spec, undefined, dry.scope);
331
+ const first = dry.notes.map((n) => `\nnote: ${n}`).join('');
276
332
  return text(d.errors.length
277
- ? `✗ ${d.errors.length} error(s):\n` + d.errors.map((e) => ` [${e.node}] ${e.message}${e.hint ? `\n hint: ${e.hint}` : ''}`).join('\n')
278
- : `✓ valid: ${Object.keys(spec.nodes).length} nodes, output "${d.output}"` + (d.notes.length ? '\nnotes: ' + d.notes.join('; ') : ''), d.errors.length > 0);
333
+ ? `✗ ${d.errors.length} error(s):\n` + d.errors.map((e) => ` [${e.node}] ${e.message}${e.hint ? `\n hint: ${e.hint}` : ''}`).join('\n') + first
334
+ : `✓ valid: ${Object.keys(spec.nodes).length} nodes, output "${d.output}"` + (d.notes.length ? '\nnotes: ' + d.notes.join('; ') : '') + first, d.errors.length > 0);
279
335
  }
280
- const v = engine.validate(spec);
336
+ // validated as a dry run sees it: a graph that is not saved adds no package and writes nothing
337
+ const v = engine.validate(spec, '', ws.dryScope(spec).scope);
281
338
  if (v.errors.length)
282
339
  return text(`✗ graph not saved — ${v.errors.length} error(s):\n` + v.errors.map((e) => ` [${e.node}] ${e.message}${e.hint ? `\n hint: ${e.hint}` : ''}`).join('\n'), true);
340
+ // packages the graph names for the first time join the package
341
+ const added = ws.packages?.addFor(spec) ?? [];
283
342
  ws.setGraph(name, spec);
284
- return cookAndReport(name, a);
343
+ return cookAndReport(name, a, added);
285
344
  },
286
345
  },
287
346
  {
@@ -313,13 +372,17 @@ export function makeTools(ws, opts = {}) {
313
372
  },
314
373
  {
315
374
  name: 'inspect',
316
- description: 'Inspect any node\'s output as text: summary; detail "attributes" (min/max/mean, unique strings), "topology" (watertight/manifold, pieces, volume, area, genus), "elements" (list values for a range), or "all".',
375
+ description: 'Inspect any node\'s output as text: detail "summary" (default: one screen: counts, triangles, bbox in mm, parts, materials and maps, images, uv state, closed or open edges after welding seam splits); "budget" (triangles per part (prim "name", each an exported mesh) split per LOD (_lodN names), and per node (what each adds), sorted, with totals); "scene" (the glb export read back: nodes and parents, sockets, meshes and triangles, materials and maps, images; export_options as for export); "attributes" (min/max/mean, unique strings), "topology" (a closed solid or why not: open edges counted after welding the vertex splits of uv/normal seams, non-manifold edges, flipped faces, inward pieces, degenerate faces, each with the part (prim name/group) and world position of the first one and the fix; pieces, volume, area, genus, render/export triangle health), "elements" (list values for a range), "all", or "uv" (exact uv overlaps split into in-tile (atlas) overlap, tiling overlap (charts across tile borders: a repeating texture, flagged tiling) and overlap across LODs (_lodN names), each listed with parts and positions; collapsed / non-finite / out-of-tile triangles, charts, utilization, per-piece texel density with resolution; json:true appends the machine-readable report).',
317
376
  inputSchema: {
318
377
  type: 'object',
319
378
  properties: {
320
379
  graph: { type: 'string', description: 'graph name (default "main")' },
321
380
  node: { type: 'string', description: 'node to inspect (default: graph output)' },
322
- detail: { type: 'string', enum: ['summary', 'attributes', 'topology', 'elements', 'all'] },
381
+ detail: { type: 'string', enum: ['summary', 'attributes', 'topology', 'elements', 'all', 'uv', 'budget', 'scene'] },
382
+ export_options: { type: 'object', description: 'detail "scene": export options as the export tool takes them (up_axis, scale, split_by_name, materials, custom_attribs, tangents, instancing, compress …)' },
383
+ uv_attrib: { type: 'string', description: 'detail "uv": the uv attribute (default "uv")' },
384
+ resolution: { description: 'detail "uv": texture size in texels for texel density, n or [width, height]', anyOf: [{ type: 'number' }, { type: 'array', items: { type: 'number' } }] },
385
+ json: { type: 'boolean', description: 'detail "uv", "budget" or "scene": append the report as JSON' },
323
386
  class: { type: 'string', enum: ['point', 'prim', 'vertex', 'detail', 'edge'], description: 'element class; "edge" lists unique edges (point pair, length, polygon count, dihedral angle, edge groups)' },
324
387
  attribs: { type: 'array', items: { type: 'string' } },
325
388
  start: { type: 'number' }, count: { type: 'number' },
@@ -332,7 +395,17 @@ export function makeTools(ws, opts = {}) {
332
395
  const node = r.target;
333
396
  const res = r.results.get(node);
334
397
  const head = `${name}/${node}${atFrame(r)}${res ? ` (${res.cached ? 'cached' : res.ms.toFixed(0) + ' ms'})` : ''}`;
335
- return text(head + '\n' + inspect(geo, { detail: a.detail, cls: a.class, attribs: a.attribs, start: a.start, count: a.count, group: a.group }));
398
+ if (a.detail === 'scene') {
399
+ // the glb export with these options, read back from its bytes (io/inspect-scene.ts)
400
+ const ex = await serializeExport(geo, 'glb', path.join(ws.exportDir, 'scene.glb'), exportToolOptions(a.export_options ?? {}), engine.host);
401
+ const glb = ex.files.find((f) => /\.glb$/i.test(f.path));
402
+ if (!glb)
403
+ return text(`${head}\nscene: the glb export wrote no file`, true);
404
+ const rep = glbSceneReport(glb.bytes);
405
+ return text([head, ...sceneReportText(rep), ...ex.warnings.map((w) => `warning: ${w}`), ...(a.json ? ['scene (JSON):', JSON.stringify(rep)] : [])].join('\n'));
406
+ }
407
+ const nodes = a.detail === 'budget' ? nodeBudgetInput(ws.getGraph(name), r.results) : undefined;
408
+ return text(head + '\n' + inspect(geo, { detail: a.detail, cls: a.class, attribs: a.attribs, start: a.start, count: a.count, group: a.group, uvAttrib: a.uv_attrib, uvResolution: a.resolution, json: a.json, nodes }));
336
409
  },
337
410
  },
338
411
  {
@@ -343,13 +416,13 @@ export function makeTools(ws, opts = {}) {
343
416
  properties: {
344
417
  graph: { type: 'string', description: 'graph name (default "main")' }, node: { type: 'string', description: 'node to look at (default: the graph output)' },
345
418
  ...RENDER_PROPS,
346
- save_to: { type: 'string', description: 'also write the PNG to this path (relative to the workspace)' },
419
+ save_to: { type: 'string', description: 'also write the PNG to this path (relative to the package)' },
347
420
  ...FRAME_PROP,
348
421
  },
349
422
  },
350
423
  run: async (a) => {
351
424
  const { geo, name, r } = await resolveNodeGeo(a);
352
- const { img, notes, png } = pngContent(geo, renderOpts(a, geo, `${name}/${r.target}${atFrame(r)}`));
425
+ const { img, notes, png } = await pngContent(geo, renderOpts(a, geo, `${name}/${r.target}${atFrame(r)}`, ws.dir), engine.host);
353
426
  const content = [img];
354
427
  const info = [];
355
428
  {
@@ -368,7 +441,7 @@ export function makeTools(ws, opts = {}) {
368
441
  },
369
442
  {
370
443
  name: 'export',
371
- description: 'Write a node\'s output to a file: .glb/.gltf (glTF via gltf-transform: materials + texture maps, vertex colours, uv, custom attributes, EXT_mesh_gpu_instancing with per-instance attributes, meshopt compression; best for Unreal/Blender/web), .obj, .usda (PointInstancer with per-instance primvars, UsdPreviewSurface materials), .ply, .stl, .geo (Houdini JSON geometry, every attribute and group, packed prims as PackedGeometry), .csv (point stream; pcg:true for Unreal PCG columns; packed instances = one row per instance + Mesh column + .meshes.json sidecar + one GLB per source), .points.json, .json (lossless topotopo). Relative paths go into the workspace. help {topic:"export"} for details. Heightfields: png16 (.png, 16-bit Unreal Landscape heightmap) or r16 (.r16/.raw) plus a .json sidecar with the height range and the Unreal scale/location, mask_png (8-bit weight layers; param layers), unreal_landscape (a directory: heightmap, every layer, manifest with the exact Landscape import settings, objects.glb and the instance stream). Textures: glb/gltf embed the image textures of materials (texture_to_material) as PNG, usda writes them to <name>_textures/ next to the file, format textures writes every image as <path>/<image>.png (layers: extra layers, or ["*"]).',
444
+ description: 'Write a node\'s output to a file: .glb/.gltf (glTF via gltf-transform: materials + texture maps, vertex colours, uv, custom attributes, EXT_mesh_gpu_instancing with per-instance attributes, meshopt compression; best for Unreal/Blender/web), .obj, .usda (PointInstancer with per-instance primvars, UsdPreviewSurface materials), .ply, .stl, .geo (Houdini JSON geometry, every attribute and group, packed prims as PackedGeometry), .csv (point stream; pcg:true for Unreal PCG columns; packed instances = one row per instance + Mesh column + .meshes.json sidecar + one GLB per source), .points.json, .json (lossless topotopo). Relative paths go into the package. help {topic:"export"} for details. Heightfields: png16 (.png, 16-bit Unreal Landscape heightmap) or r16 (.r16/.raw) plus a .json sidecar with the height range and the Unreal scale/location, mask_png (8-bit weight layers; param layers), unreal_landscape (a directory: heightmap, every layer, manifest with the exact Landscape import settings, objects.glb and the instance stream). Textures: glb/gltf embed the image textures of materials (texture_to_material) as PNG, usda writes them to <name>_textures/ next to the file, format textures writes every image as <path>/<image>.png (layers: extra layers, or ["*"]). Every export records how it was made (graph, vars, seeds, frame, version) in its sidecar or in <file>.source.json next to it (help topic "export").',
372
445
  inputSchema: {
373
446
  type: 'object',
374
447
  properties: {
@@ -386,10 +459,12 @@ export function makeTools(ws, opts = {}) {
386
459
  up_axis: { type: 'string', enum: ['y', 'z'] },
387
460
  scale: { type: 'number', description: 'multiply positions (100 = metres → centimetres; pcg csv defaults to 100)' },
388
461
  split_by_name: { type: 'boolean', description: 'separate meshes per prim "name" (default true)' },
389
- custom_attribs: { type: 'boolean', description: 'glTF/PLY/USD: include extra numeric attributes (glTF _NAME accessors; default true for glTF and PLY, false for USD)' },
462
+ custom_attribs: { type: 'boolean', description: 'glTF/PLY/USD: include extra numeric attributes (glTF _NAME vertex and per-instance accessors, PLY properties, USD primvars; default false for glb/gltf/usda, true for ply). The CLI flag is --custom-attribs / --no-custom-attribs' },
390
463
  materials: { type: 'boolean', description: 'glTF: write materials from the prim "material" attribute + table (default true)' },
464
+ vertex_colors: { type: 'boolean', description: 'glTF: also write Cd as COLOR_0 on prims that have a named material (default false: the material decides their colour; prims without one keep their Cd)' },
391
465
  compress: { type: 'string', enum: ['none', 'meshopt', 'draco'], description: 'glTF: meshopt = EXT_meshopt_compression + quantization; draco needs the optional draco3dgltf package' },
392
466
  quantize: { type: 'boolean', description: 'glTF: KHR_mesh_quantization (smaller, lossy) without compression' },
467
+ tangents: { type: 'string', enum: ['auto', 'preserve', 'none'], description: 'glTF TANGENT: auto (default) = MikkTSpace for normal-mapped materials, a valid supplied "tangent" attribute elsewhere; preserve = the supplied attribute wherever it exists (malformed = error); none = never' },
393
468
  attributes: { type: 'array', items: { type: 'string' }, description: 'csv / points.json: point attributes to write (default all)' },
394
469
  pcg: { type: 'boolean', description: 'csv: Unreal PCG columns (Position/Rotation/Scale/Density/Color/Seed) in Unreal space (Z-up, left-handed, cm)' },
395
470
  pcg_struct: { type: 'boolean', description: 'csv with pcg: Unreal struct-text cells ("(X=…,Y=…,Z=…)") for DataTable import with a row struct' },
@@ -403,19 +478,23 @@ export function makeTools(ws, opts = {}) {
403
478
  run: async (a) => {
404
479
  if (a.path === undefined)
405
480
  return exportTargets(a);
406
- const { geo, name, r } = await resolveNodeGeo(a);
481
+ const { geo, name, r, scope } = await resolveNodeGeo(a, true);
407
482
  const p = path.resolve(ws.dir, a.path);
408
483
  const fmt0 = String(a.format ?? exportFormatFromPath(p)).toLowerCase();
409
484
  const ext = ({ png: 'png16', raw: 'r16' }[fmt0] ?? fmt0);
410
485
  if (!EXPORT_FORMATS.includes(ext))
411
486
  throw new Error(`unknown format "${ext}"; use ${EXPORT_FORMATS.map((f) => (f === 'pointsjson' ? '.points.json' : '.' + f)).join(' ')}`);
412
- const report = await writeExport(geo, ext, p, a, engine.host, (files) => new ArtifactStore(ws.exportDir).record(files, { graph: name, node: r.target, format: ext }));
413
- return text(`${report}\n(from ${name}/${r.target}${atFrame(r)}: ${geo.numPoints} points, ${geo.numPrims} prims)`);
487
+ const source = exportSource({
488
+ graph: name, spec: ws.getGraph(name), node: r.target, frame: r.frame, fps: r.fps,
489
+ format: ext, options: exportToolOptions(a), packages: packagesUsed(engine, ws.getGraph(name), scope ?? engine.root), version: TOPOTOPO_VERSION,
490
+ });
491
+ const report = await writeExport(geo, ext, p, a, engine.host, (files) => new ArtifactStore(ws.exportDir).record(files, { graph: name, node: r.target, format: ext }), source);
492
+ return text(`${report}\n(from ${name}/${r.target}${atFrame(r)}: ${geo.numPoints} points, ${geo.numPrims} prims)${publishedLine(ws.getGraph(name))}`);
414
493
  },
415
494
  },
416
495
  {
417
496
  name: 'graphs',
418
- description: 'Manage workspace graphs: list (with node counts), get (full JSON), delete, rename, duplicate. Graphs persist as JSON files in workspace/graphs.',
497
+ description: 'Manage package graphs: list (with node counts), get (full JSON), delete, rename, duplicate. Graphs persist as JSON files in the package graphs/ folder.',
419
498
  inputSchema: {
420
499
  type: 'object',
421
500
  required: ['action'],
@@ -425,11 +504,11 @@ export function makeTools(ws, opts = {}) {
425
504
  switch (a.action) {
426
505
  case 'list': {
427
506
  if (!ws.graphs.size)
428
- return text(`no graphs yet (workspace ${ws.dir}). Use build.`);
507
+ return text(`no graphs yet (package ${ws.dir}). Use build.`);
429
508
  return text([...ws.graphs].map(([k, g]) => {
430
509
  const r = ws.lastReport.get(k);
431
510
  return `${k}: ${Object.keys(g.nodes).length} nodes, output ${g.output ?? '(auto)'}${r ? `, last cook ${r.ok ? 'ok' : 'FAILED'}${r.geo ? ` (${r.geo.numPoints} pts, ${r.geo.numPrims} prims)` : ''}` : ''}`;
432
- }).join('\n') + `\nworkspace: ${ws.dir}`);
511
+ }).join('\n') + `\nfolder: ${ws.dir}`);
433
512
  }
434
513
  case 'get': return text(JSON.stringify(ws.getGraph(a.name ?? 'main'), null, 1));
435
514
  case 'delete':
@@ -451,77 +530,95 @@ export function makeTools(ws, opts = {}) {
451
530
  },
452
531
  {
453
532
  name: 'assets',
454
- description: 'Reusable custom node types built from graphs (like HDAs). save {name, from_graph | graph, description, params:{var:{desc,min,max}}}: the graph\'s vars become parameters and its "input" nodes become inputs. list, get, delete. The shipped shelf assets (category shelf: stairs, wall_segment, fence, tree_lowpoly …) are read-only; fork {name, to} copies one into a workspace graph to edit, and saving under the same name overrides it.',
533
+ description: 'Reusable custom node types built from graphs (like HDAs), the package\'s own (assets/). save {name, from_graph | graph, description, params:{var:{desc,min,max}}}: the graph\'s vars become parameters and its "input" nodes become inputs. list, get, delete. fork {name: "owner/name/output", to?} copies the graph of a package output, TopoTopo\'s own included ("topotopo/architecture/stairs" …), into the package\'s assets as "to" (default: the output\'s name), an asset to edit and use like any other; get shows its graph, save writes it back.',
455
534
  inputSchema: {
456
535
  type: 'object',
457
536
  required: ['action'],
458
537
  properties: {
459
538
  action: { type: 'string', enum: ['save', 'list', 'get', 'delete', 'fork'] },
460
- name: { type: 'string' }, from_graph: { type: 'string' }, graph: { type: 'object' },
539
+ name: { type: 'string', description: 'the asset; fork: the package output to copy, "owner/name/output" (or "owner/name" for its default output)' },
540
+ from_graph: { type: 'string' }, graph: { type: 'object' },
461
541
  description: { type: 'string' }, params: { type: 'object' },
462
- to: { type: 'string', description: 'fork: name of the workspace graph to create (default: the asset name)' },
542
+ to: { type: 'string', description: 'fork: name of the asset to create (default: the output\'s name)' },
463
543
  },
464
544
  },
465
545
  run: async (a) => {
466
546
  const assetOf = (n) => {
467
- const x = engine.assets.get(n);
547
+ const x = engine.asset(n);
468
548
  if (!x) {
469
- const s = didYouMean(String(n), [...engine.assets.keys()]);
549
+ const s = didYouMean(String(n), engine.assetsIn().map((x) => x.name));
470
550
  throw new Error(`no asset "${n}"${s.length ? ` — did you mean ${s.join(', ')}?` : ''}`);
471
551
  }
472
552
  return x;
473
553
  };
554
+ /**
555
+ * An asset's name and graph checked as a dry run sees the graph, before it adds a package or writes a file:
556
+ * throws as registering it would.
557
+ */
558
+ const validAsset = (n, g) => {
559
+ if (!/^[A-Za-z_][\w]*$/.test(n))
560
+ throw new Error(`asset name must be an identifier, got "${n}"`);
561
+ const v = engine.validate(g, '', ws.dryScope(g).scope);
562
+ if (v.errors.length)
563
+ throw new Error(`asset graph invalid: ${v.errors.map((e) => `${e.node}: ${e.message}`).join('; ')}`);
564
+ };
474
565
  switch (a.action) {
475
566
  case 'list': {
476
- if (!engine.assets.size)
477
- return text('no assets yet');
567
+ const all = engine.assetsIn();
568
+ if (!all.length)
569
+ return text('no assets yet (assets {action:"save"} makes one of a graph; fork copies a package output\'s graph, catalog {category:"package"} lists them)');
478
570
  const line = (x) => ` ${x.name} — ${x.def.summary}; params: ${Object.keys(x.def.params).join(', ') || 'none'}; inputs: ${x.def.inputs.length}`;
479
- const all = [...engine.assets.values()], mine = all.filter((x) => x.def.category !== 'shelf'), shelf = all.filter((x) => x.def.category === 'shelf');
480
- const out = [];
481
- if (mine.length)
482
- out.push(`[asset] workspace assets (${mine.length})`, ...mine.map(line));
483
- if (shelf.length)
484
- out.push(`[shelf] shipped assets (${shelf.length}; read-only, fork to edit)`, ...shelf.map(line));
485
- return text(out.join('\n'));
571
+ return text([`[asset] package assets (${all.length})`, ...all.map(line)].join('\n'));
486
572
  }
487
573
  case 'get': {
488
574
  const x = assetOf(a.name);
489
575
  return text(nodeDoc(x.def) + '\n\n' + JSON.stringify(x.graph, null, 1));
490
576
  }
491
577
  case 'delete': {
492
- const x = assetOf(a.name);
493
- if (x.def.category === 'shelf')
494
- throw new Error(`"${a.name}" is a shelf asset and cannot be deleted; fork it to edit a copy: assets {action:"fork", name:"${a.name}"}`);
495
- engine.assets.delete(a.name);
578
+ assetOf(a.name);
579
+ engine.root.assets.delete(a.name);
496
580
  const f = path.join(ws.assetDir, a.name + '.json');
497
581
  if (fs.existsSync(f))
498
582
  fs.unlinkSync(f);
499
- const shipped = engine.shelf.get(a.name);
500
- if (shipped) {
501
- engine.registerAsset(a.name, shipped, { category: 'shelf' });
502
- engine.cache.clear();
503
- }
504
- return text(`deleted asset "${a.name}"${shipped ? '; restored the shelf asset of that name' : ''}`);
583
+ return text(`deleted asset "${a.name}"`);
505
584
  }
506
585
  case 'fork': {
507
- const x = assetOf(a.name);
508
- const to = a.to ?? a.name;
509
- ws.setGraph(to, structuredClone(x.graph));
510
- ws.bump(to);
511
- return text(`forked ${x.def.category === 'shelf' ? 'shelf ' : ''}asset "${a.name}" into workspace graph "${to}" (its vars are the asset params, its "input" nodes the inputs). ` +
512
- `Edit it with build/edit, then assets {action:"save", name:"${a.name}", from_graph:"${to}"} saves it as a workspace asset that replaces the ${x.def.category === 'shelf' ? 'shelf' : 'current'} one (delete restores it).`);
586
+ const name = String(a.name ?? '');
587
+ if (!name.includes('/'))
588
+ throw new Error(`fork copies a package output's graph into the package's assets: name one, "owner/name/output" (catalog {category:"package"} lists them, TopoTopo's own as "topotopo/architecture/stairs" …)${engine.asset(name) ? `; "${name}" is an asset of the package already: get shows its graph` : ''}`);
589
+ // an output the package uses, or one of TopoTopo's own it does not use yet
590
+ const all = engine.packageDefs(), o = (engine.resolveDef(name) ?? all.find((x) => x.type === name))?.package;
591
+ if (!o) {
592
+ const s = didYouMean(name, all.map((x) => x.type)), p = engine.packageIssue(name);
593
+ throw new Error(s.length ? `no package output "${name}" — did you mean ${s.join(', ')}?` : `${p.error}${p.hint ? ` (hint: ${p.hint})` : ''}`);
594
+ }
595
+ const to = String(a.to ?? o.output ?? o.package.split('/')[1]);
596
+ // the asset cooks the output's node; it publishes nothing and exports nowhere of its own
597
+ const g = { ...structuredClone(o.spec), output: o.node };
598
+ delete g.outputs;
599
+ delete g.export;
600
+ // the package's other outputs its graph names join the package (first use), once it validates
601
+ validAsset(to, g);
602
+ const added = ws.packages?.addFor(g) ?? [];
603
+ const def = engine.registerAsset(to, g);
604
+ fs.writeFileSync(path.join(ws.assetDir, to + '.json'), JSON.stringify(g, null, 2));
605
+ return text(`forked ${name} (${packageAt(o)}) into asset "${to}" of the package (assets/${to}.json; use {"type": "${to}"}): its vars are the params, its "input" nodes the inputs. ` +
606
+ `assets {action:"get", name:"${to}"} shows its graph; change it and write it back with assets {action:"save", name:"${to}", graph}. Relative paths in it now read the package's files.` +
607
+ `${added.map((n) => `\nnote: ${n}`).join('')}\n\n${nodeDoc(def)}`);
513
608
  }
514
609
  case 'save': {
515
610
  if (!a.name)
516
611
  throw new Error('"name" is required');
517
- const g = migrateGraph(structuredClone(a.graph ?? ws.getGraph(a.from_graph ?? 'main')));
612
+ const g = structuredClone(a.graph ?? ws.getGraph(a.from_graph ?? 'main'));
518
613
  if (a.description)
519
614
  g.description = a.description;
520
615
  if (a.params)
521
616
  g.params = { ...(g.params ?? {}), ...a.params };
617
+ validAsset(String(a.name), g);
618
+ const added = ws.packages?.addFor(g) ?? [];
522
619
  const def = engine.registerAsset(a.name, g);
523
620
  fs.writeFileSync(path.join(ws.assetDir, a.name + '.json'), JSON.stringify(g, null, 2));
524
- return text(`saved asset "${a.name}" (use {"type": "${a.name}"})\n\n${nodeDoc(def)}`);
621
+ return text(`saved asset "${a.name}" (use {"type": "${a.name}"})${added.map((n) => `\nnote: ${n}`).join('')}\n\n${nodeDoc(def)}`);
525
622
  }
526
623
  }
527
624
  return text('unknown action', true);
@@ -532,7 +629,7 @@ export function makeTools(ws, opts = {}) {
532
629
  if (opts.onPreview) {
533
630
  tools.push({
534
631
  name: 'preview',
535
- description: 'Start (or get the URL of) the live viewer for humans: an editor viewport of the workspace (graph menu, an outliner with the graph\'s nodes, single and quad views, the graph\'s params as Controls, input layers and guides) that updates after every build/edit. Returns the URL to open in a browser.',
632
+ description: 'Start (or get the URL of) the live viewer for humans: an editor viewport of the package (graph menu, an outliner with the graph\'s nodes, single and quad views, the graph\'s params as Controls, input layers and guides) that updates after every build/edit. Returns the URL to open in a browser.',
536
633
  inputSchema: { type: 'object', properties: {} },
537
634
  run: async () => text(`live preview: ${await opts.onPreview()} (updates automatically on every build/edit; click a node in the outliner to see its result)`),
538
635
  });
@@ -552,6 +649,8 @@ export function makeTools(ws, opts = {}) {
552
649
  for (const t of tools) {
553
650
  const run = t.run;
554
651
  t.run = async (args) => {
652
+ // what changed on disk since the last call (a followed working folder, the manifest): every tool sees it
653
+ ws.packages?.refresh();
555
654
  const result = await run(args);
556
655
  const note = inputsNote(t.name);
557
656
  if (note)