agent customzation almost working again

This commit is contained in:
Brian Madison
2025-12-13 17:50:33 +08:00
parent 25c79e3fe5
commit ce42d56fdd
17 changed files with 257 additions and 687 deletions

View File

@@ -9,6 +9,8 @@ const fs = require('node:fs');
const path = require('node:path');
const { processAgentYaml, extractInstallConfig, stripInstallConfig, getDefaultValues } = require('./template-engine');
const { escapeXml } = require('../../../lib/xml-utils');
const { ActivationBuilder } = require('../activation-builder');
const { AgentAnalyzer } = require('../agent-analyzer');
/**
* Build frontmatter for agent
@@ -30,137 +32,7 @@ You must fully embody this agent's persona and follow all activation instruction
`;
}
/**
* Build simple activation block for custom agents
* @param {Array} criticalActions - Agent-specific critical actions
* @param {Array} menuItems - Menu items to determine which handlers to include
* @param {string} deploymentType - 'ide' or 'web' - filters commands based on ide-only/web-only flags
* @returns {string} Activation XML
*/
function buildSimpleActivation(criticalActions = [], menuItems = [], deploymentType = 'ide') {
let activation = '<activation critical="MANDATORY">\n';
let stepNum = 1;
// Standard steps
activation += ` <step n="${stepNum++}">Load persona from this current agent file (already in context)</step>\n`;
activation += ` <step n="${stepNum++}">Load and read {project-root}/.bmad/core/config.yaml to get {user_name}, {communication_language}, {output_folder}</step>\n`;
activation += ` <step n="${stepNum++}">Remember: user's name is {user_name}</step>\n`;
// Agent-specific steps from critical_actions
for (const action of criticalActions) {
activation += ` <step n="${stepNum++}">${action}</step>\n`;
}
// Menu and interaction steps
activation += ` <step n="${stepNum++}">ALWAYS communicate in {communication_language}</step>\n`;
activation += ` <step n="${stepNum++}">Show greeting using {user_name} from config, communicate in {communication_language}, then display numbered list of
ALL menu items from menu section</step>\n`;
activation += ` <step n="${stepNum++}">STOP and WAIT for user input - do NOT execute menu items automatically - accept number or cmd trigger or fuzzy command
match</step>\n`;
activation += ` <step n="${stepNum++}">On user input: Number → execute menu item[n] | Text → case-insensitive substring match | Multiple matches → ask user
to clarify | No match → show "Not recognized"</step>\n`;
// Filter menu items based on deployment type
const filteredMenuItems = menuItems.filter((item) => {
// Skip web-only commands for IDE deployment
if (deploymentType === 'ide' && item['web-only'] === true) {
return false;
}
// Skip ide-only commands for web deployment
if (deploymentType === 'web' && item['ide-only'] === true) {
return false;
}
return true;
});
// Detect which handlers are actually used in the filtered menu
const usedHandlers = new Set();
for (const item of filteredMenuItems) {
if (item.action) usedHandlers.add('action');
if (item.workflow) usedHandlers.add('workflow');
if (item.exec) usedHandlers.add('exec');
if (item.tmpl) usedHandlers.add('tmpl');
if (item.data) usedHandlers.add('data');
if (item['validate-workflow']) usedHandlers.add('validate-workflow');
}
// Only include menu-handlers section if handlers are used
if (usedHandlers.size > 0) {
activation += ` <step n="${stepNum++}">When executing a menu item: Check menu-handlers section below - extract any attributes from the selected menu item and follow the corresponding handler instructions</step>\n`;
// Menu handlers - only include what's used
activation += `
<menu-handlers>
<handlers>\n`;
if (usedHandlers.has('action')) {
activation += ` <handler type="action">
When menu item has: action="#id" → Find prompt with id="id" in current agent XML, execute its content
When menu item has: action="text" → Execute the text directly as an inline instruction
</handler>\n`;
}
if (usedHandlers.has('workflow')) {
activation += ` <handler type="workflow">
When menu item has: workflow="path/to/workflow.yaml"
1. CRITICAL: Always LOAD {project-root}/.bmad/core/tasks/workflow.xml
2. Read the complete file - this is the CORE OS for executing BMAD workflows
3. Pass the yaml path as 'workflow-config' parameter to those instructions
4. Execute workflow.xml instructions precisely following all steps
5. Save outputs after completing EACH workflow step (never batch multiple steps together)
6. If workflow.yaml path is "todo", inform user the workflow hasn't been implemented yet
</handler>\n`;
}
if (usedHandlers.has('exec')) {
activation += ` <handler type="exec">
When menu item has: exec="command" → Execute the command directly
</handler>\n`;
}
if (usedHandlers.has('tmpl')) {
activation += ` <handler type="tmpl">
When menu item has: tmpl="template-path" → Load and apply the template
</handler>\n`;
}
if (usedHandlers.has('data')) {
activation += ` <handler type="data">
When menu item has: data="path/to/x.json|yaml|yml"
Load the file, parse as JSON/YAML, make available as {data} to subsequent operations
</handler>\n`;
}
if (usedHandlers.has('validate-workflow')) {
activation += ` <handler type="validate-workflow">
When menu item has: validate-workflow="path/to/workflow.yaml"
1. CRITICAL: Always LOAD {project-root}/.bmad/core/tasks/validate-workflow.xml
2. Read the complete file - this is the CORE OS for validating BMAD workflows
3. Pass the workflow.yaml path as 'workflow' parameter to those instructions
4. Pass any checklist.md from the workflow location as 'checklist' parameter if available
5. Execute validate-workflow.xml instructions precisely following all steps
6. Generate validation report with thorough analysis
</handler>\n`;
}
activation += ` </handlers>
</menu-handlers>\n`;
}
activation += `
<rules>
- ALWAYS communicate in {communication_language} UNLESS contradicted by communication_style
- Stay in character until exit selected
- Menu triggers use asterisk (*) - NOT markdown, display exactly as shown
- Number all lists, use letters for sub-options
- Load files ONLY when executing menu items or a workflow or command requires it. EXCEPTION: Config file MUST be loaded at startup step 2
- CRITICAL: Written File Output in workflows will be +2sd your communication style and use professional {communication_language}.
</rules>
</activation>\n`;
return activation;
}
// buildSimpleActivation function removed - replaced by ActivationBuilder for proper fragment loading from src/utility/agent-components/
/**
* Build persona XML section
@@ -370,9 +242,9 @@ function processExecArray(execArray) {
* @param {Object} agentYaml - Parsed and processed agent YAML
* @param {string} agentName - Final agent name (for ID and frontmatter)
* @param {string} targetPath - Target path for agent ID
* @returns {string} Compiled XML string with frontmatter
* @returns {Promise<string>} Compiled XML string with frontmatter
*/
function compileToXml(agentYaml, agentName = '', targetPath = '') {
async function compileToXml(agentYaml, agentName = '', targetPath = '') {
const agent = agentYaml.agent;
const meta = agent.metadata;
@@ -394,8 +266,16 @@ function compileToXml(agentYaml, agentName = '', targetPath = '') {
xml += `<agent ${agentAttrs.join(' ')}>\n`;
// Activation block - pass menu items and deployment type to determine which handlers to include
xml += buildSimpleActivation(agent.critical_actions || [], agent.menu || [], 'ide');
// Activation block - use ActivationBuilder for proper fragment loading
const activationBuilder = new ActivationBuilder();
const analyzer = new AgentAnalyzer();
const profile = analyzer.analyzeAgentObject(agentYaml);
xml += await activationBuilder.buildActivation(
profile,
meta,
agent.critical_actions || [],
false, // forWebBundle - set to false for IDE deployment
);
// Persona section
xml += buildPersonaXml(agent.persona);
@@ -424,15 +304,20 @@ function compileToXml(agentYaml, agentName = '', targetPath = '') {
* @param {string} agentName - Optional final agent name (user's custom persona name)
* @param {string} targetPath - Optional target path for agent ID
* @param {Object} options - Additional options including config
* @returns {Object} { xml: string, metadata: Object }
* @returns {Promise<Object>} { xml: string, metadata: Object }
*/
function compileAgent(yamlContent, answers = {}, agentName = '', targetPath = '', options = {}) {
async function compileAgent(yamlContent, answers = {}, agentName = '', targetPath = '', options = {}) {
// Parse YAML
const agentYaml = yaml.parse(yamlContent);
let agentYaml = yaml.parse(yamlContent);
// Note: agentName parameter is for UI display only, not for modifying the YAML
// The persona name (metadata.name) should always come from the YAML file
// We should NEVER modify metadata.name as it's part of the agent's identity
// Apply customization merges before template processing
// Handle metadata overrides (like name)
if (answers.metadata) {
agentYaml.agent.metadata = { ...agentYaml.agent.metadata, ...answers.metadata };
// Remove from answers so it doesn't get processed as template variables
const { metadata, ...templateAnswers } = answers;
answers = templateAnswers;
}
// Extract install_config
const installConfig = extractInstallConfig(agentYaml);
@@ -456,7 +341,7 @@ function compileAgent(yamlContent, answers = {}, agentName = '', targetPath = ''
const cleanYaml = stripInstallConfig(processedYaml);
// Replace {agent_sidecar_folder} in XML content
let xml = compileToXml(cleanYaml, agentName, targetPath);
let xml = await compileToXml(cleanYaml, agentName, targetPath);
if (finalAnswers.agent_sidecar_folder) {
xml = xml.replaceAll('{agent_sidecar_folder}', finalAnswers.agent_sidecar_folder);
}
@@ -543,7 +428,6 @@ module.exports = {
compileAgentFile,
escapeXml,
buildFrontmatter,
buildSimpleActivation,
buildPersonaXml,
buildPromptsXml,
buildMenuXml,