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(cos): add sidebar sub-navigation and mobile UX improvements

Adam Eivydf49d6233ad6
diff --git a/.changelog/v0.10.x.md b/.changelog/v0.10.x.md
index 1a593dda3d..ac97ef5521 100644
--- a/.changelog/v0.10.x.md
+++ b/.changelog/v0.10.x.md
@@ -142,12 +142,15 @@ This release introduces a structured changelog documentation system for creating
### CoS Task Prompt Enhancement
- **AI-Powered Prompt Enhancement**: New "Enhance with AI" checkbox in the Add Task form that uses AI to expand brief task descriptions into comprehensive, detailed prompts
- **Actionable Prompts**: Enhanced prompts include specific steps, relevant context, success criteria, and edge cases to watch for
-- **Provider Flexibility**: Uses OpenAI Codex by default for enhancement, with fallback to the active provider if OpenAI is unavailable
+- **Prompt Stage Configuration**: Enhancement now uses the `cos-task-enhance` prompt stage for provider/model selection - configure via Prompt Manager instead of hardcoded defaults
- **Visual Feedback**: Loading spinner and "Enhancing..." state during prompt processing, with clear success/error toasts
- **API Endpoint**: New `POST /api/cos/tasks/enhance` endpoint for programmatic access to prompt enhancement
## 🔧 Improvements
+### Prompt Manager UX
+- **Alphabetical Sorting**: Stages and variables lists are now sorted alphabetically for easier navigation in large prompt collections
+
### Release Process
- **Rich Release Descriptions**: GitHub releases now support detailed, categorized changelogs
- **Flexible Workflow**: Developers can choose between detailed changelogs or auto-generated commit logs
@@ -216,6 +219,9 @@ This release introduces a structured changelog documentation system for creating
- **Impact**: Resume context now correctly passes full multi-line instructions to agents, including previous agent output, error context, and user refinements
- **Test Coverage**: Added new round-trip test to verify multi-line metadata preservation through save/parse cycle
+### Brain Memory Delete Handler
+- **Fixed Delete Success Detection**: The MemoryTab delete handler was checking `result !== null` to determine success, but successful API responses might not return a value. Changed to track failures explicitly with a boolean flag, fixing false-positive "Deleted" toasts when delete operations failed
+
### Critical: Fixed "Unexpected end of JSON input" Errors
- **Safe JSON Parsing**: Added comprehensive JSON parsing utilities to `server/lib/fileUtils.js`:
- `isValidJSON(str)` - Pre-validates JSON structure before parsing (supports both objects and arrays)
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 3b605c080e..36e541375f 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -23,7 +23,11 @@ import {
Camera,
Brain,
Heart,
- Fingerprint
+ Fingerprint,
+ Clock,
+ Calendar,
+ GraduationCap,
+ Settings
} from 'lucide-react';
import packageJson from '../../package.json';
import Logo from './Logo';
@@ -44,7 +48,22 @@ const navItems = [
},
{ to: '/apps', label: 'Apps', icon: Package, single: true },
{ href: '//:5560', label: 'Autofixer', icon: Wrench, external: true, dynamicHost: true },
- { to: '/cos', label: 'Chief of Staff', icon: Crown, single: true, showBadge: true },
+ {
+ label: 'Chief of Staff',
+ icon: Crown,
+ showBadge: true,
+ children: [
+ { to: '/cos/tasks', label: 'Tasks', icon: FileText },
+ { to: '/cos/agents', label: 'Agents', icon: Cpu },
+ { to: '/cos/scripts', label: 'Scripts', icon: Terminal },
+ { to: '/cos/schedule', label: 'Schedule', icon: Clock },
+ { to: '/cos/digest', label: 'Digest', icon: Calendar },
+ { to: '/cos/learning', label: 'Learning', icon: GraduationCap },
+ { to: '/cos/memory', label: 'Memory', icon: Brain },
+ { to: '/cos/health', label: 'Health', icon: Activity },
+ { to: '/cos/config', label: 'Config', icon: Settings }
+ ]
+ },
{
label: 'Identity',
icon: Fingerprint,
@@ -241,16 +260,32 @@ export default function Layout() {
title={collapsed ? item.label : undefined}
>
<div className="flex items-center gap-3">
- <Icon size={20} className="flex-shrink-0" />
+ <div className="relative">
+ <Icon size={20} className="flex-shrink-0" />
+ {/* Badge for collapsed state on collapsible sections */}
+ {item.showBadge && unreadCount > 0 && collapsed && (
+ <span className="absolute -top-1.5 -right-1.5 min-w-[14px] h-[14px] flex items-center justify-center text-[9px] font-bold rounded-full bg-yellow-500 text-black px-0.5">
+ {unreadCount > 9 ? '9+' : unreadCount}
+ </span>
+ )}
+ </div>
<span className={`whitespace-nowrap ${collapsed ? 'lg:hidden' : ''}`}>
{item.label}
</span>
</div>
- {!collapsed && (
- expandedSections[item.label]
- ? <ChevronDown size={16} />
- : <ChevronRight size={16} />
- )}
+ <div className="flex items-center gap-2">
+ {/* Badge for expanded state on collapsible sections */}
+ {item.showBadge && unreadCount > 0 && !collapsed && (
+ <span className="min-w-[18px] h-[18px] flex items-center justify-center text-[10px] font-bold rounded-full bg-yellow-500 text-black px-1">
+ {unreadCount > 9 ? '9+' : unreadCount}
+ </span>
+ )}
+ {!collapsed && (
+ expandedSections[item.label]
+ ? <ChevronDown size={16} />
+ : <ChevronRight size={16} />
+ )}
+ </div>
</button>
{/* Children items */}
diff --git a/client/src/components/brain/tabs/MemoryTab.jsx b/client/src/components/brain/tabs/MemoryTab.jsx
index 596ae4fc8a..f9ea384cc0 100644
--- a/client/src/components/brain/tabs/MemoryTab.jsx
+++ b/client/src/components/brain/tabs/MemoryTab.jsx
@@ -138,35 +138,35 @@ export default function MemoryTab({ onRefresh }) {
};
const handleDelete = async (id) => {
- let result;
+ let failed = false;
switch (activeType) {
case 'people':
- result = await api.deleteBrainPerson(id).catch(err => {
+ await api.deleteBrainPerson(id).catch(err => {
toast.error(err.message);
- return null;
+ failed = true;
});
break;
case 'projects':
- result = await api.deleteBrainProject(id).catch(err => {
+ await api.deleteBrainProject(id).catch(err => {
toast.error(err.message);
- return null;
+ failed = true;
});
break;
case 'ideas':
- result = await api.deleteBrainIdea(id).catch(err => {
+ await api.deleteBrainIdea(id).catch(err => {
toast.error(err.message);
- return null;
+ failed = true;
});
break;
case 'admin':
- result = await api.deleteBrainAdminItem(id).catch(err => {
+ await api.deleteBrainAdminItem(id).catch(err => {
toast.error(err.message);
- return null;
+ failed = true;
});
break;
}
- if (result !== null) {
+ if (!failed) {
toast.success('Deleted');
fetchRecords();
onRefresh?.();
diff --git a/client/src/components/cos/StateLabel.jsx b/client/src/components/cos/StateLabel.jsx
index 1bda939a33..64b34f2826 100644
--- a/client/src/components/cos/StateLabel.jsx
+++ b/client/src/components/cos/StateLabel.jsx
@@ -1,8 +1,23 @@
import { AGENT_STATES } from './constants';
-export default function StateLabel({ state }) {
+export default function StateLabel({ state, compact = false }) {
const stateConfig = AGENT_STATES[state] || AGENT_STATES.sleeping;
+ if (compact) {
+ return (
+ <div
+ className="flex items-center gap-1.5 px-2 py-1 rounded-full font-mono text-xs"
+ style={{
+ background: 'rgba(15, 23, 42, 0.8)',
+ border: `1px solid ${stateConfig.color}`
+ }}
+ >
+ <span className="text-sm">{stateConfig.icon}</span>
+ <span className="text-gray-100">{stateConfig.label}</span>
+ </div>
+ );
+ }
+
return (
<div
className="flex items-center gap-2 px-4 py-2 rounded-full mt-4 font-mono text-xs"
diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsx
index 6766881d35..6465c81b13 100644
--- a/client/src/pages/ChiefOfStaff.jsx
+++ b/client/src/pages/ChiefOfStaff.jsx
@@ -2,7 +2,7 @@ import { useState, useEffect, useCallback, useMemo } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useSocket } from '../hooks/useSocket';
import * as api from '../services/api';
-import { Play, Square, Clock, CheckCircle, AlertCircle, Cpu } from 'lucide-react';
+import { Play, Square, Clock, CheckCircle, AlertCircle, Cpu, ChevronDown, ChevronUp } from 'lucide-react';
import toast from 'react-hot-toast';
// Import from modular components
@@ -46,6 +46,7 @@ export default function ChiefOfStaff() {
const [statusMessage, setStatusMessage] = useState("Idle - waiting for tasks...");
const [liveOutputs, setLiveOutputs] = useState({});
const [eventLogs, setEventLogs] = useState([]);
+ const [agentPanelCollapsed, setAgentPanelCollapsed] = useState(false);
const socket = useSocket();
// Derive avatar style from server config
@@ -323,96 +324,129 @@ export default function ChiefOfStaff() {
evalCountdown={evalCountdown}
/>
) : (
- <div className="relative flex border-b lg:border-b-0 lg:border-r border-indigo-500/20 bg-gradient-to-b from-slate-900/80 to-slate-900/40 shrink-0 lg:h-full lg:overflow-y-auto scrollbar-hide">
- {/* Background Effects */}
- <div
- className="absolute inset-0 pointer-events-none"
- style={{
- background: `
- radial-gradient(circle at 50% 20%, rgba(99, 102, 241, 0.1) 0%, transparent 50%),
- repeating-linear-gradient(0deg, transparent, transparent 50px, rgba(99, 102, 241, 0.03) 50px, rgba(99, 102, 241, 0.03) 51px)
- `
- }}
- />
-
- {/* Avatar Column - half width on mobile, full on desktop */}
- <div className="flex-1 lg:flex-none flex flex-col items-center p-4 lg:p-8 relative z-10">
- <div className="hidden lg:block text-sm font-semibold tracking-widest uppercase text-slate-400 mb-1 font-mono">
- Digital Assistant
+ <div className="relative flex flex-col border-b lg:border-b-0 lg:border-r border-indigo-500/20 bg-gradient-to-b from-slate-900/80 to-slate-900/40 shrink-0 lg:h-full lg:overflow-y-auto scrollbar-hide">
+ {/* Mobile Collapse Toggle Header */}
+ <button
+ onClick={() => setAgentPanelCollapsed(!agentPanelCollapsed)}
+ className="lg:hidden flex items-center justify-between w-full px-4 py-3 bg-slate-900/60 border-b border-indigo-500/20 min-h-[44px]"
+ aria-expanded={!agentPanelCollapsed}
+ aria-controls="cos-agent-panel"
+ >
+ <div className="flex items-center gap-3">
+ <h1
+ className="text-lg font-bold"
+ style={{
+ background: 'linear-gradient(135deg, #6366f1, #8b5cf6, #06b6d4)',
+ WebkitBackgroundClip: 'text',
+ WebkitTextFillColor: 'transparent',
+ backgroundClip: 'text'
+ }}
+ >
+ Chief of Staff
+ </h1>
+ <StatusIndicator running={status?.running} />
</div>
- <h1
- className="text-lg sm:text-xl lg:text-3xl font-bold mb-2 lg:mb-8"
+ <div className="flex items-center gap-2 text-gray-400">
+ <StateLabel state={agentState} compact />
+ {agentPanelCollapsed ? <ChevronDown size={20} /> : <ChevronUp size={20} />}
+ </div>
+ </button>
+
+ {/* Collapsible Content */}
+ <div
+ id="cos-agent-panel"
+ className={`${agentPanelCollapsed ? 'hidden' : 'flex'} lg:flex flex-1`}
+ >
+ {/* Background Effects */}
+ <div
+ className="absolute inset-0 pointer-events-none"
style={{
- background: 'linear-gradient(135deg, #6366f1, #8b5cf6, #06b6d4)',
- WebkitBackgroundClip: 'text',
- WebkitTextFillColor: 'transparent',
- backgroundClip: 'text'
+ background: `
+ radial-gradient(circle at 50% 20%, rgba(99, 102, 241, 0.1) 0%, transparent 50%),
+ repeating-linear-gradient(0deg, transparent, transparent 50px, rgba(99, 102, 241, 0.03) 50px, rgba(99, 102, 241, 0.03) 51px)
+ `
}}
- >
- Chief of Staff
- </h1>
-
- <CoSCharacter state={agentState} speaking={speaking} />
- <StateLabel state={agentState} />
- <div className="hidden sm:block">
- <StatusBubble message={statusMessage} countdown={evalCountdown} />
- </div>
- <div className="hidden lg:block">
- {status?.running && <EventLog logs={eventLogs} />}
- </div>
+ />
- {/* Control Buttons */}
- <div className="flex items-center gap-2 sm:gap-3 mt-3 lg:mt-6">
- {status?.running ? (
- <button
- onClick={handleStop}
- className="flex items-center gap-1 sm:gap-2 px-2 sm:px-4 py-1.5 sm:py-2 text-sm sm:text-base bg-red-500/20 hover:bg-red-500/30 text-red-400 rounded-lg transition-colors"
- aria-label="Stop Chief of Staff agent"
- >
- <Square size={14} className="sm:w-4 sm:h-4" aria-hidden="true" />
- Stop
- </button>
- ) : (
- <button
- onClick={handleStart}
- className="flex items-center gap-1 sm:gap-2 px-2 sm:px-4 py-1.5 sm:py-2 text-sm sm:text-base bg-emerald-500/20 hover:bg-emerald-500/30 text-emerald-400 rounded-lg transition-colors"
- aria-label="Start Chief of Staff agent"
- >
- <Play size={14} className="sm:w-4 sm:h-4" aria-hidden="true" />
- Start
- </button>
- )}
- <StatusIndicator running={status?.running} />
+ {/* Avatar Column - half width on mobile, full on desktop */}
+ <div className="flex-1 lg:flex-none flex flex-col items-center p-4 lg:p-8 relative z-10">
+ <div className="hidden lg:block text-sm font-semibold tracking-widest uppercase text-slate-400 mb-1 font-mono">
+ Digital Assistant
+ </div>
+ <h1
+ className="hidden lg:block text-lg sm:text-xl lg:text-3xl font-bold mb-2 lg:mb-8"
+ style={{
+ background: 'linear-gradient(135deg, #6366f1, #8b5cf6, #06b6d4)',
+ WebkitBackgroundClip: 'text',
+ WebkitTextFillColor: 'transparent',
+ backgroundClip: 'text'
+ }}
+ >
+ Chief of Staff
+ </h1>
+
+ <CoSCharacter state={agentState} speaking={speaking} />
+ <StateLabel state={agentState} />
+ <div className="hidden sm:block">
+ <StatusBubble message={statusMessage} countdown={evalCountdown} />
+ </div>
+ <div className="hidden lg:block">
+ {status?.running && <EventLog logs={eventLogs} />}
+ </div>
+
+ {/* Control Buttons */}
+ <div className="flex items-center gap-2 sm:gap-3 mt-3 lg:mt-6">
+ {status?.running ? (
+ <button
+ onClick={handleStop}
+ className="flex items-center gap-1 sm:gap-2 px-2 sm:px-4 py-1.5 sm:py-2 text-sm sm:text-base bg-red-500/20 hover:bg-red-500/30 text-red-400 rounded-lg transition-colors min-h-[40px]"
+ aria-label="Stop Chief of Staff agent"
+ >
+ <Square size={14} className="sm:w-4 sm:h-4" aria-hidden="true" />
+ Stop
+ </button>
+ ) : (
+ <button
+ onClick={handleStart}
+ className="flex items-center gap-1 sm:gap-2 px-2 sm:px-4 py-1.5 sm:py-2 text-sm sm:text-base bg-emerald-500/20 hover:bg-emerald-500/30 text-emerald-400 rounded-lg transition-colors min-h-[40px]"
+ aria-label="Start Chief of Staff agent"
+ >
+ <Play size={14} className="sm:w-4 sm:h-4" aria-hidden="true" />
+ Start
+ </button>
+ )}
+ <StatusIndicator running={status?.running} />
+ </div>
</div>
- </div>
- {/* Mobile Stats Column - only visible on mobile */}
- <div className="flex-1 flex flex-col justify-center gap-2 p-3 lg:hidden relative z-10">
- <StatCard
- label="Active"
- value={activeAgentCount}
- icon={<Cpu className="w-4 h-4 text-port-accent" />}
- active={activeAgentCount > 0}
- compact
- />
- <StatCard
- label="Pending"
- value={pendingTaskCount}
- icon={<Clock className="w-4 h-4 text-yellow-500" />}
- compact
- />
- <StatCard
- label="Done"
- value={status?.stats?.tasksCompleted || 0}
- icon={<CheckCircle className="w-4 h-4 text-port-success" />}
- compact
- />
- <StatCard
- label="Issues"
- value={health?.issues?.length || 0}
- icon={<AlertCircle className={`w-4 h-4 ${hasIssues ? 'text-port-error' : 'text-gray-500'}`} />}
- compact
- />
+ {/* Mobile Stats Column - only visible on mobile */}
+ <div className="flex-1 flex flex-col justify-center gap-2 p-3 lg:hidden relative z-10">
+ <StatCard
+ label="Active"
+ value={activeAgentCount}
+ icon={<Cpu className="w-4 h-4 text-port-accent" />}
+ active={activeAgentCount > 0}
+ compact
+ />
+ <StatCard
+ label="Pending"
+ value={pendingTaskCount}
+ icon={<Clock className="w-4 h-4 text-yellow-500" />}
+ compact
+ />
+ <StatCard
+ label="Done"
+ value={status?.stats?.tasksCompleted || 0}
+ icon={<CheckCircle className="w-4 h-4 text-port-success" />}
+ compact
+ />
+ <StatCard
+ label="Issues"
+ value={health?.issues?.length || 0}
+ icon={<AlertCircle className={`w-4 h-4 ${hasIssues ? 'text-port-error' : 'text-gray-500'}`} />}
+ compact
+ />
+ </div>
</div>
</div>
)}
@@ -449,8 +483,8 @@ export default function ChiefOfStaff() {
/>
</div>
- {/* Tabs */}
- <div role="tablist" aria-label="Chief of Staff sections" className="flex gap-1 mb-6 border-b border-port-border overflow-x-auto scrollbar-hide">
+ {/* Tabs - scrollable on mobile with touch-friendly sizing */}
+ <div role="tablist" aria-label="Chief of Staff sections" className="flex gap-1 mb-4 lg:mb-6 border-b border-port-border overflow-x-auto scrollbar-hide pb-px">
{TABS.map(tabItem => {
const Icon = tabItem.icon;
const isSelected = activeTab === tabItem.id;
@@ -462,7 +496,7 @@ export default function ChiefOfStaff() {
aria-controls={`tabpanel-${tabItem.id}`}
id={`tab-${tabItem.id}`}
onClick={() => navigate(`/cos/${tabItem.id}`)}
- className={`flex items-center gap-2 px-3 sm:px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px whitespace-nowrap ${
+ className={`flex items-center justify-center gap-1.5 sm:gap-2 px-2.5 sm:px-4 min-h-[40px] text-sm font-medium transition-colors border-b-2 -mb-px whitespace-nowrap shrink-0 ${
isSelected
? 'text-port-accent border-port-accent'
: 'text-gray-500 border-transparent hover:text-white'
diff --git a/client/src/pages/PromptManager.jsx b/client/src/pages/PromptManager.jsx
index 0e80152217..2db745c2ee 100644
--- a/client/src/pages/PromptManager.jsx
+++ b/client/src/pages/PromptManager.jsx
@@ -10,7 +10,7 @@ export default function PromptManager() {
// System stages that are protected
const systemStages = [
'cos-agent-briefing', 'cos-evaluate', 'cos-report-summary', 'cos-self-improvement',
- 'brain-classifier', 'brain-daily-digest', 'brain-weekly-review',
+ 'cos-task-enhance', 'brain-classifier', 'brain-daily-digest', 'brain-weekly-review',
'memory-evaluate', 'app-detection'
];
@@ -238,7 +238,7 @@ export default function PromptManager() {
</button>
</div>
<div className="space-y-1">
- {Object.entries(stages).map(([name, config]) => (
+ {Object.entries(stages).sort(([a], [b]) => a.localeCompare(b)).map(([name, config]) => (
<div
key={name}
className={`flex items-center gap-2 px-3 py-2 rounded-lg text-sm ${
@@ -376,7 +376,7 @@ export default function PromptManager() {
</button>
</div>
<div className="space-y-1">
- {Object.entries(variables).map(([key, v]) => (
+ {Object.entries(variables).sort(([a], [b]) => a.localeCompare(b)).map(([key, v]) => (
<div
key={key}
className={`flex items-center justify-between px-3 py-2 rounded-lg text-sm ${
diff --git a/server/index.js b/server/index.js
index 3cdd5bd6ae..4def0cb174 100644
--- a/server/index.js
+++ b/server/index.js
@@ -26,6 +26,7 @@ import standardizeRoutes from './routes/standardize.js';
import brainRoutes from './routes/brain.js';
import mediaRoutes from './routes/media.js';
import digitalTwinRoutes from './routes/digital-twin.js';
+import lmstudioRoutes from './routes/lmstudio.js';
import { initSocket } from './services/socket.js';
import { initScriptRunner } from './services/scriptRunner.js';
import { errorMiddleware, setupProcessErrorHandlers, asyncHandler } from './lib/errorHandler.js';
@@ -164,6 +165,7 @@ app.use('/api/standardize', standardizeRoutes);
app.use('/api/brain', brainRoutes);
app.use('/api/media', mediaRoutes);
app.use('/api/digital-twin', digitalTwinRoutes);
+app.use('/api/lmstudio', lmstudioRoutes);
// Initialize script runner
initScriptRunner().catch(err => console.error(`❌ Script runner init failed: ${err.message}`));
diff --git a/server/routes/prompts.js b/server/routes/prompts.js
index 9a76e19457..2ae62e5278 100644
--- a/server/routes/prompts.js
+++ b/server/routes/prompts.js
@@ -97,6 +97,7 @@ export function createPortOSPromptsRoutes(aiToolkit) {
'cos-evaluate': ['CoS task evaluation'],
'cos-report-summary': ['CoS daily reports'],
'cos-self-improvement': ['CoS self-improvement tasks'],
+ 'cos-task-enhance': ['CoS task prompt enhancement'],
'brain-classifier': ['Brain thought classification'],
'brain-daily-digest': ['Brain daily digest generation'],
'brain-weekly-review': ['Brain weekly review generation'],
@@ -122,7 +123,7 @@ export function createPortOSPromptsRoutes(aiToolkit) {
// Check if it's a system stage
const systemStages = [
'cos-agent-briefing', 'cos-evaluate', 'cos-report-summary', 'cos-self-improvement',
- 'brain-classifier', 'brain-daily-digest', 'brain-weekly-review',
+ 'cos-task-enhance', 'brain-classifier', 'brain-daily-digest', 'brain-weekly-review',
'memory-evaluate', 'app-detection'
];
diff --git a/server/services/taskEnhancer.js b/server/services/taskEnhancer.js
index 126a4971b1..ec0d1c5b63 100644
--- a/server/services/taskEnhancer.js
+++ b/server/services/taskEnhancer.js
@@ -3,16 +3,20 @@
*
* Uses AI to enhance task descriptions/prompts to be more detailed,
* actionable, and comprehensive for agent execution.
+ *
+ * Uses the 'cos-task-enhance' prompt stage for provider/model configuration.
*/
import { executeApiRun, createRun } from './runner.js';
import { getActiveProvider, getProviderById } from './providers.js';
-import { getConfig } from './cos.js';
+import { getStage, buildPrompt } from './promptService.js';
+
+const STAGE_NAME = 'cos-task-enhance';
/**
- * Default enhancement prompt template
+ * Fallback enhancement prompt template (used if stage template not found)
*/
-const ENHANCEMENT_PROMPT = `You are a task prompt enhancer for an AI agent system. Your job is to take a brief task description and expand it into a comprehensive, detailed prompt that an AI coding agent can execute effectively.
+const FALLBACK_PROMPT = `You are a task prompt enhancer for an AI agent system. Your job is to take a brief task description and expand it into a comprehensive, detailed prompt that an AI coding agent can execute effectively.
## Guidelines
@@ -42,36 +46,42 @@ Provide an enhanced version of this task that an AI agent can execute. Output ON
export async function enhanceTaskPrompt(description, context = '') {
console.log(`✨ Enhancing task prompt: "${description.substring(0, 50)}..."`);
- // Get CoS config for default enhancement settings
- const config = await getConfig();
-
- // Determine provider and model to use
- // Priority: CoS config -> active provider default
- let provider = await getActiveProvider();
- let model = 'codex';
-
- // Use OpenAI for enhancement by default if available, otherwise fall back to active provider
- const openaiProvider = await getProviderById('openai').catch(() => null);
- if (openaiProvider?.enabled) {
- provider = openaiProvider;
- model = 'codex';
- } else if (provider) {
- // Fall back to active provider's default model
- model = provider.defaultModel || provider.models?.[0] || 'claude-sonnet-4-20250514';
+ // Get prompt stage configuration for cos-task-enhance
+ const stage = getStage(STAGE_NAME);
+
+ // Determine provider and model from stage config or fallback
+ let provider;
+ let model;
+
+ if (stage?.provider) {
+ // Use stage-configured provider
+ provider = await getProviderById(stage.provider).catch(() => null);
+ model = stage.model || provider?.defaultModel;
}
+ // Fallback to active provider if stage provider not available
if (!provider) {
- throw new Error('No AI provider available for enhancement');
+ provider = await getActiveProvider();
+ model = stage?.model || provider?.defaultModel || provider?.models?.[0];
}
- // Build the enhancement prompt
- const contextSection = context
- ? `## Additional Context\n${context}`
- : '';
+ if (!provider) {
+ throw new Error('No AI provider available for enhancement');
+ }
- const fullPrompt = ENHANCEMENT_PROMPT
- .replace('{description}', description)
- .replace('{contextSection}', contextSection);
+ // Build the enhancement prompt using stage template or fallback
+ let fullPrompt;
+ const templatePrompt = await buildPrompt(STAGE_NAME, { description, context }).catch(() => null);
+
+ if (templatePrompt) {
+ fullPrompt = templatePrompt;
+ } else {
+ // Fallback to hardcoded template
+ const contextSection = context ? `## Additional Context\n${context}` : '';
+ fullPrompt = FALLBACK_PROMPT
+ .replace('{description}', description)
+ .replace('{contextSection}', contextSection);
+ }
// Create a run for this enhancement
const { runId } = await createRun({