Skip to content

Self-improving AI Employees for everyone

fix(skills): make custom Master Skill creation work end-to-end

trohitgb9be6f7eab6d
diff --git a/CLAUDE.md b/CLAUDE.md
index 922edb0a..cff0e490 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -834,8 +834,8 @@ Skill nodes display an Ant Design `Input.TextArea` (markdown content) to view an
| File | Description |
|------|-------------|
| `client/src/hooks/useParameterPanel.ts` | Loads/saves skill content for skill nodes |
-| `server/services/skill_loader.py` | SkillLoader for filesystem and database skills |
-| `server/routers/websocket.py` | `get_skill_content`, `save_skill_content`, `list_skill_folders`, `scan_skill_folder` handlers |
+| `server/services/skill_loader.py` | SkillLoader for filesystem and database skills (DB-wired via `get_skill_loader()`) |
+| `server/services/skills/handlers.py` | `get_skill_content`, `save_skill_content`, `list_skill_folders`, `scan_skill_folder` handlers |
#### Master Skill Editor
The Master Skill node uses a custom split-panel editor (`MasterSkillEditor.tsx`) instead of standard parameters:
@@ -889,7 +889,9 @@ interface MasterSkillConfig {
- No frontend cleanup of stale skills is performed to avoid race conditions with async skill loading.
**Custom Skill Creation:**
-- The `create_user_skill` WebSocket handler requires `name`, `display_name`, and `instructions`. The `description` field is optional (defaults to empty string).
+- The `create_user_skill` WebSocket handler requires `name`, `display_name`, and `instructions`. The `description` field is optional (defaults to empty string). Skill handlers live in `server/services/skills/handlers.py` (self-registered via `services.ws_handler_registry`).
+- On create, `MasterSkillEditor` persists the updated `skills_config` to the node via `save_node_parameters` (mirroring the delete path) so the new skill's enabled state survives panel close / reload, then `invalidateUserSkills()` + the `skill_lifecycle` broadcast refresh the list.
+- User skills are stored in the database and resolve through the database-wired `get_skill_loader().load_skill_async()` (so `get_skill_content` returns their instructions the same way it does for built-in skills).
**Backend Expansion:**
When AI Agent executes with a connected Master Skill node, `_collect_agent_connections()` in `handlers/ai.py` expands the skillsConfig into individual skill entries:
@@ -913,7 +915,7 @@ if skill_type == 'masterSkill':
| File | Description |
|------|-------------|
| `client/src/components/parameterPanel/MasterSkillEditor.tsx` | Split-panel skill aggregator UI with inline user skill CRUD |
-| `server/routers/websocket.py` | User skill CRUD: `get_user_skills`, `create_user_skill`, `update_user_skill`, `delete_user_skill` |
+| `server/services/skills/handlers.py` | User skill CRUD: `get_user_skills`, `create_user_skill`, `update_user_skill`, `delete_user_skill` |
| `server/core/database.py` | UserSkill model and database CRUD methods |
| `server/services/handlers/ai.py` | Expands masterSkill into individual skills at execution |
| `server/skills/GUIDE.md` | Skill creation guide for built-in skills |
diff --git a/client/src/components/parameterPanel/MasterSkillEditor.tsx b/client/src/components/parameterPanel/MasterSkillEditor.tsx
index a0b1f520..1be0a015 100644
--- a/client/src/components/parameterPanel/MasterSkillEditor.tsx
+++ b/client/src/components/parameterPanel/MasterSkillEditor.tsx
@@ -97,6 +97,16 @@ interface PendingSkillData {
color: string;
}
+// Stable empty-array references. `query.data ?? []` mints a NEW array
+// identity every render, and the folder query is disabled (so `data`
+// stays undefined) whenever the node's `skillFolder` is unset. Without
+// a stable fallback the `availableSkills` memo recomputes on every
+// render, and the "load selected user skill" effect setStates in an
+// unbounded loop -> "Maximum update depth exceeded" -> the ErrorBoundary
+// tears down the React Flow canvas.
+const EMPTY_USER_SKILLS: UserSkill[] = [];
+const EMPTY_FOLDER_SKILLS: AvailableSkill[] = [];
+
interface MasterSkillEditorProps {
skillsConfig: MasterSkillConfig;
onConfigChange: (config: MasterSkillConfig) => void;
@@ -123,6 +133,10 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({
const [isLoading, setIsLoading] = useState(false);
const [searchQuery, setSearchQuery] = useState('');
const editorWrapperRef = useRef<HTMLDivElement>(null);
+ // Tracks which skill's data has been loaded into the edit buffer so
+ // the load effect below fires once per selection instead of on every
+ // background list refetch (avoids the render loop + clobbering edits).
+ const initializedSkillRef = useRef<string | null>(null);
const queryClient = useQueryClient();
const userSkillsQuery = useQuery<UserSkill[], Error>({
@@ -136,7 +150,7 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({
},
staleTime: 60_000,
});
- const userSkills = userSkillsQuery.data ?? [];
+ const userSkills = userSkillsQuery.data ?? EMPTY_USER_SKILLS;
const invalidateUserSkills = useCallback(
() => queryClient.invalidateQueries({ queryKey: ['userSkills'] }),
[queryClient],
@@ -168,7 +182,7 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({
const foldersLoaded = !foldersQuery.isLoading;
const folderSkillsQuery = useFolderSkills(skillFolder);
- const folderSkills = folderSkillsQuery.data ?? [];
+ const folderSkills = folderSkillsQuery.data ?? EMPTY_FOLDER_SKILLS;
const folderLoading = folderSkillsQuery.isLoading;
// Inline editing state (no modal)
@@ -302,30 +316,39 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({
}
}, [availableSkills, queryClient, sendRequest, getCachedSkillContent]);
- // When selecting a user skill, load its data into pendingSkillData for editing
+ // When selecting a user skill, load its data into pendingSkillData for editing.
+ // Guarded by initializedSkillRef so it runs ONCE per selection -- re-running on
+ // every availableSkills/userSkills refetch would (a) clobber in-progress edits
+ // and (b) drive an infinite setState loop (setPendingSkillData with a fresh
+ // object every render). The ref is only advanced once the skill's data is
+ // actually present, so a selection made before its data loads still resolves.
useEffect(() => {
if (isCreatingNew || !selectedSkillName) {
+ initializedSkillRef.current = null;
return;
}
+ if (initializedSkillRef.current === selectedSkillName) return;
const selectedInfo = availableSkills.find(s => s.skillName === selectedSkillName);
- if (selectedInfo?.isUserSkill) {
+ if (!selectedInfo) return; // not in the list yet -- retry when it loads
+
+ if (selectedInfo.isUserSkill) {
const userSkill = userSkills.find(us => us.name === selectedSkillName);
- if (userSkill) {
- setPendingSkillData({
- name: userSkill.name,
- display_name: userSkill.display_name,
- description: userSkill.description,
- instructions: userSkill.instructions,
- icon: userSkill.icon || '',
- color: userSkill.color || '#6366F1'
- });
- setHasUnsavedChanges(false);
- }
+ if (!userSkill) return; // user-skill data not loaded yet -- retry
+ setPendingSkillData({
+ name: userSkill.name,
+ display_name: userSkill.display_name,
+ description: userSkill.description,
+ instructions: userSkill.instructions,
+ icon: userSkill.icon || '',
+ color: userSkill.color || '#6366F1'
+ });
+ setHasUnsavedChanges(false);
} else {
setPendingSkillData(null);
setHasUnsavedChanges(false);
}
+ initializedSkillRef.current = selectedSkillName;
}, [selectedSkillName, isCreatingNew, availableSkills, userSkills]);
// Toggle skill enabled/disabled
@@ -459,11 +482,22 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({
await invalidateUserSkills();
if (isCreatingNew) {
- // Add to config as enabled
- onConfigChange({
+ // Add to config as enabled, then persist to the database so the
+ // new skill survives panel close / reload -- mirrors
+ // handleDeleteSkill. Without the save_node_parameters call the
+ // enabled state lives only in React state and is lost unless the
+ // user also clicks the panel-level Save.
+ const newConfig = {
...skillsConfig,
[skillName]: { enabled: true, instructions: pendingSkillData.instructions, isCustomized: false }
- });
+ };
+ onConfigChange(newConfig);
+ if (nodeId) {
+ await sendRequest('save_node_parameters', {
+ node_id: nodeId,
+ parameters: { skills_config: newConfig, skillFolder: skillFolder || 'assistant' }
+ });
+ }
setIsCreatingNew(false);
setSelectedSkillName(skillName);
}
@@ -476,7 +510,7 @@ const MasterSkillEditor: React.FC<MasterSkillEditorProps> = ({
} finally {
setSavingSkill(false);
}
- }, [pendingSkillData, isCreatingNew, skillFolder, sendRequest, invalidateUserSkills, skillsConfig, onConfigChange]);
+ }, [pendingSkillData, isCreatingNew, skillFolder, sendRequest, invalidateUserSkills, skillsConfig, onConfigChange, nodeId]);
// Delete user skill
const handleDeleteSkill = useCallback(async (skillName: string) => {
diff --git a/docs-internal/agent_architecture.md b/docs-internal/agent_architecture.md
index 9682c93b..e413f747 100644
--- a/docs-internal/agent_architecture.md
+++ b/docs-internal/agent_architecture.md
@@ -228,11 +228,13 @@ Defined in `server/services/skill_loader.py:38+`:
```
SkillLoader
├── _skill_dirs: [server/skills/, .machina/skills/]
+├── _database # DI database singleton (user skills live in the DB)
├── _registry: Dict[name -> SkillMetadata] # Metadata only (~100 tokens each)
├── _cache: Dict[name -> Skill] # Full content (lazy-loaded)
│
├── scan_skills() # rglob("SKILL.md") across all dirs, parses frontmatter
-├── load_skill(name) # Loads full content: cache -> registry -> filesystem
+├── load_skill(name) # Filesystem skills: cache -> registry -> SKILL.md
+├── load_skill_async(name) # DB-aware: filesystem first, then database.get_user_skill()
├── get_registry_prompt() # Generates "## Available Skills" for system message
└── get_skill_instructions()# Shortcut for load_skill().instructions
```
@@ -249,6 +251,10 @@ SkillLoader
4. Load optional `scripts/` and `references/` directories
5. Cache and return `Skill` dataclass
+**`get_skill_loader()` is database-wired** (`skill_loader.py`):
+- The global loader is constructed with the DI `container.database()` (resolved lazily, late-bound on a subsequent call if the container was not yet ready when the loader was first requested). User-created skills are stored in the database rather than on disk, so the wired DB is what lets them resolve.
+- `load_skill_async(name)` is the DB-aware loader: filesystem `_registry` first, then `database.get_user_skill(name)`. The `get_skill_content` WebSocket handler and the agent skill paths call it, so database user skills load just like filesystem skills. `init_skill_loader(database=...)` remains available for explicit eager initialization.
+
**SKILL.md frontmatter parsing** (`skill_loader.py:126-172`):
```yaml
---
diff --git a/server/services/skill_loader.py b/server/services/skill_loader.py
index 0755ce6d..a2292d07 100644
--- a/server/services/skill_loader.py
+++ b/server/services/skill_loader.py
@@ -414,8 +414,26 @@ class SkillLoader:
_skill_loader: Optional[SkillLoader] = None
+def _resolve_database():
+ """Best-effort fetch of the DI database singleton (None if unavailable)."""
+ try:
+ from core.container import container
+
+ return container.database()
+ except Exception: # container not wired yet (very early call)
+ return None
+
+
def get_skill_loader() -> SkillLoader:
- """Get the global skill loader instance."""
+ """Get the global skill loader instance.
+
+ The loader is wired with the database so ``load_skill_async`` can
+ resolve user-created skills (stored in the DB, not on disk). The DB
+ is late-bound if the loader happened to be created before the DI
+ container was ready -- otherwise a skill created via the Master
+ Skill editor stays invisible to ``get_skill_content`` and every
+ agent path, and the editor reports "Skill '<name>' not found".
+ """
global _skill_loader
if _skill_loader is None:
# Default directories
@@ -424,8 +442,12 @@ def get_skill_loader() -> SkillLoader:
server_dir / "skills", # Built-in skills
Path.cwd() / ".machina" / "skills", # Project skills
]
- _skill_loader = SkillLoader(skill_dirs=skill_dirs)
+ _skill_loader = SkillLoader(skill_dirs=skill_dirs, database=_resolve_database())
_skill_loader.scan_skills()
+ elif _skill_loader._database is None:
+ # Created before the container was wired -- bind the DB now so
+ # user-skill lookups stop failing.
+ _skill_loader._database = _resolve_database()
return _skill_loader