"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OAuthCredentialSchema = exports.ApiKeyCredentialSchema = exports.CredentialTypeSchema = exports.CredentialNameSchema = exports.MemorySchema = exports.IndexedKeySchema = exports.MAX_INDEXED_KEYS = exports.MAX_INDEXED_KEY_NAME_LENGTH = exports.INDEXED_KEY_NAME_PATTERN_MESSAGE = exports.INDEXED_KEY_NAME_PATTERN = exports.IndexedKeyTypeSchema = exports.StreamDeliveryResourcesSchema = exports.StreamContentLevelSchema = exports.MemoryNameSchema = exports.MemoryTypeSchema = exports.ProjectNameSchema = exports.AgentCoreMcpRuntimeToolSchema = exports.AgentCoreGatewayTargetSchema = exports.AgentCoreGatewaySchema = exports.ManagedBySchema = exports.HttpGatewayTargetSchema = exports.GatewayFilterSchema = exports.TargetRefSchema = exports.ABTestModeSchema = exports.DatasetSchemaTypeSchema = exports.DatasetNameSchema = exports.DatasetSchema = exports.TagsSchema = exports.ValidationModeSchema = exports.PolicySchema = exports.PolicyNameSchema = exports.PolicyEngineNameSchema = exports.PolicyEngineSchema = exports.ComponentConfigurationMapSchema = exports.ConfigBundleNameSchema = exports.ConfigBundleSchema = exports.isValidKmsKeyArn = exports.KMS_KEY_ARN_PATTERN = exports.EvaluatorNameSchema = exports.isValidBedrockModelId = exports.BedrockModelIdSchema = exports.OnlineEvalConfigNameSchema = exports.OnlineEvalConfigSchema = exports.EvaluationLevelSchema = exports.MemoryStrategyTypeSchema = exports.MemoryStrategySchema = exports.DEFAULT_STRATEGY_NAMESPACES = exports.DEFAULT_STRATEGY_NAMESPACE_TEMPLATES = exports.DEFAULT_EPISODIC_REFLECTION_NAMESPACES = exports.DEFAULT_EPISODIC_REFLECTION_NAMESPACE_TEMPLATES = void 0;
exports.AgentCoreProjectSpecSchema = exports.EvaluatorSchema = exports.EvaluatorTypeSchema = exports.CredentialSchema = void 0;
/**
 * AgentCore Project Schema - Resource-centric model
 *
 * Flat resource model where agents, memories, and credentials are top-level.
 * All resources within a project implicitly have access to each other.
 *
 * @module agentcore-project
 */
