@roomle/web-sdk 7.0.0-alpha.1 → 7.0.0-alpha.2
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.
- package/THIRD-PARTY-NOTICES.txt +2 -2
- package/lib/{BufferGeometry-CzBRCIk3.mjs → BufferGeometry-YaAhwXNX.mjs} +2 -2
- package/lib/{BufferGeometry-CzBRCIk3.mjs.map → BufferGeometry-YaAhwXNX.mjs.map} +1 -1
- package/lib/ConfiguratorKernel.wasm +0 -0
- package/lib/{Object3D-Bkmul_of.mjs → Object3D-Dx0HN7Wz.mjs} +1 -1
- package/lib/{Object3D-Bkmul_of.mjs.map → Object3D-Dx0HN7Wz.mjs.map} +1 -1
- package/lib/{PointLightHelper-DOW-3Hvn.mjs → PointLightHelper-B8k3nJVr.mjs} +4 -4
- package/lib/{PointLightHelper-DOW-3Hvn.mjs.map → PointLightHelper-B8k3nJVr.mjs.map} +1 -1
- package/lib/RoomleCore.wasm +0 -0
- package/lib/RoomleToolsCore.wasm +0 -0
- package/lib/{SpotLightHelper-sE9yZPeq.mjs → SpotLightHelper-jqI3QyNE.mjs} +3 -3
- package/lib/{SpotLightHelper-sE9yZPeq.mjs.map → SpotLightHelper-jqI3QyNE.mjs.map} +1 -1
- package/lib/{USDZExporter-zhEk6F4K.mjs → USDZExporter-BS1qa3HO.mjs} +2 -2
- package/lib/{USDZExporter-zhEk6F4K.mjs.map → USDZExporter-BS1qa3HO.mjs.map} +1 -1
- package/lib/{Vector4-CmUR_DSp.mjs → Vector4-BmWb-htx.mjs} +2 -2
- package/lib/{Vector4-CmUR_DSp.mjs.map → Vector4-BmWb-htx.mjs.map} +1 -1
- package/lib/{api-1YHSF8TD.mjs → api-DOHbOr7K.mjs} +2 -2
- package/lib/{api-1YHSF8TD.mjs.map → api-DOHbOr7K.mjs.map} +1 -1
- package/lib/asset-loader.worker-Bdvb-pt7.mjs.map +1 -1
- package/lib/budgeteer.sw-ByZxiRBr.mjs.map +1 -1
- package/lib/{common-utils-DZiN8bjs.mjs → common-utils-zPOllvAT.mjs} +3 -2
- package/lib/common-utils-zPOllvAT.mjs.map +1 -0
- package/lib/{component-raycast-helper-BSFG09WY.mjs → component-raycast-helper-CMFpSJXC.mjs} +3 -3
- package/lib/{component-raycast-helper-BSFG09WY.mjs.map → component-raycast-helper-CMFpSJXC.mjs.map} +1 -1
- package/lib/{configuration-operations-DI677LMN.mjs → configuration-operations-DJD9A1xP.mjs} +38 -38
- package/lib/{configuration-operations-DI677LMN.mjs.map → configuration-operations-DJD9A1xP.mjs.map} +1 -1
- package/lib/configurator-D5Ehj649.mjs +3 -0
- package/lib/configurator-DCynrn7X.mjs +46 -0
- package/lib/{configurator-CgFJ2voV.mjs.map → configurator-DCynrn7X.mjs.map} +1 -1
- package/lib/{configurator-capabilities-CLqul800.mjs → configurator-capabilities-BfSMwdWh.mjs} +12 -12
- package/lib/{configurator-capabilities-CLqul800.mjs.map → configurator-capabilities-BfSMwdWh.mjs.map} +1 -1
- package/lib/configurator-capabilities-DAJuxSTw.mjs +3 -0
- package/lib/{fflate.module-CpWr9KGw.mjs → fflate.module-BfCRKtjc.mjs} +1 -1
- package/lib/{fflate.module-CpWr9KGw.mjs.map → fflate.module-BfCRKtjc.mjs.map} +1 -1
- package/lib/{glb-viewer-B2WH46su.mjs → glb-viewer-BhiCqjpE.mjs} +24 -24
- package/lib/{glb-viewer-B2WH46su.mjs.map → glb-viewer-BhiCqjpE.mjs.map} +1 -1
- package/lib/glb-viewer-BrggGLte.mjs +3 -0
- package/lib/{hi-mcp-server-tVF1bn28.mjs → hi-mcp-server-rSu1HL4m.mjs} +2 -2
- package/lib/{hi-mcp-server-tVF1bn28.mjs.map → hi-mcp-server-rSu1HL4m.mjs.map} +1 -1
- package/lib/{highlight-coordinator-CiBzWsMf.mjs → highlight-coordinator-DbqhP7Hy.mjs} +3 -3
- package/lib/{highlight-coordinator-CiBzWsMf.mjs.map → highlight-coordinator-DbqhP7Hy.mjs.map} +1 -1
- package/lib/{homag-intelligence-CdYda0Mb.mjs → homag-intelligence-DuFtYgdG.mjs} +3 -3
- package/lib/{homag-intelligence-CdYda0Mb.mjs.map → homag-intelligence-DuFtYgdG.mjs.map} +1 -1
- package/lib/{material-viewer-BrARE0p0.mjs → material-viewer-uEDqIbCx.mjs} +25 -21
- package/lib/material-viewer-uEDqIbCx.mjs.map +1 -0
- package/lib/{packages-DhBz4dX3.mjs → packages-DOCmEOxI.mjs} +6 -6
- package/lib/{packages-DhBz4dX3.mjs.map → packages-DOCmEOxI.mjs.map} +1 -1
- package/lib/planner-B9GbQLSB.mjs +3 -0
- package/lib/{planner-SRvOM5ZQ.mjs → planner-D8UVNfkJ.mjs} +16 -16
- package/lib/{planner-SRvOM5ZQ.mjs.map → planner-D8UVNfkJ.mjs.map} +1 -1
- package/lib/roomle-headless.d.ts +14 -18
- package/lib/roomle-headless.js +35 -32
- package/lib/roomle-headless.js.map +1 -1
- package/lib/{roomle-sdk-Sdrd7K0F.mjs → roomle-sdk-C0YpFZdj.mjs} +24740 -24770
- package/lib/roomle-sdk-C0YpFZdj.mjs.map +1 -0
- package/lib/roomle-sdk.d.ts +14 -18
- package/lib/roomle-sdk.js +9 -9
- package/lib/{roomle-webgpu-renderer-CWoN5YzU.mjs → roomle-webgpu-renderer-DZ9LaZfc.mjs} +3 -3
- package/lib/{roomle-webgpu-renderer-CWoN5YzU.mjs.map → roomle-webgpu-renderer-DZ9LaZfc.mjs.map} +1 -1
- package/lib/{scene-renderer-CsbP23gu.mjs → scene-renderer-BmtXHWEw.mjs} +3 -3
- package/lib/{scene-renderer-CsbP23gu.mjs.map → scene-renderer-BmtXHWEw.mjs.map} +1 -1
- package/lib/{script-loader-D9Tr-8LN.mjs → script-loader-jRBMP-ca.mjs} +2 -2
- package/lib/{script-loader-D9Tr-8LN.mjs.map → script-loader-jRBMP-ca.mjs.map} +1 -1
- package/lib/{shading-settings-mnQRn2LO.mjs → shading-settings-CpXZmOnx.mjs} +2 -2
- package/lib/{shading-settings-mnQRn2LO.mjs.map → shading-settings-CpXZmOnx.mjs.map} +1 -1
- package/lib/static/roomle-core-hsc/node_modules/roomle-core-hsc/package.json +1 -1
- package/lib/static/roomle-core-hsc/node_modules/roomle-core-hsc/wasm_modern/ConfiguratorKernel.wasm +0 -0
- package/lib/static/roomle-core-hsc/node_modules/roomle-core-hsc/wasm_modern/RoomleCore.wasm +0 -0
- package/lib/static/roomle-core-hsc/node_modules/roomle-core-hsc/wasm_modern/RoomleToolsCore.wasm +0 -0
- package/lib/{stats-helper-Q25NjvCQ.mjs → stats-helper-jzrLyoHV.mjs} +2 -2
- package/lib/{stats-helper-Q25NjvCQ.mjs.map → stats-helper-jzrLyoHV.mjs.map} +1 -1
- package/lib/{threejs-utils-C3CWKZXa.mjs → threejs-utils-D1gtvxiA.mjs} +7 -15
- package/lib/{threejs-utils-C3CWKZXa.mjs.map → threejs-utils-D1gtvxiA.mjs.map} +1 -1
- package/lib/{tools-core-BBYYzygJ.mjs → tools-core-k93qrqfB.mjs} +6 -6
- package/lib/{tools-core-BBYYzygJ.mjs.map → tools-core-k93qrqfB.mjs.map} +1 -1
- package/lib/{util-BdWrqTeC.mjs → util-LmkV26fg.mjs} +1 -1
- package/lib/{util-BdWrqTeC.mjs.map → util-LmkV26fg.mjs.map} +1 -1
- package/package.json +2 -2
- package/sbom.cdx.json +5 -5
- package/lib/common-utils-DZiN8bjs.mjs.map +0 -1
- package/lib/configurator-AwPowYQR.mjs +0 -3
- package/lib/configurator-CgFJ2voV.mjs +0 -46
- package/lib/configurator-capabilities-Dg8oD49T.mjs +0 -3
- package/lib/glb-viewer-sxVA5IgD.mjs +0 -3
- package/lib/material-viewer-BrARE0p0.mjs.map +0 -1
- package/lib/planner-D6uV0kCw.mjs +0 -3
- package/lib/roomle-sdk-Sdrd7K0F.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hi-mcp-server-tVF1bn28.mjs","names":[],"sources":["../../packages/homag-intelligence/src/hi-tools/agent-frame.ts","../../packages/homag-intelligence/src/hi-tools/plan-history.ts","../../packages/homag-intelligence/src/hi-tools/planner-api.ts","../../packages/homag-intelligence/src/hi-tools/skills/image-planning/SKILL.md?raw","../../packages/homag-intelligence/src/hi-tools/skills/kitchen-planning/SKILL.md?raw","../../packages/homag-intelligence/src/hi-tools/skills/kitchen-planning/references/planning-reference.md?raw","../../packages/homag-intelligence/src/hi-tools/skills/kitchen-planning/references/source-catalog.md?raw","../../packages/homag-intelligence/src/hi-tools/skills/kitchen-planning-fr/SKILL.md?raw","../../packages/homag-intelligence/src/hi-tools/skills/kitchen-planning-fr/references/planning-reference.md?raw","../../packages/homag-intelligence/src/hi-tools/skills/kitchen-planning-fr/references/source-catalog.md?raw","../../packages/homag-intelligence/src/hi-tools/skills/living-room-planning/SKILL.md?raw","../../packages/homag-intelligence/src/hi-tools/skills/living-room-planning/references/planning-reference.md?raw","../../packages/homag-intelligence/src/hi-tools/skills/living-room-planning/references/source-catalog.md?raw","../../packages/homag-intelligence/src/hi-tools/skills.ts","../../packages/homag-intelligence/src/hi-tools/agent-facing.ts","../../packages/homag-intelligence/src/hi-tools/tool-executors.ts","../../packages/homag-intelligence/src/hi-tools/hi-mcp-server.ts"],"sourcesContent":["// The agent works in the planner's plan space: millimetres, right-handed, z\n// up, the floor in x and y - +x to the right and +y to the top of the top-view\n// image. The planner methods, the tool commands and the HI geometry work in\n// pos space, the frame of the HI group JSON: y up, its z the plan's -y. Both\n// differ by a proper rotation, so an angle turns a group the same way in\n// both; only the names of the rotation fields change with the axis.\n\ntype Point = [number, number, number];\n\nconst isPoint = (value: unknown): value is Point =>\n Array.isArray(value) && value.length === 3 && value.every(Number.isFinite);\n\n// a floor point [x, y] or a range [from, to]\nconst isPair = (value: unknown): value is [number, number] =>\n Array.isArray(value) && value.length === 2 && value.every(Number.isFinite);\n\nconst isObject = (value: unknown): boolean =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n// + 0 turns IEEE -0 into +0 so serialized values never show -0\nconst inPlanSpace = (value: unknown): unknown =>\n isPoint(value) ? [value[0] + 0, -value[2] + 0, value[1] + 0] : value;\n\nconst inPosSpace = (value: unknown): unknown =>\n isPoint(value) ? [value[0] + 0, value[2] + 0, -value[1] + 0] : value;\n\n// A z range of pos space is the y range of plan space, negated.\nconst negatedRange = (value: unknown): unknown =>\n isPair(value) ? [-value[1] + 0, -value[0] + 0] : value;\n\n// The fields of an object converted and renamed in their place; everything\n// else as it is.\nconst withFields = (\n object: any,\n fields: Record<string, (value: any) => unknown>,\n names: Record<string, string> = {},\n): any =>\n isObject(object)\n ? Object.fromEntries(\n Object.entries(object).map(([key, value]) => [\n names[key] ?? key,\n fields[key] ? fields[key](value) : value,\n ]),\n )\n : object;\n\nconst each =\n (convert: (item: any, index: number) => unknown) =>\n (value: unknown): unknown =>\n Array.isArray(value) ? value.map(convert) : value;\n\nconst dockingOffsets = (inFrame: (value: unknown) => unknown) =>\n each((root) =>\n withFields(root, {\n contextData: (contextData) =>\n withFields(contextData, {\n dockedRoots: each((context) =>\n withFields(context, {\n dockedRoots: each((entry) =>\n withFields(entry, { offset: inFrame }),\n ),\n }),\n ),\n }),\n }),\n );\n\nconst fittingsToAgent = each((fitting) =>\n withFields(fitting, { position: inPlanSpace }),\n);\n\nconst wallToAgent = (wall: unknown) =>\n withFields(\n wall,\n { start: inPlanSpace, end: inPlanSpace },\n { facingRotationY: 'facingRotationZ' },\n );\n\nconst outlinesToAgent = each((item) =>\n withFields(item, { outline: each(inPlanSpace) }),\n);\n\nconst groupToAgent = (group: unknown) =>\n withFields(group, {\n position: (position) =>\n withFields(\n position,\n {\n pos: inPlanSpace,\n footprint: (footprint) =>\n withFields(footprint, { z: negatedRange }, { z: 'y' }),\n },\n { rotationY: 'rotationZ' },\n ),\n roots: dockingOffsets(inPlanSpace),\n interiorFittings: fittingsToAgent,\n });\n\nconst RESULT_FIELDS: Record<string, (value: any) => unknown> = {\n rooms: (rooms) =>\n withFields(rooms, {\n rooms: each((room) =>\n withFields(room, {\n levels: each((level) =>\n withFields(level, {\n segments: each((segment) =>\n withFields(segment, { pos: inPlanSpace }),\n ),\n }),\n ),\n walls: each(wallToAgent),\n corners: each((corner) =>\n withFields(\n corner,\n { point: inPlanSpace },\n { posRotationY: 'posRotationZ' },\n ),\n ),\n }),\n ),\n }),\n obstacles: (obstacles) =>\n withFields(obstacles, {\n objects: outlinesToAgent,\n groups: each((group) => withFields(group, { roots: outlinesToAgent })),\n }),\n installationElements: each((element) =>\n withFields(element, { position: inPlanSpace }),\n ),\n groups: each(groupToAgent),\n group: groupToAgent,\n wall: wallToAgent,\n fittings: fittingsToAgent,\n};\n\n// The price and the order data are the order's, not the plan's.\nconst RESULTS_WITHOUT_PLAN = ['get-price', 'get-order-data'];\n\n// The result of a tool in the agent's frame: every point, outline, range and\n// rotation of the plan context and of the changed groups in plan space.\nexport const toAgentFrame = (tool: string, result: unknown): unknown =>\n RESULTS_WITHOUT_PLAN.includes(tool)\n ? result\n : withFields(result, RESULT_FIELDS);\n\n// A number a model wrote as text - \"600\" - as the number; undefined for\n// anything else.\nconst numberOfText = (value: unknown): number | undefined =>\n typeof value === 'string' &&\n value.trim() !== '' &&\n Number.isFinite(Number(value))\n ? Number(value)\n : undefined;\n\n// The point and the rotation of a placement a model wrote as text, read as\n// numbers and named - before the frame conversion, which takes numbers only.\nconst withNumbersRead = (\n placement: any,\n prefix: string,\n corrections: string[],\n): any => {\n const read: Record<string, unknown> = {};\n if (\n Array.isArray(placement.posGroup) &&\n placement.posGroup.some(\n (value: unknown) => numberOfText(value) !== undefined,\n )\n ) {\n read.posGroup = placement.posGroup.map(\n (value: unknown) => numberOfText(value) ?? value,\n );\n }\n const rotation = numberOfText(placement.posRotationZ);\n if (rotation !== undefined) {\n read.posRotationZ = rotation;\n }\n if (Object.keys(read).length === 0) {\n return placement;\n }\n corrections.push(\n `${prefix}: the placement's ${Object.entries(read)\n .map(\n ([field, value]) =>\n `${field} ${JSON.stringify(placement[field])} was read as ${JSON.stringify(value)}`,\n )\n .join(', ')}`,\n );\n return { ...placement, ...read };\n};\n\n// A placement by point in pos space; a floor point is completed with z = 0.\n// A placement by wall names no coordinate, and a value that is no point\n// passes as it is, so the tool command reports it.\nconst placementFromAgent =\n (prefix: string, corrections: string[]) => (sent: any) => {\n if (!isObject(sent) || sent.wall !== undefined) {\n return sent;\n }\n const placement = withNumbersRead(sent, prefix, corrections);\n if (isPair(placement.posGroup)) {\n const [x, y] = placement.posGroup;\n corrections.push(\n `${prefix}: the placement's posGroup [${x}, ${y}] was completed to [${x}, ${y}, 0] (z = 0 on the floor)`,\n );\n }\n return withFields(\n placement,\n {\n posGroup: (posGroup) =>\n inPosSpace(isPair(posGroup) ? [...posGroup, 0] : posGroup),\n },\n { posRotationZ: 'posRotationY' },\n );\n };\n\n// The arguments of a tool in pos space, the frame of the planner methods -\n// the placements, the docking offsets and the insert positions of interior\n// fittings -, and the corrections the conversion made.\nexport const fromAgentFrame = (\n args: Record<string, unknown>,\n): { args: Record<string, unknown>; corrections: string[] } => {\n const corrections: string[] = [];\n const input =\n args.groupId !== undefined &&\n (args.posGroup !== undefined || args.posRotationZ !== undefined)\n ? placementFromAgent('place-group', corrections)(args)\n : args;\n const converted = withFields(input, {\n posGroups: each((group, index) => {\n const placement = placementFromAgent(`posGroups[${index}]`, corrections);\n return withFields(group, {\n placement,\n repositioningData: placement,\n roots: dockingOffsets(inPosSpace),\n });\n }),\n dockTo: (dockTo) => withFields(dockTo, { offset: inPosSpace }),\n insertPosition: inPosSpace,\n });\n return { args: converted, corrections };\n};\n","/** A tool call that changed the plan, as the undo tool reverts it. */\nexport interface ToolCallRecord {\n tool: string;\n /** The planner steps the call put on the planner's undo history. */\n steps: number;\n /** The plan's groups before and after the call, as comparison keys. */\n groupsBefore: string;\n groupsAfter: string;\n}\n\n// The tool set's view of the planner's undo history: the planner's history\n// events and the tool calls that changed the plan, with the planner steps\n// each made. An event while no tool call runs is a change the user made\n// in the planner - the tool calls below it can no longer be undone safely, so\n// they are forgotten.\nexport class PlanHistory {\n private _events = 0;\n private _inFlight = false;\n private _done: ToolCallRecord[] = [];\n private _undone: ToolCallRecord[] = [];\n private _changedInPlanner = false;\n private _waiters = new Set<() => void>();\n\n public get events(): number {\n return this._events;\n }\n\n public get changedInPlanner(): boolean {\n return this._changedInPlanner;\n }\n\n public historyChanged(): void {\n this._events += 1;\n if (!this._inFlight) {\n this.forget();\n this._changedInPlanner = true;\n }\n for (const wake of this._waiters) {\n wake();\n }\n }\n\n /** Resolves true once `count` events have arrived, false after the timeout. */\n public waitForEvents(count: number, timeoutMs: number): Promise<boolean> {\n if (this._events >= count) {\n return Promise.resolve(true);\n }\n return new Promise((resolve) => {\n const finish = (reached: boolean) => {\n clearTimeout(timer);\n this._waiters.delete(wake);\n resolve(reached);\n };\n const wake = () => {\n if (this._events >= count) {\n finish(true);\n }\n };\n const timer = setTimeout(() => finish(false), timeoutMs);\n this._waiters.add(wake);\n });\n }\n\n public begin(): void {\n this._inFlight = true;\n }\n\n public end(): void {\n this._inFlight = false;\n }\n\n /** A new change on top of the history ends redo, as in the planner. */\n public record(call: ToolCallRecord): void {\n this._done.push(call);\n this._undone = [];\n this._changedInPlanner = false;\n }\n\n public lastDone(): ToolCallRecord | undefined {\n return this._done.at(-1);\n }\n\n public lastUndone(): ToolCallRecord | undefined {\n return this._undone.at(-1);\n }\n\n public markUndone(): void {\n const call = this._done.pop();\n if (call) {\n this._undone.push(call);\n }\n }\n\n public markRedone(): void {\n const call = this._undone.pop();\n if (call) {\n this._done.push(call);\n }\n }\n\n public forget(): void {\n this._done = [];\n this._undone = [];\n }\n\n /** A change in the planner was found: no record can be trusted any more. */\n public markChangedInPlanner(): void {\n this.forget();\n this._changedInPlanner = true;\n }\n}\n","import type { ExternalObjectSnapshotRequest } from '../external-object-api';\n\nexport const DEFAULT_CALL_TIMEOUT_MS = 30_000;\nexport const SNAPSHOT_CALL_TIMEOUT_MS = 120_000;\n\n// The planner methods the tools call.\nexport interface PlannerApi {\n extended: {\n getExternalObjectPlanContext(\n include: string[],\n options?: {\n interiorDesign: {\n groupId: string;\n rootId?: string;\n containerModuleId?: string;\n articleId?: string;\n };\n },\n ): Promise<any>;\n getExternalObjectLibraryContext(\n include: string[],\n options?: { articleIds?: string[] },\n ): Promise<any>;\n externalObjectGroupOperation(\n command: string,\n payload: Record<string, unknown>,\n ): Promise<any>;\n fetchPrice(): Promise<any>;\n getExternalObjectSnapshot(\n options: ExternalObjectSnapshotRequest,\n ): Promise<any>;\n undo(): Promise<void>;\n redo(): Promise<void>;\n };\n}\n\n/**\n * The planner the HI MCP tools run in: the seven planner methods the tools\n * call, and the planner's callbacks, whose `onHistoryChange` the tools chain\n * to tell their own planner steps from the user's changes.\n */\nexport type HiMcpPlannerApi = PlannerApi & {\n extended: {\n callbacks: {\n onHistoryChange?: (undo: boolean, redo: boolean) => void;\n };\n };\n};\n\n// The seven planner methods as the tools call them: each call with a timeout -\n// a planner call has none of its own - and a log line.\nexport const createPlannerApi = ({ extended }: PlannerApi): PlannerApi => {\n let nextCallId = 1;\n const call = (\n method: keyof PlannerApi['extended'],\n args: unknown[],\n timeoutMs: number,\n ): Promise<any> => {\n const id = nextCallId++;\n console.log(\n `[hi-mcp] call ${id}: ${method} ${JSON.stringify(args).slice(0, 400)}`,\n );\n let timeout: ReturnType<typeof setTimeout> | undefined;\n const timedOut = new Promise<never>((_resolve, reject) => {\n timeout = setTimeout(\n () =>\n reject(\n new Error(\n `Planner call '${method}' timed out after ${timeoutMs}ms`,\n ),\n ),\n timeoutMs,\n );\n });\n return Promise.race([\n (extended[method] as (...callArgs: unknown[]) => Promise<unknown>).apply(\n extended,\n args,\n ),\n timedOut,\n ]).finally(() => clearTimeout(timeout));\n };\n return {\n extended: {\n getExternalObjectPlanContext: (include, options) =>\n call(\n 'getExternalObjectPlanContext',\n options === undefined ? [include] : [include, options],\n DEFAULT_CALL_TIMEOUT_MS,\n ),\n getExternalObjectLibraryContext: (include, options) =>\n call(\n 'getExternalObjectLibraryContext',\n options === undefined ? [include] : [include, options],\n DEFAULT_CALL_TIMEOUT_MS,\n ),\n externalObjectGroupOperation: (command, payload) =>\n call(\n 'externalObjectGroupOperation',\n [command, payload],\n SNAPSHOT_CALL_TIMEOUT_MS,\n ),\n fetchPrice: () => call('fetchPrice', [], DEFAULT_CALL_TIMEOUT_MS),\n getExternalObjectSnapshot: (options) =>\n call('getExternalObjectSnapshot', [options], SNAPSHOT_CALL_TIMEOUT_MS),\n undo: async () => {\n await call('undo', [], DEFAULT_CALL_TIMEOUT_MS);\n },\n redo: async () => {\n await call('redo', [], DEFAULT_CALL_TIMEOUT_MS);\n },\n },\n };\n};\n","export default \"---\\nname: image-planning\\ndescription: 'Plan furniture from an image or photo the user sends, with or without text: identify the pieces of furniture, read their layout, counts and sizes, map them onto the room of the plan and the article catalog, and report what was substituted and adapted. Use whenever a user message carries an image of furniture or of a room.'\\n---\\n\\n# Planning from an Image\\n\\n## Purpose\\n\\nThe image is the brief. Plan the furniture it shows as close to it as possible, with the articles of the catalog, in the room of the plan. The text of the message, when there is one, comes first: it names the wall, the corner, the changes or the part of the image to plan; the image supplies everything the text leaves open.\\n\\nA photo is enough for a concept. Do not ask for a measured plan, a site survey or the services first: plan with stated assumptions and name them in the answer.\\n\\n## 1. Identify the furniture\\n\\n- Name every piece of furniture in the image and its kind — a kitchen, a wardrobe, a media unit, a sideboard, shelves, a utility room, a row of tall cabinets — before choosing articles. Plan what the image shows: tall cabinets in a kitchen-like room are tall cabinets, not a kitchen.\\n- Name the appliances of each piece too — sink, hob, oven, fridge, dishwasher, hood —, those behind a cabinet front included: a fridge in a tall column, a dishwasher behind a door front.\\n- Plan each piece as one group. Cabinets beside, above or behind each other belong to the same group.\\n- Leave out what is no furniture of the catalog — walls, floors, decoration, loose items — and name the pieces the catalog has nothing for.\\n\\n## 2. Read the layout\\n\\n- The shape: one row, an L around a corner, a U, two facing rows (a galley), a row with an island, a free-standing piece.\\n- The levels: floor cabinets, tall cabinets, wall cabinets above the floor cabinets, cabinets on top; which wall cabinets hang above which floor cabinets, and where a tall cabinet interrupts the rows.\\n- The order along each row, from left to right as seen from the front: what stands next to what — sink, dishwasher, hob, oven, fridge, drawers, open shelves, a corner. Keep this sequence; it makes the planning look like the image.\\n- For an island, name the row it runs parallel to in the image — in an L or a U, one of the legs — and keep the island parallel to that row, its cabinet fronts facing that row across the working aisle. For a peninsula, keep its long axis relative to the other rows and face its cabinet fronts across the working aisle. A visible finished panel may be its back. For a straight row, rotation 0 faces -y, 90 faces +x, 180 faces +y and 270 faces -x in plan space. After mapping the kitchen into the room, turn the island to face the wall of the row it runs parallel to. Correct opposite facing with a half turn; a quarter turn changes the axis.\\n\\n## 3. Read the counts and the sizes\\n\\n- Count the cabinets per row and per level. A pair of doors is usually one cabinet, one wide drawer front one cabinet.\\n- Judge the widths relative to each other and to a reference of known size — a door, an appliance, the height of the floor cabinets or of the room. Then take for each cabinet the catalog article whose width comes closest: the catalog's widths are the truth, the estimate is not.\\n- A photo distorts: cabinets far from the camera look narrower, cabinets at the edge of the image wider. Prefer the count and the proportions over the width in pixels.\\n- A row of wall units is as long as the widths of its units: fit it to the floor units it hangs over — on a leg, to the stretch from the first floor unit it hangs over to the wall or the corner at the end of the leg — and keep its place in the image.\\n\\n## 4. Map it onto the plan\\n\\n- The room of the plan is not the room in the image. Read its walls, doors, windows and obstacles from the plan context.\\n- When the text names a wall or a corner, plan there. Otherwise choose the wall or corner whose length and openings fit the shape: an L into a room corner with two free walls, a long row onto the longest free wall, a galley onto two facing walls.\\n- Fit the length to the wall. Keep the sequence and the proportions; when the wall is shorter than the furniture in the image, leave out or narrow the cabinets of least weight — a filler, an open shelf, a second drawer cabinet. When it is longer, add nothing the image does not show.\\n- Keep doors and windows clear, and name in the answer what moved for them.\\n- Check the returned island against the row it runs parallel to: its long axis parallel to that row, its fronts facing that row's wall. Correct an existing island with point-form `place-group`, keeping its construction and finishes.\\n\\n## 5. Articles and attributes\\n\\n- Choose each article by what the cabinet does in the image — a sink cabinet, a drawer cabinet, an appliance housing, a corner cabinet — from the desc, the category, the dimensions and the subModules of the catalog. The subModules list the appliances an article comes with: an appliance of the image goes into an article whose subModules carry it, even when its fronts differ from the image — the fronts are the substitution, never the appliance.\\n- Before the create, check every appliance you named against the subModules of the articles you send.\\n- Finish the exposed back of an island or peninsula in the same create with the catalog component that matches the image's construction, `behind` any unit of its cabinet row — the server anchors the panel at the row's start end and runs it along the whole row — and as long as that row's whole back, a peninsula corner's back included. Match its height profile too: use the calculated roots' `bottomMm` and `topMm` to compare finished surfaces, accounting for the finishing component's bottom. Keep a raised surface when the image or text asks for one; otherwise align the intended flush surfaces. A separate cap is not a continuous worktop; report the substitution when the catalog cannot reproduce the surface shown.\\n- Read the fronts, the handles, the worktop and the carcase that the image or the text shows and set them as attributes of the group. Look every value up - the attributes section of the plan context for the create attributes, find-attributes for the rest - and say which value you took.\\n\\n## 6. The room skills\\n\\nWhen the furniture is of a kind another planning skill covers — a kitchen, a living room — fetch that skill too, for its checks. The image keeps precedence:\\n\\n- Apply its hard constraints: clearances, openings, what an appliance needs to work and to be installed.\\n- Report its recommendations — a better sequence, more worktop, another position of an appliance — in the answer as notes. Do not change what the image shows for them, unless the user asks for an improved planning.\\n- Fetch its planning reference only for a dimension this skill does not settle.\\n\\n## 7. The answer\\n\\nSay in a few sentences:\\n\\n- what you identified in the image and planned, group by group;\\n- what you substituted — the closest article or attribute value for what the catalog lacks;\\n- each appliance of the image the plan does not carry, and why;\\n- what you adapted to the room — the wall, the length, the cabinets left out, the openings kept clear;\\n- the assumptions, and the open checks of the room skill.\\n\"","export default \"---\\nname: kitchen-planning\\ndescription: 'Plan or review a residential kitchen: room survey, kitchen layout, sink and hob spacing, dishwasher placement, cabinet ordering, drawer organization, storage zones, short walking routes, ergonomics, accessibility, appliance clearances, and installation readiness. Use for kitchen planning, kitchen design, Kuechenplanung, arranging cabinets, or improving cooking and dishwasher-unloading workflows. Defaults to Germany/EU and millimetres; adapt rules to the actual jurisdiction.'\\n---\\n\\n# Kitchen Planning\\n\\n## Purpose and Scope\\n\\nProduce practical, dimensioned residential kitchen proposals with short daily routes, usable storage, and explicit feasibility checks. Plan from activities and contents before choosing cabinet fronts. Here, cabinet \\\"ordering\\\" means arranging cabinets; procurement requires a separate approval gate.\\n\\nDefault to Germany/EU, dimensions in mm, and costs in EUR. Confirm country and, in Germany, Bundesland before applying regulatory requirements. There is no single EU kitchen-clearance code. Commercial kitchens require a separate specialist workflow.\\n\\nRead [the planning constraints reference](./references/planning-reference.md) before applying numerical guidance or reviewing installation risks. It includes rule classifications, qualifications, and short source IDs for traceability. Recheck current local requirements and exact product manuals for each real project.\\n\\nThe [source catalog](./references/source-catalog.md) is optional. Load it only to verify a source-backed claim, answer a provenance/citation question, or update the guidance. Do not load it during routine planning merely to resolve source IDs; the operational guidance and its limitations are in this skill and the planning reference. This does not waive project-specific verification of regulations or product instructions.\\n\\n## Non-Negotiable Planning Discipline\\n\\n- Treat law, applicable technical requirements, product instructions, and verified site constraints as simultaneous constraints. If they conflict, stop and resolve the conflict; a manufacturer cannot waive the law.\\n- Do not turn a recommendation into a regulation. In particular, do not claim that a sink beside a hob is universally illegal. Usually the problem is missing preparation/landing space; actual installation restrictions are product- and site-specific.\\n- Unknown is not pass. Missing dimensions, manuals, or service information remain unresolved. Photographs and generated images cannot establish installation readiness.\\n- Use a planner's authoritative geometry, catalog, and prices where available. Never invent a catalog item, price, service point, clearance, or successful validation result.\\n- Optimize only after hard constraints pass. A short walking route cannot compensate for a blocked exit, unsafe installation, or inaccessible appliance.\\n- Offer concepts with explicit assumptions when facts are incomplete. Do not call them order-ready or installation-ready.\\n- Do not move services, alter structures, purchase items, or overwrite an accepted design without explicit authorization. Draft alternatives should remain reversible.\\n\\n## 1. Collect the Brief and Survey\\n\\nAsk only for missing information that changes the next decision. Start with room dimensions/openings, fixed services, users, appliances, and budget. Collect remaining details progressively.\\n\\n| Input | Required information |\\n| --- | --- |\\n| Location and scope | Country, region, dwelling type, new build/remodel, ownership/landlord restrictions, required accessibility standard, retained items. |\\n| Room | Each wall length, ceiling/soffit heights, angles/diagonals, niches, columns, slopes, and finished floor levels. Measure irregular walls at relevant heights. |\\n| Openings | Door/window position, clear opening, frame/trim, sill height, opening direction and swept volume; curtains/blinds and window handles. |\\n| Services | Measured water/drain positions and heights, shutoffs, electrical points/circuits, gas, ventilation/exhaust routes, heating, meters, and service access. Mark relocation permission separately. |\\n| Structure | Wall construction/fixing capacity, floor/ceiling constraints, existing ventilation, room-air-dependent fireplace or combustion appliance, underfloor services. |\\n| People | Household size, number of simultaneous cooks, heights/elbow heights, handedness, reach/lifting ability, mobility aids, children, and future needs. |\\n| Activities | Shopping frequency, everyday meals, batch cooking, baking, coffee, entertaining, table setting, cleaning, waste sorting, and current annoyances. |\\n| Inventory | Counts and dimensions of dishes, pans, trays, containers, food, appliances, and waste bins; frequency and typical weight of use. |\\n| Products | Exact models or provisional envelopes, installation manuals, cabinet system, appliance niches, front/hinge system, handle projections, and worktop material. |\\n| Commercial | Total installed budget, service relocation allowance, delivery/access constraints, timing, and priorities ranked by the user. |\\n\\nFor each critical fact record `value`, `unit`, `source`, `verification_state`, and measurement uncertainty where known. Use `unknown`, `inferred`, `user_verified`, or `professionally_verified`. Preserve raw measurements and identify the finished reference surfaces.\\n\\nIf only a photo is supplied, request a measured plan or verified reference dimensions. Hidden pipe routes, wall strength, electrical capacity, and regulatory compliance cannot be inferred from appearance.\\n\\n## 2. Build the Constraint Register\\n\\nGive each rule a stable ID and classify it:\\n\\n| Class | Meaning | Handling |\\n| --- | --- | --- |\\n| `regulatory` | Verified applicable legal/code requirement, with jurisdiction and edition. | Hard; no user override. |\\n| `manufacturer` | Exact installation/compatibility requirement for the selected product. | Hard; change the product or design if necessary. |\\n| `site` | Verified room, structural, service, or geometric limitation. | Hard unless an approved change creates a new verified condition. |\\n| `user_must` | Explicit user requirement, including a fixed budget if stated. | Hard for this brief; ask before relaxing. |\\n| `recommendation` | Sourced ergonomic/design recommendation or labeled planning heuristic. | Soft; document the consequence of departures. |\\n| `preference` | Style, symmetry, convenience, or other discretionary choice. | Soft; trade off transparently. |\\n\\nEach record needs `id`, `class`, `applicability`, `requirement`, `measurement_definition`, `source`, `status`, `affected_items`, and `remedy_or_next_action`. Status is `pass`, `fail`, `unknown`, or `not_applicable`; explain exclusions. Preserve recommendation deviations rather than silently deleting them.\\n\\nComplete every category in the reference's installation checklist. Record applicability separately from compliance: an unconfirmed rule is not automatically irrelevant.\\n\\n## 3. Arrange Functional Zones\\n\\nUse five zones as an adjacency model, not a compulsory left-to-right sequence [S1, S2]:\\n\\n1. Food storage: refrigerator/freezer and dry provisions.\\n2. Preparation: the principal clear work surface and preparation tools.\\n3. Cooking: hob, oven, heat-safe landing surfaces, and cookware.\\n4. Cleaning: sink, dishwasher, waste sorting, and cleaning supplies.\\n5. Clean storage/serving: dishes, dining cutlery, glasses, and serving items.\\n\\nTrace these distinct workflows:\\n\\n- Shopping arrival -> grocery landing -> refrigerator/pantry.\\n- Food storage -> sink when needed -> preparation -> cooking -> serving.\\n- Table return -> scrape/sort -> sink as needed -> dishwasher. Do not prescribe routine pre-rinsing; follow appliance guidance.\\n- Dishwasher -> clean storage -> table/serving.\\n- Hob -> sink for draining hot cookware, without avoidable traffic crossings.\\n- Coffee/breakfast and snack access without walking through active cooking.\\n\\nKeep through-traffic outside the principal work area. The refrigerator-sink-hob triangle is a diagnostic, not a mandatory geometry or a substitute for these workflows. A one-wall kitchen can work without a triangle. Mixed-handed or multi-cook households need task trials, not automatic mirroring.\\n\\n### Placing the Kitchen in the Room\\n\\nWhen the user does not name a place for the kitchen, plan it so that the sink stands near a water connection of the plan, if the room has one. The installation elements of the plan context list the water connections with their positions.\\n\\n### Sink, Preparation Surface, and Hob\\n\\nPrefer `sink -> continuous preparation surface -> hob`, or the mirror image. Blum recommends approximately 900 mm of preparation width, with 800 mm as its lower ergonomic recommendation [S3]. These are not German legal minimums. More space may be needed for two cooks or extensive baking.\\n\\nMeasure usable clear surface between fixture edges, excluding an occupied drainer, permanent appliances, or other obstructions. Record actual usable depth too. Separately verify cut-out-to-cut-out webs, edge distances, and supports from the worktop fabricator; a visible surface gap does not prove structural suitability.\\n\\nAvoid placing a tall cabinet across this continuous workflow. Keep the preparation surface genuinely available after locating the kettle, coffee machine, knife storage, and drying area. Where the room cannot accommodate the recommendation, disclose the compromise and test an adjacent alternative preparation surface.\\n\\n### Dishwasher and Clean Storage\\n\\n- Start with the dishwasher beside the sink, subject to plumbing, appliance instructions, and usable access. Prefer a side outside the main preparation stance when feasible.\\n- Compare both sides of the sink. Do not prescribe left/right solely from handedness.\\n- Locate everyday dining cutlery, plates, and bowls in an adjacent or nearby accessible drawer bank. Locate daily glasses and cups within comfortable reach nearby [S4].\\n- Aim for a comfortable turn or short step during unloading. This is a qualitative target, not a universal distance limit.\\n- Check dishwasher fully open, racks extended, destination drawer open, and a person standing in the unloading position. Neither nominal adjacency nor cabinet-centre distance establishes usability.\\n- Across an aisle can work only if the actual door/drawer projections, standing space, reach, and circulation work together. Never require stepping over a dishwasher door.\\n- At an inside corner, check perpendicular drawer collisions and access to the sink/waste. Move the dishwasher or storage bank if fillers alone cannot solve the conflict.\\n- Keep dining/table access convenient without routing other people through the hot zone. Do not put every item beside the dishwasher: cooking tools still belong at their principal point of use.\\n- Consider a raised dishwasher for users who benefit, but validate approved support, niche, front mechanism, rack heights, and adjacent unloading space.\\n\\n## 4. Assign Contents Before Cabinet Sizes\\n\\nCreate the storage schedule first. Then fit catalog modules around the fixed zones.\\n\\n| Contents | Preferred home | Checks |\\n| --- | --- | --- |\\n| Dining cutlery | Shallow upper drawer near dishwasher and dish storage. | Organizer fits internally; accessible with dishwasher open. |\\n| Everyday plates/bowls | Full-extension drawer in the same or nearby bank. | Plate diameter, stack height, restraint, loaded runner capacity, comfortable lifting height. |\\n| Glasses/cups | Reachable nearby shelf, lift-front cabinet, or suitable drawer. | Safe reach, glass height, retention, opening clearance; not forced overhead. |\\n| Preparation knives/tools | Upper drawer at principal preparation surface. | Blade protection, child security, separation from dining cutlery. |\\n| Boards/trays | Vertical divider storage near preparation/oven. | Actual tray dimensions and removal path. |\\n| Pans/pots/lids | Full-extension storage beside or below hob where permitted. | Heat separation, hob underside, ventilation and extractor/oven volume. |\\n| Spices/oils | Near preparation/cooking, protected from heat/light/moisture. | Not directly exposed to hob heat or steam. |\\n| Mixing bowls, scales, baking tools | Preparation/baking zone. | Nesting, appliance weight, lifting distance, and usable drawer height. |\\n| Dry food | Pantry/pull-outs near grocery landing and preparation. | Stock volume, visibility, shelf adjustment, runner loads. |\\n| Waste/recycling | Accessible from preparation and sink. | Local sorting streams, bin removal, odours, and access while dishwasher is open. |\\n| Cleaning chemicals | Separate secure storage, often near sink. | No food/clean-utensil mixing; child access, plumbing and leak clearance. |\\n| Food containers/lids | Near preparation, leftovers packing, and dishwasher. | Paired or divided organization; capacity for actual inventory. |\\n| Small appliances | At use location or reachable storage. | Operating footprint, lid opening, steam, power, ventilation, weight. |\\n| Rarely used items | Less accessible but safe locations. | Do not put heavy objects overhead simply because they are infrequent. |\\n\\nPrefer full-extension drawers for frequently used base storage [S4, S5]. Upper shallow drawers suit small tools; deeper drawers suit bulky items, but choose heights from actual contents, not a fixed three-drawer formula. Prioritize heavy frequently used items at a comfortable lifting height rather than automatically on the lowest level.\\n\\nCompare wide drawer banks with multiple narrow cabinets using usable capacity, load, cost, and multi-user access. A wide open drawer can block another cook. Compare corner mechanisms with a deliberately unused corner plus accessible straight drawers; maximum gross volume is not necessarily best value.\\n\\nFor each cabinet record: `id`, `zone`, `catalog_id_or_provisional`, external dimensions, usable internal dimensions, contents, load, opening direction/extension, fittings, and reason for location. Include fillers, end panels, scribes, plinths, supports, and tolerances in each run. Never assume nominal width equals usable storage or appliance niche width.\\n\\n## 5. Generate and Check Alternatives\\n\\nDevelop two or three genuinely different feasible options when geometry permits, for example retained services versus improved workflow. Do not force an island or a U-layout into a room that cannot support it.\\n\\nFor each option:\\n\\n1. Place immovable constraints and reserve circulation/accessibility envelopes.\\n2. Locate sink, principal preparation area, hob/extraction, and refrigerator landing.\\n3. Fit dishwasher, waste, and nearby clean storage as a working group.\\n4. Allocate remaining storage and secondary tasks from the inventory.\\n5. Fit actual modules, fillers, worktops, panels, and service voids.\\n6. Check 3D fit, closed projections, full swept openings, service access, ventilation, and installation tolerances.\\n7. Run the task trials below. Repair hard failures before comparing soft preferences.\\n\\nRequired trials: unload a full dishwasher; prepare/cook a typical meal; drain a heavy pot; set/clear the table; put away groceries; remove waste; and let a second person reach drinks while cooking continues. Include the actual accessibility/child-use scenarios in the brief.\\n\\nCheck necessary simultaneous openings, especially dishwasher plus receiving drawer, refrigerator door plus internal drawer, sink/waste plus dishwasher, and perpendicular corner units. Not every door must open simultaneously, but the normal task combinations must work. Record remaining conflicts and their consequences.\\n\\nMeasure travel along collision-free walkable paths between usable standing positions, with task-specific openings represented. Do not measure straight through an island or across an open door. Without a geometry/path tool, use a clearly labeled manual estimate or `unknown`; do not fabricate precision.\\n\\n### Compare Everyday Effort\\n\\nUse lexicographic priorities: hard feasibility first, essential usability/storage second, daily effort third, then cost/style trade-offs within the agreed brief.\\n\\nFor a transparent optional distance estimate, calculate:\\n\\n`daily_travel_m = sum(task_cycles_per_day * sum(trip_count_per_leg * walkable_leg_length_m))`\\n\\nDefine each leg as a one-way movement. Include return legs explicitly where they occur. For unloading, use realistic batches carried per trip, not one trip per plate and not an implausibly heavy stack. Use the same inventory, carry capacity, and task frequencies for every option. Label assumed frequencies and distances.\\n\\nReport bending/high reaching, awkward lifts, door conflicts, and traffic crossings separately; do not add metres, counts, and money without explicit normalization and user-agreed weights. Never label a heuristic score a certified optimum or claim percentage savings without a baseline calculation.\\n\\n## 6. Deliver the Plan\\n\\nReturn a concise recommendation followed by:\\n\\n1. Brief, assumptions, missing measurements, and readiness status.\\n2. Dimensioned layout, orientation, appliance locations, and clear work surfaces. If no drawing tool exists, supply wall-by-wall cabinet sequences with dimensions, not an invented rendered plan.\\n3. Cabinet/drawer schedule specifying exactly what goes where.\\n4. Dishwasher-unloading explanation: standing position, receiving drawers/cup storage, openings, paths, and compromises.\\n5. Alternatives table: hard failures/unknowns, preparation space, usable storage, travel estimate, ergonomics, installed cost confidence, and trade-offs.\\n6. Constraint report with rule IDs, measurement definitions, evidence, pass/fail/unknown, and remedies.\\n7. Action list assigning survey, electrical, plumbing, ventilation, structural, accessibility, and installation checks to the appropriate reviewer.\\n\\nUse the status `concept`, `dimensionally_checked`, or `ready_for_professional_order_review`. The last status requires verified survey, exact product compatibility, complete parts/cost scope, and no unresolved hard constraint. It is not professional installation approval. When required reviewers approve, record who approved what and against which plan/manual revisions before any separate order authorization.\\n\\nIf no feasible layout exists, identify the conflicting constraints and smallest changes to consider, such as reducing an island, changing an appliance, or obtaining approval to relocate services. Never silently shrink a required clearance or alter a user must-have.\\n\\n## Quality Checks for This Skill\\n\\nBefore delivering a plan, verify these counterexamples are handled correctly:\\n\\n- Sink beside hob: report preparation-space and installation checks, not an invented EU prohibition.\\n- Dish drawer close to dishwasher but behind its open door: reject the unloading arrangement despite the short nominal distance.\\n- Short route through an island: replace it with a walkable route or mark distance unknown.\\n- Attractive layout with unknown hood clearance: keep installation readiness blocked.\\n- Single-wall or mixed-handed kitchen: use task-based zoning without forcing a triangle or handedness rule.\\n- Wheelchair brief: invoke applicable accessibility checks and user trials; a generic aisle recommendation is insufficient.\\n- Best geometric score but insufficient plate storage or overloaded drawers: do not recommend until capacity/load are resolved.\\n\"","export default \"# Kitchen Planning Evidence and Constraints\\n\\nResearch checked: 2026-10-09. Scope: residential kitchens, Germany/EU default. This is an original synthesis of public guidance, not a reproduction of a standard, a legal opinion, or an installation specification.\\n\\n## Evidence Boundaries\\n\\nAMK, Blum, and IKEA offer useful planning guidance; their editorial advice is not law. Product marketing is not proof of compatibility or universal ergonomic superiority. A named standard is mandatory only where applicable through law, contract, or the project brief; establish that applicability with qualified reviewers.\\n\\nShort source IDs refer to the optional [source catalog](./source-catalog.md), which holds URLs, publication details, and research notes. Do not load it for routine planning; consult it only for source verification, provenance/citation questions, or guidance updates. Rule classifications and operational qualifications remain in this reference.\\n\\nThe full DIN standard and project-specific appliance installation manuals were not examined. Numerical clearance requirements for a real product therefore remain to be supplied. Verify current applicable requirements and exact product instructions for each project; the research date does not establish a document's technical currency.\\n\\nSome general advice is too absolute to reuse literally. For example, induction surfaces can remain hot from cookware, lift-up doors still need head/ceiling/reach checks, and handedness does not determine a whole household's best layout. Apply task and product checks rather than repeating marketing assurances.\\n\\n## Dimensions and How to Use Them\\n\\nAll dimensions below are in mm. Label the rule class and source whenever presenting them to a customer.\\n\\n| Topic | Starting guidance | Status and measurement |\\n| --- | --- | --- |\\n| Main preparation width | Approximately 900; Blum advises at least 800 for comfortable preparation. | Published ergonomic recommendation [S3], not a statutory minimum. Clear usable work surface, preferably between sink and hob; not centre-to-centre distance. |\\n| Single-cook working aisle | Explore roughly 1000-1200 initially. | This skill's concept-sizing heuristic, not a sourced legal minimum. Measure the narrowest gap between finished closed projections, then test open appliances and the user. |\\n| Shared working aisle | Explore roughly 1200-1500 initially. | Concept-sizing heuristic only. Simultaneous work, carry tasks, and passage can need more; extra width also lengthens transfers. |\\n| Standing preparation height | Start near measured elbow height minus 150. | AMK recommendation [S1]; test in usual footwear with a mock-up. Sink depth and cookware change effective task height. No universal 900-high worktop. |\\n| Accessible kitchen movement space | The DIN 18040-2 secondary summary describes 1200 x 1200, and 1500 x 1500 for wheelchair use; front clearance depths of 1200 and 1500 respectively. | [S7] is a secondary explanation, not the standard itself. Confirm current applicable provisions, including the wheelchair-specific category, and all other access requirements. These are not universal minimum kitchen dimensions. |\\n| Dishwasher to dish storage | Comfortable turn or short step where feasible. | Adjacency principle [S4]; no universal maximum distance established by this research. Open-state usability determines success. |\\n| Hob/oven/fridge landing | Reserve usable nearby surface sized for the actual pan, tray, or grocery load. | Functional planning recommendation. Do not invent a universal legal landing width. The hot-tray route must be safe with the appliance door open. |\\n| Hood, hob, combustible surfaces | Use exact product and applicable local requirements. | No generic numeric default. Check all applicable instructions; resolving a conflict may require changing products. |\\n| Cut-out webs, overhangs, supports | Use material/fabricator specifications. | No generic numeric default; material, thickness, cut-outs, support and installation details matter. |\\n| Drawers, fronts, fillers, service voids | Use selected cabinet/appliance system drawings. | Catalog-specific; never insert an arbitrary filler and assume collision/installation issues are resolved. |\\n\\nA concept aisle width is not the free width remaining during use. For an illustrative opposing arrangement only, a 1200 aisle minus a 600 dishwasher-door projection minus a 500 drawer projection leaves just 100 between the open fronts. That is not adequate standing space between them. Real doors, racks, handles, body envelopes, and sideways access require actual drawings and task simulation. The numbers here are hypothetical, not product specifications.\\n\\n## Installation and Usability Checklist\\n\\nUse the IDs below in the project's constraint register. These are check categories: obtain evidence to establish the exact hard requirement or recommendation for each project. Mark unknowns explicitly.\\n\\n| ID | Check | Evidence or required outcome |\\n| --- | --- | --- |\\n| GEO-01 | Verified geometry | Finished dimensions, out-of-square walls, slopes, trims, levels, and measurement tolerance are represented. No fit claim based only on photos. |\\n| GEO-02 | Circulation and exit | Doors, clear passages, room access and applicable escape requirements remain usable. Assess appliance-open task states and occupants. |\\n| GEO-03 | Collision volumes | Check full door/drawer travel, handles, lift fronts, internal pull-outs, adjacent fronts, and head clearance. Closed-box collision tests are insufficient. |\\n| GEO-04 | Windows and heat | Tap does not prevent required window operation. Window/blind/curtain position, hob heat, drafts, splash exposure and required access are reviewed. |\\n| GEO-05 | Seating and island | Account for occupied seats, pulled-out chairs, knee space, passage and hot/splash zones. Do not double-count the same area for incompatible simultaneous uses. |\\n| FIT-01 | Cabinet run and niches | Include end panels, corner solutions, fillers, scribes, wall tolerances and actual appliance niches, not just nominal cabinet widths. |\\n| FIT-02 | Front and plinth systems | Integrated dishwasher front weight/height, fixed or sliding hinge, plinth sweep, mounting and countertop protection match the exact model. |\\n| FIT-03 | Refrigerator operation | Required opening angle permits internal drawers/shelves to operate and be removed; wall stand-off, hinges and ventilation are correct. |\\n| FIT-04 | Hob underside and extraction | Body, induction cooling, required separation, cables, downdraft motor/duct/filter and drawers do not compete for the same volume. |\\n| FIT-05 | Oven and microwave | Approved niche, ventilation, door travel and shelf reach; hot vessels can be removed safely to a landing surface. A high oven must not require lifting hot trays above the user's safe reach. |\\n| FIT-06 | Raised appliances | Support structure, fixing, manufacturer approval and reachable controls/racks are verified. Do not put a floor-supported appliance on an improvised shelf. |\\n| WAT-01 | Sink assembly | Bowl, drainer, clips, tap, waste, trap, hoses, drawers and bins fit together; servicing remains possible. |\\n| WAT-02 | Water and drainage | Qualified installer verifies supplies, pressure, hot-water compatibility, drainage route/levels, appliance hose limits and required backflow protection. Proximity alone proves none of these. |\\n| WAT-03 | Shutoff and leak access | Isolation, connections and leak-protection equipment remain accessible as required; no pinched hoses or inaccessible maintenance points. |\\n| WAT-04 | Special water equipment | Boiling/chilled/carbonated/filter systems have approved taps, tank/filter/cylinder space, ventilation, power, maintenance and child protection. |\\n| ELE-01 | Electrical design | Qualified electrician verifies available supply, connected loads, circuits, protective devices, earthing, isolation and socket installation under applicable rules. |\\n| ELE-02 | Socket and cable placement | Plan for all fixed and small appliances, lighting and powered fittings. Keep cords out of wet/hot areas and across no circulation route; verify plugs do not consume a prohibited niche/service volume. |\\n| ELE-03 | No invented wet-area rule | Do not transpose bathroom electrical zones into a kitchen or assert a blanket socket-to-sink distance without an applicable source. Obtain the electrician's project-specific layout. |\\n| GAS-01 | Gas equipment | Approved professional checks supply, isolation, installation, ventilation and appliance-specific combustible clearances. No DIY connection instructions. |\\n| VEN-01 | Extraction choice | Establish exhaust or recirculation early. Check hood capture at the actual hob, installed airflow, noise, filter access, duct dimensions, bends, outlet and replacement-air strategy. |\\n| VEN-02 | Recirculation limits | Recirculation normally does not remove cooking moisture outdoors and is not a substitute for necessary room ventilation. Check system-specific requirements. |\\n| VEN-03 | Combustion interaction | Exhaust plus a room-air-dependent fireplace/heater triggers professional pressure/backdraft review with the responsible chimney sweep and ventilation specialist. Do not assume a window switch alone makes the system safe. |\\n| VEN-04 | Building permissions | Check landlord/owners' association approvals, facade penetrations, fire separations, communal shafts and whole-dwelling ventilation interactions. |\\n| TOP-01 | Worktop structure | Fabricator verifies cut-out spacing, edge webs, joint locations, supports, spans, overhangs, thermal limits and installation method. |\\n| TOP-02 | Water and steam protection | Seal/protect cut-outs, joints, sink area and dishwasher edges as specified; account for automatic-opening dishwasher steam. |\\n| STR-01 | Fixings and stability | Suitable wall fixings, rails, suspended loads, tall-unit restraint, island support and loaded drawers. Check floor/underfloor services before drilling. |\\n| STR-02 | Structural alterations | No wall removal or structural drilling assumption without qualified assessment and required permissions. |\\n| USE-01 | Preparation and landings | Real unobstructed preparation and grocery/hot-vessel landing space remains after permanent countertop items are placed. |\\n| USE-02 | Unloading | Dishwasher, rack, receiving storage and user can occupy needed positions together; no stepping over the door or excessive reaching. |\\n| USE-03 | Waste and hygiene | Scrape/sort/load route works; bins can be removed and cleaned. Separate chemicals from food/clean items; provide cleanable food-contact surfaces and drying space. |\\n| USE-04 | Storage capacity and loads | Actual inventory fits internally with chosen organizers and runner ratings. Record spare capacity if requested; do not invent a mandatory percentage. |\\n| USE-05 | Multi-user tasks | Test concurrent cooking, dish handling, drinks access and table setting; identify crossings and bottlenecks. |\\n| ACC-01 | Accessibility | Confirm required standard/category; check turning and approach spaces, knee/toe clearance, seated reach, controls, grip/force, task height and protected hot pipes. Test with the actual user/mobility aid. |\\n| SAFE-01 | Children and burns | Secure knives/chemicals, review reachable controls and hot-water dispensing, prevent pot-handle exposure to traffic/seating. Induction still has residual heat; child locks do not replace supervision. |\\n| SAFE-02 | Flooring and edges | Review slip/trip risk, thresholds, protrusions, sharp corners and cleanability. Do not let loose mats create an access hazard. |\\n| LGT-01 | Lighting | Illuminate preparation, sink and hob without the user casting a working shadow. Check glare, contrast, controls and usable light beneath cabinets; lighting drivers remain serviceable. |\\n| ENV-01 | Comfort and maintenance | Compare actual appliance noise, energy/water data, extractor filter costs, cleanability, material heat/moisture resistance and repairability. Verify current product labels. |\\n| SRV-01 | Replacement access | Appliances can be isolated, removed and replaced after flooring/worktops are installed; filters, traps, drivers and fixings can be serviced. |\\n| ORD-01 | Complete order scope | Include appliances, cabinets, fronts, hinges, runners, handles, fillers, panels, plinths, feet, rails, supports, worktops, cut-outs, lighting, extraction, fittings, delivery, installation and service work. |\\n| ORD-02 | Release gate | Final survey, product/manual revisions, costs, permissions and responsible professional checks match the exact proposed order. Obtain explicit order authorization. |\\n\\n## Worked Arrangement: Pattern, Not Template\\n\\nAn illustrative working run can be:\\n\\n`[dish/cutlery drawers] [dishwasher] [sink] [prep drawers + clear worktop] [hob/cookware]`\\n\\nDaily cups/glasses can occupy comfortably reachable storage above the dish bank or another nearby accessible location. Waste can be under the sink or in a separate nearby pull-out if loading, preparation and bin removal all work. Do not consume the only preparation drawer space without a replacement.\\n\\nThis pattern places clean storage on one side of cleanup and preparation on the other. It is neither a complete kitchen nor a mandatory sequence: refrigerator/pantry, oven, landing surfaces, end conditions and services must still be located. Mirror or split the run when the room and users benefit. A hob at the run's exposed end still needs its verified clearances and usable landing arrangement.\\n\\nFor an L-layout, a drawer around the corner from the dishwasher may be physically close but impossible to open during unloading. For a galley, opposing dish drawers may work or may block the user's standing position. The decisive check is the open-state task, not the diagram's apparent neatness.\\n\\n### Transparent Travel Example\\n\\nSuppose two otherwise feasible options each need four storage transfers per dishwasher cycle. Assume three return legs to the dishwasher before the final transfer, one cycle daily, and equal one-way path lengths in either direction:\\n\\n- Option A: 1.0 m per leg -> `(4 + 3) * 1.0 = 7.0 m` per cycle.\\n- Option B: 2.5 m per leg -> `(4 + 3) * 2.5 = 17.5 m` per cycle.\\n- Difference: 10.5 m per cycle under these assumptions, excluding any final return and other kitchen tasks.\\n\\nThese are illustrative distances and batch counts, not research results. Do not extrapolate time or lifetime savings without measurements. A comfortable turn may produce almost no walking but still involve awkward reaching; report that separately. An option with an obstructed unloading path is infeasible regardless of its calculated distance.\\n\\n## Maintenance and Unverified Requirements\\n\\nThe checklist is deliberately broad but not exhaustive. Actual regulatory requirements, permitted clearances, and compatibility depend on the site, products and users. Obtain the current applicable primary sources, exact installation manuals and qualified reviews before converting any unresolved checklist item into a pass.\\n\\nRevisit this reference when products, material systems, regulations or source guidance change. Keep the general workflow vendor-neutral; replace examples with the project's authorized catalog without losing the open-door, capacity, accessibility and safety checks.\\n\"","export default \"# Kitchen Planning Source Catalog\\n\\nOptional research reference. Load only to verify a source-backed claim, answer a provenance/citation question, or update the guidance. Routine planning does not require this file; the rules, classifications, and operational qualifications are in the skill and [planning reference](./planning-reference.md).\\n\\nResearch checked: 2026-10-09. Scope: residential kitchens, Germany/EU default. The sources below were retrieved for the stated topics. The full DIN standard, paid NKBA handbook, and project-specific appliance installation manuals were not examined. The retrieval date does not establish technical currency; verify current applicable requirements and exact product instructions for each real project.\\n\\n## Sources\\n\\n### S1. AMK: Planen und gestalten\\n\\nhttps://www.amk-ratgeber-kueche.de/kueche/planen-gestalten\\n\\nGerman kitchen-industry association guidance. Supports functional zones, point-of-use storage, approximately 150 mm elbow-to-worktop difference, individualized working heights, full-extension drawers, early service planning, lighting and accessibility considerations. This is consumer guidance, not a regulation or a complete technical standard. Do not adopt every safety/marketing statement literally; see the evidence boundaries in the planning reference.\\n\\n### S2. IKEA Germany: Gestaltungsideen fuer reibungslose Ablaeufe\\n\\nhttps://www.ikea.com/de/de/rooms/kitchen/how-to/kueche-effizient-planen-pub6d21e890/\\n\\nSupports generous preparation space between sink and hob, proximity of waste and dishwasher, and placing cookware/tools at their point of use. Uses the work triangle as a general planning aid. Does not establish a statutory sink-to-hob distance.\\n\\n### S3. Blum: Speisenvorbereitung leicht gemacht\\n\\nhttps://www.blum-inspirations.com/de-eu/wissen/speisenvorbereitung-leicht-gemacht-der-passende-schrank-unterstuetzt-sie-dabei\\n\\nManufacturer ergonomic guidance, article dated March 2022. Recommends a preparation area between sink and hob, approximately 900 mm wide, and advises at least 800 mm; preparation tools and bowls belong nearby in organized drawers. These dimensions are ergonomic recommendations, not proof of product clearance or German code compliance.\\n\\n### S4. Blum: Geschirr perfekt organisiert\\n\\nhttps://www.blum-inspirations.com/de-eu/wissen/geschirr-perfekt-organisiert-im-unterschrank-mit-auszuegen\\n\\nManufacturer guidance, article dated June 2022. Supports dining cutlery and dishes together in full-extension base storage, nearby cups/glasses, and proximity to the dishwasher to reduce unloading travel. It does not supply a universal maximum distance or guarantee collision-free access.\\n\\n### S5. Blum: Die ergonomische Kueche\\n\\nhttps://www.blum-inspirations.com/de-eu/wissen/die-ergonomische-kueche-das-muss-man-beachten\\n\\nManufacturer guidance, article dated July 2021. Explains access benefits of full-extension base drawers and overhead lift fronts versus projecting doors. Benefits still depend on actual reach, opening height, operating force and room geometry; powered fittings are optional, not necessary for every accessible kitchen.\\n\\n### S6. AMK: Geraetetechnik\\n\\nhttps://www.amk-ratgeber-kueche.de/kueche/geraetetechnik\\n\\nSupports early extraction planning, the importance of capture efficiency, storage consumed by downdraft equipment, and appliance feature/energy/noise considerations. Room-volume airflow rules of thumb alone do not constitute a ventilation design. The combustion-safety checklist in the planning reference is a professional-review trigger, not a quoted clearance rule from this page.\\n\\n### S7. nullbarriere.de: DIN 18040-2 Kuechen, Essplatz\\n\\nhttps://nullbarriere.de/din18040-2-kuechen.htm\\n\\nSpecialist secondary summary of German dwelling accessibility guidance. Describes 1200/1500 movement-space dimensions and wheelchair considerations. It is not the official DIN text. Verify the current standard, project category, legal/contractual applicability and complete requirements before claiming conformity.\\n\\n### S8. IKEA Germany: Kuechenplanung\\n\\nhttps://www.ikea.com/de/de/rooms/kitchen/kuechenplanung-pub6003162f/\\n\\nSupports surveying in mm, marking openings/services, and staged planning, checking, ordering and installation. Links to current system-specific planning and installation documents. Those documents and the chosen product manuals must be obtained for a real order.\\n\\n### S9. IKEA Germany: Schubladen organisieren\\n\\nhttps://www.ikea.com/de/de/rooms/kitchen/how-to/kuechenschraenke-und-schubladen-organisieren-8-ideen-die-zeit-und-platz-sparen-pube8ed7a50/\\n\\nSupports full-extension storage, functional grouping, protected knives, organizers and reachable everyday contents. Named fittings are examples, not a recommendation to adopt one vendor.\\n\\n### S10. NKBA Planning Guidelines: Regional Boundary\\n\\nhttps://nkba.org/planning-guidelines/\\n\\nThe public overview describes guidance intended for US/Canadian design practice and its code context. Only the overview was consulted, not the paid handbook. Do not label NKBA dimensions as German/EU requirements or cite handbook clauses not actually verified.\\n\"","export default \"---\\nname: kitchen-planning-fr\\ndescription: \\\"Plan or review a residential kitchen in France, from the measured brief to a proposal for professional order review. Use for French kitchen layouts, cuisine amenagee or equipee, NF C 15-100 planning checks, VMC and hood coordination, copropriete renovation constraints, furnished-rental equipment, sink/preparation/hob placement, dishwasher unloading, and cabinet or drawer allocation. France-first, metric guidance that distinguishes applicable requirements from ergonomic recommendations and household preferences. Not installation certification or a commercial-kitchen design standard.\\\"\\n---\\n\\n# Kitchen Planning for France\\n\\n## Purpose and scope\\n\\nProduce a usable, measurable residential kitchen proposal for a project in France. Default to millimetres and EUR; confirm territory, budget basis, building type, tenure, and work scope before applying requirements. Respond in the user's language; keep French trade terms when they improve coordination.\\n\\nThis is a self-contained specialization of the workspace kitchen-planning approach. It does not require loading the Germany/EU skill. Use [the planning reference](references/planning-reference.md) for detailed checks, evidence qualifications, and worked examples.\\n\\nThe [source catalog](references/source-catalog.md) is optional. Load it only to verify a claim, provide citations, or update guidance. Do not load the bibliography merely to resolve source IDs: operational qualifications are already in this skill and the planning reference.\\n\\n## What is specifically French?\\n\\nThere is no single \\\"normal European kitchen\\\" or uniform French kitchen style. French-market layout guidance uses the same preparation, cleaning, cooking, and point-of-use storage principles as other European guidance (FR-S5).\\n\\n| Planning topic | France-specific adaptation |\\n| --- | --- |\\n| Electrical installation | Establish the applicable NF C 15-100 edition and work scope; distinguish ordinary kitchen sockets from specialized appliance circuits. |\\n| Ventilation | Identify the actual natural ventilation or VMC system, collective or individual, before choosing a hood or moving a cooking zone. |\\n| Renovation authority | Ask about copropriete, landlord consent, common services, structure, and exterior alterations; do not treat a kitchen seller's drawing as permission. |\\n| Rental brief | Distinguish owner occupation, location nue, furnished principal-residence lease, and tourist accommodation; their equipment and legal scopes are not interchangeable. |\\n| Accessibility | Determine applicable French housing provisions and user needs. Do not relabel German DIN dimensions as French compliance. |\\n| Procurement | Resolve cuisine amenagee/equipee labels into an itemized equipment and works schedule, a devis, and an installed TTC budget. |\\n| Lifestyle | Ask about actual cooking, meals, pantry and serving needs. Gas, wine storage, an island, rustic fronts, and elaborate cooking are not national requirements. |\\n\\nThese topics are not all unique to France; their governing documents, terminology, and project decisions are localized here.\\n\\n## Authority and evidence\\n\\n- Classify constraints as `regulatory`, `manufacturer`, `site`, `user_must`, `recommendation`, or `preference`.\\n- The first four are hard constraints when applicable. Recommendations and preferences are soft and may be traded off explicitly.\\n- A published standard is not automatically a universal retroactive legal obligation. Establish the applicable regulation, standard edition, contract, project dates, and scope with the responsible professional.\\n- A manufacturer summary is not the full standard. A product-specific installation requirement is different from that manufacturer's general planning advice.\\n- Never convert an unknown to a pass. If requirements conflict, stop the affected decision and obtain clarification; do not select the convenient rule.\\n- Photographs, scans, inferred dimensions, catalog nominal widths, and AI drawings do not replace a site survey or exact product documentation.\\n- The planner's geometry, catalog, prices, and accepted design remain authoritative. Propose reversible edits and obtain acceptance before changing the design.\\n- Do not claim electrical, gas, structural, ventilation, accessibility, rental, or installation certification. Do not authorize purchases or works.\\n\\n## Workflow\\n\\n### 1. Establish the French project brief\\n\\nCollect only the missing facts needed for the next decision; allow assumptions for concepts, clearly marked.\\n\\n- Commune and territory: metropolitan France or the relevant overseas territory; do not silently apply metropolitan rules overseas.\\n- Apartment or house, approximate construction date, new build or existing dwelling, occupied or vacant during works.\\n- Owner or tenant; copropriete and syndic contact where relevant; private versus shared walls, ducts and service risers.\\n- Cosmetic replacement, partial technical renovation, complete electrical renovation, kitchen relocation, or structural alteration; project and permit/contract dates if relevant.\\n- Owner occupation, location nue, location meublee as a principal residence, bail mobilite, or tourist/secondary-residence use.\\n- Household size, simultaneous cooks, children, reach and mobility needs, wheelchair or seated work, and any applicable accessibility brief.\\n- Cooking frequency, appliance inventory, shopping/storage quantities, dining location, entertaining, and cleaning habits.\\n- Total installed budget in EUR TTC, retained items, time constraints, and responsibility for each trade.\\n\\nAsk whether the household needs a table/coin repas, separate dining area, cellier, baking area, coffee station, large serving dishes, or bottle storage. Derive dimensions from their inventory and routines, not nationality.\\n\\n### 2. Survey the room and services\\n\\nRecord wall lengths at relevant heights, diagonals, finished floor levels, ceiling height, wall build-ups, out-of-square corners, windows and opening arcs, doors, radiators, obstructions, and structural uncertainty.\\n\\nLocate water, waste, isolation valves, electrical outlets and known circuit identities, gas if present, ventilation terminals, air inlets, ducts, and service access. Record delivery access, stairs, lift restrictions, and worktop handling constraints.\\n\\nFor each fact capture `value`, `unit`, `source`, `verification_state`, and measurement uncertainty. Use `unknown`, `inferred`, `user_verified`, or `professionally_verified`. Measure service positions from a declared datum and finished floor; do not infer concealed routes from visible endpoints.\\n\\n### 3. Build the constraint register\\n\\nEach record needs:\\n\\n```text\\nid\\nclass\\napplicability\\nrequirement\\nmeasurement_definition\\nsource\\nstatus: pass | fail | unknown | not_applicable\\naffected_items\\nremedy_or_next_action\\n```\\n\\nRun the French context checks in the reference before freezing a layout. Identify the person responsible for resolving each technical unknown.\\n\\n- Electrical: confirm applicable edition and renovation scope with an electrician; reserve ordinary outlets separately from appliance connections. Socket count alone cannot establish compliance.\\n- Ventilation: a hood does not replace general dwelling ventilation (FR-S3). Preserve air inlets, transfer paths and extraction terminals. A visible communal shaft is not an approved powered-hood connection.\\n- Permissions: flag changes affecting shared services, structure, exterior outlets, or rented premises for the relevant professional, landlord, syndic, and authority checks before works.\\n- Rental: for a furnished principal-residence lease, check the scoped equipment list in the reference (FR-S4). Do not apply it to every kitchen or treat it as a complete rental-compliance assessment.\\n- Accessibility: establish applicable French requirements separately from ergonomic targets; unresolved legal applicability blocks a compliance claim, not an explicitly provisional concept.\\n\\n### 4. Arrange five functional zones\\n\\nMap food storage, preparation, cooking, cleaning, and clean storage/serving to real tasks. Prefer sink -> clear preparation surface -> hob, or its mirror, where the room allows it.\\n\\nProvide a continuous useful preparation area, not a nominal length occupied by a drainer, appliance, corner, or landing zone. As an ergonomic starting point, aim for about 900 mm clear width; around 800 mm is a lower recommendation from manufacturer planning guidance, not a French statutory minimum (FR-S6). Check actual tasks and product cutout/edge requirements separately.\\n\\nDo not invent a universal French 600 mm sink-to-hob prohibition. Assess splashing, heat, pan handles, worktop bridges, adjacent materials, and exact product requirements. A compact compliant layout can still have poor preparation space.\\n\\nKeep grocery-to-fridge, washing-to-preparation, cooking-to-serving, and dirty-dish routes short and unobstructed. A triangle is an optional analytical aid, not a rule; a linear kitchen can work well. Separate through-traffic from hot work where feasible.\\n\\nWhen the user does not name a place for the kitchen, plan it so that the sink stands near a water connection of the plan, if the room has one. The installation elements of the plan context list the water connections with their positions.\\n\\n### 5. Design dishwasher unloading and storage together\\n\\nStart with the dishwasher near the sink, subject to verified connection limits and usable access. Decide which side by actual unloading and loading tests, not handedness alone.\\n\\nTest all of these together: dishwasher door open, racks extended, receiving drawer or cupboard open, and a person standing and turning. Do not make the user step over the door or balance dishes while opening storage.\\n\\nPut everyday plates, bowls and dining cutlery close to a safe unloading position and the serving route. Put cooking utensils, pans and preparation tools near their use. Check that the shortest storage route remains accessible with doors open. A slightly longer unobstructed route can be better than blocked adjacent storage.\\n\\n### 6. Allocate cabinets and drawers by contents\\n\\nCreate a schedule with cabinet ID, location, contents, quantities, largest item size, usable internal dimensions, load limit, opening mechanism, access frequency, and service conflicts.\\n\\n- Use accessible drawers or pull-outs for frequently handled base storage where appropriate; check heavy dish stacks and hardware loads (FR-S7).\\n- Separate dining cutlery from cooking utensils. Give pans, lids, boards and trays usable storage near preparation/cooking.\\n- Size pantry storage to shopping habits; a cellier supplements but does not automatically replace daily point-of-use storage.\\n- Provide safe storage for knives and cleaning products, and a waste-sorting arrangement matching local collection and the household's carrying route.\\n- Keep shutoffs, traps, filters and appliance removal paths accessible. Under-sink space is not an empty rectangular cabinet volume.\\n- Use exact cabinet/appliance combinations: nominal 600 mm widths do not prove integration, ventilation, hinge, front, plinth or worktop compatibility.\\n\\n### 7. Compare feasible alternatives\\n\\nNormally compare two plausible layouts, such as a service-preserving option and a user-priority option. Include an island only if occupied circulation, services, budget and work surfaces support it.\\n\\nTest grocery unloading, preparing a meal, draining a hot pan, dishwasher loading/unloading, serving, waste removal, and two people sharing the room. Include chairs pulled out, doors and drawers open, and a person at the oven. Test task lighting, glare, extraction noise and sightlines for an open kitchen.\\n\\nUse 1000-1200 mm single-cook and 1200-1500 mm shared working aisles only as concept heuristics between the nearest closed projections, not French legal or wheelchair clearances. Then test actual open-state and occupied clearances; apply verified project requirements instead where stricter.\\n\\nFor repeated tasks, estimate:\\n\\n```text\\ndaily_travel_m = sum(task_cycles_per_day *\\n sum(trip_count_per_leg * walkable_leg_length_m))\\n```\\n\\nCount return trips explicitly. State assumptions; compare bending, awkward reaches, handling and collision risks separately. Do not present this proxy as a validated human-performance score.\\n\\n### 8. Resolve the devis and installation boundaries\\n\\nTranslate cuisine amenagee/equipee into explicit inclusions, never assumed legal definitions. List meubles, facades, fileurs, joues, plinthes, plan de travail, credence, evier, robinetterie, electromenager, and fittings as applicable.\\n\\nSeparate supply, delivery, carrying, removal/disposal, preparation works, plumbing, electrical/gas work, ventilation, fitting, worktop templating/cutouts, finishing, testing and handover. Record exclusions, tax basis, quote validity, allowances and who owns final measurements. Do not promise a reduced VAT rate or a fixed total without a verified quote.\\n\\nAsk the cuisiniste and trades to resolve interfaces before final ordering: sockets behind drawers, sink/trap versus bin, dishwasher front versus plinth, duct versus wall unit, and opening clearances versus fileurs are common coordination risks.\\n\\n### 9. Deliver and gate readiness\\n\\nProvide the brief and assumptions, dimensioned plan with opening envelopes, zone/task rationale, cabinet contents schedule, appliance/service schedule, constraint register, alternatives and trade-offs, installed-cost scope, and professional questions/next actions.\\n\\nUse one readiness status:\\n\\n- `concept`: assumptions or unresolved geometry/services remain; no order-ready implication.\\n- `dimensionally_checked`: stated geometry and operating envelopes checked against identified measurements and product data; list unresolved regulatory/technical matters separately.\\n- `ready_for_professional_order_review`: required survey, exact product compatibility, service feasibility, applicable permissions, and hard constraints have supporting evidence with no unresolved failures or unknowns. This still requires professional order review and is not installation approval or purchasing authorization.\\n\\nNever call a proposal \\\"French-compliant\\\" solely because it follows this skill.\\n\"","export default \"# France Kitchen Planning Reference\\n\\nOperational reference for [kitchen-planning-fr](../SKILL.md). Source IDs support traceability without requiring bibliography loading. Open the [optional source catalog](source-catalog.md) only for verification, citations or maintenance.\\n\\n## Evidence boundaries\\n\\nResearch reviewed on 2026-10-09. These are planning checks, not a complete French legal or installation specification. Refresh time-sensitive claims for the actual project. Full NF C 15-100 text, current project-specific accessibility provisions, and product-specific manuals were not inspected in this research.\\n\\nFrench-market planning guidance supports familiar workflow principles, not a separate national geometry (FR-S5). Do not infer household habits, a required style, or a gas preference from the country. Imported appliances and retained furniture need exact compatibility checks, not assumptions based on EU marketing.\\n\\n## French technical and project gates\\n\\n### Electrical scope and layout reservation\\n\\nLegrand's professional guide describes the NF C 15-100 series for new or entirely renovated low-voltage installations in France. It reports the 2024 revision, publication on 2024-08-23, and a 12-month overlap with the previous edition ending 2025-08-23; project reference dates include the contract, permit application or prior declaration (FR-S1). Schneider independently confirms a 2024 revision (FR-S2). These summaries do not determine a particular project's legal or contractual obligations.\\n\\nAsk the electrician to identify the applicable edition, reference date, affected circuits, work scope, protection and testing requirements. Do not assert that replacing cabinets, selling a dwelling, or changing one appliance automatically requires complete rewiring. Conversely, do not use \\\"existing installation\\\" as an exemption from addressing identified hazards or new-work requirements.\\n\\nUse these source-qualified reservations, not automatic compliance tests:\\n\\n| Situation | Reservation and qualification |\\n| --- | --- |\\n| Kitchen clearly greater than 4 m2 | Legrand reports at least six ordinary sockets on a dedicated kitchen circuit, including four above the worktop. Identify appliance connections separately (FR-S1). |\\n| Kitchen clearly less than 4 m2 | Legrand reports at least three ordinary sockets. Confirm applicable exception and placement with the electrician; reduced count is not proof of functional adequacy (FR-S1). |\\n| Exactly 4 m2, uncertain measurement, or open kitchen | The inspected web summary uses less-than/greater-than wording without resolving equality or area definition. Reserve six provisionally and keep applicability unknown until the electrician verifies the full rule. Do not encode a legal threshold from this ambiguity. |\\n| Hood outlet | Legrand describes an optional additional hood outlet at least 1800 mm above finished floor. This is an outlet position, NOT the hood-to-hob installation clearance (FR-S1). Confirm exact permitted position and product instructions. |\\n| Hob, oven, dishwasher and other substantial appliances | Record each model, rated load, connection method, required specialized circuit and isolation access. Have the electrician size and verify the installation. Ordinary socket count is not an appliance-circuit allowance. |\\n| Appliance operation | Verify available supply and simultaneous loads, including retained appliances. Do not assume an existing socket or adapter makes an imported appliance suitable. |\\n\\nAs a conservative planning rule, keep ordinary sockets and trailing leads away from sink and cooking surfaces and do not propose ordinary sockets directly above them. Have the electrician verify exact restrictions and hood exceptions against the applicable standard; this research did not independently verify the full placement clause. Do not import bathroom electrical volumes around a kitchen sink or assert an unsupported universal 600 mm sink/hob separation.\\n\\nCoordinate outlet positions with credence joints, wall units, drawer backs, appliance depth and accessibility. Do not supply DIY conductor, breaker or wiring instructions as part of a furniture plan. Add task lighting without assuming that a ceiling point alone lights preparation adequately.\\n\\n### Ventilation, extraction and gas\\n\\nA hood treats cooking emissions intermittently; dwelling ventilation renews indoor air more generally. Sauter's FAQ explains why a hood cannot replace VMC (FR-S3). This distinction does not prove that every existing French dwelling must receive the same mechanical system.\\n\\nSurvey natural ventilation, individual VMC, collective VMC, air inlets, transfer paths, kitchen extraction terminal, and any combustion appliance. Obtain the relevant design and maintenance information. Do not obstruct vents with cabinets or close a required air path during replacement works.\\n\\n- Recirculation filters return air to the room; do not count them as outdoor exhaust or as a substitute for moisture removal by dwelling ventilation.\\n- Dedicated outdoor extraction requires a feasible, authorized duct route and coordinated air supply. Confirm flow, pressure loss, noise, discharge, fire/acoustic provisions and service access professionally.\\n- Do not connect a powered hood to an unidentified communal duct or VMC terminal. Treat compatibility and permission as unresolved until the responsible ventilation professional and building representative confirm the design. No universal connection prohibition is claimed from the inspected sources.\\n- Where gas or another combustion appliance is present, obtain professional review of air supply and depressurization risks before changing extraction. Do not infer safety from a closed cabinet drawing.\\n- Product manuals determine hood clearance, duct arrangement, filters, maintenance and compatibility; generic advice is not installation evidence.\\n\\n### Copropriete, rented premises and works\\n\\nThese are due-diligence gates, not a sourced statement of voting thresholds or permit law. Determine ownership and permissions before relocating services, cutting walls, changing collective ventilation, penetrating floors, or adding a facade/roof outlet.\\n\\nRecord the reglement de copropriete, syndic response, any required authorization, landlord agreement where relevant, structural assessment, and any mairie/planning-authority requirement. A verbal sales assurance does not resolve these dependencies. Identify who verifies the applicable rules and what evidence is still missing.\\n\\nFor an older building, ask the responsible professional whether surveys for hazardous materials or other pre-work investigations are required before invasive works. Do not diagnose materials from a photograph.\\n\\n### Rental equipment branch\\n\\nService Public's furnished-equipment page, verified 2026-03-06, covers a furnished dwelling used as the tenant's principal residence, including bail mobilite (FR-S4). Its kitchen/meal-related minimum equipment includes:\\n\\n- Cooking plates.\\n- An oven OR a microwave, not necessarily both.\\n- A refrigerator and a freezer, OR a refrigerator with a freezing compartment reaching a maximum temperature of -6 C.\\n- Dishes sufficient for occupants' meals and cooking utensils.\\n- A table and seats, storage shelves, and lighting.\\n\\nThe full furnished-dwelling list also covers bedding, bedroom shading and appropriate cleaning equipment. An inventory and detailed furniture condition record accompany the lease. Kitchen planning alone cannot certify the whole dwelling.\\n\\nDo not add a dishwasher to this minimum list. Do not require luxurious fitted cabinets or apply this list to an owner-occupied home, location nue, or tourist rental. For those branches, identify the applicable requirements separately. The decency overview reviewed during research distinguishes metropolitan and overseas contexts but its detailed equipment sections were not inspected; do not infer that unfurnished rental means \\\"no kitchen obligations.\\\"\\n\\nIn a relevant furnished-rental project, separate `regulatory` minimum equipment from `user_must` additions and `preference` upgrades. Verify the current applicable legal basis before final review.\\n\\n### Accessibility\\n\\nConfirm whether French housing accessibility provisions apply to the building category, new/existing context, project date, dwelling status and work scope. Ask the responsible professional to supply current requirements and their measurement definitions, including any accessible/evolutive provisions relevant to the project.\\n\\nThe official-partner accessibility portal distinguishes new housing, existing housing and building types, but the inspected page was last updated in 2021 and warns of CCH recodification (FR-S8). It is orientation only, not current numerical kitchen-compliance evidence.\\n\\nDo not substitute German DIN, US guidance or a generic 1500 mm aisle for the applicable French rule. Separately test the actual user's turning, approach, knee/toe space, reach, handles, controls, sink protection, seated preparation and transfer needs. A user trial supplements, not replaces, applicable requirements.\\n\\n## Working dimensions and measurement definitions\\n\\n| Item | Concept starting point | Definition and authority |\\n| --- | --- | --- |\\n| Main preparation width | About 900 mm; around 800 mm as a lower ergonomic recommendation | Clear usable worktop between interfering features; manufacturer planning guidance, not French law (FR-S6). |\\n| Single-cook working aisle | 1000-1200 mm | Nearest closed projections, including handles; inherited planning heuristic, then test occupied/open states. |\\n| Shared working aisle | 1200-1500 mm | Same measurement; concept heuristic, not an accessibility standard. |\\n| Worktop height | User/task-specific | Trial with actual users, sink depth and hob/pan height; do not impose a fixed \\\"French height.\\\" |\\n| Appliance bay and ventilation | Exact selected system | Installation drawings, required air paths, fronts, fixings and service voids; never nominal cabinet width alone. |\\n| Sink/hob separation and worktop bridges | Product and task-specific | Distinguish clear preparation width from cutout-edge distances and structural bridges. |\\n| Accessibility dimensions | Project-specific, professionally verified | State current source, applicability and exact geometry before marking pass. |\\n\\n## Constraint checklist\\n\\nCreate project records from these categories; do not automatically mark the checklist passed. Applicable regulatory, manufacturer, site and user-must requirements are hard constraints. Record unknowns and their owners.\\n\\n| ID | Check and evidence needed |\\n| --- | --- |\\n| FR-CTX-01 | Territory, building type, tenure, lease branch and project dates established. |\\n| FR-CTX-02 | Scope of works and applicable technical/regulatory documents identified by responsible professionals. |\\n| FR-PER-01 | Shared property, structure, facade and communal-service alterations identified; permissions resolved where required. |\\n| FR-PER-02 | Landlord and project-specific pre-work survey/authority dependencies resolved where applicable. |\\n| FR-GEO-01 | Survey datums, finished surfaces, diagonals, tolerances and uncertainty recorded. |\\n| FR-GEO-02 | Window/door arcs, radiators, ceiling and service obstructions represented. |\\n| FR-GEO-03 | Delivery, lift/stair access, worktop transport and assembly path verified. |\\n| FR-FIT-01 | Cabinet runs include fileurs, joues, fronts, handles, plinths and installation tolerances. |\\n| FR-FIT-02 | Exact appliance niches, hinges, ventilation, front weights and door/plinth compatibility checked. |\\n| FR-FIT-03 | Drawers, corner mechanisms, appliances and neighboring doors tested together. |\\n| FR-FIT-04 | Walls/floors, cabinet fixings, suspended loads and worktop support verified. |\\n| FR-WAT-01 | Water, drain route, levels and proposed relocation feasible; not inferred from endpoints. |\\n| FR-WAT-02 | Valves, trap, bins, sink bowl and drawer envelopes compatible and accessible. |\\n| FR-WAT-03 | Dishwasher hose routing, limits and connection access match selected product. |\\n| FR-ELE-01 | Electrician confirms edition, reference date, work scope and applicable requirements. |\\n| FR-ELE-02 | Ordinary socket count, area interpretation and usable placement verified separately from appliance circuits. |\\n| FR-ELE-03 | Appliance loads, circuit provisions, supply, protection and isolation access professionally checked. |\\n| FR-ELE-04 | Outlet/lead positions coordinated with wet/hot areas, furniture and credence; lighting supports tasks. |\\n| FR-VEN-01 | Existing ventilation type, inlets, transfer paths and extraction terminals documented and preserved. |\\n| FR-VEN-02 | Hood mode, duct feasibility, air supply, collective-system compatibility and permissions verified. |\\n| FR-VEN-03 | Hood/product clearances, noise, filters and maintenance access checked. |\\n| FR-GAS-01 | Gas/combustion installation and extraction interaction professionally assessed where applicable. |\\n| FR-TOP-01 | Worktop cutouts, bridges, edge distances, joints and supports meet supplier requirements. |\\n| FR-TOP-02 | Splash/heat exposure and adjacent surface/material compatibility resolved. |\\n| FR-USE-01 | Continuous preparation surface remains usable with everyday appliances in place. |\\n| FR-USE-02 | Dishwasher unloading tested with racks, receiving storage and user present. |\\n| FR-USE-03 | Cabinet allocation reflects real contents, usable dimensions, loads and frequency. |\\n| FR-USE-04 | Grocery, cooking, serving and waste routes tested without unsafe crossings. |\\n| FR-USE-05 | Occupied chairs, multiple cooks and open oven/drawer states preserve required passage. |\\n| FR-ACC-01 | Applicable French accessibility requirements and actual user needs both addressed. |\\n| FR-SAF-01 | Hot-pan landing, child safety, knife/chemical storage and stable furniture addressed. |\\n| FR-SRV-01 | Appliance removal, shutoffs, filters and repair access remain possible. |\\n| FR-REN-01 | Correct lease/territory branch selected; relevant equipment inventory verified without overextending its scope. |\\n| FR-ORD-01 | Itemized supply/work/exclusion schedule and installed EUR TTC budget agreed. |\\n| FR-ORD-02 | Final measurements, exact products, technical interfaces, evidence and professional-review responsibilities resolved. |\\n\\n## Worked checks\\n\\n### Open-state dishwasher conflict\\n\\nA 1200 mm closed-front aisle looks generous. A dishwasher projects 600 mm into it and an opposing receiving drawer projects 500 mm. The residual gap is:\\n\\n```text\\n1200 - 600 - 500 = 100 mm\\n```\\n\\nThat is not usable standing/unloading space. It fails this simultaneous-use scenario even if neither closed cabinet footprint overlaps. Move the receiving storage, change opening direction/type or redesign the arrangement; then rerun the test with actual products and the user envelope.\\n\\n### Unloading travel\\n\\nAssume four equal batches carried from dishwasher to storage, three return trips, and start at the dishwasher/end at storage. For illustrative measured walkable routes of 1.0 m and 2.5 m:\\n\\n```text\\nnear_storage_m = (4 + 3) * 1.0 = 7.0\\nfar_storage_m = (4 + 3) * 2.5 = 17.5\\ndifference_per_cycle_m = 17.5 - 7.0 = 10.5\\n```\\n\\nDo not use straight-line cabinet distances through open doors. The shorter route wins only if it remains safe and usable; bending and load handling need separate assessment.\\n\\n### French socket-count boundary\\n\\nA kitchen is measured at 4.0 m2 with uncertainty, and the seller proposes three ordinary sockets. The inspected manufacturer's less-than/greater-than summary does not settle the boundary. Reserve six provisionally, ask the electrician for the applicable area/count rule, and keep that requirement `unknown`. Even six visible sockets cannot prove circuit or placement compliance.\\n\\n### Furnished-rental distinction\\n\\nA principal-residence furnished letting has a hob, microwave and suitable refrigerator/freezing compartment but no conventional oven or dishwasher. The oven-or-microwave requirement is not failed merely because there is no conventional oven; the dishwasher is not on the inspected minimum list. Verify the rest of the equipment, lease scope and dwelling requirements before any compliance conclusion (FR-S4).\\n\\n### Shared-duct constraint beats preferred island\\n\\nA proposed island hood depends on an unidentified communal shaft. Do not draw a connection and mark ventilation passed. Keep feasibility/permission `unknown`; compare a service-preserving arrangement and a professionally assessed recirculation option that retains general ventilation. Neither becomes order-review-ready until all applicable hard constraints are resolved.\\n\\n## Final review questions\\n\\nCan a user prepare, cook, unload and serve with real occupied/open states? Are French project requirements evidenced rather than presumed? Can installers resolve every service/furniture interface from the documents? Are remaining assumptions visible and incompatible with any claimed readiness? If not, return the proposal to the appropriate earlier stage.\\n\"","export default \"# France Kitchen Planning Source Catalog\\n\\nOptional research/provenance file for [the skill](../SKILL.md) and [its operational reference](planning-reference.md). Do not load during routine planning unless a claim needs verification, the user requests citations, or guidance is being updated.\\n\\nReviewed on 2026-10-09. Source claims are paraphrased. A retrieval date is not a guarantee of current legal applicability. Commercial guidance is identified as such; general manufacturer advice is not a selected product's installation manual.\\n\\n## FR-S1: Legrand, NF C 15-100 professional guide\\n\\n- URL: https://www.legrand.fr/pro/normes-et-reglementations/norme-nf-c-15-100/norme-nf-c-15-100-suivez-le-guide\\n- Publisher/type: Legrand, manufacturer technical summary; page headed \\\"Norme NF C 15-100 en 2026 : on vous dit tout.\\\"\\n- Inspected: introduction, structure of the standard, circuits prises, and related scope text.\\n- Supports: 2024 revision and reported transition dates; new/entirely renovated installation context; ordinary kitchen socket reservations; separate specialized appliance connections; four worktop sockets within the six-socket case; optional additional hood outlet at 1800 mm minimum above finished floor.\\n- Limits: not the complete standard or an independent legal interpretation. The page uses `< 4 m2` and `> 4 m2` without explicitly resolving equality. Do not convert that gap into a legal rule. Its general appliance circuit examples are not a complete design for any particular supply or appliance inventory. Full placement clauses were not independently inspected.\\n- Use in skill: French electrical intake, reservations, electrician handoff, and boundary-case test. No DIY wiring instructions or automatic retrofit obligation.\\n\\n## FR-S2: Schneider Electric, NF C 15-100 overview\\n\\n- URL: https://www.se.com/fr/fr/work/support/local/reglementation/norme-nfc15-100/\\n- Publisher/type: Schneider Electric France, manufacturer standards overview.\\n- Supports: identification of the 2024 revision and availability of updated guidance; AFNOR standard versus explanatory guide distinction.\\n- Limits: detailed expandable answers and the downloadable guide were not inspected. Does not independently verify the numeric kitchen reservations used from FR-S1.\\n- Use in skill: cross-check of the revision context, not project compliance evidence.\\n\\n## FR-S3: Sauter, hood versus VMC\\n\\n- URL: https://www.confort-sauter.com/aide/vmc/installation/ma-hotte-de-cuisine-peut-elle-remplacer-une-vmc/\\n- Publisher/type: Sauter, manufacturer ventilation FAQ.\\n- Supports: continuous air renewal by VMC versus intermittent removal of cooking emissions by a hood; their complementary functions.\\n- Limits: blanket marketing statements about mandatory VMC are not used as universal retrofit law. This FAQ did not establish legal permission or a universal prohibition for powered-hood connection to a communal system.\\n- Use in skill: retain general ventilation, investigate the actual system, and require professional compatibility/permission evidence.\\n\\n## FR-S4: Service Public, furnished-dwelling equipment\\n\\n- URL: https://www.service-public.gouv.fr/particuliers/vosdroits/F34769\\n- Title: \\\"Bail d'habitation : qu'est-ce qu'un logement meuble ?\\\"\\n- Publisher/type: French public-service administrative guidance; page verification date 2026-03-06.\\n- Supports: minimum equipment for a furnished principal-residence lease, including bail mobilite; cooking plates, oven OR microwave, refrigerator/freezer alternative, dishes, utensils, table/seats, storage and lighting; inventory documentation.\\n- Limits: not a universal specification for owner occupation, location nue, holiday rentals or every overseas jurisdiction. The whole dwelling has additional requirements beyond the kitchen. Verify the current applicable legal basis and territorial scope for the project.\\n- Use in skill: scoped rental branch and equipment distinction, not a complete decency certificate.\\n\\n## FR-S5: IKEA France, practical kitchen layout\\n\\n- URL: https://www.ikea.com/fr/fr/rooms/kitchen/how-to/idees-dagencement-pratique-pour-la-cuisine-pub6d21e890/\\n- Title: \\\"Idees d'agencement pratique pour la cuisine.\\\"\\n- Publisher/type: French-market retailer planning advice.\\n- Supports: preparation between sink and cooking, nearby dishwasher/waste, storage at point of use, and several layout forms.\\n- Limits: activity-triangle and equal-distance language is advisory, not mandatory. One retailer cannot establish the prevalence of national household habits.\\n- Use in skill: evidence that familiar ergonomic principles also apply in France; no invented French triangle or style requirement.\\n\\n## FR-S6: Blum, preparation storage and worktop\\n\\n- URL: https://www.blum-inspirations.com/de-eu/wissen/speisenvorbereitung-leicht-gemacht-der-passende-schrank-unterstuetzt-sie-dabei\\n- Publisher/type: Blum, German-language European manufacturer ergonomics/planning advice, reused from the general kitchen research.\\n- Supports: preparation worktop and related storage; approximately 900 mm recommended working width and around 800 mm lower ergonomic recommendation.\\n- Limits: not French regulation and not a universal minimum. Usable clear surface, tasks, products and users matter more than a nominal run length.\\n- Use in skill: explicitly labeled transferable ergonomic recommendation, not country-specific compliance.\\n\\n## FR-S7: Blum, accessible dish storage\\n\\n- URL: https://www.blum-inspirations.com/de-eu/wissen/geschirr-perfekt-organisiert-im-unterschrank-mit-auszuegen\\n- Publisher/type: Blum, German-language European manufacturer storage guidance, reused from the general kitchen research.\\n- Supports: accessible base-unit pull-outs for dishes and handling-oriented storage allocation.\\n- Limits: commercial guidance; verify actual usable dimensions, loads and user reach. Does not prove that every drawer is suitable for every dish stack.\\n- Use in skill: contents-driven drawers and dishwasher-unloading evaluation.\\n\\n## FR-S8: Accessibility portal, housing applicability orientation\\n\\n- URL: https://www.accessibilite-batiment.fr/logements-neufs/generalites-et-definitions/code-de-la-construction-et-de-lhabitation.html\\n- Publisher/type: DHUP-CSTB-Cerema accessibility portal, regulatory orientation.\\n- Inspected: general distinctions for collective housing and individual houses; page update 2021-09-10 and warning concerning CCH recodification from 2021-07-01.\\n- Supports: the need to distinguish building categories, project context and applicable documents rather than treating every kitchen identically.\\n- Limits: old numbering and dated material; not relied on for a current legal determination or any French kitchen dimension. Current full applicable provisions must be obtained for the project.\\n- Use in skill: accessibility applicability gate; no imported DIN or unverified French numeric requirement.\\n\\n## Research exclusions and maintenance\\n\\n- Service Public's rental-decency overview at https://www.service-public.gouv.fr/particuliers/vosdroits/F2042 was only partially accessible. Its metropolitan/overseas distinction informed the intake; detailed kitchen-equipment provisions were not verified.\\n- IZI by EDF's kitchen-electrical article was inspected but not adopted as authority because its broad claims and comments contained ambiguities or conflicts. In particular, no universal 600 mm sink/hob rule, kitchen bathroom-like volumes, mandatory kitchen RJ45, or automatic whole-dwelling upgrade on sale is adopted.\\n- IKEA France's hood article was inspected but is not used for generic hood heights, filter lifetimes or claims that recirculation removes humidity outdoors.\\n- Primary ventilation legislation could not be retrieved from Legifrance during research. No numeric statutory ventilation rate or categorical communal-duct legal rule is asserted.\\n- Copropriete permissions, landlord agreement, quotations and trade coordination are practical due-diligence checks. Voting thresholds, permit procedures, statutory quote requirements and VAT rates were not established and are not prescribed.\\n- No primary text or current project-specific French accessibility clause was verified. Do not turn portal orientation into an accessibility certificate.\\n- Before updating a numeric requirement, check the full current source, territorial/project applicability, exceptions and measurement definition; update the operational guidance and source qualification together.\\n\"","export default \"---\\nname: living-room-planning\\ndescription: \\\"Plan or review a living room, lounge, sitting room, or Wohnzimmer using household activities, verified geometry, and practical furniture constraints. Use when arranging sofas, armchairs, recliners, sofa beds, coffee tables, TV/media units, bookshelves, or storage; comparing conversation and TV layouts; checking circulation, accessibility, lighting, glare, child safety, or open-plan living zones. Defaults to Germany/EU context and metric units; separates requirements from ergonomic recommendations and preferences. Includes operational checks and an optional research source catalog.\\\"\\n---\\n\\n# Living Room Planning\\n\\n## Purpose and loading policy\\n\\nCreate practical, explainable living-room proposals that work for the household's real activities. Optimize comfort, access, storage, and ease of changing activities before decorative composition or maximum furniture count.\\n\\nDefault to Germany/EU context, dimensions in millimetres, and costs in EUR unless the user specifies otherwise. Confirm the actual country and, where relevant, German federal state. There is no single set of EU living-room layout rules.\\n\\n- Read [the planning reference](./references/planning-reference.md) before applying numerical guidance, assessing accessibility or installation risks, or declaring a layout dimensionally checked.\\n- Read [the optional source catalog](./references/source-catalog.md) only to verify a source, answer provenance/citation questions, resolve disputed claims, or update guidance.\\n- Do not load the source catalog merely to resolve source IDs during routine planning. The operational reference contains the qualifications needed for normal use.\\n- This skill supports planning, not structural design, electrical installation, fire-safety approval, clinical assessment, or permission to purchase.\\n\\n## Non-negotiable discipline\\n\\n1. Distinguish measured facts, assumptions, user preferences, recommendations, and mandatory requirements.\\n2. Never infer exact room dimensions, wall construction, load capacity, or safe clearances from a photograph alone.\\n3. Preserve the existing planner's authoritative geometry, product catalog, and accepted design. Proposals are reversible drafts until explicitly accepted.\\n4. Check occupied, moving, and fully deployed furniture, not just closed footprints. A sofa bed's sleeping surface is not its overall deployed size.\\n5. Do not treat a reachable-looking gap, generic furniture dimension, or aesthetic rule as proof of accessibility or safety.\\n6. Keep required exits and escape openings usable in every relevant mode. A blocked exit is not acceptable because guest use is infrequent.\\n7. Unknown is not pass. Missing critical dimensions or installation evidence must remain visible.\\n8. Do not prescribe a TV, fireplace, large sectional sofa, rug, or symmetry unless it serves the brief.\\n\\n## 1. Establish the brief and survey\\n\\nAsk only questions that can change the next decision; group missing information instead of sending a long questionnaire. Start with daily occupants, activities, existing furniture to retain, room geometry, and budget. If measurements are missing, offer a labelled concept and a concise measurement list.\\n\\nCapture:\\n\\n| Subject | Required information |\\n| --- | --- |\\n| Household | Daily and visiting occupants; children; mobility aids; reach, vision, hearing, balance, transfer, and sensory needs; foreseeable changes |\\n| Activities | Conversation, TV/gaming, reading, music, play, exercise, hobbies, occasional work/dining/sleeping; priorities, frequency, duration, and simultaneous use |\\n| Geometry | Room outline, ceiling/slopes, columns, niches, skirtings, changes in level, actual door and window positions, sill heights, handles, opening arcs, thresholds |\\n| Connections | Entrance, adjacent rooms, kitchen/dining area, balcony/terrace, required exits and escape openings; routes used while carrying items |\\n| Services | Radiators, thermostats, ventilation openings, fireplace/stove and hearth, sockets, switches, data/TV points, ceiling outlets, fixed lighting |\\n| Daylight and sound | Window orientation, glare at typical viewing times, shading, street/neighbour noise, adjacent bedrooms, reflective surfaces |\\n| Products | Retained pieces and exact candidate models; external and usable internal dimensions, weight/load limits, open/deployed sizes, anchoring and ventilation instructions |\\n| Inventory | Books, games, toys, blankets, media devices, controllers, chargers, hobby/work items, guest bedding; quantities, sizes, weights, access frequency |\\n| Delivery and work | Building entrance, stairs, lift, door turns, package dimensions, assembly space, wall permissions, access for installers and later servicing |\\n| Preferences and cost | Must-keep items, comfort trials, style/materials, cleaning needs, budget including delivery/assembly, wiring, mounting, shading, lighting, and disposal |\\n\\nFor each critical fact record `value`, `unit`, `source`, `verification_state`, and uncertainty/tolerance. Use `unknown`, `inferred`, `user_verified`, or `professionally_verified`. A product's nominal width does not prove the available room width.\\n\\nCreate an activity table with `mode`, `users`, `frequency`, `simultaneous_activities`, `required_items`, `deployed_state`, and `reset_steps`. Distinguish daily seats from occasional guest seats. Do not count the same floor area twice for simultaneous activities.\\n\\n## 2. Build a constraint register\\n\\nUse these classes:\\n\\n- `regulatory`: verified, applicable local requirements; record jurisdiction and edition.\\n- `manufacturer`: exact product instructions, clearances, loads, mounting, and intended use.\\n- `site`: verified fixed geometry, services, structural limits, and permissions.\\n- `user_must`: explicit non-negotiable household requirements.\\n- `recommendation`: ergonomic or functional advice, including labelled planning heuristics.\\n- `preference`: negotiable visual or lifestyle choices.\\n\\nThe first four classes are hard constraints. The latter two are soft unless explicitly adopted as a project requirement. Identify safety hazards even when their legal classification is unverified; do not bury them in an aesthetic score. A user preference cannot waive a mandatory requirement.\\n\\nRecord `id`, `class`, `applicability`, `requirement`, `measurement_definition`, `source`, `status`, `affected_items`, and `remedy_or_next_action`. Status is `pass`, `fail`, `unknown`, or `not_applicable` with a reason. Include the room mode in each state-dependent check.\\n\\nResolve conflicting requirements explicitly. Reject hard failures from viable options; separate options needing missing evidence from checked options. Escalate wall loading, fixed electrics, combustion/hearth conditions, or accessibility compliance to the appropriate professional.\\n\\n## 3. Reserve routes and activity zones\\n\\n1. Mark fixed features, required access, opening arcs, and no-go areas before placing furniture.\\n2. Connect the entrance to used seats, storage, adjacent rooms, windows, and balcony along genuinely walkable paths.\\n3. Prefer through-routes outside the conversation group and TV sightline where geometry permits. Show the compromise when a through-room makes this impossible.\\n4. Size the main zone for daily activities; reserve secondary zones only where the brief requires them.\\n5. Test daylight and noisy/quiet activities together. A shelf or curtain can separate views without providing acoustic privacy.\\n6. Locate movable furniture's parking positions. A coffee table moved for a sofa bed must not be parked in a doorway or another required activity zone.\\n\\nPossible strategies include facing/angled seating for conversation, sofa plus movable chairs for mixed use, a media-oriented group, or distinct quiet/active zones. These are alternatives, not mandatory room types.\\n\\n## 4. Fit the seating to the users\\n\\n- Select usable seat width, seat depth, compressed seat height, support, armrests, and ease of standing through user trials, not a universal ideal sofa size.\\n- Count seats that people can actually use together. A chaise, corner junction, ottoman, or armless end is not automatically an equivalent full-time seat.\\n- For conversation, arrange faces so users can hear and see each other without sustained twisting. Try angled chairs or more than one small group before enlarging a distant perimeter arrangement.\\n- Check entry to each seat, knees/feet, standing, transfers, walking-aid parking, swivel arcs, recliner mechanisms, and access to controls.\\n- Position drinks, a book, glasses, and remotes within comfortable reach. A side table can serve a seat better than a large central table.\\n- Treat coffee-table reach space and through-circulation as different things. An easy-to-reach table gap is not a corridor.\\n- Verify sofa-bed deployment, bed-making, access to bedding, night-time routes, and the effort/strength needed to operate it. Do not assume an occasional sofa bed is suitable for regular sleep.\\n\\n## 5. Locate TV, media, and listening equipment\\n\\nOnly apply this step when relevant to the brief.\\n\\n1. Identify primary and secondary viewing seats and measure actual seated eye positions.\\n2. Start with the screen centre near seated eye level, then trial the real posture, screen size, subtitles, and viewing comfort. Do not choose a fixed mounting height from the floor alone (S3, S4).\\n3. Choose viewing distance with screen size, resolution, content, eyesight, and preference. There is no universal distance multiplier suitable for every user (S5).\\n4. Check horizontal viewing positions, head turning, and sightline obstruction from every claimed TV seat. The panel's specified viewing angle is not a comfort guarantee.\\n5. Check reflections from windows and luminaires at typical times. Side-on placement to windows is a candidate, not an automatic glare solution; verify with the actual room and shading.\\n6. Check exact TV foot spacing/depth, furniture load capacity, anti-tip measures, bracket compatibility, wall substrate, and cable strain through mount movement. A wider cabinet alone does not prevent tipping (S3, S8).\\n7. Allow actual device ventilation, connector depth, plug removal, service access, and remote/signal operation behind doors. An opening for cables does not establish adequate cooling.\\n8. Position speakers using product guidance, listening trials, and neighbour considerations. Do not promise acoustic isolation from rugs, curtains, or decorative panels.\\n\\nDo not default to a TV above a fireplace: both viewing posture and verified heat/installation limits must work. An unknown heat condition blocks mounting approval.\\n\\n## 6. Assign contents before choosing storage\\n\\n| Contents | Preferred relationship | Operational check |\\n| --- | --- | --- |\\n| Remotes, glasses, current book | At the relevant seat | Reach while seated; no risky leaning or trailing charger |\\n| Games and controllers | Near play/media area | Access and return without disconnecting equipment or clearing occupied seats |\\n| Toys | Near the agreed play area | Child access where appropriate; anchoring, lid/pinch risks, tidy-up route |\\n| Books and records | Near reading/listening area | Real shelf depth, load limits, adjustable spacing, safe retrieval |\\n| Throws and cushions | Near relaxation seats | Storage opens while people are seated; no need to empty the tabletop |\\n| Guest bedding | Near sofa bed | Retrieve before/during deployment; dry storage and manageable lifting |\\n| Work or hobby equipment | Near its use zone | Fast setup/reset, suitable work surface, secure storage where needed |\\n| Hazardous or fragile items | Controlled location | Access restrictions appropriate to household; height alone is not a lock |\\n\\nUse internal clear dimensions, hinges, drawer travel, shelf loads, and actual object sizes. Locate frequent items for easy retrieval; avoid heavy overhead storage. Compare closed storage for clutter control with open storage for access/display, without sacrificing equipment cooling.\\n\\nStorage should reduce repeated interruptions: getting up, asking someone to move, reaching across a screen, unloading a tabletop to lift a lid, or shifting furniture. Shorter walking distance is useful only when access remains safe and convenient.\\n\\n## 7. Integrate light, environment, and safety\\n\\n- Combine general, task, and ambient/accent lighting with independently usable controls (S2). Reading needs suitable light on the page, not just a bright room.\\n- Check source glare, reflected screen glare, contrast, shadows, and seated/standing sightlines. Place switches where users can reach them on entry and at key seats; retain usable non-app control.\\n- Plan cables and outlets before accepting floating furniture. Do not hide extension leads under rugs or use cable routing that creates trip, pinch, or heat hazards. Fixed electrical alterations require qualified work.\\n- Keep radiator heat flow, thermostat sensing, and ventilation unobstructed (S7). Check exact installation instructions and any cold/damp wall concern; do not invent a universal furniture-to-wall gap.\\n- Treat required furniture/TV anchoring as part of the layout. Verify suitable wall/floor construction and fixings; an unknown wall is not a passed mounting check (S8).\\n- Address climbing access to windows, accessible blind cords, unstable tall furniture, loose rugs, sharp/glass edges, hot surfaces, and moving mechanisms. Prefer cordless window coverings around young children; moving furniture alone does not eliminate cord hazards (S9).\\n- For echo, consider appropriate absorptive furnishings subject to cleaning, trip, and fire constraints. Speech privacy, bass transmission, and sound isolation require different assessment; do not invent decibel improvements.\\n- If sustained work or dining is required, check a suitable table/chair/task-light setup. A sofa with a laptop tray is not evidence of an ergonomic full-time workstation.\\n\\n## 8. Generate and test alternatives\\n\\nOffer two or three meaningfully different layouts when useful, not multiple cosmetic versions. Preserve existing furniture when it meets the brief. Explain when only one credible option fits.\\n\\nFor each option test the required states:\\n\\n- Normal day with the usual seats occupied.\\n- Conversation/guests with occasional seats placed and used.\\n- TV/gaming with sightlines, glare, and controller/device access.\\n- Reading/work/play occurring simultaneously where requested.\\n- Recliners, drawers, doors, swivel chairs, and sofa bed through their full motion and deployed states.\\n- Night-time access, window operation, cleaning, servicing, and eventual furniture removal.\\n\\nMeasure the narrowest clear route between actual obstacles, including occupied feet/knees and deployed parts. Check turning and approach geometry as well as width. Use tolerance-aware dimensions; marginal clearance with unverified geometry remains unknown.\\n\\nUse scaled geometry checks where available and full-size tape/cardboard mock-ups with user trials where practical. Describe exactly what was checked; a language-model review alone is not deterministic collision validation.\\n\\nCompare options by hard failures/unknowns first, then daily comfort, circulation, conversation/media suitability, storage access, reset effort, light/glare, maintenance, cost, and preferences. Let the user set priorities; do not invent authoritative scoring weights.\\n\\nCount furniture moves, lifting, setup time, interruptions, and actual walkable trips for repeated routines. State assumptions and frequency. Do not optimize walking distance at the expense of comfort, inclusion, or required access.\\n\\n## 9. Deliver the proposal\\n\\nProvide:\\n\\n1. Brief, priority activities, assumptions, and missing evidence.\\n2. Recommended layout and alternatives, using labelled walls or a defined coordinate origin; include external furniture dimensions and critical clearances.\\n3. Seating and storage assignments, TV/light relationships, services, and required anchors.\\n4. Mode-by-mode checks, worst pinch points, and the destination of every displaced item.\\n5. Constraint register with failures, unknowns, source type, and next action/owner.\\n6. Budget range, retained/new items, installation/delivery dependencies, and next measurements or trials.\\n7. An explicit readiness level.\\n\\nUse `concept` when dimensions or products are provisional. Use `dimensionally_checked` only for the listed modes and checks supported by verified geometry/product envelopes. Use `ready_for_professional_order_review` only when critical unknowns and hard failures are resolved and delivery/installation evidence is assembled. None of these labels authorizes purchase or certifies regulatory compliance; professional review and user acceptance remain separate.\\n\\n## Counterexample quality checks\\n\\nBefore concluding, reject these false passes:\\n\\n- The closed recliner leaves a wide route, but its footrest blocks the balcony when used.\\n- Six nominal sofa places exist, but two require twisting and one blocks access to another.\\n- A nearby storage ottoman is convenient only when nobody uses it and everything is removed from its lid.\\n- A sofa bed opens only after the coffee table is moved, with no safe parking place for that table.\\n- A low TV cabinet fits, but the television feet overhang or its anti-tip provision is unresolved.\\n- A 1500 mm square is shown somewhere in the room, but the wheelchair user cannot reach a seat, storage, or exit.\\n- A room divider hides a desk but does not make concurrent calls and television acoustically private.\\n- A layout photographs well but covers a radiator, blocks a window handle, or requires a cable across a walking route.\\n\"","export default \"# Living Room Planning Reference\\n\\nOperational guidance for the living-room-planning skill. Defaults: Germany/EU context, millimetres, EUR. Source IDs identify research without requiring bibliography loading.\\n\\nLoad [the optional source catalog](./source-catalog.md) only for source verification, citations/provenance, disputed claims, or maintenance. Do not load it just to resolve IDs in routine planning.\\n\\n## Evidence boundaries\\n\\n- S1-S3 are IKEA consumer guidance on activity zones, lighting, and TV furniture. They support design reasoning, not building-code compliance or endorsement of particular products.\\n- S4-S5 are Sony general support guidance on TV height and distance. They are not exact product installation manuals or universal health limits.\\n- S6 is a secondary summary of DIN 18040-2 living/sleeping-room accessibility. Its index identifies the 2011-09 edition. Verify the current edition, project applicability, state adoption, and any contractual requirements before treating a dimension as mandatory. The full standard was not reviewed.\\n- S7 is German consumer advice supporting unobstructed radiator heat flow and thermostat sensing, not a numerical clearance standard.\\n- S8-S9 are US CPSC safety guidance on tip-over and window-covering cords. The hazard principles are relevant; US legal provisions are not German/EU requirements.\\n- The workflow, check catalog, and examples below are planning synthesis. A source supports only the stated claim, not every adjacent check. Project-specific manuals, structural conditions, and local requirements still need verification.\\n\\n## Dimensions and measurement definitions\\n\\nThe heuristic rows below are deliberately provisional starting points for mock-ups. They are not sourced standards, minimum legal dimensions, accessibility specifications, or guarantees of comfort. Override them for actual users, geometry, products, and applicable requirements.\\n\\n| Topic | Starting guidance | Measurement and qualification |\\n| --- | --- | --- |\\n| Main walking route | Explore 900-1200 mm clear width | Skill heuristic for initial ordinary residential layouts; measure narrowest obstacle-to-obstacle gap in the relevant occupied mode. Passing, carrying, mobility aids, turns, or applicable rules may need more. This does not certify an escape route. |\\n| Seat to coffee table | Try 400-500 mm | Skill heuristic between seat front and table edge for reach and leg space; trial actual posture. Not a through-route or wheelchair-transfer clearance. Side tables or no central table may be better. |\\n| Conversation spacing | Trial roughly 1500-2500 mm between seated head positions | Skill heuristic for a small conversational group, not between sofa backs. Hearing, room noise, furniture angles, and personal space govern the result. |\\n| Turning/movement area | S6 reports 1200 x 1200 mm; 1500 x 1500 mm for unrestricted wheelchair use | Secondary DIN summary for relevant living/sleeping rooms. Distinguish general barrier-free from the R category; verify applicability and full provisions. A free square alone does not prove accessible use. |\\n| Space along/in front of furniture | S6 reports 900 mm depth; 1500 mm for unrestricted wheelchair use | Secondary summary; not a universal route-width substitute. Verify the actual approach, transfer, furniture function, and applicable category. |\\n| Seat dimensions | User- and product-specific | Measure usable width/depth and compressed seat height; trial support, feet placement, standing, and transfers. No fixed ideal dimensions specified here. |\\n| Screen centre height | Start near seated eye level (S3, S4) | Finished floor to centre of visible screen; use actual primary viewers and posture. Reclined viewing may require a different tested arrangement. |\\n| Viewing distance | No mandatory multiplier (S5) | Eye position to screen; note size, resolution, content, subtitles, and preference. Distinguish this from wall-to-sofa distance. |\\n| TV support/mount | Exact product dimensions and limits | Check TV feet, support depth, load rating, anchors, wall construction, bracket specification, and full movement envelope. Screen diagonal alone is insufficient. |\\n| Sofa bed/recliner | Exact fully deployed dimensions and motion | Include mechanisms, rear travel, user operation/standing, feet, bedding access, and displaced furniture. No generic clearance is approved. |\\n| Cabinet/device clearances | Exact manuals and usable internal space | Include plugs, cable bend space, drawer/door travel, ventilation, load capacity, and service removal. |\\n| Radiators, stove/hearth, cold walls | Site and product assessment | No universal gap. Keep heat flow and controls usable (S7); obtain verified combustion clearances and investigate moisture concerns. |\\n| Lighting | Activity-specific placement and controls (S2) | No mandatory domestic lux or colour-temperature target is established by this research. Agree needs; use photometric data/measurement for quantified claims. |\\n\\nOverlap of movement areas may be permissible in an applicable accessibility design, but do not overlap fixed obstacles or simultaneous occupied/deployed functions. Record exactly which states can share space and validate the applicable provisions.\\n\\n## Practical check catalog\\n\\nThese are check categories, not a claim that all checks apply or are legally required. Instantiate the relevant checks with the constraint class, measurement, mode, evidence, status, and next action. Preserve `unknown` where evidence is missing.\\n\\n| ID | Check | Failure or unresolved condition to expose |\\n| --- | --- | --- |\\n| GEO-01 | Survey and tolerances | Furniture accepted against estimated wall dimensions, unmeasured skirtings, slopes, or out-of-square corners |\\n| GEO-02 | Openings | Door/window arcs, handles, curtains, thresholds, or escape openings obstructed |\\n| GEO-03 | Route continuity | A nominal clear width exists locally but the full entrance-seat-storage-exit route fails |\\n| GEO-04 | Required access | Balcony, services, ventilation, cleaning, or emergency access sacrificed to furniture |\\n| USE-01 | Activity brief | Maximum seating or TV dominance chosen without household priorities |\\n| USE-02 | Simultaneous use | Work, play, conversation, or dining claim the same space at the same time |\\n| USE-03 | Real seating capacity | Corner/chaise/occasional places counted as equivalent comfortable daily seats |\\n| USE-04 | Seated comfort | Unsupported feet, excessive seat depth, difficult standing, or inaccessible controls |\\n| USE-05 | Conversation | Sustained twisting, blocked faces, distance/noise incompatible with hearing needs |\\n| USE-06 | Reach and standing | Table placement forces leaning or removes space for feet, standing, or transfers |\\n| FIT-01 | Actual external envelope | Product footprint excludes arms, legs, handles, overhang, or cables |\\n| FIT-02 | Motion and deployment | Recliner, swivel chair, drawer, or sofa-bed travel collides with people or objects |\\n| FIT-03 | Reset and parking | Displaced tables, cushions, bedding, or guest seats have no safe destination |\\n| FIT-04 | Delivery and assembly | Package or assembled piece cannot negotiate entry, stairs, lift, or room turns |\\n| STO-01 | Contents and loads | Object sizes/weights exceed usable shelf/drawer dimensions or ratings |\\n| STO-02 | Retrieval | Frequent items require moving occupants, unloading a lid, or crossing active viewing |\\n| STO-03 | Safe reach | Heavy overhead items, climbing, insecure hazardous contents, or inaccessible essentials |\\n| MED-01 | TV eye geometry | Screen height/distance/angle chosen without the primary viewers and actual screen |\\n| MED-02 | All claimed viewing seats | Obstructed picture, neck turning, subtitle difficulty, or unsuitable off-axis image |\\n| MED-03 | Glare | Window or luminaire reflections untested at relevant times |\\n| MED-04 | TV support and mounting | Feet overhang, inadequate loads, incompatible bracket, unknown substrate or fixing |\\n| MED-05 | Device operation | Cooling, cable/plug space, service removal, or remote/signal access missing |\\n| LGT-01 | General/task/ambient light | One source cannot serve agreed activities or leaves routes inadequately visible |\\n| LGT-02 | Control and glare | Unreachable controls, app-only dependency, glare or harsh contrast at a used seat |\\n| ENV-01 | Heating and ventilation | Sofa, cabinetry, or curtains obstruct radiator flow, thermostat sensing, or vents |\\n| ENV-02 | Moisture and finishes | Cold/damp wall concern ignored; finishes/rugs unsuitable for actual conditions |\\n| ENV-03 | Acoustic compatibility | Visual screen treated as sound isolation; no plan for concurrent noisy/quiet use |\\n| ACC-01 | Accessible movement | Applicable clear areas, approaches, turning, and route continuity not verified |\\n| ACC-02 | Inclusive use | Seat transfer, aid parking, reach, contrast, hearing, or control needs not met |\\n| SAFE-01 | Stability and anchoring | Furniture, TV, or room divider lacks required stability/anchors and verified substrate |\\n| SAFE-02 | Child/window safety | Climbing route, accessible blind cord, pinch/lid risk, or hazardous contents unresolved |\\n| SAFE-03 | Trips and impact | Loose rug edges, trailing leads, low unseen obstacles, sharp/glass edges on routes |\\n| SAFE-04 | Heat and combustion | Unverified stove/hearth/TV relationship, combustible furnishings, or obstructed provisions |\\n| SRV-01 | Power and data | Unsafe extension routing, pinched leads, insufficient outlets, or unapproved fixed work |\\n| ORD-01 | Ordering evidence | Product variants, prices, measurements, permissions, or installation checks unresolved |\\n| ORD-02 | Readiness claim | Concept labelled installation-ready, unverified checks passed, or approval implied |\\n\\n## Worked examples\\n\\nAll dimensions, timings, and counts in these examples are invented teaching inputs, not recommended product clearances or measured performance.\\n\\n### 1. Closed-state route that fails when used\\n\\nA straight passage between a closed recliner front and a cabinet front is 1250 mm. In the same cross-section, the footrest extends 550 mm into the passage and an opposing drawer extends 400 mm.\\n\\n```text\\nremaining_gap_mm = 1250 - 550 - 400 = 300\\n```\\n\\nThe positive gap does not imply a usable route. Feet, the person retrieving contents, and approach/turning space have not even been included. It fails an agreed 900 mm project route target. If this is the only access to an exit, rejecting the simultaneous state alone is not a sufficient remedy; relocate or resize furniture so required access remains usable in intended operation.\\n\\nThis subtraction is valid only for aligned projections at that cross-section. Offset furniture, curves, swing arcs, and room turns require actual geometry checks.\\n\\n### 2. Sofa-bed mode includes its displaced furniture\\n\\nA room has 3500 mm clear depth on the deployment axis. The bed's verified overall deployed depth is 2200 mm and the opposite cabinet is 400 mm deep.\\n\\n```text\\nnominal_foot_gap_mm = 3500 - 2200 - 400 = 900\\n```\\n\\nThis is not yet a pass: check doors, drawer access, operator standing, side approach, night-time route, and tolerances. A 600 mm deep coffee table parked in that gap leaves only 300 mm on the assumed aligned section. Find a separate safe parking position or change the furniture plan. Do not claim the mattress length is the deployed furniture depth.\\n\\n### 3. Viewing geometry, not a prescribed distance\\n\\nFor a centred, perpendicular viewer and a 16:9 screen:\\n\\n```text\\ndiagonal_mm = diagonal_inches * 25.4\\nscreen_width_mm = diagonal_mm * 16 / sqrt(16^2 + 9^2)\\nhorizontal_angle_degrees = 2 * atan(screen_width_mm / (2 * eye_distance_mm)) * 180 / pi\\n```\\n\\nA 65-inch screen is about 1439 mm wide. At a 2500 mm perpendicular eye-to-screen distance it spans about 32.1 degrees horizontally. This describes the geometry; it is not a recommended angle, a safety threshold, a panel off-axis specification, or a comfort guarantee. Trial content, subtitle readability, eyesight, and actual seated posture (S4, S5).\\n\\n### 4. Storage reduces reset effort, not just distance\\n\\nSuppose daily hobby setup/reset requires moving a table twice and clearing an ottoman lid twice, each assumed to take 20 seconds. A nearby accessible drawer avoids those four actions without creating another obstruction.\\n\\n```text\\navoided_actions_per_day = 2 + 2 = 4\\nillustrative_time_saved_seconds_per_day = 4 * 20 = 80\\n```\\n\\nThese are user-supplied or trial assumptions to verify, not a product claim. Also compare lifting effort, comfort, actual walkable trips, and whether anyone must move. Do not choose unsafe reachable storage to save time.\\n\\n## Maintenance and limits\\n\\nKeep numerical heuristics labelled whenever repeated in a proposal. If a source changes, update the affected operational claim as well as the optional catalog. Record exact manual editions and project evidence separately from this generic research.\\n\\nNo exact project product manuals, structural calculations, full accessibility standard, local fire/escape provisions, quantitative acoustic assessment, or photometric design were reviewed to produce this generic skill. Obtain them when the project requires them. A checklist review does not replace installation approval.\\n\"","export default \"# Living Room Planning Source Catalog\\n\\nOptional research/provenance file. Do not load for routine planning or solely to expand a source ID. Load when the user asks for citations, a claim needs verification, sources conflict, or the skill is being maintained.\\n\\nResearch reviewed: 2026-10-09. Scope: generic domestic living-room planning with Germany/EU defaults. Summaries are original planning notes, not reproduced articles. The operational rules and qualifications are in [the planning reference](./planning-reference.md); the workflow is in [the skill](../SKILL.md).\\n\\n## S1 - IKEA Germany: activity zones and reset storage\\n\\n- Source: [So gestaltest du drei Arbeitsbereiche in einem Raum](https://www.ikea.com/de/de/rooms/living-room/how-to/wohnzimmer-aufteilen-pubd020bb20/).\\n- Type: retailer guidance; German market.\\n- Retrieved support: separate work/relaxation areas, visual screening, movable storage, keeping work items together for easy reset.\\n- Applied: activity and simultaneous-use brief, nearby storage, explicit setup/reset actions.\\n- Limits: product inspiration, not dimensional or acoustic compliance evidence. Do not generalize the sofa/laptop examples into suitable full-time workstation ergonomics. Screens do not establish speech privacy or sound isolation.\\n\\n## S2 - IKEA Germany: living-room lighting\\n\\n- Source: [Bestmoegliche Nutzung deiner Wohnzimmerbeleuchtung](https://www.ikea.com/de/de/rooms/living-room/how-to/wohnzimmerbeleuchtung-ideen-pub75352e80/).\\n- Type: retailer guidance; German market.\\n- Retrieved support: combine general, task, and mood lighting; support concentrated tasks with appropriate surrounding light; cabinet lighting and adjustable controls.\\n- Applied: activity-specific lighting, contrast/glare review, multiple controllable sources.\\n- Limits: does not establish mandatory domestic illuminance, colour temperature, or a required number of lamps. Battery-powered lighting still needs energy and charging; the page's casual wording is not an electrical claim.\\n\\n## S3 - IKEA Germany: TV furniture\\n\\n- Source: [So waehlst du eine TV-Bank, die bestens in dein Zuhause passt](https://www.ikea.com/de/de/rooms/living-room/how-to/stilvolle-tv-baenke-pub8de44a60/).\\n- Type: retailer guidance; German market.\\n- Retrieved support: screen centre at seated eye height; open/closed storage choices; cable openings; suggests cabinet wider than screen.\\n- Applied: seated-eye planning, storage configuration, cable access.\\n- Limits: furniture wider than the screen does not establish stability. Check feet, depth, loads, anchors, and exact manuals independently. Product range dimensions/prices are not universal design rules and are not embedded in the skill.\\n\\n## S4 - Sony: wall-mounted TV height\\n\\n- Source: [What is the recommended height when mounting the TV on a wall?](https://www.sony.com/electronics/support/articles/00026357).\\n- Type: manufacturer general support; US site. Retrieved page displayed article ID 00026358 and modification date 2019-08-19 despite the requested URL.\\n- Retrieved support: height depends on preference and seating; generally centre the screen at viewers' eye level; model-specific off-axis image characteristics need checking.\\n- Applied: actual seated eye measurements, posture trials, per-seat sightline checks.\\n- Limits: not a fixed floor-height rule, comfort guarantee, bracket specification, or installation manual. Panel viewing-angle specifications differ from the visual angle a screen occupies.\\n\\n## S5 - Sony: viewing distance qualifications\\n\\n- Source: [Recommended viewing distance for watching TV](https://www.sony.com/electronics/support/articles/00008601).\\n- Type: manufacturer general support; US site. Retrieved page displayed article ID 00008602 and modification date 2025-01-17.\\n- Retrieved support: distance depends on screen size/resolution, content, surroundings, and the viewer; adapt reference distances to preference and room layout.\\n- Applied: avoid a universal screen-diagonal multiplier; trial the intended screen and content.\\n- Limits: the fetched text did not expose the numeric content inside the 4K/HD/SD sections. No numerical distance recommendation is attributed to this source. The reference's screen-angle example is elementary geometry, not a Sony recommendation.\\n\\n## S6 - nullbarriere: living/sleeping-room accessibility\\n\\n- Source: [DIN 18040-2 Wohnraum, Schlafraum](https://nullbarriere.de/din18040-2-wohnraum-schlafraum.htm).\\n- Context: [DIN 18040-2 index](https://nullbarriere.de/din18040-2.htm), identifying edition 2011-09 and distinguishing ordinary barrier-free use from unrestricted wheelchair use (R).\\n- Type: German specialist secondary standard summary, not the normative text.\\n- Retrieved support: turning/movement areas of 1200 x 1200 mm and 1500 x 1500 mm for wheelchair use; depths along/in front of furniture of 900 mm and 1500 mm respectively; flexibility and functional access matter.\\n- Applied: qualified accessibility prompts and provisional checks; do not import ordinary coffee-table gaps into accessible approaches.\\n- Limits: current edition, legal adoption by federal state, contractual applicability, exact measurement provisions, and exceptions need verification from authoritative project sources. Full standard text was not reviewed. Bedroom examples and unrelated dimensions are not generalized into living-room rules.\\n\\n## S7 - Verbraucherzentrale: keep radiator heat flow clear\\n\\n- Source: [Heizung optimieren und Heizkosten sparen](https://www.verbraucherzentrale.de/wissen/energie/heizen-und-warmwasser/heizung-optimieren-und-heizkosten-sparen-30096).\\n- Type: German consumer advice; retrieved article dated 2026-10-08.\\n- Retrieved support: long curtains, furniture, and covers in front of radiators can trap heat, impair room warming, and distort thermostat sensing; keep radiators unobstructed.\\n- Applied: furniture/shading layout must preserve heat flow and usable controls.\\n- Limits: no universal clearance is inferred. Heating-system modification, fireplace clearances, and cold-wall moisture assessment require their own evidence. Unrelated legislation and numerical savings on this page are not used.\\n\\n## S8 - US CPSC: furniture and TV tip-over prevention\\n\\n- Source: [Anchor It!](https://www.anchorit.gov/).\\n- Type: US government consumer-safety campaign.\\n- Retrieved support: anchor susceptible furniture and televisions using suitable anchoring equipment; follow installation instructions.\\n- Applied: include anchoring in layout/installation planning, account for wall construction, and do not assume a low or visually stable unit needs no assessment.\\n- Limits: US regulations and typical wall construction are not German/EU requirements. Exact product manuals, appropriate substrate/fixings, and professional review control project installation. This skill does not reproduce a generic DIY anchoring procedure.\\n\\n## S9 - US CPSC: window-covering cords\\n\\n- Source: [Window Covering Cords](https://www.cpsc.gov/Safety-Education/Safety-Education-Centers/Window-Covering) (retrieved canonical destination: [Go Cordless](https://www.cpsc.gov/gocordless)).\\n- Type: US government consumer-safety guidance.\\n- Retrieved support: cordless coverings are the safest choice around young children; keep furniture that enables access away from windows/cords; mitigation of existing cords does not eliminate the hazard.\\n- Applied: check climbing routes and reachable cords when positioning sofas, shelves, and play areas; prefer cordless coverings.\\n- Limits: not a claim about current German/EU product law or a complete child-safety audit. No US retrofit dimensions or regulatory requirements are transposed into the skill.\\n\\n## Research gaps and update policy\\n\\n- The initially attempted living-room accessibility URL was invalid; S6 records the valid page found through the index, not the failed address.\\n- An attempted licht.de living-room page yielded no meaningful extract and is not used as evidence.\\n- The ordinary route, coffee-table, and conversation spacing ranges are explicitly labelled skill heuristics, not research-backed minima.\\n- Acoustic cautions and delivery/open-state checks are planning synthesis, not validated acoustic performance or model-specific installation data.\\n- No exact project manuals, current full DIN standard, local fire/escape rules, engineering calculations, or quantitative lighting/acoustic study were inspected.\\n- For updates, recheck the relevant article and its scope, then update the operational claim and its qualifications. Never replace a missing source with an unqualified mandatory-sounding number.\\n\"","/** A frontmatter field as YAML reads it: a scalar, or a nested field (metadata) as an object of scalars. */\nexport type FrontmatterValue = string | Record<string, string>;\n\n/** A planning skill in the Agent Skills format: a directory with SKILL.md and supporting files. */\nexport interface Skill {\n name: string;\n description: string;\n frontmatter: Record<string, FrontmatterValue>;\n /** The text of every file of the skill by its path in the skill's directory. */\n texts: Record<string, string>;\n files: string[];\n /** The supporting files SKILL.md asks to read before planning, served with it. */\n required: string[];\n}\n\nexport const SKILL_FILE = 'SKILL.md';\n\n// The supporting files a skill asks to read before planning, by skill name.\nconst REQUIRED_FILES: Record<string, string[]> = {\n 'kitchen-planning': ['references/planning-reference.md'],\n 'kitchen-planning-fr': ['references/planning-reference.md'],\n 'living-room-planning': ['references/planning-reference.md'],\n};\n\n/** Whether a file argument of get-skill, with or without a leading ./, names SKILL.md. */\nexport const isSkillFile = (file?: string): boolean =>\n file === undefined || file.replace(/^(\\.\\/)+/, '') === SKILL_FILE;\n\n// The files of the skills directory, bundled as text, by their path below it.\nconst SKILL_FILES = Object.fromEntries(\n Object.entries(\n import.meta.glob<string>('./skills/**/*', {\n query: '?raw',\n import: 'default',\n eager: true,\n }),\n ).map(([path, text]) => [path.replace(/^\\.\\/skills\\//, ''), text]),\n);\n\nconst FRONTMATTER = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n/;\nconst FIELD = /^([A-Za-z][\\w-]*):\\s*(.*)$/;\nconst NESTED_FIELD = /^\\s+([A-Za-z][\\w-]*):\\s*(.*)$/;\nconst BLOCK_SCALAR = /^([|>])([+-]?)$/;\n\ninterface Field {\n value: string;\n lines: string[];\n}\n\nconst unquoted = (value: string): string =>\n /^'.*'$|^\".*\"$/.test(value) ? value.slice(1, -1) : value;\n\nconst folded = (lines: string[]): string =>\n lines\n .join('\\n')\n .split(/\\n\\s*\\n/)\n .map((paragraph) => paragraph.split('\\n').join(' '))\n .join('\\n');\n\n// The YAML of Agent Skills frontmatter: a plain, quoted, multi-line or block\n// scalar per field, a block scalar with its chomping (clip, - strip, + keep),\n// and a nested field (metadata) as an object of scalars.\nconst valueOf = ({ value, lines }: Field): FrontmatterValue => {\n const content = lines.filter((line) => line.trim());\n const block = BLOCK_SCALAR.exec(value);\n if (block) {\n const [, style, chomping] = block;\n const indent = Math.min(\n ...content.map((line) => line.length - line.trimStart().length),\n );\n const body = lines.map((line) => line.slice(indent));\n let end = body.length;\n while (end > 0 && !body[end - 1].trim()) {\n end--;\n }\n const core = body.slice(0, end);\n const text = style === '|' ? core.join('\\n') : folded(core);\n if (chomping === '-') {\n return text;\n }\n return text + '\\n'.repeat(chomping === '+' ? body.length - end + 1 : 1);\n }\n const nested = content.map((line) => NESTED_FIELD.exec(line));\n if (\n !value &&\n nested.length > 0 &&\n nested.every((field): field is RegExpExecArray => field !== null)\n ) {\n return Object.fromEntries(\n nested.map(([, key, nestedValue]) => [key, unquoted(nestedValue.trim())]),\n );\n }\n return unquoted(\n [value, ...content.map((line) => line.trim())].join(' ').trim(),\n );\n};\n\nconst frontmatterOf = (\n text: string,\n file: string,\n): Record<string, FrontmatterValue> => {\n const block = FRONTMATTER.exec(text)?.[1];\n if (block === undefined) {\n throw new Error(`${file}: no frontmatter`);\n }\n const fields: Record<string, Field> = {};\n let current: Field | undefined;\n for (const line of block.split(/\\r?\\n/)) {\n const field = FIELD.exec(line);\n if (field) {\n current = { value: field[2].trim(), lines: [] };\n fields[field[1]] = current;\n } else if (current && /^(\\s|$)/.test(line)) {\n current.lines.push(line);\n } else if (!line.startsWith('#')) {\n throw new Error(`${file}: the frontmatter line \"${line}\" is not a field`);\n }\n }\n return Object.fromEntries(\n Object.entries(fields).map(([key, field]) => [key, valueOf(field)]),\n );\n};\n\n/**\n * Reads every skill of the skills directory, given as the text of each file by\n * its path below the directory, with the files each skill requires before\n * planning; a broken skill or a required file the skill does not have fails the\n * load and names its file.\n */\nexport const loadSkills = (\n files: Record<string, string>,\n required: Record<string, string[]> = REQUIRED_FILES,\n): Skill[] => {\n const directories = new Map<string, Record<string, string>>();\n for (const [path, text] of Object.entries(files)) {\n const [directory, ...rest] = path.split('/');\n if (rest.length > 0) {\n directories.set(directory, {\n ...directories.get(directory),\n [rest.join('/')]: text,\n });\n }\n }\n return [...directories]\n .map(([directory, texts]) => {\n const file = `skills/${directory}/${SKILL_FILE}`;\n if (texts[SKILL_FILE] === undefined) {\n throw new Error(`${file}: no such file`);\n }\n const frontmatter = frontmatterOf(texts[SKILL_FILE], file);\n const { name, description } = frontmatter;\n if (name !== directory) {\n throw new Error(\n `${file}: the name \"${name}\" differs from its directory \"${directory}\"`,\n );\n }\n if (typeof description !== 'string' || !description.trim()) {\n throw new Error(`${file}: no description`);\n }\n const supporting = Object.keys(texts)\n .filter((path) => path !== SKILL_FILE)\n .sort();\n const requiredFiles = required[directory] ?? [];\n for (const path of requiredFiles) {\n if (!supporting.includes(path)) {\n throw new Error(\n `${file}: the required file \"${path}\" is no file of the skill`,\n );\n }\n }\n return {\n name,\n description: description.trim(),\n frontmatter,\n texts,\n files: [SKILL_FILE, ...supporting],\n required: requiredFiles,\n };\n })\n .sort((a, b) => a.name.localeCompare(b.name));\n};\n\n/** One line per skill: its name and its description. */\nexport const skillIndex = (skills: Skill[]): string =>\n skills.map((skill) => `- ${skill.name}: ${skill.description}`).join('\\n');\n\nconst skillFileText = (skill: Skill, path: string): string =>\n skill.texts[path].replace(/\\r\\n/g, '\\n');\n\nconst skillNamed = (skills: Skill[], name: string): Skill => {\n const skill = skills.find((candidate) => candidate.name === name);\n if (!skill) {\n throw new Error(\n `Unknown skill \"${name}\" - the skills are ${skills.map((candidate) => candidate.name).join(', ')}`,\n );\n }\n return skill;\n};\n\n/** A file of a skill by its path; only a file of the skill's list is read. */\nexport const readSkillFile = (\n skills: Skill[],\n name: string,\n file: string = SKILL_FILE,\n): string => {\n const skill = skillNamed(skills, name);\n const path = file.replace(/^(\\.\\/)+/, '');\n if (!skill.files.includes(path)) {\n throw new Error(\n `Unknown file \"${file}\" of the skill ${name} - its files are ${skill.files.join(', ')}`,\n );\n }\n return skillFileText(skill, path);\n};\n\nconst includedFile = (skill: Skill, path: string): string =>\n `\\n---\\n\\nThe file ${path} of this skill, included here:\\n\\n${skillFileText(skill, path)}`;\n\n/**\n * SKILL.md of a skill followed by the supporting files it asks to read before\n * planning, each under a line that names it.\n */\nexport const readSkill = (skills: Skill[], name: string): string => {\n const skill = skillNamed(skills, name);\n return skill.required.reduce(\n (text, path) => `${text.replace(/\\n*$/, '\\n')}${includedFile(skill, path)}`,\n skillFileText(skill, SKILL_FILE),\n );\n};\n\nexport const skills = loadSkills(SKILL_FILES);\n","// The plan context in the words of the agent: wall names, room corners, the\n// wall of a door or a window, and the catalog's short descriptions.\n\nimport { wallFaces } from '../hi-plan-space';\n\ntype WallSide = 'left' | 'right' | 'top' | 'bottom';\n\ninterface DerivedWall {\n index: number;\n side: WallSide;\n start: [number, number, number];\n end: [number, number, number];\n lengthMm: number;\n type?: string;\n heightMm?: number;\n thicknessMm?: number;\n facingRotationY: number;\n}\n\n// + 0 turns IEEE -0 into +0 so serialized values never show -0\nconst round2 = (value: number): number => Math.round(value * 100) / 100 + 0;\n\nconst POINT_EPSILON_MM = 1;\n\nconst samePoint = (a: [number, number], b: [number, number]): boolean =>\n Math.hypot(a[0] - b[0], a[1] - b[1]) < POINT_EPSILON_MM;\n\nconst unitDirection = (\n from: [number, number],\n to: [number, number],\n): [number, number] | undefined => {\n const length = Math.hypot(to[0] - from[0], to[1] - from[1]);\n return length < 1e-6\n ? undefined\n : [(to[0] - from[0]) / length, (to[1] - from[1]) / length];\n};\n\nconst projectOntoAxis = (\n polygon: Array<[number, number]>,\n [axisX, axisZ]: [number, number],\n): [number, number] => {\n let minimum = Number.POSITIVE_INFINITY;\n let maximum = Number.NEGATIVE_INFINITY;\n for (const [x, z] of polygon) {\n const projection = x * axisX + z * axisZ;\n minimum = Math.min(minimum, projection);\n maximum = Math.max(maximum, projection);\n }\n return [minimum, maximum];\n};\n\nconst wallFloorPoints = ({\n start,\n end,\n}: DerivedWall): [[number, number], [number, number]] => [\n [start[0], start[2]],\n [end[0], end[2]],\n];\n\nconst WALL_NAMES: Record<WallSide, string> = {\n top: 'back wall',\n bottom: 'front wall',\n left: 'left wall',\n right: 'right wall',\n};\n\n// The name of a wall in the words of the user: back and front for the top and\n// the bottom of the top-view image.\nexport const wallName = (side: WallSide): string =>\n WALL_NAMES[side] ?? `${side} wall`;\n\nexport interface RoomCorner {\n name: string;\n point: [number, number, number];\n posRotationY: number;\n}\n\n// The corners of a room: where a wall or an opening ends and the next starts\n// at an angle that turns into the room - towards the side the ending one\n// faces, as the room lies left of the contour (D61). A partition and the inner\n// corner of an L-shaped room turn away from it and give none. The name is\n// back/front plus left/right, and posRotationY is the facingRotationY of the\n// wall that ends in the corner - the rotation of a corner kitchen there, for\n// both hands of corner article (D13, D33, D83).\nexport const roomCorners = (walls: DerivedWall[]): RoomCorner[] => {\n const corners: RoomCorner[] = [];\n for (const ending of walls) {\n const [endingStart, endPoint] = wallFloorPoints(ending);\n const along = unitDirection(endingStart, endPoint);\n for (const starting of walls) {\n const [startPoint, startingEnd] = wallFloorPoints(starting);\n const next = unitDirection(startPoint, startingEnd);\n if (\n starting === ending ||\n !samePoint(endPoint, startPoint) ||\n !along ||\n !next ||\n Math.abs(along[0] * next[0] + along[1] * next[1]) > 0.999 ||\n along[1] * next[0] - along[0] * next[1] <= 0\n ) {\n continue;\n }\n const sides = [ending.side, starting.side];\n const depth = sides.find((side) => side === 'top' || side === 'bottom');\n const hand = sides.find((side) => side === 'left' || side === 'right');\n if (!depth || !hand) {\n continue;\n }\n corners.push({\n name: `${depth === 'top' ? 'back' : 'front'} ${hand}`,\n point: [endPoint[0], 0, endPoint[1]],\n posRotationY: ending.facingRotationY,\n });\n }\n }\n return corners;\n};\n\n// The extent of room points along a wall, measured from the wall's start.\nexport const spanAlongWall = (\n wall: DerivedWall,\n points: Array<[number, number]>,\n): [number, number] => {\n const [[startX, startZ], [endX, endZ]] = wallFloorPoints(wall);\n const length = Math.hypot(endX - startX, endZ - startZ);\n const along: [number, number] = [\n (endX - startX) / length,\n (endZ - startZ) / length,\n ];\n return projectOntoAxis(\n points.map(([x, z]) => [x - startX, z - startZ]),\n along,\n );\n};\n\nexport interface WallOfOpening {\n roomIndex: number;\n wall: number;\n fromEndMm: [number, number];\n}\n\n// The wall a door or a window lies in: the wall whose line its floor outline\n// touches - within the wall's thickness - over the longest stretch. The span\n// is measured from the wall's end, like the d of a placement.\nexport const wallOfOpening = (\n outline: Array<[number, number]>,\n rooms: Array<{ walls?: DerivedWall[] }>,\n): WallOfOpening | undefined => {\n let found: WallOfOpening | undefined;\n let longestOverlap = POINT_EPSILON_MM;\n rooms.forEach((room, roomIndex) => {\n for (const wall of room.walls ?? []) {\n const [[startX, startZ], [endX, endZ]] = wallFloorPoints(wall);\n const along = unitDirection([startX, startZ], [endX, endZ]);\n if (!along) {\n continue;\n }\n const distanceToLine = Math.min(\n ...outline.map(([x, z]) =>\n Math.abs((x - startX) * along[1] - (z - startZ) * along[0]),\n ),\n );\n if (distanceToLine > (wall.thicknessMm ?? 0) + POINT_EPSILON_MM) {\n continue;\n }\n const length = Math.hypot(endX - startX, endZ - startZ);\n const [from, to] = spanAlongWall(wall, outline);\n const overlap = Math.min(to, length) - Math.max(from, 0);\n if (overlap > longestOverlap) {\n longestOverlap = overlap;\n found = {\n roomIndex,\n wall: wall.index,\n fromEndMm: [\n round2(length - Math.min(to, length)),\n round2(length - Math.max(from, 0)),\n ],\n };\n }\n }\n });\n return found;\n};\n\n// A sectioned article description - FUNCTION:, PURPOSE:, …,\n// AI_SELECTION_HINT: - shortened to what the article is and when to pick it.\n// A section's text stands on the line of its name or on the next line.\nconst SHORT_DESCRIPTION_SECTIONS = ['FUNCTION', 'AI_SELECTION_HINT'];\nconst shortDescription = (desc: unknown): unknown => {\n if (typeof desc !== 'string') {\n return desc;\n }\n const lines = SHORT_DESCRIPTION_SECTIONS.map((section) =>\n desc\n .match(new RegExp(`(?:^|\\\\n)${section}:[ \\\\t]*\\\\n?([^\\\\n]+)`))?.[1]\n ?.trim(),\n ).filter((line) => line);\n return lines.length > 0 ? lines.join(' ') : desc;\n};\n\nconst hasSelections = (attribute: any): boolean =>\n Array.isArray(attribute?.selections) && attribute.selections.length > 0;\n\n// The same values of one library list alike, their catalog images aside.\nconst selectionsKey = (attribute: any): string =>\n `${attribute.libraryId}\\n${JSON.stringify(attribute.selections, (field, value) => (field === 'imageUrl' ? undefined : value))}`;\n\n// A value list several attributes share is listed once: the later attributes\n// name the attribute that lists it.\nexport const withSharedSelectionsOnce = (attributes: any[]): any[] => {\n const listedBy = new Map<string, string>();\n return attributes.map((attribute) => {\n if (!hasSelections(attribute)) {\n return attribute;\n }\n const key = selectionsKey(attribute);\n const listing = listedBy.get(key);\n if (listing === undefined) {\n listedBy.set(key, attribute.id);\n return attribute;\n }\n const shared = { ...attribute, sameSelectionsAs: listing };\n delete shared.selections;\n return shared;\n });\n};\n\n// Whether the agent sees and sets an attribute. The element type is what the\n// article is - another type is another article. The library does not mark such\n// attributes yet, so the element type is named here.\nexport const isAgentFacingAttribute = (attributeId: unknown): boolean =>\n attributeId !== 'mod_TypeElement';\n\n// A list of attributes or of attribute ids without those the agent does not see.\nconst agentFacingEntries = (entries: unknown): unknown =>\n Array.isArray(entries)\n ? entries.filter((entry) =>\n isAgentFacingAttribute(typeof entry === 'string' ? entry : entry?.id),\n )\n : entries;\n\nconst withAgentFacingAttributes = <T extends { attributes?: unknown }>(\n item: T,\n): T =>\n Array.isArray(item?.attributes)\n ? { ...item, attributes: agentFacingEntries(item.attributes) }\n : item;\n\n// The interior fittings without the attributes the agent does not see.\nexport const agentFacingFittings = (fittings: unknown): unknown =>\n Array.isArray(fittings) ? fittings.map(withAgentFacingAttributes) : fittings;\n\n// The groups without the attributes the agent does not see: those of the\n// group, its roots, their sub modules and the interior fittings.\nexport const agentFacingGroups = (groups: any): any =>\n Array.isArray(groups)\n ? groups.map((group) => ({\n ...withAgentFacingAttributes(group),\n ...(Array.isArray(group?.roots) && {\n roots: group.roots.map((root: any) => ({\n ...withAgentFacingAttributes(root),\n ...(Array.isArray(root?.subModules) && {\n subModules: root.subModules.map(withAgentFacingAttributes),\n }),\n })),\n }),\n ...(Array.isArray(group?.interiorFittings) && {\n interiorFittings: agentFacingFittings(group.interiorFittings),\n }),\n }))\n : groups;\n\n// The compacted master data without the attributes the agent does not see:\n// the attributes, the ids the modules carry and the group settings.\nexport const agentFacingMasterData = (masterData: any): any =>\n masterData !== null && typeof masterData === 'object'\n ? Object.fromEntries(\n Object.entries(masterData as Record<string, any>).map(\n ([libraryId, library]) => [\n libraryId,\n {\n ...withAgentFacingAttributes(library),\n ...(Array.isArray(library?.modules) && {\n modules: library.modules.map(withAgentFacingAttributes),\n }),\n ...(Array.isArray(library?.subModules) && {\n subModules: library.subModules.map(withAgentFacingAttributes),\n }),\n ...(Array.isArray(library?.groupSettings) && {\n groupSettings: agentFacingEntries(library.groupSettings),\n }),\n },\n ],\n ),\n )\n : masterData;\n\n// The attributes a planning sets at the create, by the library's structure:\n// those the catalog names per root module (mainAttributes, dimensions), the\n// group settings and those of the generated root modules - the modules no\n// catalog article names.\nconst createAttributeIds = (library: any, articles: any[]): Set<string> => {\n const rootModules = articles.flatMap(\n (article) => (article?.rootModules ?? []) as any[],\n );\n const catalogModuleIds = new Set(\n rootModules.map((rootModule) => rootModule?.module?.id),\n );\n return new Set([\n ...rootModules.flatMap((rootModule) =>\n [\n ...((rootModule?.mainAttributes ?? []) as any[]),\n ...((rootModule?.dimensions ?? []) as any[]),\n ].map((attribute) => attribute?.id),\n ),\n ...((library?.groupSettings ?? []) as string[]),\n ...((library?.modules ?? []) as any[])\n .filter((module) => !catalogModuleIds.has(module?.id))\n .flatMap((module) => (module?.attributes ?? []) as string[]),\n ]);\n};\n\n// The attribute vocabulary: per library every attribute of the compacted master\n// data. The values are listed for the attributes a planning sets at the\n// create, a shared value list once; every other attribute names the number of\n// its values, which find-attributes lists. The modules and the group settings\n// stay in masterData.\nexport const agentFacingAttributes = (masterData: any, articles: any[] = []) =>\n Object.fromEntries(\n Object.entries((masterData ?? {}) as Record<string, any>).map(\n ([libraryId, library]) => {\n const attributes = (library?.attributes ?? []) as any[];\n const atCreate = createAttributeIds(\n library,\n articles.filter((article) => article?.libraryId === libraryId),\n );\n const listed = new Set(\n attributes\n .filter(\n (attribute) =>\n atCreate.has(attribute.id) && hasSelections(attribute),\n )\n .map(selectionsKey),\n );\n return [\n libraryId,\n withSharedSelectionsOnce(\n attributes.map((attribute) => {\n if (\n !hasSelections(attribute) ||\n listed.has(selectionsKey(attribute))\n ) {\n return attribute;\n }\n const { selections, ...withoutValues } = attribute;\n return { ...withoutValues, valueCount: selections.length };\n }),\n ),\n ];\n },\n ),\n );\n\n// The corner point is not the agent's. The description is short; the\n// articleDescriptions section has the full one.\nexport const agentFacingArticle = (article: any) => {\n const compact = {\n ...article,\n ...(article.desc !== undefined && { desc: shortDescription(article.desc) }),\n ...(Array.isArray(article.rootModules) && {\n rootModules: article.rootModules.map((rootModule: any) => ({\n ...rootModule,\n ...(Array.isArray(rootModule?.dimensions) && {\n dimensions: agentFacingEntries(rootModule.dimensions),\n }),\n ...(Array.isArray(rootModule?.mainAttributes) && {\n mainAttributes: agentFacingEntries(rootModule.mainAttributes),\n }),\n })),\n }),\n };\n delete compact.cornerPoint;\n return compact;\n};\n\ninterface ContourLevel {\n level: number;\n segments?: Array<{\n cmd: string;\n pos: [number, number, number];\n type?: string | null;\n }>;\n}\n\ninterface WallOpening {\n fromEndMm?: [number, number];\n bottomMm?: number;\n topMm?: number;\n}\n\n// The lowest contour level above the floor at which part of the wall's span\n// is no longer solid wall: above it a sloping ceiling or a roof lies over the\n// wall. A door or a floor-to-ceiling window splits the floor contour into\n// opening pieces (D61), so only a level above the floor opens a wall piece;\n// the gap of a window between its sill and its head is one of the wall's\n// openings, not a slope, so the span of an opening counts as wall at the\n// levels it holds.\nexport const slopeFromMm = (\n levels: ContourLevel[] | undefined,\n wall: DerivedWall,\n openings: WallOpening[] = [],\n): number | undefined => {\n // an opening piece (a door, a floor-to-ceiling window) is open from the\n // floor - only a piece of wall can open above it\n if (wall.type !== 'wall') {\n return undefined;\n }\n const [[startX, startZ], [endX, endZ]] = wallFloorPoints(wall);\n const along = unitDirection([startX, startZ], [endX, endZ]);\n if (!along || !Array.isArray(levels)) {\n return undefined;\n }\n const tolerance = (wall.thicknessMm ?? 0) + POINT_EPSILON_MM;\n const sorted = [...levels].sort((a, b) => a.level - b.level);\n for (const level of sorted) {\n if (\n level.level <= 0 ||\n (wall.heightMm !== undefined && level.level >= wall.heightMm)\n ) {\n continue;\n }\n const spans: Array<[number, number]> = [];\n let previous: [number, number] | undefined;\n let subPathStart: [number, number] = [0, 0];\n for (const segment of level.segments ?? []) {\n const point: [number, number] = [segment.pos[0], segment.pos[2]];\n if (segment.cmd === 'M') {\n subPathStart = point;\n previous = point;\n continue;\n }\n const to = segment.cmd === 'Z' ? subPathStart : point;\n if (previous && segment.type === 'wall') {\n const fromLine = Math.abs(\n (previous[0] - startX) * along[1] - (previous[1] - startZ) * along[0],\n );\n const toLine = Math.abs(\n (to[0] - startX) * along[1] - (to[1] - startZ) * along[0],\n );\n if (fromLine <= tolerance && toLine <= tolerance) {\n spans.push(\n projectOntoAxis(\n [\n [previous[0] - startX, previous[1] - startZ],\n [to[0] - startX, to[1] - startZ],\n ],\n along,\n ),\n );\n }\n }\n previous = to;\n }\n for (const opening of openings) {\n const holdsTheLevel =\n Array.isArray(opening.fromEndMm) &&\n (opening.bottomMm ?? 0) <= level.level + POINT_EPSILON_MM &&\n level.level <\n (opening.topMm ?? Number.POSITIVE_INFINITY) - POINT_EPSILON_MM;\n if (holdsTheLevel) {\n const [from, to] = opening.fromEndMm as [number, number];\n spans.push([wall.lengthMm - to, wall.lengthMm - from]);\n }\n }\n spans.sort((a, b) => a[0] - b[0]);\n let coveredMm = 0;\n let reach = Number.NEGATIVE_INFINITY;\n let start = 0;\n for (const [from, to] of spans) {\n const clippedFrom = Math.max(from, 0);\n const clippedTo = Math.min(to, wall.lengthMm);\n if (clippedTo <= clippedFrom) {\n continue;\n }\n if (clippedFrom > reach + POINT_EPSILON_MM) {\n coveredMm += Math.max(reach - start, 0);\n start = clippedFrom;\n }\n reach = Math.max(reach, clippedTo);\n }\n coveredMm += Math.max(reach - start, 0);\n if (wall.lengthMm - coveredMm > POINT_EPSILON_MM) {\n return level.level;\n }\n }\n return undefined;\n};\n\ninterface OpeningObject {\n kind?: string;\n roomIndex?: number;\n wall?: number;\n fromEndMm?: [number, number];\n bottomMm?: number;\n topMm?: number;\n}\n\n// The doors and windows the obstacle list puts in one wall piece.\nconst openingsOfWall = (\n objects: OpeningObject[],\n roomIndex: number,\n wallIndex: number,\n) =>\n objects\n .filter(\n (object) =>\n (object?.kind === 'door' || object?.kind === 'window') &&\n object?.roomIndex === roomIndex &&\n object?.wall === wallIndex &&\n Array.isArray(object?.fromEndMm),\n )\n .map((object) => ({\n kind: object.kind,\n fromEndMm: object.fromEndMm,\n bottomMm: object?.bottomMm,\n topMm: object?.topMm,\n }));\n\n// The walls in the words of the user: a name per wall, an opening named as\n// such (the contour gives it no type), the room's index and every wall's\n// roomIndex, per wall its openings and the height above which the wall is\n// open (a sloping ceiling from the contour levels), per room its wall faces,\n// and the room corners with their point and the rotation of a group that\n// starts with a corner article there. A piece of wall is free at the floor\n// over its length - a door or a floor-to-ceiling window is a piece of its own\n// (D61) -, so no field says so.\nexport const agentFacingRooms = (rooms: any, obstacles?: any) => {\n if (!Array.isArray(rooms?.rooms)) {\n return rooms;\n }\n const objects: OpeningObject[] = Array.isArray(obstacles?.objects)\n ? obstacles.objects\n : [];\n return {\n ...rooms,\n rooms: rooms.rooms.map((room: any, roomIndex: number) => {\n const walls = ((room?.walls ?? []) as any[]).map((wall) => {\n const openings = openingsOfWall(objects, roomIndex, wall?.index);\n const slope = slopeFromMm(room?.levels, wall, openings);\n return {\n ...wall,\n ...(wall?.type === null || wall?.type === undefined\n ? { type: 'opening' }\n : {}),\n name: wallName(wall?.side),\n roomIndex,\n ...(openings.length > 0 ? { openings } : {}),\n ...(slope !== undefined ? { slopeFromMm: slope } : {}),\n };\n });\n const faces = wallFaces(walls).map((face) => {\n const openingMm = round2(\n face.pieces\n .filter((piece) => piece.type !== 'wall')\n .reduce((sum, piece) => sum + piece.lengthMm, 0),\n );\n const slopes = face.pieces\n .map((piece) => (piece as any).slopeFromMm)\n .filter((slope): slope is number => slope !== undefined);\n return {\n roomIndex,\n side: face.side,\n name: wallName(face.side),\n index: face.index,\n lengthMm: face.lengthMm,\n openingMm,\n openingShare: round2(\n face.lengthMm > 0 ? openingMm / face.lengthMm : 0,\n ),\n ...(slopes.length > 0 ? { slopeFromMm: Math.min(...slopes) } : {}),\n };\n });\n return {\n ...room,\n index: roomIndex,\n walls,\n faces,\n corners: roomCorners(walls),\n };\n }),\n };\n};\n\n// A door or a window lies in a wall: the room, the wall and its span along the\n// wall, measured from the wall's end like the d of a placement.\nexport const agentFacingObstacles = (obstacles: any, rooms: any) => {\n if (!Array.isArray(obstacles?.objects)) {\n return obstacles;\n }\n return {\n ...obstacles,\n objects: obstacles.objects.map((object: any) => {\n if (object?.kind !== 'door' && object?.kind !== 'window') {\n return object;\n }\n const wall = wallOfOpening(\n ((object.outline ?? []) as number[][]).map(\n ([x, , z]): [number, number] => [x, z],\n ),\n rooms?.rooms ?? [],\n );\n return wall ? { ...object, ...wall } : object;\n }),\n };\n};\n","import {\n agentFacingArticle,\n agentFacingAttributes,\n agentFacingFittings,\n agentFacingGroups,\n agentFacingMasterData,\n agentFacingObstacles,\n agentFacingRooms,\n withSharedSelectionsOnce,\n} from './agent-facing';\nimport type { PlanHistory, ToolCallRecord } from './plan-history';\nimport type { PlannerApi } from './planner-api';\nimport { isSkillFile, readSkill, readSkillFile, skills } from './skills';\nimport { searchableText } from '../util';\n\n/** The format of the images of get-plan-images: a fraction of a PNG's bytes, read alike by the model. */\nexport const PLAN_IMAGE_TYPE = 'image/jpeg';\nexport const PLAN_IMAGE_QUALITY = 0.8;\n\nexport type ToolExecutor = (\n roomDesignerApi: PlannerApi,\n args: Record<string, unknown>,\n) => Promise<unknown>;\n\ntype PlanContextSection =\n | 'masterData'\n | 'rooms'\n | 'articles'\n | 'groups'\n | 'obstacles'\n | 'installationElements';\n\nconst PLAN_CONTEXT_SECTIONS: unknown[] = [\n 'masterData',\n 'rooms',\n 'articles',\n 'groups',\n 'obstacles',\n 'installationElements',\n];\n\n// The sections of these the library context returns; the others are the plan\n// context's.\nconst LIBRARY_CONTEXT_SECTIONS: unknown[] = ['masterData', 'articles'];\n\n// The sections of the server: the full descriptions of the catalog's\n// articles, and the attribute vocabulary, both derived from the planner's\n// sections.\nconst ARTICLE_DESCRIPTIONS = 'articleDescriptions';\nconst ATTRIBUTES = 'attributes';\nconst SERVER_SECTIONS: unknown[] = [ARTICLE_DESCRIPTIONS, ATTRIBUTES];\n\nconst DEFAULT_SECTIONS: unknown[] = [\n 'rooms',\n 'articles',\n ATTRIBUTES,\n 'groups',\n 'obstacles',\n 'installationElements',\n];\n\nconst MAX_ATTRIBUTE_MATCHES = 20;\n\nconst searchWords = (text: string): string[] =>\n searchableText(text)\n .split(/[\\s,;()-]+/)\n .filter((word) => word.length > 0);\n\n// Every word is in one of the attribute's fields.\nconst attributeMatches = (attribute: any, words: string[]): boolean => {\n const fields = [\n attribute.id,\n attribute.name,\n attribute.desc,\n attribute.group,\n ...(attribute.selections ?? []).flatMap((selection: any) => [\n selection.name,\n selection.desc,\n selection.value,\n ]),\n ]\n .filter((value) => value !== undefined && value !== null)\n .map((value) => searchableText(String(value)));\n return words.every((word) => fields.some((field) => field.includes(word)));\n};\n\nconst rootsOfGroups = (groups: any[]): any[] =>\n groups.flatMap((group) => (group?.roots ?? []) as any[]);\n\nconst planGroups = async (roomDesignerApi: PlannerApi): Promise<any[]> =>\n ((await roomDesignerApi.extended.getExternalObjectPlanContext(['groups']))\n .groups ?? []) as any[];\n\nconst isObject = (value: unknown): boolean =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n// A planner undo or redo is confirmed by its history event.\nconst HISTORY_EVENT_WAIT_MS = 1000;\n\nconst roundedToTenthMm = (_key: string, value: unknown) =>\n typeof value === 'number' ? Math.round(value * 10) / 10 : value;\n\n// The plan's groups as a comparison key, sorted by id - an undo restores them\n// to the tenth of a millimetre.\nconst groupsKey = (groups: unknown): string =>\n JSON.stringify(\n [...((groups ?? []) as any[])].sort((a, b) =>\n String(a?.id).localeCompare(String(b?.id)),\n ),\n roundedToTenthMm,\n );\n\nconst readGroupsKey = async (roomDesignerApi: PlannerApi) =>\n groupsKey(await planGroups(roomDesignerApi));\n\n// The planner API of a tool call that changes the plan. The tool runs in the\n// planner page as one group command, which answers after its last reload and\n// reports the steps it put on the planner's undo history - one per load that\n// loaded something and one per group command. The API counts the steps and\n// reads the plan before the first one.\nconst countingPlannerApi = (roomDesignerApi: PlannerApi) => {\n const { extended } = roomDesignerApi;\n const count = {\n steps: 0,\n groupsBefore: undefined as string | undefined,\n };\n const api: PlannerApi = {\n extended: {\n ...extended,\n externalObjectGroupOperation: async (command, payload) => {\n count.groupsBefore ??= await readGroupsKey(roomDesignerApi);\n const result = await extended.externalObjectGroupOperation(\n command,\n payload,\n );\n count.steps += Number(result?.historySteps ?? 1);\n return result;\n },\n },\n };\n return { api, count };\n};\n\ntype HistoryDirection = 'undo' | 'redo';\n\nconst NOTHING_TO_UNDO =\n 'Nothing to undo: no tool call has changed the plan since the planner page connected.';\nconst NOTHING_TO_REDO =\n 'Nothing to redo: redo brings back a tool call that undo reverted, and a new change of the plan ends redo.';\nconst CHANGED_IN_PLANNER =\n \"The plan was changed in the planner after the last tool call, so no tool call was reverted - the planner's own undo button reverts the changes made there.\";\n\n// The groups a tool call changed, by the plan before and after it: those it\n// created, removed or changed.\nconst changedGroupIds = (call: ToolCallRecord): Set<string> => {\n const byId = (key: string) =>\n new Map(\n ((JSON.parse(key) ?? []) as any[]).map((group) => [\n String(group?.id),\n JSON.stringify(group),\n ]),\n );\n const before = byId(call.groupsBefore);\n const after = byId(call.groupsAfter);\n return new Set(\n [...before.keys(), ...after.keys()].filter(\n (id) => before.get(id) !== after.get(id),\n ),\n );\n};\n\n// A result that changed some groups of the plan: those groups in full, the\n// others by their id - the agent knows them already.\nconst changedGroupsOnly = (\n groups: any[],\n changed: (group: any) => boolean,\n): { groups: any[]; otherGroupIds?: string[] } => {\n const others = groups.filter((group) => !changed(group));\n return {\n groups: groups.filter(changed),\n ...(others.length > 0 && {\n otherGroupIds: others.map((group) => group.id),\n }),\n };\n};\n\n// The root modules and groups the library cannot calculate, one sentence\n// each: \"is still not built\" after an attribute change - a change that makes\n// one fail is discarded before the load, so each of them failed before the\n// call, unless a follow-up calculation of the call left it -, \"is not built\"\n// in the price and the order.\nconst notBuilt = (\n groups: any[],\n state: 'still not built' | 'not built',\n): string[] =>\n groups.flatMap((group) => [\n ...(group?.calculationError !== undefined\n ? [`group '${group.id}' is ${state} - ${group.calculationError}.`]\n : []),\n ...((group?.roots ?? []) as any[])\n .filter((root) => root?.calculationError !== undefined)\n .map(\n (root) =>\n `root module '${root.id}' (${root.articleId}) of group '${group.id}' is ${state} - ${root.calculationError}.`,\n ),\n ]);\n\n// The price and the order data count every root module of the plan, also one\n// the library could not calculate: the answer stays as the planner gives it,\n// and the hint names what is not built. A plan without one gets the answer\n// alone.\nconst withNotBuiltHint = (answer: any, groups: any[], counted: string) => {\n const sentences = notBuilt(groups, 'not built');\n return sentences.length === 0\n ? answer\n : {\n ...answer,\n hint: `${sentences.join(' ')} ${counted} includes what is not built, without calculated dimensions and parts - say so in the answer, or change the value that fails.`,\n };\n};\n\n// An attribute change answers with what changed, not with the whole group:\n// get-plan-context shows the group. What the library still cannot calculate\n// in the changed groups is the hint, so a repair that failed again shows.\nconst compactAttributeResult = (result: any) => {\n const groups = (result.groups ?? []) as any[];\n const stillNotBuilt = notBuilt(groups, 'still not built');\n return {\n command: result.command,\n groupIds: groups.map((group) => group.id),\n ...(result.changedModuleIds?.length > 0 && {\n changedModuleIds: result.changedModuleIds,\n }),\n ...(result.corrections?.length > 0 && { corrections: result.corrections }),\n ...(result.libraryFailures?.length > 0 && {\n libraryFailures: result.libraryFailures,\n }),\n ...(stillNotBuilt.length > 0 && {\n hint: `${stillNotBuilt.join(' ')} Change the value that fails, or tell the user.`,\n }),\n };\n};\n\n// Opening or closing changes the view, not the plan: the answer names the\n// target and the state its doors and drawers are in now - the planner has the\n// requested state once the call succeeds - without the changed flag of the\n// group operation, which keeps the switch out of undo (D88). A target without\n// doors or drawers keeps its correction and gets no state.\nconst doorsAndDrawersResult =\n (target: 'groupId' | 'rootModuleId') =>\n (result: any, args: Record<string, unknown>) => ({\n command: result.command,\n [target]: args[target],\n ...(result.corrections?.length > 0\n ? { corrections: result.corrections }\n : { doorsAndDrawers: args.open === true ? 'open' : 'closed' }),\n });\n\n// The executors of one tool set: its plan changes run one after another and\n// its tool calls that changed the plan are recorded in its plan history.\nexport const createToolExecutors = (\n planHistory: PlanHistory,\n): Record<string, ToolExecutor> => {\n // The tool calls that change the plan run one after another: the record of a\n // call for undo compares the plan before and after it, and the page runs every\n // planner call it receives at once, so a concurrent call would mix into the\n // record. get-plan-context, find-attributes, get-price and get-order-data\n // wait as well, so that they never read a plan halfway through a change.\n let planChanges: Promise<unknown> = Promise.resolve();\n\n const oneAtATime =\n (executor: ToolExecutor): ToolExecutor =>\n (roomDesignerApi, args) => {\n const run = planChanges.then(() => executor(roomDesignerApi, args));\n planChanges = run.catch(() => undefined);\n return run;\n };\n // A tool call that changed the plan is recorded with its planner steps and\n // the plan before and after it, so that undo can revert it; the history\n // events while it runs are its own. A plan that cannot be read afterwards\n // leaves no record the undo could trust.\n const recorded =\n (tool: string, executor: ToolExecutor): ToolExecutor =>\n async (roomDesignerApi, args) => {\n const { api, count } = countingPlannerApi(roomDesignerApi);\n planHistory.begin();\n try {\n return await executor(api, args);\n } finally {\n const recordable = count.steps > 0 && count.groupsBefore !== undefined;\n let groupsAfter: string | undefined;\n if (recordable) {\n try {\n groupsAfter = await readGroupsKey(roomDesignerApi);\n } catch {\n groupsAfter = undefined;\n }\n }\n if (recordable && groupsAfter === undefined) {\n planHistory.forget();\n } else if (recordable) {\n planHistory.record({\n tool,\n steps: count.steps,\n groupsBefore: count.groupsBefore!,\n groupsAfter: groupsAfter!,\n });\n }\n planHistory.end();\n }\n };\n\n const planChange = (tool: string, executor: ToolExecutor): ToolExecutor =>\n oneAtATime(recorded(tool, executor));\n\n // One planner undo or redo per step, each confirmed by its history event.\n // Returns the number of steps done: fewer when the planner's history ran out.\n const stepHistory = async (\n roomDesignerApi: PlannerApi,\n direction: HistoryDirection,\n steps: number,\n ): Promise<number> => {\n planHistory.begin();\n try {\n for (let step = 0; step < steps; step++) {\n const eventsBefore = planHistory.events;\n await roomDesignerApi.extended[direction]();\n const confirmed = await planHistory.waitForEvents(\n eventsBefore + 1,\n HISTORY_EVENT_WAIT_MS,\n );\n if (!confirmed) {\n return step;\n }\n }\n return steps;\n } finally {\n planHistory.end();\n }\n };\n\n // undo reverts the last tool call that changed the plan, redo brings back the\n // last one undo reverted - only while the plan is as that call left it. The\n // server cannot keep the user from changing the plan in the planner while a\n // tool call runs, and such a change sits among the call's steps: an undo or\n // redo that does not give back the plan before or after the call is taken\n // back, so it never leaves a wrong revert in place.\n const revertToolCall =\n (direction: HistoryDirection): ToolExecutor =>\n async (roomDesignerApi) => {\n const undo = direction === 'undo';\n const call = undo ? planHistory.lastDone() : planHistory.lastUndone();\n const answer = async (tool: string | null, hint?: string) => ({\n [undo ? 'undone' : 'redone']: tool,\n groups: agentFacingGroups(await planGroups(roomDesignerApi)),\n ...(hint && { hint }),\n });\n if (!call) {\n return answer(\n null,\n planHistory.changedInPlanner\n ? CHANGED_IN_PLANNER\n : undo\n ? NOTHING_TO_UNDO\n : NOTHING_TO_REDO,\n );\n }\n const [from, to] = undo\n ? [call.groupsAfter, call.groupsBefore]\n : [call.groupsBefore, call.groupsAfter];\n if ((await readGroupsKey(roomDesignerApi)) !== from) {\n planHistory.forget();\n return answer(null, CHANGED_IN_PLANNER);\n }\n const done = await stepHistory(roomDesignerApi, direction, call.steps);\n if (done < call.steps) {\n planHistory.forget();\n return answer(\n null,\n done === 0\n ? `The planner's undo history no longer holds ${call.tool} - the plan was loaded again, nothing was ${undo ? 'undone' : 'redone'}.`\n : `The planner's undo history ended after ${done} of ${call.steps} steps of ${call.tool} - check the plan with get-plan-context.`,\n );\n }\n if ((await readGroupsKey(roomDesignerApi)) !== to) {\n const back = await stepHistory(\n roomDesignerApi,\n undo ? 'redo' : 'undo',\n call.steps,\n );\n const restored =\n back === call.steps &&\n (await readGroupsKey(roomDesignerApi)) === from;\n planHistory.markChangedInPlanner();\n const missed = `${undo ? 'Undo' : 'Redo'} of ${call.tool} did not give back the plan ${undo ? 'before' : 'after'} it - the plan was changed in the planner while the tool call ran.`;\n return answer(\n null,\n restored\n ? `${missed} The ${direction} was taken back and the plan is as it was; the planner's undo button reverts the changes made there.`\n : `${missed} The ${direction} could not be taken back completely - check the plan with get-plan-context.`,\n );\n }\n if (undo) {\n planHistory.markUndone();\n } else {\n planHistory.markRedone();\n }\n const changed = changedGroupIds(call);\n const groups = await planGroups(roomDesignerApi);\n const removed = [...changed].filter(\n (id) => !groups.some((group) => group.id === id),\n );\n return {\n [undo ? 'undone' : 'redone']: call.tool,\n ...changedGroupsOnly(agentFacingGroups(groups), (group) =>\n changed.has(group.id),\n ),\n ...(removed.length > 0 && { removedGroupIds: removed }),\n };\n };\n\n // The tools that change the plan run in the planner page: roomle-ui performs\n // the tool with the agent's arguments and reports the planner steps it made,\n // which the server records for undo. A tool that failed after it changed the\n // plan answers with its error and its steps: the steps are recorded, so undo\n // reverts them, and the agent gets the error. A change the library could not\n // calculate is discarded in the planner before it is loaded; libraryFailures\n // of a result name what a follow-up calculation of the call left.\n const inPlanner = (\n tool: string,\n shape: (result: any, args: Record<string, unknown>) => any = (result) =>\n result,\n ): ToolExecutor =>\n planChange(tool, async (roomDesignerApi, args) => {\n const result = {\n ...(await roomDesignerApi.extended.externalObjectGroupOperation(\n tool,\n args,\n )),\n };\n delete result.historySteps;\n delete result.historyFollowUps;\n if (typeof result.error === 'string') {\n throw new Error(result.error);\n }\n if (result.groups !== undefined) {\n result.groups = agentFacingGroups(result.groups);\n }\n if (result.fittings !== undefined) {\n result.fittings = agentFacingFittings(result.fittings);\n }\n return shape(result, args);\n });\n\n return {\n 'add-interior-fitting': inPlanner('add-interior-fitting'),\n 'move-interior-fitting': inPlanner('move-interior-fitting'),\n 'delete-interior-fittings': inPlanner('delete-interior-fittings'),\n 'replace-interior-fitting': inPlanner('replace-interior-fitting'),\n 'open-or-close-group': inPlanner(\n 'open-or-close-group',\n doorsAndDrawersResult('groupId'),\n ),\n 'open-or-close-article': inPlanner(\n 'open-or-close-article',\n doorsAndDrawersResult('rootModuleId'),\n ),\n 'get-interior-design-options': oneAtATime(async (api, args) => {\n const { groupId, rootId, containerModuleId, articleId } = args;\n if (typeof groupId !== 'string' || !groupId.trim()) {\n throw new Error('groupId is required for interior discovery.');\n }\n const { interiorDesign } =\n await api.extended.getExternalObjectPlanContext(['interiorDesign'], {\n interiorDesign: {\n groupId,\n ...(typeof rootId === 'string' && { rootId }),\n ...(typeof containerModuleId === 'string' && { containerModuleId }),\n ...(typeof articleId === 'string' && { articleId }),\n },\n });\n return interiorDesign?.fittings === undefined\n ? interiorDesign\n : {\n ...interiorDesign,\n fittings: agentFacingFittings(interiorDesign.fittings),\n };\n }),\n // The plan and the library context arrive agent-ready from the planner API\n // (compacted sections, 3D room contours with derived walls, the groups in\n // the frame a placement names); the executor asks each for its sections,\n // names the walls and leaves out the articles' corner points.\n 'get-plan-context': oneAtATime(async (roomDesignerApi, args) => {\n // an unknown section is ignored\n const named = (Array.isArray(args.include) ? args.include : []).filter(\n (section) =>\n PLAN_CONTEXT_SECTIONS.includes(section) ||\n SERVER_SECTIONS.includes(section),\n );\n const include = named.length > 0 ? named : DEFAULT_SECTIONS;\n const withDescriptions = include.includes(ARTICLE_DESCRIPTIONS);\n const withAttributes = include.includes(ATTRIBUTES);\n const requested = include.filter(\n (section): section is PlanContextSection =>\n PLAN_CONTEXT_SECTIONS.includes(section),\n );\n // the descriptions and the vocabulary come with the articles\n const withArticles =\n (withDescriptions || withAttributes) && !requested.includes('articles');\n // the walls name the doors and windows of the obstacles, and they tell\n // a window's gap from a slope by them\n const withRooms =\n requested.includes('obstacles') && !requested.includes('rooms');\n const withObstacles =\n requested.includes('rooms') && !requested.includes('obstacles');\n // the vocabulary comes with the master data\n const withMasterData =\n withAttributes && !requested.includes('masterData');\n const sections = [\n ...requested,\n ...(withRooms ? ['rooms' as const] : []),\n ...(withObstacles ? ['obstacles' as const] : []),\n ...(withArticles ? ['articles' as const] : []),\n ...(withMasterData ? ['masterData' as const] : []),\n ];\n const planSections = sections.filter(\n (section) => !LIBRARY_CONTEXT_SECTIONS.includes(section),\n );\n const librarySections = sections.filter((section) =>\n LIBRARY_CONTEXT_SECTIONS.includes(section),\n );\n const [planContext, libraryContext] = await Promise.all([\n planSections.length > 0\n ? roomDesignerApi.extended.getExternalObjectPlanContext(planSections)\n : {},\n librarySections.length > 0\n ? roomDesignerApi.extended.getExternalObjectLibraryContext(\n librarySections,\n )\n : {},\n ]);\n if (!isObject(planContext)) {\n return planContext;\n }\n if (!isObject(libraryContext)) {\n return libraryContext;\n }\n const result: Record<string, any> = {\n ...planContext,\n ...libraryContext,\n };\n if (result.obstacles !== undefined) {\n result.obstacles = agentFacingObstacles(result.obstacles, result.rooms);\n }\n if (result.rooms !== undefined) {\n result.rooms = agentFacingRooms(result.rooms, result.obstacles);\n }\n if (result.groups !== undefined) {\n result.groups = agentFacingGroups(result.groups);\n }\n if (result.masterData !== undefined) {\n result.masterData = agentFacingMasterData(result.masterData);\n }\n if (withRooms) {\n delete result.rooms;\n }\n if (withObstacles) {\n delete result.obstacles;\n }\n if (Array.isArray(result.articles)) {\n const articles = result.articles as any[];\n if (withDescriptions) {\n result[ARTICLE_DESCRIPTIONS] = articles.map(\n ({ articleId, desc }) => ({\n articleId,\n desc,\n }),\n );\n }\n result.articles = articles.map((article) =>\n agentFacingArticle(article),\n );\n }\n if (withAttributes && result.masterData !== undefined) {\n result[ATTRIBUTES] = agentFacingAttributes(\n result.masterData,\n Array.isArray(result.articles) ? result.articles : [],\n );\n }\n if (withArticles) {\n delete result.articles;\n }\n if (withMasterData) {\n delete result.masterData;\n }\n return result;\n }),\n\n 'find-attributes': oneAtATime(async (roomDesignerApi, args) => {\n const words = searchWords(String(args.text ?? ''));\n const ids = (Array.isArray(args.ids) ? args.ids : []).filter(\n (id): id is string => typeof id === 'string' && id.length > 0,\n );\n if (words.length === 0 && ids.length === 0) {\n throw new Error('text or ids must not be empty.');\n }\n const libraryId = args.libraryId as string | undefined;\n const [planContext, libraryContext] = await Promise.all([\n roomDesignerApi.extended.getExternalObjectPlanContext(['groups']),\n roomDesignerApi.extended.getExternalObjectLibraryContext([\n 'masterData',\n ]),\n ]);\n const context = {\n groups: planContext?.groups,\n masterData: agentFacingMasterData(libraryContext?.masterData),\n };\n // the attributes the root modules in the plan and their sub modules\n // carry - the worktop of a group, not a panel top it does not have\n const inPlan = new Set(\n rootsOfGroups((context.groups ?? []) as any[]).flatMap((root) =>\n [root, ...((root?.subModules ?? []) as any[])].flatMap((module) =>\n ((module?.attributes ?? []) as any[]).map(\n (attribute) => attribute?.id,\n ),\n ),\n ),\n );\n const named: any[] = [];\n const matches: any[] = [];\n for (const [id, masterData] of Object.entries(\n (context.masterData ?? {}) as Record<string, any>,\n )) {\n if (libraryId && id !== libraryId) {\n continue;\n }\n // The master data arrives compacted: every attribute, the root modules\n // and the sub modules with the attributes they carry.\n const carriers = (modules: any[], attributeId: string) =>\n modules\n .filter((module: any) =>\n (module.attributes ?? []).includes(attributeId),\n )\n .map((module: any) => ({ id: module.id, name: module.name }));\n for (const attribute of masterData.attributes ?? []) {\n const isNamed = ids.includes(attribute.id);\n if (\n !isNamed &&\n !(words.length > 0 && attributeMatches(attribute, words))\n ) {\n continue;\n }\n const subModules = carriers(\n masterData.subModules ?? [],\n attribute.id,\n );\n (isNamed ? named : matches).push({\n libraryId: id,\n ...attribute,\n rootModules: carriers(masterData.modules ?? [], attribute.id),\n ...(subModules.length > 0 && { subModules }),\n });\n }\n }\n // the attributes named by id in the order of the ids, then the text\n // matches\n const ranked = [\n ...[...named].sort((a, b) => ids.indexOf(a.id) - ids.indexOf(b.id)),\n ...matches.filter((match) => inPlan.has(match.id)),\n ...matches.filter((match) => !inPlan.has(match.id)),\n ];\n const notFound = ids.filter(\n (attributeId) => !named.some((match) => match.id === attributeId),\n );\n const hints = [\n ...(notFound.length > 0\n ? [\n `No attribute has the id ${notFound.map((attributeId) => `\"${attributeId}\"`).join(', ')} - the ids are in the attributes section of get-plan-context.`,\n ]\n : []),\n ...(matches.length > MAX_ATTRIBUTE_MATCHES\n ? [\n `Only the first ${MAX_ATTRIBUTE_MATCHES} of ${matches.length} matches are listed - narrow the text.`,\n ]\n : []),\n ];\n return {\n matches: withSharedSelectionsOnce(\n ranked.slice(0, named.length + MAX_ATTRIBUTE_MATCHES),\n ),\n total: named.length + matches.length,\n ...(notFound.length > 0 && { notFound }),\n ...(hints.length > 0 && { hint: hints.join(' ') }),\n };\n }),\n\n 'create-or-replace-groups': inPlanner('create-or-replace-groups'),\n 'place-group': inPlanner('place-group'),\n 'change-module-attribute': inPlanner(\n 'change-module-attribute',\n compactAttributeResult,\n ),\n 'change-group-attribute': inPlanner(\n 'change-group-attribute',\n compactAttributeResult,\n ),\n 'delete-group': inPlanner('delete-group'),\n 'delete-article-in-place': inPlanner('delete-article-in-place'),\n 'delete-article-and-compact': inPlanner('delete-article-and-compact'),\n 'merge-article-into-group': inPlanner('merge-article-into-group'),\n 'exchange-root-module': inPlanner('exchange-root-module'),\n 'insert-article-into-group': inPlanner('insert-article-into-group'),\n 'swap-root-modules': inPlanner('swap-root-modules'),\n 'merge-groups': inPlanner('merge-groups'),\n\n undo: oneAtATime(revertToolCall('undo')),\n\n redo: oneAtATime(revertToolCall('redo')),\n\n 'get-skill': async (_roomDesignerApi, { name, file }) =>\n isSkillFile(file === undefined ? undefined : String(file))\n ? readSkill(skills, String(name))\n : readSkillFile(skills, String(name), String(file)),\n\n 'get-price': oneAtATime(async (roomDesignerApi) => {\n const price = await roomDesignerApi.extended.fetchPrice();\n return withNotBuiltHint(\n price,\n await planGroups(roomDesignerApi),\n 'The price',\n );\n }),\n\n 'get-order-data': oneAtATime(async (roomDesignerApi) => {\n const snapshot = await roomDesignerApi.extended.getExternalObjectSnapshot(\n {\n orderData: true,\n },\n );\n return withNotBuiltHint(\n snapshot?.orderData ?? null,\n await planGroups(roomDesignerApi),\n 'The order data',\n );\n }),\n\n // waits like get-plan-context, so the images show the plan and the doors\n // after the change or the opening sent before them\n 'get-plan-images': oneAtATime(async (roomDesignerApi) => {\n const snapshot = await roomDesignerApi.extended.getExternalObjectSnapshot(\n {\n perspectiveObjectImage: true,\n topImage: true,\n keepOpenGeometry: true,\n imageType: PLAN_IMAGE_TYPE,\n imageQuality: PLAN_IMAGE_QUALITY,\n },\n );\n return {\n perspectiveObjectImage: snapshot?.perspectiveObjectImage,\n topImage: snapshot?.topImage,\n };\n }),\n };\n};\n","import { z } from 'zod';\nimport type { HiAgentPrompts } from '../hi-agent-prompts';\nimport { fromAgentFrame, toAgentFrame } from './agent-frame';\nimport { mcpTool } from './mcp-tool';\nimport type { HiAgentTools, McpToolResult } from './mcp-tool-types';\nimport { PlanHistory } from './plan-history';\nimport { createPlannerApi } from './planner-api';\nimport type { HiMcpPlannerApi } from './planner-api';\nimport { isSkillFile, skillIndex, skills } from './skills';\nimport { PLAN_IMAGE_TYPE, createToolExecutors } from './tool-executors';\n\nconst MOUNTING_GUIDANCE =\n 'Choose articles and mounting settings from their descriptions and attributes; categories organize the catalog. ' +\n 'For an article used at wall level, above names the root module below it and gapMm sets the clearance; ' +\n 'rightOf or leftOf continues that wall row, including its finishing parts. ' +\n 'Fetch articleDescriptions when its mounting requirements are unclear.';\n\nconst AUTHORING_RULES = `Authoring rules for pos groups:\n- ${MOUNTING_GUIDANCE}\n- Words: the catalog offers articles - cabinets, wardrobes, appliances, panels. A group is one piece of furniture made of articles: a kitchen, a wardrobe, a sideboard, a utility room, a row of cabinets. An article placed in a group is a root module (root for short); the user may call it a cabinet, a unit or a module. The description says what an article is and dimensions give its size. The user decides which articles stand next to each other: a low cabinet between two high cabinets is an order like any other. When the user names a kind, not an article, take the article of that kind from the category of its neighbours where that category has one (a kitchen cabinet into a kitchen, a wardrobe into a wardrobe), else the closest kind of another category.\n- A group is { id?, libraryId?, placement?, roots: [...] }. A root module is an article pick and nothing else: { id, articleId, attributes? } plus one relation that names its neighbour (rightOf, leftOf, onTop, above or behind - see Relations below). The server ignores every other field - a position on a root or a group included - and drops roots marked isGenerated (worktop, toe kick - the library regenerates them). Every root position comes from its relation; the position of a new group comes from its placement. Groups returned by get-plan-context carry their docking as contextData instead - resubmit them as they are. Use a unique id of your choice for new roots (the planner regenerates it and remaps your docking references); keep the real ids of roots that already exist in a replaced group. Choose the articleId from the article catalog of get-plan-context: desc and category say what an article is and what it is for, dimensions give its size (per size attribute its id, its name - e.g. Width, Depth, Height - and its value in millimetres; a root in groups carries the same attribute ids among its attributes, and change-module-attribute with that attribute id, never its name, changes the size of a root module; an article of another size - \"a 900 mm cabinet\" - is the same article with that attribute set, which merge-article-into-group, insert-article-into-group and exchange-root-module take in their attributes), dockingVectors the names of its docking vectors, subModules its fronts and appliances, cornerArticle true marks an article made for a room corner. Sub-modules come with the article. For Interior Design, interior fittings or sub-articles use get-interior-design-options and the interior fitting tools; never author nested module trees. Ask for clarification when the requested interior change or installed instance is ambiguous. Identify an upper/lower fitting from its measured position in the same parent, never its array order. attributes is an optional list of { id, value } overrides of that root module - an attribute only its sub modules carry is set on those sub modules; a material for the whole group - the fronts, the worktop, the carcase - goes into the group's attributes ({ id, value } entries beside roots), and the server sets it on every root module and on the worktop; a root module that names its own value of it in its attributes keeps that value - an accent, e.g. dark wall units in a light group. Attribute ids are in the attributes section of get-plan-context - every attribute of the library. It lists the values (selections) of the attributes a planning sets at the create - a value list several attributes share is listed once, sameSelectionsAs names the attribute that lists it - and for every other attribute the number of its values (valueCount): find-attributes with their ids returns those values, several attributes in one call. The desc of a colour value carries its code. A value is a selection's value - send \"324\", not \"White\": a name, desc or colour code sent as the value is read as that value and named in corrections. The first kitchen does not wait for a lookup: in the create, set the attributes whose values the section lists - a material (fronts, worktop, carcase, handles) only when the request asks for one; an attribute with valueCount keeps its article's value until you change it after the create. find-attributes answers a question about an attribute. Everything else the calculation needs is completed automatically from the article template.\n- Every desc - of an article, a root, a module, an attribute and an attribute value - is authoritative: trust it for what that article, module or value is, and trust dimensions for how big an article is. A colour code in the desc of an attribute value - Cloudy blue (#506080) - is the colour of that value: take it as it is, and tell light from dark and one hue from another by it, not by the name. All of them are authoritative over the catalog images of the master data (imageUrl): never take the kind or the size of an article, or the colour of a value, from a catalog image. A desc says what an article is, not where the user may put it.\n- Fronts: the front program says how a front is built - by its desc: simple fronts, frame fronts with wooden filling, mitred frame fronts with glass filling, milled fronts. Choose it by its desc first, then the front colour. A program offers only some colours: a colour it does not offer switches the program to one that does, and the fronts are then built as that program says; a program resets a colour it does not offer. corrections name every such change. When the colour the user wants comes only with fronts built differently, keep the fronts the user wants: undo a switched program, take the closest colour their program offers, and tell the user which fronts the wanted colour comes with.\n- Doors: a door is hinged on one side and has its handle on the other. In a row, the door at the left end is hinged on the left and the door at the right end on the right, as seen from the front, so no handle is on the outside of the row; a pair of doors side by side is hinged at its two outer sides. The wall units hanging side by side above a floor row form a row of their own, docked to each other or each above its floor unit; it ends at a wall, at a gap or beside a tall unit, and its end doors are hinged like those of a floor row. Set it with the attribute whose values say on which side a door is hinged - the value for single doors or for a pair of doors, as the article has - in the attributes of the root modules at the two ends of the row (rowIndex 1 and the last), and again on the root module at an end after an edit that gives the row a new end: an article added, exchanged or swapped at an end, an end article deleted, or a delete that leaves the gap and so splits the row into two rows. A single door that is a row of its own - one root module - keeps its side: both its sides are outer sides. The other doors keep their side.\n- One piece of furniture is one group. Every article standing beside, above or back to back with another article is a root module of the SAME group, related to it; a new group carries one placement, and the planner derives every root position from the relations. Never create a second group to put articles next to existing ones - articles that belong together are related.\n- Never author a position: roots are positioned by their relation only, a new group with placement only; a position on a root or a group is ignored.\n- Relations: every root after the first names one neighbour of the same group by its id, with exactly one of these fields - the server builds the docking from it:\n rightOf: \"<id>\" - the article stands right of that root module; leftOf: \"<id>\" - left of it (right and left as seen from the front). A row is each root module rightOf the one before.\n onTop: \"<id>\" - the article stands on top of that root module (stacking on a tall unit or a wall unit, also several levels); align: \"left\" (default), \"right\" or \"back\" says which edges line up, gapMm lifts it.\n above: \"<id>\" - a wall unit hanging above that floor-standing root module, its top flush with the tall units; gapMm sets another gap below it - the same for every wall unit of the group. A wall unit rightOf or leftOf another wall unit hangs at that wall unit's bottom, so a shorter wall unit whose top lines up with its neighbours stands onTop of the root module below it, e.g. an open shelf unit.\n behind: \"<id>\" - back to back with that root module, turned by 180 degrees: an island, a peninsula, and the panel that closes the back of such a row. A panel behind a row is anchored by the server at the row's start end - the corner article of a peninsula leg, else the row's first unit as seen from its front - and runs along the whole row, so name any unit of the row; size the panel to the row's whole back, a corner's back included (corner articles list their cornerBackLengthsMm).\n A wall unit rightOf or leftOf a tall unit hangs beside it with the tops flush, on the side of the base units (leftOf a tall unit that ends the row on the right); further wall units continue rightOf or leftOf each other. Without a tall unit, the first wall unit hangs above a floor unit and the next ones continue rightOf or leftOf it. A range hood hangs above the hob unit, with its own gapMm; the next wall unit past the hood hangs above its own floor unit.\n A room corner (an L-shaped kitchen, \"in the corner\"): start the group with a corner article (cornerArticle true in the catalog), give the group a placement at one wall of that corner with the other wall as alignment (the back right corner: wall right, alignment back), and continue one row rightOf the corner article and the other row leftOf it - the complete payload is example 3. The wall units of each leg hang above the floor units of that leg: the first one above a floor unit of the leg, the next ones rightOf or leftOf it; never put a wall unit on or above the corner article. Prefer a corner article over butting two straight articles together in a corner; a U-shaped kitchen continues a row with a second corner article.\n A root without a relation continues the row of its kind: right of the previous floor-standing root module or wall unit in the list; corrections says so.\n- Docking vectors: groups from get-plan-context show their docking as contextData - per root its ownDockingVector and the dockingVector of each root it names. RightBottom -> LeftBottom puts that root to the right, LeftBottom -> RightBottom to the left, a Top vector -> a Bottom vector on top, BackBottom -> BackBottom back to back. Two root modules that name each other with RightBottom -> LeftBottom stand side by side. freeDockingVectors are the vectors a new root module can dock to; merge-article-into-group names them in dockTo.\n- placement positions a new group, in one of two forms. At a wall or in a room corner: { wall, alignment?, offsetMm?, roomIndex? } - wall a side label (left, right, back, front; back = top, front = bottom in the top-view image) or the index of a wall in the walls array; alignment center (the default), the side label of the adjoining wall to stand flush in the corner the two walls share (wall back with alignment right: the back right corner; with two corner articles the first one in roots goes into the corner), or end; offsetMm moves the group along the wall away from that corner or from the wall's end; roomIndex the room, 0 by default. The server computes the point and the rotation from the calculated group, as place-group does; a group that would overlap another group moves along the wall to the nearest free place, and corrections say so. The wall form stands a new group on the floor; a new group of wall units only hangs at the wall-unit height, which the server sets and corrections name. Anywhere else - an island, the middle of the room - and for a group of wall units only: { posGroup: [x, y, z], posRotationZ, rootId? } - posGroup the room point of the group's back left bottom corner in millimetres - of the whole group, a rear panel behind the row included (z up, z = 0 on the floor; for a group of wall units only, their mounting height), posRotationZ its rotation in degrees, counter-clockwise as seen from above (in the top-view image), required, 0 for no rotation; rootId optional: with two corner articles, the one that goes into the corner posGroup names. A placement is applied exactly once, when the group is created; a placement on a group that is already in the plan is not used (move it with place-group), and groups returned by get-plan-context never carry this field.\n- Walls: every room of get-plan-context carries a walls array - per wall its index, roomIndex, side, name (back wall, front wall, left wall, right wall), start and end (points [x, y, 0] on the floor, in the coordinates of posGroup), lengthMm, type and facingRotationZ, the posRotationZ of a group with its back against that wall (back 0, left 90, front 180, right 270 in a rectangular room); a door or a floor-to-ceiling window splits a wall into several entries of the same side and name - pieces of type wall and the openings between them, each piece of wall free at the floor over its lengthMm, and a window above the floor leaves the floor below it free; a side label names the whole wall, and the server puts the group on its longest piece of wall, or across the openings when no piece is wide enough. Every room carries its index, and the same wall names repeat in every room - a wall a prompt describes is the one of the room the description fits, and a placement names the room with roomIndex (0 by default). Per wall: openings - the doors and windows in it with kind, fromEndMm span and bottomMm/topMm -, slopeFromMm - above that height part of the wall is open: a sloping ceiling or a roof (the room's levels carry the contour per height, pos [x, y, level], level the height above the floor; the slices above 0 are the ceiling). Per room, faces lists each side's whole run of wall pieces - index, side, name, lengthMm, openingMm, openingShare (above 0.5 mostly openings, a glass front; 0 a solid wall), slopeFromMm. For a group anywhere else (an island, the middle of the room, next to a door): any point on the floor as posGroup, any posRotationZ.\n- Room corners: every room of get-plan-context carries a corners list - per corner its name (back left, back right, front left, front right; back = top, front = bottom in the top-view image) and its point. A group in a room corner names one of the two walls as wall and the other as alignment; a corner article first in the group goes into the corner. Looking into the corner from the room, the root modules rightOf the corner article run along the wall on the right, the root modules leftOf it along the wall on the left (the back right corner: rightOf along the right wall, leftOf along the back wall). This holds for both hands of corner article.\n- Obstacles: the obstacles section of get-plan-context lists what stands in the room, in the coordinates of the walls - objects (doors, windows, other furniture) with kind, outline (floor points [x, y, 0]) and bottomMm to topMm, a door or a window also with roomIndex, wall (its index in the walls array) and fromEndMm, its span along that wall measured from the wall's end -, and per group its root modules with id, outline and bottomMm to topMm. Root outlines bound the calculated parts and can reach past the docking edges over a neighbour in the same group - a part over a neighbour is no placement error; two root modules of one group whose bodies overlap are, and the hint of create-or-replace-groups names them. A group goes where the user puts it - the wall, the corner or the spot the user names, also when a door, a window or other furniture is there: the result's hint names what it stands in front of or on, and your answer says so. Where the user leaves the place open, choose a stretch of wall or a spot that obstacles leaves free: fromEndMm is measured from the wall's end, so a placement with that wall, alignment end and offsetMm = the start of a free stretch puts the group on it; base units lower than a window's bottomMm fit below it. Along a wall the user names, choose its free stretch the same way; when none is as wide as the group, put the group on that wall where it stands on the least, and your answer names what it stands on and the alternatives - another wall where it fits, narrower units. A group placed in a room corner reaches along the adjoining wall by its depth: a door or a window of the adjoining wall that begins within that depth of the corner is in its way - when the user leaves the corner open, choose the other corner, or an offsetMm of at least 600 mm from that corner, which keeps the group out of the 600 mm strip in front of the opening. The result's hint names every root module that overlaps an object or another group or stands in front of a door or a window, with the free stretches of its wall; for an obstacle on the group's own wall it names the offsetMm with alignment end of a free stretch the whole group fits, for a group placed by point a free point as posGroup and posRotationZ, and for a group placed at a wall in front of a door or a window of the adjoining wall the offsetMm that keeps it clear.\n- Extending a group: articles next to an existing group are root modules of that group, never a new group. Dock each new article to a free docking vector of the root module it continues (freeDockingVectors per root: a free LeftBottom takes the new root's RightBottom, a free RightBottom takes LeftBottom, a free Top vector takes the new root's Bottom vector) - one article with merge-article-into-group, several at once by adding the picks, each with its relation, to the group from get-plan-context and resubmitting it with its id; an article between two root modules with insert-article-into-group. A new root module inherits the attributes the library passes on between neighbours - fronts, handles, carcase - from the root module it is docked to (insert-article-into-group: the first of between), as in the planner; its attributes override them. Never position a new group against an existing one.\n- To move an existing group, call place-group with wall, alignment and offsetMm at a wall or in a corner, or posGroup and posRotationZ anywhere else. A point names the same back left docking corner as a new group's placement; rootId selects the anchor with two corner articles. The group keeps its roots and docking.\n- To change an existing group, use the command tools: merge-article-into-group adds an article at a free end of a row, insert-article-into-group inserts an article between two root modules, delete-article-and-compact deletes an article and closes the gap, delete-article-in-place deletes an article and leaves the gap (root modules no longer docked together become separate groups where they stand), exchange-root-module replaces a root module - with attributes also by an article of another width -, swap-root-modules lets two root modules change places, delete-group deletes a group, change-module-attribute and change-group-attribute set attributes, merge-groups joins groups where they stand (nothing is moved, no docking is added). Delete and remove mean the same: delete-article-in-place, unless the user asks to close the gap - then delete-article-and-compact. In an insert, a delete that closes the gap, an exchange or a swap the root modules at a wall or in a corner keep their place and the others move; wall units and the range hood move with the root module they hang from. Every command returns the changed groups. To rebuild a group, take it from get-plan-context, change it, and resubmit it with its id and without placement via create-or-replace-groups - it keeps its position; keep the ids of the root modules you keep.\n- Calculated roots, including generated surfaces, carry measured bottomMm and topMm in room-space millimetres when visible geometry and placement are known. These are read-only facts, not input attributes. Missing heights are unknown.\n- Verify results numerically: the returned groups carry position (pos, rotationZ, footprint), standsAt - where the group stands in the words of the plan context: the wall with its fromEndMm span along it (along the whole wall of that side, its pieces joined, measured from its end; the fromEndMm of a door or a window runs along its piece), the corner of a corner group, or a point in the room, with bottomMm/topMm - and per root the dockingVectors, the input attributes, the docking, rowIndex and wall, the wall it stands at - check that each row and each leg of a corner stands at the wall you meant, and name standsAt in your answer instead of deriving the place from the coordinates; the hint names a root module that stands on an obstacle. Do not judge a position from a rendering alone.\n- A root module named by its place - the middle unit, the second from the left, the last one - is found by rowIndex: its place in its row, 1 at the left end as seen from the front, floor units and wall units counted apart - the wall units hanging side by side above a floor row are a row, docked to each other or not. The roots are listed in the order they were added, not in row order.\n- Undo a wrong result: when a result is not what was asked - the wrong wall, a root module missing or replaced by mistake, a merge or a delete that went wrong - send the corrected call instead of correcting the wrong plan piece by piece: a group of the plan is sent again with its id, and the plan keeps it until the replacement is loaded. undo reverts one tool call and leaves the plan without it until the next call: it serves a call that put something where nothing belongs. A group is sent again for a wrong layout - the wall, the corner, articles missing or wrong; other sizes or materials of its root modules are a change, made with the command tools: change-module-attribute, every root module that takes the same value in one call. undo and redo also serve the user who asks for them: the user's last change is everything you changed for their last request, one undo per tool call that changed the plan, and redo brings back as many.\n- Read corrections, notLoaded and hint in a result: corrections lists what the server changed in your input and has already applied, and what the library changed beyond the attribute you set - a front program switched by a front colour -, and a value a module does not take by the library's own check: it is not set on that module, and the sentence names the values the module takes, so send one of them; notLoaded lists the groups and the roots it could not build, with what to send instead; hint names something to check that stopped nothing - a root module on an obstacle, with the free stretches of its wall; a group that reaches past the end of its wall or out of the room, with how far past; when the user left the place open and the hint names a placement that clears what the group stands on, move the group there with place-group in the same turn. A result that says two units now overlap leaves a plan that cannot be built: resolve it in the same turn with one more call - delete one of them or move it - and say how. A change the library cannot calculate is not made and the plan stays as it was: the answer says that nothing was changed - notLoaded for a group of a create, the error result for every other call - with the root modules, the library's message and what to change.\n\nExample 1 - \"a row of three tall units along the right wall, from the back right corner\" is ONE call, create-or-replace-groups, placed at the right wall, flush into its corner with the back wall:\n{ \"posGroups\": [{ \"libraryId\": \"<libraryId>\", \"placement\": { \"wall\": \"right\", \"alignment\": \"back\" }, \"roots\": [\n { \"id\": \"u1\", \"articleId\": \"<articleId from the catalog>\" },\n { \"id\": \"u2\", \"articleId\": \"<articleId>\", \"rightOf\": \"u1\" },\n { \"id\": \"u3\", \"articleId\": \"<articleId>\", \"rightOf\": \"u2\" }\n] }] }\n\nExample 2 - \"a tall unit and two base units with a wall unit above each\" is the same call with these roots - the wall units hang beside the tall unit with the tops flush:\n { \"id\": \"t1\", \"articleId\": \"<tall unit>\" },\n { \"id\": \"b1\", \"articleId\": \"<base unit>\", \"rightOf\": \"t1\" },\n { \"id\": \"b2\", \"articleId\": \"<base unit>\", \"rightOf\": \"b1\" },\n { \"id\": \"w1\", \"articleId\": \"<wall unit>\", \"rightOf\": \"t1\" },\n { \"id\": \"w2\", \"articleId\": \"<wall unit>\", \"rightOf\": \"w1\" }\nWithout the tall unit, the first wall unit hangs above a base unit: { \"id\": \"w1\", \"articleId\": \"<wall unit>\", \"above\": \"b1\" }.\n\nExample 3 - \"an L-shaped kitchen in the back right corner\" (back = top in the top view) is ONE group starting with the corner article c1, placed at the right wall with the back wall as alignment; looking into the corner from the room, the root modules rightOf c1 run along the right wall, the root modules leftOf it along the back wall (see the corner rules above), and the wall units hang above the floor units of their leg:\n{ \"posGroups\": [{ \"libraryId\": \"<libraryId>\", \"placement\": { \"wall\": \"right\", \"alignment\": \"back\" }, \"roots\": [\n { \"id\": \"c1\", \"articleId\": \"<corner article, cornerArticle true>\" },\n { \"id\": \"r1\", \"articleId\": \"<base unit>\", \"rightOf\": \"c1\" },\n { \"id\": \"r2\", \"articleId\": \"<base unit>\", \"rightOf\": \"r1\" },\n { \"id\": \"l1\", \"articleId\": \"<base unit>\", \"leftOf\": \"c1\" },\n { \"id\": \"l2\", \"articleId\": \"<base unit>\", \"leftOf\": \"l1\" },\n { \"id\": \"w1\", \"articleId\": \"<wall unit>\", \"above\": \"r1\" },\n { \"id\": \"w2\", \"articleId\": \"<wall unit>\", \"above\": \"l1\" }\n] }] }\n\nExample 4 - \"the row centred on the back wall\" is \"placement\": { \"wall\": \"back\" } - centred is the default.\n\nExample 5 - \"add a cabinet to the right of the existing cabinets\" extends that group, never a new group: take the group from get-plan-context, find the root module with a free RightBottom (freeDockingVectors) and call merge-article-into-group { \"groupId\": \"<group id>\", \"articleId\": \"<article>\", \"dockTo\": { \"rootId\": \"<that root module>\", \"ownDockingVector\": \"RightBottom\", \"dockingVector\": \"LeftBottom\" } } - the group keeps its position.\n\nExample 6 - \"insert a low cabinet between the high cabinets\" is insert-article-into-group { \"groupId\": \"<group id>\", \"articleId\": \"<a base cabinet from the catalog>\", \"between\": [\"<first root module>\", \"<second root module>\"] }: the high cabinets are the two root modules of the group that stand side by side - whatever the group is, a wardrobe too -, the low cabinet an article about 720 mm high; the root modules on the side away from the wall move by the article's width, the ones at the wall keep their place.`;\n\n// Put before every SKILL.md: how a planning skill meets this session.\nconst SKILL_IN_SESSION =\n 'In this planning session the survey is the plan context - the walls, the doors and windows, the obstacles, the ' +\n 'installation elements with the positions of the electric plugs and the water connections - and the products are the ' +\n 'article catalog. What the plan context does not carry - services beyond those connection positions, budget, ' +\n 'inventory, the household - ' +\n 'is unknown: plan a concept with stated assumptions and name them in your answer, instead of asking first, unless the ' +\n 'user asks to be interviewed. The layout is the groups you create, one group per piece of furniture: check them against ' +\n 'the returned positions and the obstacles, and name the alternatives and the open checks in your answer instead of ' +\n 'building them.';\n\nexport const getAgentReferenceBlocks = (): NonNullable<\n HiAgentPrompts['referenceBlocks']\n> => [{ id: 'authoring-rules', text: AUTHORING_RULES }];\n\n// The plan context carries a signed CDN image URL for every article, module\n// and attribute value - three quarters of its tokens, and no agent can open them.\n// The order data carries them as downloadUri.\nconst withoutImageUrls = (key: string, value: unknown) =>\n key === 'imageUrl' || key === 'downloadUri' ? undefined : value;\n\nconst textResult = (result: unknown) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result ?? null, withoutImageUrls),\n },\n ],\n});\n\nconst PLAN_CHANGING_TOOLS = [\n 'add-interior-fitting',\n 'move-interior-fitting',\n 'delete-interior-fittings',\n 'replace-interior-fitting',\n 'create-or-replace-groups',\n 'place-group',\n 'change-module-attribute',\n 'change-group-attribute',\n 'delete-group',\n 'delete-article-in-place',\n 'delete-article-and-compact',\n 'merge-article-into-group',\n 'insert-article-into-group',\n 'exchange-root-module',\n 'swap-root-modules',\n 'merge-groups',\n 'undo',\n 'redo',\n];\n\nconst ATTRIBUTE_OVERRIDES = z.array(\n z.object({\n id: z.string(),\n value: z.union([z.string(), z.number(), z.boolean()]),\n }),\n);\n\nconst stripDataUrlPrefix = (image: string): string =>\n image.replace(/^data:image\\/\\w+;base64,/, '');\n\nexport const createHiMcpTools = (\n roomDesignerApi: HiMcpPlannerApi,\n): HiAgentTools => {\n // The tools tell their own planner steps from the changes the user makes in\n // the planner by the planner's history events; the handler the planner's UI\n // and the host set keeps running.\n const planHistory = new PlanHistory();\n const { callbacks } = roomDesignerApi.extended;\n const previousHistoryChange = callbacks.onHistoryChange;\n callbacks.onHistoryChange = (undo: boolean, redo: boolean) => {\n planHistory.historyChanged();\n previousHistoryChange?.call(callbacks, undo, redo);\n };\n const plannerApi = createPlannerApi(roomDesignerApi);\n const toolExecutors = createToolExecutors(planHistory);\n\n const tools: HiAgentTools = {};\n const registerTool = (\n name: string,\n {\n description,\n inputSchema,\n }: { description: string; inputSchema: z.ZodRawShape },\n handler: (args: any) => Promise<McpToolResult>,\n ) => {\n tools[name] = mcpTool(name, description, z.object(inputSchema), handler);\n };\n\n // What the agent sent to a tool that changes the plan, and the feedback it\n // got, go to the log as one JSON line each, so a test run can tell what the\n // agent sent and which corrections and errors it saw. The arguments are\n // copied first, so the log shows them as sent. Every call of a\n // tool that changes the plan ends with one feedback or error line, empty\n // feedback included, so a test run can pair the lines in call order.\n // The agent reads and writes plan space, the executors and the planner\n // pos space: the arguments and the result are converted here.\n const runTool = async (tool: string, args: Record<string, unknown>) => {\n console.log(`[hi-mcp] tool ${tool}`);\n const sent = structuredClone(args);\n if (PLAN_CHANGING_TOOLS.includes(tool)) {\n console.log(`[hi-mcp] tool ${tool} args ${JSON.stringify(sent)}`);\n }\n try {\n const inPosSpace = fromAgentFrame(args);\n const result = toAgentFrame(\n tool,\n await toolExecutors[tool](plannerApi, inPosSpace.args),\n ) as any;\n if (inPosSpace.corrections.length > 0) {\n result.corrections = [\n ...inPosSpace.corrections,\n ...(result.corrections ?? []),\n ];\n }\n const { corrections, notLoaded, hint } = result ?? {};\n if (corrections || notLoaded || PLAN_CHANGING_TOOLS.includes(tool)) {\n console.log(\n `[hi-mcp] tool ${tool} feedback ${JSON.stringify({ corrections, notLoaded, hint })}`,\n );\n }\n return result;\n } catch (error) {\n console.log(\n `[hi-mcp] tool ${tool} error ${JSON.stringify({\n message: (error as Error)?.message ?? String(error),\n args: sent,\n })}`,\n );\n throw error;\n }\n };\n\n const fittingId = z.string().min(1);\n const insertion = z\n .tuple([z.number().finite(), z.number().finite(), z.number().finite()])\n .optional()\n .describe(\n 'Millimetres x right, y towards the back, z up, relative to parentModuleId - the frame of a fitting position from get-interior-design-options; to move a fitting by an offset, add it to that position. Omit for the library default on add, or retain actual placement on move/replace. Read calculated result for adjustments.',\n );\n const destination = z.object({\n rootId: fittingId,\n containerModuleId: fittingId,\n parentModuleId: fittingId,\n });\n registerTool(\n 'get-interior-design-options',\n {\n description:\n 'Inspect Interior Design / interior fittings / sub-articles of one loaded HI group without selecting it. Returns unique installed instance IDs, parent-local positions where each fitting starts, compatible additions with destination tuples and fittings[].replacementArticles for each occupied parent. defaultInteriors lists the parts a parent shows of its own while its container holds no fitting; any fitting added to that parent replaces all of them. Choose replacements from that installed fitting, even when no additions fit. articleId filters addition/replacement candidates. Discover before editing; clarify ambiguous instances or unspecified interior changes. Empty options differ from unsupported or failed discovery. To see the fittings in get-plan-images, open the cabinet with open-or-close-article first.',\n inputSchema: {\n groupId: fittingId,\n rootId: fittingId.optional(),\n containerModuleId: fittingId.optional(),\n articleId: fittingId.optional(),\n },\n },\n async (args) =>\n textResult(await runTool('get-interior-design-options', args)),\n );\n registerTool(\n 'add-interior-fitting',\n {\n description:\n \"Add a compatible Interior Design fitting inside a group, using an article and destination returned by get-interior-design-options. Waits for final calculation/load and returns actual instance IDs, placement and corrections. One undoable action when changed. A fitting added to a parent listed in defaultInteriors replaces all the parts listed there; it does not add to them. A fitting the library cannot calculate is not added and the group stays as it was: the error result says that nothing was changed, with the root module and the library's message, and what to send instead.\",\n inputSchema: {\n groupId: fittingId,\n articleId: fittingId,\n destination,\n insertPosition: insertion,\n },\n },\n async (args) => textResult(await runTool('add-interior-fitting', args)),\n );\n registerTool(\n 'move-interior-fitting',\n {\n description:\n \"Reposition one installed interior fitting or transfer it to a compatible container/root within the SAME group. Use its unique instanceId from discovery. Omitted destination keeps the current parent. Supply a destination and/or insertion point. Recreation may change the instance ID; use returned IDs. A fitting the library cannot calculate is not moved and the group stays as it was: the error result says that nothing was changed, with the root module and the library's message, and what to send instead.\",\n inputSchema: {\n groupId: fittingId,\n instanceId: fittingId,\n destination: destination.optional(),\n insertPosition: insertion,\n },\n },\n async (args) => textResult(await runTool('move-interior-fitting', args)),\n );\n registerTool(\n 'delete-interior-fittings',\n {\n description:\n 'Delete the explicitly identified installed interior fittings of one group, preserving the cabinet and unrelated contents. Validates the entire batch before changing anything, deduplicates IDs with a correction, and makes one undoable action.',\n inputSchema: {\n groupId: fittingId,\n instanceIds: z.array(fittingId).min(1),\n },\n },\n async (args) => textResult(await runTool('delete-interior-fittings', args)),\n );\n registerTool(\n 'replace-interior-fitting',\n {\n description:\n \"Atomically replace one installed interior fitting with an article from its replacementArticles in get-interior-design-options, in its current parent, retaining actual placement and compatible settings. An explicit insertion point overrides placement. Failure restores the original; lost settings and new IDs are returned. A fitting the library cannot calculate is not replaced and the group stays as it was: the error result says that nothing was changed, with the root module and the library's message, and what to send instead. Never implement replacement as separate delete and add calls.\",\n inputSchema: {\n groupId: fittingId,\n instanceId: fittingId,\n articleId: fittingId,\n insertPosition: insertion,\n },\n },\n async (args) => textResult(await runTool('replace-interior-fitting', args)),\n );\n const VIEW_ONLY =\n 'It is a view of the planner: it changes nothing in the plan, is not saved, is not part of undo and changes ' +\n 'neither the price nor the order.';\n registerTool(\n 'open-or-close-group',\n {\n description:\n 'Opens (open true) or closes (open false) every door and drawer of a group at once, so get-plan-images ' +\n 'shows the group as it is - open it to look inside its cabinets. ' +\n VIEW_ONLY +\n ' Returns the groupId and doorsAndDrawers, open or closed - the state they are in now; a group without ' +\n 'doors or drawers is named in corrections instead.',\n inputSchema: {\n groupId: z\n .string()\n .describe('The id of the group, as get-plan-context shows it.'),\n open: z.boolean().describe('true opens, false closes.'),\n },\n },\n async (args) => textResult(await runTool('open-or-close-group', args)),\n );\n registerTool(\n 'open-or-close-article',\n {\n description:\n 'Opens (open true) or closes (open false) the doors and drawers of one root module at once, none of the ' +\n 'root modules next to it, so get-plan-images shows the cabinet as it is - open it to look inside, at its ' +\n 'interior fittings for example. ' +\n VIEW_ONLY +\n ' Returns the rootModuleId and doorsAndDrawers, open or closed - the state they are in now; a root ' +\n 'module without doors or drawers is named in corrections instead.',\n inputSchema: {\n rootModuleId: z\n .string()\n .describe('The id of the root module, as get-plan-context shows it.'),\n open: z.boolean().describe('true opens, false closes.'),\n },\n },\n async (args) => textResult(await runTool('open-or-close-article', args)),\n );\n\n registerTool(\n 'get-plan-context',\n {\n description:\n MOUNTING_GUIDANCE +\n ' Returns a snapshot of the HI planning session - one coordinate system throughout, that of the planner: 3D, ' +\n 'right-handed, Z up, in millimetres, x to the right and y to the top of the top-view image, z = 0 on the ' +\n 'floor (room contours use pos: [x, y, level]). Default ' +\n 'sections: rooms (every room carries its index, its contour levels with 3D segments (pos [x, y, level], ' +\n 'level the height above the floor - the slices above 0 are the ceiling, a sloping ceiling reads from them), ' +\n 'a derived walls array - per wall: index, roomIndex, a side label (left/right/top/bottom as seen in the ' +\n 'top-view image), start/end [x, y, 0] in millimetres (the 3D contour points on the floor), lengthMm, type ' +\n '(wall, or opening for a door or a floor-to-ceiling window), heightMm, thicknessMm and facingRotationZ - the ' +\n 'posRotationZ of a group standing with its back against that wall -, openings (the doors and windows in it: ' +\n 'kind, fromEndMm span, bottomMm/topMm) and slopeFromMm where it applies - and its faces, per ' +\n 'side the whole run of wall pieces with index, side, name, lengthMm, openingMm, openingShare and slopeFromMm), ' +\n 'articles (compact catalog: articleId, ' +\n 'name, desc - what the article is and when to pick it -, category, and per root module its master-data module, dimensions (the size attributes - ' +\n 'e.g. Width, Depth, Height - with their values in millimetres), main attribute values, ' +\n 'docking vector names, insert levels and sub-modules, plus cornerArticle ' +\n 'for articles made for a room corner), attributes (the attribute vocabulary: per library every ' +\n 'attribute with id, name, desc, group and type - the ids ' +\n \"the catalog's mainAttributes, the roots' attributes and their sub modules' attributes carry -, with its values - value, name, desc - \" +\n 'for the attributes a planning sets at the create and valueCount, the number of its values, for every other one, ' +\n 'whose values find-attributes returns by its id; a value list several attributes share is ' +\n 'listed once, sameSelectionsAs names the attribute that lists it; send a value, not its name - ' +\n 'a name, desc or colour code sent as the value is read as that value and named in corrections), ' +\n \"groups (calculated roots include read-only measured bottomMm/topMm in room-space millimetres, including generated surfaces; missing heights are unknown; the groups currently in the plan: position with pos - the room point of the group's back left bottom corner, as a placement names it - rotationZ, rootId (only with two corner articles: the one pos belongs to) and footprint (the x and y ranges of the group from pos, its front towards -y), and standsAt, where the group stands in the words of the plan context - the wall with its fromEndMm span along it (along the whole wall of that side, its pieces joined, measured from its end; the fromEndMm of a door or a window runs along its piece), the corner of a corner group, or a point in the room, with bottomMm/topMm -, and \" +\n 'per root the article pick with input attributes, docking, docking vector names and the free docking vectors ' +\n 'a new root can dock to, plus its desc, its subModules with their input attributes and its rowIndex, its place in its row - 1 at the left end as seen from the ' +\n 'front; floor units and wall units form rows of their own, and the roots are listed in the order they were added -, ' +\n 'and its wall, the name of the wall it stands at; ' +\n 'no root positions, ' +\n 'no geometry; a returned group is a valid create-or-replace-groups payload) and obstacles (what stands in the ' +\n 'room, in the coordinates of the walls: objects - doors, windows, other furniture - with kind, outline ' +\n \"(floor points [x, y, 0]) and bottomMm/topMm, a door or a window also with roomIndex, wall and fromEndMm (its span along that wall from the wall's end); \" +\n 'and per group its root modules with id, outline and bottomMm/topMm), ' +\n 'and installationElements (the electric plugs and the water connections of the plan: per element its type - ' +\n 'ElectricPlug or WaterConnection - and its position [x, y, z] in the coordinates of the walls, z its height; a ' +\n 'position only, no size, and no obstacle: a group may stand on a supply). ' +\n 'When an edit gives a row a new end - an article added, exchanged or swapped at an end, an end ' +\n 'article deleted, or a delete that leaves the gap and splits the row into two rows -, hinge its ' +\n 'end doors at the outer sides: left at the left end, ' +\n 'right at the right end, as seen from the front. A single door that is a row of its own keeps its side. ' +\n \"Choose the attribute and value from the library's \" +\n 'descriptions for single or paired doors, and keep other door directions unchanged. ' +\n 'Root outlines bound the calculated parts and can reach past the docking edges over a neighbour in the same group - ' +\n 'a part over a neighbour is no placement error; two root modules of one group whose bodies overlap are, and the ' +\n 'hint of create-or-replace-groups names them. ' +\n 'When a door or window determines a placement, briefly name it and explain whether the final placement ' +\n 'keeps it clear, using the returned obstacle dimensions and final tool results. masterData (per library the root ' +\n 'modules with their attribute ids, the attributes and the group settings) is returned only when included ' +\n 'explicitly. desc - what an article is and when to pick it - is enough to choose an article; ' +\n 'articleDescriptions (per article its full description: purpose, placement, requirements, neighbours, ' +\n 'restrictions, style) is returned only when included explicitly and answers a question about one ' +\n 'article, not the planning. Every desc is ' +\n 'authoritative and dimensions give the size - trust them over the catalog images (imageUrl); a colour ' +\n 'code in the desc of an attribute value (#rrggbb) is the colour of that value. ' +\n 'A root or a group that carries calculationError is not built: the library could not calculate it with its ' +\n 'attribute values, and calculationError is the first line of its message. Until a value the library can ' +\n 'calculate replaces the one that failed it has no docking vectors and no parts - say so in the answer and ' +\n 'never describe it as planned. The groups of a tool result carry the field as well. Use it before ' +\n 'authoring or modifying groups. When the current library articles and attributes are already supplied, ' +\n 'request rooms, groups, obstacles and installationElements for fresh plan state; retrieve library sections only when missing.',\n inputSchema: {\n include: z\n .array(z.string())\n .optional()\n .describe(\n 'The sections to include: rooms, articles, attributes, groups, obstacles, installationElements, masterData, articleDescriptions. Default: rooms, articles, attributes, groups, obstacles and installationElements. ' +\n 'Add masterData for the root modules of the master data, articleDescriptions for a question about ' +\n \"one article's requirements and neighbours - desc is enough to pick the articles of a planning.\",\n ),\n },\n },\n async ({ include }) =>\n textResult(await runTool('get-plan-context', { include })),\n );\n\n registerTool(\n 'find-attributes',\n {\n description:\n 'Answers a question about an attribute: searches the attribute vocabulary - the attributes section of ' +\n 'get-plan-context - by text (attribute id, name, description, ' +\n 'group or selection name) or by ids and returns the matching attributes with their values (each with ' +\n 'its desc) and the root modules and sub modules that carry them, with their names - the worktop colour is the colour of ' +\n 'the root module Countertop; the attributes the root modules in the plan and their sub modules carry come first. ' +\n 'Your answer names the attribute by its name and its id - several attributes can share a name - with the values it lists. ' +\n 'The attributes section holds every attribute and the values of those a planning sets at the create; ' +\n 'for an attribute it shows with valueCount, send its id in ids to get its values - several ids in one call, ' +\n 'e.g. every attribute of one change. Search by text for the modules that carry an attribute, or for a property - e.g. \"front color\" - whose ' +\n 'attribute the section does not make obvious. Every word of the text is matched on ' +\n 'its own, in any order, British and American spelling alike (colour and color, grey and gray, worktop ' +\n 'and countertop): one search for \"color\" returns every colour attribute - front, carcase, countertop, ' +\n 'toe kick and the others - with their values, and a value list several attributes share is listed once ' +\n '(sameSelectionsAs names the attribute that lists it). The desc of a value carries ' +\n 'its colour code where the library gives one - Cloudy blue (#506080) -, the colour of that value: ' +\n 'pick a dark, a light or a blue value by its code.',\n inputSchema: {\n text: z\n .string()\n .optional()\n .describe('The words to search for, case-insensitive.'),\n ids: z\n .array(z.string().min(1))\n .optional()\n .describe(\n 'Attribute ids: returns these attributes with their values, several in one call.',\n ),\n libraryId: z\n .string()\n .optional()\n .describe('Restricts the search to one library.'),\n },\n },\n async ({ text, ids, libraryId }) =>\n textResult(await runTool('find-attributes', { text, ids, libraryId })),\n );\n\n registerTool(\n 'get-authoring-rules',\n {\n description:\n 'Returns the authoring rules for pos groups: the payload format of create-or-replace-groups, the root ' +\n 'module fields, how to position a new group with a placement and move an existing one with place-group, ' +\n 'the relations a unit names its neighbour with (rightOf, leftOf, onTop, above, behind), the docking vector ' +\n 'names of existing groups, and complete examples for a row against a wall, wall units beside a tall unit, ' +\n 'a group around a room corner and extending a group. Use the supplied authoring rules or fetch this before authoring pos groups when they are missing.',\n inputSchema: {},\n },\n async () => ({\n content: [{ type: 'text' as const, text: AUTHORING_RULES }],\n }),\n );\n\n registerTool(\n 'get-skill',\n {\n description:\n 'Returns a planning skill with the reference it asks to read before planning, in one result: how to plan a room of one kind, ' +\n 'or from an image the user sends, well - the workflow, the zones, the dimensions and the checks. Before planning a room ' +\n 'of a kind listed here, or from an image, follow its skill; use supplied files. file fetches one file of a skill, e.g. its optional source catalog. ' +\n 'Apply only the relevant kind and region; the France kitchen skill replaces the general kitchen skill in France. Skills:\\n' +\n skillIndex(skills),\n inputSchema: {\n name: z.string().describe('The name of the skill'),\n file: z\n .string()\n .optional()\n .describe(\n 'A file of the skill by its path, e.g. references/source-catalog.md; SKILL.md with its planning reference by default',\n ),\n },\n },\n async ({ name, file }) => {\n const text = (await runTool('get-skill', { name, file })) as string;\n const preamble = isSkillFile(file) ? `${SKILL_IN_SESSION}\\n\\n` : '';\n return {\n content: [{ type: 'text' as const, text: `${preamble}${text}` }],\n };\n },\n );\n\n // The payload format of create-or-replace-groups, declared so the schema a\n // model reads first carries the field names. The objects stay open\n // (looseObject): the AI SDK adds additionalProperties: false to nested\n // objects, and a closed object would refuse the fields a model guesses\n // before the server can correct them - the server maps them and names the\n // mapping in corrections. For the same reason the numbers take a string too\n // (a number a model writes as text is read by the server and named) and\n // articleId and roots stay optional: the server answers per group, a typed\n // required field would refuse the whole call at validation.\n const aNumber = z.union([z.number(), z.string()]).optional();\n const posGroupAttributes = z\n .union([\n z.array(\n z.looseObject({\n id: z.string().optional().describe('The attribute id'),\n value: z.unknown().describe('The attribute value'),\n }),\n ),\n z.record(z.string(), z.unknown()),\n ])\n .optional()\n .describe(\n 'Attribute overrides as [{ id, value }]; an object of ids and values is read as such',\n );\n const posGroupPlacement = z.looseObject({\n wall: z\n .union([z.string(), z.number()])\n .optional()\n .describe(\n 'At a wall or in a room corner: a side label (left, right, back, front) or the index of a wall in the walls array of get-plan-context; the wall form stands the group on the floor - a group of wall units only hangs at the wall-unit height',\n ),\n alignment: z\n .string()\n .optional()\n .describe(\n 'center (the default), end, start, or the side label of an adjoining wall to stand flush into that corner',\n ),\n offsetMm: aNumber.describe(\n 'Moves the group along the wall away from that corner or from the wall end, in millimetres - a number',\n ),\n roomIndex: aNumber.describe(\n 'The room of the plan, 0 by default - a number',\n ),\n posGroup: z\n .array(z.union([z.number(), z.string()]))\n .min(2)\n .max(3)\n .optional()\n .describe(\n 'Anywhere else: the room point of the group back left corner [x, y, z] in millimetres - numbers; z = 0 on the floor is completed',\n ),\n posRotationZ: aNumber.describe(\n 'The rotation in degrees, counter-clockwise as seen from above - a number',\n ),\n rootId: z\n .string()\n .optional()\n .describe('With two corner articles, the one that goes into the corner'),\n });\n const posGroupRoot = z.looseObject({\n id: z\n .string()\n .optional()\n .describe(\n 'A unique id of the root module within its group; the relations of the other roots name this id',\n ),\n articleId: z\n .string()\n .optional()\n .describe(\n 'The article id from the article catalog of get-plan-context; a root without one is not built, the others are',\n ),\n libraryId: z.string().optional().describe('The library of the article'),\n attributes: posGroupAttributes.describe(\n 'Attribute overrides of this root module',\n ),\n contextData: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\n 'The docking of a group returned by get-plan-context, resubmitted as it is',\n ),\n rightOf: z\n .string()\n .optional()\n .describe(\n 'The id of the root module this one stands right of, as seen from the front',\n ),\n leftOf: z\n .string()\n .optional()\n .describe(\n 'The id of the root module this one stands left of, as seen from the front',\n ),\n onTop: z\n .string()\n .optional()\n .describe('The id of the root module this one stands on top of'),\n above: z\n .string()\n .optional()\n .describe(\n 'The id of the floor-standing root module this wall unit hangs above',\n ),\n behind: z\n .string()\n .optional()\n .describe('The id of the root module this one stands back to back with'),\n align: z\n .string()\n .optional()\n .describe(\n 'With onTop or above: which edges line up - left (the default), right or back',\n ),\n gapMm: aNumber.describe(\n 'With onTop or above: the clearance below, in millimetres - a number',\n ),\n });\n const posGroup = z.looseObject({\n id: z\n .string()\n .optional()\n .describe(\n 'The group id; an id of an existing group replaces that group and keeps its position',\n ),\n libraryId: z.string().optional().describe('The library of the group'),\n placement: posGroupPlacement\n .optional()\n .describe(\n 'Positions a new group; not used on a group already in the plan',\n ),\n attributes: posGroupAttributes.describe(\n 'A material for the whole group, set on every root module',\n ),\n roots: z\n .array(posGroupRoot)\n .optional()\n .describe(\n 'Every root module of the group from the first call, each after the first naming its neighbour with one relation; non-empty - a group without roots is not built, the others are',\n ),\n });\n\n registerTool(\n 'create-or-replace-groups',\n {\n description:\n MOUNTING_GUIDANCE +\n ' Creates or replaces HI object groups in the plan from an array of pos groups. Roots are article picks ' +\n '({ id, articleId, attributes? }) - the server completes them from the article template -, and every root ' +\n 'after the first names its neighbour with one relation: rightOf, leftOf, onTop, above or behind with the ' +\n 'id of the neighbour; the server builds the docking from it, and the planner arranges the root modules; never author root ' +\n 'positions. Author one piece of furniture as ONE group: articles beside, above or back to back with each other are ' +\n \"related root modules of the same group, never separately positioned groups; a material for the whole group goes into the group's attributes, and a root module's own value of it stays. \" +\n 'A group is created with all its articles in one call: roots holds every article of the group from the first call, each with its relation - a group is never created empty and filled later. ' +\n 'An article beside an existing group goes into that group: merge-article-into-group at the end of a row, insert-article-into-group between two root modules. ' +\n 'Position a new group in the same ' +\n 'call with placement. At a wall or in a room corner: { wall, alignment?, offsetMm?, roomIndex? } - wall a ' +\n 'side label (left, right, back, front) or a wall index; alignment center (the default), the side label ' +\n 'of the adjoining wall, which puts the group flush into that corner (wall back with alignment right: the ' +\n 'back right corner) and a group that starts with a corner article into the corner, or end; offsetMm moves ' +\n \"it along the wall away from that corner or from the wall's end - the fromEndMm of the obstacles is \" +\n 'measured from there; roomIndex the room, 0 by default. The server computes the point and the rotation. ' +\n 'Anywhere else, an island or ' +\n \"a free spot: { posGroup, posRotationZ }, the room point of the group's back left corner and its \" +\n 'rotation. A group whose id matches an existing group completely ' +\n 'replaces that group and keeps its position (root modules keep their ids when they already exist in ' +\n 'the replaced group; a placement on it is not used; a root module the replace adds inherits ' +\n 'the attributes the library passes on between neighbours - fronts, handles, carcase - from the root module it is docked to, and its attributes override them); ' +\n 'the replace is the rebuild - a wrong layout, wall or set of articles: take the group from ' +\n 'get-plan-context, change it and resubmit it with its id. A single edit has its own tool, named by the ' +\n 'words the user says: \"move\" - place-group, \"add one more\" - merge-article-into-group, \"put one between\" - ' +\n 'insert-article-into-group, \"exchange\" or \"wider\" - exchange-root-module, \"swap the two\" - swap-root-modules, ' +\n '\"delete\" - delete-article-in-place, \"change the colour\" - change-module-attribute or change-group-attribute. ' +\n 'all other groups are created with regenerated ids. Returns the loaded object ids, the groups of the call - ' +\n 'each with standsAt, where it stands in the words of the plan context, position with pos and footprint, and its root modules with their article ids - check the position and the count and kinds of units against what the user asked for - and otherGroupIds, the other groups of the plan, unchanged; plus groupAttributes (per group the group attributes set on every unit, ' +\n 'notCarried: attributes no current module carries. For a requested part the library generates, use find-attributes to look for an enabling attribute on the units; ' +\n \"if available, enable it with change-group-attribute after the group is built, then set the part's attributes - a part the library cannot calculate leaves that change unmade and the group as it is. Report only what is still missing. \" +\n 'rootValues: the root modules that keep their own value of one), corrections (what ' +\n 'the server changed in the input, and what the library ' +\n 'changed beyond the attributes sent - a front colour reset by a front program -, and a value of a root or of the group ' +\n \"a root module does not take by the library's own check, which is left out on it, with the values it takes), notLoaded (the groups or \" +\n 'roots it could not build, with what to send instead) and hint (the root modules each built group has, with their articles, a root module that overlaps another root module of its own group, a root module on an obstacle, in another group or in front of ' +\n 'a door or a window, with the free stretches of its wall, the offsetMm and alignment that clear an obstacle on its own wall, a free point for a point placement, and the offsetMm that clears an opening of the adjoining wall). ' +\n \"A group the library cannot calculate is not built and the plan stays as it was: notLoaded says that nothing was changed for it, with the root modules and the library's message; the other groups of the call are built. \" +\n 'The payload format is returned by get-authoring-rules.',\n inputSchema: {\n posGroups: z\n .array(posGroup)\n .min(1)\n .describe(\n 'The pos groups to create or replace, following the rules returned by get-authoring-rules.',\n ),\n },\n },\n async ({ posGroups }) =>\n textResult(await runTool('create-or-replace-groups', { posGroups })),\n );\n\n registerTool(\n 'place-group',\n {\n description:\n 'The tool for \"move\": when the user asks to move, shift or slide an existing group - \"move it to the ' +\n 'other wall\", \"into the back right corner\" - this tool moves it to a wall, a room corner, or a point ' +\n 'and rotation, and reloads it there. ' +\n 'For a freestanding group use posGroup [x, y, z] and posRotationZ: the same placement-frame docking corner and counter-clockwise angle as a new group. rootId selects the anchor with two corner articles. Explicit point targets are kept, including outside the room, with obstacle hints. ' +\n 'At a wall, the ' +\n \"server computes the position from the wall, the alignment and the group's calculated footprint; a \" +\n 'group with a corner article goes into the corner when the alignment names the adjoining wall. A ' +\n 'target that overlaps another group moves along the wall to the nearest free position; corrections in ' +\n 'the result say so. Name the wall by its side ' +\n 'label (left/right/top/bottom as seen in the top-view image) or its index in the walls array of ' +\n 'get-plan-context. Use it to move a group that is already in the plan; a new group takes the same ' +\n 'wall, alignment and offsetMm in its placement in create-or-replace-groups. Returns placedIn (corner, ' +\n 'wall or point), the wall for wall/corner targets, the resulting group and a hint when a root module stands on an object or in front of ' +\n 'a door or a window, with the placement that clears it.',\n inputSchema: {\n groupId: z\n .string()\n .describe(\n 'The id of the group to move. A unique id prefix is accepted.',\n ),\n wall: z\n .union([\n z.enum(['left', 'right', 'top', 'bottom', 'back', 'front']),\n z.number().int().min(0),\n ])\n .optional()\n .describe(\n \"The target wall: a side label as seen in the top view ('right' is the whole right wall, its \" +\n \"doors and floor-to-ceiling windows included; 'back' is 'top', 'front' is 'bottom') or a \" +\n 'wall index from the walls array of get-plan-context, which names one piece of a wall.',\n ),\n roomIndex: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('The index of the room in the rooms array. Defaults to 0.'),\n alignment: z\n .enum([\n 'start',\n 'center',\n 'end',\n 'left',\n 'right',\n 'top',\n 'bottom',\n 'back',\n 'front',\n ])\n .optional()\n .describe(\n \"Where the group sits along the wall: 'center' (default), 'start'/'end' (the wall's endpoints), \" +\n 'or the side label of an adjoining wall to sit flush in that corner (e.g. wall \"right\" + ' +\n 'alignment \"top\" is the back right corner in the top view).',\n ),\n offsetMm: z\n .number()\n .optional()\n .describe(\n 'Extra distance in millimetres along the wall from the chosen alignment. Defaults to 0.',\n ),\n posGroup: z\n .array(z.number())\n .min(2)\n .max(3)\n .optional()\n .describe(\n 'Point target: the placement-frame back left bottom corner [x, y, z] in plan-space millimetres; z is height, omitted z means floor.',\n ),\n posRotationZ: z\n .number()\n .optional()\n .describe(\n 'With posGroup, the rotation in degrees counter-clockwise as seen from above; 0 is valid.',\n ),\n rootId: z\n .string()\n .optional()\n .describe(\n 'With a point target and two corner articles, the root whose docking corner the point names.',\n ),\n },\n },\n async (args) => textResult(await runTool('place-group', args)),\n );\n\n registerTool(\n 'change-module-attribute',\n {\n description:\n 'The tool for \"change the colour of ...\", \"make it wider\" and every other change of one attribute: ' +\n 'sets one attribute of one or more root modules in the plan and of their sub modules that carry it - ' +\n 'a size change (\"wider\", \"900 mm wide\") is the size attribute by its id from the catalog (the dimensions ' +\n 'of the article name the attribute and its value in millimetres), never its name - ' +\n 'the front colour of a root module reaches its fronts -, or with moduleId of that one sub module of ' +\n 'each root module only, and recalculates their groups: name every root module that gets the value in ' +\n 'one call, e.g. the accent fronts of a row. The root modules may belong to one group or to several. ' +\n 'The ids are the ones get-plan-context shows (a sub module by its id in ' +\n 'subModules); attribute ids and values are in the attributes section of get-plan-context, the values of an attribute with valueCount come from find-attributes with its id; send the value of a selection, not its name - a name or desc is read as the value and named in corrections. ' +\n 'The library may change a related attribute with it - a front colour the front program does not offer ' +\n 'switches the program, and the fronts are built differently; corrections name every attribute the ' +\n 'library changed besides the one set. ' +\n \"A value a root module does not take by the library's own check is not set on it; corrections name the values it takes, with their names. \" +\n \"A value the library cannot calculate a root module with is not set and the group stays as it was: the error result says that nothing was changed, with the root modules and the library's message. \" +\n 'Returns the ids of the changed groups and modules and the corrections; get-plan-context shows the groups.',\n inputSchema: {\n rootModuleIds: z\n .array(z.string())\n .optional()\n .describe('The ids of the root modules that get the value.'),\n rootModuleId: z\n .string()\n .optional()\n .describe('The id of a single root module, as one of rootModuleIds.'),\n moduleId: z\n .string()\n .optional()\n .describe(\n 'The id of the sub module. Omit to change the root modules and their sub modules that carry the attribute.',\n ),\n attributeId: z.string().describe('The id of the attribute.'),\n value: z\n .union([z.string(), z.number(), z.boolean()])\n .describe(\n 'The new value: the value of a selection of the attribute (the attributes section lists each value with its name and desc) - a string, a number or a boolean; a name or desc is read as the value.',\n ),\n },\n },\n async (args) => textResult(await runTool('change-module-attribute', args)),\n );\n\n registerTool(\n 'change-group-attribute',\n {\n description:\n 'The tool for \"the whole group in ...\", \"all of them in white\": sets attributes on every module of a ' +\n 'group that has them - the root modules and their sub ' +\n 'modules, e.g. the front colour of a whole group - in one recalculation: one attribute with attributeId ' +\n 'and value, several at once with attributes - all the materials of a group in one call, the programs set ' +\n 'before the colours; attribute ids and values are in the attributes section of get-plan-context, and a ' +\n 'value sent by its name or desc is read as the value and named in corrections. ' +\n 'The library may change a related attribute with it - a front colour the front program does not offer ' +\n 'switches the program, and the fronts are built differently; corrections name every attribute the ' +\n 'library changed besides the ones set, and an attribute no module of the group has. ' +\n \"A value a root module does not take by the library's own check is not set on it; corrections name the values it takes, with their names. \" +\n \"A value the library cannot calculate a root module with is not set and the group stays as it was: the error result says that nothing was changed, with the root modules and the library's message. \" +\n 'Returns the id of the group, the ids of the changed modules and the corrections; get-plan-context shows the group.',\n inputSchema: {\n groupId: z\n .string()\n .describe('The id of the group. A unique id prefix is accepted.'),\n attributeId: z\n .string()\n .optional()\n .describe('The id of the attribute, with value.'),\n value: z\n .union([z.string(), z.number(), z.boolean()])\n .optional()\n .describe(\n 'The new value: the value of a selection of the attribute (the attributes section lists each value with its name and desc) - a string, a number or a boolean; a name or desc is read as the value.',\n ),\n attributes: z\n .array(\n z.object({\n attributeId: z.string(),\n value: z.union([z.string(), z.number(), z.boolean()]),\n }),\n )\n .min(1)\n .optional()\n .describe(\n 'Several attributes set in one recalculation: [{ attributeId, value }].',\n ),\n },\n },\n async (args) => textResult(await runTool('change-group-attribute', args)),\n );\n\n registerTool(\n 'delete-group',\n {\n description:\n 'The tool when the user asks to delete or remove a whole group, not one article of it ' +\n '(delete-article-in-place): deletes a group with all its root modules from the plan. Returns the ' +\n 'id of the deleted group.',\n inputSchema: {\n groupId: z\n .string()\n .describe('The id of the group. A unique id prefix is accepted.'),\n },\n },\n async (args) => textResult(await runTool('delete-group', args)),\n );\n\n registerTool(\n 'delete-article-in-place',\n {\n description:\n 'Deletes an article from its group and leaves the gap - the tool for \"delete\" or \"remove\" when the user does ' +\n 'not ask to close the gap: every other root module keeps its place; root modules that are no longer ' +\n 'docked together afterwards become separate groups where they stand, and deleting the only root module deletes ' +\n 'the group. To close the gap, use delete-article-and-compact. Generated roots (worktop, toe kick) ' +\n 'cannot be deleted - the library regenerates them. Returns the remaining groups.',\n inputSchema: {\n rootModuleId: z.string().describe('The id of the root module.'),\n },\n },\n async (args) => textResult(await runTool('delete-article-in-place', args)),\n );\n\n registerTool(\n 'delete-article-and-compact',\n {\n description:\n 'Deletes an article from its group and closes the gap - the tool when the user asks to close the gap (move ' +\n 'the others up, keep the row together): the root modules beside it are docked together, and the ' +\n 'root modules at a wall or in a corner keep their place. A wall unit or a range hood that hung from the ' +\n 'deleted root module hangs from the one that moves into the gap - unless that one carries a unit above already: ' +\n 'then it keeps its place, and the result names the units that now overlap. A root module with a neighbour on one side only is deleted and ' +\n 'nothing else moves. Deleting a corner article between two legs closes the gap as well: one leg turns by 90 ' +\n 'degrees, with the units above it, and is docked to the other, so the legs form one straight row - the result ' +\n 'names the leg that turned. Deleting the only root module deletes the group. To leave the gap, ' +\n 'use delete-article-in-place. Generated roots ' +\n '(worktop, toe kick) cannot be deleted - the library regenerates them. Returns the changed group.',\n inputSchema: {\n groupId: z\n .string()\n .optional()\n .describe(\n 'The id of the group, optional - left out, the server takes the group of the root module. ' +\n 'A unique id prefix is accepted.',\n ),\n rootModuleId: z.string().describe('The id of the root module.'),\n },\n },\n async (args) =>\n textResult(await runTool('delete-article-and-compact', args)),\n );\n\n registerTool(\n 'merge-article-into-group',\n {\n description:\n 'The tool for \"add one more\", \"extend the row\": adds one article to an existing group as a new root ' +\n 'module, docked to a ' +\n 'free docking vector of a root module of the group, the way the authoring rules describe docking. dockTo ' +\n \"names the root module the article continues, that root module's free vector (one of its freeDockingVectors in \" +\n \"get-plan-context) and the new root module's vector: RightBottom -> LeftBottom puts it to the right, \" +\n 'LeftBottom -> RightBottom to the left, LeftTop -> LeftBottom hangs a wall unit or a range hood above ' +\n 'a floor-standing root module at the height of the wall units. For an article mounted above a floor unit, ' +\n 'the server sets the gap when offset has no z value; a supplied z value is the clearance, and an explicit zero stays zero. The new root module inherits ' +\n 'the attributes the library passes on between neighbours - fronts, handles, carcase - from the root module of dockTo, as in the planner; attributes override them. ' +\n 'To put an article between two root modules, use insert-article-into-group. The group keeps its position. Returns the changed group.',\n inputSchema: {\n groupId: z\n .string()\n .describe('The id of the group. A unique id prefix is accepted.'),\n articleId: z.string().describe('The article id from the catalog.'),\n attributes: ATTRIBUTE_OVERRIDES.optional().describe(\n 'Attribute overrides of the new root module: [{ id, value }].',\n ),\n dockTo: z\n .object({\n rootId: z\n .string()\n .describe(\n 'The id of the root module of the group the new article docks to.',\n ),\n ownDockingVector: z\n .string()\n .describe(\n \"That root module's free docking vector, e.g. RightBottom.\",\n ),\n dockingVector: z\n .string()\n .describe(\n \"The new root module's docking vector that meets it, e.g. LeftBottom.\",\n ),\n mode: z\n .enum(['StartStart', 'EndEnd', 'StartEnd', 'EndStart'])\n .optional()\n .describe(\n 'Which endpoints of the two vectors coincide. Default StartStart; back to back (BackBottom -> BackBottom) StartEnd, as behind places it.',\n ),\n offset: z\n .tuple([z.number(), z.number(), z.number()])\n .optional()\n .describe(\n '[x, y, z] in millimetres added after docking. For an article mounted above a floor-standing root module, omit offset to let the server set the hang gap; a supplied z value sets the clearance, including zero. Otherwise the default is [0, 0, 0].',\n ),\n })\n .describe('Where the new root module docks.'),\n },\n },\n async (args) => textResult(await runTool('merge-article-into-group', args)),\n );\n\n registerTool(\n 'insert-article-into-group',\n {\n description:\n 'The tool for \"put one between\": inserts one article from the catalog between two root modules of an ' +\n 'existing group that stand side by side - ' +\n 'whatever the group is and whatever the article is: a low cabinet between two high cabinets or wardrobes too; the user ' +\n 'decides what stands between what. between names the two root modules, in either order; a group of two root modules ' +\n 'has one place to insert: between them. No gap is needed - the tool makes room. The new root module is docked to both; the root modules at a wall or in a ' +\n \"corner keep their place, the others move by the article's width. Wall units and the range hood move with the \" +\n 'root module they hang from. The new root module inherits the attributes the library passes on between neighbours - fronts, handles, carcase - from the first root module of between, ' +\n 'as in the planner; attributes override them. To add an article beside the last root module of a row, use merge-article-into-group. ' +\n 'Returns the changed group.',\n inputSchema: {\n groupId: z\n .string()\n .describe('The id of the group. A unique id prefix is accepted.'),\n articleId: z.string().describe('The article id from the catalog.'),\n attributes: ATTRIBUTE_OVERRIDES.optional().describe(\n 'Attribute overrides of the new root module: [{ id, value }].',\n ),\n between: z\n .tuple([z.string(), z.string()])\n .describe(\n 'The ids of the two root modules that stand side by side and take the new article between them, in either order.',\n ),\n },\n },\n async (args) =>\n textResult(await runTool('insert-article-into-group', args)),\n );\n\n registerTool(\n 'exchange-root-module',\n {\n description:\n 'The tool for \"exchange\", \"swap the X for a Y\", \"make it wider, 900 mm wide\": replaces one root module ' +\n 'of a group with an article from the catalog that has one root ' +\n 'module, e.g. a base cabinet with a drawer cabinet; the new root module takes over the position, the docking and ' +\n 'the attributes the library passes on between neighbours - fronts, handles, carcase - of the replaced one, as in the planner; attributes override them - another size of the article, set by its size attribute id from the catalog (the dimensions of the article name the attribute and its value in millimetres), e.g. a cabinet 900 mm wide: ' +\n 'the other root modules move by the difference, and the ones at a wall keep their ' +\n 'place. A docking the new article cannot take is named in corrections. Returns the changed group.',\n inputSchema: {\n groupId: z\n .string()\n .describe('The id of the group. A unique id prefix is accepted.'),\n rootModuleId: z\n .string()\n .describe('The id of the root module to replace.'),\n articleId: z.string().describe('The article id from the catalog.'),\n attributes: ATTRIBUTE_OVERRIDES.optional().describe(\n 'Attribute overrides of the new root module: [{ id, value }].',\n ),\n },\n },\n async (args) => textResult(await runTool('exchange-root-module', args)),\n );\n\n registerTool(\n 'swap-root-modules',\n {\n description:\n 'The tool for \"swap the two units\", \"change their places\": lets two root modules of a group change ' +\n 'places, neighbours or not. Each keeps its attributes, and the ' +\n 'wall units and the range hood hanging from a root module move with it. The group keeps its length, and the root modules ' +\n 'at a wall keep their place. Returns the changed group.',\n inputSchema: {\n groupId: z\n .string()\n .describe('The id of the group. A unique id prefix is accepted.'),\n rootModuleIds: z\n .tuple([z.string(), z.string()])\n .describe('The ids of the two root modules that change places.'),\n },\n },\n async (args) => textResult(await runTool('swap-root-modules', args)),\n );\n\n registerTool(\n 'merge-groups',\n {\n description:\n 'Joins groups into one: the groups in groupIds are merged into the target group where they stand, ' +\n 'like the merge action of the planner - nothing is moved and no docking is added, so merge groups ' +\n 'that already stand next to each other. Groups of different libraries cannot be merged. To add an article ' +\n 'next to a group, use merge-article-into-group instead. Returns the merged group and the ids of the ' +\n 'groups merged into it.',\n inputSchema: {\n targetGroupId: z\n .string()\n .describe(\n 'The id of the group the others are merged into. A unique id prefix is accepted.',\n ),\n groupIds: z\n .array(z.string())\n .min(1)\n .describe('The ids of the groups to merge into the target group.'),\n },\n },\n async (args) => textResult(await runTool('merge-groups', args)),\n );\n\n registerTool(\n 'undo',\n {\n description:\n \"Reverts the plan change of the last tool call that changed the plan, as the planner's undo does. \" +\n 'When the user asks to undo their last change, revert everything you changed for their last request: ' +\n 'one undo per tool call that changed the plan, the last call first. ' +\n 'Use it when that result is not what was asked - the user says it was the wrong article, wall or group, or a ' +\n 'merge or delete went wrong - and then send the corrected call; call it again to revert the call before. ' +\n 'To bring back what an undo reverted, call redo, not undo. ' +\n 'Returns the reverted tool, the groups it changed back as they are now, removedGroupIds - the groups it took out ' +\n 'of the plan - and otherGroupIds, the groups it left as they were; when there is nothing to undo, the result says so.',\n inputSchema: {},\n },\n async () => textResult(await runTool('undo', {})),\n );\n\n registerTool(\n 'redo',\n {\n description:\n 'Brings back the tool call the last undo reverted - the tool when the user asks to redo or to bring back ' +\n 'what was undone (\"redo it\", \"bring it back\"); undo would revert one more call instead. ' +\n 'When the user asks to redo a change that took several undo calls, call redo as often. ' +\n 'A new change of the plan ends redo. Returns the ' +\n 'restored tool, the groups it changed as they are now, removedGroupIds - the groups it took out of the plan - ' +\n 'and otherGroupIds, the groups it left as they were; when there is nothing to redo, the result says so.',\n inputSchema: {},\n },\n async () => textResult(await runTool('redo', {})),\n );\n\n registerTool(\n 'get-price',\n {\n description:\n 'Calculates and returns the price/order data of the current planning situation. ' +\n 'When the plan holds a root or a group the library could not calculate, hint names it: the price includes it, ' +\n 'but it is not built - say so in the answer.',\n inputSchema: {},\n },\n async () => textResult(await runTool('get-price', {})),\n );\n\n registerTool(\n 'get-order-data',\n {\n description:\n 'Returns the order data of the current planning situation without placing an order. ' +\n 'When the plan holds a root or a group the library could not calculate, hint names it: the order data includes ' +\n 'it, but it is not built - say so in the answer.',\n inputSchema: {},\n },\n async () => textResult(await runTool('get-order-data', {})),\n );\n\n registerTool(\n 'get-plan-images',\n {\n description:\n 'Renders two images of the current plan when the user asks to see it or to look inside a cabinet, or to ' +\n 'compare a planning from an image the user sent with that image; a create or edit result already carries ' +\n 'the positions to verify, so a check needs no render. First the groups ' +\n 'alone, seen from their front without the room or other objects - one camera for all groups, so where ' +\n 'fronts face opposite directions one side is seen from behind, and root modules can hide one another: a ' +\n 'root module not seen is not missing, get-plan-context lists the root modules. Second a top view of the ' +\n 'whole plan that shows where the groups stand; its orientation matches the wall side labels of ' +\n \"get-plan-context: a wall with side 'right' is at the right edge of the top image, 'top' at the upper \" +\n 'edge. A text before the images names them; without groups in the plan only the top view is returned. ' +\n 'Doors and drawers are shown as they are: to look inside a cabinet, open it with open-or-close-article ' +\n '(a whole group with open-or-close-group) right before this tool.',\n inputSchema: {},\n },\n async () => {\n const images = (await runTool('get-plan-images', {})) as {\n perspectiveObjectImage?: string;\n topImage?: string;\n };\n const views = [\n {\n image: images.perspectiveObjectImage,\n name: 'the HI groups alone, seen from their front, without the room',\n },\n { image: images.topImage, name: 'the top view of the whole plan' },\n ].filter((view) => view.image);\n if (views.length === 0) {\n return textResult({ error: 'No images available' });\n }\n const names = views\n .map((view, index) => `Image ${index + 1}: ${view.name}.`)\n .join(' ');\n return {\n content: [\n {\n type: 'text' as const,\n text: images.perspectiveObjectImage\n ? names\n : `The plan has no groups, so there is no group view. ${names}`,\n },\n ...views.map((view) => ({\n type: 'image' as const,\n data: stripDataUrlPrefix(view.image as string),\n mimeType: PLAN_IMAGE_TYPE,\n })),\n ],\n };\n },\n );\n\n return tools;\n};\n"],"mappings":";;;;;AASA,IAAM,KAAW,MACf,MAAM,QAAQ,EAAM,IAAI,EAAM,WAAW,KAAK,EAAM,MAAM,OAAO,SAAS,EAGtE,KAAU,MACd,MAAM,QAAQ,EAAM,IAAI,EAAM,WAAW,KAAK,EAAM,MAAM,OAAO,SAAS,EAEtE,KAAY,MAChB,OAAO,KAAU,cAAY,KAAkB,CAAC,MAAM,QAAQ,EAAM,EAGhE,KAAe,MACnB,EAAQ,EAAM,GAAG;CAAC,EAAM,KAAK;CAAG,CAAC,EAAM,KAAK;CAAG,EAAM,KAAK;CAAE,GAAG,GAE3D,KAAc,MAClB,EAAQ,EAAM,GAAG;CAAC,EAAM,KAAK;CAAG,EAAM,KAAK;CAAG,CAAC,EAAM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Aa,EAAE;EAChB,EACD,YAAY,EAAW,MAAM,EAAQ,kBAAkB,EAAE,CAAC,CAAC,CAC5D,EAED,EACE,mBACA;EACE,aACE;EAWF,aAAa,EAAE;EAChB,EACD,YAAY;EACV,IAAM,IAAU,MAAM,EAAQ,mBAAmB,EAAE,CAAC,EAI9C,IAAQ,CACZ;GACE,OAAO,EAAO;GACd,MAAM;GACP,EACD;GAAE,OAAO,EAAO;GAAU,MAAM;GAAkC,CACnE,CAAC,QAAQ,MAAS,EAAK,MAAM;AAC9B,MAAI,EAAM,WAAW,EACnB,QAAO,EAAW,EAAE,OAAO,uBAAuB,CAAC;EAErD,IAAM,IAAQ,EACX,KAAK,GAAM,MAAU,SAAS,IAAQ,EAAE,IAAI,EAAK,KAAK,GAAG,CACzD,KAAK,IAAI;AACZ,SAAO,EACL,SAAS,CACP;GACE,MAAM;GACN,MAAM,EAAO,yBACT,IACA,sDAAsD;GAC3D,EACD,GAAG,EAAM,KAAK,OAAU;GACtB,MAAM;GACN,MAAM,GAAmB,EAAK,MAAgB;GAC9C,UAAU;GACX,EAAE,CACJ,EACF;GAEJ,EAEM"}
|
|
1
|
+
{"version":3,"file":"hi-mcp-server-rSu1HL4m.mjs","names":[],"sources":["../../packages/homag-intelligence/src/hi-tools/agent-frame.ts","../../packages/homag-intelligence/src/hi-tools/plan-history.ts","../../packages/homag-intelligence/src/hi-tools/planner-api.ts","../../packages/homag-intelligence/src/hi-tools/skills/image-planning/SKILL.md?raw","../../packages/homag-intelligence/src/hi-tools/skills/kitchen-planning/SKILL.md?raw","../../packages/homag-intelligence/src/hi-tools/skills/kitchen-planning/references/planning-reference.md?raw","../../packages/homag-intelligence/src/hi-tools/skills/kitchen-planning/references/source-catalog.md?raw","../../packages/homag-intelligence/src/hi-tools/skills/kitchen-planning-fr/SKILL.md?raw","../../packages/homag-intelligence/src/hi-tools/skills/kitchen-planning-fr/references/planning-reference.md?raw","../../packages/homag-intelligence/src/hi-tools/skills/kitchen-planning-fr/references/source-catalog.md?raw","../../packages/homag-intelligence/src/hi-tools/skills/living-room-planning/SKILL.md?raw","../../packages/homag-intelligence/src/hi-tools/skills/living-room-planning/references/planning-reference.md?raw","../../packages/homag-intelligence/src/hi-tools/skills/living-room-planning/references/source-catalog.md?raw","../../packages/homag-intelligence/src/hi-tools/skills.ts","../../packages/homag-intelligence/src/hi-tools/agent-facing.ts","../../packages/homag-intelligence/src/hi-tools/tool-executors.ts","../../packages/homag-intelligence/src/hi-tools/hi-mcp-server.ts"],"sourcesContent":["// The agent works in the planner's plan space: millimetres, right-handed, z\n// up, the floor in x and y - +x to the right and +y to the top of the top-view\n// image. The planner methods, the tool commands and the HI geometry work in\n// pos space, the frame of the HI group JSON: y up, its z the plan's -y. Both\n// differ by a proper rotation, so an angle turns a group the same way in\n// both; only the names of the rotation fields change with the axis.\n\ntype Point = [number, number, number];\n\nconst isPoint = (value: unknown): value is Point =>\n Array.isArray(value) && value.length === 3 && value.every(Number.isFinite);\n\n// a floor point [x, y] or a range [from, to]\nconst isPair = (value: unknown): value is [number, number] =>\n Array.isArray(value) && value.length === 2 && value.every(Number.isFinite);\n\nconst isObject = (value: unknown): boolean =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n// + 0 turns IEEE -0 into +0 so serialized values never show -0\nconst inPlanSpace = (value: unknown): unknown =>\n isPoint(value) ? [value[0] + 0, -value[2] + 0, value[1] + 0] : value;\n\nconst inPosSpace = (value: unknown): unknown =>\n isPoint(value) ? [value[0] + 0, value[2] + 0, -value[1] + 0] : value;\n\n// A z range of pos space is the y range of plan space, negated.\nconst negatedRange = (value: unknown): unknown =>\n isPair(value) ? [-value[1] + 0, -value[0] + 0] : value;\n\n// The fields of an object converted and renamed in their place; everything\n// else as it is.\nconst withFields = (\n object: any,\n fields: Record<string, (value: any) => unknown>,\n names: Record<string, string> = {},\n): any =>\n isObject(object)\n ? Object.fromEntries(\n Object.entries(object).map(([key, value]) => [\n names[key] ?? key,\n fields[key] ? fields[key](value) : value,\n ]),\n )\n : object;\n\nconst each =\n (convert: (item: any, index: number) => unknown) =>\n (value: unknown): unknown =>\n Array.isArray(value) ? value.map(convert) : value;\n\nconst dockingOffsets = (inFrame: (value: unknown) => unknown) =>\n each((root) =>\n withFields(root, {\n contextData: (contextData) =>\n withFields(contextData, {\n dockedRoots: each((context) =>\n withFields(context, {\n dockedRoots: each((entry) =>\n withFields(entry, { offset: inFrame }),\n ),\n }),\n ),\n }),\n }),\n );\n\nconst fittingsToAgent = each((fitting) =>\n withFields(fitting, { position: inPlanSpace }),\n);\n\nconst wallToAgent = (wall: unknown) =>\n withFields(\n wall,\n { start: inPlanSpace, end: inPlanSpace },\n { facingRotationY: 'facingRotationZ' },\n );\n\nconst outlinesToAgent = each((item) =>\n withFields(item, { outline: each(inPlanSpace) }),\n);\n\nconst groupToAgent = (group: unknown) =>\n withFields(group, {\n position: (position) =>\n withFields(\n position,\n {\n pos: inPlanSpace,\n footprint: (footprint) =>\n withFields(footprint, { z: negatedRange }, { z: 'y' }),\n },\n { rotationY: 'rotationZ' },\n ),\n roots: dockingOffsets(inPlanSpace),\n interiorFittings: fittingsToAgent,\n });\n\nconst RESULT_FIELDS: Record<string, (value: any) => unknown> = {\n rooms: (rooms) =>\n withFields(rooms, {\n rooms: each((room) =>\n withFields(room, {\n levels: each((level) =>\n withFields(level, {\n segments: each((segment) =>\n withFields(segment, { pos: inPlanSpace }),\n ),\n }),\n ),\n walls: each(wallToAgent),\n corners: each((corner) =>\n withFields(\n corner,\n { point: inPlanSpace },\n { posRotationY: 'posRotationZ' },\n ),\n ),\n }),\n ),\n }),\n obstacles: (obstacles) =>\n withFields(obstacles, {\n objects: outlinesToAgent,\n groups: each((group) => withFields(group, { roots: outlinesToAgent })),\n }),\n installationElements: each((element) =>\n withFields(element, { position: inPlanSpace }),\n ),\n groups: each(groupToAgent),\n group: groupToAgent,\n wall: wallToAgent,\n fittings: fittingsToAgent,\n};\n\n// The price and the order data are the order's, not the plan's.\nconst RESULTS_WITHOUT_PLAN = ['get-price', 'get-order-data'];\n\n// The result of a tool in the agent's frame: every point, outline, range and\n// rotation of the plan context and of the changed groups in plan space.\nexport const toAgentFrame = (tool: string, result: unknown): unknown =>\n RESULTS_WITHOUT_PLAN.includes(tool)\n ? result\n : withFields(result, RESULT_FIELDS);\n\n// A number a model wrote as text - \"600\" - as the number; undefined for\n// anything else.\nconst numberOfText = (value: unknown): number | undefined =>\n typeof value === 'string' &&\n value.trim() !== '' &&\n Number.isFinite(Number(value))\n ? Number(value)\n : undefined;\n\n// The point and the rotation of a placement a model wrote as text, read as\n// numbers and named - before the frame conversion, which takes numbers only.\nconst withNumbersRead = (\n placement: any,\n prefix: string,\n corrections: string[],\n): any => {\n const read: Record<string, unknown> = {};\n if (\n Array.isArray(placement.posGroup) &&\n placement.posGroup.some(\n (value: unknown) => numberOfText(value) !== undefined,\n )\n ) {\n read.posGroup = placement.posGroup.map(\n (value: unknown) => numberOfText(value) ?? value,\n );\n }\n const rotation = numberOfText(placement.posRotationZ);\n if (rotation !== undefined) {\n read.posRotationZ = rotation;\n }\n if (Object.keys(read).length === 0) {\n return placement;\n }\n corrections.push(\n `${prefix}: the placement's ${Object.entries(read)\n .map(\n ([field, value]) =>\n `${field} ${JSON.stringify(placement[field])} was read as ${JSON.stringify(value)}`,\n )\n .join(', ')}`,\n );\n return { ...placement, ...read };\n};\n\n// A placement by point in pos space; a floor point is completed with z = 0.\n// A placement by wall names no coordinate, and a value that is no point\n// passes as it is, so the tool command reports it.\nconst placementFromAgent =\n (prefix: string, corrections: string[]) => (sent: any) => {\n if (!isObject(sent) || sent.wall !== undefined) {\n return sent;\n }\n const placement = withNumbersRead(sent, prefix, corrections);\n if (isPair(placement.posGroup)) {\n const [x, y] = placement.posGroup;\n corrections.push(\n `${prefix}: the placement's posGroup [${x}, ${y}] was completed to [${x}, ${y}, 0] (z = 0 on the floor)`,\n );\n }\n return withFields(\n placement,\n {\n posGroup: (posGroup) =>\n inPosSpace(isPair(posGroup) ? [...posGroup, 0] : posGroup),\n },\n { posRotationZ: 'posRotationY' },\n );\n };\n\n// The arguments of a tool in pos space, the frame of the planner methods -\n// the placements, the docking offsets and the insert positions of interior\n// fittings -, and the corrections the conversion made.\nexport const fromAgentFrame = (\n args: Record<string, unknown>,\n): { args: Record<string, unknown>; corrections: string[] } => {\n const corrections: string[] = [];\n const input =\n args.groupId !== undefined &&\n (args.posGroup !== undefined || args.posRotationZ !== undefined)\n ? placementFromAgent('place-group', corrections)(args)\n : args;\n const converted = withFields(input, {\n posGroups: each((group, index) => {\n const placement = placementFromAgent(`posGroups[${index}]`, corrections);\n return withFields(group, {\n placement,\n repositioningData: placement,\n roots: dockingOffsets(inPosSpace),\n });\n }),\n dockTo: (dockTo) => withFields(dockTo, { offset: inPosSpace }),\n insertPosition: inPosSpace,\n });\n return { args: converted, corrections };\n};\n","/** A tool call that changed the plan, as the undo tool reverts it. */\nexport interface ToolCallRecord {\n tool: string;\n /** The planner steps the call put on the planner's undo history. */\n steps: number;\n /** The plan's groups before and after the call, as comparison keys. */\n groupsBefore: string;\n groupsAfter: string;\n}\n\n// The tool set's view of the planner's undo history: the planner's history\n// events and the tool calls that changed the plan, with the planner steps\n// each made. An event while no tool call runs is a change the user made\n// in the planner - the tool calls below it can no longer be undone safely, so\n// they are forgotten.\nexport class PlanHistory {\n private _events = 0;\n private _inFlight = false;\n private _done: ToolCallRecord[] = [];\n private _undone: ToolCallRecord[] = [];\n private _changedInPlanner = false;\n private _waiters = new Set<() => void>();\n\n public get events(): number {\n return this._events;\n }\n\n public get changedInPlanner(): boolean {\n return this._changedInPlanner;\n }\n\n public historyChanged(): void {\n this._events += 1;\n if (!this._inFlight) {\n this.forget();\n this._changedInPlanner = true;\n }\n for (const wake of this._waiters) {\n wake();\n }\n }\n\n /** Resolves true once `count` events have arrived, false after the timeout. */\n public waitForEvents(count: number, timeoutMs: number): Promise<boolean> {\n if (this._events >= count) {\n return Promise.resolve(true);\n }\n return new Promise((resolve) => {\n const finish = (reached: boolean) => {\n clearTimeout(timer);\n this._waiters.delete(wake);\n resolve(reached);\n };\n const wake = () => {\n if (this._events >= count) {\n finish(true);\n }\n };\n const timer = setTimeout(() => finish(false), timeoutMs);\n this._waiters.add(wake);\n });\n }\n\n public begin(): void {\n this._inFlight = true;\n }\n\n public end(): void {\n this._inFlight = false;\n }\n\n /** A new change on top of the history ends redo, as in the planner. */\n public record(call: ToolCallRecord): void {\n this._done.push(call);\n this._undone = [];\n this._changedInPlanner = false;\n }\n\n public lastDone(): ToolCallRecord | undefined {\n return this._done.at(-1);\n }\n\n public lastUndone(): ToolCallRecord | undefined {\n return this._undone.at(-1);\n }\n\n public markUndone(): void {\n const call = this._done.pop();\n if (call) {\n this._undone.push(call);\n }\n }\n\n public markRedone(): void {\n const call = this._undone.pop();\n if (call) {\n this._done.push(call);\n }\n }\n\n public forget(): void {\n this._done = [];\n this._undone = [];\n }\n\n /** A change in the planner was found: no record can be trusted any more. */\n public markChangedInPlanner(): void {\n this.forget();\n this._changedInPlanner = true;\n }\n}\n","import type { ExternalObjectSnapshotRequest } from '../external-object-api';\n\nexport const DEFAULT_CALL_TIMEOUT_MS = 30_000;\nexport const SNAPSHOT_CALL_TIMEOUT_MS = 120_000;\n\n// The planner methods the tools call.\nexport interface PlannerApi {\n extended: {\n getExternalObjectPlanContext(\n include: string[],\n options?: {\n interiorDesign: {\n groupId: string;\n rootId?: string;\n containerModuleId?: string;\n articleId?: string;\n };\n },\n ): Promise<any>;\n getExternalObjectLibraryContext(\n include: string[],\n options?: { articleIds?: string[] },\n ): Promise<any>;\n externalObjectGroupOperation(\n command: string,\n payload: Record<string, unknown>,\n ): Promise<any>;\n fetchPrice(): Promise<any>;\n getExternalObjectSnapshot(\n options: ExternalObjectSnapshotRequest,\n ): Promise<any>;\n undo(): Promise<void>;\n redo(): Promise<void>;\n };\n}\n\n/**\n * The planner the HI MCP tools run in: the seven planner methods the tools\n * call, and the planner's callbacks, whose `onHistoryChange` the tools chain\n * to tell their own planner steps from the user's changes.\n */\nexport type HiMcpPlannerApi = PlannerApi & {\n extended: {\n callbacks: {\n onHistoryChange?: (undo: boolean, redo: boolean) => void;\n };\n };\n};\n\n// The seven planner methods as the tools call them: each call with a timeout -\n// a planner call has none of its own - and a log line.\nexport const createPlannerApi = ({ extended }: PlannerApi): PlannerApi => {\n let nextCallId = 1;\n const call = (\n method: keyof PlannerApi['extended'],\n args: unknown[],\n timeoutMs: number,\n ): Promise<any> => {\n const id = nextCallId++;\n console.log(\n `[hi-mcp] call ${id}: ${method} ${JSON.stringify(args).slice(0, 400)}`,\n );\n let timeout: ReturnType<typeof setTimeout> | undefined;\n const timedOut = new Promise<never>((_resolve, reject) => {\n timeout = setTimeout(\n () =>\n reject(\n new Error(\n `Planner call '${method}' timed out after ${timeoutMs}ms`,\n ),\n ),\n timeoutMs,\n );\n });\n return Promise.race([\n (extended[method] as (...callArgs: unknown[]) => Promise<unknown>).apply(\n extended,\n args,\n ),\n timedOut,\n ]).finally(() => clearTimeout(timeout));\n };\n return {\n extended: {\n getExternalObjectPlanContext: (include, options) =>\n call(\n 'getExternalObjectPlanContext',\n options === undefined ? [include] : [include, options],\n DEFAULT_CALL_TIMEOUT_MS,\n ),\n getExternalObjectLibraryContext: (include, options) =>\n call(\n 'getExternalObjectLibraryContext',\n options === undefined ? [include] : [include, options],\n DEFAULT_CALL_TIMEOUT_MS,\n ),\n externalObjectGroupOperation: (command, payload) =>\n call(\n 'externalObjectGroupOperation',\n [command, payload],\n SNAPSHOT_CALL_TIMEOUT_MS,\n ),\n fetchPrice: () => call('fetchPrice', [], DEFAULT_CALL_TIMEOUT_MS),\n getExternalObjectSnapshot: (options) =>\n call('getExternalObjectSnapshot', [options], SNAPSHOT_CALL_TIMEOUT_MS),\n undo: async () => {\n await call('undo', [], DEFAULT_CALL_TIMEOUT_MS);\n },\n redo: async () => {\n await call('redo', [], DEFAULT_CALL_TIMEOUT_MS);\n },\n },\n };\n};\n","export default \"---\\nname: image-planning\\ndescription: 'Plan furniture from an image or photo the user sends, with or without text: identify the pieces of furniture, read their layout, counts and sizes, map them onto the room of the plan and the article catalog, and report what was substituted and adapted. Use whenever a user message carries an image of furniture or of a room.'\\n---\\n\\n# Planning from an Image\\n\\n## Purpose\\n\\nThe image is the brief. Plan the furniture it shows as close to it as possible, with the articles of the catalog, in the room of the plan. The text of the message, when there is one, comes first: it names the wall, the corner, the changes or the part of the image to plan; the image supplies everything the text leaves open.\\n\\nA photo is enough for a concept. Do not ask for a measured plan, a site survey or the services first: plan with stated assumptions and name them in the answer.\\n\\n## 1. Identify the furniture\\n\\n- Name every piece of furniture in the image and its kind — a kitchen, a wardrobe, a media unit, a sideboard, shelves, a utility room, a row of tall cabinets — before choosing articles. Plan what the image shows: tall cabinets in a kitchen-like room are tall cabinets, not a kitchen.\\n- Name the appliances of each piece too — sink, hob, oven, fridge, dishwasher, hood —, those behind a cabinet front included: a fridge in a tall column, a dishwasher behind a door front.\\n- Plan each piece as one group. Cabinets beside, above or behind each other belong to the same group.\\n- Leave out what is no furniture of the catalog — walls, floors, decoration, loose items — and name the pieces the catalog has nothing for.\\n\\n## 2. Read the layout\\n\\n- The shape: one row, an L around a corner, a U, two facing rows (a galley), a row with an island, a free-standing piece.\\n- The levels: floor cabinets, tall cabinets, wall cabinets above the floor cabinets, cabinets on top; which wall cabinets hang above which floor cabinets, and where a tall cabinet interrupts the rows.\\n- The order along each row, from left to right as seen from the front: what stands next to what — sink, dishwasher, hob, oven, fridge, drawers, open shelves, a corner. Keep this sequence; it makes the planning look like the image.\\n- For an island, name the row it runs parallel to in the image — in an L or a U, one of the legs — and keep the island parallel to that row, its cabinet fronts facing that row across the working aisle. For a peninsula, keep its long axis relative to the other rows and face its cabinet fronts across the working aisle. A visible finished panel may be its back. For a straight row, rotation 0 faces -y, 90 faces +x, 180 faces +y and 270 faces -x in plan space. After mapping the kitchen into the room, turn the island to face the wall of the row it runs parallel to. Correct opposite facing with a half turn; a quarter turn changes the axis.\\n\\n## 3. Read the counts and the sizes\\n\\n- Count the cabinets per row and per level. A pair of doors is usually one cabinet, one wide drawer front one cabinet.\\n- Judge the widths relative to each other and to a reference of known size — a door, an appliance, the height of the floor cabinets or of the room. Then take for each cabinet the catalog article whose width comes closest: the catalog's widths are the truth, the estimate is not.\\n- A photo distorts: cabinets far from the camera look narrower, cabinets at the edge of the image wider. Prefer the count and the proportions over the width in pixels.\\n- A row of wall units is as long as the widths of its units: fit it to the floor units it hangs over — on a leg, to the stretch from the first floor unit it hangs over to the wall or the corner at the end of the leg — and keep its place in the image.\\n\\n## 4. Map it onto the plan\\n\\n- The room of the plan is not the room in the image. Read its walls, doors, windows and obstacles from the plan context.\\n- When the text names a wall or a corner, plan there. Otherwise choose the wall or corner whose length and openings fit the shape: an L into a room corner with two free walls, a long row onto the longest free wall, a galley onto two facing walls.\\n- Fit the length to the wall. Keep the sequence and the proportions; when the wall is shorter than the furniture in the image, leave out or narrow the cabinets of least weight — a filler, an open shelf, a second drawer cabinet. When it is longer, add nothing the image does not show.\\n- Keep doors and windows clear, and name in the answer what moved for them.\\n- Check the returned island against the row it runs parallel to: its long axis parallel to that row, its fronts facing that row's wall. Correct an existing island with point-form `place-group`, keeping its construction and finishes.\\n\\n## 5. Articles and attributes\\n\\n- Choose each article by what the cabinet does in the image — a sink cabinet, a drawer cabinet, an appliance housing, a corner cabinet — from the desc, the category, the dimensions and the subModules of the catalog. The subModules list the appliances an article comes with: an appliance of the image goes into an article whose subModules carry it, even when its fronts differ from the image — the fronts are the substitution, never the appliance.\\n- Before the create, check every appliance you named against the subModules of the articles you send.\\n- Finish the exposed back of an island or peninsula in the same create with the catalog component that matches the image's construction, `behind` any unit of its cabinet row — the server anchors the panel at the row's start end and runs it along the whole row — and as long as that row's whole back, a peninsula corner's back included. Match its height profile too: use the calculated roots' `bottomMm` and `topMm` to compare finished surfaces, accounting for the finishing component's bottom. Keep a raised surface when the image or text asks for one; otherwise align the intended flush surfaces. A separate cap is not a continuous worktop; report the substitution when the catalog cannot reproduce the surface shown.\\n- Read the fronts, the handles, the worktop and the carcase that the image or the text shows and set them as attributes of the group. Look every value up - the attributes section of the plan context for the create attributes, find-attributes for the rest - and say which value you took.\\n\\n## 6. The room skills\\n\\nWhen the furniture is of a kind another planning skill covers — a kitchen, a living room — fetch that skill too, for its checks. The image keeps precedence:\\n\\n- Apply its hard constraints: clearances, openings, what an appliance needs to work and to be installed.\\n- Report its recommendations — a better sequence, more worktop, another position of an appliance — in the answer as notes. Do not change what the image shows for them, unless the user asks for an improved planning.\\n- Fetch its planning reference only for a dimension this skill does not settle.\\n\\n## 7. The answer\\n\\nSay in a few sentences:\\n\\n- what you identified in the image and planned, group by group;\\n- what you substituted — the closest article or attribute value for what the catalog lacks;\\n- each appliance of the image the plan does not carry, and why;\\n- what you adapted to the room — the wall, the length, the cabinets left out, the openings kept clear;\\n- the assumptions, and the open checks of the room skill.\\n\"","export default \"---\\nname: kitchen-planning\\ndescription: 'Plan or review a residential kitchen: room survey, kitchen layout, sink and hob spacing, dishwasher placement, cabinet ordering, drawer organization, storage zones, short walking routes, ergonomics, accessibility, appliance clearances, and installation readiness. Use for kitchen planning, kitchen design, Kuechenplanung, arranging cabinets, or improving cooking and dishwasher-unloading workflows. Defaults to Germany/EU and millimetres; adapt rules to the actual jurisdiction.'\\n---\\n\\n# Kitchen Planning\\n\\n## Purpose and Scope\\n\\nProduce practical, dimensioned residential kitchen proposals with short daily routes, usable storage, and explicit feasibility checks. Plan from activities and contents before choosing cabinet fronts. Here, cabinet \\\"ordering\\\" means arranging cabinets; procurement requires a separate approval gate.\\n\\nDefault to Germany/EU, dimensions in mm, and costs in EUR. Confirm country and, in Germany, Bundesland before applying regulatory requirements. There is no single EU kitchen-clearance code. Commercial kitchens require a separate specialist workflow.\\n\\nRead [the planning constraints reference](./references/planning-reference.md) before applying numerical guidance or reviewing installation risks. It includes rule classifications, qualifications, and short source IDs for traceability. Recheck current local requirements and exact product manuals for each real project.\\n\\nThe [source catalog](./references/source-catalog.md) is optional. Load it only to verify a source-backed claim, answer a provenance/citation question, or update the guidance. Do not load it during routine planning merely to resolve source IDs; the operational guidance and its limitations are in this skill and the planning reference. This does not waive project-specific verification of regulations or product instructions.\\n\\n## Non-Negotiable Planning Discipline\\n\\n- Treat law, applicable technical requirements, product instructions, and verified site constraints as simultaneous constraints. If they conflict, stop and resolve the conflict; a manufacturer cannot waive the law.\\n- Do not turn a recommendation into a regulation. In particular, do not claim that a sink beside a hob is universally illegal. Usually the problem is missing preparation/landing space; actual installation restrictions are product- and site-specific.\\n- Unknown is not pass. Missing dimensions, manuals, or service information remain unresolved. Photographs and generated images cannot establish installation readiness.\\n- Use a planner's authoritative geometry, catalog, and prices where available. Never invent a catalog item, price, service point, clearance, or successful validation result.\\n- Optimize only after hard constraints pass. A short walking route cannot compensate for a blocked exit, unsafe installation, or inaccessible appliance.\\n- Offer concepts with explicit assumptions when facts are incomplete. Do not call them order-ready or installation-ready.\\n- Do not move services, alter structures, purchase items, or overwrite an accepted design without explicit authorization. Draft alternatives should remain reversible.\\n\\n## 1. Collect the Brief and Survey\\n\\nAsk only for missing information that changes the next decision. Start with room dimensions/openings, fixed services, users, appliances, and budget. Collect remaining details progressively.\\n\\n| Input | Required information |\\n| --- | --- |\\n| Location and scope | Country, region, dwelling type, new build/remodel, ownership/landlord restrictions, required accessibility standard, retained items. |\\n| Room | Each wall length, ceiling/soffit heights, angles/diagonals, niches, columns, slopes, and finished floor levels. Measure irregular walls at relevant heights. |\\n| Openings | Door/window position, clear opening, frame/trim, sill height, opening direction and swept volume; curtains/blinds and window handles. |\\n| Services | Measured water/drain positions and heights, shutoffs, electrical points/circuits, gas, ventilation/exhaust routes, heating, meters, and service access. Mark relocation permission separately. |\\n| Structure | Wall construction/fixing capacity, floor/ceiling constraints, existing ventilation, room-air-dependent fireplace or combustion appliance, underfloor services. |\\n| People | Household size, number of simultaneous cooks, heights/elbow heights, handedness, reach/lifting ability, mobility aids, children, and future needs. |\\n| Activities | Shopping frequency, everyday meals, batch cooking, baking, coffee, entertaining, table setting, cleaning, waste sorting, and current annoyances. |\\n| Inventory | Counts and dimensions of dishes, pans, trays, containers, food, appliances, and waste bins; frequency and typical weight of use. |\\n| Products | Exact models or provisional envelopes, installation manuals, cabinet system, appliance niches, front/hinge system, handle projections, and worktop material. |\\n| Commercial | Total installed budget, service relocation allowance, delivery/access constraints, timing, and priorities ranked by the user. |\\n\\nFor each critical fact record `value`, `unit`, `source`, `verification_state`, and measurement uncertainty where known. Use `unknown`, `inferred`, `user_verified`, or `professionally_verified`. Preserve raw measurements and identify the finished reference surfaces.\\n\\nIf only a photo is supplied, request a measured plan or verified reference dimensions. Hidden pipe routes, wall strength, electrical capacity, and regulatory compliance cannot be inferred from appearance.\\n\\n## 2. Build the Constraint Register\\n\\nGive each rule a stable ID and classify it:\\n\\n| Class | Meaning | Handling |\\n| --- | --- | --- |\\n| `regulatory` | Verified applicable legal/code requirement, with jurisdiction and edition. | Hard; no user override. |\\n| `manufacturer` | Exact installation/compatibility requirement for the selected product. | Hard; change the product or design if necessary. |\\n| `site` | Verified room, structural, service, or geometric limitation. | Hard unless an approved change creates a new verified condition. |\\n| `user_must` | Explicit user requirement, including a fixed budget if stated. | Hard for this brief; ask before relaxing. |\\n| `recommendation` | Sourced ergonomic/design recommendation or labeled planning heuristic. | Soft; document the consequence of departures. |\\n| `preference` | Style, symmetry, convenience, or other discretionary choice. | Soft; trade off transparently. |\\n\\nEach record needs `id`, `class`, `applicability`, `requirement`, `measurement_definition`, `source`, `status`, `affected_items`, and `remedy_or_next_action`. Status is `pass`, `fail`, `unknown`, or `not_applicable`; explain exclusions. Preserve recommendation deviations rather than silently deleting them.\\n\\nComplete every category in the reference's installation checklist. Record applicability separately from compliance: an unconfirmed rule is not automatically irrelevant.\\n\\n## 3. Arrange Functional Zones\\n\\nUse five zones as an adjacency model, not a compulsory left-to-right sequence [S1, S2]:\\n\\n1. Food storage: refrigerator/freezer and dry provisions.\\n2. Preparation: the principal clear work surface and preparation tools.\\n3. Cooking: hob, oven, heat-safe landing surfaces, and cookware.\\n4. Cleaning: sink, dishwasher, waste sorting, and cleaning supplies.\\n5. Clean storage/serving: dishes, dining cutlery, glasses, and serving items.\\n\\nTrace these distinct workflows:\\n\\n- Shopping arrival -> grocery landing -> refrigerator/pantry.\\n- Food storage -> sink when needed -> preparation -> cooking -> serving.\\n- Table return -> scrape/sort -> sink as needed -> dishwasher. Do not prescribe routine pre-rinsing; follow appliance guidance.\\n- Dishwasher -> clean storage -> table/serving.\\n- Hob -> sink for draining hot cookware, without avoidable traffic crossings.\\n- Coffee/breakfast and snack access without walking through active cooking.\\n\\nKeep through-traffic outside the principal work area. The refrigerator-sink-hob triangle is a diagnostic, not a mandatory geometry or a substitute for these workflows. A one-wall kitchen can work without a triangle. Mixed-handed or multi-cook households need task trials, not automatic mirroring.\\n\\n### Placing the Kitchen in the Room\\n\\nWhen the user does not name a place for the kitchen, plan it so that the sink stands near a water connection of the plan, if the room has one. The installation elements of the plan context list the water connections with their positions.\\n\\n### Sink, Preparation Surface, and Hob\\n\\nPrefer `sink -> continuous preparation surface -> hob`, or the mirror image. Blum recommends approximately 900 mm of preparation width, with 800 mm as its lower ergonomic recommendation [S3]. These are not German legal minimums. More space may be needed for two cooks or extensive baking.\\n\\nMeasure usable clear surface between fixture edges, excluding an occupied drainer, permanent appliances, or other obstructions. Record actual usable depth too. Separately verify cut-out-to-cut-out webs, edge distances, and supports from the worktop fabricator; a visible surface gap does not prove structural suitability.\\n\\nAvoid placing a tall cabinet across this continuous workflow. Keep the preparation surface genuinely available after locating the kettle, coffee machine, knife storage, and drying area. Where the room cannot accommodate the recommendation, disclose the compromise and test an adjacent alternative preparation surface.\\n\\n### Dishwasher and Clean Storage\\n\\n- Start with the dishwasher beside the sink, subject to plumbing, appliance instructions, and usable access. Prefer a side outside the main preparation stance when feasible.\\n- Compare both sides of the sink. Do not prescribe left/right solely from handedness.\\n- Locate everyday dining cutlery, plates, and bowls in an adjacent or nearby accessible drawer bank. Locate daily glasses and cups within comfortable reach nearby [S4].\\n- Aim for a comfortable turn or short step during unloading. This is a qualitative target, not a universal distance limit.\\n- Check dishwasher fully open, racks extended, destination drawer open, and a person standing in the unloading position. Neither nominal adjacency nor cabinet-centre distance establishes usability.\\n- Across an aisle can work only if the actual door/drawer projections, standing space, reach, and circulation work together. Never require stepping over a dishwasher door.\\n- At an inside corner, check perpendicular drawer collisions and access to the sink/waste. Move the dishwasher or storage bank if fillers alone cannot solve the conflict.\\n- Keep dining/table access convenient without routing other people through the hot zone. Do not put every item beside the dishwasher: cooking tools still belong at their principal point of use.\\n- Consider a raised dishwasher for users who benefit, but validate approved support, niche, front mechanism, rack heights, and adjacent unloading space.\\n\\n## 4. Assign Contents Before Cabinet Sizes\\n\\nCreate the storage schedule first. Then fit catalog modules around the fixed zones.\\n\\n| Contents | Preferred home | Checks |\\n| --- | --- | --- |\\n| Dining cutlery | Shallow upper drawer near dishwasher and dish storage. | Organizer fits internally; accessible with dishwasher open. |\\n| Everyday plates/bowls | Full-extension drawer in the same or nearby bank. | Plate diameter, stack height, restraint, loaded runner capacity, comfortable lifting height. |\\n| Glasses/cups | Reachable nearby shelf, lift-front cabinet, or suitable drawer. | Safe reach, glass height, retention, opening clearance; not forced overhead. |\\n| Preparation knives/tools | Upper drawer at principal preparation surface. | Blade protection, child security, separation from dining cutlery. |\\n| Boards/trays | Vertical divider storage near preparation/oven. | Actual tray dimensions and removal path. |\\n| Pans/pots/lids | Full-extension storage beside or below hob where permitted. | Heat separation, hob underside, ventilation and extractor/oven volume. |\\n| Spices/oils | Near preparation/cooking, protected from heat/light/moisture. | Not directly exposed to hob heat or steam. |\\n| Mixing bowls, scales, baking tools | Preparation/baking zone. | Nesting, appliance weight, lifting distance, and usable drawer height. |\\n| Dry food | Pantry/pull-outs near grocery landing and preparation. | Stock volume, visibility, shelf adjustment, runner loads. |\\n| Waste/recycling | Accessible from preparation and sink. | Local sorting streams, bin removal, odours, and access while dishwasher is open. |\\n| Cleaning chemicals | Separate secure storage, often near sink. | No food/clean-utensil mixing; child access, plumbing and leak clearance. |\\n| Food containers/lids | Near preparation, leftovers packing, and dishwasher. | Paired or divided organization; capacity for actual inventory. |\\n| Small appliances | At use location or reachable storage. | Operating footprint, lid opening, steam, power, ventilation, weight. |\\n| Rarely used items | Less accessible but safe locations. | Do not put heavy objects overhead simply because they are infrequent. |\\n\\nPrefer full-extension drawers for frequently used base storage [S4, S5]. Upper shallow drawers suit small tools; deeper drawers suit bulky items, but choose heights from actual contents, not a fixed three-drawer formula. Prioritize heavy frequently used items at a comfortable lifting height rather than automatically on the lowest level.\\n\\nCompare wide drawer banks with multiple narrow cabinets using usable capacity, load, cost, and multi-user access. A wide open drawer can block another cook. Compare corner mechanisms with a deliberately unused corner plus accessible straight drawers; maximum gross volume is not necessarily best value.\\n\\nFor each cabinet record: `id`, `zone`, `catalog_id_or_provisional`, external dimensions, usable internal dimensions, contents, load, opening direction/extension, fittings, and reason for location. Include fillers, end panels, scribes, plinths, supports, and tolerances in each run. Never assume nominal width equals usable storage or appliance niche width.\\n\\n## 5. Generate and Check Alternatives\\n\\nDevelop two or three genuinely different feasible options when geometry permits, for example retained services versus improved workflow. Do not force an island or a U-layout into a room that cannot support it.\\n\\nFor each option:\\n\\n1. Place immovable constraints and reserve circulation/accessibility envelopes.\\n2. Locate sink, principal preparation area, hob/extraction, and refrigerator landing.\\n3. Fit dishwasher, waste, and nearby clean storage as a working group.\\n4. Allocate remaining storage and secondary tasks from the inventory.\\n5. Fit actual modules, fillers, worktops, panels, and service voids.\\n6. Check 3D fit, closed projections, full swept openings, service access, ventilation, and installation tolerances.\\n7. Run the task trials below. Repair hard failures before comparing soft preferences.\\n\\nRequired trials: unload a full dishwasher; prepare/cook a typical meal; drain a heavy pot; set/clear the table; put away groceries; remove waste; and let a second person reach drinks while cooking continues. Include the actual accessibility/child-use scenarios in the brief.\\n\\nCheck necessary simultaneous openings, especially dishwasher plus receiving drawer, refrigerator door plus internal drawer, sink/waste plus dishwasher, and perpendicular corner units. Not every door must open simultaneously, but the normal task combinations must work. Record remaining conflicts and their consequences.\\n\\nMeasure travel along collision-free walkable paths between usable standing positions, with task-specific openings represented. Do not measure straight through an island or across an open door. Without a geometry/path tool, use a clearly labeled manual estimate or `unknown`; do not fabricate precision.\\n\\n### Compare Everyday Effort\\n\\nUse lexicographic priorities: hard feasibility first, essential usability/storage second, daily effort third, then cost/style trade-offs within the agreed brief.\\n\\nFor a transparent optional distance estimate, calculate:\\n\\n`daily_travel_m = sum(task_cycles_per_day * sum(trip_count_per_leg * walkable_leg_length_m))`\\n\\nDefine each leg as a one-way movement. Include return legs explicitly where they occur. For unloading, use realistic batches carried per trip, not one trip per plate and not an implausibly heavy stack. Use the same inventory, carry capacity, and task frequencies for every option. Label assumed frequencies and distances.\\n\\nReport bending/high reaching, awkward lifts, door conflicts, and traffic crossings separately; do not add metres, counts, and money without explicit normalization and user-agreed weights. Never label a heuristic score a certified optimum or claim percentage savings without a baseline calculation.\\n\\n## 6. Deliver the Plan\\n\\nReturn a concise recommendation followed by:\\n\\n1. Brief, assumptions, missing measurements, and readiness status.\\n2. Dimensioned layout, orientation, appliance locations, and clear work surfaces. If no drawing tool exists, supply wall-by-wall cabinet sequences with dimensions, not an invented rendered plan.\\n3. Cabinet/drawer schedule specifying exactly what goes where.\\n4. Dishwasher-unloading explanation: standing position, receiving drawers/cup storage, openings, paths, and compromises.\\n5. Alternatives table: hard failures/unknowns, preparation space, usable storage, travel estimate, ergonomics, installed cost confidence, and trade-offs.\\n6. Constraint report with rule IDs, measurement definitions, evidence, pass/fail/unknown, and remedies.\\n7. Action list assigning survey, electrical, plumbing, ventilation, structural, accessibility, and installation checks to the appropriate reviewer.\\n\\nUse the status `concept`, `dimensionally_checked`, or `ready_for_professional_order_review`. The last status requires verified survey, exact product compatibility, complete parts/cost scope, and no unresolved hard constraint. It is not professional installation approval. When required reviewers approve, record who approved what and against which plan/manual revisions before any separate order authorization.\\n\\nIf no feasible layout exists, identify the conflicting constraints and smallest changes to consider, such as reducing an island, changing an appliance, or obtaining approval to relocate services. Never silently shrink a required clearance or alter a user must-have.\\n\\n## Quality Checks for This Skill\\n\\nBefore delivering a plan, verify these counterexamples are handled correctly:\\n\\n- Sink beside hob: report preparation-space and installation checks, not an invented EU prohibition.\\n- Dish drawer close to dishwasher but behind its open door: reject the unloading arrangement despite the short nominal distance.\\n- Short route through an island: replace it with a walkable route or mark distance unknown.\\n- Attractive layout with unknown hood clearance: keep installation readiness blocked.\\n- Single-wall or mixed-handed kitchen: use task-based zoning without forcing a triangle or handedness rule.\\n- Wheelchair brief: invoke applicable accessibility checks and user trials; a generic aisle recommendation is insufficient.\\n- Best geometric score but insufficient plate storage or overloaded drawers: do not recommend until capacity/load are resolved.\\n\"","export default \"# Kitchen Planning Evidence and Constraints\\n\\nResearch checked: 2026-10-09. Scope: residential kitchens, Germany/EU default. This is an original synthesis of public guidance, not a reproduction of a standard, a legal opinion, or an installation specification.\\n\\n## Evidence Boundaries\\n\\nAMK, Blum, and IKEA offer useful planning guidance; their editorial advice is not law. Product marketing is not proof of compatibility or universal ergonomic superiority. A named standard is mandatory only where applicable through law, contract, or the project brief; establish that applicability with qualified reviewers.\\n\\nShort source IDs refer to the optional [source catalog](./source-catalog.md), which holds URLs, publication details, and research notes. Do not load it for routine planning; consult it only for source verification, provenance/citation questions, or guidance updates. Rule classifications and operational qualifications remain in this reference.\\n\\nThe full DIN standard and project-specific appliance installation manuals were not examined. Numerical clearance requirements for a real product therefore remain to be supplied. Verify current applicable requirements and exact product instructions for each project; the research date does not establish a document's technical currency.\\n\\nSome general advice is too absolute to reuse literally. For example, induction surfaces can remain hot from cookware, lift-up doors still need head/ceiling/reach checks, and handedness does not determine a whole household's best layout. Apply task and product checks rather than repeating marketing assurances.\\n\\n## Dimensions and How to Use Them\\n\\nAll dimensions below are in mm. Label the rule class and source whenever presenting them to a customer.\\n\\n| Topic | Starting guidance | Status and measurement |\\n| --- | --- | --- |\\n| Main preparation width | Approximately 900; Blum advises at least 800 for comfortable preparation. | Published ergonomic recommendation [S3], not a statutory minimum. Clear usable work surface, preferably between sink and hob; not centre-to-centre distance. |\\n| Single-cook working aisle | Explore roughly 1000-1200 initially. | This skill's concept-sizing heuristic, not a sourced legal minimum. Measure the narrowest gap between finished closed projections, then test open appliances and the user. |\\n| Shared working aisle | Explore roughly 1200-1500 initially. | Concept-sizing heuristic only. Simultaneous work, carry tasks, and passage can need more; extra width also lengthens transfers. |\\n| Standing preparation height | Start near measured elbow height minus 150. | AMK recommendation [S1]; test in usual footwear with a mock-up. Sink depth and cookware change effective task height. No universal 900-high worktop. |\\n| Accessible kitchen movement space | The DIN 18040-2 secondary summary describes 1200 x 1200, and 1500 x 1500 for wheelchair use; front clearance depths of 1200 and 1500 respectively. | [S7] is a secondary explanation, not the standard itself. Confirm current applicable provisions, including the wheelchair-specific category, and all other access requirements. These are not universal minimum kitchen dimensions. |\\n| Dishwasher to dish storage | Comfortable turn or short step where feasible. | Adjacency principle [S4]; no universal maximum distance established by this research. Open-state usability determines success. |\\n| Hob/oven/fridge landing | Reserve usable nearby surface sized for the actual pan, tray, or grocery load. | Functional planning recommendation. Do not invent a universal legal landing width. The hot-tray route must be safe with the appliance door open. |\\n| Hood, hob, combustible surfaces | Use exact product and applicable local requirements. | No generic numeric default. Check all applicable instructions; resolving a conflict may require changing products. |\\n| Cut-out webs, overhangs, supports | Use material/fabricator specifications. | No generic numeric default; material, thickness, cut-outs, support and installation details matter. |\\n| Drawers, fronts, fillers, service voids | Use selected cabinet/appliance system drawings. | Catalog-specific; never insert an arbitrary filler and assume collision/installation issues are resolved. |\\n\\nA concept aisle width is not the free width remaining during use. For an illustrative opposing arrangement only, a 1200 aisle minus a 600 dishwasher-door projection minus a 500 drawer projection leaves just 100 between the open fronts. That is not adequate standing space between them. Real doors, racks, handles, body envelopes, and sideways access require actual drawings and task simulation. The numbers here are hypothetical, not product specifications.\\n\\n## Installation and Usability Checklist\\n\\nUse the IDs below in the project's constraint register. These are check categories: obtain evidence to establish the exact hard requirement or recommendation for each project. Mark unknowns explicitly.\\n\\n| ID | Check | Evidence or required outcome |\\n| --- | --- | --- |\\n| GEO-01 | Verified geometry | Finished dimensions, out-of-square walls, slopes, trims, levels, and measurement tolerance are represented. No fit claim based only on photos. |\\n| GEO-02 | Circulation and exit | Doors, clear passages, room access and applicable escape requirements remain usable. Assess appliance-open task states and occupants. |\\n| GEO-03 | Collision volumes | Check full door/drawer travel, handles, lift fronts, internal pull-outs, adjacent fronts, and head clearance. Closed-box collision tests are insufficient. |\\n| GEO-04 | Windows and heat | Tap does not prevent required window operation. Window/blind/curtain position, hob heat, drafts, splash exposure and required access are reviewed. |\\n| GEO-05 | Seating and island | Account for occupied seats, pulled-out chairs, knee space, passage and hot/splash zones. Do not double-count the same area for incompatible simultaneous uses. |\\n| FIT-01 | Cabinet run and niches | Include end panels, corner solutions, fillers, scribes, wall tolerances and actual appliance niches, not just nominal cabinet widths. |\\n| FIT-02 | Front and plinth systems | Integrated dishwasher front weight/height, fixed or sliding hinge, plinth sweep, mounting and countertop protection match the exact model. |\\n| FIT-03 | Refrigerator operation | Required opening angle permits internal drawers/shelves to operate and be removed; wall stand-off, hinges and ventilation are correct. |\\n| FIT-04 | Hob underside and extraction | Body, induction cooling, required separation, cables, downdraft motor/duct/filter and drawers do not compete for the same volume. |\\n| FIT-05 | Oven and microwave | Approved niche, ventilation, door travel and shelf reach; hot vessels can be removed safely to a landing surface. A high oven must not require lifting hot trays above the user's safe reach. |\\n| FIT-06 | Raised appliances | Support structure, fixing, manufacturer approval and reachable controls/racks are verified. Do not put a floor-supported appliance on an improvised shelf. |\\n| WAT-01 | Sink assembly | Bowl, drainer, clips, tap, waste, trap, hoses, drawers and bins fit together; servicing remains possible. |\\n| WAT-02 | Water and drainage | Qualified installer verifies supplies, pressure, hot-water compatibility, drainage route/levels, appliance hose limits and required backflow protection. Proximity alone proves none of these. |\\n| WAT-03 | Shutoff and leak access | Isolation, connections and leak-protection equipment remain accessible as required; no pinched hoses or inaccessible maintenance points. |\\n| WAT-04 | Special water equipment | Boiling/chilled/carbonated/filter systems have approved taps, tank/filter/cylinder space, ventilation, power, maintenance and child protection. |\\n| ELE-01 | Electrical design | Qualified electrician verifies available supply, connected loads, circuits, protective devices, earthing, isolation and socket installation under applicable rules. |\\n| ELE-02 | Socket and cable placement | Plan for all fixed and small appliances, lighting and powered fittings. Keep cords out of wet/hot areas and across no circulation route; verify plugs do not consume a prohibited niche/service volume. |\\n| ELE-03 | No invented wet-area rule | Do not transpose bathroom electrical zones into a kitchen or assert a blanket socket-to-sink distance without an applicable source. Obtain the electrician's project-specific layout. |\\n| GAS-01 | Gas equipment | Approved professional checks supply, isolation, installation, ventilation and appliance-specific combustible clearances. No DIY connection instructions. |\\n| VEN-01 | Extraction choice | Establish exhaust or recirculation early. Check hood capture at the actual hob, installed airflow, noise, filter access, duct dimensions, bends, outlet and replacement-air strategy. |\\n| VEN-02 | Recirculation limits | Recirculation normally does not remove cooking moisture outdoors and is not a substitute for necessary room ventilation. Check system-specific requirements. |\\n| VEN-03 | Combustion interaction | Exhaust plus a room-air-dependent fireplace/heater triggers professional pressure/backdraft review with the responsible chimney sweep and ventilation specialist. Do not assume a window switch alone makes the system safe. |\\n| VEN-04 | Building permissions | Check landlord/owners' association approvals, facade penetrations, fire separations, communal shafts and whole-dwelling ventilation interactions. |\\n| TOP-01 | Worktop structure | Fabricator verifies cut-out spacing, edge webs, joint locations, supports, spans, overhangs, thermal limits and installation method. |\\n| TOP-02 | Water and steam protection | Seal/protect cut-outs, joints, sink area and dishwasher edges as specified; account for automatic-opening dishwasher steam. |\\n| STR-01 | Fixings and stability | Suitable wall fixings, rails, suspended loads, tall-unit restraint, island support and loaded drawers. Check floor/underfloor services before drilling. |\\n| STR-02 | Structural alterations | No wall removal or structural drilling assumption without qualified assessment and required permissions. |\\n| USE-01 | Preparation and landings | Real unobstructed preparation and grocery/hot-vessel landing space remains after permanent countertop items are placed. |\\n| USE-02 | Unloading | Dishwasher, rack, receiving storage and user can occupy needed positions together; no stepping over the door or excessive reaching. |\\n| USE-03 | Waste and hygiene | Scrape/sort/load route works; bins can be removed and cleaned. Separate chemicals from food/clean items; provide cleanable food-contact surfaces and drying space. |\\n| USE-04 | Storage capacity and loads | Actual inventory fits internally with chosen organizers and runner ratings. Record spare capacity if requested; do not invent a mandatory percentage. |\\n| USE-05 | Multi-user tasks | Test concurrent cooking, dish handling, drinks access and table setting; identify crossings and bottlenecks. |\\n| ACC-01 | Accessibility | Confirm required standard/category; check turning and approach spaces, knee/toe clearance, seated reach, controls, grip/force, task height and protected hot pipes. Test with the actual user/mobility aid. |\\n| SAFE-01 | Children and burns | Secure knives/chemicals, review reachable controls and hot-water dispensing, prevent pot-handle exposure to traffic/seating. Induction still has residual heat; child locks do not replace supervision. |\\n| SAFE-02 | Flooring and edges | Review slip/trip risk, thresholds, protrusions, sharp corners and cleanability. Do not let loose mats create an access hazard. |\\n| LGT-01 | Lighting | Illuminate preparation, sink and hob without the user casting a working shadow. Check glare, contrast, controls and usable light beneath cabinets; lighting drivers remain serviceable. |\\n| ENV-01 | Comfort and maintenance | Compare actual appliance noise, energy/water data, extractor filter costs, cleanability, material heat/moisture resistance and repairability. Verify current product labels. |\\n| SRV-01 | Replacement access | Appliances can be isolated, removed and replaced after flooring/worktops are installed; filters, traps, drivers and fixings can be serviced. |\\n| ORD-01 | Complete order scope | Include appliances, cabinets, fronts, hinges, runners, handles, fillers, panels, plinths, feet, rails, supports, worktops, cut-outs, lighting, extraction, fittings, delivery, installation and service work. |\\n| ORD-02 | Release gate | Final survey, product/manual revisions, costs, permissions and responsible professional checks match the exact proposed order. Obtain explicit order authorization. |\\n\\n## Worked Arrangement: Pattern, Not Template\\n\\nAn illustrative working run can be:\\n\\n`[dish/cutlery drawers] [dishwasher] [sink] [prep drawers + clear worktop] [hob/cookware]`\\n\\nDaily cups/glasses can occupy comfortably reachable storage above the dish bank or another nearby accessible location. Waste can be under the sink or in a separate nearby pull-out if loading, preparation and bin removal all work. Do not consume the only preparation drawer space without a replacement.\\n\\nThis pattern places clean storage on one side of cleanup and preparation on the other. It is neither a complete kitchen nor a mandatory sequence: refrigerator/pantry, oven, landing surfaces, end conditions and services must still be located. Mirror or split the run when the room and users benefit. A hob at the run's exposed end still needs its verified clearances and usable landing arrangement.\\n\\nFor an L-layout, a drawer around the corner from the dishwasher may be physically close but impossible to open during unloading. For a galley, opposing dish drawers may work or may block the user's standing position. The decisive check is the open-state task, not the diagram's apparent neatness.\\n\\n### Transparent Travel Example\\n\\nSuppose two otherwise feasible options each need four storage transfers per dishwasher cycle. Assume three return legs to the dishwasher before the final transfer, one cycle daily, and equal one-way path lengths in either direction:\\n\\n- Option A: 1.0 m per leg -> `(4 + 3) * 1.0 = 7.0 m` per cycle.\\n- Option B: 2.5 m per leg -> `(4 + 3) * 2.5 = 17.5 m` per cycle.\\n- Difference: 10.5 m per cycle under these assumptions, excluding any final return and other kitchen tasks.\\n\\nThese are illustrative distances and batch counts, not research results. Do not extrapolate time or lifetime savings without measurements. A comfortable turn may produce almost no walking but still involve awkward reaching; report that separately. An option with an obstructed unloading path is infeasible regardless of its calculated distance.\\n\\n## Maintenance and Unverified Requirements\\n\\nThe checklist is deliberately broad but not exhaustive. Actual regulatory requirements, permitted clearances, and compatibility depend on the site, products and users. Obtain the current applicable primary sources, exact installation manuals and qualified reviews before converting any unresolved checklist item into a pass.\\n\\nRevisit this reference when products, material systems, regulations or source guidance change. Keep the general workflow vendor-neutral; replace examples with the project's authorized catalog without losing the open-door, capacity, accessibility and safety checks.\\n\"","export default \"# Kitchen Planning Source Catalog\\n\\nOptional research reference. Load only to verify a source-backed claim, answer a provenance/citation question, or update the guidance. Routine planning does not require this file; the rules, classifications, and operational qualifications are in the skill and [planning reference](./planning-reference.md).\\n\\nResearch checked: 2026-10-09. Scope: residential kitchens, Germany/EU default. The sources below were retrieved for the stated topics. The full DIN standard, paid NKBA handbook, and project-specific appliance installation manuals were not examined. The retrieval date does not establish technical currency; verify current applicable requirements and exact product instructions for each real project.\\n\\n## Sources\\n\\n### S1. AMK: Planen und gestalten\\n\\nhttps://www.amk-ratgeber-kueche.de/kueche/planen-gestalten\\n\\nGerman kitchen-industry association guidance. Supports functional zones, point-of-use storage, approximately 150 mm elbow-to-worktop difference, individualized working heights, full-extension drawers, early service planning, lighting and accessibility considerations. This is consumer guidance, not a regulation or a complete technical standard. Do not adopt every safety/marketing statement literally; see the evidence boundaries in the planning reference.\\n\\n### S2. IKEA Germany: Gestaltungsideen fuer reibungslose Ablaeufe\\n\\nhttps://www.ikea.com/de/de/rooms/kitchen/how-to/kueche-effizient-planen-pub6d21e890/\\n\\nSupports generous preparation space between sink and hob, proximity of waste and dishwasher, and placing cookware/tools at their point of use. Uses the work triangle as a general planning aid. Does not establish a statutory sink-to-hob distance.\\n\\n### S3. Blum: Speisenvorbereitung leicht gemacht\\n\\nhttps://www.blum-inspirations.com/de-eu/wissen/speisenvorbereitung-leicht-gemacht-der-passende-schrank-unterstuetzt-sie-dabei\\n\\nManufacturer ergonomic guidance, article dated March 2022. Recommends a preparation area between sink and hob, approximately 900 mm wide, and advises at least 800 mm; preparation tools and bowls belong nearby in organized drawers. These dimensions are ergonomic recommendations, not proof of product clearance or German code compliance.\\n\\n### S4. Blum: Geschirr perfekt organisiert\\n\\nhttps://www.blum-inspirations.com/de-eu/wissen/geschirr-perfekt-organisiert-im-unterschrank-mit-auszuegen\\n\\nManufacturer guidance, article dated June 2022. Supports dining cutlery and dishes together in full-extension base storage, nearby cups/glasses, and proximity to the dishwasher to reduce unloading travel. It does not supply a universal maximum distance or guarantee collision-free access.\\n\\n### S5. Blum: Die ergonomische Kueche\\n\\nhttps://www.blum-inspirations.com/de-eu/wissen/die-ergonomische-kueche-das-muss-man-beachten\\n\\nManufacturer guidance, article dated July 2021. Explains access benefits of full-extension base drawers and overhead lift fronts versus projecting doors. Benefits still depend on actual reach, opening height, operating force and room geometry; powered fittings are optional, not necessary for every accessible kitchen.\\n\\n### S6. AMK: Geraetetechnik\\n\\nhttps://www.amk-ratgeber-kueche.de/kueche/geraetetechnik\\n\\nSupports early extraction planning, the importance of capture efficiency, storage consumed by downdraft equipment, and appliance feature/energy/noise considerations. Room-volume airflow rules of thumb alone do not constitute a ventilation design. The combustion-safety checklist in the planning reference is a professional-review trigger, not a quoted clearance rule from this page.\\n\\n### S7. nullbarriere.de: DIN 18040-2 Kuechen, Essplatz\\n\\nhttps://nullbarriere.de/din18040-2-kuechen.htm\\n\\nSpecialist secondary summary of German dwelling accessibility guidance. Describes 1200/1500 movement-space dimensions and wheelchair considerations. It is not the official DIN text. Verify the current standard, project category, legal/contractual applicability and complete requirements before claiming conformity.\\n\\n### S8. IKEA Germany: Kuechenplanung\\n\\nhttps://www.ikea.com/de/de/rooms/kitchen/kuechenplanung-pub6003162f/\\n\\nSupports surveying in mm, marking openings/services, and staged planning, checking, ordering and installation. Links to current system-specific planning and installation documents. Those documents and the chosen product manuals must be obtained for a real order.\\n\\n### S9. IKEA Germany: Schubladen organisieren\\n\\nhttps://www.ikea.com/de/de/rooms/kitchen/how-to/kuechenschraenke-und-schubladen-organisieren-8-ideen-die-zeit-und-platz-sparen-pube8ed7a50/\\n\\nSupports full-extension storage, functional grouping, protected knives, organizers and reachable everyday contents. Named fittings are examples, not a recommendation to adopt one vendor.\\n\\n### S10. NKBA Planning Guidelines: Regional Boundary\\n\\nhttps://nkba.org/planning-guidelines/\\n\\nThe public overview describes guidance intended for US/Canadian design practice and its code context. Only the overview was consulted, not the paid handbook. Do not label NKBA dimensions as German/EU requirements or cite handbook clauses not actually verified.\\n\"","export default \"---\\nname: kitchen-planning-fr\\ndescription: \\\"Plan or review a residential kitchen in France, from the measured brief to a proposal for professional order review. Use for French kitchen layouts, cuisine amenagee or equipee, NF C 15-100 planning checks, VMC and hood coordination, copropriete renovation constraints, furnished-rental equipment, sink/preparation/hob placement, dishwasher unloading, and cabinet or drawer allocation. France-first, metric guidance that distinguishes applicable requirements from ergonomic recommendations and household preferences. Not installation certification or a commercial-kitchen design standard.\\\"\\n---\\n\\n# Kitchen Planning for France\\n\\n## Purpose and scope\\n\\nProduce a usable, measurable residential kitchen proposal for a project in France. Default to millimetres and EUR; confirm territory, budget basis, building type, tenure, and work scope before applying requirements. Respond in the user's language; keep French trade terms when they improve coordination.\\n\\nThis is a self-contained specialization of the workspace kitchen-planning approach. It does not require loading the Germany/EU skill. Use [the planning reference](references/planning-reference.md) for detailed checks, evidence qualifications, and worked examples.\\n\\nThe [source catalog](references/source-catalog.md) is optional. Load it only to verify a claim, provide citations, or update guidance. Do not load the bibliography merely to resolve source IDs: operational qualifications are already in this skill and the planning reference.\\n\\n## What is specifically French?\\n\\nThere is no single \\\"normal European kitchen\\\" or uniform French kitchen style. French-market layout guidance uses the same preparation, cleaning, cooking, and point-of-use storage principles as other European guidance (FR-S5).\\n\\n| Planning topic | France-specific adaptation |\\n| --- | --- |\\n| Electrical installation | Establish the applicable NF C 15-100 edition and work scope; distinguish ordinary kitchen sockets from specialized appliance circuits. |\\n| Ventilation | Identify the actual natural ventilation or VMC system, collective or individual, before choosing a hood or moving a cooking zone. |\\n| Renovation authority | Ask about copropriete, landlord consent, common services, structure, and exterior alterations; do not treat a kitchen seller's drawing as permission. |\\n| Rental brief | Distinguish owner occupation, location nue, furnished principal-residence lease, and tourist accommodation; their equipment and legal scopes are not interchangeable. |\\n| Accessibility | Determine applicable French housing provisions and user needs. Do not relabel German DIN dimensions as French compliance. |\\n| Procurement | Resolve cuisine amenagee/equipee labels into an itemized equipment and works schedule, a devis, and an installed TTC budget. |\\n| Lifestyle | Ask about actual cooking, meals, pantry and serving needs. Gas, wine storage, an island, rustic fronts, and elaborate cooking are not national requirements. |\\n\\nThese topics are not all unique to France; their governing documents, terminology, and project decisions are localized here.\\n\\n## Authority and evidence\\n\\n- Classify constraints as `regulatory`, `manufacturer`, `site`, `user_must`, `recommendation`, or `preference`.\\n- The first four are hard constraints when applicable. Recommendations and preferences are soft and may be traded off explicitly.\\n- A published standard is not automatically a universal retroactive legal obligation. Establish the applicable regulation, standard edition, contract, project dates, and scope with the responsible professional.\\n- A manufacturer summary is not the full standard. A product-specific installation requirement is different from that manufacturer's general planning advice.\\n- Never convert an unknown to a pass. If requirements conflict, stop the affected decision and obtain clarification; do not select the convenient rule.\\n- Photographs, scans, inferred dimensions, catalog nominal widths, and AI drawings do not replace a site survey or exact product documentation.\\n- The planner's geometry, catalog, prices, and accepted design remain authoritative. Propose reversible edits and obtain acceptance before changing the design.\\n- Do not claim electrical, gas, structural, ventilation, accessibility, rental, or installation certification. Do not authorize purchases or works.\\n\\n## Workflow\\n\\n### 1. Establish the French project brief\\n\\nCollect only the missing facts needed for the next decision; allow assumptions for concepts, clearly marked.\\n\\n- Commune and territory: metropolitan France or the relevant overseas territory; do not silently apply metropolitan rules overseas.\\n- Apartment or house, approximate construction date, new build or existing dwelling, occupied or vacant during works.\\n- Owner or tenant; copropriete and syndic contact where relevant; private versus shared walls, ducts and service risers.\\n- Cosmetic replacement, partial technical renovation, complete electrical renovation, kitchen relocation, or structural alteration; project and permit/contract dates if relevant.\\n- Owner occupation, location nue, location meublee as a principal residence, bail mobilite, or tourist/secondary-residence use.\\n- Household size, simultaneous cooks, children, reach and mobility needs, wheelchair or seated work, and any applicable accessibility brief.\\n- Cooking frequency, appliance inventory, shopping/storage quantities, dining location, entertaining, and cleaning habits.\\n- Total installed budget in EUR TTC, retained items, time constraints, and responsibility for each trade.\\n\\nAsk whether the household needs a table/coin repas, separate dining area, cellier, baking area, coffee station, large serving dishes, or bottle storage. Derive dimensions from their inventory and routines, not nationality.\\n\\n### 2. Survey the room and services\\n\\nRecord wall lengths at relevant heights, diagonals, finished floor levels, ceiling height, wall build-ups, out-of-square corners, windows and opening arcs, doors, radiators, obstructions, and structural uncertainty.\\n\\nLocate water, waste, isolation valves, electrical outlets and known circuit identities, gas if present, ventilation terminals, air inlets, ducts, and service access. Record delivery access, stairs, lift restrictions, and worktop handling constraints.\\n\\nFor each fact capture `value`, `unit`, `source`, `verification_state`, and measurement uncertainty. Use `unknown`, `inferred`, `user_verified`, or `professionally_verified`. Measure service positions from a declared datum and finished floor; do not infer concealed routes from visible endpoints.\\n\\n### 3. Build the constraint register\\n\\nEach record needs:\\n\\n```text\\nid\\nclass\\napplicability\\nrequirement\\nmeasurement_definition\\nsource\\nstatus: pass | fail | unknown | not_applicable\\naffected_items\\nremedy_or_next_action\\n```\\n\\nRun the French context checks in the reference before freezing a layout. Identify the person responsible for resolving each technical unknown.\\n\\n- Electrical: confirm applicable edition and renovation scope with an electrician; reserve ordinary outlets separately from appliance connections. Socket count alone cannot establish compliance.\\n- Ventilation: a hood does not replace general dwelling ventilation (FR-S3). Preserve air inlets, transfer paths and extraction terminals. A visible communal shaft is not an approved powered-hood connection.\\n- Permissions: flag changes affecting shared services, structure, exterior outlets, or rented premises for the relevant professional, landlord, syndic, and authority checks before works.\\n- Rental: for a furnished principal-residence lease, check the scoped equipment list in the reference (FR-S4). Do not apply it to every kitchen or treat it as a complete rental-compliance assessment.\\n- Accessibility: establish applicable French requirements separately from ergonomic targets; unresolved legal applicability blocks a compliance claim, not an explicitly provisional concept.\\n\\n### 4. Arrange five functional zones\\n\\nMap food storage, preparation, cooking, cleaning, and clean storage/serving to real tasks. Prefer sink -> clear preparation surface -> hob, or its mirror, where the room allows it.\\n\\nProvide a continuous useful preparation area, not a nominal length occupied by a drainer, appliance, corner, or landing zone. As an ergonomic starting point, aim for about 900 mm clear width; around 800 mm is a lower recommendation from manufacturer planning guidance, not a French statutory minimum (FR-S6). Check actual tasks and product cutout/edge requirements separately.\\n\\nDo not invent a universal French 600 mm sink-to-hob prohibition. Assess splashing, heat, pan handles, worktop bridges, adjacent materials, and exact product requirements. A compact compliant layout can still have poor preparation space.\\n\\nKeep grocery-to-fridge, washing-to-preparation, cooking-to-serving, and dirty-dish routes short and unobstructed. A triangle is an optional analytical aid, not a rule; a linear kitchen can work well. Separate through-traffic from hot work where feasible.\\n\\nWhen the user does not name a place for the kitchen, plan it so that the sink stands near a water connection of the plan, if the room has one. The installation elements of the plan context list the water connections with their positions.\\n\\n### 5. Design dishwasher unloading and storage together\\n\\nStart with the dishwasher near the sink, subject to verified connection limits and usable access. Decide which side by actual unloading and loading tests, not handedness alone.\\n\\nTest all of these together: dishwasher door open, racks extended, receiving drawer or cupboard open, and a person standing and turning. Do not make the user step over the door or balance dishes while opening storage.\\n\\nPut everyday plates, bowls and dining cutlery close to a safe unloading position and the serving route. Put cooking utensils, pans and preparation tools near their use. Check that the shortest storage route remains accessible with doors open. A slightly longer unobstructed route can be better than blocked adjacent storage.\\n\\n### 6. Allocate cabinets and drawers by contents\\n\\nCreate a schedule with cabinet ID, location, contents, quantities, largest item size, usable internal dimensions, load limit, opening mechanism, access frequency, and service conflicts.\\n\\n- Use accessible drawers or pull-outs for frequently handled base storage where appropriate; check heavy dish stacks and hardware loads (FR-S7).\\n- Separate dining cutlery from cooking utensils. Give pans, lids, boards and trays usable storage near preparation/cooking.\\n- Size pantry storage to shopping habits; a cellier supplements but does not automatically replace daily point-of-use storage.\\n- Provide safe storage for knives and cleaning products, and a waste-sorting arrangement matching local collection and the household's carrying route.\\n- Keep shutoffs, traps, filters and appliance removal paths accessible. Under-sink space is not an empty rectangular cabinet volume.\\n- Use exact cabinet/appliance combinations: nominal 600 mm widths do not prove integration, ventilation, hinge, front, plinth or worktop compatibility.\\n\\n### 7. Compare feasible alternatives\\n\\nNormally compare two plausible layouts, such as a service-preserving option and a user-priority option. Include an island only if occupied circulation, services, budget and work surfaces support it.\\n\\nTest grocery unloading, preparing a meal, draining a hot pan, dishwasher loading/unloading, serving, waste removal, and two people sharing the room. Include chairs pulled out, doors and drawers open, and a person at the oven. Test task lighting, glare, extraction noise and sightlines for an open kitchen.\\n\\nUse 1000-1200 mm single-cook and 1200-1500 mm shared working aisles only as concept heuristics between the nearest closed projections, not French legal or wheelchair clearances. Then test actual open-state and occupied clearances; apply verified project requirements instead where stricter.\\n\\nFor repeated tasks, estimate:\\n\\n```text\\ndaily_travel_m = sum(task_cycles_per_day *\\n sum(trip_count_per_leg * walkable_leg_length_m))\\n```\\n\\nCount return trips explicitly. State assumptions; compare bending, awkward reaches, handling and collision risks separately. Do not present this proxy as a validated human-performance score.\\n\\n### 8. Resolve the devis and installation boundaries\\n\\nTranslate cuisine amenagee/equipee into explicit inclusions, never assumed legal definitions. List meubles, facades, fileurs, joues, plinthes, plan de travail, credence, evier, robinetterie, electromenager, and fittings as applicable.\\n\\nSeparate supply, delivery, carrying, removal/disposal, preparation works, plumbing, electrical/gas work, ventilation, fitting, worktop templating/cutouts, finishing, testing and handover. Record exclusions, tax basis, quote validity, allowances and who owns final measurements. Do not promise a reduced VAT rate or a fixed total without a verified quote.\\n\\nAsk the cuisiniste and trades to resolve interfaces before final ordering: sockets behind drawers, sink/trap versus bin, dishwasher front versus plinth, duct versus wall unit, and opening clearances versus fileurs are common coordination risks.\\n\\n### 9. Deliver and gate readiness\\n\\nProvide the brief and assumptions, dimensioned plan with opening envelopes, zone/task rationale, cabinet contents schedule, appliance/service schedule, constraint register, alternatives and trade-offs, installed-cost scope, and professional questions/next actions.\\n\\nUse one readiness status:\\n\\n- `concept`: assumptions or unresolved geometry/services remain; no order-ready implication.\\n- `dimensionally_checked`: stated geometry and operating envelopes checked against identified measurements and product data; list unresolved regulatory/technical matters separately.\\n- `ready_for_professional_order_review`: required survey, exact product compatibility, service feasibility, applicable permissions, and hard constraints have supporting evidence with no unresolved failures or unknowns. This still requires professional order review and is not installation approval or purchasing authorization.\\n\\nNever call a proposal \\\"French-compliant\\\" solely because it follows this skill.\\n\"","export default \"# France Kitchen Planning Reference\\n\\nOperational reference for [kitchen-planning-fr](../SKILL.md). Source IDs support traceability without requiring bibliography loading. Open the [optional source catalog](source-catalog.md) only for verification, citations or maintenance.\\n\\n## Evidence boundaries\\n\\nResearch reviewed on 2026-10-09. These are planning checks, not a complete French legal or installation specification. Refresh time-sensitive claims for the actual project. Full NF C 15-100 text, current project-specific accessibility provisions, and product-specific manuals were not inspected in this research.\\n\\nFrench-market planning guidance supports familiar workflow principles, not a separate national geometry (FR-S5). Do not infer household habits, a required style, or a gas preference from the country. Imported appliances and retained furniture need exact compatibility checks, not assumptions based on EU marketing.\\n\\n## French technical and project gates\\n\\n### Electrical scope and layout reservation\\n\\nLegrand's professional guide describes the NF C 15-100 series for new or entirely renovated low-voltage installations in France. It reports the 2024 revision, publication on 2024-08-23, and a 12-month overlap with the previous edition ending 2025-08-23; project reference dates include the contract, permit application or prior declaration (FR-S1). Schneider independently confirms a 2024 revision (FR-S2). These summaries do not determine a particular project's legal or contractual obligations.\\n\\nAsk the electrician to identify the applicable edition, reference date, affected circuits, work scope, protection and testing requirements. Do not assert that replacing cabinets, selling a dwelling, or changing one appliance automatically requires complete rewiring. Conversely, do not use \\\"existing installation\\\" as an exemption from addressing identified hazards or new-work requirements.\\n\\nUse these source-qualified reservations, not automatic compliance tests:\\n\\n| Situation | Reservation and qualification |\\n| --- | --- |\\n| Kitchen clearly greater than 4 m2 | Legrand reports at least six ordinary sockets on a dedicated kitchen circuit, including four above the worktop. Identify appliance connections separately (FR-S1). |\\n| Kitchen clearly less than 4 m2 | Legrand reports at least three ordinary sockets. Confirm applicable exception and placement with the electrician; reduced count is not proof of functional adequacy (FR-S1). |\\n| Exactly 4 m2, uncertain measurement, or open kitchen | The inspected web summary uses less-than/greater-than wording without resolving equality or area definition. Reserve six provisionally and keep applicability unknown until the electrician verifies the full rule. Do not encode a legal threshold from this ambiguity. |\\n| Hood outlet | Legrand describes an optional additional hood outlet at least 1800 mm above finished floor. This is an outlet position, NOT the hood-to-hob installation clearance (FR-S1). Confirm exact permitted position and product instructions. |\\n| Hob, oven, dishwasher and other substantial appliances | Record each model, rated load, connection method, required specialized circuit and isolation access. Have the electrician size and verify the installation. Ordinary socket count is not an appliance-circuit allowance. |\\n| Appliance operation | Verify available supply and simultaneous loads, including retained appliances. Do not assume an existing socket or adapter makes an imported appliance suitable. |\\n\\nAs a conservative planning rule, keep ordinary sockets and trailing leads away from sink and cooking surfaces and do not propose ordinary sockets directly above them. Have the electrician verify exact restrictions and hood exceptions against the applicable standard; this research did not independently verify the full placement clause. Do not import bathroom electrical volumes around a kitchen sink or assert an unsupported universal 600 mm sink/hob separation.\\n\\nCoordinate outlet positions with credence joints, wall units, drawer backs, appliance depth and accessibility. Do not supply DIY conductor, breaker or wiring instructions as part of a furniture plan. Add task lighting without assuming that a ceiling point alone lights preparation adequately.\\n\\n### Ventilation, extraction and gas\\n\\nA hood treats cooking emissions intermittently; dwelling ventilation renews indoor air more generally. Sauter's FAQ explains why a hood cannot replace VMC (FR-S3). This distinction does not prove that every existing French dwelling must receive the same mechanical system.\\n\\nSurvey natural ventilation, individual VMC, collective VMC, air inlets, transfer paths, kitchen extraction terminal, and any combustion appliance. Obtain the relevant design and maintenance information. Do not obstruct vents with cabinets or close a required air path during replacement works.\\n\\n- Recirculation filters return air to the room; do not count them as outdoor exhaust or as a substitute for moisture removal by dwelling ventilation.\\n- Dedicated outdoor extraction requires a feasible, authorized duct route and coordinated air supply. Confirm flow, pressure loss, noise, discharge, fire/acoustic provisions and service access professionally.\\n- Do not connect a powered hood to an unidentified communal duct or VMC terminal. Treat compatibility and permission as unresolved until the responsible ventilation professional and building representative confirm the design. No universal connection prohibition is claimed from the inspected sources.\\n- Where gas or another combustion appliance is present, obtain professional review of air supply and depressurization risks before changing extraction. Do not infer safety from a closed cabinet drawing.\\n- Product manuals determine hood clearance, duct arrangement, filters, maintenance and compatibility; generic advice is not installation evidence.\\n\\n### Copropriete, rented premises and works\\n\\nThese are due-diligence gates, not a sourced statement of voting thresholds or permit law. Determine ownership and permissions before relocating services, cutting walls, changing collective ventilation, penetrating floors, or adding a facade/roof outlet.\\n\\nRecord the reglement de copropriete, syndic response, any required authorization, landlord agreement where relevant, structural assessment, and any mairie/planning-authority requirement. A verbal sales assurance does not resolve these dependencies. Identify who verifies the applicable rules and what evidence is still missing.\\n\\nFor an older building, ask the responsible professional whether surveys for hazardous materials or other pre-work investigations are required before invasive works. Do not diagnose materials from a photograph.\\n\\n### Rental equipment branch\\n\\nService Public's furnished-equipment page, verified 2026-03-06, covers a furnished dwelling used as the tenant's principal residence, including bail mobilite (FR-S4). Its kitchen/meal-related minimum equipment includes:\\n\\n- Cooking plates.\\n- An oven OR a microwave, not necessarily both.\\n- A refrigerator and a freezer, OR a refrigerator with a freezing compartment reaching a maximum temperature of -6 C.\\n- Dishes sufficient for occupants' meals and cooking utensils.\\n- A table and seats, storage shelves, and lighting.\\n\\nThe full furnished-dwelling list also covers bedding, bedroom shading and appropriate cleaning equipment. An inventory and detailed furniture condition record accompany the lease. Kitchen planning alone cannot certify the whole dwelling.\\n\\nDo not add a dishwasher to this minimum list. Do not require luxurious fitted cabinets or apply this list to an owner-occupied home, location nue, or tourist rental. For those branches, identify the applicable requirements separately. The decency overview reviewed during research distinguishes metropolitan and overseas contexts but its detailed equipment sections were not inspected; do not infer that unfurnished rental means \\\"no kitchen obligations.\\\"\\n\\nIn a relevant furnished-rental project, separate `regulatory` minimum equipment from `user_must` additions and `preference` upgrades. Verify the current applicable legal basis before final review.\\n\\n### Accessibility\\n\\nConfirm whether French housing accessibility provisions apply to the building category, new/existing context, project date, dwelling status and work scope. Ask the responsible professional to supply current requirements and their measurement definitions, including any accessible/evolutive provisions relevant to the project.\\n\\nThe official-partner accessibility portal distinguishes new housing, existing housing and building types, but the inspected page was last updated in 2021 and warns of CCH recodification (FR-S8). It is orientation only, not current numerical kitchen-compliance evidence.\\n\\nDo not substitute German DIN, US guidance or a generic 1500 mm aisle for the applicable French rule. Separately test the actual user's turning, approach, knee/toe space, reach, handles, controls, sink protection, seated preparation and transfer needs. A user trial supplements, not replaces, applicable requirements.\\n\\n## Working dimensions and measurement definitions\\n\\n| Item | Concept starting point | Definition and authority |\\n| --- | --- | --- |\\n| Main preparation width | About 900 mm; around 800 mm as a lower ergonomic recommendation | Clear usable worktop between interfering features; manufacturer planning guidance, not French law (FR-S6). |\\n| Single-cook working aisle | 1000-1200 mm | Nearest closed projections, including handles; inherited planning heuristic, then test occupied/open states. |\\n| Shared working aisle | 1200-1500 mm | Same measurement; concept heuristic, not an accessibility standard. |\\n| Worktop height | User/task-specific | Trial with actual users, sink depth and hob/pan height; do not impose a fixed \\\"French height.\\\" |\\n| Appliance bay and ventilation | Exact selected system | Installation drawings, required air paths, fronts, fixings and service voids; never nominal cabinet width alone. |\\n| Sink/hob separation and worktop bridges | Product and task-specific | Distinguish clear preparation width from cutout-edge distances and structural bridges. |\\n| Accessibility dimensions | Project-specific, professionally verified | State current source, applicability and exact geometry before marking pass. |\\n\\n## Constraint checklist\\n\\nCreate project records from these categories; do not automatically mark the checklist passed. Applicable regulatory, manufacturer, site and user-must requirements are hard constraints. Record unknowns and their owners.\\n\\n| ID | Check and evidence needed |\\n| --- | --- |\\n| FR-CTX-01 | Territory, building type, tenure, lease branch and project dates established. |\\n| FR-CTX-02 | Scope of works and applicable technical/regulatory documents identified by responsible professionals. |\\n| FR-PER-01 | Shared property, structure, facade and communal-service alterations identified; permissions resolved where required. |\\n| FR-PER-02 | Landlord and project-specific pre-work survey/authority dependencies resolved where applicable. |\\n| FR-GEO-01 | Survey datums, finished surfaces, diagonals, tolerances and uncertainty recorded. |\\n| FR-GEO-02 | Window/door arcs, radiators, ceiling and service obstructions represented. |\\n| FR-GEO-03 | Delivery, lift/stair access, worktop transport and assembly path verified. |\\n| FR-FIT-01 | Cabinet runs include fileurs, joues, fronts, handles, plinths and installation tolerances. |\\n| FR-FIT-02 | Exact appliance niches, hinges, ventilation, front weights and door/plinth compatibility checked. |\\n| FR-FIT-03 | Drawers, corner mechanisms, appliances and neighboring doors tested together. |\\n| FR-FIT-04 | Walls/floors, cabinet fixings, suspended loads and worktop support verified. |\\n| FR-WAT-01 | Water, drain route, levels and proposed relocation feasible; not inferred from endpoints. |\\n| FR-WAT-02 | Valves, trap, bins, sink bowl and drawer envelopes compatible and accessible. |\\n| FR-WAT-03 | Dishwasher hose routing, limits and connection access match selected product. |\\n| FR-ELE-01 | Electrician confirms edition, reference date, work scope and applicable requirements. |\\n| FR-ELE-02 | Ordinary socket count, area interpretation and usable placement verified separately from appliance circuits. |\\n| FR-ELE-03 | Appliance loads, circuit provisions, supply, protection and isolation access professionally checked. |\\n| FR-ELE-04 | Outlet/lead positions coordinated with wet/hot areas, furniture and credence; lighting supports tasks. |\\n| FR-VEN-01 | Existing ventilation type, inlets, transfer paths and extraction terminals documented and preserved. |\\n| FR-VEN-02 | Hood mode, duct feasibility, air supply, collective-system compatibility and permissions verified. |\\n| FR-VEN-03 | Hood/product clearances, noise, filters and maintenance access checked. |\\n| FR-GAS-01 | Gas/combustion installation and extraction interaction professionally assessed where applicable. |\\n| FR-TOP-01 | Worktop cutouts, bridges, edge distances, joints and supports meet supplier requirements. |\\n| FR-TOP-02 | Splash/heat exposure and adjacent surface/material compatibility resolved. |\\n| FR-USE-01 | Continuous preparation surface remains usable with everyday appliances in place. |\\n| FR-USE-02 | Dishwasher unloading tested with racks, receiving storage and user present. |\\n| FR-USE-03 | Cabinet allocation reflects real contents, usable dimensions, loads and frequency. |\\n| FR-USE-04 | Grocery, cooking, serving and waste routes tested without unsafe crossings. |\\n| FR-USE-05 | Occupied chairs, multiple cooks and open oven/drawer states preserve required passage. |\\n| FR-ACC-01 | Applicable French accessibility requirements and actual user needs both addressed. |\\n| FR-SAF-01 | Hot-pan landing, child safety, knife/chemical storage and stable furniture addressed. |\\n| FR-SRV-01 | Appliance removal, shutoffs, filters and repair access remain possible. |\\n| FR-REN-01 | Correct lease/territory branch selected; relevant equipment inventory verified without overextending its scope. |\\n| FR-ORD-01 | Itemized supply/work/exclusion schedule and installed EUR TTC budget agreed. |\\n| FR-ORD-02 | Final measurements, exact products, technical interfaces, evidence and professional-review responsibilities resolved. |\\n\\n## Worked checks\\n\\n### Open-state dishwasher conflict\\n\\nA 1200 mm closed-front aisle looks generous. A dishwasher projects 600 mm into it and an opposing receiving drawer projects 500 mm. The residual gap is:\\n\\n```text\\n1200 - 600 - 500 = 100 mm\\n```\\n\\nThat is not usable standing/unloading space. It fails this simultaneous-use scenario even if neither closed cabinet footprint overlaps. Move the receiving storage, change opening direction/type or redesign the arrangement; then rerun the test with actual products and the user envelope.\\n\\n### Unloading travel\\n\\nAssume four equal batches carried from dishwasher to storage, three return trips, and start at the dishwasher/end at storage. For illustrative measured walkable routes of 1.0 m and 2.5 m:\\n\\n```text\\nnear_storage_m = (4 + 3) * 1.0 = 7.0\\nfar_storage_m = (4 + 3) * 2.5 = 17.5\\ndifference_per_cycle_m = 17.5 - 7.0 = 10.5\\n```\\n\\nDo not use straight-line cabinet distances through open doors. The shorter route wins only if it remains safe and usable; bending and load handling need separate assessment.\\n\\n### French socket-count boundary\\n\\nA kitchen is measured at 4.0 m2 with uncertainty, and the seller proposes three ordinary sockets. The inspected manufacturer's less-than/greater-than summary does not settle the boundary. Reserve six provisionally, ask the electrician for the applicable area/count rule, and keep that requirement `unknown`. Even six visible sockets cannot prove circuit or placement compliance.\\n\\n### Furnished-rental distinction\\n\\nA principal-residence furnished letting has a hob, microwave and suitable refrigerator/freezing compartment but no conventional oven or dishwasher. The oven-or-microwave requirement is not failed merely because there is no conventional oven; the dishwasher is not on the inspected minimum list. Verify the rest of the equipment, lease scope and dwelling requirements before any compliance conclusion (FR-S4).\\n\\n### Shared-duct constraint beats preferred island\\n\\nA proposed island hood depends on an unidentified communal shaft. Do not draw a connection and mark ventilation passed. Keep feasibility/permission `unknown`; compare a service-preserving arrangement and a professionally assessed recirculation option that retains general ventilation. Neither becomes order-review-ready until all applicable hard constraints are resolved.\\n\\n## Final review questions\\n\\nCan a user prepare, cook, unload and serve with real occupied/open states? Are French project requirements evidenced rather than presumed? Can installers resolve every service/furniture interface from the documents? Are remaining assumptions visible and incompatible with any claimed readiness? If not, return the proposal to the appropriate earlier stage.\\n\"","export default \"# France Kitchen Planning Source Catalog\\n\\nOptional research/provenance file for [the skill](../SKILL.md) and [its operational reference](planning-reference.md). Do not load during routine planning unless a claim needs verification, the user requests citations, or guidance is being updated.\\n\\nReviewed on 2026-10-09. Source claims are paraphrased. A retrieval date is not a guarantee of current legal applicability. Commercial guidance is identified as such; general manufacturer advice is not a selected product's installation manual.\\n\\n## FR-S1: Legrand, NF C 15-100 professional guide\\n\\n- URL: https://www.legrand.fr/pro/normes-et-reglementations/norme-nf-c-15-100/norme-nf-c-15-100-suivez-le-guide\\n- Publisher/type: Legrand, manufacturer technical summary; page headed \\\"Norme NF C 15-100 en 2026 : on vous dit tout.\\\"\\n- Inspected: introduction, structure of the standard, circuits prises, and related scope text.\\n- Supports: 2024 revision and reported transition dates; new/entirely renovated installation context; ordinary kitchen socket reservations; separate specialized appliance connections; four worktop sockets within the six-socket case; optional additional hood outlet at 1800 mm minimum above finished floor.\\n- Limits: not the complete standard or an independent legal interpretation. The page uses `< 4 m2` and `> 4 m2` without explicitly resolving equality. Do not convert that gap into a legal rule. Its general appliance circuit examples are not a complete design for any particular supply or appliance inventory. Full placement clauses were not independently inspected.\\n- Use in skill: French electrical intake, reservations, electrician handoff, and boundary-case test. No DIY wiring instructions or automatic retrofit obligation.\\n\\n## FR-S2: Schneider Electric, NF C 15-100 overview\\n\\n- URL: https://www.se.com/fr/fr/work/support/local/reglementation/norme-nfc15-100/\\n- Publisher/type: Schneider Electric France, manufacturer standards overview.\\n- Supports: identification of the 2024 revision and availability of updated guidance; AFNOR standard versus explanatory guide distinction.\\n- Limits: detailed expandable answers and the downloadable guide were not inspected. Does not independently verify the numeric kitchen reservations used from FR-S1.\\n- Use in skill: cross-check of the revision context, not project compliance evidence.\\n\\n## FR-S3: Sauter, hood versus VMC\\n\\n- URL: https://www.confort-sauter.com/aide/vmc/installation/ma-hotte-de-cuisine-peut-elle-remplacer-une-vmc/\\n- Publisher/type: Sauter, manufacturer ventilation FAQ.\\n- Supports: continuous air renewal by VMC versus intermittent removal of cooking emissions by a hood; their complementary functions.\\n- Limits: blanket marketing statements about mandatory VMC are not used as universal retrofit law. This FAQ did not establish legal permission or a universal prohibition for powered-hood connection to a communal system.\\n- Use in skill: retain general ventilation, investigate the actual system, and require professional compatibility/permission evidence.\\n\\n## FR-S4: Service Public, furnished-dwelling equipment\\n\\n- URL: https://www.service-public.gouv.fr/particuliers/vosdroits/F34769\\n- Title: \\\"Bail d'habitation : qu'est-ce qu'un logement meuble ?\\\"\\n- Publisher/type: French public-service administrative guidance; page verification date 2026-03-06.\\n- Supports: minimum equipment for a furnished principal-residence lease, including bail mobilite; cooking plates, oven OR microwave, refrigerator/freezer alternative, dishes, utensils, table/seats, storage and lighting; inventory documentation.\\n- Limits: not a universal specification for owner occupation, location nue, holiday rentals or every overseas jurisdiction. The whole dwelling has additional requirements beyond the kitchen. Verify the current applicable legal basis and territorial scope for the project.\\n- Use in skill: scoped rental branch and equipment distinction, not a complete decency certificate.\\n\\n## FR-S5: IKEA France, practical kitchen layout\\n\\n- URL: https://www.ikea.com/fr/fr/rooms/kitchen/how-to/idees-dagencement-pratique-pour-la-cuisine-pub6d21e890/\\n- Title: \\\"Idees d'agencement pratique pour la cuisine.\\\"\\n- Publisher/type: French-market retailer planning advice.\\n- Supports: preparation between sink and cooking, nearby dishwasher/waste, storage at point of use, and several layout forms.\\n- Limits: activity-triangle and equal-distance language is advisory, not mandatory. One retailer cannot establish the prevalence of national household habits.\\n- Use in skill: evidence that familiar ergonomic principles also apply in France; no invented French triangle or style requirement.\\n\\n## FR-S6: Blum, preparation storage and worktop\\n\\n- URL: https://www.blum-inspirations.com/de-eu/wissen/speisenvorbereitung-leicht-gemacht-der-passende-schrank-unterstuetzt-sie-dabei\\n- Publisher/type: Blum, German-language European manufacturer ergonomics/planning advice, reused from the general kitchen research.\\n- Supports: preparation worktop and related storage; approximately 900 mm recommended working width and around 800 mm lower ergonomic recommendation.\\n- Limits: not French regulation and not a universal minimum. Usable clear surface, tasks, products and users matter more than a nominal run length.\\n- Use in skill: explicitly labeled transferable ergonomic recommendation, not country-specific compliance.\\n\\n## FR-S7: Blum, accessible dish storage\\n\\n- URL: https://www.blum-inspirations.com/de-eu/wissen/geschirr-perfekt-organisiert-im-unterschrank-mit-auszuegen\\n- Publisher/type: Blum, German-language European manufacturer storage guidance, reused from the general kitchen research.\\n- Supports: accessible base-unit pull-outs for dishes and handling-oriented storage allocation.\\n- Limits: commercial guidance; verify actual usable dimensions, loads and user reach. Does not prove that every drawer is suitable for every dish stack.\\n- Use in skill: contents-driven drawers and dishwasher-unloading evaluation.\\n\\n## FR-S8: Accessibility portal, housing applicability orientation\\n\\n- URL: https://www.accessibilite-batiment.fr/logements-neufs/generalites-et-definitions/code-de-la-construction-et-de-lhabitation.html\\n- Publisher/type: DHUP-CSTB-Cerema accessibility portal, regulatory orientation.\\n- Inspected: general distinctions for collective housing and individual houses; page update 2021-09-10 and warning concerning CCH recodification from 2021-07-01.\\n- Supports: the need to distinguish building categories, project context and applicable documents rather than treating every kitchen identically.\\n- Limits: old numbering and dated material; not relied on for a current legal determination or any French kitchen dimension. Current full applicable provisions must be obtained for the project.\\n- Use in skill: accessibility applicability gate; no imported DIN or unverified French numeric requirement.\\n\\n## Research exclusions and maintenance\\n\\n- Service Public's rental-decency overview at https://www.service-public.gouv.fr/particuliers/vosdroits/F2042 was only partially accessible. Its metropolitan/overseas distinction informed the intake; detailed kitchen-equipment provisions were not verified.\\n- IZI by EDF's kitchen-electrical article was inspected but not adopted as authority because its broad claims and comments contained ambiguities or conflicts. In particular, no universal 600 mm sink/hob rule, kitchen bathroom-like volumes, mandatory kitchen RJ45, or automatic whole-dwelling upgrade on sale is adopted.\\n- IKEA France's hood article was inspected but is not used for generic hood heights, filter lifetimes or claims that recirculation removes humidity outdoors.\\n- Primary ventilation legislation could not be retrieved from Legifrance during research. No numeric statutory ventilation rate or categorical communal-duct legal rule is asserted.\\n- Copropriete permissions, landlord agreement, quotations and trade coordination are practical due-diligence checks. Voting thresholds, permit procedures, statutory quote requirements and VAT rates were not established and are not prescribed.\\n- No primary text or current project-specific French accessibility clause was verified. Do not turn portal orientation into an accessibility certificate.\\n- Before updating a numeric requirement, check the full current source, territorial/project applicability, exceptions and measurement definition; update the operational guidance and source qualification together.\\n\"","export default \"---\\nname: living-room-planning\\ndescription: \\\"Plan or review a living room, lounge, sitting room, or Wohnzimmer using household activities, verified geometry, and practical furniture constraints. Use when arranging sofas, armchairs, recliners, sofa beds, coffee tables, TV/media units, bookshelves, or storage; comparing conversation and TV layouts; checking circulation, accessibility, lighting, glare, child safety, or open-plan living zones. Defaults to Germany/EU context and metric units; separates requirements from ergonomic recommendations and preferences. Includes operational checks and an optional research source catalog.\\\"\\n---\\n\\n# Living Room Planning\\n\\n## Purpose and loading policy\\n\\nCreate practical, explainable living-room proposals that work for the household's real activities. Optimize comfort, access, storage, and ease of changing activities before decorative composition or maximum furniture count.\\n\\nDefault to Germany/EU context, dimensions in millimetres, and costs in EUR unless the user specifies otherwise. Confirm the actual country and, where relevant, German federal state. There is no single set of EU living-room layout rules.\\n\\n- Read [the planning reference](./references/planning-reference.md) before applying numerical guidance, assessing accessibility or installation risks, or declaring a layout dimensionally checked.\\n- Read [the optional source catalog](./references/source-catalog.md) only to verify a source, answer provenance/citation questions, resolve disputed claims, or update guidance.\\n- Do not load the source catalog merely to resolve source IDs during routine planning. The operational reference contains the qualifications needed for normal use.\\n- This skill supports planning, not structural design, electrical installation, fire-safety approval, clinical assessment, or permission to purchase.\\n\\n## Non-negotiable discipline\\n\\n1. Distinguish measured facts, assumptions, user preferences, recommendations, and mandatory requirements.\\n2. Never infer exact room dimensions, wall construction, load capacity, or safe clearances from a photograph alone.\\n3. Preserve the existing planner's authoritative geometry, product catalog, and accepted design. Proposals are reversible drafts until explicitly accepted.\\n4. Check occupied, moving, and fully deployed furniture, not just closed footprints. A sofa bed's sleeping surface is not its overall deployed size.\\n5. Do not treat a reachable-looking gap, generic furniture dimension, or aesthetic rule as proof of accessibility or safety.\\n6. Keep required exits and escape openings usable in every relevant mode. A blocked exit is not acceptable because guest use is infrequent.\\n7. Unknown is not pass. Missing critical dimensions or installation evidence must remain visible.\\n8. Do not prescribe a TV, fireplace, large sectional sofa, rug, or symmetry unless it serves the brief.\\n\\n## 1. Establish the brief and survey\\n\\nAsk only questions that can change the next decision; group missing information instead of sending a long questionnaire. Start with daily occupants, activities, existing furniture to retain, room geometry, and budget. If measurements are missing, offer a labelled concept and a concise measurement list.\\n\\nCapture:\\n\\n| Subject | Required information |\\n| --- | --- |\\n| Household | Daily and visiting occupants; children; mobility aids; reach, vision, hearing, balance, transfer, and sensory needs; foreseeable changes |\\n| Activities | Conversation, TV/gaming, reading, music, play, exercise, hobbies, occasional work/dining/sleeping; priorities, frequency, duration, and simultaneous use |\\n| Geometry | Room outline, ceiling/slopes, columns, niches, skirtings, changes in level, actual door and window positions, sill heights, handles, opening arcs, thresholds |\\n| Connections | Entrance, adjacent rooms, kitchen/dining area, balcony/terrace, required exits and escape openings; routes used while carrying items |\\n| Services | Radiators, thermostats, ventilation openings, fireplace/stove and hearth, sockets, switches, data/TV points, ceiling outlets, fixed lighting |\\n| Daylight and sound | Window orientation, glare at typical viewing times, shading, street/neighbour noise, adjacent bedrooms, reflective surfaces |\\n| Products | Retained pieces and exact candidate models; external and usable internal dimensions, weight/load limits, open/deployed sizes, anchoring and ventilation instructions |\\n| Inventory | Books, games, toys, blankets, media devices, controllers, chargers, hobby/work items, guest bedding; quantities, sizes, weights, access frequency |\\n| Delivery and work | Building entrance, stairs, lift, door turns, package dimensions, assembly space, wall permissions, access for installers and later servicing |\\n| Preferences and cost | Must-keep items, comfort trials, style/materials, cleaning needs, budget including delivery/assembly, wiring, mounting, shading, lighting, and disposal |\\n\\nFor each critical fact record `value`, `unit`, `source`, `verification_state`, and uncertainty/tolerance. Use `unknown`, `inferred`, `user_verified`, or `professionally_verified`. A product's nominal width does not prove the available room width.\\n\\nCreate an activity table with `mode`, `users`, `frequency`, `simultaneous_activities`, `required_items`, `deployed_state`, and `reset_steps`. Distinguish daily seats from occasional guest seats. Do not count the same floor area twice for simultaneous activities.\\n\\n## 2. Build a constraint register\\n\\nUse these classes:\\n\\n- `regulatory`: verified, applicable local requirements; record jurisdiction and edition.\\n- `manufacturer`: exact product instructions, clearances, loads, mounting, and intended use.\\n- `site`: verified fixed geometry, services, structural limits, and permissions.\\n- `user_must`: explicit non-negotiable household requirements.\\n- `recommendation`: ergonomic or functional advice, including labelled planning heuristics.\\n- `preference`: negotiable visual or lifestyle choices.\\n\\nThe first four classes are hard constraints. The latter two are soft unless explicitly adopted as a project requirement. Identify safety hazards even when their legal classification is unverified; do not bury them in an aesthetic score. A user preference cannot waive a mandatory requirement.\\n\\nRecord `id`, `class`, `applicability`, `requirement`, `measurement_definition`, `source`, `status`, `affected_items`, and `remedy_or_next_action`. Status is `pass`, `fail`, `unknown`, or `not_applicable` with a reason. Include the room mode in each state-dependent check.\\n\\nResolve conflicting requirements explicitly. Reject hard failures from viable options; separate options needing missing evidence from checked options. Escalate wall loading, fixed electrics, combustion/hearth conditions, or accessibility compliance to the appropriate professional.\\n\\n## 3. Reserve routes and activity zones\\n\\n1. Mark fixed features, required access, opening arcs, and no-go areas before placing furniture.\\n2. Connect the entrance to used seats, storage, adjacent rooms, windows, and balcony along genuinely walkable paths.\\n3. Prefer through-routes outside the conversation group and TV sightline where geometry permits. Show the compromise when a through-room makes this impossible.\\n4. Size the main zone for daily activities; reserve secondary zones only where the brief requires them.\\n5. Test daylight and noisy/quiet activities together. A shelf or curtain can separate views without providing acoustic privacy.\\n6. Locate movable furniture's parking positions. A coffee table moved for a sofa bed must not be parked in a doorway or another required activity zone.\\n\\nPossible strategies include facing/angled seating for conversation, sofa plus movable chairs for mixed use, a media-oriented group, or distinct quiet/active zones. These are alternatives, not mandatory room types.\\n\\n## 4. Fit the seating to the users\\n\\n- Select usable seat width, seat depth, compressed seat height, support, armrests, and ease of standing through user trials, not a universal ideal sofa size.\\n- Count seats that people can actually use together. A chaise, corner junction, ottoman, or armless end is not automatically an equivalent full-time seat.\\n- For conversation, arrange faces so users can hear and see each other without sustained twisting. Try angled chairs or more than one small group before enlarging a distant perimeter arrangement.\\n- Check entry to each seat, knees/feet, standing, transfers, walking-aid parking, swivel arcs, recliner mechanisms, and access to controls.\\n- Position drinks, a book, glasses, and remotes within comfortable reach. A side table can serve a seat better than a large central table.\\n- Treat coffee-table reach space and through-circulation as different things. An easy-to-reach table gap is not a corridor.\\n- Verify sofa-bed deployment, bed-making, access to bedding, night-time routes, and the effort/strength needed to operate it. Do not assume an occasional sofa bed is suitable for regular sleep.\\n\\n## 5. Locate TV, media, and listening equipment\\n\\nOnly apply this step when relevant to the brief.\\n\\n1. Identify primary and secondary viewing seats and measure actual seated eye positions.\\n2. Start with the screen centre near seated eye level, then trial the real posture, screen size, subtitles, and viewing comfort. Do not choose a fixed mounting height from the floor alone (S3, S4).\\n3. Choose viewing distance with screen size, resolution, content, eyesight, and preference. There is no universal distance multiplier suitable for every user (S5).\\n4. Check horizontal viewing positions, head turning, and sightline obstruction from every claimed TV seat. The panel's specified viewing angle is not a comfort guarantee.\\n5. Check reflections from windows and luminaires at typical times. Side-on placement to windows is a candidate, not an automatic glare solution; verify with the actual room and shading.\\n6. Check exact TV foot spacing/depth, furniture load capacity, anti-tip measures, bracket compatibility, wall substrate, and cable strain through mount movement. A wider cabinet alone does not prevent tipping (S3, S8).\\n7. Allow actual device ventilation, connector depth, plug removal, service access, and remote/signal operation behind doors. An opening for cables does not establish adequate cooling.\\n8. Position speakers using product guidance, listening trials, and neighbour considerations. Do not promise acoustic isolation from rugs, curtains, or decorative panels.\\n\\nDo not default to a TV above a fireplace: both viewing posture and verified heat/installation limits must work. An unknown heat condition blocks mounting approval.\\n\\n## 6. Assign contents before choosing storage\\n\\n| Contents | Preferred relationship | Operational check |\\n| --- | --- | --- |\\n| Remotes, glasses, current book | At the relevant seat | Reach while seated; no risky leaning or trailing charger |\\n| Games and controllers | Near play/media area | Access and return without disconnecting equipment or clearing occupied seats |\\n| Toys | Near the agreed play area | Child access where appropriate; anchoring, lid/pinch risks, tidy-up route |\\n| Books and records | Near reading/listening area | Real shelf depth, load limits, adjustable spacing, safe retrieval |\\n| Throws and cushions | Near relaxation seats | Storage opens while people are seated; no need to empty the tabletop |\\n| Guest bedding | Near sofa bed | Retrieve before/during deployment; dry storage and manageable lifting |\\n| Work or hobby equipment | Near its use zone | Fast setup/reset, suitable work surface, secure storage where needed |\\n| Hazardous or fragile items | Controlled location | Access restrictions appropriate to household; height alone is not a lock |\\n\\nUse internal clear dimensions, hinges, drawer travel, shelf loads, and actual object sizes. Locate frequent items for easy retrieval; avoid heavy overhead storage. Compare closed storage for clutter control with open storage for access/display, without sacrificing equipment cooling.\\n\\nStorage should reduce repeated interruptions: getting up, asking someone to move, reaching across a screen, unloading a tabletop to lift a lid, or shifting furniture. Shorter walking distance is useful only when access remains safe and convenient.\\n\\n## 7. Integrate light, environment, and safety\\n\\n- Combine general, task, and ambient/accent lighting with independently usable controls (S2). Reading needs suitable light on the page, not just a bright room.\\n- Check source glare, reflected screen glare, contrast, shadows, and seated/standing sightlines. Place switches where users can reach them on entry and at key seats; retain usable non-app control.\\n- Plan cables and outlets before accepting floating furniture. Do not hide extension leads under rugs or use cable routing that creates trip, pinch, or heat hazards. Fixed electrical alterations require qualified work.\\n- Keep radiator heat flow, thermostat sensing, and ventilation unobstructed (S7). Check exact installation instructions and any cold/damp wall concern; do not invent a universal furniture-to-wall gap.\\n- Treat required furniture/TV anchoring as part of the layout. Verify suitable wall/floor construction and fixings; an unknown wall is not a passed mounting check (S8).\\n- Address climbing access to windows, accessible blind cords, unstable tall furniture, loose rugs, sharp/glass edges, hot surfaces, and moving mechanisms. Prefer cordless window coverings around young children; moving furniture alone does not eliminate cord hazards (S9).\\n- For echo, consider appropriate absorptive furnishings subject to cleaning, trip, and fire constraints. Speech privacy, bass transmission, and sound isolation require different assessment; do not invent decibel improvements.\\n- If sustained work or dining is required, check a suitable table/chair/task-light setup. A sofa with a laptop tray is not evidence of an ergonomic full-time workstation.\\n\\n## 8. Generate and test alternatives\\n\\nOffer two or three meaningfully different layouts when useful, not multiple cosmetic versions. Preserve existing furniture when it meets the brief. Explain when only one credible option fits.\\n\\nFor each option test the required states:\\n\\n- Normal day with the usual seats occupied.\\n- Conversation/guests with occasional seats placed and used.\\n- TV/gaming with sightlines, glare, and controller/device access.\\n- Reading/work/play occurring simultaneously where requested.\\n- Recliners, drawers, doors, swivel chairs, and sofa bed through their full motion and deployed states.\\n- Night-time access, window operation, cleaning, servicing, and eventual furniture removal.\\n\\nMeasure the narrowest clear route between actual obstacles, including occupied feet/knees and deployed parts. Check turning and approach geometry as well as width. Use tolerance-aware dimensions; marginal clearance with unverified geometry remains unknown.\\n\\nUse scaled geometry checks where available and full-size tape/cardboard mock-ups with user trials where practical. Describe exactly what was checked; a language-model review alone is not deterministic collision validation.\\n\\nCompare options by hard failures/unknowns first, then daily comfort, circulation, conversation/media suitability, storage access, reset effort, light/glare, maintenance, cost, and preferences. Let the user set priorities; do not invent authoritative scoring weights.\\n\\nCount furniture moves, lifting, setup time, interruptions, and actual walkable trips for repeated routines. State assumptions and frequency. Do not optimize walking distance at the expense of comfort, inclusion, or required access.\\n\\n## 9. Deliver the proposal\\n\\nProvide:\\n\\n1. Brief, priority activities, assumptions, and missing evidence.\\n2. Recommended layout and alternatives, using labelled walls or a defined coordinate origin; include external furniture dimensions and critical clearances.\\n3. Seating and storage assignments, TV/light relationships, services, and required anchors.\\n4. Mode-by-mode checks, worst pinch points, and the destination of every displaced item.\\n5. Constraint register with failures, unknowns, source type, and next action/owner.\\n6. Budget range, retained/new items, installation/delivery dependencies, and next measurements or trials.\\n7. An explicit readiness level.\\n\\nUse `concept` when dimensions or products are provisional. Use `dimensionally_checked` only for the listed modes and checks supported by verified geometry/product envelopes. Use `ready_for_professional_order_review` only when critical unknowns and hard failures are resolved and delivery/installation evidence is assembled. None of these labels authorizes purchase or certifies regulatory compliance; professional review and user acceptance remain separate.\\n\\n## Counterexample quality checks\\n\\nBefore concluding, reject these false passes:\\n\\n- The closed recliner leaves a wide route, but its footrest blocks the balcony when used.\\n- Six nominal sofa places exist, but two require twisting and one blocks access to another.\\n- A nearby storage ottoman is convenient only when nobody uses it and everything is removed from its lid.\\n- A sofa bed opens only after the coffee table is moved, with no safe parking place for that table.\\n- A low TV cabinet fits, but the television feet overhang or its anti-tip provision is unresolved.\\n- A 1500 mm square is shown somewhere in the room, but the wheelchair user cannot reach a seat, storage, or exit.\\n- A room divider hides a desk but does not make concurrent calls and television acoustically private.\\n- A layout photographs well but covers a radiator, blocks a window handle, or requires a cable across a walking route.\\n\"","export default \"# Living Room Planning Reference\\n\\nOperational guidance for the living-room-planning skill. Defaults: Germany/EU context, millimetres, EUR. Source IDs identify research without requiring bibliography loading.\\n\\nLoad [the optional source catalog](./source-catalog.md) only for source verification, citations/provenance, disputed claims, or maintenance. Do not load it just to resolve IDs in routine planning.\\n\\n## Evidence boundaries\\n\\n- S1-S3 are IKEA consumer guidance on activity zones, lighting, and TV furniture. They support design reasoning, not building-code compliance or endorsement of particular products.\\n- S4-S5 are Sony general support guidance on TV height and distance. They are not exact product installation manuals or universal health limits.\\n- S6 is a secondary summary of DIN 18040-2 living/sleeping-room accessibility. Its index identifies the 2011-09 edition. Verify the current edition, project applicability, state adoption, and any contractual requirements before treating a dimension as mandatory. The full standard was not reviewed.\\n- S7 is German consumer advice supporting unobstructed radiator heat flow and thermostat sensing, not a numerical clearance standard.\\n- S8-S9 are US CPSC safety guidance on tip-over and window-covering cords. The hazard principles are relevant; US legal provisions are not German/EU requirements.\\n- The workflow, check catalog, and examples below are planning synthesis. A source supports only the stated claim, not every adjacent check. Project-specific manuals, structural conditions, and local requirements still need verification.\\n\\n## Dimensions and measurement definitions\\n\\nThe heuristic rows below are deliberately provisional starting points for mock-ups. They are not sourced standards, minimum legal dimensions, accessibility specifications, or guarantees of comfort. Override them for actual users, geometry, products, and applicable requirements.\\n\\n| Topic | Starting guidance | Measurement and qualification |\\n| --- | --- | --- |\\n| Main walking route | Explore 900-1200 mm clear width | Skill heuristic for initial ordinary residential layouts; measure narrowest obstacle-to-obstacle gap in the relevant occupied mode. Passing, carrying, mobility aids, turns, or applicable rules may need more. This does not certify an escape route. |\\n| Seat to coffee table | Try 400-500 mm | Skill heuristic between seat front and table edge for reach and leg space; trial actual posture. Not a through-route or wheelchair-transfer clearance. Side tables or no central table may be better. |\\n| Conversation spacing | Trial roughly 1500-2500 mm between seated head positions | Skill heuristic for a small conversational group, not between sofa backs. Hearing, room noise, furniture angles, and personal space govern the result. |\\n| Turning/movement area | S6 reports 1200 x 1200 mm; 1500 x 1500 mm for unrestricted wheelchair use | Secondary DIN summary for relevant living/sleeping rooms. Distinguish general barrier-free from the R category; verify applicability and full provisions. A free square alone does not prove accessible use. |\\n| Space along/in front of furniture | S6 reports 900 mm depth; 1500 mm for unrestricted wheelchair use | Secondary summary; not a universal route-width substitute. Verify the actual approach, transfer, furniture function, and applicable category. |\\n| Seat dimensions | User- and product-specific | Measure usable width/depth and compressed seat height; trial support, feet placement, standing, and transfers. No fixed ideal dimensions specified here. |\\n| Screen centre height | Start near seated eye level (S3, S4) | Finished floor to centre of visible screen; use actual primary viewers and posture. Reclined viewing may require a different tested arrangement. |\\n| Viewing distance | No mandatory multiplier (S5) | Eye position to screen; note size, resolution, content, subtitles, and preference. Distinguish this from wall-to-sofa distance. |\\n| TV support/mount | Exact product dimensions and limits | Check TV feet, support depth, load rating, anchors, wall construction, bracket specification, and full movement envelope. Screen diagonal alone is insufficient. |\\n| Sofa bed/recliner | Exact fully deployed dimensions and motion | Include mechanisms, rear travel, user operation/standing, feet, bedding access, and displaced furniture. No generic clearance is approved. |\\n| Cabinet/device clearances | Exact manuals and usable internal space | Include plugs, cable bend space, drawer/door travel, ventilation, load capacity, and service removal. |\\n| Radiators, stove/hearth, cold walls | Site and product assessment | No universal gap. Keep heat flow and controls usable (S7); obtain verified combustion clearances and investigate moisture concerns. |\\n| Lighting | Activity-specific placement and controls (S2) | No mandatory domestic lux or colour-temperature target is established by this research. Agree needs; use photometric data/measurement for quantified claims. |\\n\\nOverlap of movement areas may be permissible in an applicable accessibility design, but do not overlap fixed obstacles or simultaneous occupied/deployed functions. Record exactly which states can share space and validate the applicable provisions.\\n\\n## Practical check catalog\\n\\nThese are check categories, not a claim that all checks apply or are legally required. Instantiate the relevant checks with the constraint class, measurement, mode, evidence, status, and next action. Preserve `unknown` where evidence is missing.\\n\\n| ID | Check | Failure or unresolved condition to expose |\\n| --- | --- | --- |\\n| GEO-01 | Survey and tolerances | Furniture accepted against estimated wall dimensions, unmeasured skirtings, slopes, or out-of-square corners |\\n| GEO-02 | Openings | Door/window arcs, handles, curtains, thresholds, or escape openings obstructed |\\n| GEO-03 | Route continuity | A nominal clear width exists locally but the full entrance-seat-storage-exit route fails |\\n| GEO-04 | Required access | Balcony, services, ventilation, cleaning, or emergency access sacrificed to furniture |\\n| USE-01 | Activity brief | Maximum seating or TV dominance chosen without household priorities |\\n| USE-02 | Simultaneous use | Work, play, conversation, or dining claim the same space at the same time |\\n| USE-03 | Real seating capacity | Corner/chaise/occasional places counted as equivalent comfortable daily seats |\\n| USE-04 | Seated comfort | Unsupported feet, excessive seat depth, difficult standing, or inaccessible controls |\\n| USE-05 | Conversation | Sustained twisting, blocked faces, distance/noise incompatible with hearing needs |\\n| USE-06 | Reach and standing | Table placement forces leaning or removes space for feet, standing, or transfers |\\n| FIT-01 | Actual external envelope | Product footprint excludes arms, legs, handles, overhang, or cables |\\n| FIT-02 | Motion and deployment | Recliner, swivel chair, drawer, or sofa-bed travel collides with people or objects |\\n| FIT-03 | Reset and parking | Displaced tables, cushions, bedding, or guest seats have no safe destination |\\n| FIT-04 | Delivery and assembly | Package or assembled piece cannot negotiate entry, stairs, lift, or room turns |\\n| STO-01 | Contents and loads | Object sizes/weights exceed usable shelf/drawer dimensions or ratings |\\n| STO-02 | Retrieval | Frequent items require moving occupants, unloading a lid, or crossing active viewing |\\n| STO-03 | Safe reach | Heavy overhead items, climbing, insecure hazardous contents, or inaccessible essentials |\\n| MED-01 | TV eye geometry | Screen height/distance/angle chosen without the primary viewers and actual screen |\\n| MED-02 | All claimed viewing seats | Obstructed picture, neck turning, subtitle difficulty, or unsuitable off-axis image |\\n| MED-03 | Glare | Window or luminaire reflections untested at relevant times |\\n| MED-04 | TV support and mounting | Feet overhang, inadequate loads, incompatible bracket, unknown substrate or fixing |\\n| MED-05 | Device operation | Cooling, cable/plug space, service removal, or remote/signal access missing |\\n| LGT-01 | General/task/ambient light | One source cannot serve agreed activities or leaves routes inadequately visible |\\n| LGT-02 | Control and glare | Unreachable controls, app-only dependency, glare or harsh contrast at a used seat |\\n| ENV-01 | Heating and ventilation | Sofa, cabinetry, or curtains obstruct radiator flow, thermostat sensing, or vents |\\n| ENV-02 | Moisture and finishes | Cold/damp wall concern ignored; finishes/rugs unsuitable for actual conditions |\\n| ENV-03 | Acoustic compatibility | Visual screen treated as sound isolation; no plan for concurrent noisy/quiet use |\\n| ACC-01 | Accessible movement | Applicable clear areas, approaches, turning, and route continuity not verified |\\n| ACC-02 | Inclusive use | Seat transfer, aid parking, reach, contrast, hearing, or control needs not met |\\n| SAFE-01 | Stability and anchoring | Furniture, TV, or room divider lacks required stability/anchors and verified substrate |\\n| SAFE-02 | Child/window safety | Climbing route, accessible blind cord, pinch/lid risk, or hazardous contents unresolved |\\n| SAFE-03 | Trips and impact | Loose rug edges, trailing leads, low unseen obstacles, sharp/glass edges on routes |\\n| SAFE-04 | Heat and combustion | Unverified stove/hearth/TV relationship, combustible furnishings, or obstructed provisions |\\n| SRV-01 | Power and data | Unsafe extension routing, pinched leads, insufficient outlets, or unapproved fixed work |\\n| ORD-01 | Ordering evidence | Product variants, prices, measurements, permissions, or installation checks unresolved |\\n| ORD-02 | Readiness claim | Concept labelled installation-ready, unverified checks passed, or approval implied |\\n\\n## Worked examples\\n\\nAll dimensions, timings, and counts in these examples are invented teaching inputs, not recommended product clearances or measured performance.\\n\\n### 1. Closed-state route that fails when used\\n\\nA straight passage between a closed recliner front and a cabinet front is 1250 mm. In the same cross-section, the footrest extends 550 mm into the passage and an opposing drawer extends 400 mm.\\n\\n```text\\nremaining_gap_mm = 1250 - 550 - 400 = 300\\n```\\n\\nThe positive gap does not imply a usable route. Feet, the person retrieving contents, and approach/turning space have not even been included. It fails an agreed 900 mm project route target. If this is the only access to an exit, rejecting the simultaneous state alone is not a sufficient remedy; relocate or resize furniture so required access remains usable in intended operation.\\n\\nThis subtraction is valid only for aligned projections at that cross-section. Offset furniture, curves, swing arcs, and room turns require actual geometry checks.\\n\\n### 2. Sofa-bed mode includes its displaced furniture\\n\\nA room has 3500 mm clear depth on the deployment axis. The bed's verified overall deployed depth is 2200 mm and the opposite cabinet is 400 mm deep.\\n\\n```text\\nnominal_foot_gap_mm = 3500 - 2200 - 400 = 900\\n```\\n\\nThis is not yet a pass: check doors, drawer access, operator standing, side approach, night-time route, and tolerances. A 600 mm deep coffee table parked in that gap leaves only 300 mm on the assumed aligned section. Find a separate safe parking position or change the furniture plan. Do not claim the mattress length is the deployed furniture depth.\\n\\n### 3. Viewing geometry, not a prescribed distance\\n\\nFor a centred, perpendicular viewer and a 16:9 screen:\\n\\n```text\\ndiagonal_mm = diagonal_inches * 25.4\\nscreen_width_mm = diagonal_mm * 16 / sqrt(16^2 + 9^2)\\nhorizontal_angle_degrees = 2 * atan(screen_width_mm / (2 * eye_distance_mm)) * 180 / pi\\n```\\n\\nA 65-inch screen is about 1439 mm wide. At a 2500 mm perpendicular eye-to-screen distance it spans about 32.1 degrees horizontally. This describes the geometry; it is not a recommended angle, a safety threshold, a panel off-axis specification, or a comfort guarantee. Trial content, subtitle readability, eyesight, and actual seated posture (S4, S5).\\n\\n### 4. Storage reduces reset effort, not just distance\\n\\nSuppose daily hobby setup/reset requires moving a table twice and clearing an ottoman lid twice, each assumed to take 20 seconds. A nearby accessible drawer avoids those four actions without creating another obstruction.\\n\\n```text\\navoided_actions_per_day = 2 + 2 = 4\\nillustrative_time_saved_seconds_per_day = 4 * 20 = 80\\n```\\n\\nThese are user-supplied or trial assumptions to verify, not a product claim. Also compare lifting effort, comfort, actual walkable trips, and whether anyone must move. Do not choose unsafe reachable storage to save time.\\n\\n## Maintenance and limits\\n\\nKeep numerical heuristics labelled whenever repeated in a proposal. If a source changes, update the affected operational claim as well as the optional catalog. Record exact manual editions and project evidence separately from this generic research.\\n\\nNo exact project product manuals, structural calculations, full accessibility standard, local fire/escape provisions, quantitative acoustic assessment, or photometric design were reviewed to produce this generic skill. Obtain them when the project requires them. A checklist review does not replace installation approval.\\n\"","export default \"# Living Room Planning Source Catalog\\n\\nOptional research/provenance file. Do not load for routine planning or solely to expand a source ID. Load when the user asks for citations, a claim needs verification, sources conflict, or the skill is being maintained.\\n\\nResearch reviewed: 2026-10-09. Scope: generic domestic living-room planning with Germany/EU defaults. Summaries are original planning notes, not reproduced articles. The operational rules and qualifications are in [the planning reference](./planning-reference.md); the workflow is in [the skill](../SKILL.md).\\n\\n## S1 - IKEA Germany: activity zones and reset storage\\n\\n- Source: [So gestaltest du drei Arbeitsbereiche in einem Raum](https://www.ikea.com/de/de/rooms/living-room/how-to/wohnzimmer-aufteilen-pubd020bb20/).\\n- Type: retailer guidance; German market.\\n- Retrieved support: separate work/relaxation areas, visual screening, movable storage, keeping work items together for easy reset.\\n- Applied: activity and simultaneous-use brief, nearby storage, explicit setup/reset actions.\\n- Limits: product inspiration, not dimensional or acoustic compliance evidence. Do not generalize the sofa/laptop examples into suitable full-time workstation ergonomics. Screens do not establish speech privacy or sound isolation.\\n\\n## S2 - IKEA Germany: living-room lighting\\n\\n- Source: [Bestmoegliche Nutzung deiner Wohnzimmerbeleuchtung](https://www.ikea.com/de/de/rooms/living-room/how-to/wohnzimmerbeleuchtung-ideen-pub75352e80/).\\n- Type: retailer guidance; German market.\\n- Retrieved support: combine general, task, and mood lighting; support concentrated tasks with appropriate surrounding light; cabinet lighting and adjustable controls.\\n- Applied: activity-specific lighting, contrast/glare review, multiple controllable sources.\\n- Limits: does not establish mandatory domestic illuminance, colour temperature, or a required number of lamps. Battery-powered lighting still needs energy and charging; the page's casual wording is not an electrical claim.\\n\\n## S3 - IKEA Germany: TV furniture\\n\\n- Source: [So waehlst du eine TV-Bank, die bestens in dein Zuhause passt](https://www.ikea.com/de/de/rooms/living-room/how-to/stilvolle-tv-baenke-pub8de44a60/).\\n- Type: retailer guidance; German market.\\n- Retrieved support: screen centre at seated eye height; open/closed storage choices; cable openings; suggests cabinet wider than screen.\\n- Applied: seated-eye planning, storage configuration, cable access.\\n- Limits: furniture wider than the screen does not establish stability. Check feet, depth, loads, anchors, and exact manuals independently. Product range dimensions/prices are not universal design rules and are not embedded in the skill.\\n\\n## S4 - Sony: wall-mounted TV height\\n\\n- Source: [What is the recommended height when mounting the TV on a wall?](https://www.sony.com/electronics/support/articles/00026357).\\n- Type: manufacturer general support; US site. Retrieved page displayed article ID 00026358 and modification date 2019-08-19 despite the requested URL.\\n- Retrieved support: height depends on preference and seating; generally centre the screen at viewers' eye level; model-specific off-axis image characteristics need checking.\\n- Applied: actual seated eye measurements, posture trials, per-seat sightline checks.\\n- Limits: not a fixed floor-height rule, comfort guarantee, bracket specification, or installation manual. Panel viewing-angle specifications differ from the visual angle a screen occupies.\\n\\n## S5 - Sony: viewing distance qualifications\\n\\n- Source: [Recommended viewing distance for watching TV](https://www.sony.com/electronics/support/articles/00008601).\\n- Type: manufacturer general support; US site. Retrieved page displayed article ID 00008602 and modification date 2025-01-17.\\n- Retrieved support: distance depends on screen size/resolution, content, surroundings, and the viewer; adapt reference distances to preference and room layout.\\n- Applied: avoid a universal screen-diagonal multiplier; trial the intended screen and content.\\n- Limits: the fetched text did not expose the numeric content inside the 4K/HD/SD sections. No numerical distance recommendation is attributed to this source. The reference's screen-angle example is elementary geometry, not a Sony recommendation.\\n\\n## S6 - nullbarriere: living/sleeping-room accessibility\\n\\n- Source: [DIN 18040-2 Wohnraum, Schlafraum](https://nullbarriere.de/din18040-2-wohnraum-schlafraum.htm).\\n- Context: [DIN 18040-2 index](https://nullbarriere.de/din18040-2.htm), identifying edition 2011-09 and distinguishing ordinary barrier-free use from unrestricted wheelchair use (R).\\n- Type: German specialist secondary standard summary, not the normative text.\\n- Retrieved support: turning/movement areas of 1200 x 1200 mm and 1500 x 1500 mm for wheelchair use; depths along/in front of furniture of 900 mm and 1500 mm respectively; flexibility and functional access matter.\\n- Applied: qualified accessibility prompts and provisional checks; do not import ordinary coffee-table gaps into accessible approaches.\\n- Limits: current edition, legal adoption by federal state, contractual applicability, exact measurement provisions, and exceptions need verification from authoritative project sources. Full standard text was not reviewed. Bedroom examples and unrelated dimensions are not generalized into living-room rules.\\n\\n## S7 - Verbraucherzentrale: keep radiator heat flow clear\\n\\n- Source: [Heizung optimieren und Heizkosten sparen](https://www.verbraucherzentrale.de/wissen/energie/heizen-und-warmwasser/heizung-optimieren-und-heizkosten-sparen-30096).\\n- Type: German consumer advice; retrieved article dated 2026-10-08.\\n- Retrieved support: long curtains, furniture, and covers in front of radiators can trap heat, impair room warming, and distort thermostat sensing; keep radiators unobstructed.\\n- Applied: furniture/shading layout must preserve heat flow and usable controls.\\n- Limits: no universal clearance is inferred. Heating-system modification, fireplace clearances, and cold-wall moisture assessment require their own evidence. Unrelated legislation and numerical savings on this page are not used.\\n\\n## S8 - US CPSC: furniture and TV tip-over prevention\\n\\n- Source: [Anchor It!](https://www.anchorit.gov/).\\n- Type: US government consumer-safety campaign.\\n- Retrieved support: anchor susceptible furniture and televisions using suitable anchoring equipment; follow installation instructions.\\n- Applied: include anchoring in layout/installation planning, account for wall construction, and do not assume a low or visually stable unit needs no assessment.\\n- Limits: US regulations and typical wall construction are not German/EU requirements. Exact product manuals, appropriate substrate/fixings, and professional review control project installation. This skill does not reproduce a generic DIY anchoring procedure.\\n\\n## S9 - US CPSC: window-covering cords\\n\\n- Source: [Window Covering Cords](https://www.cpsc.gov/Safety-Education/Safety-Education-Centers/Window-Covering) (retrieved canonical destination: [Go Cordless](https://www.cpsc.gov/gocordless)).\\n- Type: US government consumer-safety guidance.\\n- Retrieved support: cordless coverings are the safest choice around young children; keep furniture that enables access away from windows/cords; mitigation of existing cords does not eliminate the hazard.\\n- Applied: check climbing routes and reachable cords when positioning sofas, shelves, and play areas; prefer cordless coverings.\\n- Limits: not a claim about current German/EU product law or a complete child-safety audit. No US retrofit dimensions or regulatory requirements are transposed into the skill.\\n\\n## Research gaps and update policy\\n\\n- The initially attempted living-room accessibility URL was invalid; S6 records the valid page found through the index, not the failed address.\\n- An attempted licht.de living-room page yielded no meaningful extract and is not used as evidence.\\n- The ordinary route, coffee-table, and conversation spacing ranges are explicitly labelled skill heuristics, not research-backed minima.\\n- Acoustic cautions and delivery/open-state checks are planning synthesis, not validated acoustic performance or model-specific installation data.\\n- No exact project manuals, current full DIN standard, local fire/escape rules, engineering calculations, or quantitative lighting/acoustic study were inspected.\\n- For updates, recheck the relevant article and its scope, then update the operational claim and its qualifications. Never replace a missing source with an unqualified mandatory-sounding number.\\n\"","/** A frontmatter field as YAML reads it: a scalar, or a nested field (metadata) as an object of scalars. */\nexport type FrontmatterValue = string | Record<string, string>;\n\n/** A planning skill in the Agent Skills format: a directory with SKILL.md and supporting files. */\nexport interface Skill {\n name: string;\n description: string;\n frontmatter: Record<string, FrontmatterValue>;\n /** The text of every file of the skill by its path in the skill's directory. */\n texts: Record<string, string>;\n files: string[];\n /** The supporting files SKILL.md asks to read before planning, served with it. */\n required: string[];\n}\n\nexport const SKILL_FILE = 'SKILL.md';\n\n// The supporting files a skill asks to read before planning, by skill name.\nconst REQUIRED_FILES: Record<string, string[]> = {\n 'kitchen-planning': ['references/planning-reference.md'],\n 'kitchen-planning-fr': ['references/planning-reference.md'],\n 'living-room-planning': ['references/planning-reference.md'],\n};\n\n/** Whether a file argument of get-skill, with or without a leading ./, names SKILL.md. */\nexport const isSkillFile = (file?: string): boolean =>\n file === undefined || file.replace(/^(\\.\\/)+/, '') === SKILL_FILE;\n\n// The files of the skills directory, bundled as text, by their path below it.\nconst SKILL_FILES = Object.fromEntries(\n Object.entries(\n import.meta.glob<string>('./skills/**/*', {\n query: '?raw',\n import: 'default',\n eager: true,\n }),\n ).map(([path, text]) => [path.replace(/^\\.\\/skills\\//, ''), text]),\n);\n\nconst FRONTMATTER = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n/;\nconst FIELD = /^([A-Za-z][\\w-]*):\\s*(.*)$/;\nconst NESTED_FIELD = /^\\s+([A-Za-z][\\w-]*):\\s*(.*)$/;\nconst BLOCK_SCALAR = /^([|>])([+-]?)$/;\n\ninterface Field {\n value: string;\n lines: string[];\n}\n\nconst unquoted = (value: string): string =>\n /^'.*'$|^\".*\"$/.test(value) ? value.slice(1, -1) : value;\n\nconst folded = (lines: string[]): string =>\n lines\n .join('\\n')\n .split(/\\n\\s*\\n/)\n .map((paragraph) => paragraph.split('\\n').join(' '))\n .join('\\n');\n\n// The YAML of Agent Skills frontmatter: a plain, quoted, multi-line or block\n// scalar per field, a block scalar with its chomping (clip, - strip, + keep),\n// and a nested field (metadata) as an object of scalars.\nconst valueOf = ({ value, lines }: Field): FrontmatterValue => {\n const content = lines.filter((line) => line.trim());\n const block = BLOCK_SCALAR.exec(value);\n if (block) {\n const [, style, chomping] = block;\n const indent = Math.min(\n ...content.map((line) => line.length - line.trimStart().length),\n );\n const body = lines.map((line) => line.slice(indent));\n let end = body.length;\n while (end > 0 && !body[end - 1].trim()) {\n end--;\n }\n const core = body.slice(0, end);\n const text = style === '|' ? core.join('\\n') : folded(core);\n if (chomping === '-') {\n return text;\n }\n return text + '\\n'.repeat(chomping === '+' ? body.length - end + 1 : 1);\n }\n const nested = content.map((line) => NESTED_FIELD.exec(line));\n if (\n !value &&\n nested.length > 0 &&\n nested.every((field): field is RegExpExecArray => field !== null)\n ) {\n return Object.fromEntries(\n nested.map(([, key, nestedValue]) => [key, unquoted(nestedValue.trim())]),\n );\n }\n return unquoted(\n [value, ...content.map((line) => line.trim())].join(' ').trim(),\n );\n};\n\nconst frontmatterOf = (\n text: string,\n file: string,\n): Record<string, FrontmatterValue> => {\n const block = FRONTMATTER.exec(text)?.[1];\n if (block === undefined) {\n throw new Error(`${file}: no frontmatter`);\n }\n const fields: Record<string, Field> = {};\n let current: Field | undefined;\n for (const line of block.split(/\\r?\\n/)) {\n const field = FIELD.exec(line);\n if (field) {\n current = { value: field[2].trim(), lines: [] };\n fields[field[1]] = current;\n } else if (current && /^(\\s|$)/.test(line)) {\n current.lines.push(line);\n } else if (!line.startsWith('#')) {\n throw new Error(`${file}: the frontmatter line \"${line}\" is not a field`);\n }\n }\n return Object.fromEntries(\n Object.entries(fields).map(([key, field]) => [key, valueOf(field)]),\n );\n};\n\n/**\n * Reads every skill of the skills directory, given as the text of each file by\n * its path below the directory, with the files each skill requires before\n * planning; a broken skill or a required file the skill does not have fails the\n * load and names its file.\n */\nexport const loadSkills = (\n files: Record<string, string>,\n required: Record<string, string[]> = REQUIRED_FILES,\n): Skill[] => {\n const directories = new Map<string, Record<string, string>>();\n for (const [path, text] of Object.entries(files)) {\n const [directory, ...rest] = path.split('/');\n if (rest.length > 0) {\n directories.set(directory, {\n ...directories.get(directory),\n [rest.join('/')]: text,\n });\n }\n }\n return [...directories]\n .map(([directory, texts]) => {\n const file = `skills/${directory}/${SKILL_FILE}`;\n if (texts[SKILL_FILE] === undefined) {\n throw new Error(`${file}: no such file`);\n }\n const frontmatter = frontmatterOf(texts[SKILL_FILE], file);\n const { name, description } = frontmatter;\n if (name !== directory) {\n throw new Error(\n `${file}: the name \"${name}\" differs from its directory \"${directory}\"`,\n );\n }\n if (typeof description !== 'string' || !description.trim()) {\n throw new Error(`${file}: no description`);\n }\n const supporting = Object.keys(texts)\n .filter((path) => path !== SKILL_FILE)\n .sort();\n const requiredFiles = required[directory] ?? [];\n for (const path of requiredFiles) {\n if (!supporting.includes(path)) {\n throw new Error(\n `${file}: the required file \"${path}\" is no file of the skill`,\n );\n }\n }\n return {\n name,\n description: description.trim(),\n frontmatter,\n texts,\n files: [SKILL_FILE, ...supporting],\n required: requiredFiles,\n };\n })\n .sort((a, b) => a.name.localeCompare(b.name));\n};\n\n/** One line per skill: its name and its description. */\nexport const skillIndex = (skills: Skill[]): string =>\n skills.map((skill) => `- ${skill.name}: ${skill.description}`).join('\\n');\n\nconst skillFileText = (skill: Skill, path: string): string =>\n skill.texts[path].replace(/\\r\\n/g, '\\n');\n\nconst skillNamed = (skills: Skill[], name: string): Skill => {\n const skill = skills.find((candidate) => candidate.name === name);\n if (!skill) {\n throw new Error(\n `Unknown skill \"${name}\" - the skills are ${skills.map((candidate) => candidate.name).join(', ')}`,\n );\n }\n return skill;\n};\n\n/** A file of a skill by its path; only a file of the skill's list is read. */\nexport const readSkillFile = (\n skills: Skill[],\n name: string,\n file: string = SKILL_FILE,\n): string => {\n const skill = skillNamed(skills, name);\n const path = file.replace(/^(\\.\\/)+/, '');\n if (!skill.files.includes(path)) {\n throw new Error(\n `Unknown file \"${file}\" of the skill ${name} - its files are ${skill.files.join(', ')}`,\n );\n }\n return skillFileText(skill, path);\n};\n\nconst includedFile = (skill: Skill, path: string): string =>\n `\\n---\\n\\nThe file ${path} of this skill, included here:\\n\\n${skillFileText(skill, path)}`;\n\n/**\n * SKILL.md of a skill followed by the supporting files it asks to read before\n * planning, each under a line that names it.\n */\nexport const readSkill = (skills: Skill[], name: string): string => {\n const skill = skillNamed(skills, name);\n return skill.required.reduce(\n (text, path) => `${text.replace(/\\n*$/, '\\n')}${includedFile(skill, path)}`,\n skillFileText(skill, SKILL_FILE),\n );\n};\n\nexport const skills = loadSkills(SKILL_FILES);\n","// The plan context in the words of the agent: wall names, room corners, the\n// wall of a door or a window, and the catalog's short descriptions.\n\nimport { wallFaces } from '../hi-plan-space';\n\ntype WallSide = 'left' | 'right' | 'top' | 'bottom';\n\ninterface DerivedWall {\n index: number;\n side: WallSide;\n start: [number, number, number];\n end: [number, number, number];\n lengthMm: number;\n type?: string;\n heightMm?: number;\n thicknessMm?: number;\n facingRotationY: number;\n}\n\n// + 0 turns IEEE -0 into +0 so serialized values never show -0\nconst round2 = (value: number): number => Math.round(value * 100) / 100 + 0;\n\nconst POINT_EPSILON_MM = 1;\n\nconst samePoint = (a: [number, number], b: [number, number]): boolean =>\n Math.hypot(a[0] - b[0], a[1] - b[1]) < POINT_EPSILON_MM;\n\nconst unitDirection = (\n from: [number, number],\n to: [number, number],\n): [number, number] | undefined => {\n const length = Math.hypot(to[0] - from[0], to[1] - from[1]);\n return length < 1e-6\n ? undefined\n : [(to[0] - from[0]) / length, (to[1] - from[1]) / length];\n};\n\nconst projectOntoAxis = (\n polygon: Array<[number, number]>,\n [axisX, axisZ]: [number, number],\n): [number, number] => {\n let minimum = Number.POSITIVE_INFINITY;\n let maximum = Number.NEGATIVE_INFINITY;\n for (const [x, z] of polygon) {\n const projection = x * axisX + z * axisZ;\n minimum = Math.min(minimum, projection);\n maximum = Math.max(maximum, projection);\n }\n return [minimum, maximum];\n};\n\nconst wallFloorPoints = ({\n start,\n end,\n}: DerivedWall): [[number, number], [number, number]] => [\n [start[0], start[2]],\n [end[0], end[2]],\n];\n\nconst WALL_NAMES: Record<WallSide, string> = {\n top: 'back wall',\n bottom: 'front wall',\n left: 'left wall',\n right: 'right wall',\n};\n\n// The name of a wall in the words of the user: back and front for the top and\n// the bottom of the top-view image.\nexport const wallName = (side: WallSide): string =>\n WALL_NAMES[side] ?? `${side} wall`;\n\nexport interface RoomCorner {\n name: string;\n point: [number, number, number];\n posRotationY: number;\n}\n\n// The corners of a room: where a wall or an opening ends and the next starts\n// at an angle that turns into the room - towards the side the ending one\n// faces, as the room lies left of the contour (D61). A partition and the inner\n// corner of an L-shaped room turn away from it and give none. The name is\n// back/front plus left/right, and posRotationY is the facingRotationY of the\n// wall that ends in the corner - the rotation of a corner kitchen there, for\n// both hands of corner article (D13, D33, D83).\nexport const roomCorners = (walls: DerivedWall[]): RoomCorner[] => {\n const corners: RoomCorner[] = [];\n for (const ending of walls) {\n const [endingStart, endPoint] = wallFloorPoints(ending);\n const along = unitDirection(endingStart, endPoint);\n for (const starting of walls) {\n const [startPoint, startingEnd] = wallFloorPoints(starting);\n const next = unitDirection(startPoint, startingEnd);\n if (\n starting === ending ||\n !samePoint(endPoint, startPoint) ||\n !along ||\n !next ||\n Math.abs(along[0] * next[0] + along[1] * next[1]) > 0.999 ||\n along[1] * next[0] - along[0] * next[1] <= 0\n ) {\n continue;\n }\n const sides = [ending.side, starting.side];\n const depth = sides.find((side) => side === 'top' || side === 'bottom');\n const hand = sides.find((side) => side === 'left' || side === 'right');\n if (!depth || !hand) {\n continue;\n }\n corners.push({\n name: `${depth === 'top' ? 'back' : 'front'} ${hand}`,\n point: [endPoint[0], 0, endPoint[1]],\n posRotationY: ending.facingRotationY,\n });\n }\n }\n return corners;\n};\n\n// The extent of room points along a wall, measured from the wall's start.\nexport const spanAlongWall = (\n wall: DerivedWall,\n points: Array<[number, number]>,\n): [number, number] => {\n const [[startX, startZ], [endX, endZ]] = wallFloorPoints(wall);\n const length = Math.hypot(endX - startX, endZ - startZ);\n const along: [number, number] = [\n (endX - startX) / length,\n (endZ - startZ) / length,\n ];\n return projectOntoAxis(\n points.map(([x, z]) => [x - startX, z - startZ]),\n along,\n );\n};\n\nexport interface WallOfOpening {\n roomIndex: number;\n wall: number;\n fromEndMm: [number, number];\n}\n\n// The wall a door or a window lies in: the wall whose line its floor outline\n// touches - within the wall's thickness - over the longest stretch. The span\n// is measured from the wall's end, like the d of a placement.\nexport const wallOfOpening = (\n outline: Array<[number, number]>,\n rooms: Array<{ walls?: DerivedWall[] }>,\n): WallOfOpening | undefined => {\n let found: WallOfOpening | undefined;\n let longestOverlap = POINT_EPSILON_MM;\n rooms.forEach((room, roomIndex) => {\n for (const wall of room.walls ?? []) {\n const [[startX, startZ], [endX, endZ]] = wallFloorPoints(wall);\n const along = unitDirection([startX, startZ], [endX, endZ]);\n if (!along) {\n continue;\n }\n const distanceToLine = Math.min(\n ...outline.map(([x, z]) =>\n Math.abs((x - startX) * along[1] - (z - startZ) * along[0]),\n ),\n );\n if (distanceToLine > (wall.thicknessMm ?? 0) + POINT_EPSILON_MM) {\n continue;\n }\n const length = Math.hypot(endX - startX, endZ - startZ);\n const [from, to] = spanAlongWall(wall, outline);\n const overlap = Math.min(to, length) - Math.max(from, 0);\n if (overlap > longestOverlap) {\n longestOverlap = overlap;\n found = {\n roomIndex,\n wall: wall.index,\n fromEndMm: [\n round2(length - Math.min(to, length)),\n round2(length - Math.max(from, 0)),\n ],\n };\n }\n }\n });\n return found;\n};\n\n// A sectioned article description - FUNCTION:, PURPOSE:, …,\n// AI_SELECTION_HINT: - shortened to what the article is and when to pick it.\n// A section's text stands on the line of its name or on the next line.\nconst SHORT_DESCRIPTION_SECTIONS = ['FUNCTION', 'AI_SELECTION_HINT'];\nconst shortDescription = (desc: unknown): unknown => {\n if (typeof desc !== 'string') {\n return desc;\n }\n const lines = SHORT_DESCRIPTION_SECTIONS.map((section) =>\n desc\n .match(new RegExp(`(?:^|\\\\n)${section}:[ \\\\t]*\\\\n?([^\\\\n]+)`))?.[1]\n ?.trim(),\n ).filter((line) => line);\n return lines.length > 0 ? lines.join(' ') : desc;\n};\n\nconst hasSelections = (attribute: any): boolean =>\n Array.isArray(attribute?.selections) && attribute.selections.length > 0;\n\n// The same values of one library list alike, their catalog images aside.\nconst selectionsKey = (attribute: any): string =>\n `${attribute.libraryId}\\n${JSON.stringify(attribute.selections, (field, value) => (field === 'imageUrl' ? undefined : value))}`;\n\n// A value list several attributes share is listed once: the later attributes\n// name the attribute that lists it.\nexport const withSharedSelectionsOnce = (attributes: any[]): any[] => {\n const listedBy = new Map<string, string>();\n return attributes.map((attribute) => {\n if (!hasSelections(attribute)) {\n return attribute;\n }\n const key = selectionsKey(attribute);\n const listing = listedBy.get(key);\n if (listing === undefined) {\n listedBy.set(key, attribute.id);\n return attribute;\n }\n const shared = { ...attribute, sameSelectionsAs: listing };\n delete shared.selections;\n return shared;\n });\n};\n\n// Whether the agent sees and sets an attribute. The element type is what the\n// article is - another type is another article. The library does not mark such\n// attributes yet, so the element type is named here.\nexport const isAgentFacingAttribute = (attributeId: unknown): boolean =>\n attributeId !== 'mod_TypeElement';\n\n// A list of attributes or of attribute ids without those the agent does not see.\nconst agentFacingEntries = (entries: unknown): unknown =>\n Array.isArray(entries)\n ? entries.filter((entry) =>\n isAgentFacingAttribute(typeof entry === 'string' ? entry : entry?.id),\n )\n : entries;\n\nconst withAgentFacingAttributes = <T extends { attributes?: unknown }>(\n item: T,\n): T =>\n Array.isArray(item?.attributes)\n ? { ...item, attributes: agentFacingEntries(item.attributes) }\n : item;\n\n// The interior fittings without the attributes the agent does not see.\nexport const agentFacingFittings = (fittings: unknown): unknown =>\n Array.isArray(fittings) ? fittings.map(withAgentFacingAttributes) : fittings;\n\n// The groups without the attributes the agent does not see: those of the\n// group, its roots, their sub modules and the interior fittings.\nexport const agentFacingGroups = (groups: any): any =>\n Array.isArray(groups)\n ? groups.map((group) => ({\n ...withAgentFacingAttributes(group),\n ...(Array.isArray(group?.roots) && {\n roots: group.roots.map((root: any) => ({\n ...withAgentFacingAttributes(root),\n ...(Array.isArray(root?.subModules) && {\n subModules: root.subModules.map(withAgentFacingAttributes),\n }),\n })),\n }),\n ...(Array.isArray(group?.interiorFittings) && {\n interiorFittings: agentFacingFittings(group.interiorFittings),\n }),\n }))\n : groups;\n\n// The compacted master data without the attributes the agent does not see:\n// the attributes, the ids the modules carry and the group settings.\nexport const agentFacingMasterData = (masterData: any): any =>\n masterData !== null && typeof masterData === 'object'\n ? Object.fromEntries(\n Object.entries(masterData as Record<string, any>).map(\n ([libraryId, library]) => [\n libraryId,\n {\n ...withAgentFacingAttributes(library),\n ...(Array.isArray(library?.modules) && {\n modules: library.modules.map(withAgentFacingAttributes),\n }),\n ...(Array.isArray(library?.subModules) && {\n subModules: library.subModules.map(withAgentFacingAttributes),\n }),\n ...(Array.isArray(library?.groupSettings) && {\n groupSettings: agentFacingEntries(library.groupSettings),\n }),\n },\n ],\n ),\n )\n : masterData;\n\n// The attributes a planning sets at the create, by the library's structure:\n// those the catalog names per root module (mainAttributes, dimensions), the\n// group settings and those of the generated root modules - the modules no\n// catalog article names.\nconst createAttributeIds = (library: any, articles: any[]): Set<string> => {\n const rootModules = articles.flatMap(\n (article) => (article?.rootModules ?? []) as any[],\n );\n const catalogModuleIds = new Set(\n rootModules.map((rootModule) => rootModule?.module?.id),\n );\n return new Set([\n ...rootModules.flatMap((rootModule) =>\n [\n ...((rootModule?.mainAttributes ?? []) as any[]),\n ...((rootModule?.dimensions ?? []) as any[]),\n ].map((attribute) => attribute?.id),\n ),\n ...((library?.groupSettings ?? []) as string[]),\n ...((library?.modules ?? []) as any[])\n .filter((module) => !catalogModuleIds.has(module?.id))\n .flatMap((module) => (module?.attributes ?? []) as string[]),\n ]);\n};\n\n// The attribute vocabulary: per library every attribute of the compacted master\n// data. The values are listed for the attributes a planning sets at the\n// create, a shared value list once; every other attribute names the number of\n// its values, which find-attributes lists. The modules and the group settings\n// stay in masterData.\nexport const agentFacingAttributes = (masterData: any, articles: any[] = []) =>\n Object.fromEntries(\n Object.entries((masterData ?? {}) as Record<string, any>).map(\n ([libraryId, library]) => {\n const attributes = (library?.attributes ?? []) as any[];\n const atCreate = createAttributeIds(\n library,\n articles.filter((article) => article?.libraryId === libraryId),\n );\n const listed = new Set(\n attributes\n .filter(\n (attribute) =>\n atCreate.has(attribute.id) && hasSelections(attribute),\n )\n .map(selectionsKey),\n );\n return [\n libraryId,\n withSharedSelectionsOnce(\n attributes.map((attribute) => {\n if (\n !hasSelections(attribute) ||\n listed.has(selectionsKey(attribute))\n ) {\n return attribute;\n }\n const { selections, ...withoutValues } = attribute;\n return { ...withoutValues, valueCount: selections.length };\n }),\n ),\n ];\n },\n ),\n );\n\n// The corner point is not the agent's. The description is short; the\n// articleDescriptions section has the full one.\nexport const agentFacingArticle = (article: any) => {\n const compact = {\n ...article,\n ...(article.desc !== undefined && { desc: shortDescription(article.desc) }),\n ...(Array.isArray(article.rootModules) && {\n rootModules: article.rootModules.map((rootModule: any) => ({\n ...rootModule,\n ...(Array.isArray(rootModule?.dimensions) && {\n dimensions: agentFacingEntries(rootModule.dimensions),\n }),\n ...(Array.isArray(rootModule?.mainAttributes) && {\n mainAttributes: agentFacingEntries(rootModule.mainAttributes),\n }),\n })),\n }),\n };\n delete compact.cornerPoint;\n return compact;\n};\n\ninterface ContourLevel {\n level: number;\n segments?: Array<{\n cmd: string;\n pos: [number, number, number];\n type?: string | null;\n }>;\n}\n\ninterface WallOpening {\n fromEndMm?: [number, number];\n bottomMm?: number;\n topMm?: number;\n}\n\n// The lowest contour level above the floor at which part of the wall's span\n// is no longer solid wall: above it a sloping ceiling or a roof lies over the\n// wall. A door or a floor-to-ceiling window splits the floor contour into\n// opening pieces (D61), so only a level above the floor opens a wall piece;\n// the gap of a window between its sill and its head is one of the wall's\n// openings, not a slope, so the span of an opening counts as wall at the\n// levels it holds.\nexport const slopeFromMm = (\n levels: ContourLevel[] | undefined,\n wall: DerivedWall,\n openings: WallOpening[] = [],\n): number | undefined => {\n // an opening piece (a door, a floor-to-ceiling window) is open from the\n // floor - only a piece of wall can open above it\n if (wall.type !== 'wall') {\n return undefined;\n }\n const [[startX, startZ], [endX, endZ]] = wallFloorPoints(wall);\n const along = unitDirection([startX, startZ], [endX, endZ]);\n if (!along || !Array.isArray(levels)) {\n return undefined;\n }\n const tolerance = (wall.thicknessMm ?? 0) + POINT_EPSILON_MM;\n const sorted = [...levels].sort((a, b) => a.level - b.level);\n for (const level of sorted) {\n if (\n level.level <= 0 ||\n (wall.heightMm !== undefined && level.level >= wall.heightMm)\n ) {\n continue;\n }\n const spans: Array<[number, number]> = [];\n let previous: [number, number] | undefined;\n let subPathStart: [number, number] = [0, 0];\n for (const segment of level.segments ?? []) {\n const point: [number, number] = [segment.pos[0], segment.pos[2]];\n if (segment.cmd === 'M') {\n subPathStart = point;\n previous = point;\n continue;\n }\n const to = segment.cmd === 'Z' ? subPathStart : point;\n if (previous && segment.type === 'wall') {\n const fromLine = Math.abs(\n (previous[0] - startX) * along[1] - (previous[1] - startZ) * along[0],\n );\n const toLine = Math.abs(\n (to[0] - startX) * along[1] - (to[1] - startZ) * along[0],\n );\n if (fromLine <= tolerance && toLine <= tolerance) {\n spans.push(\n projectOntoAxis(\n [\n [previous[0] - startX, previous[1] - startZ],\n [to[0] - startX, to[1] - startZ],\n ],\n along,\n ),\n );\n }\n }\n previous = to;\n }\n for (const opening of openings) {\n const holdsTheLevel =\n Array.isArray(opening.fromEndMm) &&\n (opening.bottomMm ?? 0) <= level.level + POINT_EPSILON_MM &&\n level.level <\n (opening.topMm ?? Number.POSITIVE_INFINITY) - POINT_EPSILON_MM;\n if (holdsTheLevel) {\n const [from, to] = opening.fromEndMm as [number, number];\n spans.push([wall.lengthMm - to, wall.lengthMm - from]);\n }\n }\n spans.sort((a, b) => a[0] - b[0]);\n let coveredMm = 0;\n let reach = Number.NEGATIVE_INFINITY;\n let start = 0;\n for (const [from, to] of spans) {\n const clippedFrom = Math.max(from, 0);\n const clippedTo = Math.min(to, wall.lengthMm);\n if (clippedTo <= clippedFrom) {\n continue;\n }\n if (clippedFrom > reach + POINT_EPSILON_MM) {\n coveredMm += Math.max(reach - start, 0);\n start = clippedFrom;\n }\n reach = Math.max(reach, clippedTo);\n }\n coveredMm += Math.max(reach - start, 0);\n if (wall.lengthMm - coveredMm > POINT_EPSILON_MM) {\n return level.level;\n }\n }\n return undefined;\n};\n\ninterface OpeningObject {\n kind?: string;\n roomIndex?: number;\n wall?: number;\n fromEndMm?: [number, number];\n bottomMm?: number;\n topMm?: number;\n}\n\n// The doors and windows the obstacle list puts in one wall piece.\nconst openingsOfWall = (\n objects: OpeningObject[],\n roomIndex: number,\n wallIndex: number,\n) =>\n objects\n .filter(\n (object) =>\n (object?.kind === 'door' || object?.kind === 'window') &&\n object?.roomIndex === roomIndex &&\n object?.wall === wallIndex &&\n Array.isArray(object?.fromEndMm),\n )\n .map((object) => ({\n kind: object.kind,\n fromEndMm: object.fromEndMm,\n bottomMm: object?.bottomMm,\n topMm: object?.topMm,\n }));\n\n// The walls in the words of the user: a name per wall, an opening named as\n// such (the contour gives it no type), the room's index and every wall's\n// roomIndex, per wall its openings and the height above which the wall is\n// open (a sloping ceiling from the contour levels), per room its wall faces,\n// and the room corners with their point and the rotation of a group that\n// starts with a corner article there. A piece of wall is free at the floor\n// over its length - a door or a floor-to-ceiling window is a piece of its own\n// (D61) -, so no field says so.\nexport const agentFacingRooms = (rooms: any, obstacles?: any) => {\n if (!Array.isArray(rooms?.rooms)) {\n return rooms;\n }\n const objects: OpeningObject[] = Array.isArray(obstacles?.objects)\n ? obstacles.objects\n : [];\n return {\n ...rooms,\n rooms: rooms.rooms.map((room: any, roomIndex: number) => {\n const walls = ((room?.walls ?? []) as any[]).map((wall) => {\n const openings = openingsOfWall(objects, roomIndex, wall?.index);\n const slope = slopeFromMm(room?.levels, wall, openings);\n return {\n ...wall,\n ...(wall?.type === null || wall?.type === undefined\n ? { type: 'opening' }\n : {}),\n name: wallName(wall?.side),\n roomIndex,\n ...(openings.length > 0 ? { openings } : {}),\n ...(slope !== undefined ? { slopeFromMm: slope } : {}),\n };\n });\n const faces = wallFaces(walls).map((face) => {\n const openingMm = round2(\n face.pieces\n .filter((piece) => piece.type !== 'wall')\n .reduce((sum, piece) => sum + piece.lengthMm, 0),\n );\n const slopes = face.pieces\n .map((piece) => (piece as any).slopeFromMm)\n .filter((slope): slope is number => slope !== undefined);\n return {\n roomIndex,\n side: face.side,\n name: wallName(face.side),\n index: face.index,\n lengthMm: face.lengthMm,\n openingMm,\n openingShare: round2(\n face.lengthMm > 0 ? openingMm / face.lengthMm : 0,\n ),\n ...(slopes.length > 0 ? { slopeFromMm: Math.min(...slopes) } : {}),\n };\n });\n return {\n ...room,\n index: roomIndex,\n walls,\n faces,\n corners: roomCorners(walls),\n };\n }),\n };\n};\n\n// A door or a window lies in a wall: the room, the wall and its span along the\n// wall, measured from the wall's end like the d of a placement.\nexport const agentFacingObstacles = (obstacles: any, rooms: any) => {\n if (!Array.isArray(obstacles?.objects)) {\n return obstacles;\n }\n return {\n ...obstacles,\n objects: obstacles.objects.map((object: any) => {\n if (object?.kind !== 'door' && object?.kind !== 'window') {\n return object;\n }\n const wall = wallOfOpening(\n ((object.outline ?? []) as number[][]).map(\n ([x, , z]): [number, number] => [x, z],\n ),\n rooms?.rooms ?? [],\n );\n return wall ? { ...object, ...wall } : object;\n }),\n };\n};\n","import {\n agentFacingArticle,\n agentFacingAttributes,\n agentFacingFittings,\n agentFacingGroups,\n agentFacingMasterData,\n agentFacingObstacles,\n agentFacingRooms,\n withSharedSelectionsOnce,\n} from './agent-facing';\nimport type { PlanHistory, ToolCallRecord } from './plan-history';\nimport type { PlannerApi } from './planner-api';\nimport { isSkillFile, readSkill, readSkillFile, skills } from './skills';\nimport { searchableText } from '../util';\n\n/** The format of the images of get-plan-images: a fraction of a PNG's bytes, read alike by the model. */\nexport const PLAN_IMAGE_TYPE = 'image/jpeg';\nexport const PLAN_IMAGE_QUALITY = 0.8;\n\nexport type ToolExecutor = (\n roomDesignerApi: PlannerApi,\n args: Record<string, unknown>,\n) => Promise<unknown>;\n\ntype PlanContextSection =\n | 'masterData'\n | 'rooms'\n | 'articles'\n | 'groups'\n | 'obstacles'\n | 'installationElements';\n\nconst PLAN_CONTEXT_SECTIONS: unknown[] = [\n 'masterData',\n 'rooms',\n 'articles',\n 'groups',\n 'obstacles',\n 'installationElements',\n];\n\n// The sections of these the library context returns; the others are the plan\n// context's.\nconst LIBRARY_CONTEXT_SECTIONS: unknown[] = ['masterData', 'articles'];\n\n// The sections of the server: the full descriptions of the catalog's\n// articles, and the attribute vocabulary, both derived from the planner's\n// sections.\nconst ARTICLE_DESCRIPTIONS = 'articleDescriptions';\nconst ATTRIBUTES = 'attributes';\nconst SERVER_SECTIONS: unknown[] = [ARTICLE_DESCRIPTIONS, ATTRIBUTES];\n\nconst DEFAULT_SECTIONS: unknown[] = [\n 'rooms',\n 'articles',\n ATTRIBUTES,\n 'groups',\n 'obstacles',\n 'installationElements',\n];\n\nconst MAX_ATTRIBUTE_MATCHES = 20;\n\nconst searchWords = (text: string): string[] =>\n searchableText(text)\n .split(/[\\s,;()-]+/)\n .filter((word) => word.length > 0);\n\n// Every word is in one of the attribute's fields.\nconst attributeMatches = (attribute: any, words: string[]): boolean => {\n const fields = [\n attribute.id,\n attribute.name,\n attribute.desc,\n attribute.group,\n ...(attribute.selections ?? []).flatMap((selection: any) => [\n selection.name,\n selection.desc,\n selection.value,\n ]),\n ]\n .filter((value) => value !== undefined && value !== null)\n .map((value) => searchableText(String(value)));\n return words.every((word) => fields.some((field) => field.includes(word)));\n};\n\nconst rootsOfGroups = (groups: any[]): any[] =>\n groups.flatMap((group) => (group?.roots ?? []) as any[]);\n\nconst planGroups = async (roomDesignerApi: PlannerApi): Promise<any[]> =>\n ((await roomDesignerApi.extended.getExternalObjectPlanContext(['groups']))\n .groups ?? []) as any[];\n\nconst isObject = (value: unknown): boolean =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n// A planner undo or redo is confirmed by its history event.\nconst HISTORY_EVENT_WAIT_MS = 1000;\n\nconst roundedToTenthMm = (_key: string, value: unknown) =>\n typeof value === 'number' ? Math.round(value * 10) / 10 : value;\n\n// The plan's groups as a comparison key, sorted by id - an undo restores them\n// to the tenth of a millimetre.\nconst groupsKey = (groups: unknown): string =>\n JSON.stringify(\n [...((groups ?? []) as any[])].sort((a, b) =>\n String(a?.id).localeCompare(String(b?.id)),\n ),\n roundedToTenthMm,\n );\n\nconst readGroupsKey = async (roomDesignerApi: PlannerApi) =>\n groupsKey(await planGroups(roomDesignerApi));\n\n// The planner API of a tool call that changes the plan. The tool runs in the\n// planner page as one group command, which answers after its last reload and\n// reports the steps it put on the planner's undo history - one per load that\n// loaded something and one per group command. The API counts the steps and\n// reads the plan before the first one.\nconst countingPlannerApi = (roomDesignerApi: PlannerApi) => {\n const { extended } = roomDesignerApi;\n const count = {\n steps: 0,\n groupsBefore: undefined as string | undefined,\n };\n const api: PlannerApi = {\n extended: {\n ...extended,\n externalObjectGroupOperation: async (command, payload) => {\n count.groupsBefore ??= await readGroupsKey(roomDesignerApi);\n const result = await extended.externalObjectGroupOperation(\n command,\n payload,\n );\n count.steps += Number(result?.historySteps ?? 1);\n return result;\n },\n },\n };\n return { api, count };\n};\n\ntype HistoryDirection = 'undo' | 'redo';\n\nconst NOTHING_TO_UNDO =\n 'Nothing to undo: no tool call has changed the plan since the planner page connected.';\nconst NOTHING_TO_REDO =\n 'Nothing to redo: redo brings back a tool call that undo reverted, and a new change of the plan ends redo.';\nconst CHANGED_IN_PLANNER =\n \"The plan was changed in the planner after the last tool call, so no tool call was reverted - the planner's own undo button reverts the changes made there.\";\n\n// The groups a tool call changed, by the plan before and after it: those it\n// created, removed or changed.\nconst changedGroupIds = (call: ToolCallRecord): Set<string> => {\n const byId = (key: string) =>\n new Map(\n ((JSON.parse(key) ?? []) as any[]).map((group) => [\n String(group?.id),\n JSON.stringify(group),\n ]),\n );\n const before = byId(call.groupsBefore);\n const after = byId(call.groupsAfter);\n return new Set(\n [...before.keys(), ...after.keys()].filter(\n (id) => before.get(id) !== after.get(id),\n ),\n );\n};\n\n// A result that changed some groups of the plan: those groups in full, the\n// others by their id - the agent knows them already.\nconst changedGroupsOnly = (\n groups: any[],\n changed: (group: any) => boolean,\n): { groups: any[]; otherGroupIds?: string[] } => {\n const others = groups.filter((group) => !changed(group));\n return {\n groups: groups.filter(changed),\n ...(others.length > 0 && {\n otherGroupIds: others.map((group) => group.id),\n }),\n };\n};\n\n// The root modules and groups the library cannot calculate, one sentence\n// each: \"is still not built\" after an attribute change - a change that makes\n// one fail is discarded before the load, so each of them failed before the\n// call, unless a follow-up calculation of the call left it -, \"is not built\"\n// in the price and the order.\nconst notBuilt = (\n groups: any[],\n state: 'still not built' | 'not built',\n): string[] =>\n groups.flatMap((group) => [\n ...(group?.calculationError !== undefined\n ? [`group '${group.id}' is ${state} - ${group.calculationError}.`]\n : []),\n ...((group?.roots ?? []) as any[])\n .filter((root) => root?.calculationError !== undefined)\n .map(\n (root) =>\n `root module '${root.id}' (${root.articleId}) of group '${group.id}' is ${state} - ${root.calculationError}.`,\n ),\n ]);\n\n// The price and the order data count every root module of the plan, also one\n// the library could not calculate: the answer stays as the planner gives it,\n// and the hint names what is not built. A plan without one gets the answer\n// alone.\nconst withNotBuiltHint = (answer: any, groups: any[], counted: string) => {\n const sentences = notBuilt(groups, 'not built');\n return sentences.length === 0\n ? answer\n : {\n ...answer,\n hint: `${sentences.join(' ')} ${counted} includes what is not built, without calculated dimensions and parts - say so in the answer, or change the value that fails.`,\n };\n};\n\n// An attribute change answers with what changed, not with the whole group:\n// get-plan-context shows the group. What the library still cannot calculate\n// in the changed groups is the hint, so a repair that failed again shows.\nconst compactAttributeResult = (result: any) => {\n const groups = (result.groups ?? []) as any[];\n const stillNotBuilt = notBuilt(groups, 'still not built');\n return {\n command: result.command,\n groupIds: groups.map((group) => group.id),\n ...(result.changedModuleIds?.length > 0 && {\n changedModuleIds: result.changedModuleIds,\n }),\n ...(result.corrections?.length > 0 && { corrections: result.corrections }),\n ...(result.libraryFailures?.length > 0 && {\n libraryFailures: result.libraryFailures,\n }),\n ...(stillNotBuilt.length > 0 && {\n hint: `${stillNotBuilt.join(' ')} Change the value that fails, or tell the user.`,\n }),\n };\n};\n\n// Opening or closing changes the view, not the plan: the answer names the\n// target and the state its doors and drawers are in now - the planner has the\n// requested state once the call succeeds - without the changed flag of the\n// group operation, which keeps the switch out of undo (D88). A target without\n// doors or drawers keeps its correction and gets no state.\nconst doorsAndDrawersResult =\n (target: 'groupId' | 'rootModuleId') =>\n (result: any, args: Record<string, unknown>) => ({\n command: result.command,\n [target]: args[target],\n ...(result.corrections?.length > 0\n ? { corrections: result.corrections }\n : { doorsAndDrawers: args.open === true ? 'open' : 'closed' }),\n });\n\n// The executors of one tool set: its plan changes run one after another and\n// its tool calls that changed the plan are recorded in its plan history.\nexport const createToolExecutors = (\n planHistory: PlanHistory,\n): Record<string, ToolExecutor> => {\n // The tool calls that change the plan run one after another: the record of a\n // call for undo compares the plan before and after it, and the page runs every\n // planner call it receives at once, so a concurrent call would mix into the\n // record. get-plan-context, find-attributes, get-price and get-order-data\n // wait as well, so that they never read a plan halfway through a change.\n let planChanges: Promise<unknown> = Promise.resolve();\n\n const oneAtATime =\n (executor: ToolExecutor): ToolExecutor =>\n (roomDesignerApi, args) => {\n const run = planChanges.then(() => executor(roomDesignerApi, args));\n planChanges = run.catch(() => undefined);\n return run;\n };\n // A tool call that changed the plan is recorded with its planner steps and\n // the plan before and after it, so that undo can revert it; the history\n // events while it runs are its own. A plan that cannot be read afterwards\n // leaves no record the undo could trust.\n const recorded =\n (tool: string, executor: ToolExecutor): ToolExecutor =>\n async (roomDesignerApi, args) => {\n const { api, count } = countingPlannerApi(roomDesignerApi);\n planHistory.begin();\n try {\n return await executor(api, args);\n } finally {\n const recordable = count.steps > 0 && count.groupsBefore !== undefined;\n let groupsAfter: string | undefined;\n if (recordable) {\n try {\n groupsAfter = await readGroupsKey(roomDesignerApi);\n } catch {\n groupsAfter = undefined;\n }\n }\n if (recordable && groupsAfter === undefined) {\n planHistory.forget();\n } else if (recordable) {\n planHistory.record({\n tool,\n steps: count.steps,\n groupsBefore: count.groupsBefore!,\n groupsAfter: groupsAfter!,\n });\n }\n planHistory.end();\n }\n };\n\n const planChange = (tool: string, executor: ToolExecutor): ToolExecutor =>\n oneAtATime(recorded(tool, executor));\n\n // One planner undo or redo per step, each confirmed by its history event.\n // Returns the number of steps done: fewer when the planner's history ran out.\n const stepHistory = async (\n roomDesignerApi: PlannerApi,\n direction: HistoryDirection,\n steps: number,\n ): Promise<number> => {\n planHistory.begin();\n try {\n for (let step = 0; step < steps; step++) {\n const eventsBefore = planHistory.events;\n await roomDesignerApi.extended[direction]();\n const confirmed = await planHistory.waitForEvents(\n eventsBefore + 1,\n HISTORY_EVENT_WAIT_MS,\n );\n if (!confirmed) {\n return step;\n }\n }\n return steps;\n } finally {\n planHistory.end();\n }\n };\n\n // undo reverts the last tool call that changed the plan, redo brings back the\n // last one undo reverted - only while the plan is as that call left it. The\n // server cannot keep the user from changing the plan in the planner while a\n // tool call runs, and such a change sits among the call's steps: an undo or\n // redo that does not give back the plan before or after the call is taken\n // back, so it never leaves a wrong revert in place.\n const revertToolCall =\n (direction: HistoryDirection): ToolExecutor =>\n async (roomDesignerApi) => {\n const undo = direction === 'undo';\n const call = undo ? planHistory.lastDone() : planHistory.lastUndone();\n const answer = async (tool: string | null, hint?: string) => ({\n [undo ? 'undone' : 'redone']: tool,\n groups: agentFacingGroups(await planGroups(roomDesignerApi)),\n ...(hint && { hint }),\n });\n if (!call) {\n return answer(\n null,\n planHistory.changedInPlanner\n ? CHANGED_IN_PLANNER\n : undo\n ? NOTHING_TO_UNDO\n : NOTHING_TO_REDO,\n );\n }\n const [from, to] = undo\n ? [call.groupsAfter, call.groupsBefore]\n : [call.groupsBefore, call.groupsAfter];\n if ((await readGroupsKey(roomDesignerApi)) !== from) {\n planHistory.forget();\n return answer(null, CHANGED_IN_PLANNER);\n }\n const done = await stepHistory(roomDesignerApi, direction, call.steps);\n if (done < call.steps) {\n planHistory.forget();\n return answer(\n null,\n done === 0\n ? `The planner's undo history no longer holds ${call.tool} - the plan was loaded again, nothing was ${undo ? 'undone' : 'redone'}.`\n : `The planner's undo history ended after ${done} of ${call.steps} steps of ${call.tool} - check the plan with get-plan-context.`,\n );\n }\n if ((await readGroupsKey(roomDesignerApi)) !== to) {\n const back = await stepHistory(\n roomDesignerApi,\n undo ? 'redo' : 'undo',\n call.steps,\n );\n const restored =\n back === call.steps &&\n (await readGroupsKey(roomDesignerApi)) === from;\n planHistory.markChangedInPlanner();\n const missed = `${undo ? 'Undo' : 'Redo'} of ${call.tool} did not give back the plan ${undo ? 'before' : 'after'} it - the plan was changed in the planner while the tool call ran.`;\n return answer(\n null,\n restored\n ? `${missed} The ${direction} was taken back and the plan is as it was; the planner's undo button reverts the changes made there.`\n : `${missed} The ${direction} could not be taken back completely - check the plan with get-plan-context.`,\n );\n }\n if (undo) {\n planHistory.markUndone();\n } else {\n planHistory.markRedone();\n }\n const changed = changedGroupIds(call);\n const groups = await planGroups(roomDesignerApi);\n const removed = [...changed].filter(\n (id) => !groups.some((group) => group.id === id),\n );\n return {\n [undo ? 'undone' : 'redone']: call.tool,\n ...changedGroupsOnly(agentFacingGroups(groups), (group) =>\n changed.has(group.id),\n ),\n ...(removed.length > 0 && { removedGroupIds: removed }),\n };\n };\n\n // The tools that change the plan run in the planner page: roomle-ui performs\n // the tool with the agent's arguments and reports the planner steps it made,\n // which the server records for undo. A tool that failed after it changed the\n // plan answers with its error and its steps: the steps are recorded, so undo\n // reverts them, and the agent gets the error. A change the library could not\n // calculate is discarded in the planner before it is loaded; libraryFailures\n // of a result name what a follow-up calculation of the call left.\n const inPlanner = (\n tool: string,\n shape: (result: any, args: Record<string, unknown>) => any = (result) =>\n result,\n ): ToolExecutor =>\n planChange(tool, async (roomDesignerApi, args) => {\n const result = {\n ...(await roomDesignerApi.extended.externalObjectGroupOperation(\n tool,\n args,\n )),\n };\n delete result.historySteps;\n delete result.historyFollowUps;\n if (typeof result.error === 'string') {\n throw new Error(result.error);\n }\n if (result.groups !== undefined) {\n result.groups = agentFacingGroups(result.groups);\n }\n if (result.fittings !== undefined) {\n result.fittings = agentFacingFittings(result.fittings);\n }\n return shape(result, args);\n });\n\n return {\n 'add-interior-fitting': inPlanner('add-interior-fitting'),\n 'move-interior-fitting': inPlanner('move-interior-fitting'),\n 'delete-interior-fittings': inPlanner('delete-interior-fittings'),\n 'replace-interior-fitting': inPlanner('replace-interior-fitting'),\n 'open-or-close-group': inPlanner(\n 'open-or-close-group',\n doorsAndDrawersResult('groupId'),\n ),\n 'open-or-close-article': inPlanner(\n 'open-or-close-article',\n doorsAndDrawersResult('rootModuleId'),\n ),\n 'get-interior-design-options': oneAtATime(async (api, args) => {\n const { groupId, rootId, containerModuleId, articleId } = args;\n if (typeof groupId !== 'string' || !groupId.trim()) {\n throw new Error('groupId is required for interior discovery.');\n }\n const { interiorDesign } =\n await api.extended.getExternalObjectPlanContext(['interiorDesign'], {\n interiorDesign: {\n groupId,\n ...(typeof rootId === 'string' && { rootId }),\n ...(typeof containerModuleId === 'string' && { containerModuleId }),\n ...(typeof articleId === 'string' && { articleId }),\n },\n });\n return interiorDesign?.fittings === undefined\n ? interiorDesign\n : {\n ...interiorDesign,\n fittings: agentFacingFittings(interiorDesign.fittings),\n };\n }),\n // The plan and the library context arrive agent-ready from the planner API\n // (compacted sections, 3D room contours with derived walls, the groups in\n // the frame a placement names); the executor asks each for its sections,\n // names the walls and leaves out the articles' corner points.\n 'get-plan-context': oneAtATime(async (roomDesignerApi, args) => {\n // an unknown section is ignored\n const named = (Array.isArray(args.include) ? args.include : []).filter(\n (section) =>\n PLAN_CONTEXT_SECTIONS.includes(section) ||\n SERVER_SECTIONS.includes(section),\n );\n const include = named.length > 0 ? named : DEFAULT_SECTIONS;\n const withDescriptions = include.includes(ARTICLE_DESCRIPTIONS);\n const withAttributes = include.includes(ATTRIBUTES);\n const requested = include.filter(\n (section): section is PlanContextSection =>\n PLAN_CONTEXT_SECTIONS.includes(section),\n );\n // the descriptions and the vocabulary come with the articles\n const withArticles =\n (withDescriptions || withAttributes) && !requested.includes('articles');\n // the walls name the doors and windows of the obstacles, and they tell\n // a window's gap from a slope by them\n const withRooms =\n requested.includes('obstacles') && !requested.includes('rooms');\n const withObstacles =\n requested.includes('rooms') && !requested.includes('obstacles');\n // the vocabulary comes with the master data\n const withMasterData =\n withAttributes && !requested.includes('masterData');\n const sections = [\n ...requested,\n ...(withRooms ? ['rooms' as const] : []),\n ...(withObstacles ? ['obstacles' as const] : []),\n ...(withArticles ? ['articles' as const] : []),\n ...(withMasterData ? ['masterData' as const] : []),\n ];\n const planSections = sections.filter(\n (section) => !LIBRARY_CONTEXT_SECTIONS.includes(section),\n );\n const librarySections = sections.filter((section) =>\n LIBRARY_CONTEXT_SECTIONS.includes(section),\n );\n const [planContext, libraryContext] = await Promise.all([\n planSections.length > 0\n ? roomDesignerApi.extended.getExternalObjectPlanContext(planSections)\n : {},\n librarySections.length > 0\n ? roomDesignerApi.extended.getExternalObjectLibraryContext(\n librarySections,\n )\n : {},\n ]);\n if (!isObject(planContext)) {\n return planContext;\n }\n if (!isObject(libraryContext)) {\n return libraryContext;\n }\n const result: Record<string, any> = {\n ...planContext,\n ...libraryContext,\n };\n if (result.obstacles !== undefined) {\n result.obstacles = agentFacingObstacles(result.obstacles, result.rooms);\n }\n if (result.rooms !== undefined) {\n result.rooms = agentFacingRooms(result.rooms, result.obstacles);\n }\n if (result.groups !== undefined) {\n result.groups = agentFacingGroups(result.groups);\n }\n if (result.masterData !== undefined) {\n result.masterData = agentFacingMasterData(result.masterData);\n }\n if (withRooms) {\n delete result.rooms;\n }\n if (withObstacles) {\n delete result.obstacles;\n }\n if (Array.isArray(result.articles)) {\n const articles = result.articles as any[];\n if (withDescriptions) {\n result[ARTICLE_DESCRIPTIONS] = articles.map(\n ({ articleId, desc }) => ({\n articleId,\n desc,\n }),\n );\n }\n result.articles = articles.map((article) =>\n agentFacingArticle(article),\n );\n }\n if (withAttributes && result.masterData !== undefined) {\n result[ATTRIBUTES] = agentFacingAttributes(\n result.masterData,\n Array.isArray(result.articles) ? result.articles : [],\n );\n }\n if (withArticles) {\n delete result.articles;\n }\n if (withMasterData) {\n delete result.masterData;\n }\n return result;\n }),\n\n 'find-attributes': oneAtATime(async (roomDesignerApi, args) => {\n const words = searchWords(String(args.text ?? ''));\n const ids = (Array.isArray(args.ids) ? args.ids : []).filter(\n (id): id is string => typeof id === 'string' && id.length > 0,\n );\n if (words.length === 0 && ids.length === 0) {\n throw new Error('text or ids must not be empty.');\n }\n const libraryId = args.libraryId as string | undefined;\n const [planContext, libraryContext] = await Promise.all([\n roomDesignerApi.extended.getExternalObjectPlanContext(['groups']),\n roomDesignerApi.extended.getExternalObjectLibraryContext([\n 'masterData',\n ]),\n ]);\n const context = {\n groups: planContext?.groups,\n masterData: agentFacingMasterData(libraryContext?.masterData),\n };\n // the attributes the root modules in the plan and their sub modules\n // carry - the worktop of a group, not a panel top it does not have\n const inPlan = new Set(\n rootsOfGroups((context.groups ?? []) as any[]).flatMap((root) =>\n [root, ...((root?.subModules ?? []) as any[])].flatMap((module) =>\n ((module?.attributes ?? []) as any[]).map(\n (attribute) => attribute?.id,\n ),\n ),\n ),\n );\n const named: any[] = [];\n const matches: any[] = [];\n for (const [id, masterData] of Object.entries(\n (context.masterData ?? {}) as Record<string, any>,\n )) {\n if (libraryId && id !== libraryId) {\n continue;\n }\n // The master data arrives compacted: every attribute, the root modules\n // and the sub modules with the attributes they carry.\n const carriers = (modules: any[], attributeId: string) =>\n modules\n .filter((module: any) =>\n (module.attributes ?? []).includes(attributeId),\n )\n .map((module: any) => ({ id: module.id, name: module.name }));\n for (const attribute of masterData.attributes ?? []) {\n const isNamed = ids.includes(attribute.id);\n if (\n !isNamed &&\n !(words.length > 0 && attributeMatches(attribute, words))\n ) {\n continue;\n }\n const subModules = carriers(\n masterData.subModules ?? [],\n attribute.id,\n );\n (isNamed ? named : matches).push({\n libraryId: id,\n ...attribute,\n rootModules: carriers(masterData.modules ?? [], attribute.id),\n ...(subModules.length > 0 && { subModules }),\n });\n }\n }\n // the attributes named by id in the order of the ids, then the text\n // matches\n const ranked = [\n ...[...named].sort((a, b) => ids.indexOf(a.id) - ids.indexOf(b.id)),\n ...matches.filter((match) => inPlan.has(match.id)),\n ...matches.filter((match) => !inPlan.has(match.id)),\n ];\n const notFound = ids.filter(\n (attributeId) => !named.some((match) => match.id === attributeId),\n );\n const hints = [\n ...(notFound.length > 0\n ? [\n `No attribute has the id ${notFound.map((attributeId) => `\"${attributeId}\"`).join(', ')} - the ids are in the attributes section of get-plan-context.`,\n ]\n : []),\n ...(matches.length > MAX_ATTRIBUTE_MATCHES\n ? [\n `Only the first ${MAX_ATTRIBUTE_MATCHES} of ${matches.length} matches are listed - narrow the text.`,\n ]\n : []),\n ];\n return {\n matches: withSharedSelectionsOnce(\n ranked.slice(0, named.length + MAX_ATTRIBUTE_MATCHES),\n ),\n total: named.length + matches.length,\n ...(notFound.length > 0 && { notFound }),\n ...(hints.length > 0 && { hint: hints.join(' ') }),\n };\n }),\n\n 'create-or-replace-groups': inPlanner('create-or-replace-groups'),\n 'place-group': inPlanner('place-group'),\n 'change-module-attribute': inPlanner(\n 'change-module-attribute',\n compactAttributeResult,\n ),\n 'change-group-attribute': inPlanner(\n 'change-group-attribute',\n compactAttributeResult,\n ),\n 'delete-group': inPlanner('delete-group'),\n 'delete-article-in-place': inPlanner('delete-article-in-place'),\n 'delete-article-and-compact': inPlanner('delete-article-and-compact'),\n 'merge-article-into-group': inPlanner('merge-article-into-group'),\n 'exchange-root-module': inPlanner('exchange-root-module'),\n 'insert-article-into-group': inPlanner('insert-article-into-group'),\n 'swap-root-modules': inPlanner('swap-root-modules'),\n 'merge-groups': inPlanner('merge-groups'),\n\n undo: oneAtATime(revertToolCall('undo')),\n\n redo: oneAtATime(revertToolCall('redo')),\n\n 'get-skill': async (_roomDesignerApi, { name, file }) =>\n isSkillFile(file === undefined ? undefined : String(file))\n ? readSkill(skills, String(name))\n : readSkillFile(skills, String(name), String(file)),\n\n 'get-price': oneAtATime(async (roomDesignerApi) => {\n const price = await roomDesignerApi.extended.fetchPrice();\n return withNotBuiltHint(\n price,\n await planGroups(roomDesignerApi),\n 'The price',\n );\n }),\n\n 'get-order-data': oneAtATime(async (roomDesignerApi) => {\n const snapshot = await roomDesignerApi.extended.getExternalObjectSnapshot(\n {\n orderData: true,\n },\n );\n return withNotBuiltHint(\n snapshot?.orderData ?? null,\n await planGroups(roomDesignerApi),\n 'The order data',\n );\n }),\n\n // waits like get-plan-context, so the images show the plan and the doors\n // after the change or the opening sent before them\n 'get-plan-images': oneAtATime(async (roomDesignerApi) => {\n const snapshot = await roomDesignerApi.extended.getExternalObjectSnapshot(\n {\n perspectiveObjectImage: true,\n topImage: true,\n keepOpenGeometry: true,\n imageType: PLAN_IMAGE_TYPE,\n imageQuality: PLAN_IMAGE_QUALITY,\n },\n );\n return {\n perspectiveObjectImage: snapshot?.perspectiveObjectImage,\n topImage: snapshot?.topImage,\n };\n }),\n };\n};\n","import { z } from 'zod';\nimport type { HiAgentPrompts } from '../hi-agent-prompts';\nimport { fromAgentFrame, toAgentFrame } from './agent-frame';\nimport { mcpTool } from './mcp-tool';\nimport type { HiAgentTools, McpToolResult } from './mcp-tool-types';\nimport { PlanHistory } from './plan-history';\nimport { createPlannerApi } from './planner-api';\nimport type { HiMcpPlannerApi } from './planner-api';\nimport { isSkillFile, skillIndex, skills } from './skills';\nimport { PLAN_IMAGE_TYPE, createToolExecutors } from './tool-executors';\n\nconst MOUNTING_GUIDANCE =\n 'Choose articles and mounting settings from their descriptions and attributes; categories organize the catalog. ' +\n 'For an article used at wall level, above names the root module below it and gapMm sets the clearance; ' +\n 'rightOf or leftOf continues that wall row, including its finishing parts. ' +\n 'Fetch articleDescriptions when its mounting requirements are unclear.';\n\nconst AUTHORING_RULES = `Authoring rules for pos groups:\n- ${MOUNTING_GUIDANCE}\n- Words: the catalog offers articles - cabinets, wardrobes, appliances, panels. A group is one piece of furniture made of articles: a kitchen, a wardrobe, a sideboard, a utility room, a row of cabinets. An article placed in a group is a root module (root for short); the user may call it a cabinet, a unit or a module. The description says what an article is and dimensions give its size. The user decides which articles stand next to each other: a low cabinet between two high cabinets is an order like any other. When the user names a kind, not an article, take the article of that kind from the category of its neighbours where that category has one (a kitchen cabinet into a kitchen, a wardrobe into a wardrobe), else the closest kind of another category.\n- A group is { id?, libraryId?, placement?, roots: [...] }. A root module is an article pick and nothing else: { id, articleId, attributes? } plus one relation that names its neighbour (rightOf, leftOf, onTop, above or behind - see Relations below). The server ignores every other field - a position on a root or a group included - and drops roots marked isGenerated (worktop, toe kick - the library regenerates them). Every root position comes from its relation; the position of a new group comes from its placement. Groups returned by get-plan-context carry their docking as contextData instead - resubmit them as they are. Use a unique id of your choice for new roots (the planner regenerates it and remaps your docking references); keep the real ids of roots that already exist in a replaced group. Choose the articleId from the article catalog of get-plan-context: desc and category say what an article is and what it is for, dimensions give its size (per size attribute its id, its name - e.g. Width, Depth, Height - and its value in millimetres; a root in groups carries the same attribute ids among its attributes, and change-module-attribute with that attribute id, never its name, changes the size of a root module; an article of another size - \"a 900 mm cabinet\" - is the same article with that attribute set, which merge-article-into-group, insert-article-into-group and exchange-root-module take in their attributes), dockingVectors the names of its docking vectors, subModules its fronts and appliances, cornerArticle true marks an article made for a room corner. Sub-modules come with the article. For Interior Design, interior fittings or sub-articles use get-interior-design-options and the interior fitting tools; never author nested module trees. Ask for clarification when the requested interior change or installed instance is ambiguous. Identify an upper/lower fitting from its measured position in the same parent, never its array order. attributes is an optional list of { id, value } overrides of that root module - an attribute only its sub modules carry is set on those sub modules; a material for the whole group - the fronts, the worktop, the carcase - goes into the group's attributes ({ id, value } entries beside roots), and the server sets it on every root module and on the worktop; a root module that names its own value of it in its attributes keeps that value - an accent, e.g. dark wall units in a light group. Attribute ids are in the attributes section of get-plan-context - every attribute of the library. It lists the values (selections) of the attributes a planning sets at the create - a value list several attributes share is listed once, sameSelectionsAs names the attribute that lists it - and for every other attribute the number of its values (valueCount): find-attributes with their ids returns those values, several attributes in one call. The desc of a colour value carries its code. A value is a selection's value - send \"324\", not \"White\": a name, desc or colour code sent as the value is read as that value and named in corrections. The first kitchen does not wait for a lookup: in the create, set the attributes whose values the section lists - a material (fronts, worktop, carcase, handles) only when the request asks for one; an attribute with valueCount keeps its article's value until you change it after the create. find-attributes answers a question about an attribute. Everything else the calculation needs is completed automatically from the article template.\n- Every desc - of an article, a root, a module, an attribute and an attribute value - is authoritative: trust it for what that article, module or value is, and trust dimensions for how big an article is. A colour code in the desc of an attribute value - Cloudy blue (#506080) - is the colour of that value: take it as it is, and tell light from dark and one hue from another by it, not by the name. All of them are authoritative over the catalog images of the master data (imageUrl): never take the kind or the size of an article, or the colour of a value, from a catalog image. A desc says what an article is, not where the user may put it.\n- Fronts: the front program says how a front is built - by its desc: simple fronts, frame fronts with wooden filling, mitred frame fronts with glass filling, milled fronts. Choose it by its desc first, then the front colour. A program offers only some colours: a colour it does not offer switches the program to one that does, and the fronts are then built as that program says; a program resets a colour it does not offer. corrections name every such change. When the colour the user wants comes only with fronts built differently, keep the fronts the user wants: undo a switched program, take the closest colour their program offers, and tell the user which fronts the wanted colour comes with.\n- Doors: a door is hinged on one side and has its handle on the other. In a row, the door at the left end is hinged on the left and the door at the right end on the right, as seen from the front, so no handle is on the outside of the row; a pair of doors side by side is hinged at its two outer sides. The wall units hanging side by side above a floor row form a row of their own, docked to each other or each above its floor unit; it ends at a wall, at a gap or beside a tall unit, and its end doors are hinged like those of a floor row. Set it with the attribute whose values say on which side a door is hinged - the value for single doors or for a pair of doors, as the article has - in the attributes of the root modules at the two ends of the row (rowIndex 1 and the last), and again on the root module at an end after an edit that gives the row a new end: an article added, exchanged or swapped at an end, an end article deleted, or a delete that leaves the gap and so splits the row into two rows. A single door that is a row of its own - one root module - keeps its side: both its sides are outer sides. The other doors keep their side.\n- One piece of furniture is one group. Every article standing beside, above or back to back with another article is a root module of the SAME group, related to it; a new group carries one placement, and the planner derives every root position from the relations. Never create a second group to put articles next to existing ones - articles that belong together are related.\n- Never author a position: roots are positioned by their relation only, a new group with placement only; a position on a root or a group is ignored.\n- Relations: every root after the first names one neighbour of the same group by its id, with exactly one of these fields - the server builds the docking from it:\n rightOf: \"<id>\" - the article stands right of that root module; leftOf: \"<id>\" - left of it (right and left as seen from the front). A row is each root module rightOf the one before.\n onTop: \"<id>\" - the article stands on top of that root module (stacking on a tall unit or a wall unit, also several levels); align: \"left\" (default), \"right\" or \"back\" says which edges line up, gapMm lifts it.\n above: \"<id>\" - a wall unit hanging above that floor-standing root module, its top flush with the tall units; gapMm sets another gap below it - the same for every wall unit of the group. A wall unit rightOf or leftOf another wall unit hangs at that wall unit's bottom, so a shorter wall unit whose top lines up with its neighbours stands onTop of the root module below it, e.g. an open shelf unit.\n behind: \"<id>\" - back to back with that root module, turned by 180 degrees: an island, a peninsula, and the panel that closes the back of such a row. A panel behind a row is anchored by the server at the row's start end - the corner article of a peninsula leg, else the row's first unit as seen from its front - and runs along the whole row, so name any unit of the row; size the panel to the row's whole back, a corner's back included (corner articles list their cornerBackLengthsMm).\n A wall unit rightOf or leftOf a tall unit hangs beside it with the tops flush, on the side of the base units (leftOf a tall unit that ends the row on the right); further wall units continue rightOf or leftOf each other. Without a tall unit, the first wall unit hangs above a floor unit and the next ones continue rightOf or leftOf it. A range hood hangs above the hob unit, with its own gapMm; the next wall unit past the hood hangs above its own floor unit.\n A room corner (an L-shaped kitchen, \"in the corner\"): start the group with a corner article (cornerArticle true in the catalog), give the group a placement at one wall of that corner with the other wall as alignment (the back right corner: wall right, alignment back), and continue one row rightOf the corner article and the other row leftOf it - the complete payload is example 3. The wall units of each leg hang above the floor units of that leg: the first one above a floor unit of the leg, the next ones rightOf or leftOf it; never put a wall unit on or above the corner article. Prefer a corner article over butting two straight articles together in a corner; a U-shaped kitchen continues a row with a second corner article.\n A root without a relation continues the row of its kind: right of the previous floor-standing root module or wall unit in the list; corrections says so.\n- Docking vectors: groups from get-plan-context show their docking as contextData - per root its ownDockingVector and the dockingVector of each root it names. RightBottom -> LeftBottom puts that root to the right, LeftBottom -> RightBottom to the left, a Top vector -> a Bottom vector on top, BackBottom -> BackBottom back to back. Two root modules that name each other with RightBottom -> LeftBottom stand side by side. freeDockingVectors are the vectors a new root module can dock to; merge-article-into-group names them in dockTo.\n- placement positions a new group, in one of two forms. At a wall or in a room corner: { wall, alignment?, offsetMm?, roomIndex? } - wall a side label (left, right, back, front; back = top, front = bottom in the top-view image) or the index of a wall in the walls array; alignment center (the default), the side label of the adjoining wall to stand flush in the corner the two walls share (wall back with alignment right: the back right corner; with two corner articles the first one in roots goes into the corner), or end; offsetMm moves the group along the wall away from that corner or from the wall's end; roomIndex the room, 0 by default. The server computes the point and the rotation from the calculated group, as place-group does; a group that would overlap another group moves along the wall to the nearest free place, and corrections say so. The wall form stands a new group on the floor; a new group of wall units only hangs at the wall-unit height, which the server sets and corrections name. Anywhere else - an island, the middle of the room - and for a group of wall units only: { posGroup: [x, y, z], posRotationZ, rootId? } - posGroup the room point of the group's back left bottom corner in millimetres - of the whole group, a rear panel behind the row included (z up, z = 0 on the floor; for a group of wall units only, their mounting height), posRotationZ its rotation in degrees, counter-clockwise as seen from above (in the top-view image), required, 0 for no rotation; rootId optional: with two corner articles, the one that goes into the corner posGroup names. A placement is applied exactly once, when the group is created; a placement on a group that is already in the plan is not used (move it with place-group), and groups returned by get-plan-context never carry this field.\n- Walls: every room of get-plan-context carries a walls array - per wall its index, roomIndex, side, name (back wall, front wall, left wall, right wall), start and end (points [x, y, 0] on the floor, in the coordinates of posGroup), lengthMm, type and facingRotationZ, the posRotationZ of a group with its back against that wall (back 0, left 90, front 180, right 270 in a rectangular room); a door or a floor-to-ceiling window splits a wall into several entries of the same side and name - pieces of type wall and the openings between them, each piece of wall free at the floor over its lengthMm, and a window above the floor leaves the floor below it free; a side label names the whole wall, and the server puts the group on its longest piece of wall, or across the openings when no piece is wide enough. Every room carries its index, and the same wall names repeat in every room - a wall a prompt describes is the one of the room the description fits, and a placement names the room with roomIndex (0 by default). Per wall: openings - the doors and windows in it with kind, fromEndMm span and bottomMm/topMm -, slopeFromMm - above that height part of the wall is open: a sloping ceiling or a roof (the room's levels carry the contour per height, pos [x, y, level], level the height above the floor; the slices above 0 are the ceiling). Per room, faces lists each side's whole run of wall pieces - index, side, name, lengthMm, openingMm, openingShare (above 0.5 mostly openings, a glass front; 0 a solid wall), slopeFromMm. For a group anywhere else (an island, the middle of the room, next to a door): any point on the floor as posGroup, any posRotationZ.\n- Room corners: every room of get-plan-context carries a corners list - per corner its name (back left, back right, front left, front right; back = top, front = bottom in the top-view image) and its point. A group in a room corner names one of the two walls as wall and the other as alignment; a corner article first in the group goes into the corner. Looking into the corner from the room, the root modules rightOf the corner article run along the wall on the right, the root modules leftOf it along the wall on the left (the back right corner: rightOf along the right wall, leftOf along the back wall). This holds for both hands of corner article.\n- Obstacles: the obstacles section of get-plan-context lists what stands in the room, in the coordinates of the walls - objects (doors, windows, other furniture) with kind, outline (floor points [x, y, 0]) and bottomMm to topMm, a door or a window also with roomIndex, wall (its index in the walls array) and fromEndMm, its span along that wall measured from the wall's end -, and per group its root modules with id, outline and bottomMm to topMm. Root outlines bound the calculated parts and can reach past the docking edges over a neighbour in the same group - a part over a neighbour is no placement error; two root modules of one group whose bodies overlap are, and the hint of create-or-replace-groups names them. A group goes where the user puts it - the wall, the corner or the spot the user names, also when a door, a window or other furniture is there: the result's hint names what it stands in front of or on, and your answer says so. Where the user leaves the place open, choose a stretch of wall or a spot that obstacles leaves free: fromEndMm is measured from the wall's end, so a placement with that wall, alignment end and offsetMm = the start of a free stretch puts the group on it; base units lower than a window's bottomMm fit below it. Along a wall the user names, choose its free stretch the same way; when none is as wide as the group, put the group on that wall where it stands on the least, and your answer names what it stands on and the alternatives - another wall where it fits, narrower units. A group placed in a room corner reaches along the adjoining wall by its depth: a door or a window of the adjoining wall that begins within that depth of the corner is in its way - when the user leaves the corner open, choose the other corner, or an offsetMm of at least 600 mm from that corner, which keeps the group out of the 600 mm strip in front of the opening. The result's hint names every root module that overlaps an object or another group or stands in front of a door or a window, with the free stretches of its wall; for an obstacle on the group's own wall it names the offsetMm with alignment end of a free stretch the whole group fits, for a group placed by point a free point as posGroup and posRotationZ, and for a group placed at a wall in front of a door or a window of the adjoining wall the offsetMm that keeps it clear.\n- Extending a group: articles next to an existing group are root modules of that group, never a new group. Dock each new article to a free docking vector of the root module it continues (freeDockingVectors per root: a free LeftBottom takes the new root's RightBottom, a free RightBottom takes LeftBottom, a free Top vector takes the new root's Bottom vector) - one article with merge-article-into-group, several at once by adding the picks, each with its relation, to the group from get-plan-context and resubmitting it with its id; an article between two root modules with insert-article-into-group. A new root module inherits the attributes the library passes on between neighbours - fronts, handles, carcase - from the root module it is docked to (insert-article-into-group: the first of between), as in the planner; its attributes override them. Never position a new group against an existing one.\n- To move an existing group, call place-group with wall, alignment and offsetMm at a wall or in a corner, or posGroup and posRotationZ anywhere else. A point names the same back left docking corner as a new group's placement; rootId selects the anchor with two corner articles. The group keeps its roots and docking.\n- To change an existing group, use the command tools: merge-article-into-group adds an article at a free end of a row, insert-article-into-group inserts an article between two root modules, delete-article-and-compact deletes an article and closes the gap, delete-article-in-place deletes an article and leaves the gap (root modules no longer docked together become separate groups where they stand), exchange-root-module replaces a root module - with attributes also by an article of another width -, swap-root-modules lets two root modules change places, delete-group deletes a group, change-module-attribute and change-group-attribute set attributes, merge-groups joins groups where they stand (nothing is moved, no docking is added). Delete and remove mean the same: delete-article-in-place, unless the user asks to close the gap - then delete-article-and-compact. In an insert, a delete that closes the gap, an exchange or a swap the root modules at a wall or in a corner keep their place and the others move; wall units and the range hood move with the root module they hang from. Every command returns the changed groups. To rebuild a group, take it from get-plan-context, change it, and resubmit it with its id and without placement via create-or-replace-groups - it keeps its position; keep the ids of the root modules you keep.\n- Calculated roots, including generated surfaces, carry measured bottomMm and topMm in room-space millimetres when visible geometry and placement are known. These are read-only facts, not input attributes. Missing heights are unknown.\n- Verify results numerically: the returned groups carry position (pos, rotationZ, footprint), standsAt - where the group stands in the words of the plan context: the wall with its fromEndMm span along it (along the whole wall of that side, its pieces joined, measured from its end; the fromEndMm of a door or a window runs along its piece), the corner of a corner group, or a point in the room, with bottomMm/topMm - and per root the dockingVectors, the input attributes, the docking, rowIndex and wall, the wall it stands at - check that each row and each leg of a corner stands at the wall you meant, and name standsAt in your answer instead of deriving the place from the coordinates; the hint names a root module that stands on an obstacle. Do not judge a position from a rendering alone.\n- A root module named by its place - the middle unit, the second from the left, the last one - is found by rowIndex: its place in its row, 1 at the left end as seen from the front, floor units and wall units counted apart - the wall units hanging side by side above a floor row are a row, docked to each other or not. The roots are listed in the order they were added, not in row order.\n- Undo a wrong result: when a result is not what was asked - the wrong wall, a root module missing or replaced by mistake, a merge or a delete that went wrong - send the corrected call instead of correcting the wrong plan piece by piece: a group of the plan is sent again with its id, and the plan keeps it until the replacement is loaded. undo reverts one tool call and leaves the plan without it until the next call: it serves a call that put something where nothing belongs. A group is sent again for a wrong layout - the wall, the corner, articles missing or wrong; other sizes or materials of its root modules are a change, made with the command tools: change-module-attribute, every root module that takes the same value in one call. undo and redo also serve the user who asks for them: the user's last change is everything you changed for their last request, one undo per tool call that changed the plan, and redo brings back as many.\n- Read corrections, notLoaded and hint in a result: corrections lists what the server changed in your input and has already applied, and what the library changed beyond the attribute you set - a front program switched by a front colour -, and a value a module does not take by the library's own check: it is not set on that module, and the sentence names the values the module takes, so send one of them; notLoaded lists the groups and the roots it could not build, with what to send instead; hint names something to check that stopped nothing - a root module on an obstacle, with the free stretches of its wall; a group that reaches past the end of its wall or out of the room, with how far past; when the user left the place open and the hint names a placement that clears what the group stands on, move the group there with place-group in the same turn. A result that says two units now overlap leaves a plan that cannot be built: resolve it in the same turn with one more call - delete one of them or move it - and say how. A change the library cannot calculate is not made and the plan stays as it was: the answer says that nothing was changed - notLoaded for a group of a create, the error result for every other call - with the root modules, the library's message and what to change.\n\nExample 1 - \"a row of three tall units along the right wall, from the back right corner\" is ONE call, create-or-replace-groups, placed at the right wall, flush into its corner with the back wall:\n{ \"posGroups\": [{ \"libraryId\": \"<libraryId>\", \"placement\": { \"wall\": \"right\", \"alignment\": \"back\" }, \"roots\": [\n { \"id\": \"u1\", \"articleId\": \"<articleId from the catalog>\" },\n { \"id\": \"u2\", \"articleId\": \"<articleId>\", \"rightOf\": \"u1\" },\n { \"id\": \"u3\", \"articleId\": \"<articleId>\", \"rightOf\": \"u2\" }\n] }] }\n\nExample 2 - \"a tall unit and two base units with a wall unit above each\" is the same call with these roots - the wall units hang beside the tall unit with the tops flush:\n { \"id\": \"t1\", \"articleId\": \"<tall unit>\" },\n { \"id\": \"b1\", \"articleId\": \"<base unit>\", \"rightOf\": \"t1\" },\n { \"id\": \"b2\", \"articleId\": \"<base unit>\", \"rightOf\": \"b1\" },\n { \"id\": \"w1\", \"articleId\": \"<wall unit>\", \"rightOf\": \"t1\" },\n { \"id\": \"w2\", \"articleId\": \"<wall unit>\", \"rightOf\": \"w1\" }\nWithout the tall unit, the first wall unit hangs above a base unit: { \"id\": \"w1\", \"articleId\": \"<wall unit>\", \"above\": \"b1\" }.\n\nExample 3 - \"an L-shaped kitchen in the back right corner\" (back = top in the top view) is ONE group starting with the corner article c1, placed at the right wall with the back wall as alignment; looking into the corner from the room, the root modules rightOf c1 run along the right wall, the root modules leftOf it along the back wall (see the corner rules above), and the wall units hang above the floor units of their leg:\n{ \"posGroups\": [{ \"libraryId\": \"<libraryId>\", \"placement\": { \"wall\": \"right\", \"alignment\": \"back\" }, \"roots\": [\n { \"id\": \"c1\", \"articleId\": \"<corner article, cornerArticle true>\" },\n { \"id\": \"r1\", \"articleId\": \"<base unit>\", \"rightOf\": \"c1\" },\n { \"id\": \"r2\", \"articleId\": \"<base unit>\", \"rightOf\": \"r1\" },\n { \"id\": \"l1\", \"articleId\": \"<base unit>\", \"leftOf\": \"c1\" },\n { \"id\": \"l2\", \"articleId\": \"<base unit>\", \"leftOf\": \"l1\" },\n { \"id\": \"w1\", \"articleId\": \"<wall unit>\", \"above\": \"r1\" },\n { \"id\": \"w2\", \"articleId\": \"<wall unit>\", \"above\": \"l1\" }\n] }] }\n\nExample 4 - \"the row centred on the back wall\" is \"placement\": { \"wall\": \"back\" } - centred is the default.\n\nExample 5 - \"add a cabinet to the right of the existing cabinets\" extends that group, never a new group: take the group from get-plan-context, find the root module with a free RightBottom (freeDockingVectors) and call merge-article-into-group { \"groupId\": \"<group id>\", \"articleId\": \"<article>\", \"dockTo\": { \"rootId\": \"<that root module>\", \"ownDockingVector\": \"RightBottom\", \"dockingVector\": \"LeftBottom\" } } - the group keeps its position.\n\nExample 6 - \"insert a low cabinet between the high cabinets\" is insert-article-into-group { \"groupId\": \"<group id>\", \"articleId\": \"<a base cabinet from the catalog>\", \"between\": [\"<first root module>\", \"<second root module>\"] }: the high cabinets are the two root modules of the group that stand side by side - whatever the group is, a wardrobe too -, the low cabinet an article about 720 mm high; the root modules on the side away from the wall move by the article's width, the ones at the wall keep their place.`;\n\n// Put before every SKILL.md: how a planning skill meets this session.\nconst SKILL_IN_SESSION =\n 'In this planning session the survey is the plan context - the walls, the doors and windows, the obstacles, the ' +\n 'installation elements with the positions of the electric plugs and the water connections - and the products are the ' +\n 'article catalog. What the plan context does not carry - services beyond those connection positions, budget, ' +\n 'inventory, the household - ' +\n 'is unknown: plan a concept with stated assumptions and name them in your answer, instead of asking first, unless the ' +\n 'user asks to be interviewed. The layout is the groups you create, one group per piece of furniture: check them against ' +\n 'the returned positions and the obstacles, and name the alternatives and the open checks in your answer instead of ' +\n 'building them.';\n\nexport const getAgentReferenceBlocks = (): NonNullable<\n HiAgentPrompts['referenceBlocks']\n> => [{ id: 'authoring-rules', text: AUTHORING_RULES }];\n\n// The plan context carries a signed CDN image URL for every article, module\n// and attribute value - three quarters of its tokens, and no agent can open them.\n// The order data carries them as downloadUri.\nconst withoutImageUrls = (key: string, value: unknown) =>\n key === 'imageUrl' || key === 'downloadUri' ? undefined : value;\n\nconst textResult = (result: unknown) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result ?? null, withoutImageUrls),\n },\n ],\n});\n\nconst PLAN_CHANGING_TOOLS = [\n 'add-interior-fitting',\n 'move-interior-fitting',\n 'delete-interior-fittings',\n 'replace-interior-fitting',\n 'create-or-replace-groups',\n 'place-group',\n 'change-module-attribute',\n 'change-group-attribute',\n 'delete-group',\n 'delete-article-in-place',\n 'delete-article-and-compact',\n 'merge-article-into-group',\n 'insert-article-into-group',\n 'exchange-root-module',\n 'swap-root-modules',\n 'merge-groups',\n 'undo',\n 'redo',\n];\n\nconst ATTRIBUTE_OVERRIDES = z.array(\n z.object({\n id: z.string(),\n value: z.union([z.string(), z.number(), z.boolean()]),\n }),\n);\n\nconst stripDataUrlPrefix = (image: string): string =>\n image.replace(/^data:image\\/\\w+;base64,/, '');\n\nexport const createHiMcpTools = (\n roomDesignerApi: HiMcpPlannerApi,\n): HiAgentTools => {\n // The tools tell their own planner steps from the changes the user makes in\n // the planner by the planner's history events; the handler the planner's UI\n // and the host set keeps running.\n const planHistory = new PlanHistory();\n const { callbacks } = roomDesignerApi.extended;\n const previousHistoryChange = callbacks.onHistoryChange;\n callbacks.onHistoryChange = (undo: boolean, redo: boolean) => {\n planHistory.historyChanged();\n previousHistoryChange?.call(callbacks, undo, redo);\n };\n const plannerApi = createPlannerApi(roomDesignerApi);\n const toolExecutors = createToolExecutors(planHistory);\n\n const tools: HiAgentTools = {};\n const registerTool = (\n name: string,\n {\n description,\n inputSchema,\n }: { description: string; inputSchema: z.ZodRawShape },\n handler: (args: any) => Promise<McpToolResult>,\n ) => {\n tools[name] = mcpTool(name, description, z.object(inputSchema), handler);\n };\n\n // What the agent sent to a tool that changes the plan, and the feedback it\n // got, go to the log as one JSON line each, so a test run can tell what the\n // agent sent and which corrections and errors it saw. The arguments are\n // copied first, so the log shows them as sent. Every call of a\n // tool that changes the plan ends with one feedback or error line, empty\n // feedback included, so a test run can pair the lines in call order.\n // The agent reads and writes plan space, the executors and the planner\n // pos space: the arguments and the result are converted here.\n const runTool = async (tool: string, args: Record<string, unknown>) => {\n console.log(`[hi-mcp] tool ${tool}`);\n const sent = structuredClone(args);\n if (PLAN_CHANGING_TOOLS.includes(tool)) {\n console.log(`[hi-mcp] tool ${tool} args ${JSON.stringify(sent)}`);\n }\n try {\n const inPosSpace = fromAgentFrame(args);\n const result = toAgentFrame(\n tool,\n await toolExecutors[tool](plannerApi, inPosSpace.args),\n ) as any;\n if (inPosSpace.corrections.length > 0) {\n result.corrections = [\n ...inPosSpace.corrections,\n ...(result.corrections ?? []),\n ];\n }\n const { corrections, notLoaded, hint } = result ?? {};\n if (corrections || notLoaded || PLAN_CHANGING_TOOLS.includes(tool)) {\n console.log(\n `[hi-mcp] tool ${tool} feedback ${JSON.stringify({ corrections, notLoaded, hint })}`,\n );\n }\n return result;\n } catch (error) {\n console.log(\n `[hi-mcp] tool ${tool} error ${JSON.stringify({\n message: (error as Error)?.message ?? String(error),\n args: sent,\n })}`,\n );\n throw error;\n }\n };\n\n const fittingId = z.string().min(1);\n const insertion = z\n .tuple([z.number().finite(), z.number().finite(), z.number().finite()])\n .optional()\n .describe(\n 'Millimetres x right, y towards the back, z up, relative to parentModuleId - the frame of a fitting position from get-interior-design-options; to move a fitting by an offset, add it to that position. Omit for the library default on add, or retain actual placement on move/replace. Read calculated result for adjustments.',\n );\n const destination = z.object({\n rootId: fittingId,\n containerModuleId: fittingId,\n parentModuleId: fittingId,\n });\n registerTool(\n 'get-interior-design-options',\n {\n description:\n 'Inspect Interior Design / interior fittings / sub-articles of one loaded HI group without selecting it. Returns unique installed instance IDs, parent-local positions where each fitting starts, compatible additions with destination tuples and fittings[].replacementArticles for each occupied parent. defaultInteriors lists the parts a parent shows of its own while its container holds no fitting; any fitting added to that parent replaces all of them. Choose replacements from that installed fitting, even when no additions fit. articleId filters addition/replacement candidates. Discover before editing; clarify ambiguous instances or unspecified interior changes. Empty options differ from unsupported or failed discovery. To see the fittings in get-plan-images, open the cabinet with open-or-close-article first.',\n inputSchema: {\n groupId: fittingId,\n rootId: fittingId.optional(),\n containerModuleId: fittingId.optional(),\n articleId: fittingId.optional(),\n },\n },\n async (args) =>\n textResult(await runTool('get-interior-design-options', args)),\n );\n registerTool(\n 'add-interior-fitting',\n {\n description:\n \"Add a compatible Interior Design fitting inside a group, using an article and destination returned by get-interior-design-options. Waits for final calculation/load and returns actual instance IDs, placement and corrections. One undoable action when changed. A fitting added to a parent listed in defaultInteriors replaces all the parts listed there; it does not add to them. A fitting the library cannot calculate is not added and the group stays as it was: the error result says that nothing was changed, with the root module and the library's message, and what to send instead.\",\n inputSchema: {\n groupId: fittingId,\n articleId: fittingId,\n destination,\n insertPosition: insertion,\n },\n },\n async (args) => textResult(await runTool('add-interior-fitting', args)),\n );\n registerTool(\n 'move-interior-fitting',\n {\n description:\n \"Reposition one installed interior fitting or transfer it to a compatible container/root within the SAME group. Use its unique instanceId from discovery. Omitted destination keeps the current parent. Supply a destination and/or insertion point. Recreation may change the instance ID; use returned IDs. A fitting the library cannot calculate is not moved and the group stays as it was: the error result says that nothing was changed, with the root module and the library's message, and what to send instead.\",\n inputSchema: {\n groupId: fittingId,\n instanceId: fittingId,\n destination: destination.optional(),\n insertPosition: insertion,\n },\n },\n async (args) => textResult(await runTool('move-interior-fitting', args)),\n );\n registerTool(\n 'delete-interior-fittings',\n {\n description:\n 'Delete the explicitly identified installed interior fittings of one group, preserving the cabinet and unrelated contents. Validates the entire batch before changing anything, deduplicates IDs with a correction, and makes one undoable action.',\n inputSchema: {\n groupId: fittingId,\n instanceIds: z.array(fittingId).min(1),\n },\n },\n async (args) => textResult(await runTool('delete-interior-fittings', args)),\n );\n registerTool(\n 'replace-interior-fitting',\n {\n description:\n \"Atomically replace one installed interior fitting with an article from its replacementArticles in get-interior-design-options, in its current parent, retaining actual placement and compatible settings. An explicit insertion point overrides placement. Failure restores the original; lost settings and new IDs are returned. A fitting the library cannot calculate is not replaced and the group stays as it was: the error result says that nothing was changed, with the root module and the library's message, and what to send instead. Never implement replacement as separate delete and add calls.\",\n inputSchema: {\n groupId: fittingId,\n instanceId: fittingId,\n articleId: fittingId,\n insertPosition: insertion,\n },\n },\n async (args) => textResult(await runTool('replace-interior-fitting', args)),\n );\n const VIEW_ONLY =\n 'It is a view of the planner: it changes nothing in the plan, is not saved, is not part of undo and changes ' +\n 'neither the price nor the order.';\n registerTool(\n 'open-or-close-group',\n {\n description:\n 'Opens (open true) or closes (open false) every door and drawer of a group at once, so get-plan-images ' +\n 'shows the group as it is - open it to look inside its cabinets. ' +\n VIEW_ONLY +\n ' Returns the groupId and doorsAndDrawers, open or closed - the state they are in now; a group without ' +\n 'doors or drawers is named in corrections instead.',\n inputSchema: {\n groupId: z\n .string()\n .describe('The id of the group, as get-plan-context shows it.'),\n open: z.boolean().describe('true opens, false closes.'),\n },\n },\n async (args) => textResult(await runTool('open-or-close-group', args)),\n );\n registerTool(\n 'open-or-close-article',\n {\n description:\n 'Opens (open true) or closes (open false) the doors and drawers of one root module at once, none of the ' +\n 'root modules next to it, so get-plan-images shows the cabinet as it is - open it to look inside, at its ' +\n 'interior fittings for example. ' +\n VIEW_ONLY +\n ' Returns the rootModuleId and doorsAndDrawers, open or closed - the state they are in now; a root ' +\n 'module without doors or drawers is named in corrections instead.',\n inputSchema: {\n rootModuleId: z\n .string()\n .describe('The id of the root module, as get-plan-context shows it.'),\n open: z.boolean().describe('true opens, false closes.'),\n },\n },\n async (args) => textResult(await runTool('open-or-close-article', args)),\n );\n\n registerTool(\n 'get-plan-context',\n {\n description:\n MOUNTING_GUIDANCE +\n ' Returns a snapshot of the HI planning session - one coordinate system throughout, that of the planner: 3D, ' +\n 'right-handed, Z up, in millimetres, x to the right and y to the top of the top-view image, z = 0 on the ' +\n 'floor (room contours use pos: [x, y, level]). Default ' +\n 'sections: rooms (every room carries its index, its contour levels with 3D segments (pos [x, y, level], ' +\n 'level the height above the floor - the slices above 0 are the ceiling, a sloping ceiling reads from them), ' +\n 'a derived walls array - per wall: index, roomIndex, a side label (left/right/top/bottom as seen in the ' +\n 'top-view image), start/end [x, y, 0] in millimetres (the 3D contour points on the floor), lengthMm, type ' +\n '(wall, or opening for a door or a floor-to-ceiling window), heightMm, thicknessMm and facingRotationZ - the ' +\n 'posRotationZ of a group standing with its back against that wall -, openings (the doors and windows in it: ' +\n 'kind, fromEndMm span, bottomMm/topMm) and slopeFromMm where it applies - and its faces, per ' +\n 'side the whole run of wall pieces with index, side, name, lengthMm, openingMm, openingShare and slopeFromMm), ' +\n 'articles (compact catalog: articleId, ' +\n 'name, desc - what the article is and when to pick it -, category, and per root module its master-data module, dimensions (the size attributes - ' +\n 'e.g. Width, Depth, Height - with their values in millimetres), main attribute values, ' +\n 'docking vector names, insert levels and sub-modules, plus cornerArticle ' +\n 'for articles made for a room corner), attributes (the attribute vocabulary: per library every ' +\n 'attribute with id, name, desc, group and type - the ids ' +\n \"the catalog's mainAttributes, the roots' attributes and their sub modules' attributes carry -, with its values - value, name, desc - \" +\n 'for the attributes a planning sets at the create and valueCount, the number of its values, for every other one, ' +\n 'whose values find-attributes returns by its id; a value list several attributes share is ' +\n 'listed once, sameSelectionsAs names the attribute that lists it; send a value, not its name - ' +\n 'a name, desc or colour code sent as the value is read as that value and named in corrections), ' +\n \"groups (calculated roots include read-only measured bottomMm/topMm in room-space millimetres, including generated surfaces; missing heights are unknown; the groups currently in the plan: position with pos - the room point of the group's back left bottom corner, as a placement names it - rotationZ, rootId (only with two corner articles: the one pos belongs to) and footprint (the x and y ranges of the group from pos, its front towards -y), and standsAt, where the group stands in the words of the plan context - the wall with its fromEndMm span along it (along the whole wall of that side, its pieces joined, measured from its end; the fromEndMm of a door or a window runs along its piece), the corner of a corner group, or a point in the room, with bottomMm/topMm -, and \" +\n 'per root the article pick with input attributes, docking, docking vector names and the free docking vectors ' +\n 'a new root can dock to, plus its desc, its subModules with their input attributes and its rowIndex, its place in its row - 1 at the left end as seen from the ' +\n 'front; floor units and wall units form rows of their own, and the roots are listed in the order they were added -, ' +\n 'and its wall, the name of the wall it stands at; ' +\n 'no root positions, ' +\n 'no geometry; a returned group is a valid create-or-replace-groups payload) and obstacles (what stands in the ' +\n 'room, in the coordinates of the walls: objects - doors, windows, other furniture - with kind, outline ' +\n \"(floor points [x, y, 0]) and bottomMm/topMm, a door or a window also with roomIndex, wall and fromEndMm (its span along that wall from the wall's end); \" +\n 'and per group its root modules with id, outline and bottomMm/topMm), ' +\n 'and installationElements (the electric plugs and the water connections of the plan: per element its type - ' +\n 'ElectricPlug or WaterConnection - and its position [x, y, z] in the coordinates of the walls, z its height; a ' +\n 'position only, no size, and no obstacle: a group may stand on a supply). ' +\n 'When an edit gives a row a new end - an article added, exchanged or swapped at an end, an end ' +\n 'article deleted, or a delete that leaves the gap and splits the row into two rows -, hinge its ' +\n 'end doors at the outer sides: left at the left end, ' +\n 'right at the right end, as seen from the front. A single door that is a row of its own keeps its side. ' +\n \"Choose the attribute and value from the library's \" +\n 'descriptions for single or paired doors, and keep other door directions unchanged. ' +\n 'Root outlines bound the calculated parts and can reach past the docking edges over a neighbour in the same group - ' +\n 'a part over a neighbour is no placement error; two root modules of one group whose bodies overlap are, and the ' +\n 'hint of create-or-replace-groups names them. ' +\n 'When a door or window determines a placement, briefly name it and explain whether the final placement ' +\n 'keeps it clear, using the returned obstacle dimensions and final tool results. masterData (per library the root ' +\n 'modules with their attribute ids, the attributes and the group settings) is returned only when included ' +\n 'explicitly. desc - what an article is and when to pick it - is enough to choose an article; ' +\n 'articleDescriptions (per article its full description: purpose, placement, requirements, neighbours, ' +\n 'restrictions, style) is returned only when included explicitly and answers a question about one ' +\n 'article, not the planning. Every desc is ' +\n 'authoritative and dimensions give the size - trust them over the catalog images (imageUrl); a colour ' +\n 'code in the desc of an attribute value (#rrggbb) is the colour of that value. ' +\n 'A root or a group that carries calculationError is not built: the library could not calculate it with its ' +\n 'attribute values, and calculationError is the first line of its message. Until a value the library can ' +\n 'calculate replaces the one that failed it has no docking vectors and no parts - say so in the answer and ' +\n 'never describe it as planned. The groups of a tool result carry the field as well. Use it before ' +\n 'authoring or modifying groups. When the current library articles and attributes are already supplied, ' +\n 'request rooms, groups, obstacles and installationElements for fresh plan state; retrieve library sections only when missing.',\n inputSchema: {\n include: z\n .array(z.string())\n .optional()\n .describe(\n 'The sections to include: rooms, articles, attributes, groups, obstacles, installationElements, masterData, articleDescriptions. Default: rooms, articles, attributes, groups, obstacles and installationElements. ' +\n 'Add masterData for the root modules of the master data, articleDescriptions for a question about ' +\n \"one article's requirements and neighbours - desc is enough to pick the articles of a planning.\",\n ),\n },\n },\n async ({ include }) =>\n textResult(await runTool('get-plan-context', { include })),\n );\n\n registerTool(\n 'find-attributes',\n {\n description:\n 'Answers a question about an attribute: searches the attribute vocabulary - the attributes section of ' +\n 'get-plan-context - by text (attribute id, name, description, ' +\n 'group or selection name) or by ids and returns the matching attributes with their values (each with ' +\n 'its desc) and the root modules and sub modules that carry them, with their names - the worktop colour is the colour of ' +\n 'the root module Countertop; the attributes the root modules in the plan and their sub modules carry come first. ' +\n 'Your answer names the attribute by its name and its id - several attributes can share a name - with the values it lists. ' +\n 'The attributes section holds every attribute and the values of those a planning sets at the create; ' +\n 'for an attribute it shows with valueCount, send its id in ids to get its values - several ids in one call, ' +\n 'e.g. every attribute of one change. Search by text for the modules that carry an attribute, or for a property - e.g. \"front color\" - whose ' +\n 'attribute the section does not make obvious. Every word of the text is matched on ' +\n 'its own, in any order, British and American spelling alike (colour and color, grey and gray, worktop ' +\n 'and countertop): one search for \"color\" returns every colour attribute - front, carcase, countertop, ' +\n 'toe kick and the others - with their values, and a value list several attributes share is listed once ' +\n '(sameSelectionsAs names the attribute that lists it). The desc of a value carries ' +\n 'its colour code where the library gives one - Cloudy blue (#506080) -, the colour of that value: ' +\n 'pick a dark, a light or a blue value by its code.',\n inputSchema: {\n text: z\n .string()\n .optional()\n .describe('The words to search for, case-insensitive.'),\n ids: z\n .array(z.string().min(1))\n .optional()\n .describe(\n 'Attribute ids: returns these attributes with their values, several in one call.',\n ),\n libraryId: z\n .string()\n .optional()\n .describe('Restricts the search to one library.'),\n },\n },\n async ({ text, ids, libraryId }) =>\n textResult(await runTool('find-attributes', { text, ids, libraryId })),\n );\n\n registerTool(\n 'get-authoring-rules',\n {\n description:\n 'Returns the authoring rules for pos groups: the payload format of create-or-replace-groups, the root ' +\n 'module fields, how to position a new group with a placement and move an existing one with place-group, ' +\n 'the relations a unit names its neighbour with (rightOf, leftOf, onTop, above, behind), the docking vector ' +\n 'names of existing groups, and complete examples for a row against a wall, wall units beside a tall unit, ' +\n 'a group around a room corner and extending a group. Use the supplied authoring rules or fetch this before authoring pos groups when they are missing.',\n inputSchema: {},\n },\n async () => ({\n content: [{ type: 'text' as const, text: AUTHORING_RULES }],\n }),\n );\n\n registerTool(\n 'get-skill',\n {\n description:\n 'Returns a planning skill with the reference it asks to read before planning, in one result: how to plan a room of one kind, ' +\n 'or from an image the user sends, well - the workflow, the zones, the dimensions and the checks. Before planning a room ' +\n 'of a kind listed here, or from an image, follow its skill; use supplied files. file fetches one file of a skill, e.g. its optional source catalog. ' +\n 'Apply only the relevant kind and region; the France kitchen skill replaces the general kitchen skill in France. Skills:\\n' +\n skillIndex(skills),\n inputSchema: {\n name: z.string().describe('The name of the skill'),\n file: z\n .string()\n .optional()\n .describe(\n 'A file of the skill by its path, e.g. references/source-catalog.md; SKILL.md with its planning reference by default',\n ),\n },\n },\n async ({ name, file }) => {\n const text = (await runTool('get-skill', { name, file })) as string;\n const preamble = isSkillFile(file) ? `${SKILL_IN_SESSION}\\n\\n` : '';\n return {\n content: [{ type: 'text' as const, text: `${preamble}${text}` }],\n };\n },\n );\n\n // The payload format of create-or-replace-groups, declared so the schema a\n // model reads first carries the field names. The objects stay open\n // (looseObject): the AI SDK adds additionalProperties: false to nested\n // objects, and a closed object would refuse the fields a model guesses\n // before the server can correct them - the server maps them and names the\n // mapping in corrections. For the same reason the numbers take a string too\n // (a number a model writes as text is read by the server and named) and\n // articleId and roots stay optional: the server answers per group, a typed\n // required field would refuse the whole call at validation.\n const aNumber = z.union([z.number(), z.string()]).optional();\n const posGroupAttributes = z\n .union([\n z.array(\n z.looseObject({\n id: z.string().optional().describe('The attribute id'),\n value: z.unknown().describe('The attribute value'),\n }),\n ),\n z.record(z.string(), z.unknown()),\n ])\n .optional()\n .describe(\n 'Attribute overrides as [{ id, value }]; an object of ids and values is read as such',\n );\n const posGroupPlacement = z.looseObject({\n wall: z\n .union([z.string(), z.number()])\n .optional()\n .describe(\n 'At a wall or in a room corner: a side label (left, right, back, front) or the index of a wall in the walls array of get-plan-context; the wall form stands the group on the floor - a group of wall units only hangs at the wall-unit height',\n ),\n alignment: z\n .string()\n .optional()\n .describe(\n 'center (the default), end, start, or the side label of an adjoining wall to stand flush into that corner',\n ),\n offsetMm: aNumber.describe(\n 'Moves the group along the wall away from that corner or from the wall end, in millimetres - a number',\n ),\n roomIndex: aNumber.describe(\n 'The room of the plan, 0 by default - a number',\n ),\n posGroup: z\n .array(z.union([z.number(), z.string()]))\n .min(2)\n .max(3)\n .optional()\n .describe(\n 'Anywhere else: the room point of the group back left corner [x, y, z] in millimetres - numbers; z = 0 on the floor is completed',\n ),\n posRotationZ: aNumber.describe(\n 'The rotation in degrees, counter-clockwise as seen from above - a number',\n ),\n rootId: z\n .string()\n .optional()\n .describe('With two corner articles, the one that goes into the corner'),\n });\n const posGroupRoot = z.looseObject({\n id: z\n .string()\n .optional()\n .describe(\n 'A unique id of the root module within its group; the relations of the other roots name this id',\n ),\n articleId: z\n .string()\n .optional()\n .describe(\n 'The article id from the article catalog of get-plan-context; a root without one is not built, the others are',\n ),\n libraryId: z.string().optional().describe('The library of the article'),\n attributes: posGroupAttributes.describe(\n 'Attribute overrides of this root module',\n ),\n contextData: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\n 'The docking of a group returned by get-plan-context, resubmitted as it is',\n ),\n rightOf: z\n .string()\n .optional()\n .describe(\n 'The id of the root module this one stands right of, as seen from the front',\n ),\n leftOf: z\n .string()\n .optional()\n .describe(\n 'The id of the root module this one stands left of, as seen from the front',\n ),\n onTop: z\n .string()\n .optional()\n .describe('The id of the root module this one stands on top of'),\n above: z\n .string()\n .optional()\n .describe(\n 'The id of the floor-standing root module this wall unit hangs above',\n ),\n behind: z\n .string()\n .optional()\n .describe('The id of the root module this one stands back to back with'),\n align: z\n .string()\n .optional()\n .describe(\n 'With onTop or above: which edges line up - left (the default), right or back',\n ),\n gapMm: aNumber.describe(\n 'With onTop or above: the clearance below, in millimetres - a number',\n ),\n });\n const posGroup = z.looseObject({\n id: z\n .string()\n .optional()\n .describe(\n 'The group id; an id of an existing group replaces that group and keeps its position',\n ),\n libraryId: z.string().optional().describe('The library of the group'),\n placement: posGroupPlacement\n .optional()\n .describe(\n 'Positions a new group; not used on a group already in the plan',\n ),\n attributes: posGroupAttributes.describe(\n 'A material for the whole group, set on every root module',\n ),\n roots: z\n .array(posGroupRoot)\n .optional()\n .describe(\n 'Every root module of the group from the first call, each after the first naming its neighbour with one relation; non-empty - a group without roots is not built, the others are',\n ),\n });\n\n registerTool(\n 'create-or-replace-groups',\n {\n description:\n MOUNTING_GUIDANCE +\n ' Creates or replaces HI object groups in the plan from an array of pos groups. Roots are article picks ' +\n '({ id, articleId, attributes? }) - the server completes them from the article template -, and every root ' +\n 'after the first names its neighbour with one relation: rightOf, leftOf, onTop, above or behind with the ' +\n 'id of the neighbour; the server builds the docking from it, and the planner arranges the root modules; never author root ' +\n 'positions. Author one piece of furniture as ONE group: articles beside, above or back to back with each other are ' +\n \"related root modules of the same group, never separately positioned groups; a material for the whole group goes into the group's attributes, and a root module's own value of it stays. \" +\n 'A group is created with all its articles in one call: roots holds every article of the group from the first call, each with its relation - a group is never created empty and filled later. ' +\n 'An article beside an existing group goes into that group: merge-article-into-group at the end of a row, insert-article-into-group between two root modules. ' +\n 'Position a new group in the same ' +\n 'call with placement. At a wall or in a room corner: { wall, alignment?, offsetMm?, roomIndex? } - wall a ' +\n 'side label (left, right, back, front) or a wall index; alignment center (the default), the side label ' +\n 'of the adjoining wall, which puts the group flush into that corner (wall back with alignment right: the ' +\n 'back right corner) and a group that starts with a corner article into the corner, or end; offsetMm moves ' +\n \"it along the wall away from that corner or from the wall's end - the fromEndMm of the obstacles is \" +\n 'measured from there; roomIndex the room, 0 by default. The server computes the point and the rotation. ' +\n 'Anywhere else, an island or ' +\n \"a free spot: { posGroup, posRotationZ }, the room point of the group's back left corner and its \" +\n 'rotation. A group whose id matches an existing group completely ' +\n 'replaces that group and keeps its position (root modules keep their ids when they already exist in ' +\n 'the replaced group; a placement on it is not used; a root module the replace adds inherits ' +\n 'the attributes the library passes on between neighbours - fronts, handles, carcase - from the root module it is docked to, and its attributes override them); ' +\n 'the replace is the rebuild - a wrong layout, wall or set of articles: take the group from ' +\n 'get-plan-context, change it and resubmit it with its id. A single edit has its own tool, named by the ' +\n 'words the user says: \"move\" - place-group, \"add one more\" - merge-article-into-group, \"put one between\" - ' +\n 'insert-article-into-group, \"exchange\" or \"wider\" - exchange-root-module, \"swap the two\" - swap-root-modules, ' +\n '\"delete\" - delete-article-in-place, \"change the colour\" - change-module-attribute or change-group-attribute. ' +\n 'all other groups are created with regenerated ids. Returns the loaded object ids, the groups of the call - ' +\n 'each with standsAt, where it stands in the words of the plan context, position with pos and footprint, and its root modules with their article ids - check the position and the count and kinds of units against what the user asked for - and otherGroupIds, the other groups of the plan, unchanged; plus groupAttributes (per group the group attributes set on every unit, ' +\n 'notCarried: attributes no current module carries. For a requested part the library generates, use find-attributes to look for an enabling attribute on the units; ' +\n \"if available, enable it with change-group-attribute after the group is built, then set the part's attributes - a part the library cannot calculate leaves that change unmade and the group as it is. Report only what is still missing. \" +\n 'rootValues: the root modules that keep their own value of one), corrections (what ' +\n 'the server changed in the input, and what the library ' +\n 'changed beyond the attributes sent - a front colour reset by a front program -, and a value of a root or of the group ' +\n \"a root module does not take by the library's own check, which is left out on it, with the values it takes), notLoaded (the groups or \" +\n 'roots it could not build, with what to send instead) and hint (the root modules each built group has, with their articles, a root module that overlaps another root module of its own group, a root module on an obstacle, in another group or in front of ' +\n 'a door or a window, with the free stretches of its wall, the offsetMm and alignment that clear an obstacle on its own wall, a free point for a point placement, and the offsetMm that clears an opening of the adjoining wall). ' +\n \"A group the library cannot calculate is not built and the plan stays as it was: notLoaded says that nothing was changed for it, with the root modules and the library's message; the other groups of the call are built. \" +\n 'The payload format is returned by get-authoring-rules.',\n inputSchema: {\n posGroups: z\n .array(posGroup)\n .min(1)\n .describe(\n 'The pos groups to create or replace, following the rules returned by get-authoring-rules.',\n ),\n },\n },\n async ({ posGroups }) =>\n textResult(await runTool('create-or-replace-groups', { posGroups })),\n );\n\n registerTool(\n 'place-group',\n {\n description:\n 'The tool for \"move\": when the user asks to move, shift or slide an existing group - \"move it to the ' +\n 'other wall\", \"into the back right corner\" - this tool moves it to a wall, a room corner, or a point ' +\n 'and rotation, and reloads it there. ' +\n 'For a freestanding group use posGroup [x, y, z] and posRotationZ: the same placement-frame docking corner and counter-clockwise angle as a new group. rootId selects the anchor with two corner articles. Explicit point targets are kept, including outside the room, with obstacle hints. ' +\n 'At a wall, the ' +\n \"server computes the position from the wall, the alignment and the group's calculated footprint; a \" +\n 'group with a corner article goes into the corner when the alignment names the adjoining wall. A ' +\n 'target that overlaps another group moves along the wall to the nearest free position; corrections in ' +\n 'the result say so. Name the wall by its side ' +\n 'label (left/right/top/bottom as seen in the top-view image) or its index in the walls array of ' +\n 'get-plan-context. Use it to move a group that is already in the plan; a new group takes the same ' +\n 'wall, alignment and offsetMm in its placement in create-or-replace-groups. Returns placedIn (corner, ' +\n 'wall or point), the wall for wall/corner targets, the resulting group and a hint when a root module stands on an object or in front of ' +\n 'a door or a window, with the placement that clears it.',\n inputSchema: {\n groupId: z\n .string()\n .describe(\n 'The id of the group to move. A unique id prefix is accepted.',\n ),\n wall: z\n .union([\n z.enum(['left', 'right', 'top', 'bottom', 'back', 'front']),\n z.number().int().min(0),\n ])\n .optional()\n .describe(\n \"The target wall: a side label as seen in the top view ('right' is the whole right wall, its \" +\n \"doors and floor-to-ceiling windows included; 'back' is 'top', 'front' is 'bottom') or a \" +\n 'wall index from the walls array of get-plan-context, which names one piece of a wall.',\n ),\n roomIndex: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('The index of the room in the rooms array. Defaults to 0.'),\n alignment: z\n .enum([\n 'start',\n 'center',\n 'end',\n 'left',\n 'right',\n 'top',\n 'bottom',\n 'back',\n 'front',\n ])\n .optional()\n .describe(\n \"Where the group sits along the wall: 'center' (default), 'start'/'end' (the wall's endpoints), \" +\n 'or the side label of an adjoining wall to sit flush in that corner (e.g. wall \"right\" + ' +\n 'alignment \"top\" is the back right corner in the top view).',\n ),\n offsetMm: z\n .number()\n .optional()\n .describe(\n 'Extra distance in millimetres along the wall from the chosen alignment. Defaults to 0.',\n ),\n posGroup: z\n .array(z.number())\n .min(2)\n .max(3)\n .optional()\n .describe(\n 'Point target: the placement-frame back left bottom corner [x, y, z] in plan-space millimetres; z is height, omitted z means floor.',\n ),\n posRotationZ: z\n .number()\n .optional()\n .describe(\n 'With posGroup, the rotation in degrees counter-clockwise as seen from above; 0 is valid.',\n ),\n rootId: z\n .string()\n .optional()\n .describe(\n 'With a point target and two corner articles, the root whose docking corner the point names.',\n ),\n },\n },\n async (args) => textResult(await runTool('place-group', args)),\n );\n\n registerTool(\n 'change-module-attribute',\n {\n description:\n 'The tool for \"change the colour of ...\", \"make it wider\" and every other change of one attribute: ' +\n 'sets one attribute of one or more root modules in the plan and of their sub modules that carry it - ' +\n 'a size change (\"wider\", \"900 mm wide\") is the size attribute by its id from the catalog (the dimensions ' +\n 'of the article name the attribute and its value in millimetres), never its name - ' +\n 'the front colour of a root module reaches its fronts -, or with moduleId of that one sub module of ' +\n 'each root module only, and recalculates their groups: name every root module that gets the value in ' +\n 'one call, e.g. the accent fronts of a row. The root modules may belong to one group or to several. ' +\n 'The ids are the ones get-plan-context shows (a sub module by its id in ' +\n 'subModules); attribute ids and values are in the attributes section of get-plan-context, the values of an attribute with valueCount come from find-attributes with its id; send the value of a selection, not its name - a name or desc is read as the value and named in corrections. ' +\n 'The library may change a related attribute with it - a front colour the front program does not offer ' +\n 'switches the program, and the fronts are built differently; corrections name every attribute the ' +\n 'library changed besides the one set. ' +\n \"A value a root module does not take by the library's own check is not set on it; corrections name the values it takes, with their names. \" +\n \"A value the library cannot calculate a root module with is not set and the group stays as it was: the error result says that nothing was changed, with the root modules and the library's message. \" +\n 'Returns the ids of the changed groups and modules and the corrections; get-plan-context shows the groups.',\n inputSchema: {\n rootModuleIds: z\n .array(z.string())\n .optional()\n .describe('The ids of the root modules that get the value.'),\n rootModuleId: z\n .string()\n .optional()\n .describe('The id of a single root module, as one of rootModuleIds.'),\n moduleId: z\n .string()\n .optional()\n .describe(\n 'The id of the sub module. Omit to change the root modules and their sub modules that carry the attribute.',\n ),\n attributeId: z.string().describe('The id of the attribute.'),\n value: z\n .union([z.string(), z.number(), z.boolean()])\n .describe(\n 'The new value: the value of a selection of the attribute (the attributes section lists each value with its name and desc) - a string, a number or a boolean; a name or desc is read as the value.',\n ),\n },\n },\n async (args) => textResult(await runTool('change-module-attribute', args)),\n );\n\n registerTool(\n 'change-group-attribute',\n {\n description:\n 'The tool for \"the whole group in ...\", \"all of them in white\": sets attributes on every module of a ' +\n 'group that has them - the root modules and their sub ' +\n 'modules, e.g. the front colour of a whole group - in one recalculation: one attribute with attributeId ' +\n 'and value, several at once with attributes - all the materials of a group in one call, the programs set ' +\n 'before the colours; attribute ids and values are in the attributes section of get-plan-context, and a ' +\n 'value sent by its name or desc is read as the value and named in corrections. ' +\n 'The library may change a related attribute with it - a front colour the front program does not offer ' +\n 'switches the program, and the fronts are built differently; corrections name every attribute the ' +\n 'library changed besides the ones set, and an attribute no module of the group has. ' +\n \"A value a root module does not take by the library's own check is not set on it; corrections name the values it takes, with their names. \" +\n \"A value the library cannot calculate a root module with is not set and the group stays as it was: the error result says that nothing was changed, with the root modules and the library's message. \" +\n 'Returns the id of the group, the ids of the changed modules and the corrections; get-plan-context shows the group.',\n inputSchema: {\n groupId: z\n .string()\n .describe('The id of the group. A unique id prefix is accepted.'),\n attributeId: z\n .string()\n .optional()\n .describe('The id of the attribute, with value.'),\n value: z\n .union([z.string(), z.number(), z.boolean()])\n .optional()\n .describe(\n 'The new value: the value of a selection of the attribute (the attributes section lists each value with its name and desc) - a string, a number or a boolean; a name or desc is read as the value.',\n ),\n attributes: z\n .array(\n z.object({\n attributeId: z.string(),\n value: z.union([z.string(), z.number(), z.boolean()]),\n }),\n )\n .min(1)\n .optional()\n .describe(\n 'Several attributes set in one recalculation: [{ attributeId, value }].',\n ),\n },\n },\n async (args) => textResult(await runTool('change-group-attribute', args)),\n );\n\n registerTool(\n 'delete-group',\n {\n description:\n 'The tool when the user asks to delete or remove a whole group, not one article of it ' +\n '(delete-article-in-place): deletes a group with all its root modules from the plan. Returns the ' +\n 'id of the deleted group.',\n inputSchema: {\n groupId: z\n .string()\n .describe('The id of the group. A unique id prefix is accepted.'),\n },\n },\n async (args) => textResult(await runTool('delete-group', args)),\n );\n\n registerTool(\n 'delete-article-in-place',\n {\n description:\n 'Deletes an article from its group and leaves the gap - the tool for \"delete\" or \"remove\" when the user does ' +\n 'not ask to close the gap: every other root module keeps its place; root modules that are no longer ' +\n 'docked together afterwards become separate groups where they stand, and deleting the only root module deletes ' +\n 'the group. To close the gap, use delete-article-and-compact. Generated roots (worktop, toe kick) ' +\n 'cannot be deleted - the library regenerates them. Returns the remaining groups.',\n inputSchema: {\n rootModuleId: z.string().describe('The id of the root module.'),\n },\n },\n async (args) => textResult(await runTool('delete-article-in-place', args)),\n );\n\n registerTool(\n 'delete-article-and-compact',\n {\n description:\n 'Deletes an article from its group and closes the gap - the tool when the user asks to close the gap (move ' +\n 'the others up, keep the row together): the root modules beside it are docked together, and the ' +\n 'root modules at a wall or in a corner keep their place. A wall unit or a range hood that hung from the ' +\n 'deleted root module hangs from the one that moves into the gap - unless that one carries a unit above already: ' +\n 'then it keeps its place, and the result names the units that now overlap. A root module with a neighbour on one side only is deleted and ' +\n 'nothing else moves. Deleting a corner article between two legs closes the gap as well: one leg turns by 90 ' +\n 'degrees, with the units above it, and is docked to the other, so the legs form one straight row - the result ' +\n 'names the leg that turned. Deleting the only root module deletes the group. To leave the gap, ' +\n 'use delete-article-in-place. Generated roots ' +\n '(worktop, toe kick) cannot be deleted - the library regenerates them. Returns the changed group.',\n inputSchema: {\n groupId: z\n .string()\n .optional()\n .describe(\n 'The id of the group, optional - left out, the server takes the group of the root module. ' +\n 'A unique id prefix is accepted.',\n ),\n rootModuleId: z.string().describe('The id of the root module.'),\n },\n },\n async (args) =>\n textResult(await runTool('delete-article-and-compact', args)),\n );\n\n registerTool(\n 'merge-article-into-group',\n {\n description:\n 'The tool for \"add one more\", \"extend the row\": adds one article to an existing group as a new root ' +\n 'module, docked to a ' +\n 'free docking vector of a root module of the group, the way the authoring rules describe docking. dockTo ' +\n \"names the root module the article continues, that root module's free vector (one of its freeDockingVectors in \" +\n \"get-plan-context) and the new root module's vector: RightBottom -> LeftBottom puts it to the right, \" +\n 'LeftBottom -> RightBottom to the left, LeftTop -> LeftBottom hangs a wall unit or a range hood above ' +\n 'a floor-standing root module at the height of the wall units. For an article mounted above a floor unit, ' +\n 'the server sets the gap when offset has no z value; a supplied z value is the clearance, and an explicit zero stays zero. The new root module inherits ' +\n 'the attributes the library passes on between neighbours - fronts, handles, carcase - from the root module of dockTo, as in the planner; attributes override them. ' +\n 'To put an article between two root modules, use insert-article-into-group. The group keeps its position. Returns the changed group.',\n inputSchema: {\n groupId: z\n .string()\n .describe('The id of the group. A unique id prefix is accepted.'),\n articleId: z.string().describe('The article id from the catalog.'),\n attributes: ATTRIBUTE_OVERRIDES.optional().describe(\n 'Attribute overrides of the new root module: [{ id, value }].',\n ),\n dockTo: z\n .object({\n rootId: z\n .string()\n .describe(\n 'The id of the root module of the group the new article docks to.',\n ),\n ownDockingVector: z\n .string()\n .describe(\n \"That root module's free docking vector, e.g. RightBottom.\",\n ),\n dockingVector: z\n .string()\n .describe(\n \"The new root module's docking vector that meets it, e.g. LeftBottom.\",\n ),\n mode: z\n .enum(['StartStart', 'EndEnd', 'StartEnd', 'EndStart'])\n .optional()\n .describe(\n 'Which endpoints of the two vectors coincide. Default StartStart; back to back (BackBottom -> BackBottom) StartEnd, as behind places it.',\n ),\n offset: z\n .tuple([z.number(), z.number(), z.number()])\n .optional()\n .describe(\n '[x, y, z] in millimetres added after docking. For an article mounted above a floor-standing root module, omit offset to let the server set the hang gap; a supplied z value sets the clearance, including zero. Otherwise the default is [0, 0, 0].',\n ),\n })\n .describe('Where the new root module docks.'),\n },\n },\n async (args) => textResult(await runTool('merge-article-into-group', args)),\n );\n\n registerTool(\n 'insert-article-into-group',\n {\n description:\n 'The tool for \"put one between\": inserts one article from the catalog between two root modules of an ' +\n 'existing group that stand side by side - ' +\n 'whatever the group is and whatever the article is: a low cabinet between two high cabinets or wardrobes too; the user ' +\n 'decides what stands between what. between names the two root modules, in either order; a group of two root modules ' +\n 'has one place to insert: between them. No gap is needed - the tool makes room. The new root module is docked to both; the root modules at a wall or in a ' +\n \"corner keep their place, the others move by the article's width. Wall units and the range hood move with the \" +\n 'root module they hang from. The new root module inherits the attributes the library passes on between neighbours - fronts, handles, carcase - from the first root module of between, ' +\n 'as in the planner; attributes override them. To add an article beside the last root module of a row, use merge-article-into-group. ' +\n 'Returns the changed group.',\n inputSchema: {\n groupId: z\n .string()\n .describe('The id of the group. A unique id prefix is accepted.'),\n articleId: z.string().describe('The article id from the catalog.'),\n attributes: ATTRIBUTE_OVERRIDES.optional().describe(\n 'Attribute overrides of the new root module: [{ id, value }].',\n ),\n between: z\n .tuple([z.string(), z.string()])\n .describe(\n 'The ids of the two root modules that stand side by side and take the new article between them, in either order.',\n ),\n },\n },\n async (args) =>\n textResult(await runTool('insert-article-into-group', args)),\n );\n\n registerTool(\n 'exchange-root-module',\n {\n description:\n 'The tool for \"exchange\", \"swap the X for a Y\", \"make it wider, 900 mm wide\": replaces one root module ' +\n 'of a group with an article from the catalog that has one root ' +\n 'module, e.g. a base cabinet with a drawer cabinet; the new root module takes over the position, the docking and ' +\n 'the attributes the library passes on between neighbours - fronts, handles, carcase - of the replaced one, as in the planner; attributes override them - another size of the article, set by its size attribute id from the catalog (the dimensions of the article name the attribute and its value in millimetres), e.g. a cabinet 900 mm wide: ' +\n 'the other root modules move by the difference, and the ones at a wall keep their ' +\n 'place. A docking the new article cannot take is named in corrections. Returns the changed group.',\n inputSchema: {\n groupId: z\n .string()\n .describe('The id of the group. A unique id prefix is accepted.'),\n rootModuleId: z\n .string()\n .describe('The id of the root module to replace.'),\n articleId: z.string().describe('The article id from the catalog.'),\n attributes: ATTRIBUTE_OVERRIDES.optional().describe(\n 'Attribute overrides of the new root module: [{ id, value }].',\n ),\n },\n },\n async (args) => textResult(await runTool('exchange-root-module', args)),\n );\n\n registerTool(\n 'swap-root-modules',\n {\n description:\n 'The tool for \"swap the two units\", \"change their places\": lets two root modules of a group change ' +\n 'places, neighbours or not. Each keeps its attributes, and the ' +\n 'wall units and the range hood hanging from a root module move with it. The group keeps its length, and the root modules ' +\n 'at a wall keep their place. Returns the changed group.',\n inputSchema: {\n groupId: z\n .string()\n .describe('The id of the group. A unique id prefix is accepted.'),\n rootModuleIds: z\n .tuple([z.string(), z.string()])\n .describe('The ids of the two root modules that change places.'),\n },\n },\n async (args) => textResult(await runTool('swap-root-modules', args)),\n );\n\n registerTool(\n 'merge-groups',\n {\n description:\n 'Joins groups into one: the groups in groupIds are merged into the target group where they stand, ' +\n 'like the merge action of the planner - nothing is moved and no docking is added, so merge groups ' +\n 'that already stand next to each other. Groups of different libraries cannot be merged. To add an article ' +\n 'next to a group, use merge-article-into-group instead. Returns the merged group and the ids of the ' +\n 'groups merged into it.',\n inputSchema: {\n targetGroupId: z\n .string()\n .describe(\n 'The id of the group the others are merged into. A unique id prefix is accepted.',\n ),\n groupIds: z\n .array(z.string())\n .min(1)\n .describe('The ids of the groups to merge into the target group.'),\n },\n },\n async (args) => textResult(await runTool('merge-groups', args)),\n );\n\n registerTool(\n 'undo',\n {\n description:\n \"Reverts the plan change of the last tool call that changed the plan, as the planner's undo does. \" +\n 'When the user asks to undo their last change, revert everything you changed for their last request: ' +\n 'one undo per tool call that changed the plan, the last call first. ' +\n 'Use it when that result is not what was asked - the user says it was the wrong article, wall or group, or a ' +\n 'merge or delete went wrong - and then send the corrected call; call it again to revert the call before. ' +\n 'To bring back what an undo reverted, call redo, not undo. ' +\n 'Returns the reverted tool, the groups it changed back as they are now, removedGroupIds - the groups it took out ' +\n 'of the plan - and otherGroupIds, the groups it left as they were; when there is nothing to undo, the result says so.',\n inputSchema: {},\n },\n async () => textResult(await runTool('undo', {})),\n );\n\n registerTool(\n 'redo',\n {\n description:\n 'Brings back the tool call the last undo reverted - the tool when the user asks to redo or to bring back ' +\n 'what was undone (\"redo it\", \"bring it back\"); undo would revert one more call instead. ' +\n 'When the user asks to redo a change that took several undo calls, call redo as often. ' +\n 'A new change of the plan ends redo. Returns the ' +\n 'restored tool, the groups it changed as they are now, removedGroupIds - the groups it took out of the plan - ' +\n 'and otherGroupIds, the groups it left as they were; when there is nothing to redo, the result says so.',\n inputSchema: {},\n },\n async () => textResult(await runTool('redo', {})),\n );\n\n registerTool(\n 'get-price',\n {\n description:\n 'Calculates and returns the price/order data of the current planning situation. ' +\n 'When the plan holds a root or a group the library could not calculate, hint names it: the price includes it, ' +\n 'but it is not built - say so in the answer.',\n inputSchema: {},\n },\n async () => textResult(await runTool('get-price', {})),\n );\n\n registerTool(\n 'get-order-data',\n {\n description:\n 'Returns the order data of the current planning situation without placing an order. ' +\n 'When the plan holds a root or a group the library could not calculate, hint names it: the order data includes ' +\n 'it, but it is not built - say so in the answer.',\n inputSchema: {},\n },\n async () => textResult(await runTool('get-order-data', {})),\n );\n\n registerTool(\n 'get-plan-images',\n {\n description:\n 'Renders two images of the current plan when the user asks to see it or to look inside a cabinet, or to ' +\n 'compare a planning from an image the user sent with that image; a create or edit result already carries ' +\n 'the positions to verify, so a check needs no render. First the groups ' +\n 'alone, seen from their front without the room or other objects - one camera for all groups, so where ' +\n 'fronts face opposite directions one side is seen from behind, and root modules can hide one another: a ' +\n 'root module not seen is not missing, get-plan-context lists the root modules. Second a top view of the ' +\n 'whole plan that shows where the groups stand; its orientation matches the wall side labels of ' +\n \"get-plan-context: a wall with side 'right' is at the right edge of the top image, 'top' at the upper \" +\n 'edge. A text before the images names them; without groups in the plan only the top view is returned. ' +\n 'Doors and drawers are shown as they are: to look inside a cabinet, open it with open-or-close-article ' +\n '(a whole group with open-or-close-group) right before this tool.',\n inputSchema: {},\n },\n async () => {\n const images = (await runTool('get-plan-images', {})) as {\n perspectiveObjectImage?: string;\n topImage?: string;\n };\n const views = [\n {\n image: images.perspectiveObjectImage,\n name: 'the HI groups alone, seen from their front, without the room',\n },\n { image: images.topImage, name: 'the top view of the whole plan' },\n ].filter((view) => view.image);\n if (views.length === 0) {\n return textResult({ error: 'No images available' });\n }\n const names = views\n .map((view, index) => `Image ${index + 1}: ${view.name}.`)\n .join(' ');\n return {\n content: [\n {\n type: 'text' as const,\n text: images.perspectiveObjectImage\n ? names\n : `The plan has no groups, so there is no group view. ${names}`,\n },\n ...views.map((view) => ({\n type: 'image' as const,\n data: stripDataUrlPrefix(view.image as string),\n mimeType: PLAN_IMAGE_TYPE,\n })),\n ],\n };\n },\n );\n\n return tools;\n};\n"],"mappings":";;;;;AASA,IAAM,KAAW,MACf,MAAM,QAAQ,EAAM,IAAI,EAAM,WAAW,KAAK,EAAM,MAAM,OAAO,SAAS,EAGtE,KAAU,MACd,MAAM,QAAQ,EAAM,IAAI,EAAM,WAAW,KAAK,EAAM,MAAM,OAAO,SAAS,EAEtE,KAAY,MAChB,OAAO,KAAU,cAAY,KAAkB,CAAC,MAAM,QAAQ,EAAM,EAGhE,KAAe,MACnB,EAAQ,EAAM,GAAG;CAAC,EAAM,KAAK;CAAG,CAAC,EAAM,KAAK;CAAG,EAAM,KAAK;CAAE,GAAG,GAE3D,KAAc,MAClB,EAAQ,EAAM,GAAG;CAAC,EAAM,KAAK;CAAG,EAAM,KAAK;CAAG,CAAC,EAAM,KAAK;CAAE,GAAG,GAG3D,KAAgB,MACpB,EAAO,EAAM,GAAG,CAAC,CAAC,EAAM,KAAK,GAAG,CAAC,EAAM,KAAK,EAAE,GAAG,GAI7C,KACJ,GACA,GACA,IAAgC,EAAE,KAElC,EAAS,EAAO,GACZ,OAAO,YACL,OAAO,QAAQ,EAAO,CAAC,KAAK,CAAC,GAAK,OAAW,CAC3C,EAAM,MAAQ,GACd,EAAO,KAAO,EAAO,GAAK,EAAM,GAAG,EACpC,CAAC,CACH,GACD,GAEA,KACH,OACA,MACC,MAAM,QAAQ,EAAM,GAAG,EAAM,IAAI,EAAQ,GAAG,GAE1C,KAAkB,MACtB,GAAM,MACJ,EAAW,GAAM,EACf,cAAc,MACZ,EAAW,GAA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CACR,UAAU,CACV,SAAS,8DAA8D;EAC1E,OAAO,GACI,CACR,UAAU,CACV,SACC,+EACD;EACH,OAAO,EAAQ,SACb,sEACD;EACF,CAAC,EACI,IAAW,EAAc;EAC7B,IAAI,GACO,CACR,UAAU,CACV,SACC,sFACD;EACH,WAAW,GAAU,CAAC,UAAU,CAAC,SAAS,2BAA2B;EACrE,WAAW,EACR,UAAU,CACV,SACC,iEACD;EACH,YAAY,EAAmB,SAC7B,2DACD;EACD,OAAO,EACE,GAAa,CACnB,UAAU,CACV,SACC,kLACD;EACJ,CAAC;AA0jBF,QAxjBA,EACE,4BACA;EACE,aACE,IACA;EAsCF,aAAa,EACX,WAAW,EACF,EAAS,CACf,IAAI,EAAE,CACN,SACC,4FACD,EACJ;EACF,EACD,OAAO,EAAE,mBACP,EAAW,MAAM,EAAQ,4BAA4B,EAAE,cAAW,CAAC,CAAC,CACvE,EAED,EACE,eACA;EACE,aACE;EAcF,aAAa;GACX,SAAS,GACE,CACR,SACC,+DACD;GACH,MAAM,EACG,CACL,EAAO;IAAC;IAAQ;IAAS;IAAO;IAAU;IAAQ;IAAQ,CAAC,EAC3D,GAAU,CAAC,KAAK,CAAC,IAAI,EAAE,CACxB,CAAC,CACD,UAAU,CACV,SACC,4QAGD;GACH,WAAW,GACA,CACR,KAAK,CACL,IAAI,EAAE,CACN,UAAU,CACV,SAAS,2DAA2D;GACvE,WAAW,EACH;IACJ;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACD,CAAC,CACD,UAAU,CACV,SACC,wPAGD;GACH,UAAU,GACC,CACR,UAAU,CACV,SACC,yFACD;GACH,UAAU,EACD,GAAU,CAAC,CACjB,IAAI,EAAE,CACN,IAAI,EAAE,CACN,UAAU,CACV,SACC,qIACD;GACH,cAAc,GACH,CACR,UAAU,CACV,SACC,2FACD;GACH,QAAQ,GACG,CACR,UAAU,CACV,SACC,8FACD;GACJ;EACF,EACD,OAAO,MAAS,EAAW,MAAM,EAAQ,eAAe,EAA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