import { Li as resourceIdSchema, Pi as MAX_ID_LENGTH, f as AgentWithinContextOfProjectSchema } from "./props-validation.js";
import { z } from "@hono/zod-openapi";

//#region src/validation/cycleDetection.ts
function detectDelegationCycles(agentData) {
	const graph = buildDelegationGraph(agentData);
	const cycles = [];
	const visited = /* @__PURE__ */ new Set();
	const stack = /* @__PURE__ */ new Set();
	const path = [];
	function dfs(node) {
		visited.add(node);
		stack.add(node);
		path.push(node);
		for (const neighbor of graph.get(node) || []) if (!visited.has(neighbor)) {
			if (dfs(neighbor)) return true;
		} else if (stack.has(neighbor)) {
			const cycleStart = path.indexOf(neighbor);
			cycles.push(`Circular delegation detected: ${[...path.slice(cycleStart), neighbor].join(" → ")}`);
			return true;
		}
		stack.delete(node);
		path.pop();
		return false;
	}
	for (const node of graph.keys()) if (!visited.has(node)) {
		path.length = 0;
		dfs(node);
	}
	return cycles;
}
function buildDelegationGraph(agentData) {
	const graph = /* @__PURE__ */ new Map();
	for (const [subAgentId, subAgent] of Object.entries(agentData.subAgents)) {
		const delegates = subAgent.canDelegateTo?.filter((d) => typeof d === "string");
		if (delegates?.length) graph.set(subAgentId, delegates);
	}
	return graph;
}

//#endregion
//#region src/validation/agentFull.ts
function validateAndTypeAgentData(data) {
	return AgentWithinContextOfProjectSchema.parse(data);
}
/**
* Validates that all tool IDs referenced in agents exist in the tools record
* Note: With scoped architecture, tool validation should be done at the project level
* This function is kept for backward compatibility but will need project-scoped tool data
*/
function validateToolReferences(agentData, availableToolIds) {
	if (!availableToolIds) return;
	const errors = [];
	for (const [subAgentId, subAgent] of Object.entries(agentData.subAgents)) if (subAgent.canUse && Array.isArray(subAgent.canUse)) {
		for (const canUseItem of subAgent.canUse) if (!availableToolIds.has(canUseItem.toolId)) errors.push(`Agent '${subAgentId}' references non-existent tool '${canUseItem.toolId}'`);
	}
	if (errors.length > 0) throw new Error(`Tool reference validation failed:\n${errors.join("\n")}`);
}
/**
* Validates that all dataComponent IDs referenced in agents exist in the dataComponents record
* Note: With scoped architecture, dataComponent validation should be done at the project level
*/
function validateDataComponentReferences(agentData, availableDataComponentIds) {
	if (!availableDataComponentIds) return;
	const errors = [];
	for (const [subAgentId, subAgent] of Object.entries(agentData.subAgents)) if (subAgent.dataComponents) {
		for (const dataComponentId of subAgent.dataComponents) if (!availableDataComponentIds.has(dataComponentId)) errors.push(`Agent '${subAgentId}' references non-existent dataComponent '${dataComponentId}'`);
	}
	if (errors.length > 0) throw new Error(`DataComponent reference validation failed:\n${errors.join("\n")}`);
}
/**
* Validates that all artifactComponent IDs referenced in agents exist in the artifactComponents record.
* Note: With scoped architecture, artifactComponent validation should be done at the project level
*/
function validateArtifactComponentReferences(agentData, availableArtifactComponentIds) {
	if (!availableArtifactComponentIds) return;
	const errors = [];
	for (const [subAgentId, subAgent] of Object.entries(agentData.subAgents)) if (subAgent.artifactComponents) {
		for (const artifactComponentId of subAgent.artifactComponents) if (!availableArtifactComponentIds.has(artifactComponentId)) errors.push(`Agent '${subAgentId}' references non-existent artifactComponent '${artifactComponentId}'`);
	}
	if (errors.length > 0) throw new Error(`ArtifactComponent reference validation failed:\n${errors.join("\n")}`);
}
/**
* Validates agent relationships (transfer and delegation targets exist, and there is no circular delegation)
*/
function validateAgentRelationships(agentData) {
	const errors = [];
	const availableAgentIds = new Set(Object.keys(agentData.subAgents));
	const availableExternalAgentIds = new Set(Object.keys(agentData.externalAgents ?? {}));
	for (const [subAgentId, subAgent] of Object.entries(agentData.subAgents)) {
		if (subAgent.canTransferTo && Array.isArray(subAgent.canTransferTo)) {
			for (const targetId of subAgent.canTransferTo) if (!availableAgentIds.has(targetId)) errors.push(`Agent '${subAgentId}' has transfer target '${targetId}' that doesn't exist in agent`);
		}
		if (subAgent.canDelegateTo && Array.isArray(subAgent.canDelegateTo)) for (const targetItem of subAgent.canDelegateTo) {
			console.log("targetItem", targetItem);
			if (typeof targetItem === "string") {
				console.log("targetItem is string", targetItem);
				if (!availableAgentIds.has(targetItem) && !availableExternalAgentIds.has(targetItem)) errors.push(`Agent '${subAgentId}' has delegation target '${targetItem}' that doesn't exist in agent`);
			}
		}
	}
	const cycles = detectDelegationCycles(agentData);
	if (cycles.length > 0) errors.push(...cycles);
	if (errors.length > 0) throw new Error(`Agent relationship validation failed:\n${errors.join("\n")}`);
}
function validateSubAgentExternalAgentRelations(agentData, availableExternalAgentIds) {
	if (!availableExternalAgentIds) return;
	const errors = [];
	for (const [subAgentId, subAgent] of Object.entries(agentData.subAgents)) if (subAgent.canDelegateTo && Array.isArray(subAgent.canDelegateTo)) {
		for (const targetItem of subAgent.canDelegateTo) if (typeof targetItem === "object" && "externalAgentId" in targetItem) {
			if (!availableExternalAgentIds.has(targetItem.externalAgentId)) errors.push(`Agent '${subAgentId}' has delegation target '${targetItem.externalAgentId}' that doesn't exist in agent`);
		}
	}
	if (errors.length > 0) throw new Error(`Sub agent external agent relation validation failed:\n${errors.join("\n")}`);
}
/**
* Validates the agent structure before creation/update
* Note: With scoped architecture, project-scoped resource validation should be done at project level
*/
function validateAgentStructure(agentData, projectResources) {
	if (agentData.defaultSubAgentId && !agentData.subAgents[agentData.defaultSubAgentId]) throw new Error(`Default agent '${agentData.defaultSubAgentId}' does not exist in agents`);
	if (projectResources) {
		validateToolReferences(agentData, projectResources.toolIds);
		validateDataComponentReferences(agentData, projectResources.dataComponentIds);
		validateArtifactComponentReferences(agentData, projectResources.artifactComponentIds);
		validateSubAgentExternalAgentRelations(agentData, projectResources.externalAgentIds);
	}
	validateAgentRelationships(agentData);
}

