Skip to content

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.

refactor: split the repo into client, server, contracts and resources

codingFeng10125b0c7cd9db5
diff --git a/api/routes/chat.ts b/api/routes/chat.ts
deleted file mode 100644
index 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.ts
deleted file mode 100644
index 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.ts
deleted file mode 100644
index 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.ts
deleted file mode 100644
index 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.ts
deleted file mode 100644
index 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.ts
deleted file mode 100644
index 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.ts
deleted file mode 100644
index 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.ts
deleted file mode 100644
index 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.ts
deleted file mode 100644
index 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.ts
similarity index 96%
rename from src/ai/client.ts
rename to client/ai/client.ts
index 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.ts
similarity index 100%
rename from src/ai/browser-image.ts
rename to client/ai/images.ts
diff --git a/src/ai/language-policy.ts b/client/ai/language-policy.ts
similarity index 96%
rename from src/ai/language-policy.ts
rename to client/ai/language-policy.ts
index 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 output
diff --git a/src/ai/limiter.ts b/client/ai/limiter.ts
similarity index 100%
rename from src/ai/limiter.ts
rename to client/ai/limiter.ts
diff --git a/client/ai/storage.ts b/client/ai/storage.ts
new file mode 100644
index 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.tsx
similarity index 100%
rename from src/app/App.tsx
rename to client/app/App.tsx
diff --git a/src/app/BrandIcon.tsx b/client/app/BrandIcon.tsx
similarity index 100%
rename from src/app/BrandIcon.tsx
rename to client/app/BrandIcon.tsx
diff --git a/src/app/ErrorBoundary.tsx b/client/app/ErrorBoundary.tsx
similarity index 100%
rename from src/app/ErrorBoundary.tsx
rename to client/app/ErrorBoundary.tsx
diff --git a/src/app/workspaces.ts b/client/app/workspaces.ts
similarity index 100%
rename from src/app/workspaces.ts
rename to client/app/workspaces.ts
diff --git a/src/components/SettingsDialog.tsx b/client/components/SettingsDialog.tsx
similarity index 98%
rename from src/components/SettingsDialog.tsx
rename to client/components/SettingsDialog.tsx
index 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.ts
similarity index 100%
rename from src/features/ppt-editor/adapters/fromCanvasAnvil.ts
rename to client/features/ppt-editor/adapters/fromCanvasAnvil.ts
diff --git a/src/features/ppt-editor/adapters/toCanvasAnvil.ts b/client/features/ppt-editor/adapters/toCanvasAnvil.ts
similarity index 100%
rename from src/features/ppt-editor/adapters/toCanvasAnvil.ts
rename to client/features/ppt-editor/adapters/toCanvasAnvil.ts
diff --git a/src/features/ppt-editor/components/PptEditorBridge.tsx b/client/features/ppt-editor/components/PptEditorBridge.tsx
similarity index 100%
rename from src/features/ppt-editor/components/PptEditorBridge.tsx
rename to client/features/ppt-editor/components/PptEditorBridge.tsx
diff --git a/src/features/ppt-editor/components/PptReviewBridge.tsx b/client/features/ppt-editor/components/PptReviewBridge.tsx
similarity index 100%
rename from src/features/ppt-editor/components/PptReviewBridge.tsx
rename to client/features/ppt-editor/components/PptReviewBridge.tsx
diff --git a/src/features/ppt-editor/components/index.ts b/client/features/ppt-editor/components/index.ts
similarity index 100%
rename from src/features/ppt-editor/components/index.ts
rename to client/features/ppt-editor/components/index.ts
diff --git a/src/features/ppt-editor/index.ts b/client/features/ppt-editor/index.ts
similarity index 100%
rename from src/features/ppt-editor/index.ts
rename to client/features/ppt-editor/index.ts
diff --git a/src/features/ppt-editor/shape-config.ts b/client/features/ppt-editor/shape-config.ts
similarity index 100%
rename from src/features/ppt-editor/shape-config.ts
rename to client/features/ppt-editor/shape-config.ts
diff --git a/src/features/ppt-editor/types.ts b/client/features/ppt-editor/types.ts
similarity index 100%
rename from src/features/ppt-editor/types.ts
rename to client/features/ppt-editor/types.ts
diff --git a/src/index.css b/client/index.css
similarity index 100%
rename from src/index.css
rename to client/index.css
diff --git a/client/lib/cad-agents.ts b/client/lib/cad-agents.ts
new file mode 100644
index 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.ts
similarity index 100%
rename from src/lib/cad-render-titles.ts
rename to client/lib/cad-render-titles.ts
diff --git a/src/lib/cad-tasks.ts b/client/lib/cad-tasks.ts
similarity index 78%
rename from src/lib/cad-tasks.ts
rename to client/lib/cad-tasks.ts
index 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.ts
similarity index 100%
rename from src/lib/ppt-prompts.ts
rename to client/lib/ppt-prompts.ts
diff --git a/src/lib/ppt-service.ts b/client/lib/ppt-service.ts
similarity index 99%
rename from src/lib/ppt-service.ts
rename to client/lib/ppt-service.ts
index 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.ts
similarity index 100%
rename from src/lib/risen-prompt.ts
rename to client/lib/risen-prompt.ts
diff --git a/client/lib/system-prompts.ts b/client/lib/system-prompts.ts
new file mode 100644
index 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.tsx
similarity index 100%
rename from src/main.tsx
rename to client/main.tsx
diff --git a/src/pages/LandingPage.tsx b/client/pages/LandingPage.tsx
similarity index 100%
rename from src/pages/LandingPage.tsx
rename to client/pages/LandingPage.tsx
diff --git a/src/pages/portal/PortalPage.tsx b/client/pages/portal/PortalPage.tsx
similarity index 100%
rename from src/pages/portal/PortalPage.tsx
rename to client/pages/portal/PortalPage.tsx
diff --git a/src/pages/portal/data.ts b/client/pages/portal/data.ts
similarity index 100%
rename from src/pages/portal/data.ts
rename to client/pages/portal/data.ts
diff --git a/src/shared/chat/assistant-stream.ts b/client/shared/chat/assistant-stream.ts
similarity index 98%
rename from src/shared/chat/assistant-stream.ts
rename to client/shared/chat/assistant-stream.ts
index 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.ts
similarity index 100%
rename from src/shared/chat/bom-table.ts
rename to client/shared/chat/bom-table.ts
diff --git a/src/shared/chat/button-with-tooltip.tsx b/client/shared/chat/button-with-tooltip.tsx
similarity index 100%
rename from src/shared/chat/button-with-tooltip.tsx
rename to client/shared/chat/button-with-tooltip.tsx
diff --git a/src/shared/chat/chat-errors.ts b/client/shared/chat/chat-errors.ts
similarity index 100%
rename from src/shared/chat/chat-errors.ts
rename to client/shared/chat/chat-errors.ts
diff --git a/src/shared/chat/chat-input.tsx b/client/shared/chat/chat-input.tsx
similarity index 100%
rename from src/shared/chat/chat-input.tsx
rename to client/shared/chat/chat-input.tsx
diff --git a/src/shared/chat/chat-storage.ts b/client/shared/chat/chat-storage.ts
similarity index 99%
rename from src/shared/chat/chat-storage.ts
rename to client/shared/chat/chat-storage.ts
index 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.tsx
similarity index 100%
rename from src/shared/chat/file-preview-list.tsx
rename to client/shared/chat/file-preview-list.tsx
diff --git a/src/shared/chat/global-constraints-dialog.tsx b/client/shared/chat/global-constraints-dialog.tsx
similarity index 100%
rename from src/shared/chat/global-constraints-dialog.tsx
rename to client/shared/chat/global-constraints-dialog.tsx
diff --git a/src/shared/chat/history-dialog.tsx b/client/shared/chat/history-dialog.tsx
similarity index 100%
rename from src/shared/chat/history-dialog.tsx
rename to client/shared/chat/history-dialog.tsx
diff --git a/src/shared/chat/index.ts b/client/shared/chat/index.ts
similarity index 100%
rename from src/shared/chat/index.ts
rename to client/shared/chat/index.ts
diff --git a/src/shared/chat/reasoning.tsx b/client/shared/chat/reasoning.tsx
similarity index 100%
rename from src/shared/chat/reasoning.tsx
rename to client/shared/chat/reasoning.tsx
diff --git a/src/shared/chat/reset-warning-modal.tsx b/client/shared/chat/reset-warning-modal.tsx
similarity index 100%
rename from src/shared/chat/reset-warning-modal.tsx
rename to client/shared/chat/reset-warning-modal.tsx
diff --git a/src/shared/chat/shimmer.tsx b/client/shared/chat/shimmer.tsx
similarity index 100%
rename from src/shared/chat/shimmer.tsx
rename to client/shared/chat/shimmer.tsx
diff --git a/src/shared/files/binary.ts b/client/shared/files/binary.ts
similarity index 100%
rename from src/shared/files/binary.ts
rename to client/shared/files/binary.ts
diff --git a/src/shared/files/detect.ts b/client/shared/files/detect.ts
similarity index 100%
rename from src/shared/files/detect.ts
rename to client/shared/files/detect.ts
diff --git a/src/shared/files/extract-text.ts b/client/shared/files/extract-text.ts
similarity index 100%
rename from src/shared/files/extract-text.ts
rename to client/shared/files/extract-text.ts
diff --git a/src/shared/files/index.ts b/client/shared/files/index.ts
similarity index 100%
rename from src/shared/files/index.ts
rename to client/shared/files/index.ts
diff --git a/src/shared/files/latex-archives.ts b/client/shared/files/latex-archives.ts
similarity index 100%
rename from src/shared/files/latex-archives.ts
rename to client/shared/files/latex-archives.ts
diff --git a/src/shared/files/pdf-render.ts b/client/shared/files/pdf-render.ts
similarity index 100%
rename from src/shared/files/pdf-render.ts
rename to client/shared/files/pdf-render.ts
diff --git a/src/shared/files/types.ts b/client/shared/files/types.ts
similarity index 100%
rename from src/shared/files/types.ts
rename to client/shared/files/types.ts
diff --git a/src/shared/files/use-file-processor.ts b/client/shared/files/use-file-processor.ts
similarity index 99%
rename from src/shared/files/use-file-processor.ts
rename to client/shared/files/use-file-processor.ts
index 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.ts
similarity index 100%
rename from src/shared/files/visual-assets.ts
rename to client/shared/files/visual-assets.ts
diff --git a/src/shared/i18n/index.ts b/client/shared/i18n/index.ts
similarity index 100%
rename from src/shared/i18n/index.ts
rename to client/shared/i18n/index.ts
diff --git a/src/shared/i18n/language.ts b/client/shared/i18n/language.ts
similarity index 100%
rename from src/shared/i18n/language.ts
rename to client/shared/i18n/language.ts
diff --git a/src/shared/i18n/messages.ts b/client/shared/i18n/messages.ts
similarity index 100%
rename from src/shared/i18n/messages.ts
rename to client/shared/i18n/messages.ts
diff --git a/src/shared/i18n/translator.ts b/client/shared/i18n/translator.ts
similarity index 100%
rename from src/shared/i18n/translator.ts
rename to client/shared/i18n/translator.ts
diff --git a/src/shared/lib/utils.ts b/client/shared/lib/utils.ts
similarity index 100%
rename from src/shared/lib/utils.ts
rename to client/shared/lib/utils.ts
diff --git a/src/shared/storage/indexed-db-store.ts b/client/shared/storage/indexed-db-store.ts
similarity index 100%
rename from src/shared/storage/indexed-db-store.ts
rename to client/shared/storage/indexed-db-store.ts
diff --git a/src/shared/ui/button.tsx b/client/shared/ui/button.tsx
similarity index 100%
rename from src/shared/ui/button.tsx
rename to client/shared/ui/button.tsx
diff --git a/src/shared/ui/collapsible.tsx b/client/shared/ui/collapsible.tsx
similarity index 100%
rename from src/shared/ui/collapsible.tsx
rename to client/shared/ui/collapsible.tsx
diff --git a/src/shared/ui/context-menu.tsx b/client/shared/ui/context-menu.tsx
similarity index 100%
rename from src/shared/ui/context-menu.tsx
rename to client/shared/ui/context-menu.tsx
diff --git a/src/shared/ui/dialog.tsx b/client/shared/ui/dialog.tsx
similarity index 100%
rename from src/shared/ui/dialog.tsx
rename to client/shared/ui/dialog.tsx
diff --git a/src/shared/ui/input.tsx b/client/shared/ui/input.tsx
similarity index 100%
rename from src/shared/ui/input.tsx
rename to client/shared/ui/input.tsx
diff --git a/src/shared/ui/label.tsx b/client/shared/ui/label.tsx
similarity index 100%
rename from src/shared/ui/label.tsx
rename to client/shared/ui/label.tsx
diff --git a/src/shared/ui/resizable.tsx b/client/shared/ui/resizable.tsx
similarity index 100%
rename from src/shared/ui/resizable.tsx
rename to client/shared/ui/resizable.tsx
diff --git a/src/shared/ui/scroll-area.tsx b/client/shared/ui/scroll-area.tsx
similarity index 100%
rename from src/shared/ui/scroll-area.tsx
rename to client/shared/ui/scroll-area.tsx
diff --git a/src/shared/ui/select.tsx b/client/shared/ui/select.tsx
similarity index 100%
rename from src/shared/ui/select.tsx
rename to client/shared/ui/select.tsx
diff --git a/src/shared/ui/switch.tsx b/client/shared/ui/switch.tsx
similarity index 100%
rename from src/shared/ui/switch.tsx
rename to client/shared/ui/switch.tsx
diff --git a/src/shared/ui/textarea.tsx b/client/shared/ui/textarea.tsx
similarity index 100%
rename from src/shared/ui/textarea.tsx
rename to client/shared/ui/textarea.tsx
diff --git a/src/shared/ui/tooltip.tsx b/client/shared/ui/tooltip.tsx
similarity index 100%
rename from src/shared/ui/tooltip.tsx
rename to client/shared/ui/tooltip.tsx
diff --git a/src/vite-env.d.ts b/client/vite-env.d.ts
similarity index 100%
rename from src/vite-env.d.ts
rename to client/vite-env.d.ts
diff --git a/src/workspaces/cad/CadWorkspaceShell.tsx b/client/workspaces/cad/CadWorkspaceShell.tsx
similarity index 100%
rename from src/workspaces/cad/CadWorkspaceShell.tsx
rename to client/workspaces/cad/CadWorkspaceShell.tsx
diff --git a/src/workspaces/cad/chat/ChatMessageDisplay.tsx b/client/workspaces/cad/chat/ChatMessageDisplay.tsx
similarity index 100%
rename from src/workspaces/cad/chat/ChatMessageDisplay.tsx
rename to client/workspaces/cad/chat/ChatMessageDisplay.tsx
diff --git a/src/workspaces/cad/chat/ChatPanel.tsx b/client/workspaces/cad/chat/ChatPanel.tsx
similarity index 100%
rename from src/workspaces/cad/chat/ChatPanel.tsx
rename to client/workspaces/cad/chat/ChatPanel.tsx
diff --git a/src/workspaces/cad/chat/code-block.tsx b/client/workspaces/cad/chat/code-block.tsx
similarity index 100%
rename from src/workspaces/cad/chat/code-block.tsx
rename to client/workspaces/cad/chat/code-block.tsx
diff --git a/src/workspaces/cad/storage.ts b/client/workspaces/cad/storage.ts
similarity index 100%
rename from src/workspaces/cad/storage.ts
rename to client/workspaces/cad/storage.ts
diff --git a/src/workspaces/cad/workspace/CadWorkspace.tsx b/client/workspaces/cad/workspace/CadWorkspace.tsx
similarity index 100%
rename from src/workspaces/cad/workspace/CadWorkspace.tsx
rename to client/workspaces/cad/workspace/CadWorkspace.tsx
diff --git a/src/workspaces/flow/FlowWorkspaceShell.tsx b/client/workspaces/flow/FlowWorkspaceShell.tsx
similarity index 100%
rename from src/workspaces/flow/FlowWorkspaceShell.tsx
rename to client/workspaces/flow/FlowWorkspaceShell.tsx
diff --git a/src/workspaces/flow/next/NextFlowWorkspace.tsx b/client/workspaces/flow/next/NextFlowWorkspace.tsx
similarity index 100%
rename from src/workspaces/flow/next/NextFlowWorkspace.tsx
rename to client/workspaces/flow/next/NextFlowWorkspace.tsx
diff --git a/src/workspaces/flow/next/components/chat-input.tsx b/client/workspaces/flow/next/components/chat-input.tsx
similarity index 100%
rename from src/workspaces/flow/next/components/chat-input.tsx
rename to client/workspaces/flow/next/components/chat-input.tsx
diff --git a/src/workspaces/flow/next/components/chat-message-display.tsx b/client/workspaces/flow/next/components/chat-message-display.tsx
similarity index 100%
rename from src/workspaces/flow/next/components/chat-message-display.tsx
rename to client/workspaces/flow/next/components/chat-message-display.tsx
diff --git a/src/workspaces/flow/next/components/chat-panel.tsx b/client/workspaces/flow/next/components/chat-panel.tsx
similarity index 100%
rename from src/workspaces/flow/next/components/chat-panel.tsx
rename to client/workspaces/flow/next/components/chat-panel.tsx
diff --git a/src/workspaces/flow/next/components/code-block.tsx b/client/workspaces/flow/next/components/code-block.tsx
similarity index 100%
rename from src/workspaces/flow/next/components/code-block.tsx
rename to client/workspaces/flow/next/components/code-block.tsx
diff --git a/src/workspaces/flow/next/components/error-toast.tsx b/client/workspaces/flow/next/components/error-toast.tsx
similarity index 100%
rename from src/workspaces/flow/next/components/error-toast.tsx
rename to client/workspaces/flow/next/components/error-toast.tsx
diff --git a/src/workspaces/flow/next/components/history-dialog.tsx b/client/workspaces/flow/next/components/history-dialog.tsx
similarity index 100%
rename from src/workspaces/flow/next/components/history-dialog.tsx
rename to client/workspaces/flow/next/components/history-dialog.tsx
diff --git a/src/workspaces/flow/next/components/quota-limit-toast.tsx b/client/workspaces/flow/next/components/quota-limit-toast.tsx
similarity index 100%
rename from src/workspaces/flow/next/components/quota-limit-toast.tsx
rename to client/workspaces/flow/next/components/quota-limit-toast.tsx
diff --git a/src/workspaces/flow/next/components/save-dialog.tsx b/client/workspaces/flow/next/components/save-dialog.tsx
similarity index 100%
rename from src/workspaces/flow/next/components/save-dialog.tsx
rename to client/workspaces/flow/next/components/save-dialog.tsx
diff --git a/src/workspaces/flow/next/components/settings-dialog.tsx b/client/workspaces/flow/next/components/settings-dialog.tsx
similarity index 100%
rename from src/workspaces/flow/next/components/settings-dialog.tsx
rename to client/workspaces/flow/next/components/settings-dialog.tsx
diff --git a/src/workspaces/flow/next/contexts/diagram-context.tsx b/client/workspaces/flow/next/contexts/diagram-context.tsx
similarity index 100%
rename from src/workspaces/flow/next/contexts/diagram-context.tsx
rename to client/workspaces/flow/next/contexts/diagram-context.tsx
diff --git a/src/workspaces/flow/next/lib/ai-config.ts b/client/workspaces/flow/next/lib/ai-config.ts
similarity index 79%
rename from src/workspaces/flow/next/lib/ai-config.ts
rename to client/workspaces/flow/next/lib/ai-config.ts
index 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 an
diff --git a/src/workspaces/flow/next/lib/diagram-operations.ts b/client/workspaces/flow/next/lib/diagram-operations.ts
similarity index 100%
rename from src/workspaces/flow/next/lib/diagram-operations.ts
rename to client/workspaces/flow/next/lib/diagram-operations.ts
diff --git a/src/workspaces/flow/next/lib/drawio-xml.ts b/client/workspaces/flow/next/lib/drawio-xml.ts
similarity index 100%
rename from src/workspaces/flow/next/lib/drawio-xml.ts
rename to client/workspaces/flow/next/lib/drawio-xml.ts
diff --git a/src/workspaces/flow/next/lib/flow-storage-keys.ts b/client/workspaces/flow/next/lib/flow-storage-keys.ts
similarity index 100%
rename from src/workspaces/flow/next/lib/flow-storage-keys.ts
rename to client/workspaces/flow/next/lib/flow-storage-keys.ts
diff --git a/src/workspaces/flow/next/lib/storage.ts b/client/workspaces/flow/next/lib/storage.ts
similarity index 100%
rename from src/workspaces/flow/next/lib/storage.ts
rename to client/workspaces/flow/next/lib/storage.ts
diff --git a/src/workspaces/flow/next/lib/translations.ts b/client/workspaces/flow/next/lib/translations.ts
similarity index 100%
rename from src/workspaces/flow/next/lib/translations.ts
rename to client/workspaces/flow/next/lib/translations.ts
diff --git a/src/workspaces/flow/next/lib/use-quota-manager.tsx b/client/workspaces/flow/next/lib/use-quota-manager.tsx
similarity index 100%
rename from src/workspaces/flow/next/lib/use-quota-manager.tsx
rename to client/workspaces/flow/next/lib/use-quota-manager.tsx
diff --git a/src/workspaces/flow/next/page.tsx b/client/workspaces/flow/next/page.tsx
similarity index 100%
rename from src/workspaces/flow/next/page.tsx
rename to client/workspaces/flow/next/page.tsx
diff --git a/src/workspaces/flow/next/shims/next-image.tsx b/client/workspaces/flow/next/shims/next-image.tsx
similarity index 100%
rename from src/workspaces/flow/next/shims/next-image.tsx
rename to client/workspaces/flow/next/shims/next-image.tsx
diff --git a/src/workspaces/ppt/PptWorkspaceShell.tsx b/client/workspaces/ppt/PptWorkspaceShell.tsx
similarity index 100%
rename from src/workspaces/ppt/PptWorkspaceShell.tsx
rename to client/workspaces/ppt/PptWorkspaceShell.tsx
diff --git a/src/workspaces/ppt/chat/ChatMessageDisplay.tsx b/client/workspaces/ppt/chat/ChatMessageDisplay.tsx
similarity index 100%
rename from src/workspaces/ppt/chat/ChatMessageDisplay.tsx
rename to client/workspaces/ppt/chat/ChatMessageDisplay.tsx
diff --git a/src/workspaces/ppt/chat/ChatPanel.tsx b/client/workspaces/ppt/chat/ChatPanel.tsx
similarity index 100%
rename from src/workspaces/ppt/chat/ChatPanel.tsx
rename to client/workspaces/ppt/chat/ChatPanel.tsx
diff --git a/src/workspaces/ppt/chat/code-block.tsx b/client/workspaces/ppt/chat/code-block.tsx
similarity index 100%
rename from src/workspaces/ppt/chat/code-block.tsx
rename to client/workspaces/ppt/chat/code-block.tsx
diff --git a/src/workspaces/ppt/storage.ts b/client/workspaces/ppt/storage.ts
similarity index 100%
rename from src/workspaces/ppt/storage.ts
rename to client/workspaces/ppt/storage.ts
diff --git a/src/workspaces/ppt/workspace/PptWorkspace.tsx b/client/workspaces/ppt/workspace/PptWorkspace.tsx
similarity index 100%
rename from src/workspaces/ppt/workspace/PptWorkspace.tsx
rename to client/workspaces/ppt/workspace/PptWorkspace.tsx
diff --git a/src/workspaces/ppt/workspace/constants.ts b/client/workspaces/ppt/workspace/constants.ts
similarity index 100%
rename from src/workspaces/ppt/workspace/constants.ts
rename to client/workspaces/ppt/workspace/constants.ts
diff --git a/src/workspaces/ppt/workspace/persisted-state.ts b/client/workspaces/ppt/workspace/persisted-state.ts
similarity index 100%
rename from src/workspaces/ppt/workspace/persisted-state.ts
rename to client/workspaces/ppt/workspace/persisted-state.ts
diff --git a/src/workspaces/ppt/workspace/slide-content.ts b/client/workspaces/ppt/workspace/slide-content.ts
similarity index 100%
rename from src/workspaces/ppt/workspace/slide-content.ts
rename to client/workspaces/ppt/workspace/slide-content.ts
diff --git a/src/workspaces/ppt/workspace/types.ts b/client/workspaces/ppt/workspace/types.ts
similarity index 100%
rename from src/workspaces/ppt/workspace/types.ts
rename to client/workspaces/ppt/workspace/types.ts
diff --git a/src/ai/config.ts b/contracts/ai.ts
similarity index 53%
rename from src/ai/config.ts
rename to contracts/ai.ts
index 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.html
index 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.json
index 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.md
similarity index 100%
rename from agent/cad/bom-prompt.md
rename to resources/prompts/cad/bom-prompt.md
diff --git a/agent/cad/images-agents/detail-drawings.md b/resources/prompts/cad/images-agents/detail-drawings.md
similarity index 100%
rename from agent/cad/images-agents/detail-drawings.md
rename to resources/prompts/cad/images-agents/detail-drawings.md
diff --git a/agent/cad/images-agents/elevation-index-and-interior-elevations.md b/resources/prompts/cad/images-agents/elevation-index-and-interior-elevations.md
similarity index 100%
rename from agent/cad/images-agents/elevation-index-and-interior-elevations.md
rename to resources/prompts/cad/images-agents/elevation-index-and-interior-elevations.md
diff --git a/agent/cad/images-agents/floor-finish-plan.md b/resources/prompts/cad/images-agents/floor-finish-plan.md
similarity index 100%
rename from agent/cad/images-agents/floor-finish-plan.md
rename to resources/prompts/cad/images-agents/floor-finish-plan.md
diff --git a/agent/cad/images-agents/key-strategy-board.md b/resources/prompts/cad/images-agents/key-strategy-board.md
similarity index 100%
rename from agent/cad/images-agents/key-strategy-board.md
rename to resources/prompts/cad/images-agents/key-strategy-board.md
diff --git a/agent/cad/images-agents/master-renovation-scheme.md b/resources/prompts/cad/images-agents/master-renovation-scheme.md
similarity index 100%
rename from agent/cad/images-agents/master-renovation-scheme.md
rename to resources/prompts/cad/images-agents/master-renovation-scheme.md
diff --git a/agent/cad/images-agents/mep-plan.md b/resources/prompts/cad/images-agents/mep-plan.md
similarity index 100%
rename from agent/cad/images-agents/mep-plan.md
rename to resources/prompts/cad/images-agents/mep-plan.md
diff --git a/agent/cad/images-agents/overall-analysis-board.md b/resources/prompts/cad/images-agents/overall-analysis-board.md
similarity index 100%
rename from agent/cad/images-agents/overall-analysis-board.md
rename to resources/prompts/cad/images-agents/overall-analysis-board.md
diff --git a/agent/cad/images-agents/reflected-ceiling-plan.md b/resources/prompts/cad/images-agents/reflected-ceiling-plan.md
similarity index 100%
rename from agent/cad/images-agents/reflected-ceiling-plan.md
rename to resources/prompts/cad/images-agents/reflected-ceiling-plan.md
diff --git a/agent/cad/images-agents/renovation-plan-layout.md b/resources/prompts/cad/images-agents/renovation-plan-layout.md
similarity index 100%
rename from agent/cad/images-agents/renovation-plan-layout.md
rename to resources/prompts/cad/images-agents/renovation-plan-layout.md
diff --git a/agent/cad/images-agents/wall-setting-out-plan.md b/resources/prompts/cad/images-agents/wall-setting-out-plan.md
similarity index 100%
rename from agent/cad/images-agents/wall-setting-out-plan.md
rename to resources/prompts/cad/images-agents/wall-setting-out-plan.md
diff --git a/agent/cad/plan.md b/resources/prompts/cad/plan.md
similarity index 100%
rename from agent/cad/plan.md
rename to resources/prompts/cad/plan.md
diff --git a/agent/cad/svg/patch.md b/resources/prompts/cad/svg/patch.md
similarity index 100%
rename from agent/cad/svg/patch.md
rename to resources/prompts/cad/svg/patch.md
diff --git a/agent/cad/svg/replace.md b/resources/prompts/cad/svg/replace.md
similarity index 100%
rename from agent/cad/svg/replace.md
rename to resources/prompts/cad/svg/replace.md
diff --git a/agent/cad/svg/system.md b/resources/prompts/cad/svg/system.md
similarity index 100%
rename from agent/cad/svg/system.md
rename to resources/prompts/cad/svg/system.md
diff --git a/agent/cad/system.md b/resources/prompts/cad/system.md
similarity index 100%
rename from agent/cad/system.md
rename to resources/prompts/cad/system.md
diff --git a/agent/flow/deep-thinking-image.md b/resources/prompts/flow/deep-thinking-image.md
similarity index 100%
rename from agent/flow/deep-thinking-image.md
rename to resources/prompts/flow/deep-thinking-image.md
diff --git a/agent/flow/patch.md b/resources/prompts/flow/patch.md
similarity index 100%
rename from agent/flow/patch.md
rename to resources/prompts/flow/patch.md
diff --git a/agent/flow/replace.md b/resources/prompts/flow/replace.md
similarity index 100%
rename from agent/flow/replace.md
rename to resources/prompts/flow/replace.md
diff --git a/agent/flow/system.md b/resources/prompts/flow/system.md
similarity index 100%
rename from agent/flow/system.md
rename to resources/prompts/flow/system.md
diff --git a/agent/ppt/outline-edit.md b/resources/prompts/ppt/outline-edit.md
similarity index 100%
rename from agent/ppt/outline-edit.md
rename to resources/prompts/ppt/outline-edit.md
diff --git a/agent/ppt/outline.md b/resources/prompts/ppt/outline.md
similarity index 100%
rename from agent/ppt/outline.md
rename to resources/prompts/ppt/outline.md
diff --git a/agent/ppt/slides-generate.md b/resources/prompts/ppt/slides-generate.md
similarity index 100%
rename from agent/ppt/slides-generate.md
rename to resources/prompts/ppt/slides-generate.md
diff --git a/agent/ppt/system.md b/resources/prompts/ppt/system.md
similarity index 100%
rename from agent/ppt/system.md
rename to resources/prompts/ppt/system.md
diff --git a/docs/shape-libraries/README.md b/resources/shape-libraries/README.md
similarity index 100%
rename from docs/shape-libraries/README.md
rename to resources/shape-libraries/README.md
diff --git a/docs/shape-libraries/alibaba_cloud.md b/resources/shape-libraries/alibaba_cloud.md
similarity index 100%
rename from docs/shape-libraries/alibaba_cloud.md
rename to resources/shape-libraries/alibaba_cloud.md
diff --git a/docs/shape-libraries/android.md b/resources/shape-libraries/android.md
similarity index 100%
rename from docs/shape-libraries/android.md
rename to resources/shape-libraries/android.md
diff --git a/docs/shape-libraries/arrows2.md b/resources/shape-libraries/arrows2.md
similarity index 100%
rename from docs/shape-libraries/arrows2.md
rename to resources/shape-libraries/arrows2.md
diff --git a/docs/shape-libraries/atlassian.md b/resources/shape-libraries/atlassian.md
similarity index 100%
rename from docs/shape-libraries/atlassian.md
rename to resources/shape-libraries/atlassian.md
diff --git a/docs/shape-libraries/aws4.md b/resources/shape-libraries/aws4.md
similarity index 100%
rename from docs/shape-libraries/aws4.md
rename to resources/shape-libraries/aws4.md
diff --git a/docs/shape-libraries/azure2.md b/resources/shape-libraries/azure2.md
similarity index 100%
rename from docs/shape-libraries/azure2.md
rename to resources/shape-libraries/azure2.md
diff --git a/docs/shape-libraries/basic.md b/resources/shape-libraries/basic.md
similarity index 100%
rename from docs/shape-libraries/basic.md
rename to resources/shape-libraries/basic.md
diff --git a/docs/shape-libraries/bpmn.md b/resources/shape-libraries/bpmn.md
similarity index 100%
rename from docs/shape-libraries/bpmn.md
rename to resources/shape-libraries/bpmn.md
diff --git a/docs/shape-libraries/cabinets.md b/resources/shape-libraries/cabinets.md
similarity index 100%
rename from docs/shape-libraries/cabinets.md
rename to resources/shape-libraries/cabinets.md
diff --git a/docs/shape-libraries/cisco19.md b/resources/shape-libraries/cisco19.md
similarity index 100%
rename from docs/shape-libraries/cisco19.md
rename to resources/shape-libraries/cisco19.md
diff --git a/docs/shape-libraries/citrix.md b/resources/shape-libraries/citrix.md
similarity index 100%
rename from docs/shape-libraries/citrix.md
rename to resources/shape-libraries/citrix.md
diff --git a/docs/shape-libraries/electrical.md b/resources/shape-libraries/electrical.md
similarity index 100%
rename from docs/shape-libraries/electrical.md
rename to resources/shape-libraries/electrical.md
diff --git a/docs/shape-libraries/floorplan.md b/resources/shape-libraries/floorplan.md
similarity index 100%
rename from docs/shape-libraries/floorplan.md
rename to resources/shape-libraries/floorplan.md
diff --git a/docs/shape-libraries/flowchart.md b/resources/shape-libraries/flowchart.md
similarity index 100%
rename from docs/shape-libraries/flowchart.md
rename to resources/shape-libraries/flowchart.md
diff --git a/docs/shape-libraries/fluidpower.md b/resources/shape-libraries/fluidpower.md
similarity index 100%
rename from docs/shape-libraries/fluidpower.md
rename to resources/shape-libraries/fluidpower.md
diff --git a/docs/shape-libraries/gcp2.md b/resources/shape-libraries/gcp2.md
similarity index 100%
rename from docs/shape-libraries/gcp2.md
rename to resources/shape-libraries/gcp2.md
diff --git a/docs/shape-libraries/infographic.md b/resources/shape-libraries/infographic.md
similarity index 100%
rename from docs/shape-libraries/infographic.md
rename to resources/shape-libraries/infographic.md
diff --git a/docs/shape-libraries/kubernetes.md b/resources/shape-libraries/kubernetes.md
similarity index 100%
rename from docs/shape-libraries/kubernetes.md
rename to resources/shape-libraries/kubernetes.md
diff --git a/docs/shape-libraries/lean_mapping.md b/resources/shape-libraries/lean_mapping.md
similarity index 100%
rename from docs/shape-libraries/lean_mapping.md
rename to resources/shape-libraries/lean_mapping.md
diff --git a/docs/shape-libraries/material_design.md b/resources/shape-libraries/material_design.md
similarity index 100%
rename from docs/shape-libraries/material_design.md
rename to resources/shape-libraries/material_design.md
diff --git a/docs/shape-libraries/mscae.md b/resources/shape-libraries/mscae.md
similarity index 100%
rename from docs/shape-libraries/mscae.md
rename to resources/shape-libraries/mscae.md
diff --git a/docs/shape-libraries/network.md b/resources/shape-libraries/network.md
similarity index 100%
rename from docs/shape-libraries/network.md
rename to resources/shape-libraries/network.md
diff --git a/docs/shape-libraries/openstack.md b/resources/shape-libraries/openstack.md
similarity index 100%
rename from docs/shape-libraries/openstack.md
rename to resources/shape-libraries/openstack.md
diff --git a/docs/shape-libraries/pid.md b/resources/shape-libraries/pid.md
similarity index 100%
rename from docs/shape-libraries/pid.md
rename to resources/shape-libraries/pid.md
diff --git a/docs/shape-libraries/rack.md b/resources/shape-libraries/rack.md
similarity index 100%
rename from docs/shape-libraries/rack.md
rename to resources/shape-libraries/rack.md
diff --git a/docs/shape-libraries/salesforce.md b/resources/shape-libraries/salesforce.md
similarity index 100%
rename from docs/shape-libraries/salesforce.md
rename to resources/shape-libraries/salesforce.md
diff --git a/docs/shape-libraries/sap.md b/resources/shape-libraries/sap.md
similarity index 100%
rename from docs/shape-libraries/sap.md
rename to resources/shape-libraries/sap.md
diff --git a/docs/shape-libraries/sitemap.md b/resources/shape-libraries/sitemap.md
similarity index 100%
rename from docs/shape-libraries/sitemap.md
rename to resources/shape-libraries/sitemap.md
diff --git a/docs/shape-libraries/vvd.md b/resources/shape-libraries/vvd.md
similarity index 100%
rename from docs/shape-libraries/vvd.md
rename to resources/shape-libraries/vvd.md
diff --git a/docs/shape-libraries/webicons.md b/resources/shape-libraries/webicons.md
similarity index 100%
rename from docs/shape-libraries/webicons.md
rename to resources/shape-libraries/webicons.md
diff --git a/src/ai/image.ts b/server/ai/image.ts
similarity index 98%
rename from src/ai/image.ts
rename to server/ai/image.ts
index 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.ts
similarity index 95%
rename from src/ai/server-model.ts
rename to server/ai/model.ts
index 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.ts
similarity index 92%
rename from src/ai/text.ts
rename to server/ai/text.ts
index 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.ts
similarity index 98%
rename from src/ai/transport.ts
rename to server/ai/transport.ts
index 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.ts
similarity index 98%
rename from src/server/chat/deep-thinking.ts
rename to server/chat/deep-thinking.ts
index 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.ts
similarity index 100%
rename from src/server/chat/files.ts
rename to server/chat/files.ts
diff --git a/src/server/chat/intent.ts b/server/chat/intent.ts
similarity index 100%
rename from src/server/chat/intent.ts
rename to server/chat/intent.ts
diff --git a/src/server/chat/messages.ts b/server/chat/messages.ts
similarity index 100%
rename from src/server/chat/messages.ts
rename to server/chat/messages.ts
diff --git a/src/server/chat/shape-library.ts b/server/chat/shape-library.ts
similarity index 59%
rename from src/server/chat/shape-library.ts
rename to server/chat/shape-library.ts
index 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.ts
similarity index 100%
rename from src/server/chat/summarize.ts
rename to server/chat/summarize.ts
diff --git a/src/server/chat/system-prompt.ts b/server/chat/system-prompt.ts
similarity index 100%
rename from src/server/chat/system-prompt.ts
rename to server/chat/system-prompt.ts
diff --git a/server/http/adapter.ts b/server/http/adapter.ts
new file mode 100644
index 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.ts
new file mode 100644
index 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.ts
new file mode 100644
index 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.ts
new file mode 100644
index 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.ts
similarity index 98%
rename from src/server/routes/chat.ts
rename to server/routes/chat.ts
index 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.ts
similarity index 100%
rename from src/server/routes/config.ts
rename to server/routes/config.ts
diff --git a/src/server/routes/log-feedback.ts b/server/routes/log-feedback.ts
similarity index 100%
rename from src/server/routes/log-feedback.ts
rename to server/routes/log-feedback.ts
diff --git a/src/server/routes/log-file-parser.ts b/server/routes/log-file-parser.ts
similarity index 100%
rename from src/server/routes/log-file-parser.ts
rename to server/routes/log-file-parser.ts
diff --git a/src/server/routes/log-save.ts b/server/routes/log-save.ts
similarity index 100%
rename from src/server/routes/log-save.ts
rename to server/routes/log-save.ts
diff --git a/src/server/routes/ppt-ai.ts b/server/routes/ppt-ai.ts
similarity index 94%
rename from src/server/routes/ppt-ai.ts
rename to server/routes/ppt-ai.ts
index 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.ts
similarity index 100%
rename from src/server/routes/third-party-parser.ts
rename to server/routes/third-party-parser.ts
diff --git a/src/server/routes/verify-access-code.ts b/server/routes/verify-access-code.ts
similarity index 100%
rename from src/server/routes/verify-access-code.ts
rename to server/routes/verify-access-code.ts
diff --git a/src/server/telemetry/langfuse.ts b/server/telemetry/langfuse.ts
similarity index 100%
rename from src/server/telemetry/langfuse.ts
rename to server/telemetry/langfuse.ts
diff --git a/src/ai/types.ts b/src/ai/types.ts
deleted file mode 100644
index 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.ts
deleted file mode 100644
index 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.ts
deleted file mode 100644
index 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.js
index 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.ts
index 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.ts
index 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 three
diff --git a/tsconfig.json b/tsconfig.json
index 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.ts
index 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()],
+});