const constants_1 = require("../constants");
const agent_env_1 = require("./agent-env");
const mcp_1 = require("./mcp");
const ab_test_1 = require("./primitives/ab-test");
const config_bundle_1 = require("./primitives/config-bundle");
Object.defineProperty(exports, "ConfigBundleSchema", { enumerable: true, get: function () { return config_bundle_1.ConfigBundleSchema; } });
const dataset_1 = require("./primitives/dataset");
Object.defineProperty(exports, "DatasetSchema", { enumerable: true, get: function () { return dataset_1.DatasetSchema; } });
const evaluator_1 = require("./primitives/evaluator");
Object.defineProperty(exports, "EvaluationLevelSchema", { enumerable: true, get: function () { return evaluator_1.EvaluationLevelSchema; } });
const http_gateway_1 = require("./primitives/http-gateway");
const memory_1 = require("./primitives/memory");
Object.defineProperty(exports, "DEFAULT_EPISODIC_REFLECTION_NAMESPACES", { enumerable: true, get: function () { return memory_1.DEFAULT_EPISODIC_REFLECTION_NAMESPACES; } });
Object.defineProperty(exports, "DEFAULT_EPISODIC_REFLECTION_NAMESPACE_TEMPLATES", { enumerable: true, get: function () { return memory_1.DEFAULT_EPISODIC_REFLECTION_NAMESPACE_TEMPLATES; } });
Object.defineProperty(exports, "DEFAULT_STRATEGY_NAMESPACES", { enumerable: true, get: function () { return memory_1.DEFAULT_STRATEGY_NAMESPACES; } });
Object.defineProperty(exports, "DEFAULT_STRATEGY_NAMESPACE_TEMPLATES", { enumerable: true, get: function () { return memory_1.DEFAULT_STRATEGY_NAMESPACE_TEMPLATES; } });
Object.defineProperty(exports, "MemoryStrategySchema", { enumerable: true, get: function () { return memory_1.MemoryStrategySchema; } });
Object.defineProperty(exports, "MemoryStrategyTypeSchema", { enumerable: true, get: function () { return memory_1.MemoryStrategyTypeSchema; } });
const online_eval_config_1 = require("./primitives/online-eval-config");
const policy_1 = require("./primitives/policy");
Object.defineProperty(exports, "PolicyEngineSchema", { enumerable: true, get: function () { return policy_1.PolicyEngineSchema; } });
const tags_1 = require("./primitives/tags");
Object.defineProperty(exports, "TagsSchema", { enumerable: true, get: function () { return tags_1.TagsSchema; } });
const zod_util_1 = require("./zod-util");
const zod_1 = require("zod");
var online_eval_config_2 = require("./primitives/online-eval-config");
Object.defineProperty(exports, "OnlineEvalConfigSchema", { enumerable: true, get: function () { return online_eval_config_2.OnlineEvalConfigSchema; } });
Object.defineProperty(exports, "OnlineEvalConfigNameSchema", { enumerable: true, get: function () { return online_eval_config_2.OnlineEvalConfigNameSchema; } });
var evaluator_2 = require("./primitives/evaluator");
Object.defineProperty(exports, "BedrockModelIdSchema", { enumerable: true, get: function () { return evaluator_2.BedrockModelIdSchema; } });
Object.defineProperty(exports, "isValidBedrockModelId", { enumerable: true, get: function () { return evaluator_2.isValidBedrockModelId; } });
Object.defineProperty(exports, "EvaluatorNameSchema", { enumerable: true, get: function () { return evaluator_2.EvaluatorNameSchema; } });
Object.defineProperty(exports, "KMS_KEY_ARN_PATTERN", { enumerable: true, get: function () { return evaluator_2.KMS_KEY_ARN_PATTERN; } });
Object.defineProperty(exports, "isValidKmsKeyArn", { enumerable: true, get: function () { return evaluator_2.isValidKmsKeyArn; } });
var config_bundle_2 = require("./primitives/config-bundle");
Object.defineProperty(exports, "ConfigBundleNameSchema", { enumerable: true, get: function () { return config_bundle_2.ConfigBundleNameSchema; } });
Object.defineProperty(exports, "ComponentConfigurationMapSchema", { enumerable: true, get: function () { return config_bundle_2.ComponentConfigurationMapSchema; } });
var policy_2 = require("./primitives/policy");
Object.defineProperty(exports, "PolicyEngineNameSchema", { enumerable: true, get: function () { return policy_2.PolicyEngineNameSchema; } });
Object.defineProperty(exports, "PolicyNameSchema", { enumerable: true, get: function () { return policy_2.PolicyNameSchema; } });
Object.defineProperty(exports, "PolicySchema", { enumerable: true, get: function () { return policy_2.PolicySchema; } });
Object.defineProperty(exports, "ValidationModeSchema", { enumerable: true, get: function () { return policy_2.ValidationModeSchema; } });
var dataset_2 = require("./primitives/dataset");
Object.defineProperty(exports, "DatasetNameSchema", { enumerable: true, get: function () { return dataset_2.DatasetNameSchema; } });
Object.defineProperty(exports, "DatasetSchemaTypeSchema", { enumerable: true, get: function () { return dataset_2.DatasetSchemaTypeSchema; } });
var ab_test_2 = require("./primitives/ab-test");
Object.defineProperty(exports, "ABTestModeSchema", { enumerable: true, get: function () { return ab_test_2.ABTestModeSchema; } });
Object.defineProperty(exports, "TargetRefSchema", { enumerable: true, get: function () { return ab_test_2.TargetRefSchema; } });
Object.defineProperty(exports, "GatewayFilterSchema", { enumerable: true, get: function () { return ab_test_2.GatewayFilterSchema; } });
var http_gateway_2 = require("./primitives/http-gateway");
Object.defineProperty(exports, "HttpGatewayTargetSchema", { enumerable: true, get: function () { return http_gateway_2.HttpGatewayTargetSchema; } });
// ============================================================================
// ManagedBy Schema
// ============================================================================
exports.ManagedBySchema = zod_1.z.enum(['CDK']).default('CDK');
var mcp_2 = require("./mcp");
Object.defineProperty(exports, "AgentCoreGatewaySchema", { enumerable: true, get: function () { return mcp_2.AgentCoreGatewaySchema; } });
Object.defineProperty(exports, "AgentCoreGatewayTargetSchema", { enumerable: true, get: function () { return mcp_2.AgentCoreGatewayTargetSchema; } });
Object.defineProperty(exports, "AgentCoreMcpRuntimeToolSchema", { enumerable: true, get: function () { return mcp_2.AgentCoreMcpRuntimeToolSchema; } });
// ============================================================================
// Project Name Schema
// ============================================================================
// Project name is a CLI-only concept (combined with agent name to form the runtime name).
// Max 23 so that projectName + "_" + agentName fits within the 48-char runtime name limit.
exports.ProjectNameSchema = zod_1.z
    .string()
    .min(1, 'Project name is required')
    .max(23, 'Project name must be 23 characters or less')
    .regex(/^[A-Za-z][A-Za-z0-9]{0,22}$/, 'Project name must start with a letter and contain only alphanumeric characters')
    .refine(name => !(0, constants_1.isReservedProjectName)(name), {
    message: 'This name conflicts with a reserved package dependency. Please choose a different name.',
});
// ============================================================================
// Memory Schema
// ============================================================================
exports.MemoryTypeSchema = zod_1.z.literal('AgentCoreMemory');
// Memory names follow the same constraints as agent runtime names.
// https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_CreateMemory.html
exports.MemoryNameSchema = zod_1.z
    .string()
    .min(1, 'Name is required')
    .max(48)
    .regex(/^[a-zA-Z][a-zA-Z0-9_]{0,47}$/, 'Must begin with a letter and contain only alphanumeric characters and underscores (max 48 chars)');
