CanvasAnvil is an open source AI diagram maker and flowchart generator - an infinite-canvas diagram editor and self-hosted drawio alternative that writes editable .drawio files. Text to diagram, then fix nodes, layout and labels in place. Also AI presentations, interior design CAD/BOM, posters and infographics.
TypeScript ai-agentsai-diagramai-presentationbomcadcanvasdiagramdiagram-generatordrawioflowchartinfographicspptppt-generatorpresentation-generatorreactsvgedittext-to-diagramtypescriptworkflow
refactor: split the repo into client, server, contracts and resources
codingFeng10125b0c7cd9db5
diff --git a/api/routes/chat.ts b/api/routes/chat.tsdeleted file mode 100644index cd95ac6..0000000--- a/api/routes/chat.ts+++ /dev/null@@ -1,2 +0,0 @@-export { POST } from "../../src/server/routes/chat"-diff --git a/api/routes/config.ts b/api/routes/config.tsdeleted file mode 100644index 7da4a86..0000000--- a/api/routes/config.ts+++ /dev/null@@ -1,2 +0,0 @@-export { GET } from "../../src/server/routes/config"-diff --git a/api/routes/log-feedback.ts b/api/routes/log-feedback.tsdeleted file mode 100644index ccf7953..0000000--- a/api/routes/log-feedback.ts+++ /dev/null@@ -1,2 +0,0 @@-export { POST } from "../../src/server/routes/log-feedback"-diff --git a/api/routes/log-file-parser.ts b/api/routes/log-file-parser.tsdeleted file mode 100644index fc0f524..0000000--- a/api/routes/log-file-parser.ts+++ /dev/null@@ -1,3 +0,0 @@-export { POST } from "../../src/server/routes/log-file-parser"--diff --git a/api/routes/log-save.ts b/api/routes/log-save.tsdeleted file mode 100644index 6c7635c..0000000--- a/api/routes/log-save.ts+++ /dev/null@@ -1,2 +0,0 @@-export { POST } from "../../src/server/routes/log-save"-diff --git a/api/routes/ppt-ai.ts b/api/routes/ppt-ai.tsdeleted file mode 100644index 52f4810..0000000--- a/api/routes/ppt-ai.ts+++ /dev/null@@ -1 +0,0 @@-export { POST } from "../../src/server/routes/ppt-ai"diff --git a/api/routes/third-party-parser.ts b/api/routes/third-party-parser.tsdeleted file mode 100644index 510a30c..0000000--- a/api/routes/third-party-parser.ts+++ /dev/null@@ -1,3 +0,0 @@-export { POST } from "../../src/server/routes/third-party-parser"--diff --git a/api/routes/verify-access-code.ts b/api/routes/verify-access-code.tsdeleted file mode 100644index a3e2991..0000000--- a/api/routes/verify-access-code.ts+++ /dev/null@@ -1,2 +0,0 @@-export { POST } from "../../src/server/routes/verify-access-code"-diff --git a/api/server.ts b/api/server.tsdeleted file mode 100644index 2735281..0000000--- a/api/server.ts+++ /dev/null@@ -1,147 +0,0 @@-import express from "express";-import type { Response as ExpressResponse } from "express";-import fs from "node:fs";-import path from "node:path";-import { fileURLToPath } from "node:url";-import { GET as getConfig } from "./routes/config";-import { POST as postVerifyAccessCode } from "./routes/verify-access-code";-import { POST as postLogFeedback } from "./routes/log-feedback";-import { POST as postLogSave } from "./routes/log-save";-import { POST as postLogFileParser } from "./routes/log-file-parser";-import { POST as postThirdPartyParser } from "./routes/third-party-parser";-import { POST as postChat } from "./routes/chat";-import { POST as postPptAi } from "./routes/ppt-ai";--const PORT = Number(process.env.PORT || process.env.API_PORT || 8080);-const BODY_LIMIT = process.env.API_BODY_LIMIT || "25mb";--const __filename = fileURLToPath(import.meta.url);-const __dirname = path.dirname(__filename);-const defaultDistDir = path.resolve(__dirname, "../dist");-const distDir = process.env.WEB_DIST_DIR- ? path.resolve(process.cwd(), process.env.WEB_DIST_DIR)- : defaultDistDir;-const indexHtmlPath = path.join(distDir, "index.html");--const app = express();-app.use(express.json({ limit: BODY_LIMIT }));--function toWebRequest(req: express.Request): Request {- const origin = `${req.protocol || "http"}://${req.get("host") || "localhost"}`;- const url = new URL(req.originalUrl || req.url, origin);- const headers = new Headers();-- for (const [key, value] of Object.entries(req.headers)) {- if (Array.isArray(value)) {- for (const v of value) headers.append(key, v);- } else if (typeof value === "string") {- headers.set(key, value);- }- }-- let body: BodyInit | undefined;- if (req.method !== "GET" && req.method !== "HEAD") {- if (typeof req.body === "string") {- body = req.body;- } else if (Buffer.isBuffer(req.body)) {- body = req.body;- } else if (req.body !== undefined) {- body = JSON.stringify(req.body);- if (!headers.has("content-type")) {- headers.set("content-type", "application/json");- }- }- }-- return new Request(url.toString(), {- method: req.method,- headers,- body,- });-}--async function sendWebResponse(webResponse: Response, res: ExpressResponse) {- res.status(webResponse.status);- webResponse.headers.forEach((value, key) => {- if (key.toLowerCase() === "transfer-encoding") return;- res.setHeader(key, value);- });-- if (!webResponse.body) {- res.end();- return;- }-- res.flushHeaders?.();- const reader = webResponse.body.getReader();- while (true) {- const { done, value } = await reader.read();- if (done) break;- if (value) res.write(Buffer.from(value));- }- res.end();-}--function withHandler(- handler: (request: Request) => Promise<Response>,-): express.RequestHandler {- return async (req, res) => {- try {- const request = toWebRequest(req);- const response = await handler(request);- await sendWebResponse(response, res);- } catch (error) {- console.error("API route failed:", error);- const message = error instanceof Error ? error.message : "Internal Server Error";- res.status(500).json({ error: message });- }- };-}--app.get("/api/config", async (_req, res) => {- try {- const response = await getConfig();- await sendWebResponse(response, res);- } catch (error) {- console.error("Config route failed:", error);- res.status(500).json({ error: "Internal Server Error" });- }-});--app.post("/api/verify-access-code", withHandler(postVerifyAccessCode));-app.post("/api/log-feedback", withHandler(postLogFeedback));-app.post("/api/log-save", withHandler(postLogSave));-app.post("/api/log-file-parser", withHandler(postLogFileParser));-app.post("/api/third-party-parser", withHandler(postThirdPartyParser));-app.post("/api/chat", withHandler(postChat));-app.post("/api/ppt-ai", withHandler(postPptAi));--app.get("/healthz", (_req, res) => {- res.json({ ok: true, ts: new Date().toISOString() });-});--if (fs.existsSync(indexHtmlPath)) {- app.use(- express.static(distDir, {- index: false,- fallthrough: true,- }),- );-- app.get(/.*/, (req, res, next) => {- if (req.path.startsWith("/api/") || req.path === "/healthz") {- next();- return;- }- res.sendFile(indexHtmlPath);- });-} else {- console.warn(- `[server] dist not found at "${distDir}". Build web assets with "npm run build".`,- );-}--app.listen(PORT, () => {- console.log(`[server] listening on http://localhost:${PORT}`);- console.log(`[server] web root: ${distDir}`);-});diff --git a/src/ai/client.ts b/client/ai/client.tssimilarity index 96%rename from src/ai/client.tsrename to client/ai/client.tsindex 48c718b..a621e96 100644--- a/src/ai/client.ts+++ b/client/ai/client.ts@@ -1,5 +1,6 @@import { getUiLanguage, t } from "@/shared/i18n";-import { getAIConfig, getImageChannel, getTextChannel } from "@/ai/config";+import { getImageChannel, getTextChannel } from "@contracts/ai";+import { getAIConfig } from "@/ai/storage";import { applyUiLanguagePolicy } from "@/ai/language-policy";import { createLimiter } from "@/ai/limiter";import {@@ -7,11 +8,11 @@ import {cleanUrl,normalizeImageUrlForModel,normalizeImageUrlsForModel,-} from "@/ai/browser-image";-import type { AIConfig, ChatContentPart, ChatMessage, MultimodalMessage } from "@/ai/types";+} from "@/ai/images";+import type { AIConfig, ChatContentPart, ChatMessage, MultimodalMessage } from "@contracts/ai";-export type { AIConfig, ChatMessage } from "@/ai/types";-export { getAIConfig, saveAIConfig } from "@/ai/config";+export type { AIConfig, ChatMessage } from "@contracts/ai";+export { getAIConfig, saveAIConfig } from "@/ai/storage";/*** Browser-side facade over the model.diff --git a/src/ai/browser-image.ts b/client/ai/images.tssimilarity index 100%rename from src/ai/browser-image.tsrename to client/ai/images.tsdiff --git a/src/ai/language-policy.ts b/client/ai/language-policy.tssimilarity index 96%rename from src/ai/language-policy.tsrename to client/ai/language-policy.tsindex 876cf42..16aa763 100644--- a/src/ai/language-policy.ts+++ b/client/ai/language-policy.ts@@ -1,5 +1,5 @@import { getUiLanguage } from "@/shared/i18n";-import type { ChatMessage } from "@/ai/types";+import type { ChatMessage } from "@contracts/ai";/*** Agents in this app emit code, XML, and JSON as often as prose, so the outputdiff --git a/src/ai/limiter.ts b/client/ai/limiter.tssimilarity index 100%rename from src/ai/limiter.tsrename to client/ai/limiter.tsdiff --git a/client/ai/storage.ts b/client/ai/storage.tsnew file mode 100644index 0000000..1a3efc2--- /dev/null+++ b/client/ai/storage.ts@@ -0,0 +1,31 @@+import { DEFAULT_AI_CONFIG, normalizeAIConfig, type AIConfig } from "@contracts/ai";++/**+ * Where the browser keeps the user's model settings.+ *+ * The shape and its normalisation are shared with the server (see+ * @contracts/ai); only the storage is browser-specific, which is why it lives+ * here rather than in the contract.+ */++const STORAGE_KEY = "unified_ai_workspace_config";++export function getAIConfig(): AIConfig {+ if (typeof window === "undefined") return DEFAULT_AI_CONFIG;+ const stored = localStorage.getItem(STORAGE_KEY);+ if (!stored) return DEFAULT_AI_CONFIG;+ try {+ return normalizeAIConfig({ ...DEFAULT_AI_CONFIG, ...JSON.parse(stored) });+ } catch {+ try {+ localStorage.removeItem(STORAGE_KEY);+ } catch {+ // A storage that cannot be written to cannot be repaired; fall through.+ }+ return DEFAULT_AI_CONFIG;+ }+}++export function saveAIConfig(config: AIConfig) {+ localStorage.setItem(STORAGE_KEY, JSON.stringify(normalizeAIConfig(config)));+}diff --git a/src/app/App.tsx b/client/app/App.tsxsimilarity index 100%rename from src/app/App.tsxrename to client/app/App.tsxdiff --git a/src/app/BrandIcon.tsx b/client/app/BrandIcon.tsxsimilarity index 100%rename from src/app/BrandIcon.tsxrename to client/app/BrandIcon.tsxdiff --git a/src/app/ErrorBoundary.tsx b/client/app/ErrorBoundary.tsxsimilarity index 100%rename from src/app/ErrorBoundary.tsxrename to client/app/ErrorBoundary.tsxdiff --git a/src/app/workspaces.ts b/client/app/workspaces.tssimilarity index 100%rename from src/app/workspaces.tsrename to client/app/workspaces.tsdiff --git a/src/components/SettingsDialog.tsx b/client/components/SettingsDialog.tsxsimilarity index 98%rename from src/components/SettingsDialog.tsxrename to client/components/SettingsDialog.tsxindex d502e68..2f93c19 100644--- a/src/components/SettingsDialog.tsx+++ b/client/components/SettingsDialog.tsx@@ -2,8 +2,9 @@ import React, { useEffect, useState } from "react";import { createPortal } from "react-dom";import { ExternalLink, Eye, EyeOff, Loader2, Save, Settings, X } from "lucide-react";import { toast } from "sonner";-import { getAIConfig, normalizeAIConfig, saveAIConfig } from "@/ai/config";-import type { AIConfig } from "@/ai/types";+import { normalizeAIConfig } from "@contracts/ai";+import { getAIConfig, saveAIConfig } from "@/ai/storage";+import type { AIConfig } from "@contracts/ai";import { Button } from "@/shared/ui/button";import { getUiLanguage, setUiLanguage, t, type UiLanguage } from "@/shared/i18n";diff --git a/src/features/ppt-editor/adapters/fromCanvasAnvil.ts b/client/features/ppt-editor/adapters/fromCanvasAnvil.tssimilarity index 100%rename from src/features/ppt-editor/adapters/fromCanvasAnvil.tsrename to client/features/ppt-editor/adapters/fromCanvasAnvil.tsdiff --git a/src/features/ppt-editor/adapters/toCanvasAnvil.ts b/client/features/ppt-editor/adapters/toCanvasAnvil.tssimilarity index 100%rename from src/features/ppt-editor/adapters/toCanvasAnvil.tsrename to client/features/ppt-editor/adapters/toCanvasAnvil.tsdiff --git a/src/features/ppt-editor/components/PptEditorBridge.tsx b/client/features/ppt-editor/components/PptEditorBridge.tsxsimilarity index 100%rename from src/features/ppt-editor/components/PptEditorBridge.tsxrename to client/features/ppt-editor/components/PptEditorBridge.tsxdiff --git a/src/features/ppt-editor/components/PptReviewBridge.tsx b/client/features/ppt-editor/components/PptReviewBridge.tsxsimilarity index 100%rename from src/features/ppt-editor/components/PptReviewBridge.tsxrename to client/features/ppt-editor/components/PptReviewBridge.tsxdiff --git a/src/features/ppt-editor/components/index.ts b/client/features/ppt-editor/components/index.tssimilarity index 100%rename from src/features/ppt-editor/components/index.tsrename to client/features/ppt-editor/components/index.tsdiff --git a/src/features/ppt-editor/index.ts b/client/features/ppt-editor/index.tssimilarity index 100%rename from src/features/ppt-editor/index.tsrename to client/features/ppt-editor/index.tsdiff --git a/src/features/ppt-editor/shape-config.ts b/client/features/ppt-editor/shape-config.tssimilarity index 100%rename from src/features/ppt-editor/shape-config.tsrename to client/features/ppt-editor/shape-config.tsdiff --git a/src/features/ppt-editor/types.ts b/client/features/ppt-editor/types.tssimilarity index 100%rename from src/features/ppt-editor/types.tsrename to client/features/ppt-editor/types.tsdiff --git a/src/index.css b/client/index.csssimilarity index 100%rename from src/index.cssrename to client/index.cssdiff --git a/client/lib/cad-agents.ts b/client/lib/cad-agents.tsnew file mode 100644index 0000000..ea2dab3--- /dev/null+++ b/client/lib/cad-agents.ts@@ -0,0 +1,9 @@+import cadPlanAgentPrompt from "@prompts/cad/plan.md?raw";+import cadSvgRouterAgentPrompt from "@prompts/cad/svg/system.md?raw";+import cadSvgFlowPatchAgentPrompt from "@prompts/cad/svg/patch.md?raw";+import cadSvgFlowReplaceAgentPrompt from "@prompts/cad/svg/replace.md?raw";++export const CAD_PLAN_AGENT_PROMPT = cadPlanAgentPrompt;+export const CAD_SVG_AGENT_ROUTER_PROMPT = cadSvgRouterAgentPrompt;+export const CAD_SVG_FLOW_PATCH_AGENT_PROMPT = cadSvgFlowPatchAgentPrompt;+export const CAD_SVG_FLOW_REPLACE_AGENT_PROMPT = cadSvgFlowReplaceAgentPrompt;diff --git a/src/lib/cad-render-titles.ts b/client/lib/cad-render-titles.tssimilarity index 100%rename from src/lib/cad-render-titles.tsrename to client/lib/cad-render-titles.tsdiff --git a/src/lib/cad-tasks.ts b/client/lib/cad-tasks.tssimilarity index 78%rename from src/lib/cad-tasks.tsrename to client/lib/cad-tasks.tsindex e4e74c3..1a433b1 100644--- a/src/lib/cad-tasks.ts+++ b/client/lib/cad-tasks.ts@@ -1,16 +1,16 @@import type { ChatMessage } from "@/ai/client";-import cadBomPromptTemplate from "../../agent/cad/bom-prompt.md?raw";-import cadImagesMasterRenovationSchemeTemplate from "../../agent/cad/images-agents/master-renovation-scheme.md?raw";-import cadRenovationPlanLayoutTemplate from "../../agent/cad/images-agents/renovation-plan-layout.md?raw";-import cadFloorFinishPlanTemplate from "../../agent/cad/images-agents/floor-finish-plan.md?raw";-import cadReflectedCeilingPlanTemplate from "../../agent/cad/images-agents/reflected-ceiling-plan.md?raw";-import cadWallSettingOutPlanTemplate from "../../agent/cad/images-agents/wall-setting-out-plan.md?raw";-import cadMepPlanTemplate from "../../agent/cad/images-agents/mep-plan.md?raw";-import cadElevationIndexAndInteriorElevationsTemplate from "../../agent/cad/images-agents/elevation-index-and-interior-elevations.md?raw";-import cadDetailDrawingsTemplate from "../../agent/cad/images-agents/detail-drawings.md?raw";-import cadOverallAnalysisBoardTemplate from "../../agent/cad/images-agents/overall-analysis-board.md?raw";-import cadKeyStrategyBoardTemplate from "../../agent/cad/images-agents/key-strategy-board.md?raw";+import cadBomPromptTemplate from "@prompts/cad/bom-prompt.md?raw";+import cadImagesMasterRenovationSchemeTemplate from "@prompts/cad/images-agents/master-renovation-scheme.md?raw";+import cadRenovationPlanLayoutTemplate from "@prompts/cad/images-agents/renovation-plan-layout.md?raw";+import cadFloorFinishPlanTemplate from "@prompts/cad/images-agents/floor-finish-plan.md?raw";+import cadReflectedCeilingPlanTemplate from "@prompts/cad/images-agents/reflected-ceiling-plan.md?raw";+import cadWallSettingOutPlanTemplate from "@prompts/cad/images-agents/wall-setting-out-plan.md?raw";+import cadMepPlanTemplate from "@prompts/cad/images-agents/mep-plan.md?raw";+import cadElevationIndexAndInteriorElevationsTemplate from "@prompts/cad/images-agents/elevation-index-and-interior-elevations.md?raw";+import cadDetailDrawingsTemplate from "@prompts/cad/images-agents/detail-drawings.md?raw";+import cadOverallAnalysisBoardTemplate from "@prompts/cad/images-agents/overall-analysis-board.md?raw";+import cadKeyStrategyBoardTemplate from "@prompts/cad/images-agents/key-strategy-board.md?raw";function applyTemplate(template: string, vars: Record<string, string>) {let out = String(template || "");diff --git a/src/lib/ppt-prompts.ts b/client/lib/ppt-prompts.tssimilarity index 100%rename from src/lib/ppt-prompts.tsrename to client/lib/ppt-prompts.tsdiff --git a/src/lib/ppt-service.ts b/client/lib/ppt-service.tssimilarity index 99%rename from src/lib/ppt-service.tsrename to client/lib/ppt-service.tsindex e004a93..53370ba 100644--- a/src/lib/ppt-service.ts+++ b/client/lib/ppt-service.ts@@ -1,7 +1,7 @@import { generateChatMessage, generateImage, generateVisionChatMessage } from "@/ai/client"import { buildRisenPrompt } from "./risen-prompt"-import pptOutlineSystem from "../../agent/ppt/outline.md?raw"-import pptSlidesGenerateSystem from "../../agent/ppt/slides-generate.md?raw"+import pptOutlineSystem from "@prompts/ppt/outline.md?raw"+import pptSlidesGenerateSystem from "@prompts/ppt/slides-generate.md?raw"export interface PptPage {title: string;diff --git a/src/lib/risen-prompt.ts b/client/lib/risen-prompt.tssimilarity index 100%rename from src/lib/risen-prompt.tsrename to client/lib/risen-prompt.tsdiff --git a/client/lib/system-prompts.ts b/client/lib/system-prompts.tsnew file mode 100644index 0000000..803f1d2--- /dev/null+++ b/client/lib/system-prompts.ts@@ -0,0 +1,13 @@+import drawioPrompt from "@prompts/flow/system.md?raw";+import cadPrompt from "@prompts/cad/system.md?raw";+import pptOutlinePrompt from "@prompts/ppt/outline.md?raw";+import pptOutlineEditPrompt from "@prompts/ppt/outline-edit.md?raw";+import pptSlidesGeneratePrompt from "@prompts/ppt/slides-generate.md?raw";+import pptSlidesEditPrompt from "@prompts/ppt/system.md?raw";++export const DRAWIO_SYSTEM_PROMPT = drawioPrompt;+export const CAD_SYSTEM_PROMPT = cadPrompt;+export const PPT_OUTLINE_SYSTEM_PROMPT = pptOutlinePrompt;+export const PPT_OUTLINE_EDIT_SYSTEM_PROMPT = pptOutlineEditPrompt;+export const PPT_SLIDES_GENERATE_SYSTEM_PROMPT = pptSlidesGeneratePrompt;+export const PPT_SLIDES_EDIT_SYSTEM_PROMPT = pptSlidesEditPrompt;diff --git a/src/main.tsx b/client/main.tsxsimilarity index 100%rename from src/main.tsxrename to client/main.tsxdiff --git a/src/pages/LandingPage.tsx b/client/pages/LandingPage.tsxsimilarity index 100%rename from src/pages/LandingPage.tsxrename to client/pages/LandingPage.tsxdiff --git a/src/pages/portal/PortalPage.tsx b/client/pages/portal/PortalPage.tsxsimilarity index 100%rename from src/pages/portal/PortalPage.tsxrename to client/pages/portal/PortalPage.tsxdiff --git a/src/pages/portal/data.ts b/client/pages/portal/data.tssimilarity index 100%rename from src/pages/portal/data.tsrename to client/pages/portal/data.tsdiff --git a/src/shared/chat/assistant-stream.ts b/client/shared/chat/assistant-stream.tssimilarity index 98%rename from src/shared/chat/assistant-stream.tsrename to client/shared/chat/assistant-stream.tsindex bc5de5d..ca6bdc3 100644--- a/src/shared/chat/assistant-stream.ts+++ b/client/shared/chat/assistant-stream.ts@@ -1,5 +1,5 @@import type { Dispatch, SetStateAction } from "react"-import type { ChatMessage } from "@/ai/types"+import type { ChatMessage } from "@contracts/ai"/*** Coalesces streamed assistant chunks into one repaint per frame.diff --git a/src/shared/chat/bom-table.ts b/client/shared/chat/bom-table.tssimilarity index 100%rename from src/shared/chat/bom-table.tsrename to client/shared/chat/bom-table.tsdiff --git a/src/shared/chat/button-with-tooltip.tsx b/client/shared/chat/button-with-tooltip.tsxsimilarity index 100%rename from src/shared/chat/button-with-tooltip.tsxrename to client/shared/chat/button-with-tooltip.tsxdiff --git a/src/shared/chat/chat-errors.ts b/client/shared/chat/chat-errors.tssimilarity index 100%rename from src/shared/chat/chat-errors.tsrename to client/shared/chat/chat-errors.tsdiff --git a/src/shared/chat/chat-input.tsx b/client/shared/chat/chat-input.tsxsimilarity index 100%rename from src/shared/chat/chat-input.tsxrename to client/shared/chat/chat-input.tsxdiff --git a/src/shared/chat/chat-storage.ts b/client/shared/chat/chat-storage.tssimilarity index 99%rename from src/shared/chat/chat-storage.tsrename to client/shared/chat/chat-storage.tsindex c184263..db82602 100644--- a/src/shared/chat/chat-storage.ts+++ b/client/shared/chat/chat-storage.ts@@ -1,4 +1,4 @@-import type { ChatMessage } from "@/ai/types"+import type { ChatMessage } from "@contracts/ai"/*** Chat history persistence.diff --git a/src/shared/chat/file-preview-list.tsx b/client/shared/chat/file-preview-list.tsxsimilarity index 100%rename from src/shared/chat/file-preview-list.tsxrename to client/shared/chat/file-preview-list.tsxdiff --git a/src/shared/chat/global-constraints-dialog.tsx b/client/shared/chat/global-constraints-dialog.tsxsimilarity index 100%rename from src/shared/chat/global-constraints-dialog.tsxrename to client/shared/chat/global-constraints-dialog.tsxdiff --git a/src/shared/chat/history-dialog.tsx b/client/shared/chat/history-dialog.tsxsimilarity index 100%rename from src/shared/chat/history-dialog.tsxrename to client/shared/chat/history-dialog.tsxdiff --git a/src/shared/chat/index.ts b/client/shared/chat/index.tssimilarity index 100%rename from src/shared/chat/index.tsrename to client/shared/chat/index.tsdiff --git a/src/shared/chat/reasoning.tsx b/client/shared/chat/reasoning.tsxsimilarity index 100%rename from src/shared/chat/reasoning.tsxrename to client/shared/chat/reasoning.tsxdiff --git a/src/shared/chat/reset-warning-modal.tsx b/client/shared/chat/reset-warning-modal.tsxsimilarity index 100%rename from src/shared/chat/reset-warning-modal.tsxrename to client/shared/chat/reset-warning-modal.tsxdiff --git a/src/shared/chat/shimmer.tsx b/client/shared/chat/shimmer.tsxsimilarity index 100%rename from src/shared/chat/shimmer.tsxrename to client/shared/chat/shimmer.tsxdiff --git a/src/shared/files/binary.ts b/client/shared/files/binary.tssimilarity index 100%rename from src/shared/files/binary.tsrename to client/shared/files/binary.tsdiff --git a/src/shared/files/detect.ts b/client/shared/files/detect.tssimilarity index 100%rename from src/shared/files/detect.tsrename to client/shared/files/detect.tsdiff --git a/src/shared/files/extract-text.ts b/client/shared/files/extract-text.tssimilarity index 100%rename from src/shared/files/extract-text.tsrename to client/shared/files/extract-text.tsdiff --git a/src/shared/files/index.ts b/client/shared/files/index.tssimilarity index 100%rename from src/shared/files/index.tsrename to client/shared/files/index.tsdiff --git a/src/shared/files/latex-archives.ts b/client/shared/files/latex-archives.tssimilarity index 100%rename from src/shared/files/latex-archives.tsrename to client/shared/files/latex-archives.tsdiff --git a/src/shared/files/pdf-render.ts b/client/shared/files/pdf-render.tssimilarity index 100%rename from src/shared/files/pdf-render.tsrename to client/shared/files/pdf-render.tsdiff --git a/src/shared/files/types.ts b/client/shared/files/types.tssimilarity index 100%rename from src/shared/files/types.tsrename to client/shared/files/types.tsdiff --git a/src/shared/files/use-file-processor.ts b/client/shared/files/use-file-processor.tssimilarity index 99%rename from src/shared/files/use-file-processor.tsrename to client/shared/files/use-file-processor.tsindex 6464be7..cac7672 100644--- a/src/shared/files/use-file-processor.ts+++ b/client/shared/files/use-file-processor.ts@@ -2,7 +2,7 @@import { useState } from "react"import { toast } from "sonner"-import { getAIConfig } from "@/ai/config"+import { getAIConfig } from "@/ai/storage";import {MAX_EXTRACTED_CHARS,isPdfFile,diff --git a/src/shared/files/visual-assets.ts b/client/shared/files/visual-assets.tssimilarity index 100%rename from src/shared/files/visual-assets.tsrename to client/shared/files/visual-assets.tsdiff --git a/src/shared/i18n/index.ts b/client/shared/i18n/index.tssimilarity index 100%rename from src/shared/i18n/index.tsrename to client/shared/i18n/index.tsdiff --git a/src/shared/i18n/language.ts b/client/shared/i18n/language.tssimilarity index 100%rename from src/shared/i18n/language.tsrename to client/shared/i18n/language.tsdiff --git a/src/shared/i18n/messages.ts b/client/shared/i18n/messages.tssimilarity index 100%rename from src/shared/i18n/messages.tsrename to client/shared/i18n/messages.tsdiff --git a/src/shared/i18n/translator.ts b/client/shared/i18n/translator.tssimilarity index 100%rename from src/shared/i18n/translator.tsrename to client/shared/i18n/translator.tsdiff --git a/src/shared/lib/utils.ts b/client/shared/lib/utils.tssimilarity index 100%rename from src/shared/lib/utils.tsrename to client/shared/lib/utils.tsdiff --git a/src/shared/storage/indexed-db-store.ts b/client/shared/storage/indexed-db-store.tssimilarity index 100%rename from src/shared/storage/indexed-db-store.tsrename to client/shared/storage/indexed-db-store.tsdiff --git a/src/shared/ui/button.tsx b/client/shared/ui/button.tsxsimilarity index 100%rename from src/shared/ui/button.tsxrename to client/shared/ui/button.tsxdiff --git a/src/shared/ui/collapsible.tsx b/client/shared/ui/collapsible.tsxsimilarity index 100%rename from src/shared/ui/collapsible.tsxrename to client/shared/ui/collapsible.tsxdiff --git a/src/shared/ui/context-menu.tsx b/client/shared/ui/context-menu.tsxsimilarity index 100%rename from src/shared/ui/context-menu.tsxrename to client/shared/ui/context-menu.tsxdiff --git a/src/shared/ui/dialog.tsx b/client/shared/ui/dialog.tsxsimilarity index 100%rename from src/shared/ui/dialog.tsxrename to client/shared/ui/dialog.tsxdiff --git a/src/shared/ui/input.tsx b/client/shared/ui/input.tsxsimilarity index 100%rename from src/shared/ui/input.tsxrename to client/shared/ui/input.tsxdiff --git a/src/shared/ui/label.tsx b/client/shared/ui/label.tsxsimilarity index 100%rename from src/shared/ui/label.tsxrename to client/shared/ui/label.tsxdiff --git a/src/shared/ui/resizable.tsx b/client/shared/ui/resizable.tsxsimilarity index 100%rename from src/shared/ui/resizable.tsxrename to client/shared/ui/resizable.tsxdiff --git a/src/shared/ui/scroll-area.tsx b/client/shared/ui/scroll-area.tsxsimilarity index 100%rename from src/shared/ui/scroll-area.tsxrename to client/shared/ui/scroll-area.tsxdiff --git a/src/shared/ui/select.tsx b/client/shared/ui/select.tsxsimilarity index 100%rename from src/shared/ui/select.tsxrename to client/shared/ui/select.tsxdiff --git a/src/shared/ui/switch.tsx b/client/shared/ui/switch.tsxsimilarity index 100%rename from src/shared/ui/switch.tsxrename to client/shared/ui/switch.tsxdiff --git a/src/shared/ui/textarea.tsx b/client/shared/ui/textarea.tsxsimilarity index 100%rename from src/shared/ui/textarea.tsxrename to client/shared/ui/textarea.tsxdiff --git a/src/shared/ui/tooltip.tsx b/client/shared/ui/tooltip.tsxsimilarity index 100%rename from src/shared/ui/tooltip.tsxrename to client/shared/ui/tooltip.tsxdiff --git a/src/vite-env.d.ts b/client/vite-env.d.tssimilarity index 100%rename from src/vite-env.d.tsrename to client/vite-env.d.tsdiff --git a/src/workspaces/cad/CadWorkspaceShell.tsx b/client/workspaces/cad/CadWorkspaceShell.tsxsimilarity index 100%rename from src/workspaces/cad/CadWorkspaceShell.tsxrename to client/workspaces/cad/CadWorkspaceShell.tsxdiff --git a/src/workspaces/cad/chat/ChatMessageDisplay.tsx b/client/workspaces/cad/chat/ChatMessageDisplay.tsxsimilarity index 100%rename from src/workspaces/cad/chat/ChatMessageDisplay.tsxrename to client/workspaces/cad/chat/ChatMessageDisplay.tsxdiff --git a/src/workspaces/cad/chat/ChatPanel.tsx b/client/workspaces/cad/chat/ChatPanel.tsxsimilarity index 100%rename from src/workspaces/cad/chat/ChatPanel.tsxrename to client/workspaces/cad/chat/ChatPanel.tsxdiff --git a/src/workspaces/cad/chat/code-block.tsx b/client/workspaces/cad/chat/code-block.tsxsimilarity index 100%rename from src/workspaces/cad/chat/code-block.tsxrename to client/workspaces/cad/chat/code-block.tsxdiff --git a/src/workspaces/cad/storage.ts b/client/workspaces/cad/storage.tssimilarity index 100%rename from src/workspaces/cad/storage.tsrename to client/workspaces/cad/storage.tsdiff --git a/src/workspaces/cad/workspace/CadWorkspace.tsx b/client/workspaces/cad/workspace/CadWorkspace.tsxsimilarity index 100%rename from src/workspaces/cad/workspace/CadWorkspace.tsxrename to client/workspaces/cad/workspace/CadWorkspace.tsxdiff --git a/src/workspaces/flow/FlowWorkspaceShell.tsx b/client/workspaces/flow/FlowWorkspaceShell.tsxsimilarity index 100%rename from src/workspaces/flow/FlowWorkspaceShell.tsxrename to client/workspaces/flow/FlowWorkspaceShell.tsxdiff --git a/src/workspaces/flow/next/NextFlowWorkspace.tsx b/client/workspaces/flow/next/NextFlowWorkspace.tsxsimilarity index 100%rename from src/workspaces/flow/next/NextFlowWorkspace.tsxrename to client/workspaces/flow/next/NextFlowWorkspace.tsxdiff --git a/src/workspaces/flow/next/components/chat-input.tsx b/client/workspaces/flow/next/components/chat-input.tsxsimilarity index 100%rename from src/workspaces/flow/next/components/chat-input.tsxrename to client/workspaces/flow/next/components/chat-input.tsxdiff --git a/src/workspaces/flow/next/components/chat-message-display.tsx b/client/workspaces/flow/next/components/chat-message-display.tsxsimilarity index 100%rename from src/workspaces/flow/next/components/chat-message-display.tsxrename to client/workspaces/flow/next/components/chat-message-display.tsxdiff --git a/src/workspaces/flow/next/components/chat-panel.tsx b/client/workspaces/flow/next/components/chat-panel.tsxsimilarity index 100%rename from src/workspaces/flow/next/components/chat-panel.tsxrename to client/workspaces/flow/next/components/chat-panel.tsxdiff --git a/src/workspaces/flow/next/components/code-block.tsx b/client/workspaces/flow/next/components/code-block.tsxsimilarity index 100%rename from src/workspaces/flow/next/components/code-block.tsxrename to client/workspaces/flow/next/components/code-block.tsxdiff --git a/src/workspaces/flow/next/components/error-toast.tsx b/client/workspaces/flow/next/components/error-toast.tsxsimilarity index 100%rename from src/workspaces/flow/next/components/error-toast.tsxrename to client/workspaces/flow/next/components/error-toast.tsxdiff --git a/src/workspaces/flow/next/components/history-dialog.tsx b/client/workspaces/flow/next/components/history-dialog.tsxsimilarity index 100%rename from src/workspaces/flow/next/components/history-dialog.tsxrename to client/workspaces/flow/next/components/history-dialog.tsxdiff --git a/src/workspaces/flow/next/components/quota-limit-toast.tsx b/client/workspaces/flow/next/components/quota-limit-toast.tsxsimilarity index 100%rename from src/workspaces/flow/next/components/quota-limit-toast.tsxrename to client/workspaces/flow/next/components/quota-limit-toast.tsxdiff --git a/src/workspaces/flow/next/components/save-dialog.tsx b/client/workspaces/flow/next/components/save-dialog.tsxsimilarity index 100%rename from src/workspaces/flow/next/components/save-dialog.tsxrename to client/workspaces/flow/next/components/save-dialog.tsxdiff --git a/src/workspaces/flow/next/components/settings-dialog.tsx b/client/workspaces/flow/next/components/settings-dialog.tsxsimilarity index 100%rename from src/workspaces/flow/next/components/settings-dialog.tsxrename to client/workspaces/flow/next/components/settings-dialog.tsxdiff --git a/src/workspaces/flow/next/contexts/diagram-context.tsx b/client/workspaces/flow/next/contexts/diagram-context.tsxsimilarity index 100%rename from src/workspaces/flow/next/contexts/diagram-context.tsxrename to client/workspaces/flow/next/contexts/diagram-context.tsxdiff --git a/src/workspaces/flow/next/lib/ai-config.ts b/client/workspaces/flow/next/lib/ai-config.tssimilarity index 79%rename from src/workspaces/flow/next/lib/ai-config.tsrename to client/workspaces/flow/next/lib/ai-config.tsindex e0de7ec..166d9ca 100644--- a/src/workspaces/flow/next/lib/ai-config.ts+++ b/client/workspaces/flow/next/lib/ai-config.ts@@ -1,6 +1,7 @@import { STORAGE_KEYS } from "@/workspaces/flow/next/lib/storage"-import { DEFAULT_AI_CONFIG, getAIConfig as getWorkspaceAIConfig } from "@/ai/config"-import type { AIConfig } from "@/ai/types"+import { DEFAULT_AI_CONFIG } from "@contracts/ai";+import { getAIConfig as getWorkspaceAIConfig } from "@/ai/storage";+import type { AIConfig } from "@contracts/ai"/*** The Flow workspace sends its model settings to `/api/chat` alongside andiff --git a/src/workspaces/flow/next/lib/diagram-operations.ts b/client/workspaces/flow/next/lib/diagram-operations.tssimilarity index 100%rename from src/workspaces/flow/next/lib/diagram-operations.tsrename to client/workspaces/flow/next/lib/diagram-operations.tsdiff --git a/src/workspaces/flow/next/lib/drawio-xml.ts b/client/workspaces/flow/next/lib/drawio-xml.tssimilarity index 100%rename from src/workspaces/flow/next/lib/drawio-xml.tsrename to client/workspaces/flow/next/lib/drawio-xml.tsdiff --git a/src/workspaces/flow/next/lib/flow-storage-keys.ts b/client/workspaces/flow/next/lib/flow-storage-keys.tssimilarity index 100%rename from src/workspaces/flow/next/lib/flow-storage-keys.tsrename to client/workspaces/flow/next/lib/flow-storage-keys.tsdiff --git a/src/workspaces/flow/next/lib/storage.ts b/client/workspaces/flow/next/lib/storage.tssimilarity index 100%rename from src/workspaces/flow/next/lib/storage.tsrename to client/workspaces/flow/next/lib/storage.tsdiff --git a/src/workspaces/flow/next/lib/translations.ts b/client/workspaces/flow/next/lib/translations.tssimilarity index 100%rename from src/workspaces/flow/next/lib/translations.tsrename to client/workspaces/flow/next/lib/translations.tsdiff --git a/src/workspaces/flow/next/lib/use-quota-manager.tsx b/client/workspaces/flow/next/lib/use-quota-manager.tsxsimilarity index 100%rename from src/workspaces/flow/next/lib/use-quota-manager.tsxrename to client/workspaces/flow/next/lib/use-quota-manager.tsxdiff --git a/src/workspaces/flow/next/page.tsx b/client/workspaces/flow/next/page.tsxsimilarity index 100%rename from src/workspaces/flow/next/page.tsxrename to client/workspaces/flow/next/page.tsxdiff --git a/src/workspaces/flow/next/shims/next-image.tsx b/client/workspaces/flow/next/shims/next-image.tsxsimilarity index 100%rename from src/workspaces/flow/next/shims/next-image.tsxrename to client/workspaces/flow/next/shims/next-image.tsxdiff --git a/src/workspaces/ppt/PptWorkspaceShell.tsx b/client/workspaces/ppt/PptWorkspaceShell.tsxsimilarity index 100%rename from src/workspaces/ppt/PptWorkspaceShell.tsxrename to client/workspaces/ppt/PptWorkspaceShell.tsxdiff --git a/src/workspaces/ppt/chat/ChatMessageDisplay.tsx b/client/workspaces/ppt/chat/ChatMessageDisplay.tsxsimilarity index 100%rename from src/workspaces/ppt/chat/ChatMessageDisplay.tsxrename to client/workspaces/ppt/chat/ChatMessageDisplay.tsxdiff --git a/src/workspaces/ppt/chat/ChatPanel.tsx b/client/workspaces/ppt/chat/ChatPanel.tsxsimilarity index 100%rename from src/workspaces/ppt/chat/ChatPanel.tsxrename to client/workspaces/ppt/chat/ChatPanel.tsxdiff --git a/src/workspaces/ppt/chat/code-block.tsx b/client/workspaces/ppt/chat/code-block.tsxsimilarity index 100%rename from src/workspaces/ppt/chat/code-block.tsxrename to client/workspaces/ppt/chat/code-block.tsxdiff --git a/src/workspaces/ppt/storage.ts b/client/workspaces/ppt/storage.tssimilarity index 100%rename from src/workspaces/ppt/storage.tsrename to client/workspaces/ppt/storage.tsdiff --git a/src/workspaces/ppt/workspace/PptWorkspace.tsx b/client/workspaces/ppt/workspace/PptWorkspace.tsxsimilarity index 100%rename from src/workspaces/ppt/workspace/PptWorkspace.tsxrename to client/workspaces/ppt/workspace/PptWorkspace.tsxdiff --git a/src/workspaces/ppt/workspace/constants.ts b/client/workspaces/ppt/workspace/constants.tssimilarity index 100%rename from src/workspaces/ppt/workspace/constants.tsrename to client/workspaces/ppt/workspace/constants.tsdiff --git a/src/workspaces/ppt/workspace/persisted-state.ts b/client/workspaces/ppt/workspace/persisted-state.tssimilarity index 100%rename from src/workspaces/ppt/workspace/persisted-state.tsrename to client/workspaces/ppt/workspace/persisted-state.tsdiff --git a/src/workspaces/ppt/workspace/slide-content.ts b/client/workspaces/ppt/workspace/slide-content.tssimilarity index 100%rename from src/workspaces/ppt/workspace/slide-content.tsrename to client/workspaces/ppt/workspace/slide-content.tsdiff --git a/src/workspaces/ppt/workspace/types.ts b/client/workspaces/ppt/workspace/types.tssimilarity index 100%rename from src/workspaces/ppt/workspace/types.tsrename to client/workspaces/ppt/workspace/types.tsdiff --git a/src/ai/config.ts b/contracts/ai.tssimilarity index 53%rename from src/ai/config.tsrename to contracts/ai.tsindex bc95030..1d25c33 100644--- a/src/ai/config.ts+++ b/contracts/ai.ts@@ -1,4 +1,66 @@-import type { AIChannel, AIConfig } from "./types";+/**+ * The contract between the browser and the API.+ *+ * The client sends its AI settings with every request and the server+ * interprets them, so both sides need the same shape and the same+ * normalisation. Nothing here touches a browser or a Node API, which is what+ * lets it sit outside both.+ */++export interface AIChannel {+ apiKey: string;+ baseUrl: string;+ model: string;+}++/**+ * Persisted settings. Text and image are separate channels because the two+ * are commonly served by different endpoints; each is still plain OpenAI.+ */+export interface AIConfig {+ textApiKey: string;+ textBaseUrl: string;+ textModel: string;+ imageApiKey: string;+ imageBaseUrl: string;+ imageModel: string;+ fileParserApiToken: string;+ systemPrompt: string;+}++export type ChatRole = "system" | "user" | "assistant";++export type ChatContentPart =+ | { type: "text"; text: string }+ | { type: "image_url"; image_url: { url: string } };++/** The common case: a text-only turn. */+export interface ChatMessage {+ role: ChatRole;+ content: string;+}++/** A turn that may also carry images, using OpenAI's content-part array. */+export interface MultimodalMessage {+ role: ChatRole;+ content: string | ChatContentPart[];+}++export interface TextRequest {+ channel: AIChannel;+ messages: MultimodalMessage[];+ signal?: AbortSignal;+}++export interface ImageRequest {+ channel: AIChannel;+ prompt: string;+ /** Primary reference image. Its presence selects the `/images/edits` route. */+ referenceImageUrl?: string;+ additionalReferenceImageUrls?: string[];+ maskImageUrl?: string;+ signal?: AbortSignal;+}export const DEFAULT_BASE_URL = "https://api.openai.com/v1";@@ -13,8 +75,6 @@ export const DEFAULT_AI_CONFIG: AIConfig = {systemPrompt: "",};-const STORAGE_KEY = "unified_ai_workspace_config";-const str = (value: unknown, fallback = "") => {const text = String(value ?? "").trim();return text || fallback;@@ -59,23 +119,3 @@ export function getImageChannel(config: AIConfig): AIChannel {model: config.imageModel,};}--export function getAIConfig(): AIConfig {- if (typeof window === "undefined") return DEFAULT_AI_CONFIG;- const stored = localStorage.getItem(STORAGE_KEY);- if (!stored) return DEFAULT_AI_CONFIG;- try {- return normalizeAIConfig({ ...DEFAULT_AI_CONFIG, ...JSON.parse(stored) });- } catch {- try {- localStorage.removeItem(STORAGE_KEY);- } catch {- // A storage that cannot be written to cannot be repaired; fall through.- }- return DEFAULT_AI_CONFIG;- }-}--export function saveAIConfig(config: AIConfig) {- localStorage.setItem(STORAGE_KEY, JSON.stringify(normalizeAIConfig(config)));-}diff --git a/index.html b/index.htmlindex 6dcdcb7..7dec64c 100644--- a/index.html+++ b/index.html@@ -20,6 +20,6 @@</head><body><div id="root"></div>- <script type="module" src="/src/main.tsx"></script>+ <script type="module" src="/client/main.tsx"></script></body></html>diff --git a/package.json b/package.jsonindex 7a4b42a..ccf2595 100644--- a/package.json+++ b/package.json@@ -6,8 +6,8 @@"type": "module","scripts": {"dev": "vite --host 0.0.0.0 --port 8001",- "dev:api": "tsx watch api/server.ts",- "start": "tsx api/server.ts",+ "dev:api": "tsx watch server/index.ts",+ "start": "tsx server/index.ts","build": "tsc -b && vite build","lint": "eslint .","test": "tsx --test tests/*.test.ts",diff --git a/agent/cad/bom-prompt.md b/resources/prompts/cad/bom-prompt.mdsimilarity index 100%rename from agent/cad/bom-prompt.mdrename to resources/prompts/cad/bom-prompt.mddiff --git a/agent/cad/images-agents/detail-drawings.md b/resources/prompts/cad/images-agents/detail-drawings.mdsimilarity index 100%rename from agent/cad/images-agents/detail-drawings.mdrename to resources/prompts/cad/images-agents/detail-drawings.mddiff --git a/agent/cad/images-agents/elevation-index-and-interior-elevations.md b/resources/prompts/cad/images-agents/elevation-index-and-interior-elevations.mdsimilarity index 100%rename from agent/cad/images-agents/elevation-index-and-interior-elevations.mdrename to resources/prompts/cad/images-agents/elevation-index-and-interior-elevations.mddiff --git a/agent/cad/images-agents/floor-finish-plan.md b/resources/prompts/cad/images-agents/floor-finish-plan.mdsimilarity index 100%rename from agent/cad/images-agents/floor-finish-plan.mdrename to resources/prompts/cad/images-agents/floor-finish-plan.mddiff --git a/agent/cad/images-agents/key-strategy-board.md b/resources/prompts/cad/images-agents/key-strategy-board.mdsimilarity index 100%rename from agent/cad/images-agents/key-strategy-board.mdrename to resources/prompts/cad/images-agents/key-strategy-board.mddiff --git a/agent/cad/images-agents/master-renovation-scheme.md b/resources/prompts/cad/images-agents/master-renovation-scheme.mdsimilarity index 100%rename from agent/cad/images-agents/master-renovation-scheme.mdrename to resources/prompts/cad/images-agents/master-renovation-scheme.mddiff --git a/agent/cad/images-agents/mep-plan.md b/resources/prompts/cad/images-agents/mep-plan.mdsimilarity index 100%rename from agent/cad/images-agents/mep-plan.mdrename to resources/prompts/cad/images-agents/mep-plan.mddiff --git a/agent/cad/images-agents/overall-analysis-board.md b/resources/prompts/cad/images-agents/overall-analysis-board.mdsimilarity index 100%rename from agent/cad/images-agents/overall-analysis-board.mdrename to resources/prompts/cad/images-agents/overall-analysis-board.mddiff --git a/agent/cad/images-agents/reflected-ceiling-plan.md b/resources/prompts/cad/images-agents/reflected-ceiling-plan.mdsimilarity index 100%rename from agent/cad/images-agents/reflected-ceiling-plan.mdrename to resources/prompts/cad/images-agents/reflected-ceiling-plan.mddiff --git a/agent/cad/images-agents/renovation-plan-layout.md b/resources/prompts/cad/images-agents/renovation-plan-layout.mdsimilarity index 100%rename from agent/cad/images-agents/renovation-plan-layout.mdrename to resources/prompts/cad/images-agents/renovation-plan-layout.mddiff --git a/agent/cad/images-agents/wall-setting-out-plan.md b/resources/prompts/cad/images-agents/wall-setting-out-plan.mdsimilarity index 100%rename from agent/cad/images-agents/wall-setting-out-plan.mdrename to resources/prompts/cad/images-agents/wall-setting-out-plan.mddiff --git a/agent/cad/plan.md b/resources/prompts/cad/plan.mdsimilarity index 100%rename from agent/cad/plan.mdrename to resources/prompts/cad/plan.mddiff --git a/agent/cad/svg/patch.md b/resources/prompts/cad/svg/patch.mdsimilarity index 100%rename from agent/cad/svg/patch.mdrename to resources/prompts/cad/svg/patch.mddiff --git a/agent/cad/svg/replace.md b/resources/prompts/cad/svg/replace.mdsimilarity index 100%rename from agent/cad/svg/replace.mdrename to resources/prompts/cad/svg/replace.mddiff --git a/agent/cad/svg/system.md b/resources/prompts/cad/svg/system.mdsimilarity index 100%rename from agent/cad/svg/system.mdrename to resources/prompts/cad/svg/system.mddiff --git a/agent/cad/system.md b/resources/prompts/cad/system.mdsimilarity index 100%rename from agent/cad/system.mdrename to resources/prompts/cad/system.mddiff --git a/agent/flow/deep-thinking-image.md b/resources/prompts/flow/deep-thinking-image.mdsimilarity index 100%rename from agent/flow/deep-thinking-image.mdrename to resources/prompts/flow/deep-thinking-image.mddiff --git a/agent/flow/patch.md b/resources/prompts/flow/patch.mdsimilarity index 100%rename from agent/flow/patch.mdrename to resources/prompts/flow/patch.mddiff --git a/agent/flow/replace.md b/resources/prompts/flow/replace.mdsimilarity index 100%rename from agent/flow/replace.mdrename to resources/prompts/flow/replace.mddiff --git a/agent/flow/system.md b/resources/prompts/flow/system.mdsimilarity index 100%rename from agent/flow/system.mdrename to resources/prompts/flow/system.mddiff --git a/agent/ppt/outline-edit.md b/resources/prompts/ppt/outline-edit.mdsimilarity index 100%rename from agent/ppt/outline-edit.mdrename to resources/prompts/ppt/outline-edit.mddiff --git a/agent/ppt/outline.md b/resources/prompts/ppt/outline.mdsimilarity index 100%rename from agent/ppt/outline.mdrename to resources/prompts/ppt/outline.mddiff --git a/agent/ppt/slides-generate.md b/resources/prompts/ppt/slides-generate.mdsimilarity index 100%rename from agent/ppt/slides-generate.mdrename to resources/prompts/ppt/slides-generate.mddiff --git a/agent/ppt/system.md b/resources/prompts/ppt/system.mdsimilarity index 100%rename from agent/ppt/system.mdrename to resources/prompts/ppt/system.mddiff --git a/docs/shape-libraries/README.md b/resources/shape-libraries/README.mdsimilarity index 100%rename from docs/shape-libraries/README.mdrename to resources/shape-libraries/README.mddiff --git a/docs/shape-libraries/alibaba_cloud.md b/resources/shape-libraries/alibaba_cloud.mdsimilarity index 100%rename from docs/shape-libraries/alibaba_cloud.mdrename to resources/shape-libraries/alibaba_cloud.mddiff --git a/docs/shape-libraries/android.md b/resources/shape-libraries/android.mdsimilarity index 100%rename from docs/shape-libraries/android.mdrename to resources/shape-libraries/android.mddiff --git a/docs/shape-libraries/arrows2.md b/resources/shape-libraries/arrows2.mdsimilarity index 100%rename from docs/shape-libraries/arrows2.mdrename to resources/shape-libraries/arrows2.mddiff --git a/docs/shape-libraries/atlassian.md b/resources/shape-libraries/atlassian.mdsimilarity index 100%rename from docs/shape-libraries/atlassian.mdrename to resources/shape-libraries/atlassian.mddiff --git a/docs/shape-libraries/aws4.md b/resources/shape-libraries/aws4.mdsimilarity index 100%rename from docs/shape-libraries/aws4.mdrename to resources/shape-libraries/aws4.mddiff --git a/docs/shape-libraries/azure2.md b/resources/shape-libraries/azure2.mdsimilarity index 100%rename from docs/shape-libraries/azure2.mdrename to resources/shape-libraries/azure2.mddiff --git a/docs/shape-libraries/basic.md b/resources/shape-libraries/basic.mdsimilarity index 100%rename from docs/shape-libraries/basic.mdrename to resources/shape-libraries/basic.mddiff --git a/docs/shape-libraries/bpmn.md b/resources/shape-libraries/bpmn.mdsimilarity index 100%rename from docs/shape-libraries/bpmn.mdrename to resources/shape-libraries/bpmn.mddiff --git a/docs/shape-libraries/cabinets.md b/resources/shape-libraries/cabinets.mdsimilarity index 100%rename from docs/shape-libraries/cabinets.mdrename to resources/shape-libraries/cabinets.mddiff --git a/docs/shape-libraries/cisco19.md b/resources/shape-libraries/cisco19.mdsimilarity index 100%rename from docs/shape-libraries/cisco19.mdrename to resources/shape-libraries/cisco19.mddiff --git a/docs/shape-libraries/citrix.md b/resources/shape-libraries/citrix.mdsimilarity index 100%rename from docs/shape-libraries/citrix.mdrename to resources/shape-libraries/citrix.mddiff --git a/docs/shape-libraries/electrical.md b/resources/shape-libraries/electrical.mdsimilarity index 100%rename from docs/shape-libraries/electrical.mdrename to resources/shape-libraries/electrical.mddiff --git a/docs/shape-libraries/floorplan.md b/resources/shape-libraries/floorplan.mdsimilarity index 100%rename from docs/shape-libraries/floorplan.mdrename to resources/shape-libraries/floorplan.mddiff --git a/docs/shape-libraries/flowchart.md b/resources/shape-libraries/flowchart.mdsimilarity index 100%rename from docs/shape-libraries/flowchart.mdrename to resources/shape-libraries/flowchart.mddiff --git a/docs/shape-libraries/fluidpower.md b/resources/shape-libraries/fluidpower.mdsimilarity index 100%rename from docs/shape-libraries/fluidpower.mdrename to resources/shape-libraries/fluidpower.mddiff --git a/docs/shape-libraries/gcp2.md b/resources/shape-libraries/gcp2.mdsimilarity index 100%rename from docs/shape-libraries/gcp2.mdrename to resources/shape-libraries/gcp2.mddiff --git a/docs/shape-libraries/infographic.md b/resources/shape-libraries/infographic.mdsimilarity index 100%rename from docs/shape-libraries/infographic.mdrename to resources/shape-libraries/infographic.mddiff --git a/docs/shape-libraries/kubernetes.md b/resources/shape-libraries/kubernetes.mdsimilarity index 100%rename from docs/shape-libraries/kubernetes.mdrename to resources/shape-libraries/kubernetes.mddiff --git a/docs/shape-libraries/lean_mapping.md b/resources/shape-libraries/lean_mapping.mdsimilarity index 100%rename from docs/shape-libraries/lean_mapping.mdrename to resources/shape-libraries/lean_mapping.mddiff --git a/docs/shape-libraries/material_design.md b/resources/shape-libraries/material_design.mdsimilarity index 100%rename from docs/shape-libraries/material_design.mdrename to resources/shape-libraries/material_design.mddiff --git a/docs/shape-libraries/mscae.md b/resources/shape-libraries/mscae.mdsimilarity index 100%rename from docs/shape-libraries/mscae.mdrename to resources/shape-libraries/mscae.mddiff --git a/docs/shape-libraries/network.md b/resources/shape-libraries/network.mdsimilarity index 100%rename from docs/shape-libraries/network.mdrename to resources/shape-libraries/network.mddiff --git a/docs/shape-libraries/openstack.md b/resources/shape-libraries/openstack.mdsimilarity index 100%rename from docs/shape-libraries/openstack.mdrename to resources/shape-libraries/openstack.mddiff --git a/docs/shape-libraries/pid.md b/resources/shape-libraries/pid.mdsimilarity index 100%rename from docs/shape-libraries/pid.mdrename to resources/shape-libraries/pid.mddiff --git a/docs/shape-libraries/rack.md b/resources/shape-libraries/rack.mdsimilarity index 100%rename from docs/shape-libraries/rack.mdrename to resources/shape-libraries/rack.mddiff --git a/docs/shape-libraries/salesforce.md b/resources/shape-libraries/salesforce.mdsimilarity index 100%rename from docs/shape-libraries/salesforce.mdrename to resources/shape-libraries/salesforce.mddiff --git a/docs/shape-libraries/sap.md b/resources/shape-libraries/sap.mdsimilarity index 100%rename from docs/shape-libraries/sap.mdrename to resources/shape-libraries/sap.mddiff --git a/docs/shape-libraries/sitemap.md b/resources/shape-libraries/sitemap.mdsimilarity index 100%rename from docs/shape-libraries/sitemap.mdrename to resources/shape-libraries/sitemap.mddiff --git a/docs/shape-libraries/vvd.md b/resources/shape-libraries/vvd.mdsimilarity index 100%rename from docs/shape-libraries/vvd.mdrename to resources/shape-libraries/vvd.mddiff --git a/docs/shape-libraries/webicons.md b/resources/shape-libraries/webicons.mdsimilarity index 100%rename from docs/shape-libraries/webicons.mdrename to resources/shape-libraries/webicons.mddiff --git a/src/ai/image.ts b/server/ai/image.tssimilarity index 98%rename from src/ai/image.tsrename to server/ai/image.tsindex 4fbe8f0..123262c 100644--- a/src/ai/image.ts+++ b/server/ai/image.ts@@ -1,5 +1,5 @@import { dataUrlToFile, postForm, postJson, toDataUrl } from "./transport";-import type { ImageRequest } from "./types";+import type { ImageRequest } from "../../contracts/ai";/*** Image models are reached through three OpenAI routes, tried in order:diff --git a/src/ai/server-model.ts b/server/ai/model.tssimilarity index 95%rename from src/ai/server-model.tsrename to server/ai/model.tsindex 1473138..ee0336e 100644--- a/src/ai/server-model.ts+++ b/server/ai/model.ts@@ -1,6 +1,6 @@import { createOpenAI } from "@ai-sdk/openai";import type { LanguageModel } from "ai";-import type { AIChannel } from "./types";+import type { AIChannel } from "../../contracts/ai";/*** Build the AI SDK model used by the streaming `/api/chat` route.diff --git a/src/ai/text.ts b/server/ai/text.tssimilarity index 92%rename from src/ai/text.tsrename to server/ai/text.tsindex 9d4271c..f2fe1d9 100644--- a/src/ai/text.ts+++ b/server/ai/text.ts@@ -1,5 +1,5 @@import { postJson } from "./transport";-import type { ChatContentPart, TextRequest } from "./types";+import type { ChatContentPart, TextRequest } from "../../contracts/ai";/** Flatten OpenAI message content (string or part array) to plain text. */export function contentToText(content: unknown): string {diff --git a/src/ai/transport.ts b/server/ai/transport.tssimilarity index 98%rename from src/ai/transport.tsrename to server/ai/transport.tsindex 05a373f..d48d831 100644--- a/src/ai/transport.ts+++ b/server/ai/transport.ts@@ -1,4 +1,4 @@-import type { AIChannel } from "./types";+import type { AIChannel } from "../../contracts/ai";/** Join a configured base URL with an API path, tolerating stray slashes. */export function joinUrl(baseUrl: string, path: string): string {diff --git a/src/server/chat/deep-thinking.ts b/server/chat/deep-thinking.tssimilarity index 98%rename from src/server/chat/deep-thinking.tsrename to server/chat/deep-thinking.tsindex a519985..9ccd942 100644--- a/src/server/chat/deep-thinking.ts+++ b/server/chat/deep-thinking.ts@@ -1,7 +1,7 @@import { mkdir, readFile, writeFile } from "fs/promises"import path from "path"-import { generateImage } from "../../ai/image"-import type { AIChannel } from "../../ai/types"+import { generateImage } from "../ai/image"+import type { AIChannel } from "../../contracts/ai"import { parseDataUrl } from "./files"/**diff --git a/src/server/chat/files.ts b/server/chat/files.tssimilarity index 100%rename from src/server/chat/files.tsrename to server/chat/files.tsdiff --git a/src/server/chat/intent.ts b/server/chat/intent.tssimilarity index 100%rename from src/server/chat/intent.tsrename to server/chat/intent.tsdiff --git a/src/server/chat/messages.ts b/server/chat/messages.tssimilarity index 100%rename from src/server/chat/messages.tsrename to server/chat/messages.tsdiff --git a/src/server/chat/shape-library.ts b/server/chat/shape-library.tssimilarity index 59%rename from src/server/chat/shape-library.tsrename to server/chat/shape-library.tsindex e301468..755e39c 100644--- a/src/server/chat/shape-library.ts+++ b/server/chat/shape-library.ts@@ -1,3 +1,12 @@+import path from "node:path"++/**+ * The draw.io shape libraries the Flow agent can pull in on demand.+ *+ * These are runtime data, not documentation: the chat route reads the+ * matching markdown file when the model calls get_shape_library.+ */+export const AVAILABLE_SHAPE_LIBRARIES = ["alibaba_cloud","android",@@ -36,3 +45,8 @@ export type ShapeLibraryName = (typeof AVAILABLE_SHAPE_LIBRARIES)[number];export function formatAvailableShapeLibraries(): string {return AVAILABLE_SHAPE_LIBRARIES.join(", ");}++/** Absolute path to the directory holding one markdown file per library. */+export function shapeLibraryDir(): string {+ return path.join(process.cwd(), "resources", "shape-libraries");+}diff --git a/src/server/chat/summarize.ts b/server/chat/summarize.tssimilarity index 100%rename from src/server/chat/summarize.tsrename to server/chat/summarize.tsdiff --git a/src/server/chat/system-prompt.ts b/server/chat/system-prompt.tssimilarity index 100%rename from src/server/chat/system-prompt.tsrename to server/chat/system-prompt.tsdiff --git a/server/http/adapter.ts b/server/http/adapter.tsnew file mode 100644index 0000000..b604766--- /dev/null+++ b/server/http/adapter.ts@@ -0,0 +1,75 @@+import type { IncomingMessage, ServerResponse } from "node:http";++/**+ * Bridges Node's http types and the Fetch API's Request/Response.+ *+ * Route handlers are written against Request/Response so they read the same+ * whichever host is running them.+ */++export function headersFrom(source: NodeJS.Dict<string | string[]>): Headers {+ const headers = new Headers();+ for (const [key, value] of Object.entries(source)) {+ if (Array.isArray(value)) {+ for (const item of value) headers.append(key, item);+ } else if (typeof value === "string") {+ headers.set(key, value);+ }+ }+ return headers;+}++/** Reads the raw body off the socket; use where nothing has consumed it yet. */+export async function toWebRequest(req: IncomingMessage): Promise<Request> {+ const origin = `http://${req.headers.host || "localhost"}`;+ const url = new URL(req.url || "/", origin);+ const headers = headersFrom(req.headers);+ const method = (req.method || "GET").toUpperCase();++ if (method === "GET" || method === "HEAD") {+ return new Request(url.toString(), { method, headers });+ }++ const chunks: Buffer[] = [];+ for await (const chunk of req) {+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));+ }+ const body = chunks.length > 0 ? Buffer.concat(chunks) : undefined;++ return new Request(url.toString(), { method, headers, body: body as BodyInit | undefined });+}++/**+ * Streams a Response back out. `transfer-encoding` is dropped: Node sets it+ * itself, and echoing the upstream value corrupts chunked replies.+ */+export async function sendWebResponse(webResponse: Response, res: ServerResponse) {+ res.statusCode = webResponse.status;+ webResponse.headers.forEach((value, key) => {+ if (key.toLowerCase() === "transfer-encoding") return;+ res.setHeader(key, value);+ });++ if (!webResponse.body) {+ res.end();+ return;+ }++ // Flush headers before the first chunk so streamed replies start immediately.+ (res as ServerResponse & { flushHeaders?: () => void }).flushHeaders?.();++ const reader = webResponse.body.getReader();+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ if (value) res.write(Buffer.from(value));+ }+ res.end();+}++export function sendError(res: ServerResponse, error: unknown) {+ const message = error instanceof Error ? error.message : "Internal Server Error";+ res.statusCode = 500;+ res.setHeader("content-type", "application/json; charset=utf-8");+ res.end(JSON.stringify({ error: message }));+}diff --git a/server/http/routes.ts b/server/http/routes.tsnew file mode 100644index 0000000..2f1c858--- /dev/null+++ b/server/http/routes.ts@@ -0,0 +1,32 @@+import { GET as getConfig } from "../routes/config";+import { POST as postChat } from "../routes/chat";+import { POST as postLogFeedback } from "../routes/log-feedback";+import { POST as postLogFileParser } from "../routes/log-file-parser";+import { POST as postLogSave } from "../routes/log-save";+import { POST as postPptAi } from "../routes/ppt-ai";+import { POST as postThirdPartyParser } from "../routes/third-party-parser";+import { POST as postVerifyAccessCode } from "../routes/verify-access-code";++/**+ * The API surface, in one table.+ *+ * Both hosts read it: the Express server in production, and the Vite dev+ * middleware. Adding a route here is enough for both.+ */++export type RouteHandler = (request: Request) => Promise<Response>;++export const API_ROUTES: Record<string, RouteHandler> = {+ "GET /api/config": async () => getConfig(),+ "POST /api/verify-access-code": postVerifyAccessCode,+ "POST /api/log-feedback": postLogFeedback,+ "POST /api/log-save": postLogSave,+ "POST /api/log-file-parser": postLogFileParser,+ "POST /api/third-party-parser": postThirdPartyParser,+ "POST /api/chat": postChat,+ "POST /api/ppt-ai": postPptAi,+};++export function routeKey(method: string | undefined, pathname: string) {+ return `${(method || "GET").toUpperCase()} ${pathname}`;+}diff --git a/server/http/vite-middleware.ts b/server/http/vite-middleware.tsnew file mode 100644index 0000000..320bb04--- /dev/null+++ b/server/http/vite-middleware.ts@@ -0,0 +1,32 @@+import type { IncomingMessage, ServerResponse } from "node:http";+import { sendError, sendWebResponse, toWebRequest } from "./adapter";+import { API_ROUTES, routeKey } from "./routes";++/**+ * Serves the API inside Vite's dev and preview servers, so `npm run dev` is+ * one command rather than an app and an API to keep in sync.+ *+ * vite.config.ts imports this, and Vite loads its config through plain Node —+ * which is why everything under server/ uses relative imports rather than the+ * `@/` alias.+ */+export function apiMiddleware() {+ return async (+ req: IncomingMessage,+ res: ServerResponse,+ next: (err?: unknown) => void,+ ) => {+ const pathname = new URL(req.url || "/", "http://localhost").pathname;+ const handler = API_ROUTES[routeKey(req.method, pathname)];+ if (!handler) {+ next();+ return;+ }++ try {+ await sendWebResponse(await handler(await toWebRequest(req)), res);+ } catch (error) {+ sendError(res, error);+ }+ };+}diff --git a/server/index.ts b/server/index.tsnew file mode 100644index 0000000..c1b7ef0--- /dev/null+++ b/server/index.ts@@ -0,0 +1,87 @@+import express from "express";+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { headersFrom, sendWebResponse } from "./http/adapter";+import { API_ROUTES, routeKey } from "./http/routes";++/**+ * The production API: serves `/api/*` and the built client from one process.+ *+ * In development Vite hosts the same routes in-process (see+ * http/vite-middleware.ts), so both hosts read the same route table.+ */++const PORT = Number(process.env.PORT || process.env.API_PORT || 8080);+const BODY_LIMIT = process.env.API_BODY_LIMIT || "25mb";++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const distDir = process.env.WEB_DIST_DIR+ ? path.resolve(process.cwd(), process.env.WEB_DIST_DIR)+ : path.resolve(__dirname, "../dist");+const indexHtmlPath = path.join(distDir, "index.html");++const app = express();+app.use(express.json({ limit: BODY_LIMIT }));++/**+ * express.json() has already consumed the socket, so the body is rebuilt from+ * `req.body` rather than re-read like the Vite middleware does.+ */+function toWebRequest(req: express.Request): Request {+ const origin = `${req.protocol || "http"}://${req.get("host") || "localhost"}`;+ const url = new URL(req.originalUrl || req.url, origin);+ const headers = headersFrom(req.headers);++ let body: BodyInit | undefined;+ if (req.method !== "GET" && req.method !== "HEAD" && req.body !== undefined) {+ if (typeof req.body === "string" || Buffer.isBuffer(req.body)) {+ body = req.body;+ } else {+ body = JSON.stringify(req.body);+ if (!headers.has("content-type")) headers.set("content-type", "application/json");+ }+ }++ return new Request(url.toString(), { method: req.method, headers, body });+}++app.use("/api", async (req, res, next) => {+ // req.path is relative to the mount point; the table keys include it.+ const handler = API_ROUTES[routeKey(req.method, `/api${req.path}`)];+ if (!handler) {+ next();+ return;+ }+ try {+ await sendWebResponse(await handler(toWebRequest(req)), res);+ } catch (error) {+ console.error("API route failed:", error);+ const message = error instanceof Error ? error.message : "Internal Server Error";+ res.status(500).json({ error: message });+ }+});++app.get("/healthz", (_req, res) => {+ res.json({ ok: true, ts: new Date().toISOString() });+});++if (fs.existsSync(indexHtmlPath)) {+ app.use(express.static(distDir, { index: false, fallthrough: true }));++ // Everything else is a client route: hand back the SPA shell.+ app.get(/.*/, (req, res, next) => {+ if (req.path.startsWith("/api/") || req.path === "/healthz") {+ next();+ return;+ }+ res.sendFile(indexHtmlPath);+ });+} else {+ console.warn(`[server] dist not found at "${distDir}". Build the client with "npm run build".`);+}++app.listen(PORT, () => {+ console.log(`[server] listening on http://localhost:${PORT}`);+ console.log(`[server] web root: ${distDir}`);+});diff --git a/src/server/routes/chat.ts b/server/routes/chat.tssimilarity index 98%rename from src/server/routes/chat.tsrename to server/routes/chat.tsindex ee0a661..4fe28cc 100644--- a/src/server/routes/chat.ts+++ b/server/routes/chat.ts@@ -10,9 +10,9 @@ import {import { appendFile, readFile } from "fs/promises"import path from "path"import { z } from "zod"-import { getImageChannel, getTextChannel, normalizeAIConfig } from "../../ai/config"-import { getChatModel } from "../../ai/server-model"-import { formatAvailableShapeLibraries } from "../chat/shape-library"+import { getImageChannel, getTextChannel, normalizeAIConfig } from "../../contracts/ai"+import { getChatModel } from "../ai/model"+import { formatAvailableShapeLibraries, shapeLibraryDir } from "../chat/shape-library"import { getSystemPrompt } from "../chat/system-prompt"import {RECURSIVE_THRESHOLD_TOKENS,@@ -702,11 +702,7 @@ Rules:return `Invalid library name. Available: ${formatAvailableShapeLibraries()}`}- const baseDir = path.join(- process.cwd(),- "docs",- "shape-libraries",- )+ const baseDir = shapeLibraryDir()const filePath = path.join(baseDir,`${sanitizedLibrary}.md`,diff --git a/src/server/routes/config.ts b/server/routes/config.tssimilarity index 100%rename from src/server/routes/config.tsrename to server/routes/config.tsdiff --git a/src/server/routes/log-feedback.ts b/server/routes/log-feedback.tssimilarity index 100%rename from src/server/routes/log-feedback.tsrename to server/routes/log-feedback.tsdiff --git a/src/server/routes/log-file-parser.ts b/server/routes/log-file-parser.tssimilarity index 100%rename from src/server/routes/log-file-parser.tsrename to server/routes/log-file-parser.tsdiff --git a/src/server/routes/log-save.ts b/server/routes/log-save.tssimilarity index 100%rename from src/server/routes/log-save.tsrename to server/routes/log-save.tsdiff --git a/src/server/routes/ppt-ai.ts b/server/routes/ppt-ai.tssimilarity index 94%rename from src/server/routes/ppt-ai.tsrename to server/routes/ppt-ai.tsindex 1a655e6..b04ace4 100644--- a/src/server/routes/ppt-ai.ts+++ b/server/routes/ppt-ai.ts@@ -1,7 +1,7 @@-import { generateImage } from "../../ai/image"-import { generateText } from "../../ai/text"-import { getImageChannel, getTextChannel, normalizeAIConfig } from "../../ai/config"-import type { AIConfig, MultimodalMessage } from "../../ai/types"+import { generateImage } from "../ai/image"+import { generateText } from "../ai/text"+import { getImageChannel, getTextChannel, normalizeAIConfig } from "../../contracts/ai"+import type { AIConfig, MultimodalMessage } from "../../contracts/ai"/*** Non-streaming model proxy for the CAD and PPT workspaces.diff --git a/src/server/routes/third-party-parser.ts b/server/routes/third-party-parser.tssimilarity index 100%rename from src/server/routes/third-party-parser.tsrename to server/routes/third-party-parser.tsdiff --git a/src/server/routes/verify-access-code.ts b/server/routes/verify-access-code.tssimilarity index 100%rename from src/server/routes/verify-access-code.tsrename to server/routes/verify-access-code.tsdiff --git a/src/server/telemetry/langfuse.ts b/server/telemetry/langfuse.tssimilarity index 100%rename from src/server/telemetry/langfuse.tsrename to server/telemetry/langfuse.tsdiff --git a/src/ai/types.ts b/src/ai/types.tsdeleted file mode 100644index 9aec2a2..0000000--- a/src/ai/types.ts+++ /dev/null@@ -1,63 +0,0 @@-/**- * Every model call in CanvasAnvil speaks the OpenAI HTTP protocol:- * `POST {baseUrl}/chat/completions`, `POST {baseUrl}/images/generations`- * and `POST {baseUrl}/images/edits`. Any vendor that exposes an- * OpenAI-compatible endpoint is configured by pointing `baseUrl` at it —- * there is no per-vendor branching anywhere in this module.- */--/** One configured endpoint: where to send requests, with what credentials. */-export interface AIChannel {- apiKey: string;- baseUrl: string;- model: string;-}--/**- * Persisted settings. Text and image are separate channels because the two- * are commonly served by different endpoints; each is still plain OpenAI.- */-export interface AIConfig {- textApiKey: string;- textBaseUrl: string;- textModel: string;- imageApiKey: string;- imageBaseUrl: string;- imageModel: string;- fileParserApiToken: string;- systemPrompt: string;-}--export type ChatRole = "system" | "user" | "assistant";--export type ChatContentPart =- | { type: "text"; text: string }- | { type: "image_url"; image_url: { url: string } };--/** The common case: a text-only turn. */-export interface ChatMessage {- role: ChatRole;- content: string;-}--/** A turn that may also carry images, using OpenAI's content-part array. */-export interface MultimodalMessage {- role: ChatRole;- content: string | ChatContentPart[];-}--export interface TextRequest {- channel: AIChannel;- messages: MultimodalMessage[];- signal?: AbortSignal;-}--export interface ImageRequest {- channel: AIChannel;- prompt: string;- /** Primary reference image. Its presence selects the `/images/edits` route. */- referenceImageUrl?: string;- additionalReferenceImageUrls?: string[];- maskImageUrl?: string;- signal?: AbortSignal;-}diff --git a/src/lib/cad-agents.ts b/src/lib/cad-agents.tsdeleted file mode 100644index 4ec6d38..0000000--- a/src/lib/cad-agents.ts+++ /dev/null@@ -1,9 +0,0 @@-import cadPlanAgentPrompt from "../../agent/cad/plan.md?raw";-import cadSvgRouterAgentPrompt from "../../agent/cad/svg/system.md?raw";-import cadSvgFlowPatchAgentPrompt from "../../agent/cad/svg/patch.md?raw";-import cadSvgFlowReplaceAgentPrompt from "../../agent/cad/svg/replace.md?raw";--export const CAD_PLAN_AGENT_PROMPT = cadPlanAgentPrompt;-export const CAD_SVG_AGENT_ROUTER_PROMPT = cadSvgRouterAgentPrompt;-export const CAD_SVG_FLOW_PATCH_AGENT_PROMPT = cadSvgFlowPatchAgentPrompt;-export const CAD_SVG_FLOW_REPLACE_AGENT_PROMPT = cadSvgFlowReplaceAgentPrompt;diff --git a/src/lib/system-prompts.ts b/src/lib/system-prompts.tsdeleted file mode 100644index c3a9ca1..0000000--- a/src/lib/system-prompts.ts+++ /dev/null@@ -1,13 +0,0 @@-import drawioPrompt from "../../agent/flow/system.md?raw";-import cadPrompt from "../../agent/cad/system.md?raw";-import pptOutlinePrompt from "../../agent/ppt/outline.md?raw";-import pptOutlineEditPrompt from "../../agent/ppt/outline-edit.md?raw";-import pptSlidesGeneratePrompt from "../../agent/ppt/slides-generate.md?raw";-import pptSlidesEditPrompt from "../../agent/ppt/system.md?raw";--export const DRAWIO_SYSTEM_PROMPT = drawioPrompt;-export const CAD_SYSTEM_PROMPT = cadPrompt;-export const PPT_OUTLINE_SYSTEM_PROMPT = pptOutlinePrompt;-export const PPT_OUTLINE_EDIT_SYSTEM_PROMPT = pptOutlineEditPrompt;-export const PPT_SLIDES_GENERATE_SYSTEM_PROMPT = pptSlidesGeneratePrompt;-export const PPT_SLIDES_EDIT_SYSTEM_PROMPT = pptSlidesEditPrompt;diff --git a/tailwind.config.js b/tailwind.config.jsindex df0fecb..91626ce 100644--- a/tailwind.config.js+++ b/tailwind.config.js@@ -1,12 +1,7 @@/** @type {import('tailwindcss').Config} */export default {darkMode: ["class"],- content: [- './pages/**/*.{ts,tsx}',- './components/**/*.{ts,tsx}',- './app/**/*.{ts,tsx}',- './src/**/*.{ts,tsx}',- ],+ content: ['./index.html', './client/**/*.{ts,tsx}'],theme: {container: {center: true,diff --git a/tests/ai-config.test.ts b/tests/ai-config.test.tsindex 6e41dd5..2124100 100644--- a/tests/ai-config.test.ts+++ b/tests/ai-config.test.ts@@ -5,7 +5,7 @@ import {getImageChannel,getTextChannel,normalizeAIConfig,-} from "../src/ai/config";+} from "../contracts/ai";test("fills both channels from an empty config", () => {const config = normalizeAIConfig({});diff --git a/tests/ai-request-shape.test.ts b/tests/ai-request-shape.test.tsindex e82f93d..2f00e2f 100644--- a/tests/ai-request-shape.test.ts+++ b/tests/ai-request-shape.test.ts@@ -1,8 +1,8 @@import assert from "node:assert/strict";import { afterEach, beforeEach, test } from "node:test";-import { generateImage } from "../src/ai/image";-import { generateText } from "../src/ai/text";-import type { AIChannel } from "../src/ai/types";+import { generateImage } from "../server/ai/image";+import { generateText } from "../server/ai/text";+import type { AIChannel } from "../contracts/ai";/*** These lock in the wire format: every model call must be one of the threediff --git a/tsconfig.json b/tsconfig.jsonindex 3042cb5..baaf292 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -25,16 +25,24 @@"baseUrl": "./","paths": {"@/*": [- "./src/*"+ "./client/*"+ ],+ "@contracts/*": [+ "./contracts/*"+ ],+ "@prompts/*": [+ "./resources/prompts/*"]}},"include": [- "src",- "api"+ "client",+ "server",+ "contracts",+ "tests"],"exclude": [- "src/features/ppt-editor/mate/**/*.reference.tsx",- "src/features/ppt-editor/mate-src/**/*"+ "dist",+ "node_modules"]}diff --git a/vite.config.ts b/vite.config.tsindex 648ccc1..1a87861 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -1,171 +1,71 @@-import { defineConfig } from 'vite'-import type { IncomingMessage, ServerResponse } from "node:http";+import { defineConfig } from "vite";import type { Connect, Plugin } from "vite";-import react from '@vitejs/plugin-react'-import tsconfigPaths from "vite-tsconfig-paths";-import { GET as getConfig } from "./api/routes/config";-import { POST as postVerifyAccessCode } from "./api/routes/verify-access-code";-import { POST as postLogFeedback } from "./api/routes/log-feedback";-import { POST as postLogSave } from "./api/routes/log-save";-import { POST as postLogFileParser } from "./api/routes/log-file-parser";-import { POST as postThirdPartyParser } from "./api/routes/third-party-parser";-import { POST as postChat } from "./api/routes/chat";-import { POST as postPptAi } from "./api/routes/ppt-ai";+import react from "@vitejs/plugin-react";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { apiMiddleware } from "./server/http/vite-middleware";-type RouteHandler = (request: Request) => Promise<Response>;+const root = path.dirname(fileURLToPath(import.meta.url));-const API_ROUTES: Record<string, RouteHandler> = {- "GET /api/config": async () => getConfig(),- "POST /api/verify-access-code": postVerifyAccessCode,- "POST /api/log-feedback": postLogFeedback,- "POST /api/log-save": postLogSave,- "POST /api/log-file-parser": postLogFileParser,- "POST /api/third-party-parser": postThirdPartyParser,- "POST /api/chat": postChat,- "POST /api/ppt-ai": postPptAi,-};--async function toWebRequest(req: IncomingMessage): Promise<Request> {- const origin = `http://${req.headers.host || "localhost"}`;- const url = new URL(req.url || "/", origin);- const headers = new Headers();-- for (const [key, value] of Object.entries(req.headers)) {- if (Array.isArray(value)) {- for (const item of value) headers.append(key, item);- } else if (typeof value === "string") {- headers.set(key, value);- }- }-- const method = (req.method || "GET").toUpperCase();- if (method === "GET" || method === "HEAD") {- return new Request(url.toString(), { method, headers });- }-- const chunks: Buffer[] = [];- for await (const chunk of req) {- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));- }- const bodyBuffer = chunks.length > 0 ? Buffer.concat(chunks) : undefined;-- return new Request(url.toString(), {- method,- headers,- body: bodyBuffer as BodyInit | null | undefined,- });-}--async function sendWebResponse(webResponse: Response, res: ServerResponse) {- res.statusCode = webResponse.status;- webResponse.headers.forEach((value, key) => {- if (key.toLowerCase() === "transfer-encoding") return;- res.setHeader(key, value);- });-- if (!webResponse.body) {- res.end();- return;- }-- const reader = webResponse.body.getReader();- while (true) {- const { done, value } = await reader.read();- if (done) break;- if (value) res.write(Buffer.from(value));- }- res.end();-}--function createLocalApiPlugin(): Plugin {- const attachApiMiddleware = (middlewares: Connect.ServerStack) => {- middlewares.use(async (req, res, next) => {- const method = (req.method || "GET").toUpperCase();- const pathname = new URL(req.url || "/", "http://localhost").pathname;- const routeKey = `${method} ${pathname}`;- const handler = API_ROUTES[routeKey];-- if (!handler) {- next();- return;- }-- try {- const request = await toWebRequest(req);- const response = await handler(request);- await sendWebResponse(response, res);- } catch (error) {- const message =- error instanceof Error ? error.message : "Internal Server Error";- res.statusCode = 500;- res.setHeader("content-type", "application/json; charset=utf-8");- res.end(JSON.stringify({ error: message }));- }- });+/**+ * Runs the API inside the dev and preview servers so `npm run dev` is a single+ * command. The routes come from server/http/routes.ts, the same table the+ * production Express server reads.+ */+function localApiPlugin(): Plugin {+ const attach = (middlewares: Connect.Server) => {+ middlewares.use(apiMiddleware());};-return {name: "local-api-routes",- configureServer(server) {- attachApiMiddleware(server.middlewares);- },- configurePreviewServer(server) {- attachApiMiddleware(server.middlewares);- },+ configureServer: (server) => attach(server.middlewares),+ configurePreviewServer: (server) => attach(server.middlewares),};}-// https://vite.dev/config/export default defineConfig({- server: {- host: "0.0.0.0",- port: 8001,- },- preview: {- host: "0.0.0.0",- port: 8001,- },- optimizeDeps: {- entries: ["index.html"],+ server: { host: "0.0.0.0", port: 8001 },+ preview: { host: "0.0.0.0", port: 8001 },+ resolve: {+ alias: {+ "@contracts": path.resolve(root, "contracts"),+ "@prompts": path.resolve(root, "resources/prompts"),+ "@": path.resolve(root, "client"),+ },},+ optimizeDeps: { entries: ["index.html"] },build: {- sourcemap: 'hidden',+ sourcemap: "hidden",rollupOptions: {output: {- // Split by package rather than by named entry point: the object- // form of manualChunks makes each listed package a chunk entry, which- // let Vite's own preload helper get hoisted into a vendor chunk and- // pulled into the initial load. Returning undefined leaves placement- // to Rollup, which keeps the helper with the entry.+ // Split by package. The object form of manualChunks makes each listed+ // package a chunk entry, which let Vite's dynamic-import preload+ // helper get hoisted into a vendor chunk and pulled into the initial+ // load; returning undefined leaves placement to Rollup.manualChunks(id: string) {- // Vite's dynamic-import preload helper is a virtual module every- // lazy chunk needs. Left to Rollup it landed in the PowerPoint- // chunk, which made the entry preload 800 kB to reach it.- if (id.includes("vite/preload-helper")) return "vendor-react"- if (!id.includes("node_modules")) return- const match = /node_modules[\\\/](?:(@[^\\\/]+)[\\\/])?([^\\\/]+)/.exec(id)- const pkg = match ? `${match[1] ? `${match[1]}/` : ""}${match[2]}` : ""- if (pkg === "react" || pkg === "react-dom" || pkg === "scheduler") return "vendor-react"- if (pkg === "pptxgenjs" || pkg === "pdf-lib") return "vendor-office"- if (pkg === "jszip" || pkg === "pako") return "vendor-zip"- if (pkg === "mammoth") return "vendor-docs"+ // Every lazy chunk needs this helper. Left to Rollup it landed in+ // the PowerPoint chunk, which made the entry preload 800 kB.+ if (id.includes("vite/preload-helper")) return "vendor-react";+ if (!id.includes("node_modules")) return;++ const match = /node_modules[\\/](?:(@[^\\/]+)[\\/])?([^\\/]+)/.exec(id);+ const pkg = match ? `${match[1] ? `${match[1]}/` : ""}${match[2]}` : "";++ if (pkg === "react" || pkg === "react-dom" || pkg === "scheduler") return "vendor-react";+ if (pkg === "pptxgenjs" || pkg === "pdf-lib") return "vendor-office";+ if (pkg === "jszip" || pkg === "pako") return "vendor-zip";+ if (pkg === "mammoth") return "vendor-docs";if (pkg === "react-markdown" || pkg === "remark-gfm" || pkg === "prism-react-renderer") {- return "vendor-markdown"- }- if (pkg === "react-drawio") return "vendor-drawio"- if (pkg === "ai" || pkg.startsWith("@ai-sdk/") || pkg === "openai") return "vendor-ai"- if (pkg === "lucide-react" || pkg === "motion" || pkg === "framer-motion" || pkg === "sonner") {- return "vendor-ui"+ return "vendor-markdown";}- if (pkg.startsWith("@radix-ui/")) return "vendor-radix"- return+ if (pkg === "react-drawio") return "vendor-drawio";+ if (pkg === "ai" || pkg.startsWith("@ai-sdk/") || pkg === "openai") return "vendor-ai";+ if (pkg === "lucide-react" || pkg === "motion" || pkg === "sonner") return "vendor-ui";+ if (pkg.startsWith("@radix-ui/")) return "vendor-radix";+ return;},},},},- plugins: [- createLocalApiPlugin(),- react(),- tsconfigPaths({ projects: ['./tsconfig.json'] })- ],-})+ plugins: [localApiPlugin(), react()],+});