Skip to content

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

feat: add prompt stage creation and deletion to ai-toolkit

Adam Eivy8b0e5e04ec10
diff --git a/client/src/pages/PromptManager.jsx b/client/src/pages/PromptManager.jsx
index 504a1e46d7..3f36e345ee 100644
--- a/client/src/pages/PromptManager.jsx
+++ b/client/src/pages/PromptManager.jsx
@@ -18,6 +18,18 @@ export default function PromptManager() {
const [selectedVar, setSelectedVar] = useState(null);
const [varForm, setVarForm] = useState({ key: '', name: '', category: '', content: '' });
+ // Stage creation
+ const [creatingStage, setCreatingStage] = useState(false);
+ const [newStageForm, setNewStageForm] = useState({
+ stageName: '',
+ name: '',
+ description: '',
+ model: 'default',
+ returnsJson: false,
+ variables: [],
+ template: ''
+ });
+
const [saving, setSaving] = useState(false);
useEffect(() => {
@@ -101,6 +113,36 @@ export default function PromptManager() {
setVarForm({ key: '', name: '', category: '', content: '' });
};
+ const createStage = async () => {
+ setSaving(true);
+ await fetch('/api/prompts', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(newStageForm)
+ });
+ setSaving(false);
+ setCreatingStage(false);
+ setNewStageForm({
+ stageName: '',
+ name: '',
+ description: '',
+ model: 'default',
+ returnsJson: false,
+ variables: [],
+ template: ''
+ });
+ await loadData();
+ };
+
+ const deleteStage = async (stageName) => {
+ if (!confirm(`Delete stage "${stageName}"? This cannot be undone.`)) return;
+ await fetch(`/api/prompts/${stageName}`, { method: 'DELETE' });
+ if (selectedStage === stageName) {
+ setSelectedStage(null);
+ }
+ await loadData();
+ };
+
if (loading) {
return <div className="flex items-center justify-center h-64 text-gray-500">Loading...</div>;
}
@@ -147,21 +189,41 @@ export default function PromptManager() {
<div className="grid grid-cols-1 lg: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="flex items-center justify-between mb-3">
+ <h3 className="text-sm font-medium text-gray-400">Prompt Stages</h3>
+ <button
+ onClick={() => setCreatingStage(true)}
+ className="p-1 text-port-accent hover:text-port-accent/80"
+ title="New Stage"
+ >
+ <Plus size={16} />
+ </button>
+ </div>
<div className="space-y-1">
{Object.entries(stages).map(([name, config]) => (
- <button
+ <div
key={name}
- onClick={() => loadStage(name)}
- className={`w-full text-left px-3 py-2 rounded-lg text-sm transition-colors ${
+ className={`flex items-center justify-between px-3 py-2 rounded-lg text-sm ${
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>
+ <button
+ onClick={() => loadStage(name)}
+ className="flex-1 text-left"
+ >
+ <div className="font-medium">{config.name || name}</div>
+ <div className="text-xs text-gray-500 truncate">{config.description}</div>
+ </button>
+ <button
+ onClick={() => deleteStage(name)}
+ className="p-1 text-gray-500 hover:text-port-error"
+ title="Delete stage"
+ >
+ <Trash2 size={14} />
+ </button>
+ </div>
))}
</div>
</div>
@@ -366,6 +428,113 @@ export default function PromptManager() {
</div>
</div>
)}
+
+ {/* Create Stage Modal */}
+ {creatingStage && (
+ <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
+ <div className="bg-port-card border border-port-border rounded-xl p-6 max-w-2xl w-full max-h-[90vh] overflow-y-auto">
+ <div className="flex items-center justify-between mb-4">
+ <h3 className="text-lg font-medium text-white">Create New Stage</h3>
+ <button
+ onClick={() => setCreatingStage(false)}
+ className="text-gray-400 hover:text-white"
+ >
+ ✕
+ </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">Stage Key *</label>
+ <input
+ type="text"
+ value={newStageForm.stageName}
+ onChange={(e) => setNewStageForm({ ...newStageForm, stageName: e.target.value })}
+ placeholder="my-stage"
+ 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"
+ />
+ <p className="text-xs text-gray-500 mt-1">Lowercase, hyphens only</p>
+ </div>
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Display Name *</label>
+ <input
+ type="text"
+ value={newStageForm.name}
+ onChange={(e) => setNewStageForm({ ...newStageForm, name: e.target.value })}
+ placeholder="My Stage"
+ 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">Description</label>
+ <input
+ type="text"
+ value={newStageForm.description}
+ onChange={(e) => setNewStageForm({ ...newStageForm, description: e.target.value })}
+ placeholder="What this stage does"
+ 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 className="grid grid-cols-2 gap-4">
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Model</label>
+ <select
+ value={newStageForm.model}
+ onChange={(e) => setNewStageForm({ ...newStageForm, 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>
+ <option value="heavy">Heavy</option>
+ </select>
+ </div>
+ <div>
+ <label className="flex items-center gap-2 text-sm text-gray-400 mt-7">
+ <input
+ type="checkbox"
+ checked={newStageForm.returnsJson}
+ onChange={(e) => setNewStageForm({ ...newStageForm, returnsJson: e.target.checked })}
+ className="rounded"
+ />
+ Returns JSON
+ </label>
+ </div>
+ </div>
+
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Template</label>
+ <textarea
+ value={newStageForm.template}
+ onChange={(e) => setNewStageForm({ ...newStageForm, template: 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"
+ placeholder="Enter your prompt template here..."
+ />
+ </div>
+
+ <div className="flex gap-2 justify-end">
+ <button
+ onClick={() => setCreatingStage(false)}
+ className="px-4 py-2 text-gray-400 hover:text-white"
+ >
+ Cancel
+ </button>
+ <button
+ onClick={createStage}
+ disabled={saving || !newStageForm.stageName || !newStageForm.name}
+ className="flex items-center gap-1 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded disabled:opacity-50"
+ >
+ <Save size={14} /> Create Stage
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
</div>
);
}
diff --git a/data.sample/prompts/stage-config.json b/data.sample/prompts/stage-config.json
index 77674bf96c..e28c017430 100644
--- a/data.sample/prompts/stage-config.json
+++ b/data.sample/prompts/stage-config.json
@@ -7,20 +7,6 @@
"returnsJson": true,
"variables": ["jsonOutputFormat", "appDetectionSchema", "portDetectionRules", "pm2NamingConvention"]
},
- "code-analysis": {
- "name": "Code Analysis",
- "description": "Analyze code structure and suggest improvements",
- "model": "default",
- "returnsJson": false,
- "variables": []
- },
- "command-suggestion": {
- "name": "Command Suggestion",
- "description": "Suggest CLI commands based on context",
- "model": "quick",
- "returnsJson": false,
- "variables": []
- },
"cos-agent-briefing": {
"name": "CoS Agent Briefing",
"description": "Brief a sub-agent on their assigned task",
diff --git a/packages/ai-toolkit/src/server/index.d.ts b/packages/ai-toolkit/src/server/index.d.ts
index 16898c285f..d876ba0f55 100644
--- a/packages/ai-toolkit/src/server/index.d.ts
+++ b/packages/ai-toolkit/src/server/index.d.ts
@@ -35,6 +35,8 @@ export interface PromptsService {
getStageTemplate(name: string): Promise<string | null>;
updateStageTemplate(name: string, content: string): Promise<void>;
updateStageConfig(name: string, config: any): Promise<void>;
+ createStage(stageName: string, config: any, template?: string): Promise<void>;
+ deleteStage(stageName: string): Promise<void>;
getVariables(): Record<string, any>;
getVariable(key: string): any | null;
updateVariable(key: string, data: any): Promise<void>;
diff --git a/packages/ai-toolkit/src/server/prompts.js b/packages/ai-toolkit/src/server/prompts.js
index 908d2ac275..c8263f89c8 100644
--- a/packages/ai-toolkit/src/server/prompts.js
+++ b/packages/ai-toolkit/src/server/prompts.js
@@ -121,6 +121,46 @@ export function createPromptsService(config = {}) {
await writeFile(join(PROMPTS_PATH, 'stage-config.json'), JSON.stringify(stageConfig, null, 2));
},
+ /**
+ * Create a new stage
+ */
+ async createStage(stageName, config, template = '') {
+ if (!stageConfig) await loadPrompts();
+ if (stageConfig.stages[stageName]) {
+ throw new Error(`Stage ${stageName} already exists`);
+ }
+ stageConfig.stages[stageName] = config;
+ await writeFile(join(PROMPTS_PATH, 'stage-config.json'), JSON.stringify(stageConfig, null, 2));
+
+ // Create template file
+ const stagesDir = join(PROMPTS_PATH, 'stages');
+ if (!existsSync(stagesDir)) await mkdir(stagesDir, { recursive: true });
+ await writeFile(join(stagesDir, `${stageName}.md`), template);
+
+ console.log(`✅ Created prompt stage: ${stageName}`);
+ },
+
+ /**
+ * Delete a stage
+ */
+ async deleteStage(stageName) {
+ if (!stageConfig) await loadPrompts();
+ if (!stageConfig.stages[stageName]) {
+ throw new Error(`Stage ${stageName} not found`);
+ }
+ delete stageConfig.stages[stageName];
+ await writeFile(join(PROMPTS_PATH, 'stage-config.json'), JSON.stringify(stageConfig, null, 2));
+
+ // Delete template file if it exists
+ const templatePath = join(PROMPTS_PATH, 'stages', `${stageName}.md`);
+ if (existsSync(templatePath)) {
+ const { unlink } = await import('fs/promises');
+ await unlink(templatePath);
+ }
+
+ console.log(`🗑️ Deleted prompt stage: ${stageName}`);
+ },
+
/**
* Get all variables
*/
diff --git a/server/index.js b/server/index.js
index 98fe6d902f..591b68b0fb 100644
--- a/server/index.js
+++ b/server/index.js
@@ -36,6 +36,7 @@ import './services/subAgentSpawner.js'; // Initialize CoS agent spawner
import { createAIToolkit } from '@portos/ai-toolkit/server';
import { createPortOSProviderRoutes } from './routes/providers.js';
import { createPortOSRunsRoutes } from './routes/runs.js';
+import { createPortOSPromptsRoutes } from './routes/prompts.js';
import { setAIToolkit as setProvidersToolkit } from './services/providers.js';
import { setAIToolkit as setRunnerToolkit } from './services/runner.js';
import { setAIToolkit as setPromptsToolkit } from './services/promptService.js';
@@ -112,6 +113,11 @@ setProvidersToolkit(aiToolkit);
setRunnerToolkit(aiToolkit);
setPromptsToolkit(aiToolkit);
+// Initialize prompts service to load stage configurations
+aiToolkit.services.prompts.init().catch(err => {
+ console.error(`❌ Failed to initialize prompts: ${err.message}`);
+});
+
// Initialize auto-fixer for error recovery
initAutoFixer();
@@ -141,7 +147,7 @@ app.use('/api', scaffoldRoutes); // Also mount at /api for /api/templates
// AI Toolkit routes with PortOS extensions
app.use('/api/providers', createPortOSProviderRoutes(aiToolkit));
app.use('/api/runs', createPortOSRunsRoutes(aiToolkit));
-app.use('/api/prompts', aiToolkit.routes.prompts);
+app.use('/api/prompts', createPortOSPromptsRoutes(aiToolkit));
app.use('/api/history', historyRoutes);
app.use('/api/commands', commandsRoutes);
diff --git a/server/routes/prompts.js b/server/routes/prompts.js
new file mode 100644
index 0000000000..3cbc2945a3
--- /dev/null
+++ b/server/routes/prompts.js
@@ -0,0 +1,110 @@
+import { Router } from 'express';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+
+/**
+ * Create PortOS-specific prompts routes
+ * Wraps toolkit routes to match PortOS API contract
+ */
+export function createPortOSPromptsRoutes(aiToolkit) {
+ const router = Router();
+ const promptsService = aiToolkit.services.prompts;
+
+ // GET /api/prompts - List all stages (wrapped in {stages: ...})
+ router.get('/', asyncHandler(async (req, res) => {
+ const stages = promptsService.getStages();
+ res.json({ stages });
+ }));
+
+ // GET /api/prompts/variables - List all variables (wrapped in {variables: ...})
+ router.get('/variables', asyncHandler(async (req, res) => {
+ const variables = promptsService.getVariables();
+ res.json({ variables });
+ }));
+
+ // GET /api/prompts/variables/:key - Get a variable
+ router.get('/variables/:key', asyncHandler(async (req, res) => {
+ const variable = promptsService.getVariable(req.params.key);
+ if (!variable) {
+ throw new ServerError('Variable not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json({ key: req.params.key, ...variable });
+ }));
+
+ // POST /api/prompts/variables - Create a variable
+ router.post('/variables', asyncHandler(async (req, res) => {
+ const { key, name, category, content } = req.body;
+ if (!key || !content) {
+ throw new ServerError('key and content are required', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ await promptsService.createVariable(key, { name, category, content });
+ res.json({ success: true, key });
+ }));
+
+ // PUT /api/prompts/variables/:key - Update a variable
+ router.put('/variables/:key', asyncHandler(async (req, res) => {
+ const { name, category, content } = req.body;
+ await promptsService.updateVariable(req.params.key, { name, category, content });
+ res.json({ success: true });
+ }));
+
+ // DELETE /api/prompts/variables/:key - Delete a variable
+ router.delete('/variables/:key', asyncHandler(async (req, res) => {
+ await promptsService.deleteVariable(req.params.key);
+ res.json({ success: true });
+ }));
+
+ // GET /api/prompts/:stage - Get stage with template
+ router.get('/:stage', asyncHandler(async (req, res) => {
+ const stage = promptsService.getStage(req.params.stage);
+ if (!stage) {
+ throw new ServerError('Stage not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ const template = await promptsService.getStageTemplate(req.params.stage);
+ res.json({ ...stage, template });
+ }));
+
+ // POST /api/prompts - Create a new stage
+ router.post('/', asyncHandler(async (req, res) => {
+ const { stageName, name, description, model = 'default', returnsJson = false, variables = [], template = '' } = req.body;
+ if (!stageName || !name) {
+ throw new ServerError('stageName and name are required', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ const config = { name, description, model, returnsJson, variables };
+ await promptsService.createStage(stageName, config, template);
+ res.json({ success: true, stageName });
+ }));
+
+ // PUT /api/prompts/:stage - Update stage config and/or template
+ router.put('/:stage', asyncHandler(async (req, res) => {
+ const { template, ...config } = req.body;
+
+ if (Object.keys(config).length > 0) {
+ await promptsService.updateStageConfig(req.params.stage, config);
+ }
+ if (template !== undefined) {
+ await promptsService.updateStageTemplate(req.params.stage, template);
+ }
+ res.json({ success: true });
+ }));
+
+ // DELETE /api/prompts/:stage - Delete a stage
+ router.delete('/:stage', asyncHandler(async (req, res) => {
+ await promptsService.deleteStage(req.params.stage);
+ res.json({ success: true });
+ }));
+
+ // POST /api/prompts/:stage/preview - Preview compiled prompt
+ router.post('/:stage/preview', asyncHandler(async (req, res) => {
+ const { testData = {} } = req.body;
+ const preview = await promptsService.previewPrompt(req.params.stage, testData);
+ res.json({ preview });
+ }));
+
+ // POST /api/prompts/reload - Reload prompts from disk
+ router.post('/reload', asyncHandler(async (req, res) => {
+ await promptsService.init();
+ res.json({ success: true });
+ }));
+
+ return router;
+}