exports.StreamContentLevelSchema = zod_1.z.enum(['FULL_CONTENT', 'METADATA_ONLY']);
// TODO: kinesis is currently the only supported delivery type. When additional types
// (e.g. S3, EventBridge) are added, this should become a discriminated union.
// Non-kinesis resources will produce a Zod error about the missing kinesis field.
exports.StreamDeliveryResourcesSchema = zod_1.z.object({
    resources: zod_1.z
        .array(zod_1.z.object({
        kinesis: zod_1.z.object({
            dataStreamArn: zod_1.z.string().min(1),
            contentConfigurations: zod_1.z
                .array(zod_1.z.object({
                type: zod_1.z.literal('MEMORY_RECORDS'),
                level: exports.StreamContentLevelSchema,
            }))
                .min(1),
        }),
    }))
        .min(1),
});
exports.IndexedKeyTypeSchema = zod_1.z.enum(['STRING', 'STRINGLIST', 'NUMBER']);
/**
 * Indexed metadata key declaration on a Memory.
 * Indexed keys enable filtering memory records on retrieval by attached metadata.
 *
 * Key pattern matches the AgentCore Control API: alphanumeric characters, whitespace,
 * and the symbols `. _ : / = + @ -` (max 128 chars).
 *
 * Note: indexed keys are append-only on the AWS service side — once added to a Memory,
 * a key cannot be removed. Reducing the array on update will fail at deploy time.
 */