//#endregion
//#region src/validation/render-validation.ts
const MAX_CODE_SIZE = 5e4;
const MAX_DATA_SIZE = 1e4;
const DANGEROUS_PATTERNS = [
	{
		pattern: /\beval\s*\(/i,
		message: "eval() is not allowed"
	},
	{
		pattern: /\bFunction\s*\(/i,
		message: "Function constructor is not allowed"
	},
	{
		pattern: /dangerouslySetInnerHTML/i,
		message: "dangerouslySetInnerHTML is not allowed"
	},
	{
		pattern: /<script\b/i,
		message: "Script tags are not allowed"
	},
	{
		pattern: /\bon\w+\s*=/i,
		message: "Inline event handlers (onClick=, onLoad=, etc.) are not allowed"
	},
	{
		pattern: /document\.write/i,
		message: "document.write is not allowed"
	},
	{
		pattern: /window\.location/i,
		message: "window.location is not allowed"
	},
	{
		pattern: /\.innerHTML\s*=/i,
		message: "innerHTML manipulation is not allowed"
	}
];
const ALLOWED_IMPORTS = ["lucide-react", "react"];
/**
* Validates component render code and data
*/
function validateRender(render) {
	const errors = [];
	if (!render.component || typeof render.component !== "string") return {
		isValid: false,
		errors: [{
			field: "render.component",
			message: "Component must be a non-empty string"
		}]
	};
	if (!render.mockData || typeof render.mockData !== "object") return {
		isValid: false,
		errors: [{
			field: "render.mockData",
			message: "MockData must be an object"
		}]
	};
	if (render.component.length > MAX_CODE_SIZE) errors.push({
		field: "render.component",
		message: `Component size exceeds maximum allowed (${MAX_CODE_SIZE} characters)`
	});
	if (JSON.stringify(render.mockData).length > MAX_DATA_SIZE) errors.push({
		field: "render.mockData",
		message: `MockData size exceeds maximum allowed (${MAX_DATA_SIZE} characters)`
	});
	for (const { pattern, message } of DANGEROUS_PATTERNS) if (pattern.test(render.component)) errors.push({
		field: "render.component",
		message: `Component contains potentially dangerous pattern: ${message}`
	});
	const importMatches = render.component.matchAll(/import\s+.*?\s+from\s+['"]([^'"]+)['"]/g);
	for (const match of importMatches) {
		const importPath = match[1];
		if (!ALLOWED_IMPORTS.includes(importPath) && !importPath.startsWith(".")) errors.push({
			field: "render.component",
			message: `Import from "${importPath}" is not allowed. Only imports from ${ALLOWED_IMPORTS.join(", ")} are permitted`
		});
	}
	if (!/function\s+\w+\s*\(/.test(render.component)) errors.push({
		field: "render.component",
		message: "Component must contain a function declaration"
	});
	if (!/return\s*\(?\s*</.test(render.component)) errors.push({
		field: "render.component",
		message: "Component function must have a return statement with JSX"
	});
	return {
		isValid: errors.length === 0,
		errors
	};
}

//#endregion
//#region src/validation/event-schemas.ts
/**
* Agent transfer event data
* Used when an agent transfers control to another agent
*/
const TransferDataSchema = z.object({
	fromSubAgent: z.string().describe("ID of the sub-agent transferring control"),
	targetSubAgent: z.string().describe("ID of the sub-agent receiving control"),
	reason: z.string().optional().describe("Reason for the transfer"),
	context: z.any().optional().describe("Additional context data")
});
/**
* Delegation sent event data
* Used when an agent delegates a task to another agent
*/
const DelegationSentDataSchema = z.object({
	delegationId: z.string().describe("Unique identifier for this delegation"),
	fromSubAgent: z.string().describe("ID of the delegating sub-agent"),
	targetSubAgent: z.string().describe("ID of the sub-agent receiving the delegation"),
	taskDescription: z.string().describe("Description of the delegated task"),
	context: z.any().optional().describe("Additional context data")
});
/**
* Delegation returned event data
* Used when a delegated task is completed and returned
*/
const DelegationReturnedDataSchema = z.object({
	delegationId: z.string().describe("Unique identifier matching the original delegation"),
	fromSubAgent: z.string().describe("ID of the sub-agent that completed the task"),
	targetSubAgent: z.string().describe("ID of the sub-agent receiving the result"),
	result: z.any().optional().describe("Result data from the delegated task")
});
/**
* Data operation event details
* Used for emit operations and agent data events
*/
const DataOperationDetailsSchema = z.object({
	timestamp: z.number().describe("Unix timestamp in milliseconds"),
	subAgentId: z.string().describe("ID of the sub-agent that generated this data"),
	data: z.any().describe("The actual data payload")
});
/**
* Complete data operation event
* Includes type and label for user-facing display
*/
const DataOperationEventSchema = z.object({
	type: z.string().describe("Event type identifier"),
	label: z.string().describe("Human-readable label for the event"),
	details: DataOperationDetailsSchema
});
/**
* Message metadata for A2A communication
* Used in message passing between agents
*/
const A2AMessageMetadataSchema = z.object({
	fromSubAgentId: z.string().optional().describe("ID of the sending sub-agent"),
	toSubAgentId: z.string().optional().describe("ID of the receiving sub-agent"),
	fromExternalAgentId: z.string().optional().describe("ID of the sending external agent"),
	toExternalAgentId: z.string().optional().describe("ID of the receiving external agent"),
	taskId: z.string().optional().describe("Associated task ID"),
	a2aTaskId: z.string().optional().describe("A2A-specific task ID")
});

//#endregion
//#region src/validation/id-validation.ts
/**
* Valid URL-safe characters for resource IDs based on RFC 3986.
*
* Allowed characters:
* - Letters: a-z, A-Z
* - Numbers: 0-9
* - Hyphens: -
* - Underscores: _
*
* Note: While dots (.) and tildes (~) are technically URL-safe,
* we exclude them for consistency with existing patterns in the codebase.
*/
/**
* Helper function to validate if a string is a valid resource ID
*/
function isValidResourceId(id) {
	return resourceIdSchema.safeParse(id).success;
}
/**
* Helper function to generate a URL-safe ID from a name or title.
* Converts to lowercase and replaces invalid characters with hyphens.
*/
function generateIdFromName(name) {
	const id = name.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "").replace(/-{2,}/g, "-");
	if (!id) throw new Error("Cannot generate valid ID from provided name");
	const truncatedId = id.substring(0, MAX_ID_LENGTH);
	const result = resourceIdSchema.safeParse(truncatedId);
	if (!result.success) throw new Error(`Generated ID "${truncatedId}" is not valid: ${result.error.message}`);
	return truncatedId;
}
/**
* Example valid IDs:
* - "qa-agent"
* - "customer_support_123"
* - "router"
* - "tool-executor-v2"
* - "PRODUCTION_CONFIG"
*
* Example invalid IDs:
* - "my.agent" (contains dot)
* - "agent@123" (contains @)
* - "agent/router" (contains slash)
* - "my agent" (contains space)
* - "agent#1" (contains hash)
* - "" (empty string)
*/

//#endregion
//#region src/validation/stream-event-schemas.ts
/**
* Vercel AI SDK Data Stream Protocol Event Schemas
*
* These schemas define the structure of events sent by the Inkeep Agents Run API.
* They are used by both the streaming backend and AI SDK providers to ensure type safety.
*/
/**
* Marks the beginning of a text stream
*/
const TextStartEventSchema = z.object({
	type: z.literal("text-start"),
	id: z.string()
});
/**
* Represents a chunk of streaming text
*/
const TextDeltaEventSchema = z.object({
	type: z.literal("text-delta"),
	id: z.string(),
	delta: z.string()
});
/**
* Marks the end of a text stream
*/
const TextEndEventSchema = z.object({
	type: z.literal("text-end"),
	id: z.string()
});
/**
* Data component event - structured data in the stream
* Used for artifacts, visualizations, or other structured outputs
*/
const DataComponentStreamEventSchema = z.object({
	type: z.literal("data-component"),
	id: z.string(),
	data: z.any()
});
/**
* Data operation event - agent operations and state changes
* Wraps operation events (agent_initializing, completion, etc.)
*/
const DataOperationStreamEventSchema = z.object({
	type: z.literal("data-operation"),
	data: z.any()
});
/**
* Data summary event - progress summaries and status updates
*/
const DataSummaryStreamEventSchema = z.object({
	type: z.literal("data-summary"),
	data: z.any()
});
/**
* Stream error event
*/
const StreamErrorEventSchema = z.object({
	type: z.literal("error"),
	error: z.string()
});
/**
* Stream finish event with usage statistics
*/
const StreamFinishEventSchema = z.object({
	type: z.literal("finish"),
	finishReason: z.string().optional(),
	usage: z.object({
		promptTokens: z.number().optional(),
		completionTokens: z.number().optional(),
		totalTokens: z.number().optional()
	}).optional()
});
/**
* Union of all stream event types
* This is the main schema used for validating incoming stream events
*/
const StreamEventSchema = z.discriminatedUnion("type", [
	TextStartEventSchema,
	TextDeltaEventSchema,
	TextEndEventSchema,
	DataComponentStreamEventSchema,
	DataOperationStreamEventSchema,
	DataSummaryStreamEventSchema,
	StreamErrorEventSchema,
	StreamFinishEventSchema
]);

//#endregion
export { validateDataComponentReferences as C, validateArtifactComponentReferences as S, validateToolReferences as T, TransferDataSchema as _, StreamEventSchema as a, validateAgentStructure as b, TextEndEventSchema as c, isValidResourceId as d, A2AMessageMetadataSchema as f, DelegationSentDataSchema as g, DelegationReturnedDataSchema as h, StreamErrorEventSchema as i, TextStartEventSchema as l, DataOperationEventSchema as m, DataOperationStreamEventSchema as n, StreamFinishEventSchema as o, DataOperationDetailsSchema as p, DataSummaryStreamEventSchema as r, TextDeltaEventSchema as s, DataComponentStreamEventSchema as t, generateIdFromName as u, validateRender as v, validateSubAgentExternalAgentRelations as w, validateAndTypeAgentData as x, validateAgentRelationships as y };
//# sourceMappingURL=validation.js.map