@kruschdev/pascal-plugin-mit-assets 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/ASSETS.md +298 -0
  2. package/LICENSE +21 -0
  3. package/README.md +71 -2
  4. package/dist/agent-operations.d.ts +8 -0
  5. package/dist/agent-operations.js +305 -0
  6. package/dist/agent-tools.d.ts +7 -0
  7. package/dist/agent-tools.js +128 -0
  8. package/dist/audit.d.ts +78 -0
  9. package/dist/bin/pascal-mit-assets.js +5238 -0
  10. package/dist/bom.d.ts +123 -0
  11. package/dist/cad/appliance-mep-builders.d.ts +7 -0
  12. package/dist/cad/furniture-builders.d.ts +9 -0
  13. package/dist/cad/index.d.ts +48 -0
  14. package/dist/cad/index.js +23 -0
  15. package/dist/cad/kitchen-bath-builders.d.ts +9 -0
  16. package/dist/cad/outdoor-fenestration-builders.d.ts +8 -0
  17. package/dist/cad/primitives.d.ts +56 -0
  18. package/dist/cad/props-vehicles-builders.d.ts +8 -0
  19. package/dist/chunk-2qgndrap.js +5200 -0
  20. package/dist/chunk-6hzyh6qv.js +346 -0
  21. package/dist/chunk-f72r2bmp.js +84 -0
  22. package/dist/chunk-hqgm57dv.js +310 -0
  23. package/dist/chunk-kgwk6kan.js +150 -0
  24. package/dist/chunk-raafkn3w.js +286 -0
  25. package/dist/chunk-vzmjt9dz.js +4380 -0
  26. package/dist/chunk-xhkwv6t4.js +5080 -0
  27. package/dist/hdri/index.d.ts +1 -0
  28. package/dist/hdri/index.js +322 -0
  29. package/dist/hdri/sky.d.ts +26 -0
  30. package/dist/index.d.ts +30 -0
  31. package/dist/index.js +198 -0
  32. package/dist/manifest.d.ts +46 -0
  33. package/dist/materials/index.d.ts +10 -0
  34. package/dist/materials/index.js +1464 -0
  35. package/dist/materials/ktx2.d.ts +10 -0
  36. package/dist/materials/noise.d.ts +89 -0
  37. package/dist/materials/patterns.d.ts +15 -0
  38. package/dist/nodes/mit-item.d.ts +76 -0
  39. package/dist/render.d.ts +10 -0
  40. package/dist/render.js +24 -0
  41. package/dist/scripts/build-assets.js +17129 -0
  42. package/dist/sfx/index.d.ts +1 -0
  43. package/dist/sfx/index.js +1223 -0
  44. package/dist/sfx/synth.d.ts +25 -0
  45. package/dist/sku-crosswalk.d.ts +46 -0
  46. package/dist/ui/chat-card.d.ts +7 -0
  47. package/dist/ui/host-panel.d.ts +1 -0
  48. package/dist/ui/inspector-card.d.ts +4 -0
  49. package/dist/ui/schedule-view.d.ts +1 -0
  50. package/package.json +135 -4
  51. package/src/agent-operations.ts +373 -0
  52. package/src/agent-tools.ts +136 -0
  53. package/src/audit.ts +356 -0
  54. package/src/bom.ts +512 -0
  55. package/src/cad/appliance-mep-builders.ts +1336 -0
  56. package/src/cad/furniture-builders.ts +1622 -0
  57. package/src/cad/index.ts +993 -0
  58. package/src/cad/kitchen-bath-builders.ts +1189 -0
  59. package/src/cad/outdoor-fenestration-builders.ts +1499 -0
  60. package/src/cad/primitives.ts +286 -0
  61. package/src/cad/props-vehicles-builders.ts +1065 -0
  62. package/src/hdri/index.ts +5 -0
  63. package/src/hdri/sky.ts +481 -0
  64. package/src/index.ts +127 -0
  65. package/src/manifest.ts +5296 -0
  66. package/src/materials/index.ts +56 -0
  67. package/src/materials/ktx2.ts +138 -0
  68. package/src/materials/noise.ts +417 -0
  69. package/src/materials/patterns.ts +1507 -0
  70. package/src/nodes/mit-item.ts +163 -0
  71. package/src/render.ts +25 -0
  72. package/src/sfx/index.ts +6 -0
  73. package/src/sfx/synth.ts +1495 -0
  74. package/src/sku-crosswalk.ts +3868 -0
  75. package/src/ui/chat-card.tsx +93 -0
  76. package/src/ui/host-panel.tsx +330 -0
  77. package/src/ui/inspector-card.tsx +213 -0
  78. package/src/ui/schedule-view.tsx +188 -0
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Clean-room MIT procedural PCM Float32 DSP audio synthesizer & WAV encoder
3
+ * for all 38 Pascal Editor SFX cues (`MIT_SFX_SPECS`).
4
+ *
5
+ * Purity invariant: ZERO imports from react, three, @pascal-app/*, next, or node:*.
6
+ * Pure deterministic TypeScript math and typed arrays.
7
+ */
8
+ export type SynthesizedSfx = {
9
+ readonly id: string;
10
+ readonly samples: Float32Array;
11
+ readonly sampleRate: number;
12
+ readonly durationSec: number;
13
+ readonly peak: number;
14
+ readonly rms: number;
15
+ };
16
+ export declare const SUPPORTED_SFX_IDS: readonly string[];
17
+ /**
18
+ * Synthesize deterministic mono Float32 PCM samples for any of the 38 MIT SFX cues.
19
+ */
20
+ export declare function synthesizeSfxPcm(cueId: string, sampleRate?: number): SynthesizedSfx;
21
+ /**
22
+ * Encode mono Float32 PCM samples (`[-1, 1]`) into a standard 44-byte header
23
+ * RIFF/WAVE 16-bit signed little-endian PCM byte buffer.
24
+ */
25
+ export declare function encodeWavPcm16(samples: Float32Array, sampleRate: number): Uint8Array;
@@ -0,0 +1,46 @@
1
+ export type MitBomTrade = "fixtures" | "surfaces" | "fenestration" | "electrical" | "plumbing" | "hvac" | "structural" | "outdoor" | "furnishings";
2
+ export type MitSkuPricingSource = "pascal-plugin-catalog" | "mit-assets-crosswalk";
3
+ export type MitItemSkuRecord = {
4
+ readonly slug: string;
5
+ readonly sku: string;
6
+ readonly catalogSku: string | null;
7
+ readonly catalogRecipeId: string | null;
8
+ readonly pascalSkuId: string | null;
9
+ readonly manufacturer: string;
10
+ readonly series: string;
11
+ readonly productName: string;
12
+ readonly trade: MitBomTrade;
13
+ readonly csiDivision: string;
14
+ readonly retailCategory: string;
15
+ readonly retailChannel: string;
16
+ readonly unitOfMeasure: string;
17
+ readonly estUnitPriceUsd: number;
18
+ readonly pricingSource: MitSkuPricingSource;
19
+ };
20
+ export type MitMaterialSkuRecord = {
21
+ readonly materialId: string;
22
+ readonly sku: string;
23
+ readonly catalogSku: string | null;
24
+ readonly catalogRecipeId: string | null;
25
+ readonly pascalSkuId: string | null;
26
+ readonly manufacturer: string;
27
+ readonly series: string;
28
+ readonly productName: string;
29
+ readonly trade: "surfaces";
30
+ readonly csiDivision: string;
31
+ readonly retailCategory: string;
32
+ readonly retailChannel: string;
33
+ readonly unitOfMeasure: string;
34
+ readonly estUnitPriceUsd: number;
35
+ readonly pricingSource: MitSkuPricingSource;
36
+ };
37
+ export declare const MIT_ITEM_SKU_CROSSWALK: Readonly<Record<string, MitItemSkuRecord>>;
38
+ export declare const MIT_MATERIAL_SKU_CROSSWALK: Readonly<Record<string, MitMaterialSkuRecord>>;
39
+ export declare function getMitItemSku(slug: string): MitItemSkuRecord | undefined;
40
+ export declare function getMitMaterialSku(materialId: string): MitMaterialSkuRecord | undefined;
41
+ export declare function getSkuCrosswalkStats(): {
42
+ totalItems: number;
43
+ catalogLinkedItems: number;
44
+ totalMaterials: number;
45
+ catalogLinkedMaterials: number;
46
+ };
@@ -0,0 +1,7 @@
1
+ import type { ChatToolCardProps } from '@pascal-app/editor';
2
+ type MitAssetsChatCardProps = Partial<ChatToolCardProps> & {
3
+ /** Legacy fallback for standalone test callers */
4
+ result?: Record<string, unknown>;
5
+ };
6
+ export default function MitAssetsChatCard({ toolName, output, state, actions, result, }: MitAssetsChatCardProps): import("react").JSX.Element;
7
+ export {};
@@ -0,0 +1 @@
1
+ export default function MitAssetsHostPanel(): import("react").JSX.Element;
@@ -0,0 +1,4 @@
1
+ import type { AnyNode } from '@pascal-app/core';
2
+ export default function MitAssetsInspectorCard({ node }: {
3
+ node?: AnyNode;
4
+ }): import("react").JSX.Element | null;
@@ -0,0 +1 @@
1
+ export default function MitAssetsScheduleView(): import("react").JSX.Element;
package/package.json CHANGED
@@ -1,6 +1,137 @@
1
1
  {
2
2
  "name": "@kruschdev/pascal-plugin-mit-assets",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "100% clean-room MIT asset replacement plugin & static public/ asset pack generator for Pascal Editor (pascalorg/editor#1327): 155 parametric 3D GLB models, 68 procedural PBR material packs (.ktx2 + .webp), 38 synthesized DSP SFX cues (.mp3), and procedural Radiance RGBE sunset HDRI.",
5
+ "author": "kruschdev <kruschdev@users.noreply.github.com>",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/kruschdev/pascal-plugin-mit-assets.git"
10
+ },
11
+ "homepage": "https://github.com/kruschdev/pascal-plugin-mit-assets",
12
+ "bugs": {
13
+ "url": "https://github.com/kruschdev/pascal-plugin-mit-assets/issues"
14
+ },
15
+ "type": "module",
16
+ "main": "./dist/index.js",
17
+ "types": "./dist/index.d.ts",
18
+ "bin": {
19
+ "pascal-mit-assets": "./dist/bin/pascal-mit-assets.js"
20
+ },
21
+ "exports": {
22
+ ".": {
23
+ "types": "./dist/index.d.ts",
24
+ "bun": "./src/index.ts",
25
+ "import": "./dist/index.js",
26
+ "default": "./dist/index.js"
27
+ },
28
+ "./render": {
29
+ "types": "./dist/render.d.ts",
30
+ "bun": "./src/render.ts",
31
+ "import": "./dist/render.js",
32
+ "default": "./dist/render.js"
33
+ },
34
+ "./cad": {
35
+ "types": "./dist/cad/index.d.ts",
36
+ "bun": "./src/cad/index.ts",
37
+ "import": "./dist/cad/index.js",
38
+ "default": "./dist/cad/index.js"
39
+ },
40
+ "./materials": {
41
+ "types": "./dist/materials/index.d.ts",
42
+ "bun": "./src/materials/index.ts",
43
+ "import": "./dist/materials/index.js",
44
+ "default": "./dist/materials/index.js"
45
+ },
46
+ "./sfx": {
47
+ "types": "./dist/sfx/index.d.ts",
48
+ "bun": "./src/sfx/index.ts",
49
+ "import": "./dist/sfx/index.js",
50
+ "default": "./dist/sfx/index.js"
51
+ },
52
+ "./hdri": {
53
+ "types": "./dist/hdri/index.d.ts",
54
+ "bun": "./src/hdri/index.ts",
55
+ "import": "./dist/hdri/index.js",
56
+ "default": "./dist/hdri/index.js"
57
+ },
58
+ "./agent-tools": {
59
+ "types": "./dist/agent-tools.d.ts",
60
+ "bun": "./src/agent-tools.ts",
61
+ "import": "./dist/agent-tools.js",
62
+ "default": "./dist/agent-tools.js"
63
+ },
64
+ "./agent-operations": {
65
+ "types": "./dist/agent-operations.d.ts",
66
+ "bun": "./src/agent-operations.ts",
67
+ "import": "./dist/agent-operations.js",
68
+ "default": "./dist/agent-operations.js"
69
+ },
70
+ "./package.json": "./package.json"
71
+ },
72
+ "files": [
73
+ "dist",
74
+ "src",
75
+ "!src/__tests__",
76
+ "ASSETS.md",
77
+ "README.md",
78
+ "LICENSE"
79
+ ],
80
+ "scripts": {
81
+ "build": "NODE_ENV=production bun scripts/build-dist.ts",
82
+ "check-types": "tsc --noEmit",
83
+ "test": "bun test src",
84
+ "check:render": "bun scripts/check-render-entry.ts",
85
+ "build:assets": "bun scripts/build-assets.ts",
86
+ "verify:assets": "bun scripts/verify-assets.ts",
87
+ "render:x-launch": "bun scripts/render-mit-assets-x-launch-video.ts",
88
+ "check": "bun run check-types && bun test && bun run check:render && bun run build",
89
+ "prepublishOnly": "bun run check"
90
+ },
91
+ "dependencies": {
92
+ "ktx-parse": "^0.7.1",
93
+ "sharp": "^0.34.2"
94
+ },
95
+ "peerDependencies": {
96
+ "@pascal-app/core": ">=1.0.0 <2",
97
+ "@pascal-app/editor": ">=1.0.0 <2",
98
+ "@pascal-app/viewer": ">=1.0.0 <2",
99
+ "react": "^18 || ^19",
100
+ "three": ">=0.185 <1",
101
+ "zod": "^4",
102
+ "zustand": "^5"
103
+ },
104
+ "devDependencies": {
105
+ "@pascal-app/core": "1.1.6",
106
+ "@pascal-app/editor": "1.1.6",
107
+ "@pascal-app/viewer": "1.1.6",
108
+ "@types/blob-stream": "^0.1.33",
109
+ "@types/bun": "^1.3.5",
110
+ "@types/node": "^22.19.12",
111
+ "@types/pdfkit": "^0.17.7",
112
+ "@types/react": "^19.2.2",
113
+ "@types/react-dom": "^19.2.2",
114
+ "@types/three": "^0.187.0",
115
+ "react": "^19.3.1",
116
+ "react-dom": "^19.3.1",
117
+ "sharp": "^0.34.2",
118
+ "three": "^0.187.0",
119
+ "typescript": "^5.9.3",
120
+ "zod": "^4.6.7",
121
+ "zustand": "^5.1.0"
122
+ },
123
+ "keywords": [
124
+ "pascal",
125
+ "pascal-plugin",
126
+ "mit",
127
+ "assets",
128
+ "glb",
129
+ "ktx2",
130
+ "pbr",
131
+ "hdri",
132
+ "sfx",
133
+ "procedural",
134
+ "3d",
135
+ "clean-room"
136
+ ]
137
+ }
@@ -0,0 +1,373 @@
1
+ /**
2
+ * Pure Headless Agent Operations (`@kruschdev/pascal-plugin-mit-assets/agent-operations`).
3
+ * Runs identically in Pascal's MCP server, detached runtime, or live editor tab in a single undo step.
4
+ * Zero React, Three.js, viewer, or editor imports.
5
+ */
6
+
7
+ import type { AnyNode } from '@pascal-app/core'
8
+ import type { AgentContext, AgentOperations, SceneNodes } from '@pascal-app/core/agent-operations'
9
+ import { refuse } from '@pascal-app/core/agent-tools'
10
+ import { auditSceneMitProvenance, getMitAssetInventorySummary, searchMitItems } from './audit'
11
+ import { buildMitAssetsBom, formatMitAssetsBomCsv, toMitAssetsPascalBom } from './bom'
12
+ import { MIT_MATERIAL_SPECS, type MitItemCategory, type MitMaterialCategory, getMitItemSpec } from './manifest'
13
+
14
+ function asRecord(nodes: SceneNodes): Readonly<Record<string, unknown>> {
15
+ return nodes as unknown as Readonly<Record<string, unknown>>
16
+ }
17
+
18
+ function resolveLevelId(
19
+ nodes: Readonly<Record<string, unknown>>,
20
+ requested: unknown,
21
+ ctx?: AgentContext,
22
+ ): string | null {
23
+ if (typeof requested === 'string' && requested.trim()) {
24
+ const id = requested.trim()
25
+ const node = nodes[id] as { type?: string } | undefined
26
+ return node?.type === 'level' ? id : null
27
+ }
28
+ if (ctx?.activeLevelId) {
29
+ const node = nodes[ctx.activeLevelId] as { type?: string } | undefined
30
+ if (node?.type === 'level') return ctx.activeLevelId
31
+ }
32
+ for (const [id, raw] of Object.entries(nodes)) {
33
+ if (raw && typeof raw === 'object' && (raw as { type?: string }).type === 'level') {
34
+ return id
35
+ }
36
+ }
37
+ return null
38
+ }
39
+
40
+ function nextNodeId(prefix: string, nodes: Readonly<Record<string, unknown>>): string {
41
+ let i = 1
42
+ while (Object.hasOwn(nodes, `${prefix}_${i}`)) i += 1
43
+ return `${prefix}_${i}`
44
+ }
45
+
46
+ function finiteRound3(v: unknown): number {
47
+ const n = Number(v)
48
+ return Number.isFinite(n) ? round3(n) : 0
49
+ }
50
+
51
+ function clampBounded(value: unknown, fallback: number, min: number, max: number): number {
52
+ const raw = typeof value === 'number' && Number.isFinite(value) ? value : fallback
53
+ return round3(Math.min(max, Math.max(min, raw)))
54
+ }
55
+
56
+ function round3(n: number): number {
57
+ return Math.round(n * 1000) / 1000
58
+ }
59
+
60
+ export const mitAssetsAgentOperations: AgentOperations = {
61
+ mit_search_items: (_nodes, input: Record<string, unknown>) => {
62
+ const raw = input ?? {}
63
+ const query = typeof raw.query === 'string' ? raw.query : ''
64
+ const category = typeof raw.category === 'string' ? (raw.category as MitItemCategory) : undefined
65
+ const limit =
66
+ typeof raw.limit === 'number' && Number.isFinite(raw.limit)
67
+ ? Math.min(200, Math.max(1, Math.round(raw.limit)))
68
+ : 50
69
+ const results = searchMitItems(query, category, limit)
70
+ return {
71
+ result: {
72
+ count: results.length,
73
+ inventory: getMitAssetInventorySummary(),
74
+ items: results.map((s) => ({
75
+ slug: s.slug,
76
+ catalogId: s.catalogId,
77
+ name: s.name,
78
+ category: s.category,
79
+ dimensions: s.dimensions,
80
+ attachTo: s.attachTo,
81
+ license: 'MIT',
82
+ })),
83
+ },
84
+ }
85
+ },
86
+
87
+ mit_list_materials: (_nodes, input: Record<string, unknown>) => {
88
+ const raw = input ?? {}
89
+ const category =
90
+ typeof raw.category === 'string' ? (raw.category as MitMaterialCategory) : undefined
91
+ const query = typeof raw.query === 'string' ? raw.query.trim().toLowerCase() : ''
92
+ const matches = MIT_MATERIAL_SPECS.filter((m) => {
93
+ if (category && m.category !== category) return false
94
+ if (query && !`${m.id} ${m.category} ${m.pattern}`.toLowerCase().includes(query)) return false
95
+ return true
96
+ })
97
+ return {
98
+ result: {
99
+ count: matches.length,
100
+ materials: matches.map((m) => ({
101
+ id: m.id,
102
+ category: m.category,
103
+ pattern: m.pattern,
104
+ previewColor: m.previewColor,
105
+ ktx2Count: m.ktx2Files.length,
106
+ webpCount: m.webpFiles.length,
107
+ license: 'MIT',
108
+ })),
109
+ },
110
+ }
111
+ },
112
+
113
+ mit_audit_scene: (nodes, input: Record<string, unknown>) => {
114
+ const raw = input ?? {}
115
+ const mitBaseUrl = typeof raw.mitBaseUrl === 'string' ? raw.mitBaseUrl : ''
116
+ const audit = auditSceneMitProvenance(asRecord(nodes), mitBaseUrl)
117
+ return { result: audit as unknown as Record<string, unknown> }
118
+ },
119
+
120
+ mit_place_item: (nodes, input: Record<string, unknown>, ctx) => {
121
+ const raw = input ?? {}
122
+ const nodeMap = asRecord(nodes)
123
+ const slug = typeof raw.slug === 'string' ? raw.slug.trim() : 'sofa'
124
+ const spec = getMitItemSpec(slug)
125
+ if (!spec) {
126
+ refuse(
127
+ 'unknown_mit_slug',
128
+ `Unknown MIT item slug "${slug}". Call mit_search_items to list all 155 supported slugs.`,
129
+ )
130
+ }
131
+ const levelId = resolveLevelId(nodeMap, raw.levelId, ctx)
132
+ if (!levelId) {
133
+ refuse('missing_level', 'No target level found in scene.')
134
+ }
135
+ const pos =
136
+ Array.isArray(raw.position) && raw.position.length === 3
137
+ ? [
138
+ finiteRound3(raw.position[0]),
139
+ finiteRound3(raw.position[1]),
140
+ finiteRound3(raw.position[2]),
141
+ ]
142
+ : [0, 0, 0]
143
+ const rotation = finiteRound3(raw.rotation)
144
+ const widthM = clampBounded(raw.widthM, spec.dimensions[0], 0.04, 20)
145
+ const heightM = clampBounded(raw.heightM, spec.dimensions[1], 0.01, 20)
146
+ const depthM = clampBounded(raw.depthM, spec.dimensions[2], 0.02, 20)
147
+ const accentColor =
148
+ typeof raw.accentColor === 'string' && /^#[0-9a-fA-F]{6}$/.test(raw.accentColor)
149
+ ? raw.accentColor
150
+ : '#5c7285'
151
+
152
+ const id = nextNodeId('mititm', nodeMap)
153
+ const node = {
154
+ object: 'node',
155
+ id,
156
+ type: 'mit-assets:item',
157
+ name: typeof raw.name === 'string' && raw.name.trim() ? raw.name.trim() : spec.name,
158
+ parentId: levelId,
159
+ visible: true,
160
+ metadata: {},
161
+ slug: spec.slug,
162
+ category: spec.category,
163
+ position: pos,
164
+ rotation,
165
+ widthM,
166
+ heightM,
167
+ depthM,
168
+ accentColor,
169
+ quantity: 1,
170
+ license: 'MIT',
171
+ } as unknown as AnyNode
172
+
173
+ return {
174
+ changes: { create: [{ node, parentId: levelId }] },
175
+ result: {
176
+ createdId: id,
177
+ slug: spec.slug,
178
+ name: spec.name,
179
+ dimensions: [widthM, heightM, depthM],
180
+ license: 'MIT',
181
+ },
182
+ }
183
+ },
184
+
185
+ mit_replace_scene_items: (nodes, input: Record<string, unknown>) => {
186
+ const raw = input ?? {}
187
+ const nodeMap = asRecord(nodes)
188
+ const dryRun = Boolean(raw.dryRun)
189
+ const mitBaseUrl = typeof raw.mitBaseUrl === 'string' ? raw.mitBaseUrl : ''
190
+ const audit = auditSceneMitProvenance(nodeMap, mitBaseUrl)
191
+ const replaceable = audit.findings.filter(
192
+ (f) =>
193
+ (f.code === 'EXTERNAL_SUPABASE_ASSET' || f.code === 'BUNDLED_UNLICENSED_ITEM') &&
194
+ f.matchedSlug,
195
+ )
196
+
197
+ if (dryRun || replaceable.length === 0) {
198
+ return {
199
+ result: {
200
+ dryRun,
201
+ convertedCount: 0,
202
+ candidateCount: replaceable.length,
203
+ candidates: replaceable.map((f) => ({
204
+ nodeId: f.nodeId,
205
+ matchedSlug: f.matchedSlug,
206
+ currentUrl: f.currentUrl,
207
+ })),
208
+ },
209
+ }
210
+ }
211
+
212
+ const create: Array<{ node: AnyNode; parentId?: string }> = []
213
+ const update: Array<{ id: string; data: Partial<AnyNode> }> = []
214
+ const del: string[] = []
215
+ const converted: Array<{ oldId: string; newId: string; slug: string }> = []
216
+ const oldToNewId = new Map<string, string>()
217
+ const simulated: Record<string, unknown> = { ...nodeMap }
218
+
219
+ for (const finding of replaceable) {
220
+ const existing = nodeMap[finding.nodeId] as Record<string, unknown> | undefined
221
+ const spec = finding.matchedSlug ? getMitItemSpec(finding.matchedSlug) : undefined
222
+ if (!existing || !spec) continue
223
+ const parentId =
224
+ typeof existing.parentId === 'string' && existing.parentId.length > 0
225
+ ? existing.parentId
226
+ : null
227
+
228
+ const pos =
229
+ Array.isArray(existing.position) && existing.position.length === 3
230
+ ? existing.position.map((v) => finiteRound3(v))
231
+ : [0, 0, 0]
232
+ const rotY =
233
+ Array.isArray(existing.rotation) && existing.rotation.length === 3
234
+ ? finiteRound3(existing.rotation[1])
235
+ : finiteRound3(existing.rotation)
236
+
237
+ const assetObj =
238
+ existing.asset && typeof existing.asset === 'object'
239
+ ? (existing.asset as Record<string, unknown>)
240
+ : null
241
+ const assetDims =
242
+ Array.isArray(assetObj?.dimensions) && assetObj.dimensions.length === 3
243
+ ? assetObj.dimensions.map((v) => Number(v))
244
+ : null
245
+ const existingScale =
246
+ Array.isArray(existing.scale) && existing.scale.length === 3
247
+ ? existing.scale.map((v) =>
248
+ typeof v === 'number' && Number.isFinite(v) && Math.abs(v) > 0 ? Math.abs(v) : 1,
249
+ )
250
+ : [1, 1, 1]
251
+ const baseW = assetDims && Number.isFinite(assetDims[0]) && assetDims[0]! > 0 ? assetDims[0]! : spec.dimensions[0]
252
+ const baseH = assetDims && Number.isFinite(assetDims[1]) && assetDims[1]! > 0 ? assetDims[1]! : spec.dimensions[1]
253
+ const baseD = assetDims && Number.isFinite(assetDims[2]) && assetDims[2]! > 0 ? assetDims[2]! : spec.dimensions[2]
254
+
255
+ const preservedMetadata =
256
+ existing.metadata && typeof existing.metadata === 'object' && !Array.isArray(existing.metadata)
257
+ ? { ...(existing.metadata as Record<string, unknown>) }
258
+ : {}
259
+ const preservedQty =
260
+ typeof existing.quantity === 'number' && Number.isFinite(existing.quantity) && existing.quantity >= 1
261
+ ? Math.min(500, Math.round(existing.quantity))
262
+ : 1
263
+ const preservedPrice =
264
+ typeof existing.unitPriceOverrideUsd === 'number' &&
265
+ Number.isFinite(existing.unitPriceOverrideUsd) &&
266
+ existing.unitPriceOverrideUsd >= 0
267
+ ? existing.unitPriceOverrideUsd
268
+ : undefined
269
+
270
+ const newId = nextNodeId('mititm', simulated)
271
+ simulated[newId] = { id: newId }
272
+ oldToNewId.set(finding.nodeId, newId)
273
+ const newNode = {
274
+ object: 'node',
275
+ id: newId,
276
+ type: 'mit-assets:item',
277
+ name:
278
+ typeof existing.name === 'string' && existing.name.trim() ? existing.name : spec.name,
279
+ parentId,
280
+ visible: existing.visible !== false,
281
+ metadata: preservedMetadata,
282
+ slug: spec.slug,
283
+ category: spec.category,
284
+ position: pos,
285
+ rotation: rotY,
286
+ widthM: clampBounded(baseW * existingScale[0]!, spec.dimensions[0], 0.04, 20),
287
+ heightM: clampBounded(baseH * existingScale[1]!, spec.dimensions[1], 0.01, 20),
288
+ depthM: clampBounded(baseD * existingScale[2]!, spec.dimensions[2], 0.02, 20),
289
+ accentColor: '#5c7285',
290
+ quantity: preservedQty,
291
+ ...(preservedPrice !== undefined ? { unitPriceOverrideUsd: preservedPrice } : {}),
292
+ license: 'MIT',
293
+ } as unknown as AnyNode
294
+
295
+ create.push(parentId !== null ? { node: newNode, parentId } : { node: newNode })
296
+ del.push(finding.nodeId)
297
+ converted.push({ oldId: finding.nodeId, newId, slug: spec.slug })
298
+ }
299
+
300
+ // Reparent any remaining scene nodes whose parentId was replaced, and fix replaced-child parentIds
301
+ for (const entry of create) {
302
+ const n = entry.node as unknown as { parentId: string | null }
303
+ if (n.parentId && oldToNewId.has(n.parentId)) {
304
+ const remapped = oldToNewId.get(n.parentId)!
305
+ n.parentId = remapped
306
+ entry.parentId = remapped
307
+ }
308
+ }
309
+ // Topologically order `create` so any newly created parent precedes its newly created children
310
+ const createdById = new Map(create.map((e) => [String((e.node as { id: string }).id), e]))
311
+ const orderedCreate: Array<{ node: AnyNode; parentId?: string }> = []
312
+ const visited = new Set<string>()
313
+ const visiting = new Set<string>()
314
+ const visit = (id: string) => {
315
+ if (visited.has(id) || visiting.has(id)) return
316
+ const entry = createdById.get(id)
317
+ if (!entry) return
318
+ visiting.add(id)
319
+ const pId = (entry.node as unknown as { parentId: string | null }).parentId
320
+ if (pId && createdById.has(pId)) visit(pId)
321
+ visiting.delete(id)
322
+ visited.add(id)
323
+ orderedCreate.push(entry)
324
+ }
325
+ for (const id of createdById.keys()) visit(id)
326
+
327
+ for (const [childId, rawChild] of Object.entries(nodeMap)) {
328
+ if (oldToNewId.has(childId) || !rawChild || typeof rawChild !== 'object') continue
329
+ const pId = (rawChild as { parentId?: unknown }).parentId
330
+ if (typeof pId === 'string' && oldToNewId.has(pId)) {
331
+ update.push({
332
+ id: childId,
333
+ data: { parentId: oldToNewId.get(pId)! } as Partial<AnyNode>,
334
+ })
335
+ }
336
+ }
337
+
338
+ return {
339
+ ...(converted.length > 0
340
+ ? { changes: { create: orderedCreate, ...(update.length > 0 ? { update } : {}), delete: del } }
341
+ : {}),
342
+ result: {
343
+ dryRun: false,
344
+ convertedCount: converted.length,
345
+ converted,
346
+ },
347
+ }
348
+ },
349
+
350
+ mit_schedule_bom: (nodes, input: Record<string, unknown>) => {
351
+ const raw = input ?? {}
352
+ const markupPct =
353
+ typeof raw.markupPct === 'number' && Number.isFinite(raw.markupPct) ? raw.markupPct : 0
354
+ const salesTaxPct =
355
+ typeof raw.salesTaxPct === 'number' && Number.isFinite(raw.salesTaxPct) ? raw.salesTaxPct : 0
356
+ const includeMappedPascalItems = raw.includeMappedPascalItems !== false
357
+ const includeCsv = raw.includeCsv !== false
358
+ const bom = buildMitAssetsBom(asRecord(nodes), {
359
+ markupPct,
360
+ salesTaxPct,
361
+ includeMappedPascalItems,
362
+ })
363
+ return {
364
+ result: {
365
+ bom,
366
+ pascalBomFragment: toMitAssetsPascalBom(bom),
367
+ ...(includeCsv ? { csv: formatMitAssetsBomCsv(bom) } : {}),
368
+ },
369
+ }
370
+ },
371
+ }
372
+
373
+ export default mitAssetsAgentOperations