exports.INDEXED_KEY_NAME_PATTERN = /^[a-zA-Z0-9\s._:/=+@-]+$/;
exports.INDEXED_KEY_NAME_PATTERN_MESSAGE = 'Must contain only alphanumeric characters, whitespace, or the symbols . _ : / = + @ -';
exports.MAX_INDEXED_KEY_NAME_LENGTH = 128;
exports.MAX_INDEXED_KEYS = 10;
exports.IndexedKeySchema = zod_1.z.object({
    key: zod_1.z
        .string()
        .min(1)
        .max(exports.MAX_INDEXED_KEY_NAME_LENGTH)
        .regex(exports.INDEXED_KEY_NAME_PATTERN, exports.INDEXED_KEY_NAME_PATTERN_MESSAGE)
        .refine(s => s.trim().length > 0, 'Key cannot be only whitespace'),
    type: exports.IndexedKeyTypeSchema,
});
exports.MemorySchema = zod_1.z
    .object({
    name: exports.MemoryNameSchema,
    eventExpiryDuration: zod_1.z.number().int().min(3).max(365),
    // Strategies array can be empty for short-term memory (just base memory with expiration)
    // Long-term memory includes strategies like SEMANTIC, SUMMARIZATION, USER_PREFERENCE
    strategies: zod_1.z
        .array(memory_1.MemoryStrategySchema)
        .default([])
        .superRefine((0, zod_util_1.uniqueBy)(strategy => strategy.type, type => `Duplicate memory strategy type: ${type}`)),
    indexedKeys: zod_1.z
        .array(exports.IndexedKeySchema)
        .max(exports.MAX_INDEXED_KEYS)
        .superRefine((0, zod_util_1.uniqueBy)(entry => entry.key, key => `Duplicate indexed key: ${key}`))
        .optional(),
    tags: tags_1.TagsSchema.optional(),
    encryptionKeyArn: zod_1.z.string().optional(),
    executionRoleArn: zod_1.z.string().optional(),
    streamDeliveryResources: exports.StreamDeliveryResourcesSchema.optional(),
})
    .superRefine((memory, ctx) => {
    // Indexed keys filter long-term memory records on retrieval; they have no
    // meaning on a short-term-only memory (no strategies => no LTM records).
    if (memory.indexedKeys && memory.indexedKeys.length > 0 && memory.strategies.length === 0) {
        ctx.addIssue({
            code: zod_1.z.ZodIssueCode.custom,
            path: ['indexedKeys'],
            message: 'indexedKeys requires at least one memory strategy (long-term memory)',
        });
    }
});
// ============================================================================
// Credential Schema
// ============================================================================
// https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_CreateApiKeyCredentialProvider.html
exports.CredentialNameSchema = zod_1.z
    .string()
    .min(1, 'Credential name is required')
    .max(128, 'Credential name must be 128 characters or less')
    .regex(/^[a-zA-Z0-9\-_]+$/, 'Must contain only alphanumeric characters, hyphens, and underscores (1-128 chars)');
