@kruschdev/pascal-plugin-furnishings 0.0.0-stage → 0.2.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.
@@ -0,0 +1,851 @@
1
+ /**
2
+ * Pure Headless Agent Operations (`@kruschdev/pascal-plugin-furnishings/agent-operations`).
3
+ * Runs identically in Pascal's MCP server, detached scene runtime, or live editor tab
4
+ * in a single undo step (`DECISIONS.md` E-016 & E-018).
5
+ * Zero React, Three.js, viewer, or editor imports.
6
+ */
7
+
8
+ import type { AnyNode } from '@pascal-app/core'
9
+ import type { AgentContext, AgentOperations, SceneNodes } from '@pascal-app/core/agent-operations'
10
+ import { refuse } from '@pascal-app/core/agent-tools'
11
+ import { type FurnishingAuditResult, auditSceneFurnishings } from './furnishings/audit'
12
+ import { type FurnishingsAutoPopulateOptions, planFurnishingsAutoPopulate } from './furnishings/autopopulate'
13
+ import {
14
+ buildFurnishingElectricalDemand,
15
+ deriveDisplayDimensionsM,
16
+ getFurnishingSpec,
17
+ isSafeAssetBaseUrl,
18
+ searchFurnishingsCatalog,
19
+ } from './furnishings/catalog'
20
+ import {
21
+ type FurnishingsBomResult,
22
+ type FurnishingsSchedule,
23
+ buildFurnishingsBom,
24
+ buildFurnishingsSchedule,
25
+ formatFurnishingsBomCsv,
26
+ formatFurnishingsScheduleCsv,
27
+ } from './furnishings/schedule'
28
+ import {
29
+ type RoomRenderPromptResult,
30
+ type RoomWallElevationProjectionResult,
31
+ type StagingDirectionCandidate,
32
+ type StagingDirectionsDiversityResult,
33
+ compileRoomRenderPrompt,
34
+ evaluateStagingDirectionsDiversity,
35
+ projectRoomWallElevations,
36
+ } from './furnishings/spatial-grounding'
37
+ import {
38
+ type BudgetTier,
39
+ type FurnishingDomain,
40
+ type PlantSeason,
41
+ STYLE_PRESET_PALETTES,
42
+ type SceneNodeLike,
43
+ type StylePreset,
44
+ type Vec2,
45
+ round3,
46
+ } from './furnishings/types'
47
+
48
+ function asRecord(nodes: SceneNodes): Readonly<Record<string, SceneNodeLike>> {
49
+ return nodes as unknown as Readonly<Record<string, SceneNodeLike>>
50
+ }
51
+
52
+ function isPlainInputRecord(value: unknown): value is Record<string, unknown> {
53
+ return Boolean(value && typeof value === 'object' && !Array.isArray(value))
54
+ }
55
+
56
+ function isValidLevelNode(nodes: SceneNodes, id: unknown): id is string {
57
+ if (typeof id !== 'string' || !id) return false
58
+ if (!Object.hasOwn(nodes, id)) return false
59
+ const node = asRecord(nodes)[id]
60
+ return Boolean(node && typeof node === 'object' && node.type === 'level')
61
+ }
62
+
63
+ function resolveLevelId(nodes: SceneNodes, requested: unknown, ctx?: AgentContext): string | null {
64
+ if (requested !== undefined) {
65
+ if (typeof requested !== 'string') return null
66
+ const trimmed = requested.trim()
67
+ if (!trimmed) return null
68
+ return isValidLevelNode(nodes, trimmed) ? trimmed : null
69
+ }
70
+ if (ctx?.activeLevelId && isValidLevelNode(nodes, ctx.activeLevelId)) {
71
+ return ctx.activeLevelId
72
+ }
73
+ for (const n of Object.values(nodes)) {
74
+ if (
75
+ n &&
76
+ typeof n === 'object' &&
77
+ (n as { type?: string }).type === 'level' &&
78
+ typeof (n as { id?: unknown }).id === 'string'
79
+ ) {
80
+ return (n as { id: string }).id
81
+ }
82
+ }
83
+ return null
84
+ }
85
+
86
+ function deterministicId(prefix: string, nodes: SceneNodes): string {
87
+ let idx = 1
88
+ while (Object.hasOwn(nodes, `${prefix}_${idx}`)) idx += 1
89
+ return `${prefix}_${idx}`
90
+ }
91
+
92
+ function sanitizeCustomGlb(raw: unknown): string | undefined {
93
+ if (typeof raw !== 'string') return undefined
94
+ const trimmed = raw.trim()
95
+ if (!trimmed) return undefined
96
+ if (!isSafeAssetBaseUrl(trimmed)) {
97
+ refuse('unsafe_glb_url', `customGlbUrl "${trimmed}" failed safety validation.`)
98
+ }
99
+ return trimmed
100
+ }
101
+
102
+ function finiteCoord(value: unknown, fallback = 0): number {
103
+ return typeof value === 'number' && Number.isFinite(value) ? round3(value) : round3(fallback)
104
+ }
105
+
106
+ function boundedDim(value: unknown, fallback: number, min: number, max: number): number {
107
+ const raw = typeof value === 'number' && Number.isFinite(value) ? value : fallback
108
+ return round3(Math.min(max, Math.max(min, raw)))
109
+ }
110
+
111
+ function boundedQty(value: unknown, max: number): number {
112
+ const raw = typeof value === 'number' && Number.isFinite(value) ? Math.round(value) : 1
113
+ return Math.min(max, Math.max(1, raw))
114
+ }
115
+
116
+ function nonNegNum(value: unknown, fallback: number, max = Number.POSITIVE_INFINITY): number {
117
+ const raw = typeof value === 'number' && Number.isFinite(value) ? value : fallback
118
+ return Math.min(max, Math.max(0, raw))
119
+ }
120
+
121
+ export type FurnishingsOpChanges = {
122
+ create?: Array<{ node: AnyNode; parentId: string }>
123
+ update?: Array<{ id: string; patch: Record<string, unknown> }>
124
+ delete?: string[]
125
+ }
126
+
127
+ export const furnishingsAgentOperations = {
128
+ furnishings_autopopulate: (
129
+ nodes: SceneNodes,
130
+ input: FurnishingsAutoPopulateOptions,
131
+ ctx: AgentContext,
132
+ ): {
133
+ result: {
134
+ summary: string
135
+ counts: ReturnType<typeof planFurnishingsAutoPopulate>['counts']
136
+ audit: FurnishingAuditResult
137
+ }
138
+ changes: FurnishingsOpChanges
139
+ } => {
140
+ if (input !== undefined && !isPlainInputRecord(input)) {
141
+ refuse('invalid_input', 'furnishings_autopopulate input must be an object.')
142
+ }
143
+ const safeInput = (input ?? {}) as FurnishingsAutoPopulateOptions
144
+ const hasExplicitLevel = safeInput.levelId !== undefined
145
+ const levelId = hasExplicitLevel ? resolveLevelId(nodes, safeInput.levelId, ctx) : null
146
+ if (hasExplicitLevel && !levelId) {
147
+ refuse('level_not_found', `Level "${String(safeInput.levelId)}" was not found in the scene.`)
148
+ }
149
+ const plan = planFurnishingsAutoPopulate(asRecord(nodes), {
150
+ ...safeInput,
151
+ ...(levelId ? { levelId } : {}),
152
+ })
153
+ if (plan.create.length === 0) {
154
+ refuse('level_not_found', 'No building level found in scene to stage furnishings.')
155
+ }
156
+
157
+ const preview: Record<string, SceneNodeLike> = { ...asRecord(nodes) }
158
+ for (const delId of plan.deleteIds) delete preview[delId]
159
+ for (const item of plan.create) {
160
+ const n = item.node as SceneNodeLike
161
+ preview[n.id] = n
162
+ }
163
+ const audit = auditSceneFurnishings(preview)
164
+
165
+ return {
166
+ result: {
167
+ summary: plan.summary,
168
+ counts: plan.counts,
169
+ audit,
170
+ },
171
+ changes: {
172
+ delete: [...plan.deleteIds],
173
+ create: plan.create.map((c) => ({ node: c.node as unknown as AnyNode, parentId: c.parentId })),
174
+ },
175
+ }
176
+ },
177
+
178
+ furnishings_search_catalog: (
179
+ _nodes: SceneNodes,
180
+ input: {
181
+ query?: string
182
+ domain?: FurnishingDomain
183
+ outdoorOnly?: boolean
184
+ indoorOnly?: boolean
185
+ limit?: number
186
+ },
187
+ _ctx?: AgentContext,
188
+ ) => {
189
+ const items = searchFurnishingsCatalog({
190
+ query: input.query,
191
+ domain: input.domain,
192
+ outdoorOnly: input.outdoorOnly,
193
+ indoorOnly: input.indoorOnly,
194
+ limit: input.limit,
195
+ })
196
+ return {
197
+ result: {
198
+ count: items.length,
199
+ items: items.map((it) => ({
200
+ kind: it.kind,
201
+ nodeType: it.nodeType,
202
+ domain: it.domain,
203
+ label: it.label,
204
+ csiDivision: it.csiDivision,
205
+ dimensionsM: [it.widthM, it.depthM, it.heightM],
206
+ estUnitPriceUsd: it.estUnitPriceUsd,
207
+ wattageW: it.wattageW,
208
+ species: it.defaultSpecies,
209
+ })),
210
+ },
211
+ }
212
+ },
213
+
214
+ furnishings_place_item: (
215
+ nodes: SceneNodes,
216
+ input: Record<string, unknown>,
217
+ ctx: AgentContext,
218
+ ): {
219
+ result: { nodeId: string; itemKind: string; name: string; roomName: string; levelId: string }
220
+ changes: FurnishingsOpChanges
221
+ } => {
222
+ const levelId = resolveLevelId(nodes, input.levelId as string | undefined, ctx)
223
+ if (!levelId) refuse('level_not_found', 'No building level found in scene to place furniture item.')
224
+ const itemKind = String(input.itemKind ?? 'sofa-3seat')
225
+ const spec = getFurnishingSpec(itemKind)
226
+ if (!spec || spec.nodeType !== 'furnishings:item') {
227
+ refuse(
228
+ 'invalid_item_kind',
229
+ `Item kind "${itemKind}" is not a valid furniture/decor/patio item. Use furnishings_place_electronics for TVs/speakers/computers or furnishings_place_plant for trees/bushes/plants.`,
230
+ )
231
+ }
232
+ const hasExplicitStyle =
233
+ typeof input.stylePreset === 'string' && Object.hasOwn(STYLE_PRESET_PALETTES, input.stylePreset)
234
+ const stylePreset = (hasExplicitStyle ? String(input.stylePreset) : 'mid-century') as StylePreset
235
+ const palette = STYLE_PRESET_PALETTES[stylePreset]
236
+ const defaultMetalFinish =
237
+ spec.kind === 'vent-grate-floor-brass' && !hasExplicitStyle ? 'brushed-brass' : palette.metalFinish
238
+ const customGlbUrl = sanitizeCustomGlb(input.customGlbUrl)
239
+ const id = deterministicId('frnitm', nodes)
240
+ const roomName = String(input.roomName ?? 'Living Room')
241
+ const name = typeof input.name === 'string' && input.name.trim() ? input.name.trim() : spec.label
242
+ const pos = Array.isArray(input.position) ? input.position : [0, spec.defaultElevationM, 0]
243
+
244
+ const posX = finiteCoord(pos[0], 0)
245
+ const posY = finiteCoord(pos[1], spec.defaultElevationM)
246
+ const posZ = finiteCoord(pos[2], 0)
247
+ const qty = boundedQty(input.quantity, 200)
248
+ const electricalDemand = buildFurnishingElectricalDemand(spec, {
249
+ wattageW: Math.max(0, spec.wattageW) * qty,
250
+ elevationM: posY,
251
+ })
252
+
253
+ const node = {
254
+ object: 'node',
255
+ id,
256
+ type: 'furnishings:item',
257
+ name,
258
+ parentId: levelId,
259
+ visible: true,
260
+ metadata: {},
261
+ itemKind: spec.kind,
262
+ position: [posX, posY, posZ],
263
+ rotation: finiteCoord(input.rotation, 0),
264
+ roomName,
265
+ stylePreset,
266
+ woodFinish: input.woodFinish ?? palette.woodFinish,
267
+ fabricFinish: input.fabricFinish ?? palette.fabricFinish,
268
+ metalFinish: input.metalFinish ?? defaultMetalFinish,
269
+ widthM: boundedDim(input.widthM, spec.widthM, 0.15, 10),
270
+ depthM: boundedDim(input.depthM, spec.depthM, 0.03, 10),
271
+ heightM: boundedDim(input.heightM, spec.heightM, 0.01, 6),
272
+ quantity: qty,
273
+ ...(electricalDemand ? { electricalDemand } : {}),
274
+ ...(typeof input.unitPriceOverrideUsd === 'number' &&
275
+ Number.isFinite(input.unitPriceOverrideUsd) &&
276
+ input.unitPriceOverrideUsd >= 0
277
+ ? { unitPriceOverrideUsd: input.unitPriceOverrideUsd }
278
+ : {}),
279
+ ...(typeof input.customSku === 'string' && input.customSku.trim() ? { customSku: input.customSku.trim() } : {}),
280
+ ...(typeof input.customBrand === 'string' && input.customBrand.trim() ? { customBrand: input.customBrand.trim() } : {}),
281
+ ...(customGlbUrl ? { customGlbUrl } : {}),
282
+ notes: typeof input.notes === 'string' ? input.notes : '',
283
+ } as unknown as AnyNode
284
+
285
+ return {
286
+ result: { nodeId: id, itemKind: spec.kind, name, roomName, levelId },
287
+ changes: { create: [{ node, parentId: levelId }] },
288
+ }
289
+ },
290
+
291
+ furnishings_place_electronics: (
292
+ nodes: SceneNodes,
293
+ input: Record<string, unknown>,
294
+ ctx: AgentContext,
295
+ ): {
296
+ result: { nodeId: string; itemKind: string; name: string; wattageW: number; roomName: string; levelId: string }
297
+ changes: FurnishingsOpChanges
298
+ } => {
299
+ const levelId = resolveLevelId(nodes, input.levelId as string | undefined, ctx)
300
+ if (!levelId) refuse('level_not_found', 'No building level found in scene to place electronics.')
301
+ const itemKind = String(input.itemKind ?? 'tv-oled-wall')
302
+ const spec = getFurnishingSpec(itemKind)
303
+ if (!spec || spec.nodeType !== 'furnishings:electronics') {
304
+ refuse('invalid_electronics_kind', `"${itemKind}" is not a valid electronics/AV/computer kind.`)
305
+ }
306
+ const customGlbUrl = sanitizeCustomGlb(input.customGlbUrl)
307
+ const id = deterministicId('frnav', nodes)
308
+ const roomName = String(input.roomName ?? 'Living Room')
309
+ const name = typeof input.name === 'string' && input.name.trim() ? input.name.trim() : spec.label
310
+ const pos = Array.isArray(input.position) ? input.position : [0, spec.defaultElevationM, 0]
311
+ const wattageW = nonNegNum(input.wattageW, spec.wattageW, 4000)
312
+ const qty = boundedQty(input.quantity, 100)
313
+
314
+ const posX = finiteCoord(pos[0], 0)
315
+ const posY = finiteCoord(pos[1], spec.defaultElevationM)
316
+ const posZ = finiteCoord(pos[2], 0)
317
+ const electricalDemand = buildFurnishingElectricalDemand(spec, {
318
+ wattageW: wattageW * qty,
319
+ elevationM: posY,
320
+ })
321
+
322
+ const rawScreenDiag =
323
+ typeof input.screenDiagonalIn === 'number' && Number.isFinite(input.screenDiagonalIn)
324
+ ? Math.min(150, Math.max(13, input.screenDiagonalIn))
325
+ : spec.defaultScreenDiagonalIn
326
+ const derivedDims = deriveDisplayDimensionsM(spec.kind, rawScreenDiag)
327
+ const resolvedScreenDiag = derivedDims ? rawScreenDiag : undefined
328
+ const defaultW = derivedDims?.widthM ?? spec.widthM
329
+ const defaultH = derivedDims?.heightM ?? spec.heightM
330
+
331
+ const node = {
332
+ object: 'node',
333
+ id,
334
+ type: 'furnishings:electronics',
335
+ name,
336
+ parentId: levelId,
337
+ visible: true,
338
+ metadata: {},
339
+ itemKind: spec.kind,
340
+ position: [posX, posY, posZ],
341
+ rotation: finiteCoord(input.rotation, 0),
342
+ roomName,
343
+ ...(resolvedScreenDiag !== undefined ? { screenDiagonalIn: resolvedScreenDiag } : {}),
344
+ mountStyle: input.mountStyle ?? spec.defaultMountStyle ?? 'stand',
345
+ finish: input.finish ?? 'matte-black',
346
+ widthM: boundedDim(input.widthM, defaultW, 0.12, 5),
347
+ depthM: boundedDim(input.depthM, spec.depthM, 0.03, 2),
348
+ heightM: boundedDim(input.heightM, defaultH, 0.05, 3),
349
+ wattageW,
350
+ channelRole: input.channelRole ?? spec.defaultChannelRole ?? 'aux',
351
+ screenState: input.screenState ?? 'ambient',
352
+ quantity: qty,
353
+ ...(electricalDemand ? { electricalDemand } : {}),
354
+ ...(typeof input.unitPriceOverrideUsd === 'number' &&
355
+ Number.isFinite(input.unitPriceOverrideUsd) &&
356
+ input.unitPriceOverrideUsd >= 0
357
+ ? { unitPriceOverrideUsd: input.unitPriceOverrideUsd }
358
+ : {}),
359
+ ...(typeof input.customSku === 'string' && input.customSku.trim() ? { customSku: input.customSku.trim() } : {}),
360
+ ...(typeof input.customBrand === 'string' && input.customBrand.trim() ? { customBrand: input.customBrand.trim() } : {}),
361
+ ...(customGlbUrl ? { customGlbUrl } : {}),
362
+ notes: typeof input.notes === 'string' ? input.notes : '',
363
+ } as unknown as AnyNode
364
+
365
+ return {
366
+ result: { nodeId: id, itemKind: spec.kind, name, wattageW, roomName, levelId },
367
+ changes: { create: [{ node, parentId: levelId }] },
368
+ }
369
+ },
370
+
371
+ furnishings_place_plant: (
372
+ nodes: SceneNodes,
373
+ input: Record<string, unknown>,
374
+ ctx: AgentContext,
375
+ ): {
376
+ result: { nodeId: string; plantKind: string; name: string; species: string; zoneName: string; levelId: string }
377
+ changes: FurnishingsOpChanges
378
+ } => {
379
+ const levelId = resolveLevelId(nodes, input.levelId as string | undefined, ctx)
380
+ if (!levelId) refuse('level_not_found', 'No building level found in scene to place plant/tree.')
381
+ const plantKind = String(input.plantKind ?? 'tree-oak-deciduous')
382
+ const spec = getFurnishingSpec(plantKind)
383
+ if (!spec || spec.nodeType !== 'furnishings:plant') {
384
+ refuse('invalid_plant_kind', `"${plantKind}" is not a valid tree, bush, hedge, or houseplant kind.`)
385
+ }
386
+ const customGlbUrl = sanitizeCustomGlb(input.customGlbUrl)
387
+ const id = deterministicId('frnplt', nodes)
388
+ const zoneName = String(input.zoneName ?? (spec.indoorOnly ? 'Living Room' : 'Yard'))
389
+ const name = typeof input.name === 'string' && input.name.trim() ? input.name.trim() : spec.label
390
+ const species =
391
+ typeof input.species === 'string' && input.species.trim()
392
+ ? input.species.trim()
393
+ : (spec.defaultSpecies ?? spec.label)
394
+ const pos = Array.isArray(input.position) ? input.position : [0, spec.defaultElevationM, 0]
395
+ const qty = boundedQty(input.quantity, 200)
396
+ const seed =
397
+ typeof input.seed === 'number' && Number.isFinite(input.seed)
398
+ ? Math.min(999999, Math.max(1, Math.round(input.seed)))
399
+ : 42
400
+
401
+ const node = {
402
+ object: 'node',
403
+ id,
404
+ type: 'furnishings:plant',
405
+ name,
406
+ parentId: levelId,
407
+ visible: true,
408
+ metadata: {},
409
+ plantKind: spec.kind,
410
+ position: [finiteCoord(pos[0], 0), finiteCoord(pos[1], spec.defaultElevationM), finiteCoord(pos[2], 0)],
411
+ rotation: finiteCoord(input.rotation, 0),
412
+ zoneName,
413
+ placement: input.placement ?? spec.defaultPlacement ?? 'in-ground',
414
+ species,
415
+ maturity: input.maturity ?? 'mature',
416
+ season: input.season ?? 'summer',
417
+ potStyle: input.potStyle ?? spec.defaultPotStyle ?? 'none',
418
+ heightM: boundedDim(input.heightM, spec.heightM, 0.2, 25),
419
+ canopyRadiusM: boundedDim(input.canopyRadiusM, spec.widthM / 2, 0.12, 12),
420
+ seed,
421
+ quantity: qty,
422
+ ...(typeof input.unitPriceOverrideUsd === 'number' &&
423
+ Number.isFinite(input.unitPriceOverrideUsd) &&
424
+ input.unitPriceOverrideUsd >= 0
425
+ ? { unitPriceOverrideUsd: input.unitPriceOverrideUsd }
426
+ : {}),
427
+ ...(typeof input.customSku === 'string' && input.customSku.trim() ? { customSku: input.customSku.trim() } : {}),
428
+ ...(typeof input.customBrand === 'string' && input.customBrand.trim() ? { customBrand: input.customBrand.trim() } : {}),
429
+ ...(customGlbUrl ? { customGlbUrl } : {}),
430
+ notes: typeof input.notes === 'string' ? input.notes : '',
431
+ } as unknown as AnyNode
432
+
433
+ return {
434
+ result: { nodeId: id, plantKind: spec.kind, name, species, zoneName, levelId },
435
+ changes: { create: [{ node, parentId: levelId }] },
436
+ }
437
+ },
438
+
439
+ furnishings_swap_item: (
440
+ nodes: SceneNodes,
441
+ input: Record<string, unknown>,
442
+ _ctx?: AgentContext,
443
+ ): {
444
+ result: { nodeId: string; nodeType: string; updatedFields: string[] }
445
+ changes: FurnishingsOpChanges
446
+ } => {
447
+ const nodeId = String(input.nodeId ?? '')
448
+ const existing = Object.hasOwn(nodes, nodeId) ? asRecord(nodes)[nodeId] : undefined
449
+ if (!existing) {
450
+ refuse('node_not_found', `Node "${nodeId}" was not found in the scene.`)
451
+ }
452
+ if (
453
+ existing.type !== 'furnishings:item' &&
454
+ existing.type !== 'furnishings:electronics' &&
455
+ existing.type !== 'furnishings:plant'
456
+ ) {
457
+ refuse('unsupported_node_type', `Node "${nodeId}" (${existing.type}) is not a furnishings node.`)
458
+ }
459
+
460
+ const patch: Record<string, unknown> = {}
461
+ const suppliedGlbUrl = sanitizeCustomGlb(input.customGlbUrl)
462
+ const suppliedSku = typeof input.customSku === 'string' && input.customSku.trim() ? input.customSku.trim() : undefined
463
+ const suppliedBrand = typeof input.customBrand === 'string' && input.customBrand.trim() ? input.customBrand.trim() : undefined
464
+ const existingPosY =
465
+ Array.isArray(existing.position) && typeof existing.position[1] === 'number' && Number.isFinite(existing.position[1])
466
+ ? existing.position[1]
467
+ : undefined
468
+ const maxQty = existing.type === 'furnishings:electronics' ? 100 : 200
469
+ const hasExplicitQty = typeof input.quantity === 'number' && Number.isFinite(input.quantity)
470
+ const effectiveQty = hasExplicitQty ? boundedQty(input.quantity, maxQty) : boundedQty(existing.quantity, maxQty)
471
+ if (hasExplicitQty) {
472
+ patch.quantity = effectiveQty
473
+ }
474
+ const hasExplicitWattage = typeof input.wattageW === 'number' && Number.isFinite(input.wattageW)
475
+ const isKindSwap = typeof input.newKind === 'string' && Boolean(input.newKind.trim())
476
+
477
+ if (isKindSwap) {
478
+ const targetSpec = getFurnishingSpec(String(input.newKind).trim())
479
+ if (!targetSpec || targetSpec.nodeType !== existing.type) {
480
+ refuse(
481
+ 'incompatible_swap_kind',
482
+ `Cannot swap ${existing.type} to "${input.newKind}": incompatible or unknown catalog kind.`,
483
+ )
484
+ }
485
+ const oldSpec = getFurnishingSpec(String(existing.itemKind ?? existing.plantKind ?? ''))
486
+ const surfaceOf = (
487
+ s: { isCeilingMounted?: boolean; isWallMounted?: boolean; isDeskTopItem?: boolean; isFloorCovering?: boolean } | undefined,
488
+ ): string =>
489
+ s?.isCeilingMounted
490
+ ? 'ceiling'
491
+ : s?.isWallMounted
492
+ ? 'wall'
493
+ : s?.isDeskTopItem
494
+ ? 'desk'
495
+ : s?.isFloorCovering
496
+ ? 'floor-covering'
497
+ : 'floor'
498
+ const surfaceChanged =
499
+ oldSpec !== undefined &&
500
+ (surfaceOf(oldSpec) !== surfaceOf(targetSpec) ||
501
+ (oldSpec.defaultElevationM !== targetSpec.defaultElevationM &&
502
+ existingPosY !== undefined &&
503
+ Math.abs(existingPosY - oldSpec.defaultElevationM) < 0.02))
504
+ if (surfaceChanged && Array.isArray(existing.position)) {
505
+ patch.position = [
506
+ finiteCoord(existing.position[0], 0),
507
+ round3(targetSpec.defaultElevationM),
508
+ finiteCoord(existing.position[2], 0),
509
+ ]
510
+ }
511
+ patch.name = targetSpec.label
512
+ // Clear stale price override & custom asset/brand/SKU overrides on kind swap unless explicitly supplied
513
+ patch.unitPriceOverrideUsd =
514
+ typeof input.unitPriceOverrideUsd === 'number' &&
515
+ Number.isFinite(input.unitPriceOverrideUsd) &&
516
+ input.unitPriceOverrideUsd >= 0
517
+ ? input.unitPriceOverrideUsd
518
+ : undefined
519
+ patch.customGlbUrl = suppliedGlbUrl ?? undefined
520
+ patch.customSku = suppliedSku ?? undefined
521
+ patch.customBrand = suppliedBrand ?? undefined
522
+
523
+ if (existing.type === 'furnishings:plant') {
524
+ patch.plantKind = targetSpec.kind
525
+ patch.species = targetSpec.defaultSpecies ?? targetSpec.label
526
+ patch.heightM = targetSpec.heightM
527
+ patch.canopyRadiusM = round3(targetSpec.widthM / 2)
528
+ patch.placement = targetSpec.defaultPlacement ?? 'in-ground'
529
+ patch.potStyle = input.potStyle ?? targetSpec.defaultPotStyle ?? 'none'
530
+ } else if (existing.type === 'furnishings:electronics') {
531
+ const unitWattageW = hasExplicitWattage
532
+ ? nonNegNum(input.wattageW, targetSpec.wattageW, 4000)
533
+ : Math.max(0, targetSpec.wattageW)
534
+ patch.itemKind = targetSpec.kind
535
+ patch.widthM = targetSpec.widthM
536
+ patch.depthM = targetSpec.depthM
537
+ patch.heightM = targetSpec.heightM
538
+ patch.wattageW = unitWattageW
539
+ patch.mountStyle = targetSpec.defaultMountStyle ?? 'stand'
540
+ patch.channelRole = targetSpec.defaultChannelRole ?? 'aux'
541
+ patch.screenDiagonalIn = targetSpec.defaultScreenDiagonalIn ?? undefined
542
+ } else {
543
+ patch.itemKind = targetSpec.kind
544
+ patch.widthM = targetSpec.widthM
545
+ patch.depthM = targetSpec.depthM
546
+ patch.heightM = targetSpec.heightM
547
+ patch.wattageW = hasExplicitWattage ? nonNegNum(input.wattageW, targetSpec.wattageW, 4000) : undefined
548
+ }
549
+ } else if (hasExplicitWattage && existing.type !== 'furnishings:plant') {
550
+ patch.wattageW = nonNegNum(input.wattageW, 0, 4000)
551
+ }
552
+
553
+ // Apply live finish / season / screen overrides
554
+ if (existing.type === 'furnishings:item') {
555
+ if (input.woodFinish) patch.woodFinish = input.woodFinish
556
+ if (input.fabricFinish) patch.fabricFinish = input.fabricFinish
557
+ if (input.metalFinish) patch.metalFinish = input.metalFinish
558
+ } else if (existing.type === 'furnishings:electronics') {
559
+ if (input.electronicsFinish) patch.finish = input.electronicsFinish
560
+ if (typeof input.screenDiagonalIn === 'number' && Number.isFinite(input.screenDiagonalIn)) {
561
+ const clampedDiag = Math.min(150, Math.max(13, input.screenDiagonalIn))
562
+ const effectiveKind = typeof patch.itemKind === 'string' ? patch.itemKind : String(existing.itemKind ?? '')
563
+ const derivedDims = deriveDisplayDimensionsM(effectiveKind, clampedDiag)
564
+ if (derivedDims) {
565
+ patch.screenDiagonalIn = clampedDiag
566
+ patch.widthM = derivedDims.widthM
567
+ patch.heightM = derivedDims.heightM
568
+ }
569
+ }
570
+ if (input.screenState) patch.screenState = input.screenState
571
+ } else if (existing.type === 'furnishings:plant') {
572
+ if (input.maturity) patch.maturity = input.maturity
573
+ if (input.season) patch.season = input.season
574
+ if (input.potStyle) patch.potStyle = input.potStyle
575
+ }
576
+
577
+ // Always refresh electricalDemand on item/electronics nodes so wattageW, quantity, or kind updates stay synchronized
578
+ if (existing.type === 'furnishings:item' || existing.type === 'furnishings:electronics') {
579
+ const effectiveKind = typeof patch.itemKind === 'string' ? patch.itemKind : String(existing.itemKind ?? '')
580
+ const effectiveSpec = getFurnishingSpec(effectiveKind)
581
+ const effectivePosY = Array.isArray(patch.position)
582
+ ? (patch.position as number[])[1]!
583
+ : (existingPosY ?? effectiveSpec?.defaultElevationM ?? 0)
584
+ const effectiveUnitWattageW =
585
+ typeof patch.wattageW === 'number'
586
+ ? patch.wattageW
587
+ : isKindSwap
588
+ ? Math.max(0, effectiveSpec?.wattageW ?? 0)
589
+ : typeof existing.wattageW === 'number' && Number.isFinite(existing.wattageW)
590
+ ? Math.max(0, existing.wattageW)
591
+ : Math.max(0, effectiveSpec?.wattageW ?? 0)
592
+ patch.electricalDemand = effectiveSpec
593
+ ? (buildFurnishingElectricalDemand(effectiveSpec, {
594
+ wattageW: effectiveUnitWattageW * effectiveQty,
595
+ elevationM: effectivePosY,
596
+ }) ?? undefined)
597
+ : undefined
598
+ }
599
+
600
+ if (
601
+ !('unitPriceOverrideUsd' in patch) &&
602
+ typeof input.unitPriceOverrideUsd === 'number' &&
603
+ Number.isFinite(input.unitPriceOverrideUsd) &&
604
+ input.unitPriceOverrideUsd >= 0
605
+ ) {
606
+ patch.unitPriceOverrideUsd = input.unitPriceOverrideUsd
607
+ }
608
+ if (!('customGlbUrl' in patch) && suppliedGlbUrl !== undefined) patch.customGlbUrl = suppliedGlbUrl
609
+ if (!('customSku' in patch) && suppliedSku !== undefined) patch.customSku = suppliedSku
610
+ if (!('customBrand' in patch) && suppliedBrand !== undefined) patch.customBrand = suppliedBrand
611
+
612
+ return {
613
+ result: {
614
+ nodeId,
615
+ nodeType: existing.type,
616
+ updatedFields: Object.keys(patch),
617
+ },
618
+ changes: {
619
+ update: [{ id: nodeId, patch }],
620
+ },
621
+ }
622
+ },
623
+
624
+ furnishings_audit_layout: (
625
+ nodes: SceneNodes,
626
+ _input: Record<string, unknown>,
627
+ _ctx?: AgentContext,
628
+ ): { result: FurnishingAuditResult } => {
629
+ return {
630
+ result: auditSceneFurnishings(asRecord(nodes)),
631
+ }
632
+ },
633
+
634
+ furnishings_generate_schedule: (
635
+ nodes: SceneNodes,
636
+ input: {
637
+ markupPct?: number
638
+ salesTaxPct?: number
639
+ budgetTier?: BudgetTier
640
+ stylePreset?: StylePreset
641
+ season?: PlantSeason
642
+ },
643
+ _ctx?: AgentContext,
644
+ ): {
645
+ result: {
646
+ schedule: FurnishingsSchedule
647
+ bom: FurnishingsBomResult
648
+ scheduleCsv: string
649
+ bomCsv: string
650
+ }
651
+ } => {
652
+ const rec = asRecord(nodes)
653
+ const schedule = buildFurnishingsSchedule(rec, {
654
+ budgetTier: input.budgetTier,
655
+ stylePreset: input.stylePreset,
656
+ season: input.season,
657
+ })
658
+ const bom = buildFurnishingsBom(rec, {
659
+ markupPct: input.markupPct,
660
+ salesTaxPct: input.salesTaxPct,
661
+ budgetTier: input.budgetTier,
662
+ schedule,
663
+ })
664
+ return {
665
+ result: {
666
+ schedule,
667
+ bom,
668
+ scheduleCsv: formatFurnishingsScheduleCsv(schedule),
669
+ bomCsv: formatFurnishingsBomCsv(bom),
670
+ },
671
+ }
672
+ },
673
+
674
+ furnishings_compile_render_prompt: (
675
+ nodes: SceneNodes,
676
+ input: {
677
+ roomIdOrName?: string
678
+ levelId?: string
679
+ viewId?: string
680
+ fromXz?: Vec2
681
+ lookAtXz?: Vec2
682
+ camera?: string
683
+ scene?: string
684
+ mustAppear?: readonly string[]
685
+ shellNotes?: readonly string[]
686
+ includeStagedItemsInMustAppear?: boolean
687
+ },
688
+ ctx?: AgentContext,
689
+ ): {
690
+ result: {
691
+ summary: string
692
+ renderPrompt: RoomRenderPromptResult
693
+ elevations: RoomWallElevationProjectionResult
694
+ }
695
+ } => {
696
+ if (input !== undefined && !isPlainInputRecord(input)) {
697
+ refuse('invalid_camera_view', 'furnishings_compile_render_prompt input must be a plain object.')
698
+ }
699
+ const raw = (input ?? {}) as Record<string, unknown>
700
+ const rec = asRecord(nodes)
701
+
702
+ let roomQuery = 'Living Room'
703
+ if (raw.roomIdOrName !== undefined) {
704
+ if (typeof raw.roomIdOrName !== 'string' || !raw.roomIdOrName.trim()) {
705
+ refuse('room_not_found', 'roomIdOrName must be a non-empty string when provided.')
706
+ }
707
+ roomQuery = raw.roomIdOrName.trim()
708
+ }
709
+
710
+ const hasExplicitLevel = raw.levelId !== undefined
711
+ const levelId = hasExplicitLevel ? resolveLevelId(nodes, raw.levelId, ctx) : null
712
+ if (hasExplicitLevel && !levelId) {
713
+ refuse('level_not_found', `Level "${String(raw.levelId)}" was not found in the scene.`)
714
+ }
715
+
716
+ let viewId = 'hero-in'
717
+ if (raw.viewId !== undefined) {
718
+ if (typeof raw.viewId !== 'string' || !raw.viewId.trim()) {
719
+ refuse('invalid_camera_view', 'viewId must be a non-empty string when provided.')
720
+ }
721
+ viewId = raw.viewId.trim()
722
+ }
723
+
724
+ if (raw.camera !== undefined && typeof raw.camera !== 'string') {
725
+ refuse('invalid_camera_view', 'camera must be a string when provided.')
726
+ }
727
+ if (raw.scene !== undefined && typeof raw.scene !== 'string') {
728
+ refuse('invalid_camera_view', 'scene must be a string when provided.')
729
+ }
730
+ if (
731
+ raw.includeStagedItemsInMustAppear !== undefined &&
732
+ typeof raw.includeStagedItemsInMustAppear !== 'boolean'
733
+ ) {
734
+ refuse('invalid_camera_view', 'includeStagedItemsInMustAppear must be a boolean when provided.')
735
+ }
736
+ if (
737
+ raw.mustAppear !== undefined &&
738
+ (!Array.isArray(raw.mustAppear) || !raw.mustAppear.every((v) => typeof v === 'string' && v.trim().length > 0))
739
+ ) {
740
+ refuse('invalid_camera_view', 'mustAppear must be an array of non-empty strings when provided.')
741
+ }
742
+ if (
743
+ raw.shellNotes !== undefined &&
744
+ (!Array.isArray(raw.shellNotes) || !raw.shellNotes.every((v) => typeof v === 'string'))
745
+ ) {
746
+ refuse('invalid_camera_view', 'shellNotes must be an array of strings when provided.')
747
+ }
748
+
749
+ const hasFrom = raw.fromXz !== undefined
750
+ const hasLook = raw.lookAtXz !== undefined
751
+ if (hasFrom !== hasLook) {
752
+ refuse(
753
+ 'invalid_camera_view',
754
+ 'Provide both fromXz and lookAtXz together, or omit both for an automatic axial camera view.',
755
+ )
756
+ }
757
+ const isFiniteVec2 = (v: unknown): v is Vec2 =>
758
+ Array.isArray(v) &&
759
+ v.length === 2 &&
760
+ typeof v[0] === 'number' &&
761
+ Number.isFinite(v[0]) &&
762
+ typeof v[1] === 'number' &&
763
+ Number.isFinite(v[1])
764
+ if (hasFrom && (!isFiniteVec2(raw.fromXz) || !isFiniteVec2(raw.lookAtXz))) {
765
+ refuse('invalid_camera_view', 'fromXz and lookAtXz must both be finite [x, z] coordinate pairs.')
766
+ }
767
+
768
+ let elevations: RoomWallElevationProjectionResult
769
+ try {
770
+ elevations = projectRoomWallElevations(rec, roomQuery, {
771
+ ...(levelId ? { levelId } : {}),
772
+ })
773
+ } catch (err) {
774
+ refuse('room_not_found', err instanceof Error ? err.message : `Room "${roomQuery}" not found.`)
775
+ }
776
+
777
+ const b = elevations.room.bounds
778
+ const spanX = Math.max(0.5, b.maxX - b.minX)
779
+ const spanZ = Math.max(0.5, b.maxZ - b.minZ)
780
+ const resolvedFromXz: Vec2 = hasFrom
781
+ ? (raw.fromXz as Vec2)
782
+ : [round3(b.minX + spanX * 0.22), round3(b.maxZ - spanZ * 0.15)]
783
+ const resolvedLookAtXz: Vec2 = hasLook
784
+ ? (raw.lookAtXz as Vec2)
785
+ : [round3(b.minX + spanX * 0.62), round3(b.minZ + spanZ * 0.15)]
786
+
787
+ let renderPrompt: RoomRenderPromptResult
788
+ try {
789
+ renderPrompt = compileRoomRenderPrompt(
790
+ rec,
791
+ elevations.roomId,
792
+ {
793
+ id: viewId,
794
+ fromXz: resolvedFromXz,
795
+ lookAtXz: resolvedLookAtXz,
796
+ ...(typeof raw.camera === 'string' && raw.camera.trim() ? { camera: raw.camera.trim() } : {}),
797
+ ...(typeof raw.scene === 'string' && raw.scene.trim() ? { scene: raw.scene.trim() } : {}),
798
+ },
799
+ {
800
+ ...(levelId ? { levelId } : {}),
801
+ ...(raw.mustAppear !== undefined ? { mustAppear: raw.mustAppear as readonly string[] } : {}),
802
+ ...(raw.shellNotes !== undefined ? { shellNotes: raw.shellNotes as readonly string[] } : {}),
803
+ includeStagedItemsInMustAppear: (raw.includeStagedItemsInMustAppear as boolean | undefined) ?? true,
804
+ },
805
+ )
806
+ } catch (err) {
807
+ refuse('invalid_camera_view', err instanceof Error ? err.message : 'Invalid camera view parameters.')
808
+ }
809
+
810
+ const summary = `${renderPrompt.roomName} [${renderPrompt.viewId}]: ${elevations.walls.length} wall(s), ${renderPrompt.solidWallIds.length} solid, ${renderPrompt.visibleWindowWalls.length} visible window wall(s), ${elevations.attributions.length} wall-attributed item(s), ${renderPrompt.sceneConflicts.length} scene conflict(s)`
811
+ return {
812
+ result: {
813
+ summary,
814
+ renderPrompt,
815
+ elevations,
816
+ },
817
+ }
818
+ },
819
+
820
+ furnishings_check_directions_diversity: (
821
+ _nodes: SceneNodes,
822
+ input: {
823
+ candidates: readonly StagingDirectionCandidate[]
824
+ axes?: readonly string[]
825
+ minDifferingAxes?: number
826
+ similarityThreshold?: number
827
+ requiredBudgetTiers?: readonly BudgetTier[]
828
+ },
829
+ _ctx?: AgentContext,
830
+ ): {
831
+ result: StagingDirectionsDiversityResult
832
+ } => {
833
+ if (!isPlainInputRecord(input)) {
834
+ refuse('invalid_diversity_spec', 'furnishings_check_directions_diversity input must be a plain object.')
835
+ }
836
+ try {
837
+ const report = evaluateStagingDirectionsDiversity(input.candidates, {
838
+ ...(input.axes !== undefined ? { axes: input.axes } : {}),
839
+ ...(input.minDifferingAxes !== undefined ? { minDifferingAxes: input.minDifferingAxes } : {}),
840
+ ...(input.similarityThreshold !== undefined ? { similarityThreshold: input.similarityThreshold } : {}),
841
+ ...(input.requiredBudgetTiers !== undefined ? { requiredBudgetTiers: input.requiredBudgetTiers } : {}),
842
+ })
843
+ return { result: report }
844
+ } catch (err) {
845
+ refuse('invalid_diversity_spec', err instanceof Error ? err.message : 'Invalid staging directions specification.')
846
+ }
847
+ },
848
+ } satisfies Record<string, unknown>
849
+
850
+ export const furnishingsOperations: AgentOperations = furnishingsAgentOperations as unknown as AgentOperations
851
+ export default furnishingsOperations