Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(M8): add Prompt Manager for customizable AI prompts
Adam Eivy59f18732f3db
diff --git a/PLAN.md b/PLAN.mdindex ed0491eb27..d88e7bb72b 100644--- a/PLAN.md+++ b/PLAN.md@@ -35,7 +35,7 @@ pm2 logs- [x] M6: Dev tools (history, command runner)- [ ] M7: App templates (create from templates, template management)- [ ] M8: Prompt manager (customizable AI prompts, variables, stages)-- [ ] M9: Streaming import detection (websocket updates, progressive discovery)+- [x] M9: Streaming import detection (websocket updates, progressive discovery)### Documentation- [Contributing Guide](./docs/CONTRIBUTING.md) - Code guidelines, git workflowdiff --git a/client/src/App.jsx b/client/src/App.jsxindex b29a47c6c8..af3a460f5b 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -7,6 +7,7 @@ import CreateApp from './pages/CreateApp';import Templates from './pages/Templates';import AIProviders from './pages/AIProviders';import DevTools from './pages/DevTools';+import PromptManager from './pages/PromptManager';export default function App() {return (@@ -18,6 +19,7 @@ export default function App() {<Route path="devtools" element={<Navigate to="/devtools/history" replace />} /><Route path="devtools/:tab" element={<DevTools />} /><Route path="ai" element={<AIProviders />} />+ <Route path="prompts" element={<PromptManager />} /><Route path="create" element={<CreateApp />} /><Route path="templates" element={<Templates />} /><Route path="*" element={<Navigate to="/" replace />} />diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex fd457b13ee..46d1c046a2 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -31,7 +31,14 @@ const navItems = [{ to: '/devtools/processes', label: 'Processes', icon: Activity }]},- { to: '/ai', label: 'AI Providers', icon: Bot, single: true },+ {+ label: 'AI Config',+ icon: Bot,+ children: [+ { to: '/ai', label: 'Providers', icon: Bot },+ { to: '/prompts', label: 'Prompts', icon: FileText }+ ]+ },{ to: '/create', label: 'Add App', icon: PlusCircle, single: true }];diff --git a/client/src/pages/PromptManager.jsx b/client/src/pages/PromptManager.jsxnew file mode 100644index 0000000000..20825559dc--- /dev/null+++ b/client/src/pages/PromptManager.jsx@@ -0,0 +1,372 @@+import { useState, useEffect } from 'react';+import { FileText, Variable, RefreshCw, Save, Plus, Trash2, Eye } from 'lucide-react';+import * as api from '../services/api';++export default function PromptManager() {+ const [tab, setTab] = useState('stages');+ const [stages, setStages] = useState({});+ const [variables, setVariables] = useState({});+ const [loading, setLoading] = useState(true);++ // Stage editing+ const [selectedStage, setSelectedStage] = useState(null);+ const [stageTemplate, setStageTemplate] = useState('');+ const [stageConfig, setStageConfig] = useState({});+ const [preview, setPreview] = useState('');+ const [testData, setTestData] = useState('{}');++ // Variable editing+ const [selectedVar, setSelectedVar] = useState(null);+ const [varForm, setVarForm] = useState({ key: '', name: '', category: '', content: '' });++ const [saving, setSaving] = useState(false);++ useEffect(() => {+ loadData();+ }, []);++ const loadData = async () => {+ setLoading(true);+ const [stagesRes, varsRes] = await Promise.all([+ fetch('/api/prompts').then(r => r.json()),+ fetch('/api/prompts/variables').then(r => r.json())+ ]);+ setStages(stagesRes.stages || {});+ setVariables(varsRes.variables || {});+ setLoading(false);+ };++ const loadStage = async (name) => {+ setSelectedStage(name);+ const res = await fetch(`/api/prompts/${name}`).then(r => r.json());+ setStageTemplate(res.template || '');+ setStageConfig({ name: res.name, description: res.description, model: res.model, variables: res.variables || [] });+ setPreview('');+ };++ const saveStage = async () => {+ setSaving(true);+ await fetch(`/api/prompts/${selectedStage}`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ template: stageTemplate, ...stageConfig })+ });+ setSaving(false);+ await loadData();+ };++ const previewStage = async () => {+ const data = JSON.parse(testData || '{}');+ const res = await fetch(`/api/prompts/${selectedStage}/preview`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ testData: data })+ }).then(r => r.json());+ setPreview(res.preview);+ };++ const loadVariable = (key) => {+ setSelectedVar(key);+ const v = variables[key];+ setVarForm({ key, name: v.name || '', category: v.category || '', content: v.content || '' });+ };++ const saveVariable = async () => {+ setSaving(true);+ if (selectedVar) {+ await fetch(`/api/prompts/variables/${selectedVar}`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(varForm)+ });+ } else {+ await fetch('/api/prompts/variables', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(varForm)+ });+ }+ setSaving(false);+ setSelectedVar(null);+ setVarForm({ key: '', name: '', category: '', content: '' });+ await loadData();+ };++ const deleteVariable = async (key) => {+ await fetch(`/api/prompts/variables/${key}`, { method: 'DELETE' });+ await loadData();+ };++ const newVariable = () => {+ setSelectedVar(null);+ setVarForm({ key: '', name: '', category: '', content: '' });+ };++ if (loading) {+ return <div className="flex items-center justify-center h-64 text-gray-500">Loading...</div>;+ }++ return (+ <div>+ {/* Header */}+ <div className="flex items-center justify-between mb-6">+ <div>+ <h1 className="text-2xl font-bold text-white">Prompt Manager</h1>+ <p className="text-gray-500">Customize AI prompts for backend operations</p>+ </div>+ <button+ onClick={loadData}+ className="p-2 text-gray-400 hover:text-white"+ title="Reload"+ >+ <RefreshCw size={20} />+ </button>+ </div>++ {/* Tabs */}+ <div className="flex gap-2 mb-6">+ <button+ onClick={() => setTab('stages')}+ className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors ${+ tab === 'stages' ? 'bg-port-accent text-white' : 'bg-port-card text-gray-400 hover:text-white'+ }`}+ >+ <FileText size={16} /> Stages+ </button>+ <button+ onClick={() => setTab('variables')}+ className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors ${+ tab === 'variables' ? 'bg-port-accent text-white' : 'bg-port-card text-gray-400 hover:text-white'+ }`}+ >+ <Variable size={16} /> Variables+ </button>+ </div>++ {/* Stages Tab */}+ {tab === 'stages' && (+ <div className="grid grid-cols-3 gap-6">+ {/* Stage List */}+ <div className="bg-port-card border border-port-border rounded-xl p-4">+ <h3 className="text-sm font-medium text-gray-400 mb-3">Prompt Stages</h3>+ <div className="space-y-1">+ {Object.entries(stages).map(([name, config]) => (+ <button+ key={name}+ onClick={() => loadStage(name)}+ className={`w-full text-left px-3 py-2 rounded-lg text-sm transition-colors ${+ selectedStage === name+ ? 'bg-port-accent/20 text-port-accent'+ : 'text-gray-300 hover:bg-port-border'+ }`}+ >+ <div className="font-medium">{config.name || name}</div>+ <div className="text-xs text-gray-500 truncate">{config.description}</div>+ </button>+ ))}+ </div>+ </div>++ {/* Stage Editor */}+ <div className="col-span-2 space-y-4">+ {selectedStage ? (+ <>+ <div className="bg-port-card border border-port-border rounded-xl p-4">+ <div className="flex items-center justify-between mb-4">+ <h3 className="text-lg font-medium text-white">{stageConfig.name}</h3>+ <div className="flex gap-2">+ <button+ onClick={previewStage}+ className="flex items-center gap-1 px-3 py-1 text-sm bg-port-border hover:bg-port-border/80 text-white rounded"+ >+ <Eye size={14} /> Preview+ </button>+ <button+ onClick={saveStage}+ disabled={saving}+ className="flex items-center gap-1 px-3 py-1 text-sm bg-port-accent hover:bg-port-accent/80 text-white rounded disabled:opacity-50"+ >+ <Save size={14} /> Save+ </button>+ </div>+ </div>++ <div className="mb-4">+ <label className="block text-sm text-gray-400 mb-1">Template</label>+ <textarea+ value={stageTemplate}+ onChange={(e) => setStageTemplate(e.target.value)}+ className="w-full h-64 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white font-mono text-sm focus:border-port-accent focus:outline-none"+ />+ <p className="text-xs text-gray-500 mt-1">+ Use {'{{variable}}'} for substitution, {'{{#array}}...{{/array}}'} for iteration+ </p>+ </div>++ <div className="grid grid-cols-2 gap-4">+ <div>+ <label className="block text-sm text-gray-400 mb-1">Model</label>+ <select+ value={stageConfig.model || 'default'}+ onChange={(e) => setStageConfig({ ...stageConfig, model: e.target.value })}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"+ >+ <option value="default">Default</option>+ <option value="quick">Quick</option>+ <option value="coding">Coding</option>+ </select>+ </div>+ <div>+ <label className="block text-sm text-gray-400 mb-1">Variables Used</label>+ <div className="text-sm text-gray-300">+ {(stageConfig.variables || []).join(', ') || 'None'}+ </div>+ </div>+ </div>+ </div>++ {/* Preview Panel */}+ {preview && (+ <div className="bg-port-card border border-port-border rounded-xl p-4">+ <h4 className="text-sm font-medium text-gray-400 mb-2">Preview</h4>+ <pre className="text-sm text-gray-300 whitespace-pre-wrap bg-port-bg p-3 rounded max-h-64 overflow-auto">+ {preview}+ </pre>+ </div>+ )}++ {/* Test Data */}+ <div className="bg-port-card border border-port-border rounded-xl p-4">+ <h4 className="text-sm font-medium text-gray-400 mb-2">Test Data (JSON)</h4>+ <textarea+ value={testData}+ onChange={(e) => setTestData(e.target.value)}+ className="w-full h-24 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white font-mono text-sm focus:border-port-accent focus:outline-none"+ placeholder='{"dirName": "my-app", "fileList": "package.json, src/"}'+ />+ </div>+ </>+ ) : (+ <div className="bg-port-card border border-port-border rounded-xl p-12 text-center text-gray-500">+ Select a stage to edit+ </div>+ )}+ </div>+ </div>+ )}++ {/* Variables Tab */}+ {tab === 'variables' && (+ <div className="grid grid-cols-3 gap-6">+ {/* Variable List */}+ <div className="bg-port-card border border-port-border rounded-xl p-4">+ <div className="flex items-center justify-between mb-3">+ <h3 className="text-sm font-medium text-gray-400">Variables</h3>+ <button+ onClick={newVariable}+ className="p-1 text-port-accent hover:text-port-accent/80"+ >+ <Plus size={16} />+ </button>+ </div>+ <div className="space-y-1">+ {Object.entries(variables).map(([key, v]) => (+ <div+ key={key}+ className={`flex items-center justify-between px-3 py-2 rounded-lg text-sm ${+ selectedVar === key+ ? 'bg-port-accent/20 text-port-accent'+ : 'text-gray-300 hover:bg-port-border'+ }`}+ >+ <button+ onClick={() => loadVariable(key)}+ className="flex-1 text-left"+ >+ <div className="font-medium">{v.name || key}</div>+ <div className="text-xs text-gray-500">{v.category || 'uncategorized'}</div>+ </button>+ <button+ onClick={() => deleteVariable(key)}+ className="p-1 text-gray-500 hover:text-port-error"+ >+ <Trash2 size={14} />+ </button>+ </div>+ ))}+ </div>+ </div>++ {/* Variable Editor */}+ <div className="col-span-2">+ <div className="bg-port-card border border-port-border rounded-xl p-4">+ <div className="flex items-center justify-between mb-4">+ <h3 className="text-lg font-medium text-white">+ {selectedVar ? `Edit: ${selectedVar}` : 'New Variable'}+ </h3>+ <button+ onClick={saveVariable}+ disabled={saving || !varForm.key || !varForm.content}+ className="flex items-center gap-1 px-3 py-1 text-sm bg-port-accent hover:bg-port-accent/80 text-white rounded disabled:opacity-50"+ >+ <Save size={14} /> Save+ </button>+ </div>++ <div className="space-y-4">+ <div className="grid grid-cols-2 gap-4">+ <div>+ <label className="block text-sm text-gray-400 mb-1">Key *</label>+ <input+ type="text"+ value={varForm.key}+ onChange={(e) => setVarForm({ ...varForm, key: e.target.value })}+ disabled={!!selectedVar}+ placeholder="variableKey"+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none disabled:opacity-50"+ />+ </div>+ <div>+ <label className="block text-sm text-gray-400 mb-1">Name</label>+ <input+ type="text"+ value={varForm.name}+ onChange={(e) => setVarForm({ ...varForm, name: e.target.value })}+ placeholder="Human Readable Name"+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"+ />+ </div>+ </div>++ <div>+ <label className="block text-sm text-gray-400 mb-1">Category</label>+ <select+ value={varForm.category}+ onChange={(e) => setVarForm({ ...varForm, category: e.target.value })}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-none"+ >+ <option value="">Select category</option>+ <option value="response">Response Format</option>+ <option value="schema">Schema</option>+ <option value="rules">Rules</option>+ <option value="system">System</option>+ </select>+ </div>++ <div>+ <label className="block text-sm text-gray-400 mb-1">Content *</label>+ <textarea+ value={varForm.content}+ onChange={(e) => setVarForm({ ...varForm, content: e.target.value })}+ className="w-full h-48 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white font-mono text-sm focus:border-port-accent focus:outline-none"+ placeholder="Variable content..."+ />+ </div>+ </div>+ </div>+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/server/index.js b/server/index.jsindex c99707cdf9..526a1fe249 100644--- a/server/index.js+++ b/server/index.js@@ -15,6 +15,7 @@ import providersRoutes from './routes/providers.js';import runsRoutes from './routes/runs.js';import historyRoutes from './routes/history.js';import commandsRoutes from './routes/commands.js';+import promptsRoutes from './routes/prompts.js';import { initSocket } from './services/socket.js';const __filename = fileURLToPath(import.meta.url);@@ -59,6 +60,7 @@ app.use('/api/providers', providersRoutes);app.use('/api/runs', runsRoutes);app.use('/api/history', historyRoutes);app.use('/api/commands', commandsRoutes);+app.use('/api/prompts', promptsRoutes);// Error handlerapp.use((err, req, res, next) => {diff --git a/server/routes/prompts.js b/server/routes/prompts.jsnew file mode 100644index 0000000000..0541a50d78--- /dev/null+++ b/server/routes/prompts.js@@ -0,0 +1,86 @@+import { Router } from 'express';+import * as promptService from '../services/promptService.js';++const router = Router();++// GET /api/prompts - List all stages+router.get('/', async (req, res) => {+ const stages = promptService.getStages();+ res.json({ stages });+});++// GET /api/prompts/variables - List all variables+router.get('/variables', async (req, res) => {+ const variables = promptService.getVariables();+ res.json({ variables });+});++// GET /api/prompts/variables/:key - Get a variable+router.get('/variables/:key', async (req, res) => {+ const variable = promptService.getVariable(req.params.key);+ if (!variable) {+ return res.status(404).json({ error: 'Variable not found' });+ }+ res.json({ key: req.params.key, ...variable });+});++// POST /api/prompts/variables - Create a variable+router.post('/variables', async (req, res) => {+ const { key, name, category, content } = req.body;+ if (!key || !content) {+ return res.status(400).json({ error: 'key and content are required' });+ }+ await promptService.createVariable(key, { name, category, content });+ res.json({ success: true, key });+});++// PUT /api/prompts/variables/:key - Update a variable+router.put('/variables/:key', async (req, res) => {+ const { name, category, content } = req.body;+ await promptService.updateVariable(req.params.key, { name, category, content });+ res.json({ success: true });+});++// DELETE /api/prompts/variables/:key - Delete a variable+router.delete('/variables/:key', async (req, res) => {+ await promptService.deleteVariable(req.params.key);+ res.json({ success: true });+});++// GET /api/prompts/:stage - Get stage with template+router.get('/:stage', async (req, res) => {+ const stage = promptService.getStage(req.params.stage);+ if (!stage) {+ return res.status(404).json({ error: 'Stage not found' });+ }+ const template = await promptService.getStageTemplate(req.params.stage);+ res.json({ ...stage, template });+});++// PUT /api/prompts/:stage - Update stage config and/or template+router.put('/:stage', async (req, res) => {+ const { template, ...config } = req.body;++ if (Object.keys(config).length > 0) {+ await promptService.updateStageConfig(req.params.stage, config);+ }+ if (template !== undefined) {+ await promptService.updateStageTemplate(req.params.stage, template);+ }+ res.json({ success: true });+});++// POST /api/prompts/:stage/preview - Preview compiled prompt+router.post('/:stage/preview', async (req, res) => {+ const { testData = {} } = req.body;+ const preview = await promptService.previewPrompt(req.params.stage, testData);+ res.json({ preview });+});++// POST /api/prompts/reload - Reload prompts from disk+router.post('/reload', async (req, res) => {+ await promptService.loadPrompts();+ res.json({ success: true });+});++export default router;diff --git a/server/services/promptService.js b/server/services/promptService.jsnew file mode 100644index 0000000000..ed12b3efcb--- /dev/null+++ b/server/services/promptService.js@@ -0,0 +1,183 @@+import { readFile, writeFile, readdir, mkdir } from 'fs/promises';+import { existsSync } from 'fs';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';++const __filename = fileURLToPath(import.meta.url);+const __dirname = dirname(__filename);+const PROMPTS_DIR = join(__dirname, '../../data/prompts');++let stageConfig = null;+let variables = null;++/**+ * Load or reload prompts configuration+ */+export async function loadPrompts() {+ const configPath = join(PROMPTS_DIR, 'stage-config.json');+ const varsPath = join(PROMPTS_DIR, 'variables.json');++ if (existsSync(configPath)) {+ stageConfig = JSON.parse(await readFile(configPath, 'utf-8'));+ } else {+ stageConfig = { stages: {} };+ }++ if (existsSync(varsPath)) {+ variables = JSON.parse(await readFile(varsPath, 'utf-8'));+ } else {+ variables = { variables: {} };+ }++ console.log(`📝 Loaded ${Object.keys(stageConfig.stages || {}).length} prompt stages`);+}++/**+ * Get all stages with their metadata+ */+export function getStages() {+ return stageConfig?.stages || {};+}++/**+ * Get stage configuration+ */+export function getStage(stageName) {+ return stageConfig?.stages?.[stageName] || null;+}++/**+ * Get stage template content+ */+export async function getStageTemplate(stageName) {+ const templatePath = join(PROMPTS_DIR, 'stages', `${stageName}.md`);+ if (!existsSync(templatePath)) return null;+ return readFile(templatePath, 'utf-8');+}++/**+ * Update stage template+ */+export async function updateStageTemplate(stageName, content) {+ const stagesDir = join(PROMPTS_DIR, 'stages');+ if (!existsSync(stagesDir)) await mkdir(stagesDir, { recursive: true });+ await writeFile(join(stagesDir, `${stageName}.md`), content);+}++/**+ * Update stage configuration+ */+export async function updateStageConfig(stageName, config) {+ if (!stageConfig) await loadPrompts();+ stageConfig.stages[stageName] = { ...stageConfig.stages[stageName], ...config };+ await writeFile(join(PROMPTS_DIR, 'stage-config.json'), JSON.stringify(stageConfig, null, 2));+}++/**+ * Get all variables+ */+export function getVariables() {+ return variables?.variables || {};+}++/**+ * Get a single variable+ */+export function getVariable(key) {+ return variables?.variables?.[key] || null;+}++/**+ * Update a variable+ */+export async function updateVariable(key, data) {+ if (!variables) await loadPrompts();+ variables.variables[key] = { ...variables.variables[key], ...data };+ await writeFile(join(PROMPTS_DIR, 'variables.json'), JSON.stringify(variables, null, 2));+}++/**+ * Create a new variable+ */+export async function createVariable(key, data) {+ if (!variables) await loadPrompts();+ if (variables.variables[key]) {+ throw new Error(`Variable ${key} already exists`);+ }+ variables.variables[key] = data;+ await writeFile(join(PROMPTS_DIR, 'variables.json'), JSON.stringify(variables, null, 2));+}++/**+ * Delete a variable+ */+export async function deleteVariable(key) {+ if (!variables) await loadPrompts();+ delete variables.variables[key];+ await writeFile(join(PROMPTS_DIR, 'variables.json'), JSON.stringify(variables, null, 2));+}++/**+ * Build a prompt from template and variables+ */+export async function buildPrompt(stageName, data = {}) {+ const stage = getStage(stageName);+ if (!stage) throw new Error(`Stage ${stageName} not found`);++ let template = await getStageTemplate(stageName);+ if (!template) throw new Error(`Template for ${stageName} not found`);++ // Collect all variables needed for this stage+ const allVars = { ...data };+ for (const varName of stage.variables || []) {+ const v = getVariable(varName);+ if (v) allVars[varName] = v.content;+ }++ // Apply Mustache-like template substitution+ return applyTemplate(template, allVars);+}++/**+ * Apply Mustache-like template substitution+ */+function applyTemplate(template, data) {+ let result = template;++ // Handle sections {{#key}}...{{/key}}+ result = result.replace(/\{\{#(\w+)\}\}([\s\S]*?)\{\{\/\1\}\}/g, (match, key, content) => {+ const value = data[key];+ if (!value) return '';+ if (Array.isArray(value)) {+ return value.map(item => {+ if (typeof item === 'object') {+ return applyTemplate(content, item);+ }+ return content.replace(/\{\{\.\}\}/g, item);+ }).join('');+ }+ return applyTemplate(content, data);+ });++ // Handle inverted sections {{^key}}...{{/key}}+ result = result.replace(/\{\{\^(\w+)\}\}([\s\S]*?)\{\{\/\1\}\}/g, (match, key, content) => {+ return data[key] ? '' : content;+ });++ // Handle simple variables {{key}}+ result = result.replace(/\{\{(\w+)\}\}/g, (match, key) => {+ return data[key] !== undefined ? String(data[key]) : '';+ });++ return result.trim();+}++/**+ * Preview a prompt with test data+ */+export async function previewPrompt(stageName, testData = {}) {+ return buildPrompt(stageName, testData);+}++// Load prompts on module init+loadPrompts().catch(err => console.error(`❌ Failed to load prompts: ${err.message}`));