import { t as generateSkillDraft } from "./skill-draft-generator-C8zPLkD-.js";
import { t as DEFAULT_EVOLUTION_CONFIG } from "./types-CrXMLXs4.js";
//#region src/cognitive/evolution/complexity-evaluator.ts
const CHINESE_CORRECTION_PATTERNS = [
	/不对/g,
	/不是这个/g,
	/换一个/g,
	/再试试/g,
	/错了/g,
	/不好/g,
	/不行/g,
	/重新来/g,
	/重新做/g,
	/不对吧/g,
	/不是这样的/g,
	/不要这个/g,
	/改一下/g,
	/换种方式/g,
	/不是我要的/g,
	/搞错了/g
];
const ENGLISH_CORRECTION_PATTERNS = [
	/\bwrong\b/gi,
	/\bnope\b/gi,
	/\bnot that\b/gi,
	/\btry again\b/gi,
	/\bincorrect\b/gi,
	/\bredo\b/gi,
	/\bnot what i wanted\b/gi,
	/\bthat's wrong\b/gi
];
const AGENT_APOLOGY_PATTERNS = [
	/抱歉/g,
	/对不起/g,
	/\bsorry\b/gi,
	/\bapologize\b/gi,
	/\blet me try again\b/gi,
	/我来重新/g,
	/换个思路/g,
	/重新来/g
];
const TOOL_CALL_REGEX = /(?:tool[_-]?call|invoke|call)[_:\s]*(\w+)/gi;
const MAX_BOOST = .25;
function detectTrialAndError(candidate) {
	const { transcript, hasTrialAndError, userCorrections: explicitCorrections } = candidate;
	if (!transcript && !hasTrialAndError && !explicitCorrections) return {
		detected: false,
		signals: [],
		userCorrections: 0,
		boost: 0
	};
	const signals = [];
	let boost = 0;
	const text = transcript ?? "";
	for (const pat of CHINESE_CORRECTION_PATTERNS) {
		pat.lastIndex = 0;
		if (pat.test(text)) {
			const matched = text.match(pat.source.startsWith("\\b") ? new RegExp(pat.source, pat.flags) : new RegExp(pat.source.replace(/\/g$/, ""), pat.flags));
			signals.push(matched?.[0] ?? pat.source);
			boost += .06;
		}
	}
	for (const pat of ENGLISH_CORRECTION_PATTERNS) {
		pat.lastIndex = 0;
		if (pat.test(text)) {
			const re = new RegExp(pat.source, pat.flags);
			const matched = text.match(re);
			signals.push(matched?.[0] ?? pat.source);
			boost += .06;
		}
	}
	for (const pat of AGENT_APOLOGY_PATTERNS) {
		pat.lastIndex = 0;
		if (pat.test(text)) {
			const re = new RegExp(pat.source, pat.flags);
			const matched = text.match(re);
			signals.push(matched?.[0] ?? pat.source);
			boost += .04;
		}
	}
	if (text) {
		const toolCounts = /* @__PURE__ */ new Map();
		const toolRe = new RegExp(TOOL_CALL_REGEX.source, TOOL_CALL_REGEX.flags);
		let m;
		while ((m = toolRe.exec(text)) !== null) {
			const toolName = m[1];
			toolCounts.set(toolName, (toolCounts.get(toolName) ?? 0) + 1);
		}
		for (const [toolName, count] of toolCounts) if (count >= 3) {
			signals.push(`repeated:${toolName}:${count}`);
			boost += .05;
		}
	}
	const corrections = explicitCorrections ?? 0;
	if (corrections > 0) {
		boost += corrections * .05;
		signals.push(`userCorrections:${corrections}`);
	}
	return {
		detected: signals.length > 0 || hasTrialAndError === true,
		signals,
		userCorrections: corrections,
		boost: Math.min(boost, MAX_BOOST)
	};
}
function evaluateComplexity(candidate) {
	const factors = [
		{
			name: "toolCount",
			raw: candidate.toolCalls.length,
			normalized: Math.min(candidate.toolCalls.length / 20, 1),
			weight: .3
		},
		{
			name: "uniqueTools",
			raw: candidate.uniqueToolCount,
			normalized: Math.min(candidate.uniqueToolCount / 8, 1),
			weight: .3
		},
		{
			name: "reasoningTurns",
			raw: candidate.reasoningTurns,
			normalized: Math.min(candidate.reasoningTurns / 10, 1),
			weight: .2
		},
		{
			name: "duration",
			raw: candidate.durationMs,
			normalized: Math.min(candidate.durationMs / 3e5, 1),
			weight: .2
		}
	];
	const baseScore = Math.min(factors.reduce((sum, f) => sum + f.normalized * f.weight, 0), 1);
	const trialError = detectTrialAndError(candidate);
	if (trialError.detected) factors.push({
		name: "trialErrorBoost",
		raw: trialError.signals.length,
		normalized: trialError.boost,
		weight: 1
	});
	const ep = candidate.errorProfile;
	if (ep && ep.errorCount > 0) {
		const errorNorm = Math.min(ep.errorCount / 3, 1);
		factors.push({
			name: "toolErrors",
			raw: ep.errorCount,
			normalized: errorNorm,
			weight: .5
		});
	}
	const uniqueSet = new Set(candidate.toolCalls);
	const rawRetryCount = candidate.toolCalls.length - uniqueSet.size;
	const retryCount = ep && ep.errorCount > 0 ? rawRetryCount : 0;
	if (retryCount > 0) {
		const retryNorm = Math.min(retryCount / 3, 1);
		factors.push({
			name: "toolRetries",
			raw: retryCount,
			normalized: retryNorm,
			weight: .4
		});
	}
	let score = baseScore + trialError.boost;
	if (ep && ep.errorCount > 0) score += Math.min(ep.errorCount / 3, 1) * .5;
	if (retryCount > 0) score += Math.min(retryCount / 3, 1) * .4;
	score = Math.min(score, 1);
	return {
		score,
		factors
	};
}
//#endregion
//#region src/cognitive/evolution/engine.ts
var EvolutionEngine = class {
	constructor(store, config, preferenceAdapter, draftGenerator) {
		this.store = store;
		this.config = config;
		this.preferenceAdapter = preferenceAdapter;
		this.draftGenerator = draftGenerator;
	}
	async effectiveConfig(agentId) {
		if (this.config) return {
			...DEFAULT_EVOLUTION_CONFIG,
			...this.config
		};
		const stored = await this.store.loadConfig(agentId);
		return {
			...DEFAULT_EVOLUTION_CONFIG,
			...stored
		};
	}
	async evaluate(candidate, agentId, userId) {
		const config = await this.effectiveConfig(agentId);
		if (!config.enabled) return {
			shouldSuggest: false,
			confidence: 0,
			complexityScore: 0,
			reasoning: "Evolution engine is disabled"
		};
		const complexity = evaluateComplexity(candidate);
		const trialError = detectTrialAndError(candidate);
		const reasoningParts = [];
		if (trialError.detected) reasoningParts.push(`Trial-and-error detected: ${trialError.signals.length} signals, boost +${trialError.boost.toFixed(2)}`);
		const hasErrors = (candidate.errorProfile?.errorCount ?? 0) > 0;
		const uniqueSet = new Set(candidate.toolCalls);
		const rawRetryCount = candidate.toolCalls.length - uniqueSet.size;
		const retryCount = hasErrors ? rawRetryCount : 0;
		const hasRetries = retryCount > 0;
		const threshold = hasErrors || hasRetries ? config.errorComplexityThreshold : config.minComplexity;
		if (hasErrors) reasoningParts.push(`Tool errors detected (${candidate.errorProfile.errorCount} errors in: ${candidate.errorProfile.failedToolNames.join(", ")}), using error threshold ${threshold}`);
		if (hasRetries) reasoningParts.push(`Tool retries detected (${retryCount} retries), using error threshold ${threshold}`);
		const recentSuggestions = (await this.store.getRecentSuggestions(agentId, userId, 48)).map((r) => ({
			skillName: r.draft?.name,
			domain: r.candidate.domain,
			hoursAgo: Math.round((Date.now() - r.timestamp) / 36e5),
			userResponse: r.userResponse
		}));
		if (complexity.score < threshold) return {
			shouldSuggest: false,
			confidence: 0,
			complexityScore: complexity.score,
			reasoning: reasoningParts.length > 0 ? `${reasoningParts.join("; ")}; Complexity score ${complexity.score.toFixed(2)} below threshold ${threshold}` : `Complexity score ${complexity.score.toFixed(2)} below threshold ${threshold}`,
			recentSuggestions
		};
		let confidence = complexity.score;
		if (this.preferenceAdapter) {
			const domainRate = await this.preferenceAdapter.getDomainAcceptanceRate(agentId, userId, candidate.domain);
			confidence = confidence * domainRate;
		}
		reasoningParts.push(`Task is complex enough (score ${complexity.score.toFixed(2)}) for skill suggestion`);
		return {
			shouldSuggest: true,
			confidence,
			complexityScore: complexity.score,
			reasoning: reasoningParts.join("; "),
			recentSuggestions
		};
	}
	async generate(candidate) {
		if (this.draftGenerator) return this.draftGenerator(candidate);
		return generateSkillDraft(candidate);
	}
	async checkBeforeGenerate(candidate, lifecycle, existingSkills, deps) {
		if (!lifecycle) return { shouldCreate: true };
		const result = deps?.generateText && existingSkills ? await lifecycle.checkSemanticDuplicate(candidate.taskSummary, candidate.taskSummary, existingSkills, deps) : await lifecycle.checkDuplicate(candidate.domain, candidate.taskSummary);
		if (result.duplicate) return {
			shouldCreate: false,
			existingSkill: result.existingName
		};
		return { shouldCreate: true };
	}
	async recordResponse(recordId, agentId, userId, response, savedPath) {
		const record = (await this.store.list(agentId, userId)).find((r) => r.id === recordId);
		if (!record) throw new Error(`Record ${recordId} not found for user ${userId}`);
		const updated = {
			...record,
			userResponse: response,
			savedSkillPath: savedPath
		};
		await this.store.save(agentId, updated);
		return updated;
	}
	async patchSkill(patch, deps) {
		const rawContent = await deps.writer.readRawSkill(patch.name);
		if (rawContent === null) return {
			ok: false,
			error: `Skill not found: ${patch.name}`
		};
		if (patch.replacements && patch.replacements.length > 0 && !deps.generateText) {
			let updated = rawContent;
			for (const { oldText, newText } of patch.replacements) {
				if (!updated.includes(oldText)) return {
					ok: false,
					error: `Text not found in skill: "${oldText}"`
				};
				updated = updated.replace(oldText, newText);
			}
			return {
				ok: true,
				updatedPath: await deps.writer.updateSkill(patch.name, updated)
			};
		}
		if (!deps.generateText) return {
			ok: false,
			error: "LLM text generation required but not provided"
		};
		const replacementsSection = patch.replacements ? `\nSpecific text replacements:\n${patch.replacements.map((r) => `- Replace "${r.oldText}" with "${r.newText}"`).join("\n")}\n` : "";
		const prompt = `You are a skill patching assistant. Update the following SKILL.md based on the user's instructions.

Current SKILL.md content:
---
${rawContent}
---

Instructions for changes:
${patch.instructions}${replacementsSection}

Return ONLY the complete updated SKILL.md content with YAML frontmatter preserved. Do not include any explanation outside the SKILL.md content.`;
		try {
			const updatedContent = await deps.generateText(prompt);
			return {
				ok: true,
				updatedPath: await deps.writer.updateSkill(patch.name, updatedContent)
			};
		} catch (err) {
			return {
				ok: false,
				error: `Failed to patch skill: ${String(err)}`
			};
		}
	}
};
//#endregion
export { EvolutionEngine };
