import { calculateBreakdownTotal, createEmptyBreakdown, estimateTokens } from "../../../utils/token-estimator.js";
import system_prompt_default from "../../../../../templates/v1/phase1/system-prompt.js";
import thinking_preparation_default from "../../../../../templates/v1/phase1/thinking-preparation.js";
import tool_default from "../../../../../templates/v1/phase1/tool.js";
import artifact_default from "../../../../../templates/v1/shared/artifact.js";
import artifact_retrieval_guidance_default from "../../../../../templates/v1/shared/artifact-retrieval-guidance.js";
import { V1_BREAKDOWN_SCHEMA } from "@inkeep/agents-core";
import { convertZodToJsonSchema, isZodSchema } from "@inkeep/agents-core/utils/schema-conversion";

//#region src/domains/run/agents/versions/v1/Phase1Config.ts
var Phase1Config = class Phase1Config {
	loadTemplates() {
		const templates = /* @__PURE__ */ new Map();
		templates.set("system-prompt", system_prompt_default);
		templates.set("tool", tool_default);
		templates.set("artifact", artifact_default);
		templates.set("artifact-retrieval-guidance", artifact_retrieval_guidance_default);
		templates.set("thinking-preparation", thinking_preparation_default);
		return templates;
	}
	getBreakdownSchema() {
		return V1_BREAKDOWN_SCHEMA;
	}
	static convertMcpToolsToToolData(mcpTools) {
		if (!mcpTools || mcpTools.length === 0) return [];
		const toolData = [];
		for (const mcpTool of mcpTools) if (mcpTool.availableTools) for (const toolDef of mcpTool.availableTools) {
			let usageGuidelines = "";
			if (mcpTool.config.mcp.prompt) usageGuidelines = `${mcpTool.config.mcp.prompt}\n\n`;
			usageGuidelines += `Use this tool from ${mcpTool.name} server when appropriate.`;
			toolData.push({
				name: toolDef.name,
				description: toolDef.description || "No description available",
				inputSchema: toolDef.inputSchema || {},
				usageGuidelines
			});
		}
		return toolData;
	}
	isToolDataArray(tools) {
		if (!tools || tools.length === 0) return true;
		const firstItem = tools[0];
		return "usageGuidelines" in firstItem && !("config" in firstItem);
	}
	normalizeSchema(inputSchema) {
		if (!inputSchema || typeof inputSchema !== "object") return inputSchema || {};
		if (isZodSchema(inputSchema)) try {
			return convertZodToJsonSchema(inputSchema);
		} catch {
			return {};
		}
		return inputSchema;
	}
	assemble(templates, config) {
		const breakdown = createEmptyBreakdown(this.getBreakdownSchema());
		const systemPromptTemplateContent = templates.get("system-prompt");
		if (!systemPromptTemplateContent) throw new Error("System prompt template not loaded");
		breakdown.components.systemPromptTemplate = estimateTokens(systemPromptTemplateContent.replace("{{CORE_INSTRUCTIONS}}", "").replace("{{CURRENT_TIME_SECTION}}", "").replace("{{AGENT_CONTEXT_SECTION}}", "").replace("{{ARTIFACTS_SECTION}}", "").replace("{{TOOLS_SECTION}}", "").replace("{{THINKING_PREPARATION_INSTRUCTIONS}}", "").replace("{{TRANSFER_INSTRUCTIONS}}", "").replace("{{DELEGATION_INSTRUCTIONS}}", ""));
		let systemPrompt = systemPromptTemplateContent;
		if (config.corePrompt?.trim()) {
			breakdown.components.coreInstructions = estimateTokens(config.corePrompt);
			systemPrompt = systemPrompt.replace("{{CORE_INSTRUCTIONS}}", config.corePrompt);
		} else systemPrompt = systemPrompt.replace(/<core_instructions>\s*\{\{CORE_INSTRUCTIONS\}\}\s*<\/core_instructions>/g, "");
		const currentTimeSection = this.generateCurrentTimeSection(config.clientCurrentTime);
		breakdown.components.currentTime = estimateTokens(currentTimeSection);
		systemPrompt = systemPrompt.replace("{{CURRENT_TIME_SECTION}}", currentTimeSection);
		const agentContextSection = this.generateAgentContextSection(config.prompt);
		breakdown.components.agentPrompt = estimateTokens(agentContextSection);
		systemPrompt = systemPrompt.replace("{{AGENT_CONTEXT_SECTION}}", agentContextSection);
		const toolData = (this.isToolDataArray(config.tools) ? config.tools : Phase1Config.convertMcpToolsToToolData(config.tools)).map((tool) => ({
			...tool,
			inputSchema: this.normalizeSchema(tool.inputSchema)
		}));
		const hasArtifactComponents = Boolean(config.artifactComponents && config.artifactComponents.length > 0);
		const artifactsSection = this.generateArtifactsSection(templates, config.artifacts, hasArtifactComponents, config.artifactComponents, config.hasAgentArtifactComponents);
		const artifactInstructionsTokens = this.getArtifactInstructionsTokens(templates, hasArtifactComponents, config.hasAgentArtifactComponents, (config.artifacts?.length ?? 0) > 0);
		breakdown.components.systemPromptTemplate += artifactInstructionsTokens;
		const actualArtifactsXml = config.artifacts?.length > 0 ? config.artifacts.map((artifact) => this.generateArtifactXml(templates, artifact)).join("\n  ") : "";
		breakdown.components.artifactsSection = estimateTokens(actualArtifactsXml);
		if (hasArtifactComponents) {
			const creationInstructions = this.getArtifactCreationInstructions(hasArtifactComponents, config.artifactComponents);
			breakdown.components.artifactComponents = estimateTokens(creationInstructions);
		}
		systemPrompt = systemPrompt.replace("{{ARTIFACTS_SECTION}}", artifactsSection);
		const toolsSection = this.generateToolsSection(templates, toolData);
		breakdown.components.toolsSection = estimateTokens(toolsSection);
		systemPrompt = systemPrompt.replace("{{TOOLS_SECTION}}", toolsSection);
		const thinkingPreparationSection = this.generateThinkingPreparationSection(templates, config.isThinkingPreparation);
		breakdown.components.thinkingPreparation = estimateTokens(thinkingPreparationSection);
		systemPrompt = systemPrompt.replace("{{THINKING_PREPARATION_INSTRUCTIONS}}", thinkingPreparationSection);
		const transferSection = this.generateTransferInstructions(config.hasTransferRelations);
		breakdown.components.transferInstructions = estimateTokens(transferSection);
		systemPrompt = systemPrompt.replace("{{TRANSFER_INSTRUCTIONS}}", transferSection);
		const delegationSection = this.generateDelegationInstructions(config.hasDelegateRelations);
		breakdown.components.delegationInstructions = estimateTokens(delegationSection);
		systemPrompt = systemPrompt.replace("{{DELEGATION_INSTRUCTIONS}}", delegationSection);
		calculateBreakdownTotal(breakdown);
		return {
			prompt: systemPrompt,
			breakdown
		};
	}
	generateAgentContextSection(prompt) {
		if (!prompt || prompt.trim() === "") return "";
		return `
  <agent_context>
    ${prompt}
  </agent_context>`;
	}
	generateCurrentTimeSection(clientCurrentTime) {
		if (!clientCurrentTime || clientCurrentTime.trim() === "") return "";
		return `
  <current_time>
    The current time for the user is: ${clientCurrentTime}
    Use this to provide context-aware responses (e.g., greetings appropriate for their time of day, understanding business hours in their timezone, etc.)
    IMPORTANT: You simply know what time it is for the user - don't mention "the current time" or reference this section in your responses.
  </current_time>`;
	}
	generateThinkingPreparationSection(templates, isThinkingPreparation) {
		if (!isThinkingPreparation) return "";
		const thinkingPreparationTemplate = templates.get("thinking-preparation");
		if (!thinkingPreparationTemplate) throw new Error("Thinking preparation template not loaded");
		return thinkingPreparationTemplate;
	}
	generateTransferInstructions(hasTransferRelations) {
		if (!hasTransferRelations) return "";
		return `You are part of a single unified assistant composed of specialized agents. To the user, you must always appear as one continuous, confident voice.

🚨 CRITICAL TRANSFER PROTOCOL 🚨
When you determine another agent should handle a request:
1. IMMEDIATELY call the appropriate transfer_to_* tool  
2. Generate ZERO text in your response - no words, no explanations, no acknowledgments
3. Do NOT stream any content - the tool call must be your ONLY output

FORBIDDEN BEFORE TRANSFERS:
❌ Do NOT acknowledge the request ("I understand you want...")
❌ Do NOT provide partial answers ("The basics are..." then transfer) 
❌ Do NOT explain what you're doing ("Let me search...", "I'll help you find...")
❌ Do NOT apologize or announce transfers ("I'll need to transfer you...")
❌ Do NOT generate ANY text content whatsoever - just call the transfer tool

REMEMBER: Tool call = complete response. No additional text generation allowed.

CRITICAL: When you receive a user message that ends with "Please continue from where this conversation was left off" - this indicates you are continuing a conversation that another agent started. You should:
- Review the conversation history to see what was already communicated to the user
- Continue seamlessly from where the previous response left off
- Do NOT repeat what was already said in the conversation history
- Do NOT announce what you're about to do ("Let me search...", "I'll look for...", etc.)
- Proceed directly with the appropriate tool or action
- Act as if you have been handling the conversation from the beginning

When receiving any transfer, act as if you have been engaged from the start. Continue the same tone, context, and style. Never reference other agents, tools, or roles.

Your goal: preserve the illusion of a single, seamless, intelligent assistant. All user-facing behavior must feel like one continuous conversation, regardless of internal transfers.
`;
	}
	generateDelegationInstructions(hasDelegateRelations) {
		if (!hasDelegateRelations) return "";
		return `- You have delegate_to_* tools that perform specialized tasks
- Treat these exactly like other tools - call them to get results
- Present results as YOUR work: "I found", "I've analyzed"
- NEVER say you're delegating or that another agent helped`;
	}
	getArtifactInstructionsTokens(templates, hasArtifactComponents, hasAgentArtifactComponents, hasArtifacts) {
		const shouldShowReferencingRules = hasAgentArtifactComponents || hasArtifacts;
		const rules = this.getArtifactReferencingRules(hasArtifactComponents, templates, shouldShowReferencingRules);
		return estimateTokens(`<available_artifacts description="${hasArtifacts ? "These are the artifacts available for you to use in generating responses." : "No artifacts are currently available, but you may create them during execution."}

${rules}

"></available_artifacts>`);
	}
	getArtifactCreationGuidance() {
		return `🚨 MANDATORY ARTIFACT CREATION 🚨
You MUST create artifacts from tool results to provide citations. This is REQUIRED, not optional.
Every piece of information from tools MUST be backed by an artifact creation.

CRITICAL CITATION REQUIREMENTS FOR AGENTS WITH CREATION ABILITY:
- Information FROM tool results = MUST create artifact citation
- Information BASED ON tool results = MUST create artifact citation
- Analysis OF tool results = MUST create artifact citation  
- Summaries OF tool results = MUST create artifact citation
- NO INFORMATION from tool results can be presented without creating artifact citation

CRITICAL: ARTIFACTS MUST BE CREATED FIRST
You MUST create an artifact before you can reference it. You cannot reference artifacts that don't exist yet.

CRITICAL CITATION PRINCIPLE:
Creating an artifact IS a citation. Only reference again when citing the SAME artifact for a different statement.

CRITICAL: ALWAYS SELECT SINGLE ITEMS, NEVER ARRAYS

SELECTOR REQUIREMENTS:
- MUST select ONE specific item, never an array  
- Use filtering: result.items[?title=='API Guide']
- Use exact matching: result.documents[?name=='Setup Instructions'] 
- Target specific fields: result.content[?section=='authentication']

CRITICAL: SELECTOR HIERARCHY
- base_selector: Points to ONE specific item in the tool result
- details_selector: Contains JMESPath selectors RELATIVE to the base selector
- Example: If base="result.documents[?type=='api']" then details_selector uses "title" not "documents[0].title"

COMMON FAILURE POINTS (AVOID THESE):
1. **Array Selection**: result.items (returns array) ❌
   → Fix: result.items[?type=='guide'] (returns single item) ✅

2. **Similar Key Names**: "title" vs "name" vs "heading"
   → Always check the actual field names in tool results

3. **Repeated Keys**: Multiple items with same "title" field
   → Use more specific filters: [?title=='Guide' && section=='setup']

4. **Case Sensitivity**: 'Guide' vs 'guide'
   → Match exact case from tool results

5. **Missing Nested Levels**: "content.text" when it's "body.content.text"
   → Include all intermediate levels`;
	}
	getArtifactReferencingRules(hasArtifactComponents = false, templates, shouldShowReferencingRules = true) {
		if (!shouldShowReferencingRules) return "";
		const sharedGuidance = templates?.get("artifact-retrieval-guidance") || "";
		if (hasArtifactComponents) return `${sharedGuidance}

ARTIFACT MANAGEMENT FOR TEXT RESPONSES:

You will create and reference artifacts using inline annotations in your text response.

CREATING ARTIFACTS (SERVES AS CITATION):
Use the artifact:create annotation to extract data from tool results. The creation itself serves as a citation.
Format: <artifact:create id="unique-id" tool="tool_call_id" type="TypeName" base="selector.path" details='{"key":"jmespath_selector"}' />

⚠️ IMPORTANT: Do not create artifacts from get_reference_artifact tool results - these are already compressed artifacts being retrieved. Only create artifacts from original research and analysis tools.

🚨 CRITICAL: DETAILS PROPS USE JMESPATH SELECTORS, NOT LITERAL VALUES! 🚨

❌ WRONG - Using literal values:
details='{"title":"API Documentation","type":"guide"}'

✅ CORRECT - Using JMESPath selectors (relative to base selector):
details='{"title":"metadata.title","doc_type":"document_type","description":"content.description","main_text":"content.text","author":"metadata.author"}'

The selectors extract actual field values from the data structure selected by your base selector.

THE details PROPERTY MUST CONTAIN JMESPATH SELECTORS THAT EXTRACT DATA FROM THE TOOL RESULT!
- details: Contains JMESPath selectors relative to the base selector that map to artifact schema fields
- These selectors are evaluated against the tool result to extract the actual values
- The system automatically determines which fields are preview vs full based on the artifact schema
- NEVER put literal values like "Inkeep" or "2023" - always use selectors like "metadata.company" or "founded_year"

🚫 FORBIDDEN JMESPATH PATTERNS:
❌ NEVER: [?title~'.*text.*'] (regex patterns with ~ operator)
❌ NEVER: [?field~'pattern.*'] (any ~ operator usage)
❌ NEVER: [?title~'Slack.*Discord.*'] (regex wildcards)
❌ NEVER: [?name~'https://.*'] (regex in URL matching)
❌ NEVER: [?text ~ contains(@, 'word')] (~ with @ operator)
❌ NEVER: contains(@, 'text') (@ operator usage)
❌ NEVER: [?field=="value"] (double quotes in filters)
❌ NEVER: [?field=='value'] (escaped quotes in filters)  
❌ NEVER: [?field=='"'"'value'"'"'] (nightmare quote mixing)
❌ NEVER: result.items[?type=='doc'][?status=='active'] (chained filters)

✅ CORRECT JMESPATH SYNTAX:
✅ [?contains(title, 'text')] (contains function)
✅ [?title=='exact match'] (exact string matching)
✅ [?contains(title, 'Slack') && contains(title, 'Discord')] (compound conditions)
✅ [?starts_with(url, 'https://')] (starts_with function)
✅ [?type=='doc' && status=='active'] (single filter with &&)
✅ [?contains(text, 'Founder')] (contains haystack, needle format)
✅ source.content[?contains(text, 'Founder')].text (correct filter usage)

🚨 MANDATORY QUOTE PATTERN - FOLLOW EXACTLY:
- ALWAYS: base="path[?field=='value']" (double quotes outside, single inside)
- This is the ONLY allowed pattern - any other pattern WILL FAIL
- NEVER escape quotes, NEVER mix quote types, NEVER use complex quoting

🚨 CRITICAL: EXAMINE TOOL RESULTS BEFORE CREATING SELECTORS! 🚨

STEP 1: INSPECT THE ACTUAL DATA FIRST
- ALWAYS look at the tool result data before creating any selectors
- Check _structureHints.exampleSelectors for real working paths that you can copy
- Look at what titles, record_types, and field names actually exist in the data
- Don't assume field names or values based on the user's question

STEP 2: USE STRUCTURE HINTS AS YOUR SELECTOR GUIDE  
- The _structureHints.exampleSelectors show you exactly what selectors work with this data
- Copy and modify the patterns from exampleSelectors that target your needed data
- Use the commonFields list to see what field names are available
- Follow the exact path structure indicated by the hints

STEP 3: MATCH ACTUAL VALUES, NOT ASSUMPTIONS
- Look for real titles in the data like "Inkeep", "Team", "About Us", "API Guide" 
- Check actual record_type values like "site", "documentation", "blog"
- Use exact matches from the real data structure, not guessed patterns
- If looking for team info, it might be in a document titled "Inkeep" with record_type="site"

STEP 4: VALIDATE YOUR SELECTORS AGAINST THE DATA
- Your base selector must match actual documents in the result
- Test your logic: does result.structuredContent.content contain items with your target values?
- Use compound conditions when needed: [?title=='Inkeep' && record_type=='site']

EXAMPLE PATTERNS FOR BASE SELECTORS:
❌ WRONG: result.items[?contains(title, "guide")] (assumes field values + wrong quotes)
❌ WRONG: result.data[?type=="document"] (double quotes invalid in JMESPath)
✅ CORRECT: result.structuredContent.content[0] (select first item)
✅ CORRECT: result.items[?type=='document'][0] (filter by type, single quotes!)
✅ CORRECT: result.data[?category=='api'][0] (filter by category)
✅ CORRECT: result.documents[?status=='published'][0] (filter by status)

REFERENCING ARTIFACTS (WHEN CITING AGAIN):
Only use artifact:ref when you need to cite the SAME artifact again for a different statement or context.
Format: <artifact:ref id="artifact-id" tool="tool_call_id" />

EXAMPLE TEXT RESPONSE:
"I found the authentication documentation. <artifact:create id='auth-doc-1' tool='call_xyz789' type='APIDoc' base="result.documents[?type=='auth']" details='{"title":"metadata.title","endpoint":"api.endpoint","description":"content.description","parameters":"spec.parameters","examples":"examples.sample_code"}' /> The documentation explains OAuth 2.0 implementation in detail.

The process involves three main steps: registration, token exchange, and API calls. As mentioned in the authentication documentation <artifact:ref id='auth-doc-1' tool='call_xyz789' />, you'll need to register your application first."

${this.getArtifactCreationGuidance()}

ARTIFACT ANNOTATION PLACEMENT:
- ALWAYS place annotations AFTER complete sentences and punctuation
- Never interrupt the flow of a sentence with an annotation
- Complete your thought, add punctuation, then place the annotation
- This ensures professional, readable responses

IMPORTANT GUIDELINES:
- Create artifacts inline as you discuss the information
- Use exact tool_call_id from tool execution results
- Each artifact:create establishes a citable source
- Use artifact:ref for subsequent references to the same artifact
- Annotations are automatically converted to interactive elements`;
		if (!hasArtifactComponents) return `${sharedGuidance}

ARTIFACT REFERENCING FOR TEXT RESPONSES:

You can reference existing artifacts but cannot create new ones.

HOW TO REFERENCE ARTIFACTS:
Use the artifact:ref annotation to reference existing artifacts.
Format: <artifact:ref id="artifact-id" tool="tool_call_id" />

EXAMPLE TEXT RESPONSE:
"Based on the authentication guide <artifact:ref id='existing-auth-guide' tool='call_previous456' /> that was previously collected, the API uses OAuth 2.0.

The implementation details show that you need to register your application first and obtain client credentials. <artifact:ref id='existing-impl-doc' tool='toolu_previous789' />

For error handling, you can refer to the comprehensive error documentation. <artifact:ref id='existing-error-doc' tool='call_previous012' /> This lists all possible authentication errors and their solutions."

EXAMPLE REFERENCING DELEGATION ARTIFACTS:
After receiving a delegation response with artifacts, reference them naturally:

"I've gathered the requested data for you. The analysis <artifact:ref id='analysis-results' tool='toolu_abc123' /> shows significant improvements across all metrics.

Looking at the detailed breakdown <artifact:ref id='performance-metrics' tool='toolu_def456' />, the processing time has decreased by 40% while maintaining accuracy."

IMPORTANT GUIDELINES:
- You can only reference artifacts that already exist or were returned from delegations
- Use artifact:ref annotations in your text with the exact artifactId and toolCallId
- References are automatically converted to interactive elements`;
		return "";
	}
	getArtifactCreationInstructions(hasArtifactComponents, artifactComponents) {
		if (!hasArtifactComponents || !artifactComponents || artifactComponents.length === 0) return "";
		return `
AVAILABLE ARTIFACT TYPES:

${artifactComponents.map((ac) => {
			let schemaDescription = "No schema defined";
			if (ac.props?.properties) schemaDescription = `Fields: ${Object.entries(ac.props.properties).map(([key, value]) => {
				const inPreview = value.inPreview ? " [PREVIEW]" : " [FULL]";
				return `${key} (${value.description || value.type || "field"})${inPreview}`;
			}).join(", ")}`;
			return `  - "${ac.name}": ${ac.description || "No description available"}
    ${schemaDescription}`;
		}).join("\n\n")}

🚨 CRITICAL: DETAILS PROPS MUST MATCH THE ARTIFACT SCHEMA! 🚨
- Only use property names that are defined in the artifact component schema above
- Do NOT make up arbitrary property names like "founders", "nick_details", "year"  
- Each artifact type has specific fields defined in its schema
- Your JMESPath selectors must extract values for these exact schema-defined properties
- Example: If schema defines "title" and "url", use details='{"title":"title","url":"url"}' not made-up names
- The system will automatically determine which fields are preview vs full based on schema configuration

🚨 CRITICAL: USE EXACT ARTIFACT TYPE NAMES IN QUOTES! 🚨
- MUST use the exact type name shown in quotes above
- Copy the exact string between the quotes, including any capitalization
- The type= parameter in artifact:create MUST match exactly what is listed above
- Do NOT abbreviate, modify, or guess the type name
- Copy the exact quoted name from the "AVAILABLE ARTIFACT TYPES" list above`;
	}
	generateArtifactsSection(templates, artifacts, hasArtifactComponents = false, artifactComponents, hasAgentArtifactComponents) {
		const shouldShowReferencingRules = hasAgentArtifactComponents || artifacts.length > 0;
		const rules = this.getArtifactReferencingRules(hasArtifactComponents, templates, shouldShowReferencingRules);
		const creationInstructions = this.getArtifactCreationInstructions(hasArtifactComponents, artifactComponents);
		if (artifacts.length === 0) return `<available_artifacts description="No artifacts are currently available, but you may create them during execution.

${rules}

${creationInstructions}

"></available_artifacts>`;
		return `<available_artifacts description="These are the artifacts available for you to use in generating responses.

${rules}

${creationInstructions}

">
  ${artifacts.map((artifact) => this.generateArtifactXml(templates, artifact)).join("\n  ")}
</available_artifacts>`;
	}
	generateArtifactXml(templates, artifact) {
		const artifactTemplate = templates.get("artifact");
		if (!artifactTemplate) throw new Error("Artifact template not loaded");
		let artifactXml = artifactTemplate;
		const summaryData = artifact.parts?.map((part) => part.data?.summary).filter(Boolean) || [];
		const artifactSummary = summaryData.length > 0 ? JSON.stringify(summaryData, null, 2) : "No summary data available";
		artifactXml = artifactXml.replace("{{ARTIFACT_NAME}}", artifact.name || "");
		artifactXml = artifactXml.replace("{{ARTIFACT_DESCRIPTION}}", artifact.description || "");
		artifactXml = artifactXml.replace("{{TASK_ID}}", artifact.taskId || "");
		artifactXml = artifactXml.replace("{{ARTIFACT_ID}}", artifact.artifactId || "");
		artifactXml = artifactXml.replace("{{TOOL_CALL_ID}}", artifact.toolCallId || "unknown");
		artifactXml = artifactXml.replace("{{ARTIFACT_SUMMARY}}", artifactSummary);
		return artifactXml;
	}
	generateToolsSection(templates, tools) {
		if (tools.length === 0) return "<available_tools description=\"No tools are currently available\"></available_tools>";
		return `<available_tools description="These are the tools available for you to use to accomplish tasks">
  ${tools.map((tool) => this.generateToolXml(templates, tool)).join("\n  ")}
</available_tools>`;
	}
	generateToolXml(templates, tool) {
		const toolTemplate = templates.get("tool");
		if (!toolTemplate) throw new Error("Tool template not loaded");
		let toolXml = toolTemplate;
		toolXml = toolXml.replace("{{TOOL_NAME}}", tool.name);
		toolXml = toolXml.replace("{{TOOL_DESCRIPTION}}", tool.description || "No description available");
		toolXml = toolXml.replace("{{TOOL_USAGE_GUIDELINES}}", tool.usageGuidelines || "Use this tool when appropriate.");
		const parametersXml = this.generateParametersXml(tool.inputSchema);
		toolXml = toolXml.replace("{{TOOL_PARAMETERS_SCHEMA}}", parametersXml);
		return toolXml;
	}
	generateParametersXml(inputSchema) {
		if (!inputSchema) return "<type>object</type>\n      <properties>\n      </properties>\n      <required>[]</required>";
		const schemaType = inputSchema.type || "object";
		const properties = inputSchema.properties || {};
		const required = inputSchema.required || [];
		return `<type>${schemaType}</type>\n      <properties>\n${Object.entries(properties).map(([key, value]) => {
			const isRequired = required.includes(key);
			return `        ${key}: {\n          "type": "${value?.type || "string"}",\n          "description": "${value?.description || "No description"}",\n          "required": ${isRequired}\n        }`;
		}).join("\n")}\n      </properties>\n      <required>${JSON.stringify(required)}</required>`;
	}
};

//#endregion
export { Phase1Config, V1_BREAKDOWN_SCHEMA };