[9] MCP-Brücke zur offenen App: KI-Zugriff (opt-in, Sitzungsschlüssel), gemeinsame Werkzeugliste, Protokoll und Pause
dossier-cli mcp --app spricht MCP über stdio und lauscht auf 127.0.0.1; die App verbindet sich nur mit „KI-Zugriff erlauben“ als WebSocket-Client (gegenseitige HMAC-Anmeldung). Werkzeuge für Datei und App aus einer Liste (core/aiToolDefs.ts, core/aiTools.ts), run_command über die Kern-Befehle, jede Änderung ein Undo-Schritt „KI: <werkzeug>“, KI-Protokoll mit Pause.
This commit is contained in:
25 files changed
+1594
-119
No files matched your search
@@ -0,0 +1,141 @@
|
||||
// [9] KI-Werkzeuge: EINE Liste für den headless MCP-Server (`dossier-cli … mcp`) und die Brücke zur
|
||||
// laufenden App (`dossier-cli mcp --app`), dazu das Brücken-Protokoll (Nachrichten, gegenseitige
|
||||
// Anmeldung per HMAC). Bewusst ohne Importe: die Brücke und der e2e-Test laden nur diese Datei.
|
||||
|
||||
/** Beschreibung eines Werkzeugs (MCP `tools/list`) plus Dossier-Merkmale. */
|
||||
export interface AiToolDef {
|
||||
name: string;
|
||||
description: string;
|
||||
inputSchema: { type: "object"; properties: Record<string, unknown>; required?: string[] };
|
||||
/** Ändert das Projekt (in der App: ein Undo-Schritt „KI: <name>“, im Protokoll markiert). */
|
||||
mutating?: boolean;
|
||||
/** Braucht die laufende App (Auswahl, Ansicht, Speichern-Dialog). */
|
||||
appOnly?: boolean;
|
||||
}
|
||||
|
||||
const obj = (properties: Record<string, unknown> = {}, required?: string[]) =>
|
||||
({ type: "object", properties, ...(required ? { required } : {}) }) as AiToolDef["inputSchema"];
|
||||
const ids = { type: "array", items: { type: "string" } };
|
||||
|
||||
export const AI_TOOLS: AiToolDef[] = [
|
||||
{
|
||||
name: "project_info",
|
||||
description: "Zählt Bauteile des Projekts und listet Geschosse/Schnitte/Ansichten (in der App mit aktivem Geschoss).",
|
||||
inputSchema: obj(),
|
||||
},
|
||||
{
|
||||
name: "query",
|
||||
description:
|
||||
"Liest Elemente einer Liste (walls, ceilings, roofs, openings, stairs, rooms, columns, drawings2d, extrudedSolids, drawingLevels, …), optional nach id/ids gefiltert.",
|
||||
inputSchema: obj({ collection: { type: "string" }, id: { type: "string" }, ids, limit: { type: "number" } }, ["collection"]),
|
||||
},
|
||||
{
|
||||
name: "render_svg",
|
||||
description: "Rendert Grundriss (kind=floor), Schnitt (section) oder Ansicht (elevation) als SVG-Text.",
|
||||
inputSchema: obj({ kind: { type: "string", enum: ["floor", "section", "elevation"] }, name: { type: "string" }, scale: { type: "number" } }, ["kind"]),
|
||||
},
|
||||
{
|
||||
name: "apply_ops",
|
||||
description:
|
||||
"Wendet CoreOps an (add/replace/remove/reorder/setField, JSON). Der Kern prüft (NaN, doppelte ids); bei Fehler bleibt das Projekt unverändert.",
|
||||
inputSchema: obj({ ops: { type: "array", items: { type: "object" } } }, ["ops"]),
|
||||
mutating: true,
|
||||
},
|
||||
{
|
||||
name: "run_command",
|
||||
description:
|
||||
"Führt einen Kern-Befehl mit JSON-Parametern aus (dieselben wie die Befehle der Oberfläche): z. B. " +
|
||||
'{cmd:"wall", pts:[[0,0],[5,0]]}, {cmd:"room"|"ceiling"|"roof", pts:[…]}, {cmd:"column", at:[x,y]}, ' +
|
||||
'{cmd:"opening", wall:<id>, start, end (Wandachse), pos, width, height, sill, kind:"door"|"window"}, {cmd:"rect"|"polyline"|"circle", …}, {cmd:"transform", ids, …}, ' +
|
||||
'{cmd:"align"|"distribute", ids, mode|axis}, {cmd:"split", ids}. `level` = Geschoss-id (Standard: aktives bzw. erstes).',
|
||||
inputSchema: obj({ cmd: { type: "string" }, params: { type: "object" }, level: { type: "string" } }, ["cmd"]),
|
||||
mutating: true,
|
||||
},
|
||||
{ name: "validate", description: "Prüft das gesamte Projekt auf nicht endliche Zahlen und doppelte ids.", inputSchema: obj() },
|
||||
{
|
||||
name: "kennzahlen",
|
||||
description: "Kennzahlen (kind=kennzahlen: Flächen/Volumen, Raumprogramm, Baurecht), SIA-416-Flächentabelle (sia416) oder IVHB-Kennziffern (ivhb) als JSON.",
|
||||
inputSchema: obj({ kind: { type: "string", enum: ["kennzahlen", "sia416", "ivhb"] } }),
|
||||
},
|
||||
{
|
||||
name: "schedule",
|
||||
description: "Listen: Fenster/Türen (kind=openings, JSON), Bauteile mit U-Werten (elements, JSON) oder Bauteilliste (list, CSV).",
|
||||
inputSchema: obj({ kind: { type: "string", enum: ["openings", "elements", "list"] } }),
|
||||
},
|
||||
{ name: "get_selection", description: "Liefert die aktuelle Auswahl der App als {collection: [ids]}.", inputSchema: obj(), appOnly: true },
|
||||
{
|
||||
name: "select",
|
||||
description: "Wählt Elemente nach id in der App aus (ersetzt die Auswahl; leere Liste = Auswahl aufheben).",
|
||||
inputSchema: obj({ ids }, ["ids"]),
|
||||
appOnly: true,
|
||||
},
|
||||
{
|
||||
name: "zoom_to",
|
||||
description: "Wechselt aufs Geschoss der Elemente und passt die Planansicht der App auf sie ein.",
|
||||
inputSchema: obj({ ids }, ["ids"]),
|
||||
appOnly: true,
|
||||
},
|
||||
{
|
||||
name: "export",
|
||||
description:
|
||||
"Exportiert Grundriss als SVG (format=svg) oder PDF (pdf, nur App) bzw. das Modell als IFC (ifc). Liefert den Inhalt " +
|
||||
"(PDF base64); mit save=true öffnet die App den Speichern-Dialog und die Nutzerin wählt den Ort.",
|
||||
inputSchema: obj(
|
||||
{ format: { type: "string", enum: ["svg", "pdf", "ifc"] }, level: { type: "string" }, scale: { type: "number" }, save: { type: "boolean" } },
|
||||
["format"],
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
export const aiToolDef = (name: string): AiToolDef | undefined => AI_TOOLS.find((t) => t.name === name);
|
||||
|
||||
// ── Brücken-Protokoll (WebSocket, JSON je Nachricht) ─────────────────────────────────────────
|
||||
//
|
||||
// Die Brücke (`dossier-cli mcp --app`) lauscht auf 127.0.0.1:<port>; die App verbindet sich nur,
|
||||
// wenn „KI-Zugriff erlauben“ an ist. Anmeldung gegenseitig, ohne dass der Schlüssel reist:
|
||||
// Brücke → App {type:"hello", nonce:Nb}
|
||||
// App → Brücke {type:"auth", nonce:Na, mac:HMAC(token, "app:"+Nb)}
|
||||
// Brücke → App {type:"auth", mac:HMAC(token, "bridge:"+Na)} (sonst Abbruch)
|
||||
// App → Brücke {type:"ready"}
|
||||
// danach Brücke → App {type:"call", id, name, args}, App → Brücke {type:"result", id, result}.
|
||||
|
||||
export const AI_BRIDGE_DEFAULT_PORT = 7979;
|
||||
|
||||
export type AiBridgeMsg =
|
||||
| { type: "hello"; nonce: string }
|
||||
| { type: "auth"; nonce?: string; mac: string }
|
||||
| { type: "ready" }
|
||||
| { type: "call"; id: number; name: string; args: Record<string, unknown> }
|
||||
| { type: "result"; id: number; result: AiToolResult };
|
||||
|
||||
/** Ergebnis eines Werkzeugs (MCP `tools/call`). */
|
||||
export interface AiToolResult {
|
||||
content: ({ type: "text"; text: string } | { type: "resource"; resource: { uri: string; mimeType: string; blob: string } })[];
|
||||
isError: boolean;
|
||||
}
|
||||
|
||||
export const aiText = (text: string, isError = false): AiToolResult => ({ content: [{ type: "text", text }], isError });
|
||||
|
||||
const hex = (b: Uint8Array) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
|
||||
|
||||
/** Zufällige Hex-Zeichenkette (`bytes` Bytes) aus dem Krypto-Zufall. */
|
||||
export function randomHex(bytes = 16): string {
|
||||
const b = new Uint8Array(bytes);
|
||||
globalThis.crypto.getRandomValues(b);
|
||||
return hex(b);
|
||||
}
|
||||
|
||||
/** HMAC-SHA256(token, msg) als Hex (WebCrypto: Browser, Tauri-WebView und Node). */
|
||||
export async function hmacHex(token: string, msg: string): Promise<string> {
|
||||
const enc = new TextEncoder();
|
||||
const key = await globalThis.crypto.subtle.importKey("raw", enc.encode(token), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
||||
return hex(new Uint8Array(await globalThis.crypto.subtle.sign("HMAC", key, enc.encode(msg))));
|
||||
}
|
||||
|
||||
/** Vergleich in konstanter Zeit (gleich lange Hex-Texte). */
|
||||
export function sameMac(a: unknown, b: string): boolean {
|
||||
if (typeof a !== "string" || a.length !== b.length) return false;
|
||||
let d = 0;
|
||||
for (let i = 0; i < a.length; i++) d |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
||||
return d === 0;
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
// [9] Gemeinsame KI-Werkzeuge: Verteilung auf einen Host (App oder Datei) und Anmeldung der Brücke.
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { callAiTool, type AiHost } from "./aiTools";
|
||||
import { AI_TOOLS, hmacHex, randomHex, sameMac } from "./aiToolDefs";
|
||||
import { applyOps, validateOps, type CoreOp } from "./ops";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import type { Project } from "../model/types";
|
||||
|
||||
/** Host im Speicher, merkt sich Commits (Beschriftung) und Auswahl. */
|
||||
function fakeHost(withApp: boolean) {
|
||||
let project: Project = sampleProject;
|
||||
const labels: string[] = [];
|
||||
let selected: string[] = [];
|
||||
let zoomed: string[] = [];
|
||||
const host: AiHost = {
|
||||
project: () => project,
|
||||
commit: (ops: CoreOp[], label: string) => {
|
||||
const next = applyOps(project, ops);
|
||||
const problems = validateOps(next, ops, project);
|
||||
if (problems.length) return problems.join("; ");
|
||||
project = next;
|
||||
labels.push(label);
|
||||
return null;
|
||||
},
|
||||
...(withApp
|
||||
? {
|
||||
activeLevelId: () => sampleProject.drawingLevels.find((l) => l.kind === "floor")?.id,
|
||||
selection: () => ({ walls: selected }),
|
||||
select: (ids: string[]) => void (selected = ids),
|
||||
zoomTo: (ids: string[]) => ((zoomed = ids), true),
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
return { host, labels, get: () => project, sel: () => selected, zoom: () => zoomed };
|
||||
}
|
||||
|
||||
const textOf = (r: { content: { type: string; text?: string }[] }) => (r.content[0] as { text: string }).text;
|
||||
|
||||
describe("KI-Werkzeuge (gemeinsame Liste)", () => {
|
||||
it("Liste: eindeutige Namen, Schema je Werkzeug, Kennzeichen für App/Änderung", () => {
|
||||
const names = AI_TOOLS.map((t) => t.name);
|
||||
expect(new Set(names).size).toBe(names.length);
|
||||
for (const n of ["project_info", "query", "render_svg", "apply_ops", "validate", "run_command", "select", "zoom_to", "export"]) expect(names).toContain(n);
|
||||
expect(AI_TOOLS.filter((t) => t.mutating).map((t) => t.name).sort()).toEqual(["apply_ops", "run_command"]);
|
||||
});
|
||||
|
||||
it("project_info und query lesen das Projekt des Hosts", async () => {
|
||||
const { host } = fakeHost(false);
|
||||
const info = JSON.parse(textOf(await callAiTool(host, "project_info", {})));
|
||||
expect(info.counts.walls).toBe(sampleProject.walls.length);
|
||||
const w = sampleProject.walls[1];
|
||||
const q = JSON.parse(textOf(await callAiTool(host, "query", { collection: "walls", ids: [w.id] })));
|
||||
expect(q.map((e: { id: string }) => e.id)).toEqual([w.id]);
|
||||
expect((await callAiTool(host, "query", { collection: "gibtsnicht" })).isError).toBe(true);
|
||||
});
|
||||
|
||||
it("run_command: Kern-Befehl mit JSON = ein Commit mit Beschriftung „KI: run_command“", async () => {
|
||||
const h = fakeHost(true);
|
||||
const before = h.get().walls.length;
|
||||
const r = await callAiTool(h.host, "run_command", { cmd: "wall", params: { pts: [[0, 0], [4, 0]] } });
|
||||
expect(r.isError).toBe(false);
|
||||
expect(h.get().walls.length).toBe(before + 1);
|
||||
expect(h.labels).toEqual(["KI: run_command"]);
|
||||
const added = h.get().walls.find((w) => !sampleProject.walls.some((o) => o.id === w.id))!;
|
||||
expect(added.floorId).toBe(h.host.activeLevelId!());
|
||||
expect(added.categoryCode).toBe(sampleProject.walls[0].categoryCode); // sichtbar wie in der Oberfläche
|
||||
expect(textOf(r)).toContain(added.id);
|
||||
// unbekannter Befehl → Fehler, kein Commit
|
||||
const bad = await callAiTool(h.host, "run_command", { cmd: "gibtsnicht" });
|
||||
expect(bad.isError).toBe(true);
|
||||
expect(h.labels.length).toBe(1);
|
||||
});
|
||||
|
||||
it("apply_ops: abgelehnte Ops melden den Grund, das Projekt bleibt", async () => {
|
||||
const h = fakeHost(false);
|
||||
const w = sampleProject.walls[0];
|
||||
const bad = await callAiTool(h.host, "apply_ops", { ops: [{ kind: "add", collection: "walls", items: [{ ...w }] }] });
|
||||
expect(bad.isError).toBe(true);
|
||||
expect(h.get()).toBe(sampleProject);
|
||||
expect((await callAiTool(h.host, "apply_ops", { ops: "x" })).isError).toBe(true);
|
||||
const ok = await callAiTool(h.host, "apply_ops", { ops: [{ kind: "replace", collection: "walls", entity: { ...w, height: 7 } }] });
|
||||
expect(ok.isError).toBe(false);
|
||||
expect(h.labels).toEqual(["KI: apply_ops"]);
|
||||
});
|
||||
|
||||
it("App-Werkzeuge: ohne App Fehler, mit App Auswahl/Zoom über den Host", async () => {
|
||||
const off = fakeHost(false);
|
||||
expect((await callAiTool(off.host, "select", { ids: ["a"] })).isError).toBe(true);
|
||||
const on = fakeHost(true);
|
||||
const id = sampleProject.walls[0].id;
|
||||
expect((await callAiTool(on.host, "select", { ids: [id] })).isError).toBe(false);
|
||||
expect(on.sel()).toEqual([id]);
|
||||
expect(JSON.parse(textOf(await callAiTool(on.host, "get_selection", {})))).toEqual({ walls: [id] });
|
||||
expect((await callAiTool(on.host, "zoom_to", { ids: [id] })).isError).toBe(false);
|
||||
expect(on.zoom()).toEqual([id]);
|
||||
expect((await callAiTool(on.host, "select", { ids: "x" })).isError).toBe(true);
|
||||
});
|
||||
|
||||
it("Auswertungen und Export ohne Dateizugriff", async () => {
|
||||
const { host } = fakeHost(false);
|
||||
expect(JSON.parse(textOf(await callAiTool(host, "kennzahlen", {}))).kennzahlen).toBeTruthy();
|
||||
expect(Array.isArray(JSON.parse(textOf(await callAiTool(host, "schedule", { kind: "openings" }))))).toBe(true);
|
||||
expect(textOf(await callAiTool(host, "export", { format: "svg" }))).toContain("<svg");
|
||||
expect((await callAiTool(host, "export", { format: "pdf" })).isError).toBe(true); // PDF nur in der App
|
||||
expect((await callAiTool(host, "export", { format: "svg", save: true })).isError).toBe(true); // Speichern nur mit Dialog
|
||||
expect((await callAiTool(host, "gibtsnicht", {})).isError).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Brücken-Anmeldung", () => {
|
||||
it("HMAC ist deterministisch, schlüsselabhängig; Vergleich in konstanter Zeit", async () => {
|
||||
const tok = randomHex();
|
||||
expect(tok).toMatch(/^[0-9a-f]{32}$/);
|
||||
const a = await hmacHex(tok, "app:123");
|
||||
expect(a).toBe(await hmacHex(tok, "app:123"));
|
||||
expect(a).not.toBe(await hmacHex(tok, "bridge:123"));
|
||||
expect(a).not.toBe(await hmacHex(randomHex(), "app:123"));
|
||||
expect(sameMac(a, a)).toBe(true);
|
||||
expect(sameMac(a.slice(1), a)).toBe(false);
|
||||
expect(sameMac(undefined, a)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,208 @@
|
||||
// [9] Verteilung der KI-Werkzeuge (`aiToolDefs.ts`) auf einen Host: die Projektdatei (headless,
|
||||
// `dossier-cli … mcp`) oder die laufende App (Brücke, `state/aiBridge.ts`). Gemeinsam ist alles, was
|
||||
// nur das Projekt braucht; Auswahl, Ansicht, PDF und Speichern-Dialog liefert nur die App.
|
||||
// Änderungen gehen ausschliesslich als Ops an `host.commit` (ein Schritt, Beschriftung „KI: <tool>“).
|
||||
|
||||
import type { Project } from "../model/types";
|
||||
import type { Plan } from "../plan/generatePlan";
|
||||
import { generatePlan } from "../plan/generatePlan";
|
||||
import { computeSection, generateSectionPlan } from "../plan/toSection";
|
||||
import { generateElevationPlan } from "../plan/toElevation";
|
||||
import { planToSvgString } from "../export/planToSvgString";
|
||||
import { exportIfcSpf } from "../export/exportIfc";
|
||||
import { exportScheduleCsv } from "../export/exportSchedule";
|
||||
import { openingSchedule } from "../export/openingSchedule";
|
||||
import { elementSchedule } from "../export/elementSchedule";
|
||||
import { computeKennzahlen, checkRoomProgram } from "../analysis/kennzahlen";
|
||||
import { computeAreaTable, computeIvhb } from "../analysis/areaTable";
|
||||
import { checkSiteRules } from "../analysis/siteRules";
|
||||
import { loadFileio } from "../engine/fileioWasm";
|
||||
import { documentFor } from "./document";
|
||||
import { validateProject, projectWarnings, type CoreOp } from "./ops";
|
||||
import { aiText, aiToolDef, randomHex, type AiToolResult } from "./aiToolDefs";
|
||||
|
||||
/** Was ein Werkzeug vom Gegenüber braucht. Optionale Teile fehlen headless. */
|
||||
export interface AiHost {
|
||||
project(): Project;
|
||||
/** Ops als EIN Schritt anwenden (Beschriftung `label`); `null` = angenommen, sonst der Grund. */
|
||||
commit(ops: CoreOp[], label: string): string | null;
|
||||
activeLevelId?(): string | undefined;
|
||||
/** Vorgaben der Befehle wie in der Oberfläche (aktive Kategorie, Wandtyp). */
|
||||
commandDefaults?(): { cat?: string; wallType?: string };
|
||||
/** Auswahl je Liste (`walls`, `rooms`, …). */
|
||||
selection?(): Record<string, string[]>;
|
||||
select?(ids: string[]): void;
|
||||
/** Auf die Elemente einpassen; `false` = keine Geometrie gefunden. */
|
||||
zoomTo?(ids: string[]): boolean;
|
||||
planPdf?(plan: Plan, scale: number, title: string): Promise<Uint8Array>;
|
||||
/** Speichern-Dialog: die Nutzerin wählt den Ort; `false` = abgebrochen. */
|
||||
save?(data: string | Uint8Array, name: string, mime: string): Promise<boolean>;
|
||||
}
|
||||
|
||||
const json = (v: unknown) => aiText(JSON.stringify(v));
|
||||
const err = (t: string) => aiText(t, true);
|
||||
|
||||
function strIds(v: unknown): string[] | null {
|
||||
return Array.isArray(v) && v.every((x) => typeof x === "string") ? (v as string[]) : null;
|
||||
}
|
||||
|
||||
function b64(bytes: Uint8Array): string {
|
||||
let s = "";
|
||||
for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
||||
return btoa(s);
|
||||
}
|
||||
|
||||
function floorLevel(project: Project, host: AiHost, want: unknown) {
|
||||
const floors = project.drawingLevels.filter((l) => l.kind === "floor");
|
||||
if (typeof want === "string" && want) return floors.find((l) => l.id === want || l.name === want);
|
||||
const active = host.activeLevelId?.();
|
||||
return floors.find((l) => l.id === active) ?? floors[0];
|
||||
}
|
||||
|
||||
const codesOf = (p: Project) => new Set(p.layers.map((l) => l.code));
|
||||
|
||||
/** Führt Werkzeug `name` mit `args` auf `host` aus (MCP-Ergebnis, Fehler als `isError`). */
|
||||
export async function callAiTool(host: AiHost, name: string, args: Record<string, unknown>): Promise<AiToolResult> {
|
||||
const def = aiToolDef(name);
|
||||
if (!def) return err(`unbekanntes Werkzeug: ${name}`);
|
||||
try {
|
||||
return await dispatch(host, name, args ?? {});
|
||||
} catch (e) {
|
||||
return err(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}
|
||||
|
||||
async function dispatch(host: AiHost, name: string, args: Record<string, unknown>): Promise<AiToolResult> {
|
||||
const project = host.project();
|
||||
const label = `KI: ${name}`;
|
||||
switch (name) {
|
||||
case "project_info":
|
||||
return json({
|
||||
name: project.name,
|
||||
counts: Object.fromEntries(
|
||||
Object.entries(project as unknown as Record<string, unknown>)
|
||||
.filter(([, v]) => Array.isArray(v))
|
||||
.map(([k, v]) => [k, (v as unknown[]).length]),
|
||||
),
|
||||
levels: project.drawingLevels.map((l) => ({ id: l.id, name: l.name, kind: l.kind })),
|
||||
...(host.activeLevelId ? { activeLevelId: host.activeLevelId() } : {}),
|
||||
});
|
||||
case "query": {
|
||||
const list = (project as unknown as Record<string, unknown>)[String(args.collection)];
|
||||
if (!Array.isArray(list)) return err(`Keine Liste: ${String(args.collection)}`);
|
||||
const want = strIds(args.ids) ?? (typeof args.id === "string" ? [args.id] : null);
|
||||
const rows = want ? list.filter((e) => want.includes((e as { id?: string }).id ?? "")) : list.slice(0, Number(args.limit ?? 50));
|
||||
return json(rows);
|
||||
}
|
||||
case "render_svg": {
|
||||
const kind = String(args.kind);
|
||||
const lvl = project.drawingLevels.find((l) => l.kind === kind && (!args.name || l.name === args.name || l.id === args.name));
|
||||
if (!lvl) return err(`Ebene nicht gefunden: ${kind} ${String(args.name ?? "")}`);
|
||||
const scale = Number(args.scale ?? 100);
|
||||
const codes = codesOf(project);
|
||||
if (kind === "floor") return aiText(planToSvgString(generatePlan(project, lvl.id, codes), { scaleDenominator: scale }));
|
||||
if (kind === "section") {
|
||||
const o = await computeSection(project, lvl);
|
||||
if (!o) return err("keine gültige Schnittlinie");
|
||||
return aiText(planToSvgString(generateSectionPlan(o, false, { visibleCodes: codes }), { scaleDenominator: scale }));
|
||||
}
|
||||
const plan = generateElevationPlan(project, lvl, { scaleDenominator: scale });
|
||||
return plan ? aiText(planToSvgString(plan, { scaleDenominator: scale })) : err("keine gültige Ansichtslinie");
|
||||
}
|
||||
case "apply_ops": {
|
||||
const ops = args.ops as CoreOp[];
|
||||
if (!Array.isArray(ops)) return err("ops muss eine Liste sein");
|
||||
const problem = host.commit(ops, label);
|
||||
return problem ? err(`Abgelehnt, nichts geändert: ${problem}`) : aiText(`ok: ${ops.length} Op(s) angewendet`);
|
||||
}
|
||||
case "run_command": {
|
||||
const cmd = args.cmd;
|
||||
if (typeof cmd !== "string" || !cmd) return err("cmd fehlt");
|
||||
const params = (args.params && typeof args.params === "object" ? args.params : {}) as Record<string, unknown>;
|
||||
const lvl = floorLevel(project, host, args.level);
|
||||
const d = host.commandDefaults?.() ?? {};
|
||||
const cat = d.cat ?? project.walls[0]?.categoryCode ?? project.layers[0]?.code ?? "";
|
||||
const ctx = { level: lvl?.id ?? "", floorHeight: lvl?.floorHeight ?? null, cat, wallType: d.wallType ?? "", ...((params.ctx as object) ?? {}) };
|
||||
const ops = documentFor(project).cmdOps({ ...params, cmd, ctx, stamp: `ki${Date.now().toString(36)}${randomHex(3)}` });
|
||||
if (ops.length === 0) return err(`Befehl „${cmd}“ ergab keine Änderung (Parameter prüfen)`);
|
||||
const problem = host.commit(ops, label);
|
||||
if (problem) return err(`Abgelehnt, nichts geändert: ${problem}`);
|
||||
const added = ops.flatMap((o) => (o.kind === "add" ? o.items.map((e) => ({ collection: o.collection, id: (e as { id?: string }).id })) : []));
|
||||
return json({ ok: true, ops: ops.length, added });
|
||||
}
|
||||
case "validate": {
|
||||
const problems = validateProject(project);
|
||||
const warnings = projectWarnings(project).map((w) => `Warnung: ${w}`);
|
||||
return aiText([...problems, ...warnings].join("\n") || "ok", problems.length > 0);
|
||||
}
|
||||
case "kennzahlen": {
|
||||
const kind = String(args.kind ?? "kennzahlen");
|
||||
if (kind === "sia416") return json(computeAreaTable(project));
|
||||
if (kind === "ivhb") return json(computeIvhb(project));
|
||||
return json({ kennzahlen: computeKennzahlen(project), raumprogramm: checkRoomProgram(project), baurecht: checkSiteRules(project) });
|
||||
}
|
||||
case "schedule": {
|
||||
const kind = String(args.kind ?? "openings");
|
||||
if (kind === "openings") return json(openingSchedule(project));
|
||||
if (kind === "elements") return json(elementSchedule(project));
|
||||
if (kind === "list") return aiText(exportScheduleCsv(project));
|
||||
return err(`schedule: unbekannte Art ${kind}`);
|
||||
}
|
||||
case "get_selection":
|
||||
return host.selection ? json(host.selection()) : appOnly(name);
|
||||
case "select": {
|
||||
if (!host.select) return appOnly(name);
|
||||
const ids = strIds(args.ids);
|
||||
if (!ids) return err("ids muss eine Liste von Texten sein");
|
||||
host.select(ids);
|
||||
return aiText(`ok: ${ids.length} gewählt`);
|
||||
}
|
||||
case "zoom_to": {
|
||||
if (!host.zoomTo) return appOnly(name);
|
||||
const ids = strIds(args.ids);
|
||||
if (!ids) return err("ids muss eine Liste von Texten sein");
|
||||
return host.zoomTo(ids) ? aiText("ok") : err("keine Geometrie zu diesen ids gefunden");
|
||||
}
|
||||
case "export":
|
||||
return exportTool(host, project, args);
|
||||
default:
|
||||
return err(`unbekanntes Werkzeug: ${name}`);
|
||||
}
|
||||
}
|
||||
|
||||
const appOnly = (name: string) => err(`${name}: nur mit der laufenden App (dossier-cli mcp --app)`);
|
||||
|
||||
async function exportTool(host: AiHost, project: Project, args: Record<string, unknown>): Promise<AiToolResult> {
|
||||
const format = String(args.format);
|
||||
const stem = project.name || "projekt";
|
||||
const scale = Number(args.scale ?? 100);
|
||||
if (args.save === true && !host.save) return err("save: Speichern nur in der App (Dialog, Ort wählt die Nutzerin)");
|
||||
let data: string | Uint8Array;
|
||||
let file: string;
|
||||
let mime: string;
|
||||
if (format === "ifc") {
|
||||
await loadFileio();
|
||||
data = exportIfcSpf(project);
|
||||
file = `${stem}.ifc`;
|
||||
mime = "application/x-step";
|
||||
} else if (format === "svg" || format === "pdf") {
|
||||
const lvl = floorLevel(project, host, args.level);
|
||||
if (!lvl) return err("kein Geschoss");
|
||||
const plan = generatePlan(project, lvl.id, codesOf(project));
|
||||
if (format === "svg") {
|
||||
data = planToSvgString(plan, { scaleDenominator: scale });
|
||||
mime = "image/svg+xml";
|
||||
} else {
|
||||
if (!host.planPdf) return appOnly("export pdf");
|
||||
data = await host.planPdf(plan, scale, `${stem} – ${lvl.name}`);
|
||||
mime = "application/pdf";
|
||||
}
|
||||
file = `${stem}-${lvl.name}.${format}`;
|
||||
} else return err(`export: unbekanntes Format ${format}`);
|
||||
if (args.save === true) {
|
||||
const ok = await host.save!(data, file, mime);
|
||||
return ok ? aiText(`gespeichert: ${file}`) : err("Speichern abgebrochen");
|
||||
}
|
||||
if (typeof data === "string") return aiText(data);
|
||||
return { content: [{ type: "resource", resource: { uri: `dossier:${file}`, mimeType: mime, blob: b64(data) } }], isError: false };
|
||||
}
|
||||
@@ -69,3 +69,7 @@ export { openingPreviewProject, openingPreviewSvgs } from "../plan/openingPrevie
|
||||
export type { OpeningPreviewSvgs } from "../plan/openingPreview";
|
||||
export { surfaceOpeningInfo, surfaceOpeningGrips, surfaceOpeningGripPatch } from "../plan/surfaceOpening";
|
||||
export type { SurfaceOpeningInfo } from "../plan/surfaceOpening";
|
||||
export { AI_TOOLS, AI_BRIDGE_DEFAULT_PORT, aiText, aiToolDef, hmacHex, randomHex, sameMac } from "./aiToolDefs";
|
||||
export type { AiToolDef, AiToolResult, AiBridgeMsg } from "./aiToolDefs";
|
||||
export { callAiTool } from "./aiTools";
|
||||
export type { AiHost } from "./aiTools";
|
||||
Reference in new issue
Block a user