exports.CredentialTypeSchema = zod_1.z.enum(['ApiKeyCredentialProvider', 'OAuthCredentialProvider']);
exports.ApiKeyCredentialSchema = zod_1.z.object({
    authorizerType: zod_1.z.literal('ApiKeyCredentialProvider'),
    name: exports.CredentialNameSchema,
});
exports.OAuthCredentialSchema = zod_1.z.object({
    authorizerType: zod_1.z.literal('OAuthCredentialProvider'),
    name: exports.CredentialNameSchema,
    /** OIDC discovery URL for the OAuth provider (optional for imported providers that already exist in Identity service) */
    discoveryUrl: zod_1.z.string().url().optional(),
    /** Scopes this credential provider supports */
    scopes: zod_1.z.array(zod_1.z.string()).optional(),
    /** Credential provider vendor type */
    vendor: zod_1.z.string().default('CustomOauth2'),
    /** Whether this credential was auto-created by the CLI (e.g., for CUSTOM_JWT inbound auth) */
    managed: zod_1.z.boolean().optional(),
    /** Whether this credential is used for inbound or outbound auth */
    usage: zod_1.z.enum(['inbound', 'outbound']).optional(),
});
exports.CredentialSchema = zod_1.z.discriminatedUnion('authorizerType', [exports.ApiKeyCredentialSchema, exports.OAuthCredentialSchema]);
// ============================================================================
// Evaluator Schema
// ============================================================================
exports.EvaluatorTypeSchema = zod_1.z.literal('CustomEvaluator');
exports.EvaluatorSchema = zod_1.z.object({
    name: evaluator_1.EvaluatorNameSchema,
    level: evaluator_1.EvaluationLevelSchema,
    description: zod_1.z.string().optional(),
    config: evaluator_1.EvaluatorConfigSchema,
    kmsKeyArn: evaluator_1.KmsKeyArnSchema.optional(),
    tags: tags_1.TagsSchema.optional(),
});
// ============================================================================
// Project Schema (Top Level)
// ============================================================================
const BUILTIN_EVALUATOR_PREFIX = 'Builtin.';
const ARN_PREFIX = 'arn:';
exports.AgentCoreProjectSpecSchema = zod_1.z
    .object({
    $schema: zod_1.z.string().optional(),
    name: exports.ProjectNameSchema,
    version: zod_1.z.number().int().min(1),
    managedBy: exports.ManagedBySchema,
    tags: tags_1.TagsSchema.optional(),
    runtimes: zod_1.z
        .array(agent_env_1.AgentEnvSpecSchema)
        .default([])
        .superRefine((0, zod_util_1.uniqueBy)(agent => agent.name, name => `Duplicate agent name: ${name}`)),
    memories: zod_1.z
        .array(exports.MemorySchema)
        .default([])
        .superRefine((0, zod_util_1.uniqueBy)(memory => memory.name, name => `Duplicate memory name: ${name}`)),
    credentials: zod_1.z
        .array(exports.CredentialSchema)
        .default([])
        .superRefine((0, zod_util_1.uniqueBy)(credential => credential.name, name => `Duplicate credential name: ${name}`)),
    evaluators: zod_1.z
        .array(exports.EvaluatorSchema)
        .default([])
        .superRefine((0, zod_util_1.uniqueBy)(evaluator => evaluator.name, name => `Duplicate evaluator name: ${name}`)),
    onlineEvalConfigs: zod_1.z
        .array(online_eval_config_1.OnlineEvalConfigSchema)
        .default([])
        .superRefine((0, zod_util_1.uniqueBy)(config => config.name, name => `Duplicate online eval config name: ${name}`)),
    // MCP / Gateway resources (previously in mcp.json)
    agentCoreGateways: zod_1.z
        .array(mcp_1.AgentCoreGatewaySchema)
        .default([])
        .superRefine((0, zod_util_1.uniqueBy)(gateway => gateway.name, name => `Duplicate gateway name: ${name}`)),
    mcpRuntimeTools: zod_1.z
        .array(mcp_1.AgentCoreMcpRuntimeToolSchema)
        .optional()
        .superRefine((tools, ctx) => {
        if (!tools)
            return;
        (0, zod_util_1.uniqueBy)((tool) => tool.name, (name) => `Duplicate MCP runtime tool name: ${name}`)(tools, ctx);
    }),
    unassignedTargets: zod_1.z
        .array(mcp_1.AgentCoreGatewayTargetSchema)
        .optional()
        .superRefine((targets, ctx) => {
        if (!targets)
            return;
        (0, zod_util_1.uniqueBy)((target) => target.name, (name) => `Duplicate unassigned target name: ${name}`)(targets, ctx);
    }),
    policyEngines: zod_1.z
        .array(policy_1.PolicyEngineSchema)
        .default([])
        .superRefine((0, zod_util_1.uniqueBy)(engine => engine.name, name => `Duplicate policy engine name: ${name}`)),
    configBundles: zod_1.z
        .array(config_bundle_1.ConfigBundleSchema)
        .default([])
        .superRefine((0, zod_util_1.uniqueBy)(bundle => bundle.name, name => `Duplicate config bundle name: ${name}`)),
    abTests: zod_1.z
        .array(ab_test_1.ABTestSchema)
        .default([])
        .superRefine((0, zod_util_1.uniqueBy)(test => test.name, name => `Duplicate AB test name: ${name}`)),
    httpGateways: zod_1.z
        .array(http_gateway_1.HttpGatewaySchema)
        .default([])
        .superRefine((0, zod_util_1.uniqueBy)(gw => gw.name, name => `Duplicate HTTP gateway name: ${name}`)),
    datasets: zod_1.z
        .array(dataset_1.DatasetSchema)
        .optional()
        .superRefine((val, ctx) => {
        if (!val)
            return;
        const seen = new Set();
        for (const dataset of val) {
            if (seen.has(dataset.name)) {
                ctx.addIssue({ code: zod_1.z.ZodIssueCode.custom, message: `Duplicate dataset name: ${dataset.name}` });
            }
            seen.add(dataset.name);
        }
    }),
})
    .strict()
    .superRefine((spec, ctx) => {
    const agentNames = new Set(spec.runtimes.map(a => a.name));
    const evaluatorNames = new Set(spec.evaluators.map(e => e.name));
    for (const config of spec.onlineEvalConfigs) {
        // Validate agent reference
        if (!agentNames.has(config.agent)) {
            ctx.addIssue({
                code: zod_1.z.ZodIssueCode.custom,
                message: `Online eval config "${config.name}" references unknown agent "${config.agent}"`,
            });
        }
        // Validate evaluator references
        for (const evalName of config.evaluators) {
            // Skip built-in evaluators and ARN references (externally managed)
            if (evalName.startsWith(BUILTIN_EVALUATOR_PREFIX) || evalName.startsWith(ARN_PREFIX))
                continue;
            if (!evaluatorNames.has(evalName)) {
                ctx.addIssue({
                    code: zod_1.z.ZodIssueCode.custom,
                    message: `Online eval config "${config.name}" references unknown evaluator "${evalName}"`,
                });
            }
        }
    }
    // Validate HTTP gateway runtimeRef references
    for (const gw of spec.httpGateways ?? []) {
        const runtimeExists = spec.runtimes.some(r => r.name === gw.runtimeRef);
        if (!runtimeExists) {
            ctx.addIssue({
                code: zod_1.z.ZodIssueCode.custom,
                message: `HTTP gateway "${gw.name}" references unknown runtime "${gw.runtimeRef}"`,
            });
        }
    }
    // Validate AB test gateway references
    for (const test of spec.abTests ?? []) {
        const gwField = test.gatewayRef;
        if (gwField && typeof gwField === 'string') {
            const match = /^\{\{gateway:(.+)\}\}$/.exec(gwField);
            if (match) {
                const gwName = match[1];
                const gwExists = (spec.httpGateways ?? []).some(gw => gw.name === gwName);
                if (!gwExists) {
                    ctx.addIssue({
                        code: zod_1.z.ZodIssueCode.custom,
                        message: `AB test "${test.name}" references gateway "${gwName}" which does not exist in httpGateways`,
                    });
                }
                // For target-based AB tests, validate target names exist in the gateway's targets array
                if (test.mode === 'target-based') {
                    const gw = (spec.httpGateways ?? []).find(g => g.name === gwName);
                    if (gw) {
                        const gwTargetNames = new Set((gw.targets ?? []).map(t => t.name));
                        for (const variant of test.variants) {
                            const targetName = variant.variantConfiguration.target?.targetName;
                            if (targetName && !gwTargetNames.has(targetName)) {
                                ctx.addIssue({
                                    code: zod_1.z.ZodIssueCode.custom,
                                    message: `AB test "${test.name}" variant "${variant.name}" references target "${targetName}" which does not exist in gateway "${gwName}" targets`,
                                });
                            }
                        }
                    }
                }
            }
        }
    }
    // Validate HTTP gateway target runtimeRef and qualifier references
    for (const gw of spec.httpGateways ?? []) {
        for (const target of gw.targets ?? []) {
            const runtime = spec.runtimes.find(r => r.name === target.runtimeRef);
            if (!runtime) {
                ctx.addIssue({
                    code: zod_1.z.ZodIssueCode.custom,
                    message: `HTTP gateway "${gw.name}" target "${target.name}" references unknown runtime "${target.runtimeRef}"`,
                });
            }
            else if (target.qualifier && target.qualifier !== 'DEFAULT' && !runtime.endpoints?.[target.qualifier]) {
                ctx.addIssue({
                    code: zod_1.z.ZodIssueCode.custom,
                    message: `HTTP gateway "${gw.name}" target "${target.name}" references qualifier "${target.qualifier}" which is not an endpoint on runtime "${target.runtimeRef}"`,
                });
            }
        }
    }
});
//# sourceMappingURL=agentcore-project.js.map