diff --git a/context7.json b/context7.json new file mode 100644 index 000000000..e425670a0 --- /dev/null +++ b/context7.json @@ -0,0 +1,13 @@ +{ + "$schema": "https://context7.com/schema/context7.json", + "projectTitle": "Frigg Framework", + "description": "Open-source, serverless-native framework for building direct/native integrations, maintained by Left Hook.", + "branch": "next", + "folders": ["docs"], + "excludeFolders": ["website", "node_modules", "**/dist", "**/__tests__"], + "rules": [ + "Frigg is serverless-native (AWS Lambda) and cloud-agnostic; adopters own their stack.", + "Integrations extend IntegrationBase; API modules are installed with `frigg install `.", + "The authoritative API-module catalog and roadmap live at /roadmap/ on friggframework.org." + ] +} diff --git a/website/friggframework-api/assistant.mjs b/website/friggframework-api/assistant.mjs index 52d9a337e..81fa8a27c 100644 --- a/website/friggframework-api/assistant.mjs +++ b/website/friggframework-api/assistant.mjs @@ -199,6 +199,13 @@ Rules: ANY question about specific ADRs, API modules, catalog counts, or what's built vs. planned, call the tool and answer from what it returns — do not guess or recite from memory. Everything else is grounded in the reference below. +- You may also have live documentation/source tools whose names end in + "_list_tools" and "_call_tool" (e.g. frigg-docs for the Frigg docs, frigg-repo + for the repository on the next branch). When present, use them for deep, + technical, or how-does-the-code-work questions the reference doesn't cover: + call the "_list_tools" one to see what a source offers, then "_call_tool" to + fetch, and answer from the result rather than guessing. If they're absent, just + rely on the reference and point to the docs. - If something isn't covered by a tool or the reference, say so plainly and point to the docs (https://docs.friggframework.org), the GitHub repo, or /roadmap/ rather than inventing specifics. diff --git a/website/friggframework-api/lib/freya-runtime.mjs b/website/friggframework-api/lib/freya-runtime.mjs index 22a447ec7..5062c2d68 100644 --- a/website/friggframework-api/lib/freya-runtime.mjs +++ b/website/friggframework-api/lib/freya-runtime.mjs @@ -1,2714 +1,73 @@ // GENERATED — vendored Freya runtime. Do not edit by hand. // Regenerate via website/tools/freya-vendor/build.mjs. - -// ../freya/packages/core/dist/domain/model/Agent.js -function createAgent(config, deploymentId) { - return { - id: config.id, - config, - deploymentId, - createdAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date() - }; -} - -// ../freya/packages/core/dist/domain/model/Session.js -function createSession(id, agentId, userId, transportId) { - return { - id, - agentId, - userId, - transportId, - messages: [], - status: "active", - turnCount: 0, - createdAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date(), - metadata: {} - }; -} -function addMessage(session, message) { - return { - ...session, - messages: [...session.messages, message], - turnCount: message.role === "assistant" ? session.turnCount + 1 : session.turnCount, - updatedAt: /* @__PURE__ */ new Date() - }; -} - -// ../freya/packages/core/dist/domain/model/Message.js -function createUserMessage(id, content, transportOrigin) { - return { - id, - role: "user", - content, - timestamp: /* @__PURE__ */ new Date(), - transportOrigin, - metadata: {} - }; -} -function createAssistantMessage(id, content, toolInvocations) { - return { - id, - role: "assistant", - content, - timestamp: /* @__PURE__ */ new Date(), - transportOrigin: "agent", - toolInvocations, - metadata: {} - }; -} - -// ../freya/packages/core/dist/domain/events/DomainEvent.js -function createEvent(id, type, agentId, payload, sessionId) { - return { id, type, timestamp: /* @__PURE__ */ new Date(), agentId, sessionId, payload }; -} - -// ../freya/packages/core/dist/domain/services/ContextBuilderService.js -function buildContext(params) { - const { config, ontology, memories, messages, tools, ontologyRenderer, transport } = params; - const parts = []; - parts.push(config.systemPrompt); - if (transport) { - parts.push(` - -[Channel: ${transport}]`); - } - const ontologyText = ontologyRenderer.render(ontology); - if (ontologyText && ontology.entityTypes.length > 0) { - parts.push("\n---\n"); - parts.push(ontologyText); - } - if (memories.length > 0) { - parts.push("\n---\n# Relevant Context from Memory\n"); - for (const memory of memories) { - parts.push(`[${memory.entityType}] ${memory.content}`); - } - } - const systemPrompt = parts.join("\n"); - const systemTokens = Math.ceil(systemPrompt.length / 4); - const messageTokens = messages.reduce((sum, m) => sum + Math.ceil(m.content.length / 4), 0); - const toolTokens = tools.reduce((sum, t) => sum + Math.ceil(JSON.stringify(t.inputSchema).length / 4), 0); - return { - systemPrompt, - messages, - tools, - tokenEstimate: systemTokens + messageTokens + toolTokens - }; -} - -// ../freya/packages/core/dist/domain/services/ModelPricingService.js -var MODEL_PRICING_PER_1M_TOKENS = { - "claude-sonnet-4-6": [3, 15], - "claude-opus-4-6": [15, 75], - "claude-haiku-4-5-20251001": [0.25, 1.25], - // Bedrock-prefixed deployment-surface ids. Real Bedrock model-id - // strings vary by AWS region and may carry different date suffixes — - // callers should normalize before calling, or unknown ids will return - // 0 (callers can detect via `isKnownPricedModel`). - "anthropic.claude-sonnet-4-6-20251022-v1:0": [3, 15], - "anthropic.claude-opus-4-6-20251022-v1:0": [15, 75], - "anthropic.claude-haiku-4-5-20251001-v1:0": [0.25, 1.25] -}; -var CACHE_WRITE_MULTIPLIER = 1.25; -var CACHE_READ_MULTIPLIER = 0.1; -function estimateCostUSD(modelId, usageOrInputTokens, outputTokens) { - const usage = typeof usageOrInputTokens === "number" ? { inputTokens: usageOrInputTokens, outputTokens: outputTokens ?? 0 } : usageOrInputTokens; - const rates = MODEL_PRICING_PER_1M_TOKENS[modelId]; - if (!rates) - return 0; - const [inputRate, outputRate] = rates; - const safe = (v) => Math.max(0, Number.isFinite(v) ? v : 0); - const safeInput = safe(usage.inputTokens); - const safeOutput = safe(usage.outputTokens); - const safeCacheRead = safe(usage.cacheReadTokens); - const safeCacheWrite = safe(usage.cacheWriteTokens); - const totalUsdPer1M = safeInput * inputRate + safeOutput * outputRate + safeCacheRead * inputRate * CACHE_READ_MULTIPLIER + safeCacheWrite * inputRate * CACHE_WRITE_MULTIPLIER; - return totalUsdPer1M / 1e6; -} - -// ../freya/packages/core/dist/domain/services/TurnBudgetService.js -var LEGACY_INPUT_RATE_PER_1K = 3e-3; -var LEGACY_OUTPUT_RATE_PER_1K = 0.015; -function createBudgetTracker(budget, optionsOrClock = {}) { - const options = "now" in optionsOrClock && typeof optionsOrClock.now === "function" ? { clock: optionsOrClock } : optionsOrClock; - const clock = options.clock ?? { now: () => Date.now() }; - const modelId = options.modelId; - let calls = 0; - let totalTokens = 0; - let totalInputTokens = 0; - let totalOutputTokens = 0; - let totalCacheReadTokens = 0; - let totalCacheWriteTokens = 0; - const startTime = clock.now(); - const sanitize = (v) => Math.max(0, Number.isFinite(v) ? v : 0); - return { - recordCall(usage) { - calls++; - const inputTokens = sanitize(usage.inputTokens); - const outputTokens = sanitize(usage.outputTokens); - const cacheReadTokens = sanitize(usage.cacheReadTokens); - const cacheWriteTokens = sanitize(usage.cacheWriteTokens); - totalInputTokens += inputTokens; - totalOutputTokens += outputTokens; - totalCacheReadTokens += cacheReadTokens; - totalCacheWriteTokens += cacheWriteTokens; - totalTokens += inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens; - }, - isExhausted() { - return this.getStatus().exhausted; - }, - getStatus() { - const elapsedMs = clock.now() - startTime; - const estimatedCostUsd = modelId !== void 0 ? estimateCostUSD(modelId, { - inputTokens: totalInputTokens, - outputTokens: totalOutputTokens, - cacheReadTokens: totalCacheReadTokens, - cacheWriteTokens: totalCacheWriteTokens - }) : totalInputTokens * LEGACY_INPUT_RATE_PER_1K / 1e3 + totalOutputTokens * LEGACY_OUTPUT_RATE_PER_1K / 1e3; - let exhausted = false; - let exhaustedReason; - if (budget.maxCalls !== void 0 && calls >= budget.maxCalls) { - exhausted = true; - exhaustedReason = `LLM call limit reached (${calls}/${budget.maxCalls})`; - } else if (budget.maxTokens !== void 0 && totalTokens >= budget.maxTokens) { - exhausted = true; - exhaustedReason = `Token limit reached (${totalTokens}/${budget.maxTokens})`; - } else if (budget.maxTimeMs !== void 0 && elapsedMs >= budget.maxTimeMs) { - exhausted = true; - exhaustedReason = `Time limit reached (${elapsedMs}ms/${budget.maxTimeMs}ms)`; - } else if (budget.maxCostUsd !== void 0 && estimatedCostUsd >= budget.maxCostUsd) { - exhausted = true; - exhaustedReason = `Cost limit reached ($${estimatedCostUsd.toFixed(4)}/$${budget.maxCostUsd})`; - } - return { - calls, - tokens: totalTokens, - timeMs: elapsedMs, - estimatedCostUsd, - exhausted, - ...exhaustedReason ? { exhaustedReason } : {} - }; - } - }; -} -function budgetFromMaxTurns(maxTurns) { - return { maxCalls: maxTurns }; -} - -// ../freya/packages/core/dist/domain/services/HooksService.js -var DEFAULT_PRIORITY = 100; -var InMemoryHookRegistry = class { - byPhase = /* @__PURE__ */ new Map(); - register(hook) { - const list = this.byPhase.get(hook.phase) ?? []; - if (list.some((h) => h.name === hook.name)) { - throw new Error(`Hook with name "${hook.name}" is already registered for phase "${hook.phase}"`); - } - list.push(hook); - this.byPhase.set(hook.phase, list); - } - unregister(name) { - for (const [phase, list] of this.byPhase) { - const filtered = list.filter((h) => h.name !== name); - if (filtered.length !== list.length) { - this.byPhase.set(phase, filtered); - } - } - } - hooksFor(phase) { - const list = this.byPhase.get(phase) ?? []; - const sorted = [...list].sort((a, b) => (a.priority ?? DEFAULT_PRIORITY) - (b.priority ?? DEFAULT_PRIORITY)); - return sorted; - } -}; -var HookExecutionError = class extends Error { - hookName; - phase; - cause; - constructor(hookName, phase, cause) { - const message = cause instanceof Error ? cause.message : String(cause); - super(`Hook "${hookName}" failed in phase "${phase}": ${message}`); - this.hookName = hookName; - this.phase = phase; - this.cause = cause; - this.name = "HookExecutionError"; - } -}; -function makeFireHook(deps) { - const annotate = deps.onAnnotation ?? (() => { - }); - return async function fire(phase, initialPayload) { - const hooks = deps.registry.hooksFor(phase); - let payload = initialPayload; - for (const hook of hooks) { - const ctx = { - phase, - agent: deps.agent, - sessionId: deps.sessionId, - turnId: deps.turnId, - userContext: deps.userContext, - payload, - emit: deps.onEvent, - annotate - }; - let outcome; - try { - outcome = await hook.run(ctx); - } catch (err) { - throw new HookExecutionError(hook.name, phase, err); - } - if (outcome.kind === "short_circuit") { - deps.onEvent(createEvent(crypto.randomUUID(), "turn.short_circuited", deps.agent.id, { hookName: hook.name, phase, reason: outcome.reason }, deps.sessionId)); - return { - payload, - shortCircuited: true, - correctionRequested: false, - reason: outcome.reason, - finalResponse: outcome.finalResponse, - hookName: hook.name - }; - } - if (outcome.kind === "request_correction") { - if (phase !== "pre_capture") { - throw new HookExecutionError(hook.name, phase, new Error(`request_correction outcome is only valid from "pre_capture", got "${phase}"`)); - } - return { - payload, - shortCircuited: false, - correctionRequested: true, - correctionPrompt: outcome.correctionPrompt, - hookName: hook.name - }; - } - if (outcome.payload) { - payload = { ...payload, ...outcome.payload }; - } - } - return { - payload, - shortCircuited: false, - correctionRequested: false - }; - }; -} - -// ../freya/packages/core/dist/domain/services/OntologyValidationService.js -function parseResponseForClaims(content, ontology) { - if (ontology.entityTypes.length === 0) - return []; - const claims = []; - for (const entityType of ontology.entityTypes) { - const entityName = entityType.name; - const pattern = new RegExp(`\\b${escapeRegex(entityName)}\\b`, "gi"); - const matches2 = [...content.matchAll(pattern)]; - if (matches2.length === 0) - continue; - for (const match of matches2) { - const matchIndex = match.index; - const windowStart = Math.max(0, matchIndex - 20); - const windowEnd = Math.min(content.length, matchIndex + entityName.length + 200); - const window = content.slice(windowStart, windowEnd); - const properties = extractProperties(window, entityType); - claims.push({ - text: window.trim(), - entityType: entityName, - properties: Object.keys(properties).length > 0 ? properties : void 0 - }); - } - } - return claims; -} -function extractProperties(text, entityType) { - const properties = {}; - for (const prop of entityType.properties) { - const patterns = [ - new RegExp(`\\b${escapeRegex(prop.name)}\\s+(?:is|:|=)\\s+(\\S+)`, "i"), - new RegExp(`\\b${escapeRegex(prop.name)}\\s+(\\S+)`, "i") - ]; - for (const pattern of patterns) { - const match = text.match(pattern); - if (match) { - const value = match[1].replace(/[.,;!?)]+$/, ""); - if (value) { - properties[prop.name] = value; - break; - } - } - } - } - return properties; -} -function validateClaims(claims, ontology) { - const result = { - valid: [], - fixable: [], - friction: [] - }; - for (const claim of claims) { - validateSingleClaim(claim, ontology, result); - } - return result; -} -function validateSingleClaim(claim, ontology, result) { - const entityResolution = resolveEntityType(claim.entityType, ontology); - if (entityResolution.status === "unknown") { - result.friction.push({ - claim, - frictionType: "unknown_entity", - context: `Entity type "${claim.entityType}" is not defined in the ontology. Known types: ${ontology.entityTypes.map((e) => e.name).join(", ")}` - }); - return; - } - if (entityResolution.status === "fixable") { - result.fixable.push({ - claim, - suggestion: `Use "${entityResolution.resolved.name}" instead of "${claim.entityType}"` - }); - return; - } - const resolvedEntity = entityResolution.resolved; - if (!claim.properties || Object.keys(claim.properties).length === 0) { - result.valid.push(claim); - return; - } - let hasIssue = false; - for (const [propName, propValue] of Object.entries(claim.properties)) { - const propResolution = resolveProperty(propName, propValue, resolvedEntity); - if (propResolution.status === "fixable") { - result.fixable.push({ - claim, - suggestion: propResolution.suggestion - }); - hasIssue = true; - break; - } - if (propResolution.status === "unknown_property") { - result.friction.push({ - claim, - frictionType: "unknown_property", - context: `Property "${propName}" does not exist on entity type "${resolvedEntity.name}". Known properties: ${resolvedEntity.properties.map((p) => p.name).join(", ")}`, - propertyName: propName, - availableProperties: resolvedEntity.properties.map((p) => p.name) - }); - hasIssue = true; - continue; - } - if (propResolution.status === "invalid_value") { - const matchedProp = resolvedEntity.properties.find((p) => p.name === propName) ?? resolvedEntity.properties.find((p) => p.name.toLowerCase() === propName.toLowerCase()); - result.friction.push({ - claim, - frictionType: "invalid_value", - context: propResolution.context, - propertyName: propName, - allowedValues: matchedProp?.enumValues ?? [] - }); - hasIssue = true; - continue; - } - } - if (!hasIssue) { - result.valid.push(claim); - } -} -function resolveEntityType(claimedType, ontology) { - if (!claimedType) - return { status: "exact" }; - const exact = ontology.entityTypes.find((e) => e.name === claimedType); - if (exact) - return { status: "exact", resolved: exact }; - const caseMatch = ontology.entityTypes.find((e) => e.name.toLowerCase() === claimedType.toLowerCase()); - if (caseMatch) - return { status: "exact", resolved: caseMatch }; - for (const entity of ontology.entityTypes) { - const claimedLower = claimedType.toLowerCase(); - const entityLower = entity.name.toLowerCase(); - if (claimedLower.includes(entityLower) || entityLower.includes(claimedLower)) { - return { status: "fixable", resolved: entity }; - } - } - for (const entity of ontology.entityTypes) { - if (editDistance(claimedType.toLowerCase(), entity.name.toLowerCase()) <= 2) { - return { status: "fixable", resolved: entity }; - } - } - return { status: "unknown" }; -} -function resolveProperty(propName, propValue, entityType) { - const exact = entityType.properties.find((p) => p.name === propName); - if (exact) { - return validatePropertyValue(exact, propValue, entityType); - } - const caseMatch = entityType.properties.find((p) => p.name.toLowerCase() === propName.toLowerCase()); - if (caseMatch) { - return validatePropertyValue(caseMatch, propValue, entityType); - } - for (const prop of entityType.properties) { - if (editDistance(propName.toLowerCase(), prop.name.toLowerCase()) <= 2) { - return { - status: "fixable", - suggestion: `Use property "${prop.name}" instead of "${propName}" on entity type "${entityType.name}"` - }; - } - } - return { status: "unknown_property" }; -} -function validatePropertyValue(prop, value, entityType) { - if (prop.type === "enum" && prop.enumValues) { - const lowerValue = value.toLowerCase(); - const match = prop.enumValues.find((v) => v.toLowerCase() === lowerValue); - if (!match) { - return { - status: "invalid_value", - context: `Property "${prop.name}" on "${entityType.name}" only allows: ${prop.enumValues.join(", ")}. Got: "${value}"` - }; - } - } - return { status: "valid" }; -} -function editDistance(a, b) { - if (a.length === 0) - return b.length; - if (b.length === 0) - return a.length; - const matrix = []; - for (let i = 0; i <= b.length; i++) { - matrix[i] = [i]; - } - for (let j = 0; j <= a.length; j++) { - matrix[0][j] = j; - } - for (let i = 1; i <= b.length; i++) { - for (let j = 1; j <= a.length; j++) { - if (b[i - 1] === a[j - 1]) { - matrix[i][j] = matrix[i - 1][j - 1]; - } else { - matrix[i][j] = Math.min( - matrix[i - 1][j - 1] + 1, - // substitution - matrix[i][j - 1] + 1, - // insertion - matrix[i - 1][j] + 1 - ); - } - } - } - return matrix[b.length][a.length]; -} -function escapeRegex(str) { - return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -} - -// ../freya/packages/core/dist/domain/services/MemoryCaptureService.js -var DEFAULT_CAPTURE_CONFIDENCE_THRESHOLD = 0.7; -var HEDGE_PATTERN = new RegExp([ - "\\bmight\\b", - "\\bmaybe\\b", - "\\bperhaps\\b", - "\\bpossibly\\b", - "\\bI\\s+think\\b", - "\\bI\\s+believe\\b", - "\\bnot\\s+sure\\b", - "\\bnot\\s+certain\\b", - "\\bprobably\\b", - "\\bunlikely\\b", - "\\bsomewhat\\b", - "\\bsort\\s+of\\b", - "\\bkind\\s+of\\b", - "\\bappears\\s+to\\b", - "\\bseems\\s+to\\b", - "\\bcould\\s+be\\b" -].join("|"), "gi"); -var HEDGE_PENALTY_PER_MATCH = 0.15; -var MAX_HEDGE_PENALTY_MATCHES = 3; -var CONFIDENCE_FLOOR = 0.1; -function countHedgeMarkers(text) { - if (!text) - return 0; - const matches2 = text.match(HEDGE_PATTERN); - if (!matches2) - return 0; - return Math.min(matches2.length, MAX_HEDGE_PENALTY_MATCHES); -} -function scoreClaimConfidence(claim) { - const propCount = claim.properties ? Object.keys(claim.properties).length : 0; - const propertyScore = 0.5 + 0.1 * Math.min(propCount, 5); - const hedgeCount = countHedgeMarkers(claim.text); - const hedgePenalty = HEDGE_PENALTY_PER_MATCH * hedgeCount; - const raw = propertyScore - hedgePenalty; - return Math.min(1, Math.max(CONFIDENCE_FLOOR, raw)); -} -function coerceStructured(claim, entityType) { - const structured = {}; - if (!claim.properties) - return structured; - for (const [k, v] of Object.entries(claim.properties)) { - const prop = entityType.properties.find((p) => p.name === k || p.name.toLowerCase() === k.toLowerCase()); - if (!prop) { - structured[k] = v; - continue; - } - if (prop.type === "number") { - const n = Number(v); - structured[prop.name] = Number.isFinite(n) ? n : v; - } else if (prop.type === "boolean") { - const lv = v.toLowerCase(); - if (lv === "true") - structured[prop.name] = true; - else if (lv === "false") - structured[prop.name] = false; - else - structured[prop.name] = v; - } else { - structured[prop.name] = v; - } - } - return structured; -} -function extractMemoriesFromResponse(params) { - const { response, ontology, agent, sessionId, turnId } = params; - if (ontology.entityTypes.length === 0 || response.length === 0) { - return { toCapture: [], dropped: [] }; - } - const threshold = agent.config.captureConfidenceThreshold ?? DEFAULT_CAPTURE_CONFIDENCE_THRESHOLD; - const claims = parseResponseForClaims(response, ontology); - if (claims.length === 0) { - return { toCapture: [], dropped: [] }; - } - const { valid } = validateClaims(claims, ontology); - const toCapture = []; - const dropped = []; - const dedupKeys = /* @__PURE__ */ new Set(); - for (const claim of valid) { - if (!claim.entityType) - continue; - const entity = ontology.entityTypes.find((e) => e.name === claim.entityType); - if (!entity) - continue; - const confidence = scoreClaimConfidence(claim); - const structured = coerceStructured(claim, entity); - const content = claim.text; - const lookup = pickPredecessorLookup(structured, entity); - const dedupKey = lookup ? `${entity.name}::${lookup.key}::${stringifyLookupValue(lookup.value)}` : `${entity.name}::__no_key__::${content}`; - if (dedupKeys.has(dedupKey)) - continue; - dedupKeys.add(dedupKey); - if (confidence < threshold) { - dropped.push({ - entityType: entity.name, - content, - confidence, - threshold, - reason: "low_confidence", - ...Object.keys(structured).length > 0 ? { structured } : {} - }); - continue; - } - const missingRequired = entity.properties.find((p) => p.required && !(p.name in structured)); - if (missingRequired) { - dropped.push({ - entityType: entity.name, - content, - confidence, - threshold, - reason: "missing_required_property", - ...Object.keys(structured).length > 0 ? { structured } : {} - }); - continue; - } - const source = { - type: "auto_capture", - sessionId, - turnId, - // Auditing handle: include the agent's id so "who captured this" - // is recoverable from `source.author` without joining via agentId. - author: `memory-capture-service:${agent.id}` - }; - toCapture.push({ - id: crypto.randomUUID(), - agentId: agent.id, - scope: "namespace", - scopeId: agent.config.memoryNamespaces[0] ?? "default", - entityType: entity.name, - content, - structured, - confidence, - source, - status: "active", - portable: false, - createdAt: /* @__PURE__ */ new Date(), - version: 1 - }); - } - return { toCapture, dropped }; -} -function pickPredecessorLookup(structured, entityType) { - const candidates = predecessorLookupCandidates(structured, entityType); - return candidates[0] ?? null; -} -function predecessorLookupCandidates(structured, entityType) { - const out = []; - if ("id" in structured && isPrimitive(structured.id)) { - out.push({ key: "id", value: structured.id }); - } - const keys = Object.keys(structured).sort(); - for (const k of keys) { - if (k === "id") - continue; - const v = structured[k]; - if (!isPrimitive(v)) - continue; - if (entityType) { - const prop = entityType.properties.find((p) => p.name === k || p.name.toLowerCase() === k.toLowerCase()); - if (prop && prop.type === "enum") - continue; - } - out.push({ key: k, value: v }); - } - return out; -} -function isPrimitive(v) { - return typeof v === "string" || typeof v === "number" || typeof v === "boolean"; -} -function stringifyLookupValue(v) { - if (typeof v === "string") - return v.toLowerCase(); - return String(v); -} -async function findPredecessor(candidate, memory, ontology) { - const entityType = ontology?.entityTypes.find((e) => e.name === candidate.entityType); - const lookups = predecessorLookupCandidates(candidate.structured, entityType); - if (lookups.length === 0) - return { kind: "none" }; - let entries; - try { - entries = await memory.getByEntityType(candidate.agentId, candidate.entityType); - } catch { - return { kind: "none" }; - } - const sameScope = entries.filter((e) => e.scope === candidate.scope && e.scopeId === candidate.scopeId); - const candidateId = candidate.structured.id; - const candidateHasPrimitiveId = isPrimitive(candidateId); - for (const lookup of lookups) { - const target = stringifyLookupValue(lookup.value); - const matches2 = sameScope.filter((e) => { - if (e.id === candidate.id) - return false; - if (e.status !== "active") - return false; - const v = e.structured[lookup.key]; - if (v === void 0 || !isPrimitive(v) || stringifyLookupValue(v) !== target) - return false; - if (lookup.key !== "id" && candidateHasPrimitiveId) { - const eId = e.structured.id; - if (isPrimitive(eId) && stringifyLookupValue(eId) !== stringifyLookupValue(candidateId)) { - return false; - } - } - return true; - }); - if (matches2.length === 0) - continue; - const sorted = [...matches2].sort((a, b) => { - const dt = b.createdAt.getTime() - a.createdAt.getTime(); - if (dt !== 0) - return dt; - const dv = (b.version ?? 0) - (a.version ?? 0); - if (dv !== 0) - return dv; - return a.id.localeCompare(b.id); - }); - if (sorted.length >= 2) { - return { kind: "ambiguous", entries: sorted }; - } - return { kind: "one", entry: sorted[0] }; - } - return { kind: "none" }; -} -async function captureFromResponse(params) { - const { memory, ...rest } = params; - const { toCapture, dropped } = extractMemoriesFromResponse(rest); - const captured = []; - const errors = []; - const frictionEvents = []; - const availableEntityTypes = rest.ontology.entityTypes.map((e) => e.name); - for (const candidate of toCapture) { - try { - const predecessor = await findPredecessor(candidate, memory, rest.ontology); - await memory.store(candidate); - captured.push(candidate); - switch (predecessor.kind) { - case "none": - break; - case "one": { - try { - await memory.supersede(predecessor.entry.id, candidate.id); - } catch (err) { - errors.push(`supersede(${predecessor.entry.id} \u2192 ${candidate.id}) failed: ${err instanceof Error ? err.message : String(err)}`); +var Vk=Object.defineProperty;var q=(e,t)=>()=>(e&&(t=e(e=0)),t);var nr=(e,t)=>{for(var r in t)Vk(e,r,{get:t[r],enumerable:!0})};var iE,sc,aE,sE,cE,uE,H,Zy,lE,cc,cp=q(()=>{iE=Object.create,sc=Object.defineProperty,aE=Object.getOwnPropertyDescriptor,sE=Object.getOwnPropertyNames,cE=Object.getPrototypeOf,uE=Object.prototype.hasOwnProperty,H=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Zy=(e,t)=>{let r={};for(var n in e)sc(r,n,{get:e[n],enumerable:!0});return t&&sc(r,Symbol.toStringTag,{value:"Module"}),r},lE=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(var o=sE(t),i=0,a=o.length,s;it[c]).bind(null,s),enumerable:!(n=aE(t,s))||n.enumerable});return e},cc=(e,t,r)=>(r=e!=null?iE(cE(e)):{},lE(t||!e||!e.__esModule?sc(r,"default",{value:e,enumerable:!0}):r,e))});function C(e,t,r){function n(s,c){if(s._zod||Object.defineProperty(s,"_zod",{value:{def:c,constr:a,traits:new Set},enumerable:!1}),s._zod.traits.has(e))return;s._zod.traits.add(e),t(s,c);let u=a.prototype,l=Object.keys(u);for(let d=0;dr?.Parent&&s instanceof r.Parent?!0:s?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}function lt(e){return e&&Object.assign(uc,e),uc}var up,ir,En,uc,yo=q(()=>{up=Object.freeze({status:"aborted"});ir=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},En=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}},uc={}});var G={};nr(G,{BIGINT_FORMAT_RANGES:()=>vp,Class:()=>dp,NUMBER_FORMAT_RANGES:()=>yp,aborted:()=>Kr,allowsEval:()=>fp,assert:()=>hE,assertEqual:()=>dE,assertIs:()=>mE,assertNever:()=>fE,assertNotEqual:()=>pE,assignProp:()=>Lr,base64ToUint8Array:()=>Gy,base64urlToUint8Array:()=>CE,cached:()=>_o,captureStackTrace:()=>dc,cleanEnum:()=>TE,cleanRegex:()=>Bi,clone:()=>At,cloneDef:()=>yE,createTransparentProxy:()=>wE,defineLazy:()=>Ie,esc:()=>lc,escapeRegex:()=>qt,extend:()=>EE,finalizeIssue:()=>Rt,floatSafeRemainder:()=>pp,getElementAtPath:()=>vE,getEnumValues:()=>Wi,getLengthableOrigin:()=>Yi,getParsedType:()=>$E,getSizableOrigin:()=>Xi,hexToUint8Array:()=>OE,isObject:()=>Rn,isPlainObject:()=>Vr,issue:()=>So,joinValues:()=>ge,jsonStringifyReplacer:()=>vo,merge:()=>xE,mergeDefs:()=>Sr,normalizeParams:()=>X,nullish:()=>qr,numKeys:()=>bE,objectClone:()=>gE,omit:()=>kE,optionalKeys:()=>gp,parsedType:()=>Se,partial:()=>IE,pick:()=>zE,prefixIssues:()=>Ot,primitiveTypes:()=>hp,promiseAllObject:()=>_E,propertyKeyTypes:()=>Gi,randomString:()=>SE,required:()=>PE,safeExtend:()=>RE,shallowClone:()=>By,slugify:()=>mp,stringifyPrimitive:()=>ye,uint8ArrayToBase64:()=>Xy,uint8ArrayToBase64url:()=>AE,uint8ArrayToHex:()=>NE,unwrapMessage:()=>Zi});function dE(e){return e}function pE(e){return e}function mE(e){}function fE(e){throw new Error("Unexpected value in exhaustive check")}function hE(e){}function Wi(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function ge(e,t="|"){return e.map(r=>ye(r)).join(t)}function vo(e,t){return typeof t=="bigint"?t.toString():t}function _o(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function qr(e){return e==null}function Bi(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function pp(e,t){let r=(e.toString().split(".")[1]||"").length,n=t.toString(),o=(n.split(".")[1]||"").length;if(o===0&&/\d?e-\d?/.test(n)){let c=n.match(/\d?e-(\d?)/);c?.[1]&&(o=Number.parseInt(c[1]))}let i=r>o?r:o,a=Number.parseInt(e.toFixed(i).replace(".","")),s=Number.parseInt(t.toFixed(i).replace(".",""));return a%s/10**i}function Ie(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==Wy)return n===void 0&&(n=Wy,n=r()),n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function gE(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function Lr(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Sr(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function yE(e){return Sr(e._zod.def)}function vE(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function _E(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let i=0;it};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function wE(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,i){return t??(t=e()),Reflect.set(t,n,o,i)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,o){return t??(t=e()),Reflect.defineProperty(t,n,o)}})}function ye(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function gp(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function zE(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i=Sr(e._zod.def,{get shape(){let a={};for(let s in t){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);t[s]&&(a[s]=r.shape[s])}return Lr(this,"shape",a),a},checks:[]});return At(e,i)}function kE(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=Sr(e._zod.def,{get shape(){let a={...e._zod.def.shape};for(let s in t){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);t[s]&&delete a[s]}return Lr(this,"shape",a),a},checks:[]});return At(e,i)}function EE(e,t){if(!Vr(t))throw new Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let i=e._zod.def.shape;for(let a in t)if(Object.getOwnPropertyDescriptor(i,a)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=Sr(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return Lr(this,"shape",i),i}});return At(e,o)}function RE(e,t){if(!Vr(t))throw new Error("Invalid input to safeExtend: expected a plain object");let r=Sr(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Lr(this,"shape",n),n}});return At(e,r)}function xE(e,t){let r=Sr(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Lr(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return At(e,r)}function IE(e,t,r){let o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let a=Sr(t._zod.def,{get shape(){let s=t._zod.def.shape,c={...s};if(r)for(let u in r){if(!(u in s))throw new Error(`Unrecognized key: "${u}"`);r[u]&&(c[u]=e?new e({type:"optional",innerType:s[u]}):s[u])}else for(let u in s)c[u]=e?new e({type:"optional",innerType:s[u]}):s[u];return Lr(this,"shape",c),c},checks:[]});return At(t,a)}function PE(e,t,r){let n=Sr(t._zod.def,{get shape(){let o=t._zod.def.shape,i={...o};if(r)for(let a in r){if(!(a in i))throw new Error(`Unrecognized key: "${a}"`);r[a]&&(i[a]=new e({type:"nonoptional",innerType:o[a]}))}else for(let a in o)i[a]=new e({type:"nonoptional",innerType:o[a]});return Lr(this,"shape",i),i}});return At(t,n)}function Kr(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Zi(e){return typeof e=="string"?e:e?.message}function Rt(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let o=Zi(e.inst?._zod.def?.error?.(e))??Zi(t?.error?.(e))??Zi(r.customError?.(e))??Zi(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function Xi(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Yi(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Se(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function So(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function TE(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function Gy(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;nt.toString(16).padStart(2,"0")).join("")}var Wy,dc,fp,$E,Gi,hp,yp,vp,dp,de=q(()=>{Wy=Symbol("evaluating");dc="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};fp=_o(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});$E=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},Gi=new Set(["string","number","symbol"]),hp=new Set(["string","number","bigint","boolean","symbol","undefined"]);yp={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},vp={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};dp=class{constructor(...t){}}});function _p(e,t=r=>r.message){let r={},n=[];for(let o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function Sp(e,t=r=>r.message){let r={_errors:[]},n=o=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>n({issues:a}));else if(i.code==="invalid_key")n({issues:i.issues});else if(i.code==="invalid_element")n({issues:i.issues});else if(i.path.length===0)r._errors.push(t(i));else{let a=r,s=0;for(;s{yo();de();Yy=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,vo,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},pc=C("$ZodError",Yy),Qi=C("$ZodError",Yy,{Parent:Error})});var ea,$p,ta,wp,ra,Qy,na,ev,tv,rv,nv,ov,iv,av,sv,cv,zp=q(()=>{yo();bp();de();ea=e=>(t,r,n,o)=>{let i=n?Object.assign(n,{async:!1}):{async:!1},a=t._zod.run({value:r,issues:[]},i);if(a instanceof Promise)throw new ir;if(a.issues.length){let s=new(o?.Err??e)(a.issues.map(c=>Rt(c,i,lt())));throw dc(s,o?.callee),s}return a.value},$p=ea(Qi),ta=e=>async(t,r,n,o)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},a=t._zod.run({value:r,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){let s=new(o?.Err??e)(a.issues.map(c=>Rt(c,i,lt())));throw dc(s,o?.callee),s}return a.value},wp=ta(Qi),ra=e=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new ir;return i.issues.length?{success:!1,error:new(e??pc)(i.issues.map(a=>Rt(a,o,lt())))}:{success:!0,data:i.value}},Qy=ra(Qi),na=e=>async(t,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},i=t._zod.run({value:r,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(a=>Rt(a,o,lt())))}:{success:!0,data:i.value}},ev=na(Qi),tv=e=>(t,r,n)=>{let o=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return ea(e)(t,r,o)},rv=e=>(t,r,n)=>ea(e)(t,r,n),nv=e=>async(t,r,n)=>{let o=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return ta(e)(t,r,o)},ov=e=>async(t,r,n)=>ta(e)(t,r,n),iv=e=>(t,r,n)=>{let o=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return ra(e)(t,r,o)},av=e=>(t,r,n)=>ra(e)(t,r,n),sv=e=>async(t,r,n)=>{let o=n?Object.assign(n,{direction:"backward"}):{direction:"backward"};return na(e)(t,r,o)},cv=e=>async(t,r,n)=>na(e)(t,r,n)});var ar={};nr(ar,{base64:()=>qp,base64url:()=>mc,bigint:()=>Hp,boolean:()=>Wp,browserEmail:()=>JE,cidrv4:()=>Mp,cidrv6:()=>Dp,cuid:()=>kp,cuid2:()=>Ep,date:()=>Vp,datetime:()=>Jp,domain:()=>ZE,duration:()=>Tp,e164:()=>Lp,email:()=>Ap,emoji:()=>Op,extendedDuration:()=>UE,guid:()=>Cp,hex:()=>WE,hostname:()=>HE,html5Email:()=>LE,idnEmail:()=>KE,integer:()=>Zp,ipv4:()=>Np,ipv6:()=>jp,ksuid:()=>Ip,lowercase:()=>Xp,mac:()=>Up,md5_base64:()=>GE,md5_base64url:()=>XE,md5_hex:()=>BE,nanoid:()=>Pp,null:()=>Bp,number:()=>fc,rfc5322Email:()=>VE,sha1_base64:()=>QE,sha1_base64url:()=>eR,sha1_hex:()=>YE,sha256_base64:()=>rR,sha256_base64url:()=>nR,sha256_hex:()=>tR,sha384_base64:()=>iR,sha384_base64url:()=>aR,sha384_hex:()=>oR,sha512_base64:()=>cR,sha512_base64url:()=>uR,sha512_hex:()=>sR,string:()=>Fp,time:()=>Kp,ulid:()=>Rp,undefined:()=>Gp,unicodeEmail:()=>uv,uppercase:()=>Yp,uuid:()=>xn,uuid4:()=>ME,uuid6:()=>DE,uuid7:()=>qE,xid:()=>xp});function Op(){return new RegExp(FE,"u")}function dv(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Kp(e){return new RegExp(`^${dv(e)}$`)}function Jp(e){let t=dv({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${lv}T(?:${n})$`)}function oa(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function ia(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}var kp,Ep,Rp,xp,Ip,Pp,Tp,UE,Cp,xn,ME,DE,qE,Ap,LE,VE,uv,KE,JE,FE,Np,jp,Up,Mp,Dp,qp,mc,HE,ZE,Lp,lv,Vp,Fp,Hp,Zp,fc,Wp,Bp,Gp,Xp,Yp,WE,BE,GE,XE,YE,QE,eR,tR,rR,nR,oR,iR,aR,sR,cR,uR,hc=q(()=>{de();kp=/^[cC][^\s-]{8,}$/,Ep=/^[0-9a-z]+$/,Rp=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xp=/^[0-9a-vA-V]{20}$/,Ip=/^[A-Za-z0-9]{27}$/,Pp=/^[a-zA-Z0-9_-]{21}$/,Tp=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,UE=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Cp=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,xn=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,ME=xn(4),DE=xn(6),qE=xn(7),Ap=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,LE=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,VE=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,uv=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,KE=uv,JE=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,FE="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";Np=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,jp=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Up=e=>{let t=qt(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},Mp=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Dp=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,qp=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,mc=/^[A-Za-z0-9_-]*$/,HE=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,ZE=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,Lp=/^\+[1-9]\d{6,14}$/,lv="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Vp=new RegExp(`^${lv}$`);Fp=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Hp=/^-?\d+n?$/,Zp=/^-?\d+$/,fc=/^-?\d+(?:\.\d+)?$/,Wp=/^(?:true|false)$/i,Bp=/^null$/i,Gp=/^undefined$/i,Xp=/^[^A-Z]*$/,Yp=/^[^a-z]*$/,WE=/^[0-9a-fA-F]*$/;BE=/^[0-9a-fA-F]{32}$/,GE=oa(22,"=="),XE=ia(22),YE=/^[0-9a-fA-F]{40}$/,QE=oa(27,"="),eR=ia(27),tR=/^[0-9a-fA-F]{64}$/,rR=oa(43,"="),nR=ia(43),oR=/^[0-9a-fA-F]{96}$/,iR=oa(64,""),aR=ia(64),sR=/^[0-9a-fA-F]{128}$/,cR=oa(86,"=="),uR=ia(86)});function pv(e,t,r){e.issues.length&&t.issues.push(...Ot(r,e.issues))}var Je,mv,Qp,em,fv,hv,gv,yv,vv,_v,Sv,bv,$v,aa,wv,zv,kv,Ev,Rv,xv,Iv,Pv,Tv,gc=q(()=>{yo();hc();de();Je=C("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),mv={number:"number",bigint:"bigint",object:"date"},Qp=C("$ZodCheckLessThan",(e,t)=>{Je.init(e,t);let r=mv[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value{(t.inclusive?n.value<=t.value:n.value{Je.init(e,t);let r=mv[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),fv=C("$ZodCheckMultipleOf",(e,t)=>{Je.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):pp(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),hv=C("$ZodCheckNumberFormat",(e,t)=>{Je.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,i]=yp[t.format];e._zod.onattach.push(a=>{let s=a._zod.bag;s.format=t.format,s.minimum=o,s.maximum=i,r&&(s.pattern=Zp)}),e._zod.check=a=>{let s=a.value;if(r){if(!Number.isInteger(s)){a.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?a.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):a.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}si&&a.issues.push({origin:"number",input:s,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),gv=C("$ZodCheckBigIntFormat",(e,t)=>{Je.init(e,t);let[r,n]=vp[t.format];e._zod.onattach.push(o=>{let i=o._zod.bag;i.format=t.format,i.minimum=r,i.maximum=n}),e._zod.check=o=>{let i=o.value;in&&o.issues.push({origin:"bigint",input:i,code:"too_big",maximum:n,inclusive:!0,inst:e,continue:!t.abort})}}),yv=C("$ZodCheckMaxSize",(e,t)=>{var r;Je.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!qr(o)&&o.size!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{let o=n.value;o.size<=t.maximum||n.issues.push({origin:Xi(o),code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),vv=C("$ZodCheckMinSize",(e,t)=>{var r;Je.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!qr(o)&&o.size!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;o.size>=t.minimum||n.issues.push({origin:Xi(o),code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),_v=C("$ZodCheckSizeEquals",(e,t)=>{var r;Je.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!qr(o)&&o.size!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.size,o.maximum=t.size,o.size=t.size}),e._zod.check=n=>{let o=n.value,i=o.size;if(i===t.size)return;let a=i>t.size;n.issues.push({origin:Xi(o),...a?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Sv=C("$ZodCheckMaxLength",(e,t)=>{var r;Je.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!qr(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{let o=n.value;if(o.length<=t.maximum)return;let a=Yi(o);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),bv=C("$ZodCheckMinLength",(e,t)=>{var r;Je.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!qr(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;if(o.length>=t.minimum)return;let a=Yi(o);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),$v=C("$ZodCheckLengthEquals",(e,t)=>{var r;Je.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!qr(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{let o=n.value,i=o.length;if(i===t.length)return;let a=Yi(o),s=i>t.length;n.issues.push({origin:a,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),aa=C("$ZodCheckStringFormat",(e,t)=>{var r,n;Je.init(e,t),e._zod.onattach.push(o=>{let i=o._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),wv=C("$ZodCheckRegex",(e,t)=>{aa.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),zv=C("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Xp),aa.init(e,t)}),kv=C("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Yp),aa.init(e,t)}),Ev=C("$ZodCheckIncludes",(e,t)=>{Je.init(e,t);let r=qt(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Rv=C("$ZodCheckStartsWith",(e,t)=>{Je.init(e,t);let r=new RegExp(`^${qt(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),xv=C("$ZodCheckEndsWith",(e,t)=>{Je.init(e,t);let r=new RegExp(`.*${qt(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});Iv=C("$ZodCheckProperty",(e,t)=>{Je.init(e,t),e._zod.check=r=>{let n=t.schema._zod.run({value:r.value[t.property],issues:[]},{});if(n instanceof Promise)return n.then(o=>pv(o,r,t.property));pv(n,r,t.property)}}),Pv=C("$ZodCheckMimeType",(e,t)=>{Je.init(e,t);let r=new Set(t.mime);e._zod.onattach.push(n=>{n._zod.bag.mime=t.mime}),e._zod.check=n=>{r.has(n.value.type)||n.issues.push({code:"invalid_value",values:t.mime,input:n.value.type,inst:e,continue:!t.abort})}}),Tv=C("$ZodCheckOverwrite",(e,t)=>{Je.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}})});var yc,tm=q(()=>{yc=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(` +`).filter(a=>a),o=Math.min(...n.map(a=>a.length-a.trimStart().length)),i=n.map(a=>a.slice(o)).map(a=>" ".repeat(this.indent*2)+a);for(let a of i)this.content.push(a)}compile(){let t=Function,r=this?.args,o=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...r,o.join(` +`))}}});var Av,rm=q(()=>{Av={major:4,minor:3,patch:6}});function d_(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}function lR(e){if(!mc.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return d_(r)}function dR(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}function Ov(e,t,r){e.issues.length&&t.issues.push(...Ot(r,e.issues)),t.value[r]=e.value}function $c(e,t,r,n,o){if(e.issues.length){if(o&&!(r in n))return;t.issues.push(...Ot(r,e.issues))}e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}function x_(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);let r=gp(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function I_(e,t,r,n,o,i){let a=[],s=o.keySet,c=o.catchall._zod,u=c.def.type,l=c.optout==="optional";for(let d in t){if(s.has(d))continue;if(u==="never"){a.push(d);continue}let m=c.run({value:t[d],issues:[]},n);m instanceof Promise?e.push(m.then(v=>$c(v,r,d,t,l))):$c(m,r,d,t,l)}return a.length&&r.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:i}),e.length?Promise.all(e).then(()=>r):r}function Nv(e,t,r,n){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;let o=e.filter(i=>!Kr(i));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(i=>i.issues.map(a=>Rt(a,n,lt())))}),t)}function jv(e,t,r,n){let o=e.filter(i=>i.issues.length===0);return o.length===1?(t.value=o[0].value,t):(o.length===0?t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(i=>i.issues.map(a=>Rt(a,n,lt())))}):t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:[],inclusive:!1}),t)}function nm(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Vr(e)&&Vr(t)){let r=Object.keys(t),n=Object.keys(e).filter(i=>r.indexOf(i)!==-1),o={...e,...t};for(let i of n){let a=nm(e[i],t[i]);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};o[i]=a.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;ns.l&&s.r).map(([s])=>s);if(i.length&&o&&e.issues.push({...o,keys:i}),Kr(e))return e;let a=nm(t.value,r.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}function vc(e,t,r){e.issues.length&&t.issues.push(...Ot(r,e.issues)),t.value[r]=e.value}function Mv(e,t,r,n,o,i,a){e.issues.length&&(Gi.has(typeof n)?r.issues.push(...Ot(n,e.issues)):r.issues.push({code:"invalid_key",origin:"map",input:o,inst:i,issues:e.issues.map(s=>Rt(s,a,lt()))})),t.issues.length&&(Gi.has(typeof n)?r.issues.push(...Ot(n,t.issues)):r.issues.push({origin:"map",code:"invalid_element",input:o,inst:i,key:n,issues:t.issues.map(s=>Rt(s,a,lt()))})),r.value.set(e.value,t.value)}function Dv(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}function qv(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}function Lv(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}function Vv(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}function _c(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},r)}function Sc(e,t,r){if(e.issues.length)return e.aborted=!0,e;if((r.direction||"forward")==="forward"){let o=t.transform(e.value,e);return o instanceof Promise?o.then(i=>bc(e,i,t.out,r)):bc(e,o,t.out,r)}else{let o=t.reverseTransform(e.value,e);return o instanceof Promise?o.then(i=>bc(e,i,t.in,r)):bc(e,o,t.in,r)}}function bc(e,t,r,n){return e.issues.length?(e.aborted=!0,e):r._zod.run({value:t,issues:e.issues},n)}function Kv(e){return e.value=Object.freeze(e.value),e}function Jv(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(So(o))}}var we,bo,Ve,Fv,Hv,Zv,Wv,Bv,Gv,Xv,Yv,Qv,e_,t_,r_,n_,o_,i_,a_,s_,c_,u_,l_,p_,m_,f_,h_,g_,om,y_,wc,im,v_,__,S_,b_,$_,w_,z_,k_,E_,R_,pR,P_,zc,T_,C_,A_,am,O_,N_,j_,U_,M_,D_,q_,sm,L_,V_,K_,J_,F_,H_,Z_,W_,B_,kc,G_,X_,Y_,Q_,eS,tS,cm=q(()=>{gc();yo();tm();zp();hc();de();rm();de();we=C("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Av;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let o of n)for(let i of o._zod.onattach)i(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(a,s,c)=>{let u=Kr(a),l;for(let d of s){if(d._zod.def.when){if(!d._zod.def.when(a))continue}else if(u)continue;let m=a.issues.length,v=d._zod.check(a);if(v instanceof Promise&&c?.async===!1)throw new ir;if(l||v instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await v,a.issues.length!==m&&(u||(u=Kr(a,m)))});else{if(a.issues.length===m)continue;u||(u=Kr(a,m))}}return l?l.then(()=>a):a},i=(a,s,c)=>{if(Kr(a))return a.aborted=!0,a;let u=o(s,n,c);if(u instanceof Promise){if(c.async===!1)throw new ir;return u.then(l=>e._zod.parse(l,c))}return e._zod.parse(u,c)};e._zod.run=(a,s)=>{if(s.skipChecks)return e._zod.parse(a,s);if(s.direction==="backward"){let u=e._zod.parse({value:a.value,issues:[]},{...s,skipChecks:!0});return u instanceof Promise?u.then(l=>i(l,a,s)):i(u,a,s)}let c=e._zod.parse(a,s);if(c instanceof Promise){if(s.async===!1)throw new ir;return c.then(u=>o(u,n,s))}return o(c,n,s)}}Ie(e,"~standard",()=>({validate:o=>{try{let i=Qy(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return ev(e,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}))}),bo=C("$ZodString",(e,t)=>{we.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Fp(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),Ve=C("$ZodStringFormat",(e,t)=>{aa.init(e,t),bo.init(e,t)}),Fv=C("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Cp),Ve.init(e,t)}),Hv=C("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=xn(n))}else t.pattern??(t.pattern=xn());Ve.init(e,t)}),Zv=C("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Ap),Ve.init(e,t)}),Wv=C("$ZodURL",(e,t)=>{Ve.init(e,t),e._zod.check=r=>{try{let n=r.value.trim(),o=new URL(n);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=o.href:r.value=n;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Bv=C("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Op()),Ve.init(e,t)}),Gv=C("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Pp),Ve.init(e,t)}),Xv=C("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=kp),Ve.init(e,t)}),Yv=C("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Ep),Ve.init(e,t)}),Qv=C("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Rp),Ve.init(e,t)}),e_=C("$ZodXID",(e,t)=>{t.pattern??(t.pattern=xp),Ve.init(e,t)}),t_=C("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Ip),Ve.init(e,t)}),r_=C("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Jp(t)),Ve.init(e,t)}),n_=C("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Vp),Ve.init(e,t)}),o_=C("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Kp(t)),Ve.init(e,t)}),i_=C("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Tp),Ve.init(e,t)}),a_=C("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Np),Ve.init(e,t),e._zod.bag.format="ipv4"}),s_=C("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=jp),Ve.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),c_=C("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=Up(t.delimiter)),Ve.init(e,t),e._zod.bag.format="mac"}),u_=C("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Mp),Ve.init(e,t)}),l_=C("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Dp),Ve.init(e,t),e._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[o,i]=n;if(!i)throw new Error;let a=Number(i);if(`${a}`!==i)throw new Error;if(a<0||a>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});p_=C("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=qp),Ve.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{d_(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});m_=C("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=mc),Ve.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{lR(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),f_=C("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Lp),Ve.init(e,t)});h_=C("$ZodJWT",(e,t)=>{Ve.init(e,t),e._zod.check=r=>{dR(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),g_=C("$ZodCustomStringFormat",(e,t)=>{Ve.init(e,t),e._zod.check=r=>{t.fn(r.value)||r.issues.push({code:"invalid_format",format:t.format,input:r.value,inst:e,continue:!t.abort})}}),om=C("$ZodNumber",(e,t)=>{we.init(e,t),e._zod.pattern=e._zod.bag.pattern??fc,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),r}}),y_=C("$ZodNumberFormat",(e,t)=>{hv.init(e,t),om.init(e,t)}),wc=C("$ZodBoolean",(e,t)=>{we.init(e,t),e._zod.pattern=Wp,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}}),im=C("$ZodBigInt",(e,t)=>{we.init(e,t),e._zod.pattern=Hp,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}}),v_=C("$ZodBigIntFormat",(e,t)=>{gv.init(e,t),im.init(e,t)}),__=C("$ZodSymbol",(e,t)=>{we.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;return typeof o=="symbol"||r.issues.push({expected:"symbol",code:"invalid_type",input:o,inst:e}),r}}),S_=C("$ZodUndefined",(e,t)=>{we.init(e,t),e._zod.pattern=Gp,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(r,n)=>{let o=r.value;return typeof o>"u"||r.issues.push({expected:"undefined",code:"invalid_type",input:o,inst:e}),r}}),b_=C("$ZodNull",(e,t)=>{we.init(e,t),e._zod.pattern=Bp,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}}),$_=C("$ZodAny",(e,t)=>{we.init(e,t),e._zod.parse=r=>r}),w_=C("$ZodUnknown",(e,t)=>{we.init(e,t),e._zod.parse=r=>r}),z_=C("$ZodNever",(e,t)=>{we.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)}),k_=C("$ZodVoid",(e,t)=>{we.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;return typeof o>"u"||r.issues.push({expected:"void",code:"invalid_type",input:o,inst:e}),r}}),E_=C("$ZodDate",(e,t)=>{we.init(e,t),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=new Date(r.value)}catch{}let o=r.value,i=o instanceof Date;return i&&!Number.isNaN(o.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:o,...i?{received:"Invalid Date"}:{},inst:e}),r}});R_=C("$ZodArray",(e,t)=>{we.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);let i=[];for(let a=0;aOv(u,r,a))):Ov(c,r,a)}return i.length?Promise.all(i).then(()=>r):r}});pR=C("$ZodObject",(e,t)=>{if(we.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let s=t.shape;Object.defineProperty(t,"shape",{get:()=>{let c={...s};return Object.defineProperty(t,"shape",{value:c}),c}})}let n=_o(()=>x_(t));Ie(e._zod,"propValues",()=>{let s=t.shape,c={};for(let u in s){let l=s[u]._zod;if(l.values){c[u]??(c[u]=new Set);for(let d of l.values)c[u].add(d)}}return c});let o=Rn,i=t.catchall,a;e._zod.parse=(s,c)=>{a??(a=n.value);let u=s.value;if(!o(u))return s.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),s;s.value={};let l=[],d=a.shape;for(let m of a.keys){let v=d[m],g=v._zod.optout==="optional",h=v._zod.run({value:u[m],issues:[]},c);h instanceof Promise?l.push(h.then(f=>$c(f,s,m,u,g))):$c(h,s,m,u,g)}return i?I_(l,u,s,c,n.value,e):l.length?Promise.all(l).then(()=>s):s}}),P_=C("$ZodObjectJIT",(e,t)=>{pR.init(e,t);let r=e._zod.parse,n=_o(()=>x_(t)),o=m=>{let v=new yc(["shape","payload","ctx"]),g=n.value,h=_=>{let $=lc(_);return`shape[${$}]._zod.run({ value: input[${$}], issues: [] }, ctx)`};v.write("const input = payload.value;");let f=Object.create(null),y=0;for(let _ of g.keys)f[_]=`key_${y++}`;v.write("const newResult = {};");for(let _ of g.keys){let $=f[_],k=lc(_),b=m[_]?._zod?.optout==="optional";v.write(`const ${$} = ${h(_)};`),b?v.write(` + if (${$}.issues.length) { + if (${k} in input) { + payload.issues = payload.issues.concat(${$}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${k}, ...iss.path] : [${k}] + }))); } - break; } - case "ambiguous": { - const conflictIds = predecessor.entries.map((e) => e.id).sort(); - const eventId = `conflicting_facts:${rest.sessionId}:${rest.agent.id}:${candidate.entityType}:${conflictIds.join(",")}`; - let claimText; - try { - claimText = JSON.stringify({ - entityType: candidate.entityType, - candidate: candidate.structured, - conflictingEntryIds: conflictIds - }); - } catch { - claimText = ""; - } - frictionEvents.push(createEvent(eventId, "ontology.friction", rest.agent.id, { - claim: claimText, - attemptedEntityType: candidate.entityType, - availableEntityTypes, - frictionType: "conflicting_facts", - count: predecessor.entries.length, - // First-class field — consumers shouldn't have to parse - // `claim` (JSON-encoded) to get the conflict set. This - // is what a human reviewer needs to act: WHICH entries - // conflict, not just how many. - conflictingEntryIds: conflictIds - }, rest.sessionId)); - break; - } - } - } catch (err) { - errors.push(`store(${candidate.id}) failed: ${err instanceof Error ? err.message : String(err)}`); - } - } - return { captured, dropped, errors, frictionEvents }; -} - -// ../freya/packages/core/dist/domain/services/AgentSessionService.js -var MAX_CORRECTION_RETRIES_PER_TURN = 2; -async function executeTurn(agent, sessionId, userMessage, deps, budget) { - const events = []; - const allToolResults = []; - let totalInputTokens = 0; - let totalOutputTokens = 0; - let totalCacheReadTokens = 0; - let totalCacheWriteTokens = 0; - let llmCalls = 0; - const tracing = deps.trace === true; - const trace = []; - const turnId = crypto.randomUUID(); - const annotationsBuf = []; - let currentPhase = "init"; - const rawFire = makeFireHook({ - registry: deps.hooks ?? new InMemoryHookRegistry(), - agent, - sessionId, - turnId, - onEvent: (e) => events.push(e), - onAnnotation: (key, value) => annotationsBuf.push({ phase: currentPhase, key, value }) - }); - const fire = async (phase, payload) => { - currentPhase = phase; - try { - return await rawFire(phase, payload); - } catch (err) { - if (!(err instanceof HookExecutionError)) - throw err; - const message = err.message; - annotationsBuf.push({ - phase, - key: "blocking.hook_exception", - value: message - }); - events.push({ - id: crypto.randomUUID(), - type: "turn.annotated", - agentId: agent.id, - sessionId, - timestamp: /* @__PURE__ */ new Date(), - payload: { - key: "blocking.hook_exception", - phase, - error: message - } - }); - return { - payload, - shortCircuited: false, - correctionRequested: false - }; - } - }; - let session = await deps.sessions.get(sessionId); - if (!session) { - session = createSession(sessionId, agent.id, userMessage.metadata.userId ?? "unknown", userMessage.transportOrigin); - } - session = addMessage(session, userMessage); - events.push(createEvent(crypto.randomUUID(), "message.received", agent.id, { messageId: userMessage.id }, sessionId)); - let ontology = await deps.ontologyService.compose(agent.id); - const recallResult = await deps.memory.recall({ - agentId: agent.id, - query: userMessage.content, - limit: 20 - }); - let memories = recallResult.entries; - const effectiveBudget = budget ?? budgetFromMaxTurns(agent.config.maxTurns || 10); - const tracker = createBudgetTracker(effectiveBudget, { modelId: agent.config.modelId }); - const hardCap = Math.max(effectiveBudget.maxCalls != null ? effectiveBudget.maxCalls * 2 : 100, 1); - let totalLLMCalls = 0; - let finalResponse = null; - let budgetExhaustedDuringLoop = false; - let earlyExit = null; - try { - const preTurn = await fire("pre_turn", { userMessage, ontology, memories, session }); - if (preTurn.shortCircuited) { - earlyExit = { finalResponse: preTurn.finalResponse ?? null, reason: preTurn.reason }; - } else { - ontology = preTurn.payload.ontology; - memories = preTurn.payload.memories; - } - const toolDefs = []; - if (!earlyExit) { - for (const scope of agent.config.toolScopes) { - const discovered = await deps.tools.discoverTools(scope); - toolDefs.push(...discovered); - } - } - const MAX_CONTEXT_MESSAGES = 20; - const windowedMessages = session.messages.length > MAX_CONTEXT_MESSAGES ? session.messages.slice(-MAX_CONTEXT_MESSAGES) : session.messages; - let context = !earlyExit ? buildContext({ - config: agent.config, - ontology, - memories, - messages: windowedMessages, - tools: toolDefs, - ontologyRenderer: deps.ontologyRenderer, - transport: userMessage.transportOrigin - }) : { systemPrompt: "", messages: [], tools: [], tokenEstimate: 0 }; - if (!earlyExit) { - const preContext = await fire("pre_context", { - context, - recall: recallResult, - recallQuery: userMessage.content, - availableEntityTypes: ontology.entityTypes.map((e) => e.name) - }); - if (preContext.shortCircuited) { - earlyExit = { finalResponse: preContext.finalResponse ?? null, reason: preContext.reason }; - } else { - context = preContext.payload.context; - } - } - let turnMessages = [...windowedMessages]; - if (tracing) { - trace.push({ step: "start", timestamp: Date.now(), data: { sessionMessages: session.messages.length, windowedMessages: windowedMessages.length, hardCap, budget: effectiveBudget } }); - } - let correctionsUsed = 0; - correctionLoop: while (!earlyExit) { - finalResponse = null; - llmLoop: while (totalLLMCalls < hardCap) { - const preLlm = await fire("pre_llm", { - messages: turnMessages, - systemPrompt: context.systemPrompt, - tools: toolDefs, - callNumber: totalLLMCalls + 1 - }); - if (preLlm.shortCircuited) { - earlyExit = { finalResponse: preLlm.finalResponse ?? null, reason: preLlm.reason }; - break llmLoop; - } - if (tracing) { - trace.push({ step: "llm_call", timestamp: Date.now(), data: { turnMessages: preLlm.payload.messages.length, toolDefs: preLlm.payload.tools.length, callNumber: totalLLMCalls + 1 } }); - } - const llmResponse = await deps.llm.complete({ - model: agent.config.modelId, - systemPrompt: preLlm.payload.systemPrompt, - messages: preLlm.payload.messages, - tools: preLlm.payload.tools - }); - totalLLMCalls++; - llmCalls++; - totalInputTokens += llmResponse.usage.inputTokens; - totalOutputTokens += llmResponse.usage.outputTokens; - totalCacheReadTokens += llmResponse.usage.cacheReadTokens ?? 0; - totalCacheWriteTokens += llmResponse.usage.cacheWriteTokens ?? 0; - tracker.recordCall(llmResponse.usage); - if (tracing) { - trace.push({ step: "llm_response", timestamp: Date.now(), data: { contentLength: llmResponse.content.length, toolCalls: llmResponse.toolCalls.length, stopReason: llmResponse.stopReason, usage: llmResponse.usage } }); - } - const postLlm = await fire("post_llm", { response: llmResponse, callNumber: totalLLMCalls }); - const effectiveResponse = postLlm.payload.response; - if (postLlm.shortCircuited) { - earlyExit = { finalResponse: postLlm.finalResponse ?? null, reason: postLlm.reason }; - finalResponse = effectiveResponse; - break llmLoop; - } - if (effectiveResponse.stopReason === "tool_use" && effectiveResponse.toolCalls.length > 0) { - let toolLoopShortCircuit = false; - for (const call of effectiveResponse.toolCalls) { - const preTool = await fire("pre_tool", { call }); - if (preTool.shortCircuited) { - earlyExit = { finalResponse: preTool.finalResponse ?? null, reason: preTool.reason }; - finalResponse = effectiveResponse; - toolLoopShortCircuit = true; - break; - } - const effectiveCall = preTool.payload.call; - events.push(createEvent(crypto.randomUUID(), "tool.invoked", agent.id, { tool: effectiveCall.toolName }, sessionId)); - const rawResult = await deps.tools.execute(effectiveCall); - const availableEntityTypes = ontology.entityTypes.map((e) => e.name); - const postTool = await fire("post_tool", { - call: effectiveCall, - result: rawResult, - availableEntityTypes - }); - const result2 = postTool.payload.result; - allToolResults.push(result2); - events.push(createEvent(crypto.randomUUID(), "tool.completed", agent.id, { tool: effectiveCall.toolName, status: result2.status }, sessionId)); - const toolUseId = effectiveCall.id; - turnMessages = [ - ...turnMessages, - { - id: crypto.randomUUID(), - role: "assistant", - content: effectiveResponse.content, - timestamp: /* @__PURE__ */ new Date(), - transportOrigin: "agent", - toolInvocations: [{ toolName: effectiveCall.toolName, input: effectiveCall.input, output: result2.output, durationMs: result2.durationMs, status: result2.status }], - metadata: { toolUseId } - }, - { - id: crypto.randomUUID(), - role: "tool", - content: typeof result2.output === "string" ? result2.output : JSON.stringify(result2.output), - timestamp: /* @__PURE__ */ new Date(), - transportOrigin: "tool", - metadata: { toolName: effectiveCall.toolName, callId: toolUseId } - } - ]; - if (postTool.shortCircuited) { - earlyExit = { finalResponse: postTool.finalResponse ?? null, reason: postTool.reason }; - finalResponse = effectiveResponse; - toolLoopShortCircuit = true; - break; - } - } - if (toolLoopShortCircuit) - break llmLoop; - if (tracker.isExhausted()) { - if (tracing) { - trace.push({ step: "budget_check", timestamp: Date.now(), data: { exhausted: true, status: tracker.getStatus() } }); - } - finalResponse = effectiveResponse; - budgetExhaustedDuringLoop = true; - break llmLoop; - } - if (tracing) { - trace.push({ step: "budget_check", timestamp: Date.now(), data: { exhausted: false, status: tracker.getStatus() } }); + + if (${$}.value === undefined) { + if (${k} in input) { + newResult[${k}] = undefined; } } else { - finalResponse = effectiveResponse; - break llmLoop; - } - } - if (earlyExit) - break correctionLoop; - const candidateContent = finalResponse?.content ?? (tracker.getStatus().exhausted || budgetExhaustedDuringLoop ? "[Agent budget exhausted]" : "[Agent reached max turns without completing]"); - const candidateMessage = createAssistantMessage(crypto.randomUUID(), candidateContent, allToolResults.map((r) => ({ - toolName: r.toolName, - input: {}, - output: r.output, - durationMs: r.durationMs, - status: r.status - }))); - const preCapture = await fire("pre_capture", { - response: candidateMessage, - toolResults: allToolResults, - ontology - }); - if (preCapture.correctionRequested) { - if (correctionsUsed < MAX_CORRECTION_RETRIES_PER_TURN) { - correctionsUsed++; - turnMessages = [ - ...turnMessages, - candidateMessage, - createUserMessage(crypto.randomUUID(), preCapture.correctionPrompt ?? "Please correct your response.", "system") - ]; - continue correctionLoop; - } - events.push(createEvent(crypto.randomUUID(), "turn.correction_cap_exceeded", agent.id, { - hookName: preCapture.hookName, - correctionsUsed, - cap: MAX_CORRECTION_RETRIES_PER_TURN - }, sessionId)); - } - if (preCapture.shortCircuited) { - earlyExit = { finalResponse: preCapture.finalResponse ?? candidateMessage, reason: preCapture.reason }; - } - break correctionLoop; - } - const budgetStatus = tracker.getStatus(); - const budgetExhausted = budgetExhaustedDuringLoop || budgetStatus.exhausted; - const fallbackContent = budgetExhausted ? "[Agent budget exhausted]" : earlyExit ? `[Agent short-circuited${earlyExit.reason ? `: ${earlyExit.reason}` : ""}]` : "[Agent reached max turns without completing]"; - const builtContent = earlyExit ? fallbackContent : finalResponse?.content ?? fallbackContent; - const responseMessage = earlyExit?.finalResponse ?? createAssistantMessage(crypto.randomUUID(), builtContent, allToolResults.map((r) => ({ - toolName: r.toolName, - input: {}, - output: r.output, - durationMs: r.durationMs, - status: r.status - }))); - session = addMessage(session, responseMessage); - await deps.sessions.save(session); - events.push(createEvent(crypto.randomUUID(), "message.sent", agent.id, { messageId: responseMessage.id }, sessionId)); - let memoriesCaptured = []; - let droppedCandidates = []; - try { - const captureResult = await captureFromResponse({ - response: responseMessage.content, - ontology, - agent, - sessionId, - turnId, - memory: deps.memory - }); - memoriesCaptured = captureResult.captured; - droppedCandidates = captureResult.dropped; - for (const errMsg of captureResult.errors) { - annotationsBuf.push({ - phase: "post_capture", - key: "memory.capture_error", - value: errMsg - }); - } - for (const fe of captureResult.frictionEvents) { - events.push(fe); - } - } catch (err) { - annotationsBuf.push({ - phase: "post_capture", - key: "memory.capture_error", - value: err instanceof Error ? err.message : String(err) - }); - } - const availableEntityTypesAtCapture = ontology.entityTypes.map((e) => e.name); - let recentlyCaptured; - if (memoriesCaptured.length > 0) { - for (const entry of memoriesCaptured) { - try { - const chain = await deps.memory.getSupersedeChain(entry.id); - if (chain.length === 0) - continue; - const propertyNames = Object.keys(entry.structured).sort(); - const nonIdKeys = propertyNames.filter((p) => p !== "id"); - const propertyName = nonIdKeys[0] ?? propertyNames[0]; - if (!propertyName) - continue; - const coverage = chain.filter((p) => propertyName in p.structured).length; - if (coverage < Math.ceil(chain.length / 2)) - continue; - const priorValues = [...chain].reverse().map((prior) => prior.structured[propertyName]); - recentlyCaptured = { - chainAnchor: entry.id, - entityType: entry.entityType, - propertyName, - currentValue: entry.structured[propertyName], - priorValues - }; - break; - } catch { - continue; - } - } - } - const postCapture = await fire("post_capture", { - captured: memoriesCaptured, - availableEntityTypes: availableEntityTypesAtCapture, - droppedCandidates, - ...recentlyCaptured ? { recentlyCaptured } : {} - }); - if (postCapture.shortCircuited && !earlyExit) { - earlyExit = { finalResponse: postCapture.finalResponse ?? null, reason: postCapture.reason }; - } - const estimatedCostUSD = estimateCostUSD(agent.config.modelId, { - inputTokens: totalInputTokens, - outputTokens: totalOutputTokens, - cacheReadTokens: totalCacheReadTokens, - cacheWriteTokens: totalCacheWriteTokens - }); - if (tracing) { - trace.push({ step: "complete", timestamp: Date.now(), data: { budgetExhausted, responseLength: responseMessage.content.length, totalLLMCalls, hardCap } }); - } - const result = { - response: responseMessage, - session, - memoriesCaptured, - events, - toolResults: allToolResults, - usage: { - inputTokens: totalInputTokens, - outputTokens: totalOutputTokens, - llmCalls, - estimatedCostUSD - }, - budgetExhausted, - budgetStatus: { - calls: budgetStatus.calls, - tokens: budgetStatus.tokens, - timeMs: budgetStatus.timeMs, - ...budgetStatus.exhaustedReason ? { reason: budgetStatus.exhaustedReason } : {} - }, - ...tracing ? { trace } : {} - }; - await fire("post_turn", { - result, - availableEntityTypes: availableEntityTypesAtCapture - }); - return result; - } catch (err) { - const partialResult = { - response: createAssistantMessage(crypto.randomUUID(), `[Agent error: ${err instanceof Error ? err.message : String(err)}]`, []), - session, - memoriesCaptured: [], - events, - toolResults: allToolResults, - usage: { - inputTokens: totalInputTokens, - outputTokens: totalOutputTokens, - llmCalls, - // Even on the error path, surface real cost when tokens were - // consumed before the throw — billing observers/cost trackers - // running at post_turn should see the spend that already happened. - estimatedCostUSD: estimateCostUSD(agent.config.modelId, { - inputTokens: totalInputTokens, - outputTokens: totalOutputTokens, - cacheReadTokens: totalCacheReadTokens, - cacheWriteTokens: totalCacheWriteTokens - }) - } - }; - try { - await fire("post_turn", { - result: partialResult, - availableEntityTypes: ontology.entityTypes.map((e) => e.name) - }); - } catch { - } - throw err; - } -} - -// ../freya/packages/core/dist/domain/services/IdentifierRedactionService.js -var OPAQUE_ID_DEFAULT_MIN = 32; -var OPAQUE_ID_DEFAULT_PATTERN = new RegExp(`\\b[A-Za-z0-9]{${OPAQUE_ID_DEFAULT_MIN},}\\b`, "g"); - -// ../freya/packages/runtime/dist/streaming.js -async function* executeStreamingTurn(agent, sessionId, userMessage, deps, budget, signal) { - const events = []; - const allToolResults = []; - let totalInputTokens = 0; - let totalOutputTokens = 0; - let totalCacheReadTokens = 0; - let totalCacheWriteTokens = 0; - let llmCalls = 0; - const effectiveBudget = budget ?? budgetFromMaxTurns(agent.config.maxTurns || 10); - const tracker = createBudgetTracker(effectiveBudget, { modelId: agent.config.modelId }); - const hardCap = Math.max(effectiveBudget.maxCalls != null ? effectiveBudget.maxCalls * 2 : 100, 1); - let budgetExhaustedDuringLoop = false; - const turnId = crypto.randomUUID(); - const annotations = []; - let currentPhase = "init"; - const rawFire = makeFireHook({ - registry: deps.hooks ?? new InMemoryHookRegistry(), - agent, - sessionId, - turnId, - onEvent: (e) => events.push(e), - // Wire annotations through to a local buffer so callers / tests can see - // them; without this they were silently dropped (the default is a no-op). - onAnnotation: (key, value) => annotations.push({ phase: currentPhase, key, value }) - }); - const fire = async (phase, payload) => { - currentPhase = phase; - try { - return await rawFire(phase, payload); - } catch (err) { - if (!(err instanceof HookExecutionError)) - throw err; - const message = err.message; - annotations.push({ - phase, - key: "streaming.hook_exception", - value: message - }); - events.push(annotationEvent(agent.id, sessionId, "streaming.hook_exception", { - phase, - error: message - })); - return { - payload, - shortCircuited: false, - correctionRequested: false - }; - } - }; - const userId = userMessage.metadata?.userId ?? "unknown"; - let session = await deps.sessions.get(sessionId); - if (!session) { - session = createSession(sessionId, agent.id, userId, userMessage.transportOrigin); - } - session = addMessage(session, userMessage); - events.push(createEvent(crypto.randomUUID(), "message.received", agent.id, { messageId: userMessage.id }, sessionId)); - let ontology = await deps.ontologyService.compose(agent.id); - const recallResult = await deps.memory.recall({ - agentId: agent.id, - query: userMessage.content, - limit: 20 - }); - let memories = recallResult.entries; - let streamingStarted = false; - let earlyExitReason; - let earlyExitResponse = null; - let earlyShortCircuit = false; - try { - const preTurn = await fire("pre_turn", { - userMessage, - ontology, - memories, - session - }); - if (preTurn.shortCircuited) { - earlyExitReason = preTurn.reason; - earlyExitResponse = preTurn.finalResponse ?? null; - yield systemMessage("pre_turn", preTurn.reason, preTurn.finalResponse); - earlyShortCircuit = true; - } else { - ontology = preTurn.payload.ontology; - memories = preTurn.payload.memories; - } - const toolDefs = []; - if (!earlyShortCircuit) { - for (const scope of agent.config.toolScopes) { - const discovered = await deps.tools.discoverTools(scope); - toolDefs.push(...discovered); - } - } - const MAX_CONTEXT_MESSAGES = 20; - const windowedMessages = session.messages.length > MAX_CONTEXT_MESSAGES ? session.messages.slice(-MAX_CONTEXT_MESSAGES) : session.messages; - let context = !earlyShortCircuit ? buildContext({ - config: agent.config, - ontology, - memories, - messages: windowedMessages, - tools: toolDefs, - ontologyRenderer: deps.ontologyRenderer, - transport: userMessage.transportOrigin - }) : { systemPrompt: "", messages: [], tools: [], tokenEstimate: 0 }; - if (!earlyShortCircuit) { - const preContext = await fire("pre_context", { - context, - recall: recallResult, - recallQuery: userMessage.content, - availableEntityTypes: ontology.entityTypes.map((e) => e.name) - }); - if (preContext.shortCircuited) { - earlyExitReason = preContext.reason; - earlyExitResponse = preContext.finalResponse ?? null; - yield systemMessage("pre_context", preContext.reason, preContext.finalResponse); - earlyShortCircuit = true; - } else { - context = preContext.payload.context; - } - } - let currentMessages = [...windowedMessages]; - let lastAssistantContent = ""; - while (!earlyShortCircuit && llmCalls < hardCap) { - const preLlm = await fire("pre_llm", { - messages: currentMessages, - systemPrompt: context.systemPrompt, - tools: toolDefs, - callNumber: llmCalls + 1 - }); - if (preLlm.shortCircuited) { - if (!streamingStarted) { - earlyExitReason = preLlm.reason; - earlyExitResponse = preLlm.finalResponse ?? null; - yield systemMessage("pre_llm", preLlm.reason, preLlm.finalResponse); - earlyShortCircuit = true; - break; - } - events.push(annotationEvent(agent.id, sessionId, "streaming.short_circuit_after_emit", { - phase: "pre_llm", - reason: preLlm.reason - })); - break; - } - let fullContent = ""; - const toolCalls = []; - let chunkUsage = { - inputTokens: 0, - outputTokens: 0 - }; - for await (const chunk of deps.llm.stream({ - model: agent.config.modelId, - systemPrompt: preLlm.payload.systemPrompt, - messages: preLlm.payload.messages, - tools: preLlm.payload.tools, - signal - })) { - if (chunk.type === "text" && chunk.content) { - fullContent += chunk.content; - streamingStarted = true; - yield chunk.content; - } else if (chunk.type === "tool_call" && chunk.toolCall) { - toolCalls.push(chunk.toolCall); - } else if (chunk.type === "done") { - if (chunk.usage) { - chunkUsage = { - inputTokens: chunk.usage.inputTokens, - outputTokens: chunk.usage.outputTokens, - ...chunk.usage.cacheReadTokens !== void 0 && { cacheReadTokens: chunk.usage.cacheReadTokens }, - ...chunk.usage.cacheWriteTokens !== void 0 && { cacheWriteTokens: chunk.usage.cacheWriteTokens } - }; - } - break; - } - } - llmCalls++; - lastAssistantContent = fullContent; - const llmResponse = { - content: fullContent, - toolCalls, - usage: chunkUsage, - stopReason: toolCalls.length > 0 ? "tool_use" : "end_turn" - }; - tracker.recordCall(llmResponse.usage); - const postLlm = await fire("post_llm", { - response: llmResponse, - callNumber: llmCalls - }); - totalInputTokens += llmResponse.usage.inputTokens; - totalOutputTokens += llmResponse.usage.outputTokens; - totalCacheReadTokens += llmResponse.usage.cacheReadTokens ?? 0; - totalCacheWriteTokens += llmResponse.usage.cacheWriteTokens ?? 0; - const effectiveResponse = postLlm.payload.response; - if (postLlm.shortCircuited) { - events.push(annotationEvent(agent.id, sessionId, "streaming.short_circuit_after_emit", { - phase: "post_llm", - reason: postLlm.reason - })); - break; - } - if (effectiveResponse.toolCalls.length === 0) - break; - const availableEntityTypes = ontology.entityTypes.map((e) => e.name); - let toolLoopBreak = false; - for (const call of effectiveResponse.toolCalls) { - const preTool = await fire("pre_tool", { call }); - if (preTool.shortCircuited) { - events.push(annotationEvent(agent.id, sessionId, "streaming.short_circuit_after_emit", { - phase: "pre_tool", - reason: preTool.reason - })); - toolLoopBreak = true; - break; - } - const effectiveCall = preTool.payload.call; - events.push(createEvent(crypto.randomUUID(), "tool.invoked", agent.id, { tool: effectiveCall.toolName }, sessionId)); - const result2 = await deps.tools.execute(effectiveCall); - const postTool = await fire("post_tool", { - call: effectiveCall, - result: result2, - availableEntityTypes - }); - const effectiveResult = postTool.payload.result; - allToolResults.push(effectiveResult); - events.push(createEvent(crypto.randomUUID(), "tool.completed", agent.id, { tool: effectiveCall.toolName, status: effectiveResult.status }, sessionId)); - currentMessages = [ - ...currentMessages, - { - id: crypto.randomUUID(), - role: "assistant", - content: fullContent, - timestamp: /* @__PURE__ */ new Date(), - transportOrigin: "agent", - toolInvocations: [ - { - toolName: effectiveCall.toolName, - input: effectiveCall.input, - output: effectiveResult.output, - durationMs: effectiveResult.durationMs, - status: effectiveResult.status - } - ], - // Thread the original tool-call id so the LLM adapter can emit a - // `tool_use` block whose id matches the `tool_result` below. Without - // this, the Anthropic adapter synthesises two *independent* ids - // (random vs Date.now()) and the provider rejects the continuation - // call with "tool_result ... has no corresponding tool_use block". - // Mirrors the blocking codepath (executeTurn) which sets the same. - metadata: { toolUseId: effectiveCall.id } - }, - { - id: crypto.randomUUID(), - role: "tool", - content: typeof effectiveResult.output === "string" ? effectiveResult.output : JSON.stringify(effectiveResult.output), - timestamp: /* @__PURE__ */ new Date(), - transportOrigin: "tool", - metadata: { toolName: effectiveCall.toolName, callId: effectiveCall.id } - } - ]; - if (postTool.shortCircuited) { - events.push(annotationEvent(agent.id, sessionId, "streaming.short_circuit_after_emit", { - phase: "post_tool", - reason: postTool.reason - })); - toolLoopBreak = true; - break; - } - } - if (toolLoopBreak) - break; - if (tracker.isExhausted()) { - budgetExhaustedDuringLoop = true; - const status = tracker.getStatus(); - events.push(annotationEvent(agent.id, sessionId, "streaming.budget_exhausted", { - reason: status.exhaustedReason, - calls: status.calls - })); - yield ` -[Agent budget exhausted${status.exhaustedReason ? `: ${status.exhaustedReason}` : ""}]`; - break; - } - } - const candidateMessage = earlyShortCircuit ? earlyExitResponse ?? createAssistantMessage(crypto.randomUUID(), `[Agent short-circuited${earlyExitReason ? `: ${earlyExitReason}` : ""}]`, []) : createAssistantMessage(crypto.randomUUID(), budgetExhaustedDuringLoop && lastAssistantContent.trim().length === 0 ? "[Agent budget exhausted]" : lastAssistantContent, allToolResults.map((r) => ({ - toolName: r.toolName, - input: {}, - output: r.output, - durationMs: r.durationMs, - status: r.status - }))); - let responseMessage = candidateMessage; - let memoriesCaptured = []; - let droppedCandidates = []; - if (!earlyShortCircuit) { - const preCapture = await fire("pre_capture", { - response: candidateMessage, - toolResults: allToolResults, - ontology - }); - if (preCapture.correctionRequested) { - events.push(annotationEvent(agent.id, sessionId, "streaming.correction_requested", { - hookName: preCapture.hookName, - correctionPrompt: preCapture.correctionPrompt - })); - } else if (preCapture.shortCircuited) { - events.push(annotationEvent(agent.id, sessionId, "streaming.short_circuit_after_emit", { - phase: "pre_capture", - reason: preCapture.reason - })); - } - responseMessage = preCapture.shortCircuited && preCapture.finalResponse ? preCapture.finalResponse : candidateMessage; - try { - const captureResult = await captureFromResponse({ - response: responseMessage.content, - ontology, - agent, - sessionId, - turnId, - memory: deps.memory - }); - memoriesCaptured = captureResult.captured; - droppedCandidates = captureResult.dropped; - for (const errMsg of captureResult.errors) { - events.push(annotationEvent(agent.id, sessionId, "streaming.memory_capture_error", { - error: errMsg - })); - } - for (const fe of captureResult.frictionEvents) { - events.push(fe); - } - } catch (err) { - events.push(annotationEvent(agent.id, sessionId, "streaming.memory_capture_error", { - error: err instanceof Error ? err.message : String(err) - })); - } - const availableEntityTypesAtCapture = ontology.entityTypes.map((e) => e.name); - let recentlyCaptured; - if (memoriesCaptured.length > 0) { - for (const entry of memoriesCaptured) { - try { - const chain = await deps.memory.getSupersedeChain(entry.id); - if (chain.length === 0) - continue; - const propertyNames = Object.keys(entry.structured).sort(); - const nonIdKeys = propertyNames.filter((p) => p !== "id"); - const propertyName = nonIdKeys[0] ?? propertyNames[0]; - if (!propertyName) - continue; - const coverage = chain.filter((p) => propertyName in p.structured).length; - if (coverage < Math.ceil(chain.length / 2)) - continue; - const priorValues = [...chain].reverse().map((prior) => prior.structured[propertyName]); - recentlyCaptured = { - chainAnchor: entry.id, - entityType: entry.entityType, - propertyName, - currentValue: entry.structured[propertyName], - priorValues - }; - break; - } catch { - continue; - } - } - } - const postCapture = await fire("post_capture", { - captured: memoriesCaptured, - availableEntityTypes: availableEntityTypesAtCapture, - droppedCandidates, - ...recentlyCaptured ? { recentlyCaptured } : {} - }); - if (postCapture.shortCircuited) { - events.push(annotationEvent(agent.id, sessionId, "streaming.short_circuit_after_emit", { - phase: "post_capture", - reason: postCapture.reason - })); - } - } - session = addMessage(session, responseMessage); - await deps.sessions.save(session); - events.push(createEvent(crypto.randomUUID(), "message.sent", agent.id, { messageId: responseMessage.id }, sessionId)); - const finalBudgetStatus = tracker.getStatus(); - const budgetExhausted = budgetExhaustedDuringLoop || finalBudgetStatus.exhausted; - const result = { - response: responseMessage, - session, - memoriesCaptured, - events, - toolResults: allToolResults, - usage: { - inputTokens: totalInputTokens, - outputTokens: totalOutputTokens, - llmCalls, - // Compute via the shared `estimateCostUSD` helper so blocking + - // streaming produce identical numbers for the same model + tokens. - // Cache tokens flow through the optional usage fields so cached - // agents get accurate cost (cache_read at 0.1× input rate, cache_write - // at 1.25×). - estimatedCostUSD: estimateCostUSD(agent.config.modelId, { - inputTokens: totalInputTokens, - outputTokens: totalOutputTokens, - cacheReadTokens: totalCacheReadTokens, - cacheWriteTokens: totalCacheWriteTokens - }) - }, - budgetExhausted, - budgetStatus: { - calls: finalBudgetStatus.calls, - tokens: finalBudgetStatus.tokens, - timeMs: finalBudgetStatus.timeMs, - ...finalBudgetStatus.exhaustedReason ? { reason: finalBudgetStatus.exhaustedReason } : {} - } - }; - try { - await fire("post_turn", { - result, - availableEntityTypes: ontology.entityTypes.map((e) => e.name) - }); - } catch { - } - } catch (err) { - const partialBudgetStatus = tracker.getStatus(); - const partialResult = { - response: createAssistantMessage(crypto.randomUUID(), `[Agent error: ${err instanceof Error ? err.message : String(err)}]`, []), - session, - memoriesCaptured: [], - events, - toolResults: allToolResults, - usage: { - inputTokens: totalInputTokens, - outputTokens: totalOutputTokens, - llmCalls, - // Even on the error path, attribute real cost for tokens already - // consumed before the throw — billing observers / cost-trackers - // at post_turn should see the spend that already happened. - estimatedCostUSD: estimateCostUSD(agent.config.modelId, { - inputTokens: totalInputTokens, - outputTokens: totalOutputTokens, - cacheReadTokens: totalCacheReadTokens, - cacheWriteTokens: totalCacheWriteTokens - }) - }, - budgetExhausted: budgetExhaustedDuringLoop || partialBudgetStatus.exhausted, - budgetStatus: { - calls: partialBudgetStatus.calls, - tokens: partialBudgetStatus.tokens, - timeMs: partialBudgetStatus.timeMs, - ...partialBudgetStatus.exhaustedReason ? { reason: partialBudgetStatus.exhaustedReason } : {} - } - }; - try { - await fire("post_turn", { - result: partialResult, - availableEntityTypes: ontology.entityTypes.map((e) => e.name) - }); - } catch { - } - throw err; - } -} -function systemMessage(phase, reason, finalResponse) { - if (finalResponse?.content) - return finalResponse.content; - return `[Agent short-circuited at ${phase}${reason ? `: ${reason}` : ""}]`; -} -function annotationEvent(agentId, sessionId, key, data) { - return { - id: crypto.randomUUID(), - type: "turn.annotated", - agentId, - sessionId, - timestamp: /* @__PURE__ */ new Date(), - payload: { key, ...data } - }; -} - -// ../freya/packages/runtime/dist/create-agent-runtime.js -function createAgentRuntime(adapters, agents = /* @__PURE__ */ new Map()) { - const agentMap = new Map(agents); - const ontologyService = { - async compose(agentId) { - const agent = agentMap.get(agentId); - if (!agent) - throw new Error(`Agent not found: ${agentId}`); - const scopes = agent.config.ontologyScopes; - return adapters.ontologyRepo.compose(scopes); - }, - render(ontology) { - return renderOntologySimple(ontology); - }, - async validate(entityType, data) { - const firstAgent = agentMap.values().next().value; - if (!firstAgent) - return true; - const ontology = await adapters.ontologyRepo.compose(firstAgent.config.ontologyScopes); - const result = adapters.ontologyRepo.validateEntry(entityType, data, ontology); - return result.valid; - } - }; - const ontologyRenderer = { - render: renderOntologySimple - }; - const registry = { - async getAgent(agentId) { - return agentMap.get(agentId) ?? null; - }, - async listAgents() { - return Array.from(agentMap.values()); - }, - async registerAgent(config, deploymentId) { - const agent = createAgent(config, deploymentId); - agentMap.set(agent.id, agent); - return agent; - } - }; - return { - async handleMessage({ agentId, sessionId, message, budget }) { - const agent = agentMap.get(agentId); - if (!agent) - throw new Error(`Agent not found: ${agentId}`); - const result = await executeTurn(agent, sessionId, message, { - llm: adapters.llm, - tools: adapters.toolExecutor, - memory: adapters.memory, - sessions: adapters.sessions, - ontologyService, - ontologyRenderer, - transport: adapters.transport ?? noopTransport, - embedding: adapters.embedding - }, budget); - return { - message: result.response, - session: result.session, - memoriesCaptured: result.memoriesCaptured, - delegations: [], - usage: result.usage - }; - }, - handleMessageStream({ agentId, sessionId, message, budget, hooks, signal }) { - const agent = agentMap.get(agentId); - if (!agent) - throw new Error(`Agent not found: ${agentId}`); - return executeStreamingTurn(agent, sessionId, message, { - llm: adapters.llm, - tools: adapters.toolExecutor, - memory: adapters.memory, - sessions: adapters.sessions, - ontologyService, - ontologyRenderer, - embedding: adapters.embedding, - ...hooks ? { hooks } : {} - }, budget, signal); - }, - async startSession({ agentId, userId, transportId }) { - const session = createSession(crypto.randomUUID(), agentId, userId, transportId); - await adapters.sessions.save(session); - return session; - }, - async getAgent(agentId) { - return agentMap.get(agentId) ?? null; - }, - registry - }; -} -function renderOntologySimple(ontology) { - if (ontology.entityTypes.length === 0) - return ""; - const lines = ["# Domain Ontology"]; - for (const entity of ontology.entityTypes) { - const props = entity.properties.map((p) => p.name).join(", "); - const rels = ontology.relationships.filter((r) => r.fromType === entity.name).map((r) => `${r.name}\u2192${r.toType}`).join(", "); - let line = `## ${entity.name}: [${props}]`; - if (rels) - line += ` | ${rels}`; - if (entity.description && entity.description !== entity.name) { - line += ` -${entity.description}`; - } - lines.push(line); - } - return lines.join("\n"); -} -var noopTransport = { - async send() { - }, - async stream() { - } -}; - -// ../freya/packages/llm/dist/adapters/anthropic.js -function toAnthropicMessages(messages) { - const result = []; - for (const m of messages) { - if (m.role === "user") { - result.push({ role: "user", content: m.content }); - } else if (m.role === "assistant") { - if (m.toolInvocations && m.toolInvocations.length > 0) { - const contentBlocks = []; - if (m.content) { - contentBlocks.push({ type: "text", text: m.content }); - } - const toolUseId = m.metadata?.toolUseId || m.toolInvocations[0].toolName + "_" + Math.random().toString(36).slice(2); - for (const tool of m.toolInvocations) { - contentBlocks.push({ - type: "tool_use", - id: toolUseId, - name: tool.toolName, - input: tool.input - }); - } - result.push({ role: "assistant", content: contentBlocks }); - } else { - result.push({ role: "assistant", content: m.content }); - } - } else if (m.role === "tool") { - const toolName = m.metadata?.toolName || "unknown"; - const callId = m.metadata?.callId || toolName + "_" + Date.now(); - result.push({ - role: "user", - content: [ - { - type: "tool_result", - tool_use_id: callId, - content: m.content + newResult[${k}] = ${$}.value; + } + + `):v.write(` + if (${$}.issues.length) { + payload.issues = payload.issues.concat(${$}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${k}, ...iss.path] : [${k}] + }))); + } + + if (${$}.value === undefined) { + if (${k} in input) { + newResult[${k}] = undefined; } - ] - }); - } - } - return result; -} -function toAnthropicTools(tools) { - return tools.map((t) => ({ - name: t.name, - description: t.description, - input_schema: t.inputSchema - })); -} -var AnthropicLLM = class { - config; - constructor(config) { - this.config = config; - } - async complete(params) { - const body = { - model: params.model || this.config.defaultModel || "claude-sonnet-4-6", - max_tokens: params.maxTokens || this.config.maxTokens || 4096, - system: params.systemPrompt, - messages: toAnthropicMessages(params.messages) - }; - if (params.temperature !== void 0) { - body.temperature = params.temperature; - } - if (params.tools && params.tools.length > 0) { - body.tools = toAnthropicTools(params.tools); - } - const baseUrl = this.config.baseUrl || "https://api.anthropic.com"; - const response = await fetch(`${baseUrl}/v1/messages`, { - method: "POST", - headers: { - "Content-Type": "application/json", - "x-api-key": this.config.apiKey, - "anthropic-version": "2023-06-01" - }, - body: JSON.stringify(body) - }); - if (!response.ok) { - const errorBody = await response.text(); - throw new Error(`Anthropic API error: ${response.status} ${errorBody}`); - } - const data = await response.json(); - let content = ""; - const toolCalls = []; - for (const block of data.content || []) { - if (block.type === "text") { - content += block.text; - } else if (block.type === "tool_use") { - toolCalls.push({ - id: block.id, - toolName: block.name, - input: block.input, - timestamp: /* @__PURE__ */ new Date() - }); - } - } - return { - content, - toolCalls, - usage: { - inputTokens: data.usage?.input_tokens || 0, - outputTokens: data.usage?.output_tokens || 0 - }, - stopReason: data.stop_reason === "tool_use" ? "tool_use" : data.stop_reason === "max_tokens" ? "max_tokens" : "end_turn" - }; - } - async *stream(params) { - const body = { - model: params.model || this.config.defaultModel || "claude-sonnet-4-6", - max_tokens: params.maxTokens || this.config.maxTokens || 4096, - system: params.systemPrompt, - messages: toAnthropicMessages(params.messages), - stream: true - }; - if (params.temperature !== void 0) { - body.temperature = params.temperature; - } - if (params.tools && params.tools.length > 0) { - body.tools = toAnthropicTools(params.tools); - } - const baseUrl = this.config.baseUrl || "https://api.anthropic.com"; - const response = await fetch(`${baseUrl}/v1/messages`, { - method: "POST", - headers: { - "Content-Type": "application/json", - "x-api-key": this.config.apiKey, - "anthropic-version": "2023-06-01" - }, - body: JSON.stringify(body), - // Aborting this signal tears down the HTTP request to Anthropic, which - // stops token generation server-side — true cancellation, not just - // closing the consumer's reader. - signal: params.signal - }); - if (!response.ok) { - const errorBody = await response.text(); - throw new Error(`Anthropic streaming error: ${response.status} ${errorBody}`); - } - const reader = response.body?.getReader(); - if (!reader) - throw new Error("No response body for streaming"); - const decoder = new TextDecoder(); - let buffer = ""; - let inputTokens = 0; - let outputTokens = 0; - let cacheReadTokens = 0; - let cacheWriteTokens = 0; - let sawUsage = false; - const pendingToolBlocks = /* @__PURE__ */ new Map(); - const sanitizeTokens = (v) => { - if (typeof v !== "number" || !Number.isFinite(v) || v < 0) - return null; - return v; - }; - const doneChunk = () => { - if (!sawUsage) - return { type: "done" }; - const usage = { - inputTokens, - outputTokens - }; - if (cacheReadTokens > 0) - usage.cacheReadTokens = cacheReadTokens; - if (cacheWriteTokens > 0) - usage.cacheWriteTokens = cacheWriteTokens; - return { type: "done", usage }; - }; - while (true) { - const { done, value } = await reader.read(); - if (done) - break; - buffer += decoder.decode(value, { stream: true }); - const lines = buffer.split("\n"); - buffer = lines.pop() || ""; - for (const line of lines) { - if (!line.startsWith("data: ")) - continue; - const data = line.slice(6).trim(); - if (data === "[DONE]") { - yield doneChunk(); - return; - } - try { - const event = JSON.parse(data); - if (event.type === "message_start") { - const u = event.message?.usage; - if (u) { - const inp = sanitizeTokens(u.input_tokens); - const out = sanitizeTokens(u.output_tokens); - const cr = sanitizeTokens(u.cache_read_input_tokens); - const cw = sanitizeTokens(u.cache_creation_input_tokens); - if (inp !== null || out !== null || cr !== null || cw !== null) { - sawUsage = true; - if (inp !== null) - inputTokens = inp; - if (out !== null) - outputTokens = out; - if (cr !== null) - cacheReadTokens = cr; - if (cw !== null) - cacheWriteTokens = cw; - } - } - } else if (event.type === "content_block_delta") { - if (event.delta?.type === "text_delta") { - yield { type: "text", content: event.delta.text }; - } else if (event.delta?.type === "input_json_delta") { - const idx = event.index; - const pending = idx !== void 0 ? pendingToolBlocks.get(idx) : void 0; - if (pending && typeof event.delta.partial_json === "string") { - pending.jsonBuffer += event.delta.partial_json; - } - } - } else if (event.type === "content_block_start") { - if (event.content_block?.type === "tool_use") { - const idx = event.index; - if (idx !== void 0) { - pendingToolBlocks.set(idx, { - id: event.content_block.id, - toolName: event.content_block.name, - jsonBuffer: "" - }); - } - } - } else if (event.type === "content_block_stop") { - const idx = event.index; - const pending = idx !== void 0 ? pendingToolBlocks.get(idx) : void 0; - if (pending) { - let input = {}; - if (pending.jsonBuffer.trim().length > 0) { - try { - const parsed = JSON.parse(pending.jsonBuffer); - if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) { - input = parsed; - } - } catch { - } - } - yield { - type: "tool_call", - toolCall: { - id: pending.id, - toolName: pending.toolName, - input, - timestamp: /* @__PURE__ */ new Date() - } - }; - pendingToolBlocks.delete(idx); - } - } else if (event.type === "message_delta") { - const u = event.usage; - if (u) { - const out = sanitizeTokens(u.output_tokens); - if (out !== null) { - sawUsage = true; - outputTokens = out; - } - } - } else if (event.type === "message_stop") { - yield doneChunk(); - return; - } - } catch { - } - } - } - if (buffer.length > 0) { - for (const line of buffer.split("\n")) { - if (!line.startsWith("data: ")) - continue; - const data = line.slice(6).trim(); - if (data === "[DONE]" || data.length === 0) - continue; - try { - const event = JSON.parse(data); - if (event.type === "message_delta") { - const u = event.usage; - if (u) { - const out = sanitizeTokens(u.output_tokens); - if (out !== null) { - sawUsage = true; - outputTokens = out; - } - } - } - } catch { - } - } - } - yield doneChunk(); - } -}; - -// ../freya/packages/llm/dist/adapters/fake-embedding.js -var FakeEmbedding = class { - callCount = 0; - async embed(text) { - this.callCount++; - const vec = new Array(8).fill(0); - for (let i = 0; i < text.length; i++) { - vec[i % vec.length] += text.charCodeAt(i) / 1e3; - } - const magnitude = Math.sqrt(vec.reduce((s2, v) => s2 + v * v, 0)); - return magnitude > 0 ? vec.map((v) => v / magnitude) : vec; - } - async embedBatch(texts) { - return Promise.all(texts.map((t) => this.embed(t))); - } - getCallCount() { - return this.callCount; - } -}; - -// ../freya/packages/memory/dist/adapters/in-memory-repo.js -var InMemoryMemoryRepository = class { - entries = []; - events = []; - async store(entry) { - this.entries.push(entry); - this.events.push({ - id: crypto.randomUUID(), - entryId: entry.id, - action: "created", - newValue: entry.content, - author: entry.source.author, - timestamp: /* @__PURE__ */ new Date() - }); - } - async recall(params) { - const limit = params.limit ?? 10; - const queryLower = params.query.toLowerCase(); - const entries = this.entries.filter((e) => { - if (e.agentId !== params.agentId) - return false; - if (e.status !== "active") - return false; - if (params.scope && e.scope !== params.scope) - return false; - if (params.scopeId && e.scopeId !== params.scopeId) - return false; - if (params.entityType && e.entityType !== params.entityType) - return false; - return e.content.toLowerCase().includes(queryLower); - }).slice(0, limit); - const textMatchCount = entries.length; - return { - entries, - source: textMatchCount > 0 ? "text" : "none", - vectorCapable: false, - vectorMatchCount: 0, - textMatchCount - }; - } - async supersede(entryId, newEntryId) { - const entry = this.entries.find((e) => e.id === entryId); - if (entry) { - const idx = this.entries.indexOf(entry); - this.entries[idx] = { - ...entry, - status: "superseded", - supersededBy: newEntryId - }; - this.events.push({ - id: crypto.randomUUID(), - entryId, - action: "superseded", - previousValue: entry.content, - author: "system", - timestamp: /* @__PURE__ */ new Date() - }); - } - } - async getEventLog(entryId) { - return this.events.filter((e) => e.entryId === entryId); - } - async getByEntityType(agentId, entityType) { - return this.entries.filter((e) => e.agentId === agentId && e.entityType === entityType && e.status === "active"); - } - /** - * Walk the supersede chain backward from `entryId`. - * - * At each step we find entries whose `supersededBy` points at the current - * node, take the most recent one (by `createdAt` desc — handles the - * unusual case of multiple predecessors pointing at the same successor), - * and continue from there. A visited-set protects against pathological - * cycles (a node whose `supersededBy` ultimately loops back to itself or - * to an ancestor in the walk). - * - * Capped at 50 versions — long-lived facts can rack up a lot of versions, - * and the detector use case only needs "what shapes have we seen recently". - */ - async getSupersedeChain(entryId) { - const CAP = 50; - const chain = []; - const visited = /* @__PURE__ */ new Set(); - let cursor = entryId; - visited.add(cursor); - const anchor = this.entries.find((e) => e.id === entryId); - if (anchor === void 0) - return []; - while (chain.length < CAP) { - const predecessors = this.entries.filter((e) => e.supersededBy === cursor && e.agentId === anchor.agentId && e.scope === anchor.scope && e.scopeId === anchor.scopeId && e.status === "superseded").sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime()); - if (predecessors.length === 0) - break; - const prior = predecessors[0]; - if (visited.has(prior.id)) { - break; - } - visited.add(prior.id); - chain.push(prior); - cursor = prior.id; - } - return chain; - } - // Test helpers - getAll() { - return [...this.entries]; - } - getAllEvents() { - return [...this.events]; - } - clear() { - this.entries = []; - this.events = []; - } -}; - -// ../freya/packages/memory/dist/adapters/in-memory-session-repo.js -var InMemorySessionRepository = class { - sessions = /* @__PURE__ */ new Map(); - async get(id) { - return this.sessions.get(id) ?? null; - } - async save(session) { - this.sessions.set(session.id, session); - } - async findByUser(userId, agentId, limit) { - const matches2 = Array.from(this.sessions.values()).filter((s2) => s2.userId === userId && s2.agentId === agentId).sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime()); - return limit ? matches2.slice(0, limit) : matches2; - } - async findByUserLightweight(userId, agentId, limit) { - const matches2 = Array.from(this.sessions.values()).filter((s2) => s2.userId === userId && s2.agentId === agentId).sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime()); - const limited = limit ? matches2.slice(0, limit) : matches2; - return limited.map((s2) => { - const firstUserMsg = s2.messages.find((m) => m.role === "user"); - const lastMsg = s2.messages.length > 0 ? s2.messages[s2.messages.length - 1] : void 0; - return { - id: s2.id, - agentId: s2.agentId, - userId: s2.userId, - status: s2.status, - turnCount: s2.turnCount, - messageCount: s2.messages.length, - createdAt: s2.createdAt, - updatedAt: s2.updatedAt, - firstMessage: firstUserMsg ? firstUserMsg.content.substring(0, 100) : void 0, - lastMessage: lastMsg ? lastMsg.content.substring(0, 100) : void 0 - }; - }); - } - // Test helpers - clear() { - this.sessions.clear(); - } - getAll() { - return Array.from(this.sessions.values()); - } -}; - -// ../freya/packages/ontology/dist/composer/composer.js -function composeLayers(layers) { - const entityMap = /* @__PURE__ */ new Map(); - const allRelationships = []; - for (const layer of layers) { - for (const entity of layer.entityTypes) { - const existing = entityMap.get(entity.name); - if (existing) { - const existingPropNames = new Set(existing.properties.map((p) => p.name)); - const newProps = entity.properties.filter((p) => !existingPropNames.has(p.name)); - entityMap.set(entity.name, { - ...existing, - properties: [...existing.properties, ...newProps], - description: entity.description || existing.description - }); - } else { - entityMap.set(entity.name, entity); - } - } - allRelationships.push(...layer.relationships); - } - const relationshipMap = /* @__PURE__ */ new Map(); - for (const rel of allRelationships) { - relationshipMap.set(rel.id, rel); - } - return { - layers, - entityTypes: Array.from(entityMap.values()), - relationships: Array.from(relationshipMap.values()), - version: layers.map((l) => `${l.name}@${l.version}`).join("+") - }; -} - -// ../freya/packages/ontology/dist/validator/validator.js -function validateAgainstOntology(entityType, data, ontology) { - const errors = []; - const warnings = []; - const entity = ontology.entityTypes.find((e) => e.name === entityType); - if (!entity) { - return { - valid: false, - errors: [{ field: "entityType", message: `Unknown entity type: ${entityType}`, code: "unknown_entity" }], - warnings: [] - }; - } - for (const prop of entity.properties) { - if (prop.required && !(prop.name in data)) { - errors.push({ - field: prop.name, - message: `Required property missing: ${prop.name}`, - code: "missing_required" - }); - } - } - for (const [key, value] of Object.entries(data)) { - const prop = entity.properties.find((p) => p.name === key); - if (!prop) { - warnings.push(`Property "${key}" not defined in ontology for ${entityType}`); - continue; - } - if (prop.type === "enum" && prop.enumValues && value !== void 0) { - if (!prop.enumValues.includes(String(value))) { - errors.push({ - field: key, - message: `Invalid value "${value}" for enum ${key}. Expected one of: ${prop.enumValues.join(", ")}`, - code: "invalid_enum" - }); - } - } - if (value !== void 0 && value !== null) { - const typeValid = checkType(value, prop.type); - if (!typeValid) { - errors.push({ - field: key, - message: `Expected ${prop.type} for ${key}, got ${typeof value}`, - code: "invalid_type" - }); - } - } - } - return { - valid: errors.length === 0, - errors, - warnings - }; -} -function checkType(value, expectedType) { - switch (expectedType) { - case "string": - case "enum": - return typeof value === "string"; - case "number": - return typeof value === "number"; - case "boolean": - return typeof value === "boolean"; - case "date": - return typeof value === "string" || value instanceof Date; - case "reference": - return typeof value === "string"; - default: - return true; - } -} - -// ../freya/packages/ontology/dist/adapters/in-memory-ontology-repo.js -var InMemoryOntologyRepository = class { - layers = /* @__PURE__ */ new Map(); - async getLayer(id) { - return this.layers.get(id) ?? null; - } - async getLayersByScope(scope) { - return Array.from(this.layers.values()).filter((l) => l.scope === scope); - } - async compose(layerIds) { - const layers = layerIds.map((id) => this.layers.get(id)).filter((l) => l != null); - return composeLayers(layers); - } - validateEntry(entityType, data, ontology) { - const result = validateAgainstOntology(entityType, data, ontology); - return { valid: result.valid, errors: result.errors.map((e) => e.message) }; - } - // Test helpers - addLayer(layer) { - this.layers.set(layer.id, layer); - } - clear() { - this.layers.clear(); - } -}; - -// ../freya/packages/ontology/dist/seed/loader.js -function parseOntologyYaml(id, raw) { - const entityTypes = []; - const relationships = []; - for (const [entityName, entityDef] of Object.entries(raw.entities || {})) { - const properties = []; - if (entityDef.properties) { - for (const prop of entityDef.properties) { - properties.push({ - name: prop, - type: "string", - required: false, - description: "" - }); - } - } - for (const [key, value] of Object.entries(entityDef)) { - if (Array.isArray(value) && key !== "properties" && key !== "belongs_to" && key !== "has_many" && key !== "connects" && value.every((v) => typeof v === "string")) { - properties.push({ - name: key, - type: "enum", - enumValues: value, - required: false, - description: `${key} for ${entityName}` - }); - } - } - entityTypes.push({ - id: `${id}:${entityName}`, - layerId: id, - name: entityName, - properties, - description: entityDef.description || entityName - }); - const belongsTo = entityDef.belongs_to ? Array.isArray(entityDef.belongs_to) ? entityDef.belongs_to : [entityDef.belongs_to] : []; - for (const target of belongsTo) { - relationships.push({ - id: `${id}:${entityName}:belongs_to:${target}`, - layerId: id, - name: "belongs_to", - fromType: entityName, - toType: target, - cardinality: "many_to_many", - description: `${entityName} belongs to ${target}` - }); - } - for (const target of entityDef.has_many || []) { - relationships.push({ - id: `${id}:${entityName}:has_many:${target}`, - layerId: id, - name: "has_many", - fromType: entityName, - toType: target, - cardinality: "one_to_many", - description: `${entityName} has many ${target}` - }); - } - for (const target of entityDef.connects || []) { - relationships.push({ - id: `${id}:${entityName}:connects:${target}`, - layerId: id, - name: "connects", - fromType: entityName, - toType: target, - cardinality: "many_to_many", - description: `${entityName} connects to ${target}` - }); - } - } - return { - id, - name: raw.name, - scope: raw.scope, - version: 1, - entityTypes, - relationships, - createdAt: /* @__PURE__ */ new Date(), - updatedAt: /* @__PURE__ */ new Date() - }; -} - -// website/tools/freya-vendor/entry.mjs -var AGENT_ID = "frigg-web"; -var TRANSPORT = "netlify-web"; -var FRIGG_ONTOLOGY = { - name: "frigg", - scope: "domain", - entities: { - Platform: { - description: "A third-party software product Frigg integrates with (e.g. HubSpot, Salesforce, Attio).", - properties: ["name", "vendor"] - }, - ApiModule: { - description: "A prebuilt Frigg connector for a platform API, installed with `frigg install ` and drawn from the api-module-library.", - properties: ["name", "provider", "authType"], - category: [ - "ai", - "analytics", - "commerce", - "communication", - "crm", - "devtools", - "finance", - "hr", - "marketing", - "other", - "productivity", - "storage", - "support" - ], - complexity: ["Low", "Medium", "High"], - status: ["Active", "Beta", "Planned"], - belongs_to: "Platform" - }, - Integration: { - description: "A running integration a developer builds by extending IntegrationBase, wiring API modules to events (USER_ACTION, CRON, QUEUE, WEBHOOK).", - properties: ["name", "useCase"], - connects: ["ApiModule", "Primitive"] - }, - Primitive: { - description: "A Frigg building block exposed to developers and their agents: an Endpoint, a Queue, a Provider-native backend, or a Fenestra in-app UI experience.", - properties: ["name"], - kind: ["Endpoint", "Queue", "ProviderNative", "Fenestra"] - }, - Capability: { - description: "A typed declaration of what a module or integration can do, pointing at a spec and its implementation (the mcp-tool / agent-tooling surface).", - properties: ["name", "spec"], - belongs_to: "ApiModule" - }, - Adr: { - description: 'A Frigg architecture decision record shaping the roadmap, tracked on the "next" branch and surfaced at /roadmap/.', - properties: ["num", "title", "theme"], - status: ["Accepted", "Proposed", "Superseded", "Draft"] - }, - Visitor: { - description: "A person chatting with the assistant on the site.", - properties: ["name", "stack", "interest"] - } - } -}; -var activeData = { adrs: [], apis: [], categories: [], builtCount: 0 }; -var s = (v) => typeof v === "string" ? v.toLowerCase() : ""; -var matches = (hay, q) => !q || s(hay).includes(s(q)); -var RoadmapTools = class { - async discoverTools(scope) { - if (scope !== "roadmap") return []; - return [ - { - name: "catalog_stats", - description: 'Frigg roadmap catalog summary: number of ADRs, number of API modules, how many are already built, and the list of API categories. Call this first for any "how many / what categories" question.', - inputSchema: { type: "object", properties: {}, additionalProperties: false }, - source: "roadmap", - requiresApproval: false, - permissionScope: "roadmap:read" - }, - { - name: "search_adrs", - description: "Search Frigg architecture decision records (ADRs). Filter by free-text query (matches title/summary/theme) and/or status (e.g. Accepted, Proposed). Returns matching ADRs with number, title, status, theme, one-line summary, and URL.", - inputSchema: { - type: "object", - properties: { - query: { type: "string", description: "Free-text filter over title/summary/theme" }, - status: { type: "string", description: 'Exact status filter, e.g. "Accepted"' } - }, - additionalProperties: false - }, - source: "roadmap", - requiresApproval: false, - permissionScope: "roadmap:read" - }, - { - name: "search_apis", - description: "Search the Frigg API module catalog (224 integrations). Filter by free-text query (matches name/provider/description/tags), category, or built=true to only return modules that already exist in api-module-library. Returns a capped list plus the total match count so you can point people to /roadmap/ for the full set.", - inputSchema: { - type: "object", - properties: { - query: { type: "string" }, - category: { type: "string", description: "One of the catalog categories" }, - built: { type: "boolean", description: "If true, only modules already built" } - }, - additionalProperties: false - }, - source: "roadmap", - requiresApproval: false, - permissionScope: "roadmap:read" - } - ]; - } - async execute(call) { - const start = Date.now(); - const done = (output, status = "success", error) => ({ - callId: call.id, - toolName: call.toolName, - output, - status, - error, - durationMs: Date.now() - start, - timestamp: /* @__PURE__ */ new Date() - }); - try { - const input = call.input || {}; - if (call.toolName === "catalog_stats") { - return done({ - adrCount: activeData.adrs.length, - apiCount: activeData.apis.length, - builtCount: activeData.builtCount, - categories: activeData.categories - }); - } - if (call.toolName === "search_adrs") { - const hits = activeData.adrs.filter( - (a) => (matches(a.title, input.query) || matches(a.summary, input.query) || matches(a.theme, input.query)) && (!input.status || s(a.status) === s(input.status)) - ); - return done({ - total: hits.length, - adrs: hits.slice(0, 12).map((a) => ({ - num: a.num, - title: a.title, - status: a.status, - theme: a.theme, - summary: a.summary, - url: a.url - })) - }); - } - if (call.toolName === "search_apis") { - const hits = activeData.apis.filter( - (a) => (matches(a.name, input.query) || matches(a.provider, input.query) || matches(a.description, input.query) || Array.isArray(a.tags) && a.tags.some((t) => matches(t, input.query))) && (!input.category || s(a.category) === s(input.category)) && (input.built === void 0 || Boolean(a.built) === Boolean(input.built)) - ); - return done({ - total: hits.length, - showing: Math.min(hits.length, 15), - apis: hits.slice(0, 15).map((a) => ({ - slug: a.slug, - name: a.name, - provider: a.provider, - category: a.category, - status: a.status, - complexity: a.complexity, - built: !!a.built, - library: a.library - })) - }); - } - return done(null, "error", `unknown tool: ${call.toolName}`); - } catch (e) { - return done(null, "error", e && e.message ? e.message : String(e)); - } - } -}; -var runtime = null; -var sessionsRepo = null; -var registered = false; -function getRuntime() { - if (runtime) return runtime; - sessionsRepo = new InMemorySessionRepository(); - const apiKey = process.env.ANTHROPIC_API_KEY || ""; - const baseUrl = process.env.ANTHROPIC_BASE_URL || void 0; - runtime = createAgentRuntime({ - llm: new AnthropicLLM({ - apiKey, - baseUrl, - defaultModel: process.env.ASSISTANT_MODEL || "claude-opus-4-8", - maxTokens: 900 - }), - toolExecutor: new RoadmapTools(), - memory: new InMemoryMemoryRepository(), - ontologyRepo: (() => { - const repo = new InMemoryOntologyRepository(); - repo.addLayer(parseOntologyYaml("frigg", FRIGG_ONTOLOGY)); - return repo; - })(), - sessions: sessionsRepo, - embedding: new FakeEmbedding() - }); - return runtime; -} -async function ensureAgent(rt, systemPrompt, model) { - if (registered) return; - await rt.registry.registerAgent( - { - id: AGENT_ID, - name: "Freya", - type: "shared", - systemPrompt, - ontologyScopes: ["frigg"], - memoryNamespaces: ["default"], - toolScopes: ["roadmap"], - routines: [], - delegationTargets: [], - modelId: model || process.env.ASSISTANT_MODEL || "claude-opus-4-8", - maxTurns: 6 - }, - "friggframework-org" - ); - registered = true; -} -async function runTurn({ systemPrompt, model, messages, data }) { - if (data) { - const apis = data.apis || {}; - activeData = { - adrs: data.adrs && data.adrs.adrs || data.adrs || [], - apis: apis.apis || (Array.isArray(apis) ? apis : []), - categories: apis.categories || [], - builtCount: apis.builtCount || 0 - }; - } - const rt = getRuntime(); - await ensureAgent(rt, systemPrompt, model); - const history = messages.slice(0, -1); - const last = messages[messages.length - 1]; - const sessionId = crypto.randomUUID(); - let session = createSession(sessionId, AGENT_ID, "web-visitor", TRANSPORT); - for (const m of history) { - const msg = m.role === "assistant" ? createAssistantMessage(crypto.randomUUID(), m.content) : createUserMessage(crypto.randomUUID(), m.content, TRANSPORT); - session = addMessage(session, msg); - } - await sessionsRepo.save(session); - const result = await rt.handleMessage({ - agentId: AGENT_ID, - sessionId, - message: createUserMessage(crypto.randomUUID(), last.content, TRANSPORT) - }); - return result && result.message && result.message.content || ""; -} -export { - runTurn -}; + } else { + newResult[${k}] = ${$}.value; + } + + `)}v.write("payload.value = newResult;"),v.write("return payload;");let S=v.compile();return(_,$)=>S(m,_,$)},i,a=Rn,s=!uc.jitless,u=s&&fp.value,l=t.catchall,d;e._zod.parse=(m,v)=>{d??(d=n.value);let g=m.value;return a(g)?s&&u&&v?.async===!1&&v.jitless!==!0?(i||(i=o(t.shape)),m=i(m,v),l?I_([],g,m,v,d,e):m):r(m,v):(m.issues.push({expected:"object",code:"invalid_type",input:g,inst:e}),m)}});zc=C("$ZodUnion",(e,t)=>{we.init(e,t),Ie(e._zod,"optin",()=>t.options.some(o=>o._zod.optin==="optional")?"optional":void 0),Ie(e._zod,"optout",()=>t.options.some(o=>o._zod.optout==="optional")?"optional":void 0),Ie(e._zod,"values",()=>{if(t.options.every(o=>o._zod.values))return new Set(t.options.flatMap(o=>Array.from(o._zod.values)))}),Ie(e._zod,"pattern",()=>{if(t.options.every(o=>o._zod.pattern)){let o=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${o.map(i=>Bi(i.source)).join("|")})$`)}});let r=t.options.length===1,n=t.options[0]._zod.run;e._zod.parse=(o,i)=>{if(r)return n(o,i);let a=!1,s=[];for(let c of t.options){let u=c._zod.run({value:o.value,issues:[]},i);if(u instanceof Promise)s.push(u),a=!0;else{if(u.issues.length===0)return u;s.push(u)}}return a?Promise.all(s).then(c=>Nv(c,o,e,i)):Nv(s,o,e,i)}});T_=C("$ZodXor",(e,t)=>{zc.init(e,t),t.inclusive=!1;let r=t.options.length===1,n=t.options[0]._zod.run;e._zod.parse=(o,i)=>{if(r)return n(o,i);let a=!1,s=[];for(let c of t.options){let u=c._zod.run({value:o.value,issues:[]},i);u instanceof Promise?(s.push(u),a=!0):s.push(u)}return a?Promise.all(s).then(c=>jv(c,o,e,i)):jv(s,o,e,i)}}),C_=C("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,zc.init(e,t);let r=e._zod.parse;Ie(e._zod,"propValues",()=>{let o={};for(let i of t.options){let a=i._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let[s,c]of Object.entries(a)){o[s]||(o[s]=new Set);for(let u of c)o[s].add(u)}}return o});let n=_o(()=>{let o=t.options,i=new Map;for(let a of o){let s=a._zod.propValues?.[t.discriminator];if(!s||s.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(let c of s){if(i.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);i.set(c,a)}}return i});e._zod.parse=(o,i)=>{let a=o.value;if(!Rn(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),o;let s=n.value.get(a?.[t.discriminator]);return s?s._zod.run(o,i):t.unionFallback?r(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:a,path:[t.discriminator],inst:e}),o)}}),A_=C("$ZodIntersection",(e,t)=>{we.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,i=t.left._zod.run({value:o,issues:[]},n),a=t.right._zod.run({value:o,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([c,u])=>Uv(r,c,u)):Uv(r,i,a)}});am=C("$ZodTuple",(e,t)=>{we.init(e,t);let r=t.items;e._zod.parse=(n,o)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({input:i,inst:e,expected:"tuple",code:"invalid_type"}),n;n.value=[];let a=[],s=[...r].reverse().findIndex(l=>l._zod.optin!=="optional"),c=s===-1?0:r.length-s;if(!t.rest){let l=i.length>r.length,d=i.length=i.length&&u>=c)continue;let d=l._zod.run({value:i[u],issues:[]},o);d instanceof Promise?a.push(d.then(m=>vc(m,n,u))):vc(d,n,u)}if(t.rest){let l=i.slice(r.length);for(let d of l){u++;let m=t.rest._zod.run({value:d,issues:[]},o);m instanceof Promise?a.push(m.then(v=>vc(v,n,u))):vc(m,n,u)}}return a.length?Promise.all(a).then(()=>n):n}});O_=C("$ZodRecord",(e,t)=>{we.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Vr(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let i=[],a=t.keyType._zod.values;if(a){r.value={};let s=new Set;for(let u of a)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){s.add(typeof u=="number"?u.toString():u);let l=t.valueType._zod.run({value:o[u],issues:[]},n);l instanceof Promise?i.push(l.then(d=>{d.issues.length&&r.issues.push(...Ot(u,d.issues)),r.value[u]=d.value})):(l.issues.length&&r.issues.push(...Ot(u,l.issues)),r.value[u]=l.value)}let c;for(let u in o)s.has(u)||(c=c??[],c.push(u));c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:c})}else{r.value={};for(let s of Reflect.ownKeys(o)){if(s==="__proto__")continue;let c=t.keyType._zod.run({value:s,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof s=="string"&&fc.test(s)&&c.issues.length){let d=t.keyType._zod.run({value:Number(s),issues:[]},n);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(c=d)}if(c.issues.length){t.mode==="loose"?r.value[s]=o[s]:r.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(d=>Rt(d,n,lt())),input:s,path:[s],inst:e});continue}let l=t.valueType._zod.run({value:o[s],issues:[]},n);l instanceof Promise?i.push(l.then(d=>{d.issues.length&&r.issues.push(...Ot(s,d.issues)),r.value[c.value]=d.value})):(l.issues.length&&r.issues.push(...Ot(s,l.issues)),r.value[c.value]=l.value)}}return i.length?Promise.all(i).then(()=>r):r}}),N_=C("$ZodMap",(e,t)=>{we.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!(o instanceof Map))return r.issues.push({expected:"map",code:"invalid_type",input:o,inst:e}),r;let i=[];r.value=new Map;for(let[a,s]of o){let c=t.keyType._zod.run({value:a,issues:[]},n),u=t.valueType._zod.run({value:s,issues:[]},n);c instanceof Promise||u instanceof Promise?i.push(Promise.all([c,u]).then(([l,d])=>{Mv(l,d,r,a,o,e,n)})):Mv(c,u,r,a,o,e,n)}return i.length?Promise.all(i).then(()=>r):r}});j_=C("$ZodSet",(e,t)=>{we.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!(o instanceof Set))return r.issues.push({input:o,inst:e,expected:"set",code:"invalid_type"}),r;let i=[];r.value=new Set;for(let a of o){let s=t.valueType._zod.run({value:a,issues:[]},n);s instanceof Promise?i.push(s.then(c=>Dv(c,r))):Dv(s,r)}return i.length?Promise.all(i).then(()=>r):r}});U_=C("$ZodEnum",(e,t)=>{we.init(e,t);let r=Wi(t.entries),n=new Set(r);e._zod.values=n,e._zod.pattern=new RegExp(`^(${r.filter(o=>Gi.has(typeof o)).map(o=>typeof o=="string"?qt(o):o.toString()).join("|")})$`),e._zod.parse=(o,i)=>{let a=o.value;return n.has(a)||o.issues.push({code:"invalid_value",values:r,input:a,inst:e}),o}}),M_=C("$ZodLiteral",(e,t)=>{if(we.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");let r=new Set(t.values);e._zod.values=r,e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?qt(n):n?qt(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,o)=>{let i=n.value;return r.has(i)||n.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),n}}),D_=C("$ZodFile",(e,t)=>{we.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;return o instanceof File||r.issues.push({expected:"file",code:"invalid_type",input:o,inst:e}),r}}),q_=C("$ZodTransform",(e,t)=>{we.init(e,t),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new En(e.constructor.name);let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(a=>(r.value=a,r));if(o instanceof Promise)throw new ir;return r.value=o,r}});sm=C("$ZodOptional",(e,t)=>{we.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Ie(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ie(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Bi(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(t.innerType._zod.optin==="optional"){let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>qv(i,r.value)):qv(o,r.value)}return r.value===void 0?r:t.innerType._zod.run(r,n)}}),L_=C("$ZodExactOptional",(e,t)=>{sm.init(e,t),Ie(e._zod,"values",()=>t.innerType._zod.values),Ie(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),V_=C("$ZodNullable",(e,t)=>{we.init(e,t),Ie(e._zod,"optin",()=>t.innerType._zod.optin),Ie(e._zod,"optout",()=>t.innerType._zod.optout),Ie(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Bi(r.source)}|null)$`):void 0}),Ie(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),K_=C("$ZodDefault",(e,t)=>{we.init(e,t),e._zod.optin="optional",Ie(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>Lv(i,t)):Lv(o,t)}});J_=C("$ZodPrefault",(e,t)=>{we.init(e,t),e._zod.optin="optional",Ie(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),F_=C("$ZodNonOptional",(e,t)=>{we.init(e,t),Ie(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>Vv(i,e)):Vv(o,e)}});H_=C("$ZodSuccess",(e,t)=>{we.init(e,t),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new En("ZodSuccess");let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>(r.value=i.issues.length===0,r)):(r.value=o.issues.length===0,r)}}),Z_=C("$ZodCatch",(e,t)=>{we.init(e,t),Ie(e._zod,"optin",()=>t.innerType._zod.optin),Ie(e._zod,"optout",()=>t.innerType._zod.optout),Ie(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>(r.value=i.value,i.issues.length&&(r.value=t.catchValue({...r,error:{issues:i.issues.map(a=>Rt(a,n,lt()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(i=>Rt(i,n,lt()))},input:r.value}),r.issues=[]),r)}}),W_=C("$ZodNaN",(e,t)=>{we.init(e,t),e._zod.parse=(r,n)=>((typeof r.value!="number"||!Number.isNaN(r.value))&&r.issues.push({input:r.value,inst:e,expected:"nan",code:"invalid_type"}),r)}),B_=C("$ZodPipe",(e,t)=>{we.init(e,t),Ie(e._zod,"values",()=>t.in._zod.values),Ie(e._zod,"optin",()=>t.in._zod.optin),Ie(e._zod,"optout",()=>t.out._zod.optout),Ie(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){let i=t.out._zod.run(r,n);return i instanceof Promise?i.then(a=>_c(a,t.in,n)):_c(i,t.in,n)}let o=t.in._zod.run(r,n);return o instanceof Promise?o.then(i=>_c(i,t.out,n)):_c(o,t.out,n)}});kc=C("$ZodCodec",(e,t)=>{we.init(e,t),Ie(e._zod,"values",()=>t.in._zod.values),Ie(e._zod,"optin",()=>t.in._zod.optin),Ie(e._zod,"optout",()=>t.out._zod.optout),Ie(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(r,n)=>{if((n.direction||"forward")==="forward"){let i=t.in._zod.run(r,n);return i instanceof Promise?i.then(a=>Sc(a,t,n)):Sc(i,t,n)}else{let i=t.out._zod.run(r,n);return i instanceof Promise?i.then(a=>Sc(a,t,n)):Sc(i,t,n)}}});G_=C("$ZodReadonly",(e,t)=>{we.init(e,t),Ie(e._zod,"propValues",()=>t.innerType._zod.propValues),Ie(e._zod,"values",()=>t.innerType._zod.values),Ie(e._zod,"optin",()=>t.innerType?._zod?.optin),Ie(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(Kv):Kv(o)}});X_=C("$ZodTemplateLiteral",(e,t)=>{we.init(e,t);let r=[];for(let n of t.parts)if(typeof n=="object"&&n!==null){if(!n._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...n._zod.traits].shift()}`);let o=n._zod.pattern instanceof RegExp?n._zod.pattern.source:n._zod.pattern;if(!o)throw new Error(`Invalid template literal part: ${n._zod.traits}`);let i=o.startsWith("^")?1:0,a=o.endsWith("$")?o.length-1:o.length;r.push(o.slice(i,a))}else if(n===null||hp.has(typeof n))r.push(qt(`${n}`));else throw new Error(`Invalid template literal part: ${n}`);e._zod.pattern=new RegExp(`^${r.join("")}$`),e._zod.parse=(n,o)=>typeof n.value!="string"?(n.issues.push({input:n.value,inst:e,expected:"string",code:"invalid_type"}),n):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(n.value)||n.issues.push({input:n.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),n)}),Y_=C("$ZodFunction",(e,t)=>(we.init(e,t),e._def=t,e._zod.def=t,e.implement=r=>{if(typeof r!="function")throw new Error("implement() must be called with a function");return function(...n){let o=e._def.input?$p(e._def.input,n):n,i=Reflect.apply(r,this,o);return e._def.output?$p(e._def.output,i):i}},e.implementAsync=r=>{if(typeof r!="function")throw new Error("implementAsync() must be called with a function");return async function(...n){let o=e._def.input?await wp(e._def.input,n):n,i=await Reflect.apply(r,this,o);return e._def.output?await wp(e._def.output,i):i}},e._zod.parse=(r,n)=>typeof r.value!="function"?(r.issues.push({code:"invalid_type",expected:"function",input:r.value,inst:e}),r):(e._def.output&&e._def.output._zod.def.type==="promise"?r.value=e.implementAsync(r.value):r.value=e.implement(r.value),r),e.input=(...r)=>{let n=e.constructor;return Array.isArray(r[0])?new n({type:"function",input:new am({type:"tuple",items:r[0],rest:r[1]}),output:e._def.output}):new n({type:"function",input:r[0],output:e._def.output})},e.output=r=>{let n=e.constructor;return new n({type:"function",input:e._def.input,output:r})},e)),Q_=C("$ZodPromise",(e,t)=>{we.init(e,t),e._zod.parse=(r,n)=>Promise.resolve(r.value).then(o=>t.innerType._zod.run({value:o,issues:[]},n))}),eS=C("$ZodLazy",(e,t)=>{we.init(e,t),Ie(e._zod,"innerType",()=>t.getter()),Ie(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),Ie(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),Ie(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),Ie(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),tS=C("$ZodCustom",(e,t)=>{Je.init(e,t),we.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{let n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(i=>Jv(i,r,n,e));Jv(o,r,n,e)}})});var rS=q(()=>{de()});var nS=q(()=>{de()});var oS=q(()=>{de()});var iS=q(()=>{de()});var aS=q(()=>{de()});var sS=q(()=>{de()});var cS=q(()=>{de()});var uS=q(()=>{de()});function um(){return{localeError:fR()}}var fR,lm=q(()=>{de();fR=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(o){return e[o]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{let i=n[o.expected]??o.expected,a=Se(o.input),s=n[a]??a;return`Invalid input: expected ${i}, received ${s}`}case"invalid_value":return o.values.length===1?`Invalid input: expected ${ye(o.values[0])}`:`Invalid option: expected one of ${ge(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",a=t(o.origin);return a?`Too big: expected ${o.origin??"value"} to have ${i}${o.maximum.toString()} ${a.unit??"elements"}`:`Too big: expected ${o.origin??"value"} to be ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",a=t(o.origin);return a?`Too small: expected ${o.origin} to have ${i}${o.minimum.toString()} ${a.unit}`:`Too small: expected ${o.origin} to be ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Invalid string: must start with "${i.prefix}"`:i.format==="ends_with"?`Invalid string: must end with "${i.suffix}"`:i.format==="includes"?`Invalid string: must include "${i.includes}"`:i.format==="regex"?`Invalid string: must match pattern ${i.pattern}`:`Invalid ${r[i.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${ge(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}}});var lS=q(()=>{de()});var dS=q(()=>{de()});var pS=q(()=>{de()});var mS=q(()=>{de()});var fS=q(()=>{de()});var hS=q(()=>{de()});var gS=q(()=>{de()});var yS=q(()=>{de()});var vS=q(()=>{de()});var _S=q(()=>{de()});var SS=q(()=>{de()});var bS=q(()=>{de()});var $S=q(()=>{de()});var wS=q(()=>{de()});var dm=q(()=>{de()});var zS=q(()=>{dm()});var kS=q(()=>{de()});var ES=q(()=>{de()});var RS=q(()=>{de()});var xS=q(()=>{de()});var IS=q(()=>{de()});var PS=q(()=>{de()});var TS=q(()=>{de()});var CS=q(()=>{de()});var AS=q(()=>{de()});var OS=q(()=>{de()});var NS=q(()=>{de()});var jS=q(()=>{de()});var US=q(()=>{de()});var MS=q(()=>{de()});var DS=q(()=>{de()});var qS=q(()=>{de()});var pm=q(()=>{de()});var LS=q(()=>{pm()});var VS=q(()=>{de()});var KS=q(()=>{de()});var JS=q(()=>{de()});var FS=q(()=>{de()});var HS=q(()=>{de()});var ZS=q(()=>{de()});var mm=q(()=>{rS();nS();oS();iS();aS();sS();cS();uS();lm();lS();dS();pS();mS();fS();hS();gS();yS();vS();_S();SS();bS();$S();wS();zS();dm();kS();ES();RS();xS();IS();PS();TS();CS();AS();OS();NS();jS();US();MS();DS();qS();LS();pm();VS();KS();JS();FS();HS();ZS()});function GS(){return new fm}var BS,fm,xt,sa=q(()=>{fm=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...r){let n=r[0];return this._map.set(t,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let n={...this.get(r)??{}};delete n.id;let o={...n,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}};(BS=globalThis).__zod_globalRegistry??(BS.__zod_globalRegistry=GS());xt=globalThis.__zod_globalRegistry});function XS(e,t){return new e({type:"string",...X(t)})}function YS(e,t){return new e({type:"string",coerce:!0,...X(t)})}function hm(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...X(t)})}function Ec(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...X(t)})}function gm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...X(t)})}function ym(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...X(t)})}function vm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...X(t)})}function _m(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...X(t)})}function Rc(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...X(t)})}function Sm(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...X(t)})}function bm(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...X(t)})}function $m(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...X(t)})}function wm(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...X(t)})}function zm(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...X(t)})}function km(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...X(t)})}function Em(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...X(t)})}function Rm(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...X(t)})}function xm(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...X(t)})}function QS(e,t){return new e({type:"string",format:"mac",check:"string_format",abort:!1,...X(t)})}function Im(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...X(t)})}function Pm(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...X(t)})}function Tm(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...X(t)})}function Cm(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...X(t)})}function Am(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...X(t)})}function Om(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...X(t)})}function eb(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...X(t)})}function tb(e,t){return new e({type:"string",format:"date",check:"string_format",...X(t)})}function rb(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...X(t)})}function nb(e,t){return new e({type:"string",format:"duration",check:"string_format",...X(t)})}function ob(e,t){return new e({type:"number",checks:[],...X(t)})}function ib(e,t){return new e({type:"number",coerce:!0,checks:[],...X(t)})}function ab(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...X(t)})}function sb(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float32",...X(t)})}function cb(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"float64",...X(t)})}function ub(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"int32",...X(t)})}function lb(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"uint32",...X(t)})}function db(e,t){return new e({type:"boolean",...X(t)})}function pb(e,t){return new e({type:"boolean",coerce:!0,...X(t)})}function mb(e,t){return new e({type:"bigint",...X(t)})}function fb(e,t){return new e({type:"bigint",coerce:!0,...X(t)})}function hb(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...X(t)})}function gb(e,t){return new e({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...X(t)})}function yb(e,t){return new e({type:"symbol",...X(t)})}function vb(e,t){return new e({type:"undefined",...X(t)})}function _b(e,t){return new e({type:"null",...X(t)})}function Sb(e){return new e({type:"any"})}function bb(e){return new e({type:"unknown"})}function $b(e,t){return new e({type:"never",...X(t)})}function wb(e,t){return new e({type:"void",...X(t)})}function zb(e,t){return new e({type:"date",...X(t)})}function kb(e,t){return new e({type:"date",coerce:!0,...X(t)})}function Eb(e,t){return new e({type:"nan",...X(t)})}function Jr(e,t){return new Qp({check:"less_than",...X(t),value:e,inclusive:!1})}function Wt(e,t){return new Qp({check:"less_than",...X(t),value:e,inclusive:!0})}function Fr(e,t){return new em({check:"greater_than",...X(t),value:e,inclusive:!1})}function Nt(e,t){return new em({check:"greater_than",...X(t),value:e,inclusive:!0})}function Rb(e){return Fr(0,e)}function xb(e){return Jr(0,e)}function Ib(e){return Wt(0,e)}function Pb(e){return Nt(0,e)}function $o(e,t){return new fv({check:"multiple_of",...X(t),value:e})}function wo(e,t){return new yv({check:"max_size",...X(t),maximum:e})}function Hr(e,t){return new vv({check:"min_size",...X(t),minimum:e})}function ca(e,t){return new _v({check:"size_equals",...X(t),size:e})}function ua(e,t){return new Sv({check:"max_length",...X(t),maximum:e})}function In(e,t){return new bv({check:"min_length",...X(t),minimum:e})}function la(e,t){return new $v({check:"length_equals",...X(t),length:e})}function xc(e,t){return new wv({check:"string_format",format:"regex",...X(t),pattern:e})}function Ic(e){return new zv({check:"string_format",format:"lowercase",...X(e)})}function Pc(e){return new kv({check:"string_format",format:"uppercase",...X(e)})}function Tc(e,t){return new Ev({check:"string_format",format:"includes",...X(t),includes:e})}function Cc(e,t){return new Rv({check:"string_format",format:"starts_with",...X(t),prefix:e})}function Ac(e,t){return new xv({check:"string_format",format:"ends_with",...X(t),suffix:e})}function Tb(e,t,r){return new Iv({check:"property",property:e,schema:t,...X(r)})}function Oc(e,t){return new Pv({check:"mime_type",mime:e,...X(t)})}function br(e){return new Tv({check:"overwrite",tx:e})}function Nc(e){return br(t=>t.normalize(e))}function jc(){return br(e=>e.trim())}function Uc(){return br(e=>e.toLowerCase())}function Mc(){return br(e=>e.toUpperCase())}function Dc(){return br(e=>mp(e))}function Cb(e,t,r){return new e({type:"array",element:t,...X(r)})}function Ab(e,t){return new e({type:"file",...X(t)})}function Ob(e,t,r){let n=X(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Nb(e,t,r){return new e({type:"custom",check:"custom",fn:t,...X(r)})}function jb(e){let t=vR(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(So(n,r.value,t._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(So(o))}},e(r.value,r)));return t}function vR(e,t){let r=new Je({check:"custom",...X(t)});return r._zod.check=e,r}function Ub(e){let t=new Je({check:"describe"});return t._zod.onattach=[r=>{let n=xt.get(r)??{};xt.add(r,{...n,description:e})}],t._zod.check=()=>{},t}function Mb(e){let t=new Je({check:"meta"});return t._zod.onattach=[r=>{let n=xt.get(r)??{};xt.add(r,{...n,...e})}],t._zod.check=()=>{},t}function Db(e,t){let r=X(t),n=r.truthy??["true","1","yes","on","y","enabled"],o=r.falsy??["false","0","no","off","n","disabled"];r.case!=="sensitive"&&(n=n.map(v=>typeof v=="string"?v.toLowerCase():v),o=o.map(v=>typeof v=="string"?v.toLowerCase():v));let i=new Set(n),a=new Set(o),s=e.Codec??kc,c=e.Boolean??wc,u=e.String??bo,l=new u({type:"string",error:r.error}),d=new c({type:"boolean",error:r.error}),m=new s({type:"pipe",in:l,out:d,transform:((v,g)=>{let h=v;return r.case!=="sensitive"&&(h=h.toLowerCase()),i.has(h)?!0:a.has(h)?!1:(g.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...a],input:g.value,inst:m,continue:!1}),{})}),reverseTransform:((v,g)=>v===!0?n[0]||"true":o[0]||"false"),error:r.error});return m}function da(e,t,r,n={}){let o=X(n),i={...X(n),check:"string_format",type:"string",format:t,fn:typeof r=="function"?r:s=>r.test(s),...o};return r instanceof RegExp&&(i.pattern=r),new e(i)}var qb=q(()=>{gc();sa();cm();de()});function zo(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??xt,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Le(e,t,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,i=t.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,a);let s=e._zod.toJSONSchema?.();if(s)a.schema=s;else{let l={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,a.schema,l);else{let m=a.schema,v=t.processors[o.type];if(!v)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);v(e,t,m,l)}let d=e._zod.parent;d&&(a.ref||(a.ref=d),Le(d,t,l),t.seen.get(d).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(a.schema,c),t.io==="input"&&$t(e)&&(delete a.schema.examples,delete a.schema.default),t.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,t.seen.get(e).schema}function ko(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let a of e.seen.entries()){let s=e.metadataRegistry.get(a[0])?.id;if(s){let c=n.get(s);if(c&&c!==a[0])throw new Error(`Duplicate schema id "${s}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(s,a[0])}}let o=a=>{let s=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let d=e.external.registry.get(a[0])?.id,m=e.external.uri??(g=>g);if(d)return{ref:m(d)};let v=a[1].defId??a[1].schema.id??`schema${e.counter++}`;return a[1].defId=v,{defId:v,ref:`${m("__shared")}#/${s}/${v}`}}if(a[1]===r)return{ref:"#"};let u=`#/${s}/`,l=a[1].schema.id??`__schema${e.counter++}`;return{defId:l,ref:u+l}},i=a=>{if(a[1].schema.$ref)return;let s=a[1],{ref:c,defId:u}=o(a);s.def={...s.schema},u&&(s.defId=u);let l=s.schema;for(let d in l)delete l[d];l.$ref=c};if(e.cycles==="throw")for(let a of e.seen.entries()){let s=a[1];if(s.cycle)throw new Error(`Cycle detected: #/${s.cycle?.join("/")}/ + +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of e.seen.entries()){let s=a[1];if(t===a[0]){i(a);continue}if(e.external){let u=e.external.registry.get(a[0])?.id;if(t!==a[0]&&u){i(a);continue}}if(e.metadataRegistry.get(a[0])?.id){i(a);continue}if(s.cycle){i(a);continue}if(s.count>1&&e.reused==="ref"){i(a);continue}}}function Eo(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=a=>{let s=e.seen.get(a);if(s.ref===null)return;let c=s.def??s.schema,u={...c},l=s.ref;if(s.ref=null,l){n(l);let m=e.seen.get(l),v=m.schema;if(v.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(v)):Object.assign(c,v),Object.assign(c,u),a._zod.parent===l)for(let h in c)h==="$ref"||h==="allOf"||h in u||delete c[h];if(v.$ref&&m.def)for(let h in c)h==="$ref"||h==="allOf"||h in m.def&&JSON.stringify(c[h])===JSON.stringify(m.def[h])&&delete c[h]}let d=a._zod.parent;if(d&&d!==l){n(d);let m=e.seen.get(d);if(m?.schema.$ref&&(c.$ref=m.schema.$ref,m.def))for(let v in c)v==="$ref"||v==="allOf"||v in m.def&&JSON.stringify(c[v])===JSON.stringify(m.def[v])&&delete c[v]}e.override({zodSchema:a,jsonSchema:c,path:s.path??[]})};for(let a of[...e.seen.entries()].reverse())n(a[0]);let o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(a)}Object.assign(o,r.def??r.schema);let i=e.external?.defs??{};for(let a of e.seen.entries()){let s=a[1];s.def&&s.defId&&(i[s.defId]=s.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:pa(t,"input",e.processors),output:pa(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function $t(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return $t(n.element,r);if(n.type==="set")return $t(n.valueType,r);if(n.type==="lazy")return $t(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return $t(n.innerType,r);if(n.type==="intersection")return $t(n.left,r)||$t(n.right,r);if(n.type==="record"||n.type==="map")return $t(n.keyType,r)||$t(n.valueType,r);if(n.type==="pipe")return $t(n.in,r)||$t(n.out,r);if(n.type==="object"){for(let o in n.shape)if($t(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if($t(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if($t(o,r))return!0;return!!(n.rest&&$t(n.rest,r))}return!1}var Lb,pa,ma=q(()=>{sa();Lb=(e,t={})=>r=>{let n=zo({...r,processors:t});return Le(e,n),ko(n,e),Eo(n,e)},pa=(e,t,r={})=>n=>{let{libraryOptions:o,target:i}=n??{},a=zo({...o??{},target:i,io:t,processors:r});return Le(e,a),ko(a,e),Eo(a,e)}});function fa(e,t){if("_idmap"in e){let n=e,o=zo({...t,processors:Nm}),i={};for(let c of n._idmap.entries()){let[u,l]=c;Le(l,o)}let a={},s={registry:n,uri:t?.uri,defs:i};o.external=s;for(let c of n._idmap.entries()){let[u,l]=c;ko(o,l),a[u]=Eo(o,l)}if(Object.keys(i).length>0){let c=o.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[c]:i}}return{schemas:a}}let r=zo({...t,processors:Nm});return Le(e,r),ko(r,e),Eo(r,e)}var _R,jm,Um,Mm,Dm,qm,Lm,Vm,Km,Jm,Fm,Hm,Zm,Wm,Bm,Gm,Xm,Ym,Qm,ef,tf,rf,nf,of,af,sf,qc,cf,uf,lf,df,pf,mf,ff,hf,gf,yf,vf,Lc,_f,Nm,ha=q(()=>{ma();de();_R={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},jm=(e,t,r,n)=>{let o=r;o.type="string";let{minimum:i,maximum:a,format:s,patterns:c,contentEncoding:u}=e._zod.bag;if(typeof i=="number"&&(o.minLength=i),typeof a=="number"&&(o.maxLength=a),s&&(o.format=_R[s]??s,o.format===""&&delete o.format,s==="time"&&delete o.format),u&&(o.contentEncoding=u),c&&c.size>0){let l=[...c];l.length===1?o.pattern=l[0].source:l.length>1&&(o.allOf=[...l.map(d=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},Um=(e,t,r,n)=>{let o=r,{minimum:i,maximum:a,format:s,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=e._zod.bag;typeof s=="string"&&s.includes("int")?o.type="integer":o.type="number",typeof l=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(o.minimum=l,o.exclusiveMinimum=!0):o.exclusiveMinimum=l),typeof i=="number"&&(o.minimum=i,typeof l=="number"&&t.target!=="draft-04"&&(l>=i?delete o.minimum:delete o.exclusiveMinimum)),typeof u=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u),typeof a=="number"&&(o.maximum=a,typeof u=="number"&&t.target!=="draft-04"&&(u<=a?delete o.maximum:delete o.exclusiveMaximum)),typeof c=="number"&&(o.multipleOf=c)},Mm=(e,t,r,n)=>{r.type="boolean"},Dm=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},qm=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},Lm=(e,t,r,n)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},Vm=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},Km=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},Jm=(e,t,r,n)=>{r.not={}},Fm=(e,t,r,n)=>{},Hm=(e,t,r,n)=>{},Zm=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},Wm=(e,t,r,n)=>{let o=e._zod.def,i=Wi(o.entries);i.every(a=>typeof a=="number")&&(r.type="number"),i.every(a=>typeof a=="string")&&(r.type="string"),r.enum=i},Bm=(e,t,r,n)=>{let o=e._zod.def,i=[];for(let a of o.values)if(a===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof a=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(a))}else i.push(a);if(i.length!==0)if(i.length===1){let a=i[0];r.type=a===null?"null":typeof a,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[a]:r.const=a}else i.every(a=>typeof a=="number")&&(r.type="number"),i.every(a=>typeof a=="string")&&(r.type="string"),i.every(a=>typeof a=="boolean")&&(r.type="boolean"),i.every(a=>a===null)&&(r.type="null"),r.enum=i},Gm=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},Xm=(e,t,r,n)=>{let o=r,i=e._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");o.type="string",o.pattern=i.source},Ym=(e,t,r,n)=>{let o=r,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:a,maximum:s,mime:c}=e._zod.bag;a!==void 0&&(i.minLength=a),s!==void 0&&(i.maxLength=s),c?c.length===1?(i.contentMediaType=c[0],Object.assign(o,i)):(Object.assign(o,i),o.anyOf=c.map(u=>({contentMediaType:u}))):Object.assign(o,i)},Qm=(e,t,r,n)=>{r.type="boolean"},ef=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},tf=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},rf=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},nf=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},of=(e,t,r,n)=>{if(t.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},af=(e,t,r,n)=>{let o=r,i=e._zod.def,{minimum:a,maximum:s}=e._zod.bag;typeof a=="number"&&(o.minItems=a),typeof s=="number"&&(o.maxItems=s),o.type="array",o.items=Le(i.element,t,{...n,path:[...n.path,"items"]})},sf=(e,t,r,n)=>{let o=r,i=e._zod.def;o.type="object",o.properties={};let a=i.shape;for(let u in a)o.properties[u]=Le(a[u],t,{...n,path:[...n.path,"properties",u]});let s=new Set(Object.keys(a)),c=new Set([...s].filter(u=>{let l=i.shape[u]._zod;return t.io==="input"?l.optin===void 0:l.optout===void 0}));c.size>0&&(o.required=Array.from(c)),i.catchall?._zod.def.type==="never"?o.additionalProperties=!1:i.catchall?i.catchall&&(o.additionalProperties=Le(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},qc=(e,t,r,n)=>{let o=e._zod.def,i=o.inclusive===!1,a=o.options.map((s,c)=>Le(s,t,{...n,path:[...n.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=a:r.anyOf=a},cf=(e,t,r,n)=>{let o=e._zod.def,i=Le(o.left,t,{...n,path:[...n.path,"allOf",0]}),a=Le(o.right,t,{...n,path:[...n.path,"allOf",1]}),s=u=>"allOf"in u&&Object.keys(u).length===1,c=[...s(i)?i.allOf:[i],...s(a)?a.allOf:[a]];r.allOf=c},uf=(e,t,r,n)=>{let o=r,i=e._zod.def;o.type="array";let a=t.target==="draft-2020-12"?"prefixItems":"items",s=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((m,v)=>Le(m,t,{...n,path:[...n.path,a,v]})),u=i.rest?Le(i.rest,t,{...n,path:[...n.path,s,...t.target==="openapi-3.0"?[i.items.length]:[]]}):null;t.target==="draft-2020-12"?(o.prefixItems=c,u&&(o.items=u)):t.target==="openapi-3.0"?(o.items={anyOf:c},u&&o.items.anyOf.push(u),o.minItems=c.length,u||(o.maxItems=c.length)):(o.items=c,u&&(o.additionalItems=u));let{minimum:l,maximum:d}=e._zod.bag;typeof l=="number"&&(o.minItems=l),typeof d=="number"&&(o.maxItems=d)},lf=(e,t,r,n)=>{let o=r,i=e._zod.def;o.type="object";let a=i.keyType,c=a._zod.bag?.patterns;if(i.mode==="loose"&&c&&c.size>0){let l=Le(i.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(let d of c)o.patternProperties[d.source]=l}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(o.propertyNames=Le(i.keyType,t,{...n,path:[...n.path,"propertyNames"]})),o.additionalProperties=Le(i.valueType,t,{...n,path:[...n.path,"additionalProperties"]});let u=a._zod.values;if(u){let l=[...u].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(o.required=l)}},df=(e,t,r,n)=>{let o=e._zod.def,i=Le(o.innerType,t,n),a=t.seen.get(e);t.target==="openapi-3.0"?(a.ref=o.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},pf=(e,t,r,n)=>{let o=e._zod.def;Le(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType},mf=(e,t,r,n)=>{let o=e._zod.def;Le(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},ff=(e,t,r,n)=>{let o=e._zod.def;Le(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType,t.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},hf=(e,t,r,n)=>{let o=e._zod.def;Le(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType;let a;try{a=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=a},gf=(e,t,r,n)=>{let o=e._zod.def,i=t.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;Le(i,t,n);let a=t.seen.get(e);a.ref=i},yf=(e,t,r,n)=>{let o=e._zod.def;Le(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType,r.readOnly=!0},vf=(e,t,r,n)=>{let o=e._zod.def;Le(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType},Lc=(e,t,r,n)=>{let o=e._zod.def;Le(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType},_f=(e,t,r,n)=>{let o=e._zod.innerType;Le(o,t,n);let i=t.seen.get(e);i.ref=o},Nm={string:jm,number:Um,boolean:Mm,bigint:Dm,symbol:qm,null:Lm,undefined:Vm,void:Km,never:Jm,any:Fm,unknown:Hm,date:Zm,enum:Wm,literal:Bm,nan:Gm,template_literal:Xm,file:Ym,success:Qm,custom:ef,function:tf,transform:rf,map:nf,set:of,array:af,object:sf,union:qc,intersection:cf,tuple:uf,record:lf,nullable:df,nonoptional:pf,default:mf,prefault:ff,catch:hf,pipe:gf,readonly:yf,promise:vf,optional:Lc,lazy:_f}});var Vb=q(()=>{ha();ma()});var Kb=q(()=>{});var It=q(()=>{yo();zp();bp();cm();gc();rm();de();hc();mm();sa();tm();qb();ma();ha();Vb();Kb()});var Vc={};nr(Vc,{endsWith:()=>Ac,gt:()=>Fr,gte:()=>Nt,includes:()=>Tc,length:()=>la,lowercase:()=>Ic,lt:()=>Jr,lte:()=>Wt,maxLength:()=>ua,maxSize:()=>wo,mime:()=>Oc,minLength:()=>In,minSize:()=>Hr,multipleOf:()=>$o,negative:()=>xb,nonnegative:()=>Pb,nonpositive:()=>Ib,normalize:()=>Nc,overwrite:()=>br,positive:()=>Rb,property:()=>Tb,regex:()=>xc,size:()=>ca,slugify:()=>Dc,startsWith:()=>Cc,toLowerCase:()=>Uc,toUpperCase:()=>Mc,trim:()=>jc,uppercase:()=>Pc});var Kc=q(()=>{It()});var Lt={};nr(Lt,{ZodISODate:()=>$f,ZodISODateTime:()=>Sf,ZodISODuration:()=>Ef,ZodISOTime:()=>zf,date:()=>wf,datetime:()=>bf,duration:()=>Rf,time:()=>kf});function bf(e){return eb(Sf,e)}function wf(e){return tb($f,e)}function kf(e){return rb(zf,e)}function Rf(e){return nb(Ef,e)}var Sf,$f,zf,Ef,ga=q(()=>{It();va();Sf=C("ZodISODateTime",(e,t)=>{r_.init(e,t),Ke.init(e,t)});$f=C("ZodISODate",(e,t)=>{n_.init(e,t),Ke.init(e,t)});zf=C("ZodISOTime",(e,t)=>{o_.init(e,t),Ke.init(e,t)});Ef=C("ZodISODuration",(e,t)=>{i_.init(e,t),Ke.init(e,t)})});var Jb,SM,jt,xf=q(()=>{It();It();de();Jb=(e,t)=>{pc.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>Sp(e,r)},flatten:{value:r=>_p(e,r)},addIssue:{value:r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,vo,2)}},addIssues:{value:r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,vo,2)}},isEmpty:{get(){return e.issues.length===0}}})},SM=C("ZodError",Jb),jt=C("ZodError",Jb,{Parent:Error})});var Fb,Hb,Jc,Zb,Wb,Bb,Gb,Xb,Yb,Qb,e$,t$,If=q(()=>{It();xf();Fb=ea(jt),Hb=ta(jt),Jc=ra(jt),Zb=na(jt),Wb=tv(jt),Bb=rv(jt),Gb=nv(jt),Xb=ov(jt),Yb=iv(jt),Qb=av(jt),e$=sv(jt),t$=cv(jt)});var ya={};nr(ya,{ZodAny:()=>a$,ZodArray:()=>l$,ZodBase64:()=>Ff,ZodBase64URL:()=>Hf,ZodBigInt:()=>ka,ZodBigIntFormat:()=>Bf,ZodBoolean:()=>za,ZodCIDRv4:()=>Kf,ZodCIDRv6:()=>Jf,ZodCUID:()=>jf,ZodCUID2:()=>Uf,ZodCatch:()=>P$,ZodCodec:()=>rh,ZodCustom:()=>Qc,ZodCustomStringFormat:()=>$a,ZodDate:()=>Bc,ZodDefault:()=>z$,ZodDiscriminatedUnion:()=>p$,ZodE164:()=>Zf,ZodEmail:()=>Cf,ZodEmoji:()=>Of,ZodEnum:()=>_a,ZodExactOptional:()=>b$,ZodFile:()=>_$,ZodFunction:()=>M$,ZodGUID:()=>Fc,ZodIPv4:()=>Lf,ZodIPv6:()=>Vf,ZodIntersection:()=>m$,ZodJWT:()=>Wf,ZodKSUID:()=>qf,ZodLazy:()=>j$,ZodLiteral:()=>v$,ZodMAC:()=>r$,ZodMap:()=>g$,ZodNaN:()=>C$,ZodNanoID:()=>Nf,ZodNever:()=>c$,ZodNonOptional:()=>eh,ZodNull:()=>i$,ZodNullable:()=>w$,ZodNumber:()=>wa,ZodNumberFormat:()=>Ro,ZodObject:()=>Gc,ZodOptional:()=>Qf,ZodPipe:()=>th,ZodPrefault:()=>E$,ZodPromise:()=>U$,ZodReadonly:()=>A$,ZodRecord:()=>Yc,ZodSet:()=>y$,ZodString:()=>Sa,ZodStringFormat:()=>Ke,ZodSuccess:()=>I$,ZodSymbol:()=>n$,ZodTemplateLiteral:()=>N$,ZodTransform:()=>S$,ZodTuple:()=>f$,ZodType:()=>xe,ZodULID:()=>Mf,ZodURL:()=>Wc,ZodUUID:()=>$r,ZodUndefined:()=>o$,ZodUnion:()=>Xc,ZodUnknown:()=>s$,ZodVoid:()=>u$,ZodXID:()=>Df,ZodXor:()=>d$,_ZodString:()=>Tf,_default:()=>k$,_function:()=>Sx,any:()=>Gf,array:()=>N,base64:()=>qR,base64url:()=>LR,bigint:()=>YR,boolean:()=>ee,catch:()=>T$,check:()=>bx,cidrv4:()=>MR,cidrv6:()=>DR,codec:()=>yx,cuid:()=>PR,cuid2:()=>TR,custom:()=>$x,date:()=>ox,describe:()=>wx,discriminatedUnion:()=>Tn,e164:()=>VR,email:()=>Af,emoji:()=>xR,enum:()=>ve,exactOptional:()=>$$,file:()=>mx,float32:()=>WR,float64:()=>BR,function:()=>Sx,guid:()=>$R,hash:()=>ZR,hex:()=>HR,hostname:()=>FR,httpUrl:()=>RR,instanceof:()=>kx,int:()=>Pf,int32:()=>GR,int64:()=>QR,intersection:()=>sr,ipv4:()=>NR,ipv6:()=>UR,json:()=>Rx,jwt:()=>KR,keyof:()=>ix,ksuid:()=>OR,lazy:()=>Cn,literal:()=>U,looseObject:()=>pe,looseRecord:()=>ux,mac:()=>jR,map:()=>lx,meta:()=>zx,nan:()=>gx,nanoid:()=>IR,nativeEnum:()=>px,never:()=>Xf,nonoptional:()=>x$,null:()=>wr,nullable:()=>Hc,nullish:()=>fx,number:()=>F,object:()=>x,optional:()=>le,partialRecord:()=>cx,pipe:()=>Zc,prefault:()=>R$,preprocess:()=>Zr,promise:()=>_x,readonly:()=>O$,record:()=>Y,refine:()=>D$,set:()=>dx,strictObject:()=>ax,string:()=>p,stringFormat:()=>JR,stringbool:()=>Ex,success:()=>hx,superRefine:()=>q$,symbol:()=>tx,templateLiteral:()=>vx,transform:()=>Yf,tuple:()=>h$,uint32:()=>XR,uint64:()=>ex,ulid:()=>CR,undefined:()=>rx,union:()=>re,unknown:()=>ue,url:()=>ba,uuid:()=>wR,uuidv4:()=>zR,uuidv6:()=>kR,uuidv7:()=>ER,void:()=>nx,xid:()=>AR,xor:()=>sx});function p(e){return XS(Sa,e)}function Af(e){return hm(Cf,e)}function $R(e){return Ec(Fc,e)}function wR(e){return gm($r,e)}function zR(e){return ym($r,e)}function kR(e){return vm($r,e)}function ER(e){return _m($r,e)}function ba(e){return Rc(Wc,e)}function RR(e){return Rc(Wc,{protocol:/^https?$/,hostname:ar.domain,...G.normalizeParams(e)})}function xR(e){return Sm(Of,e)}function IR(e){return bm(Nf,e)}function PR(e){return $m(jf,e)}function TR(e){return wm(Uf,e)}function CR(e){return zm(Mf,e)}function AR(e){return km(Df,e)}function OR(e){return Em(qf,e)}function NR(e){return Rm(Lf,e)}function jR(e){return QS(r$,e)}function UR(e){return xm(Vf,e)}function MR(e){return Im(Kf,e)}function DR(e){return Pm(Jf,e)}function qR(e){return Tm(Ff,e)}function LR(e){return Cm(Hf,e)}function VR(e){return Am(Zf,e)}function KR(e){return Om(Wf,e)}function JR(e,t,r={}){return da($a,e,t,r)}function FR(e){return da($a,"hostname",ar.hostname,e)}function HR(e){return da($a,"hex",ar.hex,e)}function ZR(e,t){let r=t?.enc??"hex",n=`${e}_${r}`,o=ar[n];if(!o)throw new Error(`Unrecognized hash format: ${n}`);return da($a,n,o,t)}function F(e){return ob(wa,e)}function Pf(e){return ab(Ro,e)}function WR(e){return sb(Ro,e)}function BR(e){return cb(Ro,e)}function GR(e){return ub(Ro,e)}function XR(e){return lb(Ro,e)}function ee(e){return db(za,e)}function YR(e){return mb(ka,e)}function QR(e){return hb(Bf,e)}function ex(e){return gb(Bf,e)}function tx(e){return yb(n$,e)}function rx(e){return vb(o$,e)}function wr(e){return _b(i$,e)}function Gf(){return Sb(a$)}function ue(){return bb(s$)}function Xf(e){return $b(c$,e)}function nx(e){return wb(u$,e)}function ox(e){return zb(Bc,e)}function N(e,t){return Cb(l$,e,t)}function ix(e){let t=e._zod.def.shape;return ve(Object.keys(t))}function x(e,t){let r={type:"object",shape:e??{},...G.normalizeParams(t)};return new Gc(r)}function ax(e,t){return new Gc({type:"object",shape:e,catchall:Xf(),...G.normalizeParams(t)})}function pe(e,t){return new Gc({type:"object",shape:e,catchall:ue(),...G.normalizeParams(t)})}function re(e,t){return new Xc({type:"union",options:e,...G.normalizeParams(t)})}function sx(e,t){return new d$({type:"union",options:e,inclusive:!1,...G.normalizeParams(t)})}function Tn(e,t,r){return new p$({type:"union",options:t,discriminator:e,...G.normalizeParams(r)})}function sr(e,t){return new m$({type:"intersection",left:e,right:t})}function h$(e,t,r){let n=t instanceof we,o=n?r:t,i=n?t:null;return new f$({type:"tuple",items:e,rest:i,...G.normalizeParams(o)})}function Y(e,t,r){return new Yc({type:"record",keyType:e,valueType:t,...G.normalizeParams(r)})}function cx(e,t,r){let n=At(e);return n._zod.values=void 0,new Yc({type:"record",keyType:n,valueType:t,...G.normalizeParams(r)})}function ux(e,t,r){return new Yc({type:"record",keyType:e,valueType:t,mode:"loose",...G.normalizeParams(r)})}function lx(e,t,r){return new g$({type:"map",keyType:e,valueType:t,...G.normalizeParams(r)})}function dx(e,t){return new y$({type:"set",valueType:e,...G.normalizeParams(t)})}function ve(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new _a({type:"enum",entries:r,...G.normalizeParams(t)})}function px(e,t){return new _a({type:"enum",entries:e,...G.normalizeParams(t)})}function U(e,t){return new v$({type:"literal",values:Array.isArray(e)?e:[e],...G.normalizeParams(t)})}function mx(e){return Ab(_$,e)}function Yf(e){return new S$({type:"transform",transform:e})}function le(e){return new Qf({type:"optional",innerType:e})}function $$(e){return new b$({type:"optional",innerType:e})}function Hc(e){return new w$({type:"nullable",innerType:e})}function fx(e){return le(Hc(e))}function k$(e,t){return new z$({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():G.shallowClone(t)}})}function R$(e,t){return new E$({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():G.shallowClone(t)}})}function x$(e,t){return new eh({type:"nonoptional",innerType:e,...G.normalizeParams(t)})}function hx(e){return new I$({type:"success",innerType:e})}function T$(e,t){return new P$({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}function gx(e){return Eb(C$,e)}function Zc(e,t){return new th({type:"pipe",in:e,out:t})}function yx(e,t,r){return new rh({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}function O$(e){return new A$({type:"readonly",innerType:e})}function vx(e,t){return new N$({type:"template_literal",parts:e,...G.normalizeParams(t)})}function Cn(e){return new j$({type:"lazy",getter:e})}function _x(e){return new U$({type:"promise",innerType:e})}function Sx(e){return new M$({type:"function",input:Array.isArray(e?.input)?h$(e?.input):e?.input??N(ue()),output:e?.output??ue()})}function bx(e){let t=new Je({check:"custom"});return t._zod.check=e,t}function $x(e,t){return Ob(Qc,e??(()=>!0),t)}function D$(e,t={}){return Nb(Qc,e,t)}function q$(e){return jb(e)}function kx(e,t={}){let r=new Qc({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...G.normalizeParams(t)});return r._zod.bag.Class=e,r._zod.check=n=>{n.value instanceof e||n.issues.push({code:"invalid_type",expected:e.name,input:n.value,inst:r,path:[...r._zod.def.path??[]]})},r}function Rx(e){let t=Cn(()=>re([p(e),F(),ee(),wr(),N(t),Y(p(),t)]));return t}function Zr(e,t){return Zc(Yf(e),t)}var xe,Tf,Sa,Ke,Cf,Fc,$r,Wc,Of,Nf,jf,Uf,Mf,Df,qf,Lf,r$,Vf,Kf,Jf,Ff,Hf,Zf,Wf,$a,wa,Ro,za,ka,Bf,n$,o$,i$,a$,s$,c$,u$,Bc,l$,Gc,Xc,d$,p$,m$,f$,Yc,g$,y$,_a,v$,_$,S$,Qf,b$,w$,z$,E$,eh,I$,P$,C$,th,rh,A$,N$,j$,U$,M$,Qc,wx,zx,Ex,va=q(()=>{It();It();ha();ma();Kc();ga();If();xe=C("ZodType",(e,t)=>(we.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:pa(e,"input"),output:pa(e,"output")}}),e.toJSONSchema=Lb(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone(G.mergeDefs(t,{checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0}),e.with=e.check,e.clone=(r,n)=>At(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>Fb(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Jc(e,r,n),e.parseAsync=async(r,n)=>Hb(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Zb(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>Wb(e,r,n),e.decode=(r,n)=>Bb(e,r,n),e.encodeAsync=async(r,n)=>Gb(e,r,n),e.decodeAsync=async(r,n)=>Xb(e,r,n),e.safeEncode=(r,n)=>Yb(e,r,n),e.safeDecode=(r,n)=>Qb(e,r,n),e.safeEncodeAsync=async(r,n)=>e$(e,r,n),e.safeDecodeAsync=async(r,n)=>t$(e,r,n),e.refine=(r,n)=>e.check(D$(r,n)),e.superRefine=r=>e.check(q$(r)),e.overwrite=r=>e.check(br(r)),e.optional=()=>le(e),e.exactOptional=()=>$$(e),e.nullable=()=>Hc(e),e.nullish=()=>le(Hc(e)),e.nonoptional=r=>x$(e,r),e.array=()=>N(e),e.or=r=>re([e,r]),e.and=r=>sr(e,r),e.transform=r=>Zc(e,Yf(r)),e.default=r=>k$(e,r),e.prefault=r=>R$(e,r),e.catch=r=>T$(e,r),e.pipe=r=>Zc(e,r),e.readonly=()=>O$(e),e.describe=r=>{let n=e.clone();return xt.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return xt.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return xt.get(e);let n=e.clone();return xt.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=r=>r(e),e)),Tf=C("_ZodString",(e,t)=>{bo.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(n,o,i)=>jm(e,n,o,i);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(xc(...n)),e.includes=(...n)=>e.check(Tc(...n)),e.startsWith=(...n)=>e.check(Cc(...n)),e.endsWith=(...n)=>e.check(Ac(...n)),e.min=(...n)=>e.check(In(...n)),e.max=(...n)=>e.check(ua(...n)),e.length=(...n)=>e.check(la(...n)),e.nonempty=(...n)=>e.check(In(1,...n)),e.lowercase=n=>e.check(Ic(n)),e.uppercase=n=>e.check(Pc(n)),e.trim=()=>e.check(jc()),e.normalize=(...n)=>e.check(Nc(...n)),e.toLowerCase=()=>e.check(Uc()),e.toUpperCase=()=>e.check(Mc()),e.slugify=()=>e.check(Dc())}),Sa=C("ZodString",(e,t)=>{bo.init(e,t),Tf.init(e,t),e.email=r=>e.check(hm(Cf,r)),e.url=r=>e.check(Rc(Wc,r)),e.jwt=r=>e.check(Om(Wf,r)),e.emoji=r=>e.check(Sm(Of,r)),e.guid=r=>e.check(Ec(Fc,r)),e.uuid=r=>e.check(gm($r,r)),e.uuidv4=r=>e.check(ym($r,r)),e.uuidv6=r=>e.check(vm($r,r)),e.uuidv7=r=>e.check(_m($r,r)),e.nanoid=r=>e.check(bm(Nf,r)),e.guid=r=>e.check(Ec(Fc,r)),e.cuid=r=>e.check($m(jf,r)),e.cuid2=r=>e.check(wm(Uf,r)),e.ulid=r=>e.check(zm(Mf,r)),e.base64=r=>e.check(Tm(Ff,r)),e.base64url=r=>e.check(Cm(Hf,r)),e.xid=r=>e.check(km(Df,r)),e.ksuid=r=>e.check(Em(qf,r)),e.ipv4=r=>e.check(Rm(Lf,r)),e.ipv6=r=>e.check(xm(Vf,r)),e.cidrv4=r=>e.check(Im(Kf,r)),e.cidrv6=r=>e.check(Pm(Jf,r)),e.e164=r=>e.check(Am(Zf,r)),e.datetime=r=>e.check(bf(r)),e.date=r=>e.check(wf(r)),e.time=r=>e.check(kf(r)),e.duration=r=>e.check(Rf(r))});Ke=C("ZodStringFormat",(e,t)=>{Ve.init(e,t),Tf.init(e,t)}),Cf=C("ZodEmail",(e,t)=>{Zv.init(e,t),Ke.init(e,t)});Fc=C("ZodGUID",(e,t)=>{Fv.init(e,t),Ke.init(e,t)});$r=C("ZodUUID",(e,t)=>{Hv.init(e,t),Ke.init(e,t)});Wc=C("ZodURL",(e,t)=>{Wv.init(e,t),Ke.init(e,t)});Of=C("ZodEmoji",(e,t)=>{Bv.init(e,t),Ke.init(e,t)});Nf=C("ZodNanoID",(e,t)=>{Gv.init(e,t),Ke.init(e,t)});jf=C("ZodCUID",(e,t)=>{Xv.init(e,t),Ke.init(e,t)});Uf=C("ZodCUID2",(e,t)=>{Yv.init(e,t),Ke.init(e,t)});Mf=C("ZodULID",(e,t)=>{Qv.init(e,t),Ke.init(e,t)});Df=C("ZodXID",(e,t)=>{e_.init(e,t),Ke.init(e,t)});qf=C("ZodKSUID",(e,t)=>{t_.init(e,t),Ke.init(e,t)});Lf=C("ZodIPv4",(e,t)=>{a_.init(e,t),Ke.init(e,t)});r$=C("ZodMAC",(e,t)=>{c_.init(e,t),Ke.init(e,t)});Vf=C("ZodIPv6",(e,t)=>{s_.init(e,t),Ke.init(e,t)});Kf=C("ZodCIDRv4",(e,t)=>{u_.init(e,t),Ke.init(e,t)});Jf=C("ZodCIDRv6",(e,t)=>{l_.init(e,t),Ke.init(e,t)});Ff=C("ZodBase64",(e,t)=>{p_.init(e,t),Ke.init(e,t)});Hf=C("ZodBase64URL",(e,t)=>{m_.init(e,t),Ke.init(e,t)});Zf=C("ZodE164",(e,t)=>{f_.init(e,t),Ke.init(e,t)});Wf=C("ZodJWT",(e,t)=>{h_.init(e,t),Ke.init(e,t)});$a=C("ZodCustomStringFormat",(e,t)=>{g_.init(e,t),Ke.init(e,t)});wa=C("ZodNumber",(e,t)=>{om.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Um(e,n,o,i),e.gt=(n,o)=>e.check(Fr(n,o)),e.gte=(n,o)=>e.check(Nt(n,o)),e.min=(n,o)=>e.check(Nt(n,o)),e.lt=(n,o)=>e.check(Jr(n,o)),e.lte=(n,o)=>e.check(Wt(n,o)),e.max=(n,o)=>e.check(Wt(n,o)),e.int=n=>e.check(Pf(n)),e.safe=n=>e.check(Pf(n)),e.positive=n=>e.check(Fr(0,n)),e.nonnegative=n=>e.check(Nt(0,n)),e.negative=n=>e.check(Jr(0,n)),e.nonpositive=n=>e.check(Wt(0,n)),e.multipleOf=(n,o)=>e.check($o(n,o)),e.step=(n,o)=>e.check($o(n,o)),e.finite=()=>e;let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});Ro=C("ZodNumberFormat",(e,t)=>{y_.init(e,t),wa.init(e,t)});za=C("ZodBoolean",(e,t)=>{wc.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Mm(e,r,n,o)});ka=C("ZodBigInt",(e,t)=>{im.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Dm(e,n,o,i),e.gte=(n,o)=>e.check(Nt(n,o)),e.min=(n,o)=>e.check(Nt(n,o)),e.gt=(n,o)=>e.check(Fr(n,o)),e.gte=(n,o)=>e.check(Nt(n,o)),e.min=(n,o)=>e.check(Nt(n,o)),e.lt=(n,o)=>e.check(Jr(n,o)),e.lte=(n,o)=>e.check(Wt(n,o)),e.max=(n,o)=>e.check(Wt(n,o)),e.positive=n=>e.check(Fr(BigInt(0),n)),e.negative=n=>e.check(Jr(BigInt(0),n)),e.nonpositive=n=>e.check(Wt(BigInt(0),n)),e.nonnegative=n=>e.check(Nt(BigInt(0),n)),e.multipleOf=(n,o)=>e.check($o(n,o));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});Bf=C("ZodBigIntFormat",(e,t)=>{v_.init(e,t),ka.init(e,t)});n$=C("ZodSymbol",(e,t)=>{__.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>qm(e,r,n,o)});o$=C("ZodUndefined",(e,t)=>{S_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Vm(e,r,n,o)});i$=C("ZodNull",(e,t)=>{b_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Lm(e,r,n,o)});a$=C("ZodAny",(e,t)=>{$_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Fm(e,r,n,o)});s$=C("ZodUnknown",(e,t)=>{w_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Hm(e,r,n,o)});c$=C("ZodNever",(e,t)=>{z_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Jm(e,r,n,o)});u$=C("ZodVoid",(e,t)=>{k_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Km(e,r,n,o)});Bc=C("ZodDate",(e,t)=>{E_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Zm(e,n,o,i),e.min=(n,o)=>e.check(Nt(n,o)),e.max=(n,o)=>e.check(Wt(n,o));let r=e._zod.bag;e.minDate=r.minimum?new Date(r.minimum):null,e.maxDate=r.maximum?new Date(r.maximum):null});l$=C("ZodArray",(e,t)=>{R_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>af(e,r,n,o),e.element=t.element,e.min=(r,n)=>e.check(In(r,n)),e.nonempty=r=>e.check(In(1,r)),e.max=(r,n)=>e.check(ua(r,n)),e.length=(r,n)=>e.check(la(r,n)),e.unwrap=()=>e.element});Gc=C("ZodObject",(e,t)=>{P_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>sf(e,r,n,o),G.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>ve(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:ue()}),e.loose=()=>e.clone({...e._zod.def,catchall:ue()}),e.strict=()=>e.clone({...e._zod.def,catchall:Xf()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>G.extend(e,r),e.safeExtend=r=>G.safeExtend(e,r),e.merge=r=>G.merge(e,r),e.pick=r=>G.pick(e,r),e.omit=r=>G.omit(e,r),e.partial=(...r)=>G.partial(Qf,e,r[0]),e.required=(...r)=>G.required(eh,e,r[0])});Xc=C("ZodUnion",(e,t)=>{zc.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>qc(e,r,n,o),e.options=t.options});d$=C("ZodXor",(e,t)=>{Xc.init(e,t),T_.init(e,t),e._zod.processJSONSchema=(r,n,o)=>qc(e,r,n,o),e.options=t.options});p$=C("ZodDiscriminatedUnion",(e,t)=>{Xc.init(e,t),C_.init(e,t)});m$=C("ZodIntersection",(e,t)=>{A_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>cf(e,r,n,o)});f$=C("ZodTuple",(e,t)=>{am.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>uf(e,r,n,o),e.rest=r=>e.clone({...e._zod.def,rest:r})});Yc=C("ZodRecord",(e,t)=>{O_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>lf(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType});g$=C("ZodMap",(e,t)=>{N_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>nf(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType,e.min=(...r)=>e.check(Hr(...r)),e.nonempty=r=>e.check(Hr(1,r)),e.max=(...r)=>e.check(wo(...r)),e.size=(...r)=>e.check(ca(...r))});y$=C("ZodSet",(e,t)=>{j_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>of(e,r,n,o),e.min=(...r)=>e.check(Hr(...r)),e.nonempty=r=>e.check(Hr(1,r)),e.max=(...r)=>e.check(wo(...r)),e.size=(...r)=>e.check(ca(...r))});_a=C("ZodEnum",(e,t)=>{U_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(n,o,i)=>Wm(e,n,o,i),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let i={};for(let a of n)if(r.has(a))i[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new _a({...t,checks:[],...G.normalizeParams(o),entries:i})},e.exclude=(n,o)=>{let i={...t.entries};for(let a of n)if(r.has(a))delete i[a];else throw new Error(`Key ${a} not found in enum`);return new _a({...t,checks:[],...G.normalizeParams(o),entries:i})}});v$=C("ZodLiteral",(e,t)=>{M_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Bm(e,r,n,o),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});_$=C("ZodFile",(e,t)=>{D_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Ym(e,r,n,o),e.min=(r,n)=>e.check(Hr(r,n)),e.max=(r,n)=>e.check(wo(r,n)),e.mime=(r,n)=>e.check(Oc(Array.isArray(r)?r:[r],n))});S$=C("ZodTransform",(e,t)=>{q_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>rf(e,r,n,o),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new En(e.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(G.issue(i,r.value,t));else{let a=i;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=e),r.issues.push(G.issue(a))}};let o=t.transform(r.value,r);return o instanceof Promise?o.then(i=>(r.value=i,r)):(r.value=o,r)}});Qf=C("ZodOptional",(e,t)=>{sm.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Lc(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});b$=C("ZodExactOptional",(e,t)=>{L_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Lc(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});w$=C("ZodNullable",(e,t)=>{V_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>df(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});z$=C("ZodDefault",(e,t)=>{K_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>mf(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});E$=C("ZodPrefault",(e,t)=>{J_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ff(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});eh=C("ZodNonOptional",(e,t)=>{F_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>pf(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});I$=C("ZodSuccess",(e,t)=>{H_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Qm(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});P$=C("ZodCatch",(e,t)=>{Z_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>hf(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});C$=C("ZodNaN",(e,t)=>{W_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Gm(e,r,n,o)});th=C("ZodPipe",(e,t)=>{B_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>gf(e,r,n,o),e.in=t.in,e.out=t.out});rh=C("ZodCodec",(e,t)=>{th.init(e,t),kc.init(e,t)});A$=C("ZodReadonly",(e,t)=>{G_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>yf(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});N$=C("ZodTemplateLiteral",(e,t)=>{X_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Xm(e,r,n,o)});j$=C("ZodLazy",(e,t)=>{eS.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>_f(e,r,n,o),e.unwrap=()=>e._zod.def.getter()});U$=C("ZodPromise",(e,t)=>{Q_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>vf(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});M$=C("ZodFunction",(e,t)=>{Y_.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>tf(e,r,n,o)});Qc=C("ZodCustom",(e,t)=>{tS.init(e,t),xe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ef(e,r,n,o)});wx=Ub,zx=Mb;Ex=(...e)=>Db({Codec:rh,Boolean:za,String:Sa},...e)});var V$,L$,K$=q(()=>{It();It();V$={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};L$||(L$={})});var xM,J$=q(()=>{sa();Kc();ga();va();xM={...ya,...Vc,iso:Lt}});var eu={};nr(eu,{bigint:()=>Cx,boolean:()=>Tx,date:()=>Ax,number:()=>Px,string:()=>Ix});function Ix(e){return YS(Sa,e)}function Px(e){return ib(wa,e)}function Tx(e){return pb(za,e)}function Cx(e){return fb(ka,e)}function Ax(e){return kb(Bc,e)}var F$=q(()=>{It();va()});var nh=q(()=>{It();va();Kc();xf();If();K$();It();lm();It();ha();J$();mm();ga();ga();F$();lt(um())});var oh=q(()=>{nh();nh()});var ih=q(()=>{oh();oh()});var Br,tu,Ea,Ra,cr,On,ur,Gr,xo,Nn,ru,nu,ou,Xr,iu,au,su,cu,uu,Wr,Ge,sh,xa,Ia,lu,du,Pa,pt,Yr,Xe,St,bt,Ta,Ye,Qr,Ca,Aa,Io,Po,Bt,pu,Oa,mu,Na,fu,en,zr,To,Nx,jx,hu,gu,yu,vu,ja,Ua,_u,Ma,Su,jn,Da,bu,$u,qa,wu,tn,rn,La,Va,ch,Ka,nn,kr,Ja,zu,ku,Eu,Ru,xu,Co,Iu,Pu,Tu,Cu,Au,Ou,Nu,ju,Fa,Uu,Mu,Du,qu,Lu,Vu,Ku,Ju,Fu,Hu,Zu,Wu,Bu,Gu,Ao,Oo,No,Xu,Yu,Qu,jo,el,tl,rl,nl,ol,Ha,il,al,Uo,uh,sl,cl,ul,Za,Wa,ll,dl,pl,ml,fl,hl,gl,yl,vl,An,_l,Sl,bl,$l,wl,Ba,Mo,Do,Ga,Xa,Ya,zl,Qa,es,kl,El,ts,qo,Rl,xl,Il,Pl,Tl,Cl,Al,Ol,Nl,jl,Ul,Ml,Dl,ql,Ll,lh,Vl,on,dh,Kl,ph,mh,fh,hh,gh,yh,vh,_h,Sh,bh,$h,wh,zh,kh,Eh,dt,rs,Un,Jl,ns,Lo,os,Mn,ah,Fl,Hl,is,Rh,xh,Z$=q(()=>{ih();Br="2025-11-25",tu="2025-03-26",Ea=[Br,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Ra="io.modelcontextprotocol/related-task",cr="io.modelcontextprotocol/protocolVersion",On="io.modelcontextprotocol/clientInfo",ur="io.modelcontextprotocol/serverInfo",Gr="io.modelcontextprotocol/clientCapabilities",xo="io.modelcontextprotocol/subscriptionId",Nn="io.modelcontextprotocol/logLevel",ru="traceparent",nu="tracestate",ou="baggage",Xr="2.0",iu=-32700,au=-32600,su=-32601,cu=-32602,uu=-32603,Wr=Cn(()=>re([p(),F(),ee(),wr(),Y(p(),Wr),N(Wr)])),Ge=Y(p(),Wr),sh=N(Wr),xa=re([p(),F().int()]),Ia=p(),lu=x({ttl:F().optional()}),du=x({taskId:p()}),Pa=pe({progressToken:xa.optional(),[Ra]:du.optional()}),pt=x({_meta:Pa.optional()}),Yr=pt.extend({task:lu.optional()}),Xe=x({method:p(),params:pt.loose().optional()}),St=x({_meta:Pa.optional()}),bt=x({method:p(),params:St.loose().optional()}),Ta=pe({get[ur](){return To.optional().catch(void 0)}}),Ye=pe({_meta:Ta.optional()}),Qr=re([p(),F().int()]),Ca=x({jsonrpc:U(Xr),id:Qr,...Xe.shape}).strict(),Aa=x({jsonrpc:U(Xr),...bt.shape}).strict(),Io=x({jsonrpc:U(Xr),id:Qr,result:Ye}).strict(),Po=x({jsonrpc:U(Xr),id:Qr.optional(),error:x({code:F().int(),message:p(),data:ue().optional()})}).strict(),Bt=re([Ca,Aa,Io,Po]),pu=re([Io,Po]),Oa=Ye.strict(),mu=St.extend({requestId:Qr.optional(),reason:p().optional()}),Na=bt.extend({method:U("notifications/cancelled"),params:mu}),fu=x({src:p(),mimeType:p().optional(),sizes:N(p()).optional(),theme:ve(["light","dark"]).optional()}),en=x({icons:N(fu).optional()}),zr=x({name:p(),title:p().optional()}),To=zr.extend({...zr.shape,...en.shape,version:p(),websiteUrl:p().optional(),description:p().optional()}),Nx=sr(x({applyDefaults:ee().optional()}),Ge),jx=Zr(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,sr(x({form:Nx.optional(),url:Ge.optional()}),Ge.optional())),hu=pe({list:Ge.optional(),cancel:Ge.optional(),requests:pe({sampling:pe({createMessage:Ge.optional()}).optional(),elicitation:pe({create:Ge.optional()}).optional()}).optional()}),gu=pe({list:Ge.optional(),cancel:Ge.optional(),requests:pe({tools:pe({call:Ge.optional()}).optional()}).optional()}),yu=x({experimental:Y(p(),Ge).optional(),sampling:x({context:Ge.optional(),tools:Ge.optional()}).optional(),elicitation:jx.optional(),roots:x({listChanged:ee().optional()}).optional(),tasks:hu.optional(),extensions:Y(p(),Ge).optional()}),vu=pt.extend({protocolVersion:p(),capabilities:yu,clientInfo:To}),ja=Xe.extend({method:U("initialize"),params:vu}),Ua=x({experimental:Y(p(),Ge).optional(),logging:Ge.optional(),completions:Ge.optional(),prompts:x({listChanged:ee().optional()}).optional(),resources:x({subscribe:ee().optional(),listChanged:ee().optional()}).optional(),tools:x({listChanged:ee().optional()}).optional(),tasks:gu.optional(),extensions:Y(p(),Ge).optional()}),_u=Ye.extend({protocolVersion:p(),capabilities:Ua,serverInfo:To,instructions:p().optional()}),Ma=bt.extend({method:U("notifications/initialized"),params:St.optional()}),Su=Xe.extend({method:U("server/discover"),params:pt.optional()}),jn=Ye.extend({supportedVersions:N(p()),capabilities:Ua,instructions:p().optional()}),Da=Xe.extend({method:U("ping"),params:pt.optional()}),bu=x({progress:F(),total:le(F()),message:le(p())}),$u=x({...St.shape,...bu.shape,progressToken:xa}),qa=bt.extend({method:U("notifications/progress"),params:$u}),wu=pt.extend({cursor:Ia.optional()}),tn=Xe.extend({params:wu.optional()}),rn=Ye.extend({nextCursor:Ia.optional()}),La=x({uri:p(),mimeType:le(p()),_meta:Y(p(),ue()).optional()}),Va=La.extend({text:p()}),ch=p().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Ka=La.extend({blob:ch}),nn=ve(["user","assistant"]),kr=x({audience:N(nn).optional(),priority:F().min(0).max(1).optional(),lastModified:Lt.datetime({offset:!0}).optional()}),Ja=x({...zr.shape,...en.shape,uri:p(),description:le(p()),mimeType:le(p()),size:le(F()),annotations:kr.optional(),_meta:le(pe({}))}),zu=x({...zr.shape,...en.shape,uriTemplate:p(),description:le(p()),mimeType:le(p()),annotations:kr.optional(),_meta:le(pe({}))}),ku=tn.extend({method:U("resources/list")}),Eu=rn.extend({resources:N(Ja)}),Ru=tn.extend({method:U("resources/templates/list")}),xu=rn.extend({resourceTemplates:N(zu)}),Co=pt.extend({uri:p()}),Iu=Co,Pu=Xe.extend({method:U("resources/read"),params:Iu}),Tu=Ye.extend({contents:N(re([Va,Ka]))}),Cu=bt.extend({method:U("notifications/resources/list_changed"),params:St.optional()}),Au=Co,Ou=Xe.extend({method:U("resources/subscribe"),params:Au}),Nu=Co,ju=Xe.extend({method:U("resources/unsubscribe"),params:Nu}),Fa=x({toolsListChanged:ee().optional(),promptsListChanged:ee().optional(),resourcesListChanged:ee().optional(),resourceSubscriptions:N(p()).optional()}),Uu=pt.extend({notifications:Fa}),Mu=Xe.extend({method:U("subscriptions/listen"),params:Uu}),Du=St.extend({notifications:Fa}),qu=bt.extend({method:U("notifications/subscriptions/acknowledged"),params:Du}),Lu=Ta.extend({[xo]:Qr}),Vu=Ye.extend({_meta:Lu}),Ku=St.extend({uri:p()}),Ju=bt.extend({method:U("notifications/resources/updated"),params:Ku}),Fu=x({name:p(),description:le(p()),required:le(ee())}),Hu=x({...zr.shape,...en.shape,description:le(p()),arguments:le(N(Fu)),_meta:le(pe({}))}),Zu=tn.extend({method:U("prompts/list")}),Wu=rn.extend({prompts:N(Hu)}),Bu=pt.extend({name:p(),arguments:Y(p(),p()).optional()}),Gu=Xe.extend({method:U("prompts/get"),params:Bu}),Ao=x({type:U("text"),text:p(),annotations:kr.optional(),_meta:Y(p(),ue()).optional()}),Oo=x({type:U("image"),data:ch,mimeType:p(),annotations:kr.optional(),_meta:Y(p(),ue()).optional()}),No=x({type:U("audio"),data:ch,mimeType:p(),annotations:kr.optional(),_meta:Y(p(),ue()).optional()}),Xu=x({type:U("tool_use"),name:p(),id:p(),input:Y(p(),ue()),_meta:Y(p(),ue()).optional()}),Yu=x({type:U("resource"),resource:re([Va,Ka]),annotations:kr.optional(),_meta:Y(p(),ue()).optional()}),Qu=Ja.extend({type:U("resource_link")}),jo=re([Ao,Oo,No,Qu,Yu]),el=x({role:nn,content:jo}),tl=Ye.extend({description:p().optional(),messages:N(el)}),rl=bt.extend({method:U("notifications/prompts/list_changed"),params:St.optional()}),nl=x({title:p().optional(),readOnlyHint:ee().optional(),destructiveHint:ee().optional(),idempotentHint:ee().optional(),openWorldHint:ee().optional()}),ol=x({taskSupport:ve(["required","optional","forbidden"]).optional()}),Ha=x({...zr.shape,...en.shape,description:p().optional(),inputSchema:x({type:U("object"),properties:Y(p(),Wr).optional(),required:N(p()).optional()}).catchall(ue()),outputSchema:pe({$schema:p().optional()}).optional(),annotations:nl.optional(),execution:ol.optional(),_meta:Y(p(),ue()).optional()}),il=tn.extend({method:U("tools/list")}),al=rn.extend({tools:N(Ha)}),Uo=Ye.extend({content:N(jo).default([]),structuredContent:ue().optional(),isError:ee().optional()}),uh=Uo.or(Ye.extend({toolResult:ue()})),sl=Yr.extend({name:p(),arguments:Y(p(),ue()).optional()}),cl=Xe.extend({method:U("tools/call"),params:sl}),ul=bt.extend({method:U("notifications/tools/list_changed"),params:St.optional()}),Za=x({autoRefresh:ee().default(!0),debounceMs:F().int().nonnegative().default(300)}),Wa=ve(["debug","info","notice","warning","error","critical","alert","emergency"]),ll=pt.extend({level:Wa}),dl=Xe.extend({method:U("logging/setLevel"),params:ll}),pl=St.extend({level:Wa,logger:p().optional(),data:ue()}),ml=bt.extend({method:U("notifications/message"),params:pl}),fl=x({name:p().optional()}),hl=x({hints:N(fl).optional(),costPriority:F().min(0).max(1).optional(),speedPriority:F().min(0).max(1).optional(),intelligencePriority:F().min(0).max(1).optional()}),gl=x({mode:ve(["auto","required","none"]).optional()}),yl=x({type:U("tool_result"),toolUseId:p().describe("The unique identifier for the corresponding tool call."),content:N(jo),structuredContent:ue().optional(),isError:ee().optional(),_meta:Y(p(),ue()).optional()}),vl=Tn("type",[Ao,Oo,No]),An=Tn("type",[Ao,Oo,No,Xu,yl]),_l=x({role:nn,content:re([An,N(An)]),_meta:Y(p(),ue()).optional()}),Sl=Yr.extend({messages:N(_l),modelPreferences:hl.optional(),systemPrompt:p().optional(),includeContext:ve(["none","thisServer","allServers"]).optional(),temperature:F().optional(),maxTokens:F().int(),stopSequences:N(p()).optional(),metadata:Ge.optional(),tools:N(Ha).optional(),toolChoice:gl.optional()}),bl=Xe.extend({method:U("sampling/createMessage"),params:Sl}),$l=Ye.extend({model:p(),stopReason:le(ve(["endTurn","stopSequence","maxTokens"]).or(p())),role:nn,content:vl}),wl=Ye.extend({model:p(),stopReason:le(ve(["endTurn","stopSequence","maxTokens","toolUse"]).or(p())),role:nn,content:re([An,N(An)])}),Ba=x({type:U("boolean"),title:p().optional(),description:p().optional(),default:ee().optional()}),Mo=x({type:U("string"),title:p().optional(),description:p().optional(),minLength:F().optional(),maxLength:F().optional(),format:ve(["email","uri","date","date-time"]).optional(),default:p().optional()}),Do=x({type:ve(["number","integer"]),title:p().optional(),description:p().optional(),minimum:F().optional(),maximum:F().optional(),default:F().optional()}),Ga=x({type:U("string"),title:p().optional(),description:p().optional(),enum:N(p()),default:p().optional()}),Xa=x({type:U("string"),title:p().optional(),description:p().optional(),oneOf:N(x({const:p(),title:p()})),default:p().optional()}),Ya=x({type:U("string"),title:p().optional(),description:p().optional(),enum:N(p()),enumNames:N(p()).optional(),default:p().optional()}),zl=re([Ga,Xa]),Qa=x({type:U("array"),title:p().optional(),description:p().optional(),minItems:F().optional(),maxItems:F().optional(),items:x({type:U("string"),enum:N(p())}),default:N(p()).optional()}),es=x({type:U("array"),title:p().optional(),description:p().optional(),minItems:F().optional(),maxItems:F().optional(),items:x({anyOf:N(x({const:p(),title:p()}))}),default:N(p()).optional()}),kl=re([Qa,es]),El=re([Ya,zl,kl]),ts=re([El,Ba,Mo,Do]),qo=Yr.extend({mode:U("form").optional(),message:p(),requestedSchema:x({type:U("object"),properties:Y(p(),ts),required:N(p()).optional()}).catchall(ue())}),Rl=Yr.extend({mode:U("url"),message:p(),elicitationId:p(),url:p().url()}),xl=re([qo,Rl]),Il=Xe.extend({method:U("elicitation/create"),params:xl}),Pl=St.extend({elicitationId:p()}),Tl=bt.extend({method:U("notifications/elicitation/complete"),params:Pl}),Cl=Ye.extend({action:ve(["accept","decline","cancel"]),content:Zr(e=>e===null?void 0:e,Y(p(),re([p(),F(),ee(),N(p())])).optional())}),Al=x({type:U("ref/resource"),uri:p()}),Ol=x({type:U("ref/prompt"),name:p()}),Nl=pt.extend({ref:re([Ol,Al]),argument:x({name:p(),value:p()}),context:x({arguments:Y(p(),p()).optional()}).optional()}),jl=Xe.extend({method:U("completion/complete"),params:Nl}),Ul=Ye.extend({completion:pe({values:N(p()).max(100),total:le(F().int()),hasMore:le(ee())})}),Ml=x({uri:p().startsWith("file://"),name:p().optional(),_meta:Y(p(),ue()).optional()}),Dl=Xe.extend({method:U("roots/list"),params:pt.optional()}),ql=Ye.extend({roots:N(Ml)}),Ll=bt.extend({method:U("notifications/roots/list_changed"),params:St.optional()}),lh=pe({ttl:F().optional(),pollInterval:F().optional()}),Vl=ve(["working","input_required","completed","failed","cancelled"]),on=x({taskId:p(),status:Vl,ttl:re([F(),wr()]),createdAt:p(),lastUpdatedAt:p(),pollInterval:le(F()),statusMessage:le(p())}),dh=Ye.extend({task:on}),Kl=St.merge(on),ph=bt.extend({method:U("notifications/tasks/status"),params:Kl}),mh=Xe.extend({method:U("tasks/get"),params:pt.extend({taskId:p()})}),fh=Ye.merge(on),hh=Xe.extend({method:U("tasks/result"),params:pt.extend({taskId:p()})}),gh=Ye.loose(),yh=tn.extend({method:U("tasks/list")}),vh=rn.extend({tasks:N(on)}),_h=Xe.extend({method:U("tasks/cancel"),params:pt.extend({taskId:p()})}),Sh=Ye.merge(on),bh=re([Da,ja,Su,jl,dl,Gu,Zu,ku,Ru,Pu,Ou,ju,Mu,cl,il]),$h=re([Na,qa,Ma,Ll]),wh=re([Oa,$l,wl,Cl,ql]),zh=re([Da,bl,Il,Dl]),kh=re([Na,qa,ml,Ju,Cu,ul,rl,qu,Tl]),Eh=re([Oa,_u,jn,Ul,tl,Wu,Eu,xu,Tu,Uo,al,Vu]),dt=ba().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:V$.custom,message:"URL must be parseable",fatal:!0}),up}).refine(e=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),rs=pe({resource:p().url(),authorization_servers:N(dt).optional(),jwks_uri:p().url().optional(),scopes_supported:N(p()).optional(),bearer_methods_supported:N(p()).optional(),resource_signing_alg_values_supported:N(p()).optional(),resource_name:p().optional(),resource_documentation:p().optional(),resource_policy_uri:p().url().optional(),resource_tos_uri:p().url().optional(),tls_client_certificate_bound_access_tokens:ee().optional(),authorization_details_types_supported:N(p()).optional(),dpop_signing_alg_values_supported:N(p()).optional(),dpop_bound_access_tokens_required:ee().optional()}),Un=pe({issuer:p(),authorization_endpoint:dt,token_endpoint:dt,registration_endpoint:dt.optional(),scopes_supported:N(p()).optional(),response_types_supported:N(p()),response_modes_supported:N(p()).optional(),grant_types_supported:N(p()).optional(),token_endpoint_auth_methods_supported:N(p()).optional(),token_endpoint_auth_signing_alg_values_supported:N(p()).optional(),service_documentation:dt.optional(),revocation_endpoint:dt.optional(),revocation_endpoint_auth_methods_supported:N(p()).optional(),revocation_endpoint_auth_signing_alg_values_supported:N(p()).optional(),introspection_endpoint:p().optional(),introspection_endpoint_auth_methods_supported:N(p()).optional(),introspection_endpoint_auth_signing_alg_values_supported:N(p()).optional(),code_challenge_methods_supported:N(p()).optional(),client_id_metadata_document_supported:ee().optional(),authorization_response_iss_parameter_supported:ee().optional().catch(void 0)}),Jl=pe({issuer:p(),authorization_endpoint:dt,token_endpoint:dt,userinfo_endpoint:dt.optional(),jwks_uri:dt,registration_endpoint:dt.optional(),scopes_supported:N(p()).optional(),response_types_supported:N(p()),response_modes_supported:N(p()).optional(),grant_types_supported:N(p()).optional(),acr_values_supported:N(p()).optional(),subject_types_supported:N(p()),id_token_signing_alg_values_supported:N(p()),id_token_encryption_alg_values_supported:N(p()).optional(),id_token_encryption_enc_values_supported:N(p()).optional(),userinfo_signing_alg_values_supported:N(p()).optional(),userinfo_encryption_alg_values_supported:N(p()).optional(),userinfo_encryption_enc_values_supported:N(p()).optional(),request_object_signing_alg_values_supported:N(p()).optional(),request_object_encryption_alg_values_supported:N(p()).optional(),request_object_encryption_enc_values_supported:N(p()).optional(),token_endpoint_auth_methods_supported:N(p()).optional(),token_endpoint_auth_signing_alg_values_supported:N(p()).optional(),display_values_supported:N(p()).optional(),claim_types_supported:N(p()).optional(),claims_supported:N(p()).optional(),service_documentation:p().optional(),claims_locales_supported:N(p()).optional(),ui_locales_supported:N(p()).optional(),claims_parameter_supported:ee().optional(),request_parameter_supported:ee().optional(),request_uri_parameter_supported:ee().optional(),require_request_uri_registration:ee().optional(),op_policy_uri:dt.optional(),op_tos_uri:dt.optional(),client_id_metadata_document_supported:ee().optional(),authorization_response_iss_parameter_supported:ee().optional().catch(void 0)}),ns=x({...Jl.shape,...Un.pick({code_challenge_methods_supported:!0}).shape}),Lo=x({access_token:p(),id_token:p().optional(),token_type:p(),expires_in:eu.number().optional(),scope:p().optional(),refresh_token:p().optional()}).strip(),os=x({issued_token_type:U("urn:ietf:params:oauth:token-type:id-jag"),access_token:p(),token_type:p().optional(),expires_in:F().optional(),scope:p().optional()}).strip(),Mn=x({error:p(),error_description:p().optional(),error_uri:p().optional()}),ah=dt.optional().or(U("").transform(()=>{})),Fl=x({redirect_uris:N(dt),token_endpoint_auth_method:p().optional(),grant_types:N(p()).optional(),response_types:N(p()).optional(),application_type:p().optional(),client_name:p().optional(),client_uri:dt.optional(),logo_uri:ah,scope:p().optional(),contacts:N(p()).optional(),tos_uri:ah,policy_uri:p().optional(),jwks_uri:dt.optional(),jwks:Gf().optional(),software_id:p().optional(),software_version:p().optional(),software_statement:p().optional()}).strip(),Hl=x({client_id:p(),client_secret:p().optional(),client_id_issued_at:F().optional(),client_secret_expires_at:F().optional()}).strip(),is=Fl.merge(Hl),Rh=x({error:p(),error_description:p().optional()}).strip(),xh=x({token:p(),token_type_hint:p().optional()}).strip()});var W$=q(()=>{Z$()});function Ln(e,t){let r=new Set,n=t;for(;typeof n=="function";){let o=n.mcpBrand;Object.prototype.hasOwnProperty.call(n,"mcpBrand")&&typeof o=="string"&&r.add(o),n=Object.getPrototypeOf(n)}r.size!==0&&Object.defineProperty(e,Oh,{value:r,enumerable:!1,configurable:!0})}function Ut(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,Oh)){let r=t[Oh];if(r&&typeof r.has=="function"&&r.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}function qh(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function Lh({requestedResource:e,configuredResource:t}){let r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length=sw}function Kh(e){return e.filter(t=>!Ir(t))}function ps(e){return e.filter(t=>Ir(t))}function cw(e){let t=e.structuredContent;return t===void 0||!(typeof t!="object"||t===null||Array.isArray(t))||(e.content?.some(r=>r.type==="text")??!1)?e:{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}function Ux(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||uw.some(t=>t in e)?e:{...e,content:[]}}function Mx(){let e=Cn(()=>re([p(),F(),ee(),wr(),Y(p(),e),N(e)])),t=Y(p(),e),r=re([p(),F().int()]),n=p(),o=x({ttl:F().optional()}),i=x({taskId:p()}),a=pe({progressToken:r.optional(),"io.modelcontextprotocol/related-task":i.optional()}),s=x({_meta:a.optional()}),c=s.extend({task:o.optional()}),u=x({method:p(),params:s.loose().optional()}),l=x({_meta:a.optional()}),d=x({method:p(),params:l.loose().optional()}),m=pe({_meta:a.optional()}),v=re([p(),F().int()]),g=m.strict(),h=l.extend({requestId:v.optional(),reason:p().optional()}),f=d.extend({method:U("notifications/cancelled"),params:h}),y=x({src:p(),mimeType:p().optional(),sizes:N(p()).optional(),theme:ve(["light","dark"]).optional()}),S=x({icons:N(y).optional()}),_=x({name:p(),title:p().optional()}),$=_.extend({..._.shape,...S.shape,version:p(),websiteUrl:p().optional(),description:p().optional()}),k=sr(x({applyDefaults:ee().optional()}),t),w=Zr(_t=>_t&&typeof _t=="object"&&!Array.isArray(_t)&&Object.keys(_t).length===0?{form:{}}:_t,sr(x({form:k.optional(),url:t.optional()}),t.optional())),b=pe({list:t.optional(),cancel:t.optional(),requests:pe({sampling:pe({createMessage:t.optional()}).optional(),elicitation:pe({create:t.optional()}).optional()}).optional()}),E=pe({list:t.optional(),cancel:t.optional(),requests:pe({tools:pe({call:t.optional()}).optional()}).optional()}),j=x({experimental:Y(p(),t).optional(),sampling:x({context:t.optional(),tools:t.optional()}).optional(),elicitation:w.optional(),roots:x({listChanged:ee().optional()}).optional(),tasks:b.optional(),extensions:Y(p(),t).optional()}),V=s.extend({protocolVersion:p(),capabilities:j,clientInfo:$}),A=u.extend({method:U("initialize"),params:V}),L=x({experimental:Y(p(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:x({listChanged:ee().optional()}).optional(),resources:x({subscribe:ee().optional(),listChanged:ee().optional()}).optional(),tools:x({listChanged:ee().optional()}).optional(),tasks:E.optional(),extensions:Y(p(),t).optional()}),Z=m.extend({protocolVersion:p(),capabilities:L,serverInfo:$,instructions:p().optional()}),J=d.extend({method:U("notifications/initialized"),params:l.optional()}),te=u.extend({method:U("ping"),params:s.optional()}),_e=x({progress:F(),total:le(F()),message:le(p())}),ke=x({...l.shape,..._e.shape,progressToken:r}),Ne=d.extend({method:U("notifications/progress"),params:ke}),be=s.extend({cursor:n.optional()}),P=u.extend({params:be.optional()}),M=m.extend({nextCursor:n.optional()}),K=x({uri:p(),mimeType:le(p()),_meta:Y(p(),ue()).optional()}),z=K.extend({text:p()}),I=p().refine(_t=>{try{return atob(_t),!0}catch{return!1}},{message:"Invalid Base64 string"}),O=K.extend({blob:I}),W=ve(["user","assistant"]),ce=x({audience:N(W).optional(),priority:F().min(0).max(1).optional(),lastModified:Lt.datetime({offset:!0}).optional()}),$e=x({..._.shape,...S.shape,uri:p(),description:le(p()),mimeType:le(p()),size:le(F()),annotations:ce.optional(),_meta:le(pe({}))}),B=x({..._.shape,...S.shape,uriTemplate:p(),description:le(p()),mimeType:le(p()),annotations:ce.optional(),_meta:le(pe({}))}),Re=P.extend({method:U("resources/list")}),Fe=M.extend({resources:N($e)}),R=P.extend({method:U("resources/templates/list")}),T=M.extend({resourceTemplates:N(B)}),D=s.extend({uri:p()}),oe=D,ne=u.extend({method:U("resources/read"),params:oe}),ie=m.extend({contents:N(re([z,O]))}),me=d.extend({method:U("notifications/resources/list_changed"),params:l.optional()}),Pe=D,Ee=u.extend({method:U("resources/subscribe"),params:Pe}),Ze=D,je=u.extend({method:U("resources/unsubscribe"),params:Ze}),De=l.extend({uri:p()}),nt=d.extend({method:U("notifications/resources/updated"),params:De}),Jt=x({name:p(),description:le(p()),required:le(ee())}),yt=x({..._.shape,...S.shape,description:le(p()),arguments:le(N(Jt)),_meta:le(pe({}))}),ut=P.extend({method:U("prompts/list")}),Ft=M.extend({prompts:N(yt)}),rr=s.extend({name:p(),arguments:Y(p(),p()).optional()}),hn=u.extend({method:U("prompts/get"),params:rr}),gn=x({type:U("text"),text:p(),annotations:ce.optional(),_meta:Y(p(),ue()).optional()}),yn=x({type:U("image"),data:I,mimeType:p(),annotations:ce.optional(),_meta:Y(p(),ue()).optional()}),vn=x({type:U("audio"),data:I,mimeType:p(),annotations:ce.optional(),_meta:Y(p(),ue()).optional()}),mi=x({type:U("tool_use"),name:p(),id:p(),input:Y(p(),ue()),_meta:Y(p(),ue()).optional()}),Or=x({type:U("resource"),resource:re([z,O]),annotations:ce.optional(),_meta:Y(p(),ue()).optional()}),fi=$e.extend({type:U("resource_link")}),Dt=re([gn,yn,vn,fi,Or]),no=x({role:W,content:Dt}),oo=m.extend({description:p().optional(),messages:N(no)}),_n=d.extend({method:U("notifications/prompts/list_changed"),params:l.optional()}),hi=x({title:p().optional(),readOnlyHint:ee().optional(),destructiveHint:ee().optional(),idempotentHint:ee().optional(),openWorldHint:ee().optional()}),io=x({taskSupport:ve(["required","optional","forbidden"]).optional()}),Sn=x({..._.shape,...S.shape,description:p().optional(),inputSchema:x({type:U("object"),properties:Y(p(),e).optional(),required:N(p()).optional()}).catchall(ue()),outputSchema:x({type:U("object"),properties:Y(p(),e).optional(),required:N(p()).optional()}).catchall(ue()).optional(),annotations:hi.optional(),execution:io.optional(),_meta:Y(p(),ue()).optional()}),ao=P.extend({method:U("tools/list")}),so=M.extend({tools:N(Sn)}),co=m.extend({content:N(Dt),structuredContent:Y(p(),ue()).optional(),isError:ee().optional()}),vt=c.extend({name:p(),arguments:Y(p(),ue()).optional()}),gi=u.extend({method:U("tools/call"),params:vt}),Us=d.extend({method:U("notifications/tools/list_changed"),params:l.optional()}),uo=ve(["debug","info","notice","warning","error","critical","alert","emergency"]),yi=s.extend({level:uo}),vi=u.extend({method:U("logging/setLevel"),params:yi}),_i=l.extend({level:uo,logger:p().optional(),data:ue()}),Si=d.extend({method:U("notifications/message"),params:_i}),bi=x({name:p().optional()}),$i=x({hints:N(bi).optional(),costPriority:F().min(0).max(1).optional(),speedPriority:F().min(0).max(1).optional(),intelligencePriority:F().min(0).max(1).optional()}),wi=x({mode:ve(["auto","required","none"]).optional()}),Ms=x({type:U("tool_result"),toolUseId:p().describe("The unique identifier for the corresponding tool call."),content:N(Dt),structuredContent:x({}).loose().optional(),isError:ee().optional(),_meta:Y(p(),ue()).optional()}),zi=Tn("type",[gn,yn,vn]),Nr=Tn("type",[gn,yn,vn,mi,Ms]),ki=x({role:W,content:re([Nr,N(Nr)]),_meta:Y(p(),ue()).optional()}),Ei=c.extend({messages:N(ki),modelPreferences:$i.optional(),systemPrompt:p().optional(),includeContext:ve(["none","thisServer","allServers"]).optional(),temperature:F().optional(),maxTokens:F().int(),stopSequences:N(p()).optional(),metadata:t.optional(),tools:N(Sn).optional(),toolChoice:wi.optional()}),Ri=u.extend({method:U("sampling/createMessage"),params:Ei}),xi=m.extend({model:p(),stopReason:le(ve(["endTurn","stopSequence","maxTokens"]).or(p())),role:W,content:zi}),Ii=m.extend({model:p(),stopReason:le(ve(["endTurn","stopSequence","maxTokens","toolUse"]).or(p())),role:W,content:re([Nr,N(Nr)])}),Pi=x({type:U("boolean"),title:p().optional(),description:p().optional(),default:ee().optional()}),Ti=x({type:U("string"),title:p().optional(),description:p().optional(),minLength:F().optional(),maxLength:F().optional(),format:ve(["email","uri","date","date-time"]).optional(),default:p().optional()}),Ci=x({type:ve(["number","integer"]),title:p().optional(),description:p().optional(),minimum:F().optional(),maximum:F().optional(),default:F().optional()}),Ai=x({type:U("string"),title:p().optional(),description:p().optional(),enum:N(p()),default:p().optional()}),Oi=x({type:U("string"),title:p().optional(),description:p().optional(),oneOf:N(x({const:p(),title:p()})),default:p().optional()}),Ni=x({type:U("string"),title:p().optional(),description:p().optional(),enum:N(p()),enumNames:N(p()).optional(),default:p().optional()}),ji=re([Ai,Oi]),bn=x({type:U("array"),title:p().optional(),description:p().optional(),minItems:F().optional(),maxItems:F().optional(),items:x({type:U("string"),enum:N(p())}),default:N(p()).optional()}),$n=x({type:U("array"),title:p().optional(),description:p().optional(),minItems:F().optional(),maxItems:F().optional(),items:x({anyOf:N(x({const:p(),title:p()}))}),default:N(p()).optional()}),Ds=re([bn,$n]),qs=re([Ni,ji,Ds]),Tt=re([qs,Pi,Ti,Ci]),Ct=c.extend({mode:U("form").optional(),message:p(),requestedSchema:x({type:U("object"),properties:Y(p(),Tt),required:N(p()).optional()}).catchall(ue())}),Ui=c.extend({mode:U("url"),message:p(),elicitationId:p(),url:p().url()}),Ht=re([Ct,Ui]),Ls=u.extend({method:U("elicitation/create"),params:Ht}),Vs=l.extend({elicitationId:p()}),Ks=d.extend({method:U("notifications/elicitation/complete"),params:Vs}),Js=m.extend({action:ve(["accept","decline","cancel"]),content:Zr(_t=>_t===null?void 0:_t,Y(p(),re([p(),F(),ee(),N(p())])).optional())}),Fs=x({type:U("ref/resource"),uri:p()}),Hs=x({type:U("ref/prompt"),name:p()}),Zs=s.extend({ref:re([Hs,Fs]),argument:x({name:p(),value:p()}),context:x({arguments:Y(p(),p()).optional()}).optional()}),Mi=u.extend({method:U("completion/complete"),params:Zs}),Ws=m.extend({completion:pe({values:N(p()).max(100),total:le(F().int()),hasMore:le(ee())})}),Bs=x({uri:p().startsWith("file://"),name:p().optional(),_meta:Y(p(),ue()).optional()}),lo=u.extend({method:U("roots/list"),params:s.optional()}),Di=m.extend({roots:N(Bs)}),Gs=d.extend({method:U("notifications/roots/list_changed"),params:l.optional()}),Xs=pe({ttl:F().optional(),pollInterval:F().optional()}),Ys=ve(["working","input_required","completed","failed","cancelled"]),jr=x({taskId:p(),status:Ys,ttl:re([F(),wr()]),createdAt:p(),lastUpdatedAt:p(),pollInterval:le(F()),statusMessage:le(p())}),kt=m.extend({task:jr}),Qs=l.merge(jr),wn=d.extend({method:U("notifications/tasks/status"),params:Qs}),po=u.extend({method:U("tasks/get"),params:s.extend({taskId:p()})}),mo=m.merge(jr),fo=u.extend({method:U("tasks/result"),params:s.extend({taskId:p()})}),np=m.loose(),Et=P.extend({method:U("tasks/list")}),et=M.extend({tasks:N(jr)}),zn=u.extend({method:U("tasks/cancel"),params:s.extend({taskId:p()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:n,TaskMetadataSchema:o,RelatedTaskMetadataSchema:i,RequestMetaSchema:a,BaseRequestParamsSchema:s,TaskAugmentedRequestParamsSchema:c,RequestSchema:u,NotificationsParamsSchema:l,NotificationSchema:d,ResultSchema:m,RequestIdSchema:v,EmptyResultSchema:g,CancelledNotificationParamsSchema:h,CancelledNotificationSchema:f,IconSchema:y,IconsSchema:S,BaseMetadataSchema:_,ImplementationSchema:$,ClientTasksCapabilitySchema:b,ServerTasksCapabilitySchema:E,ClientCapabilitiesSchema:j,InitializeRequestParamsSchema:V,InitializeRequestSchema:A,ServerCapabilitiesSchema:L,InitializeResultSchema:Z,InitializedNotificationSchema:J,PingRequestSchema:te,ProgressSchema:_e,ProgressNotificationParamsSchema:ke,ProgressNotificationSchema:Ne,PaginatedRequestParamsSchema:be,PaginatedRequestSchema:P,PaginatedResultSchema:M,ResourceContentsSchema:K,TextResourceContentsSchema:z,BlobResourceContentsSchema:O,RoleSchema:W,AnnotationsSchema:ce,ResourceSchema:$e,ResourceTemplateSchema:B,ListResourcesRequestSchema:Re,ListResourcesResultSchema:Fe,ListResourceTemplatesRequestSchema:R,ListResourceTemplatesResultSchema:T,ResourceRequestParamsSchema:D,ReadResourceRequestParamsSchema:oe,ReadResourceRequestSchema:ne,ReadResourceResultSchema:ie,ResourceListChangedNotificationSchema:me,SubscribeRequestParamsSchema:Pe,SubscribeRequestSchema:Ee,UnsubscribeRequestParamsSchema:Ze,UnsubscribeRequestSchema:je,ResourceUpdatedNotificationParamsSchema:De,ResourceUpdatedNotificationSchema:nt,PromptArgumentSchema:Jt,PromptSchema:yt,ListPromptsRequestSchema:ut,ListPromptsResultSchema:Ft,GetPromptRequestParamsSchema:rr,GetPromptRequestSchema:hn,TextContentSchema:gn,ImageContentSchema:yn,AudioContentSchema:vn,ToolUseContentSchema:mi,EmbeddedResourceSchema:Or,ResourceLinkSchema:fi,ContentBlockSchema:Dt,PromptMessageSchema:no,GetPromptResultSchema:oo,PromptListChangedNotificationSchema:_n,ToolAnnotationsSchema:hi,ToolExecutionSchema:io,ToolSchema:Sn,ListToolsRequestSchema:ao,ListToolsResultSchema:so,CallToolResultSchema:co,CallToolRequestParamsSchema:vt,CallToolRequestSchema:gi,ToolListChangedNotificationSchema:Us,LoggingLevelSchema:uo,SetLevelRequestParamsSchema:yi,SetLevelRequestSchema:vi,LoggingMessageNotificationParamsSchema:_i,LoggingMessageNotificationSchema:Si,ModelHintSchema:bi,ModelPreferencesSchema:$i,ToolChoiceSchema:wi,ToolResultContentSchema:Ms,SamplingContentSchema:zi,SamplingMessageContentBlockSchema:Nr,SamplingMessageSchema:ki,CreateMessageRequestParamsSchema:Ei,CreateMessageRequestSchema:Ri,CreateMessageResultSchema:xi,CreateMessageResultWithToolsSchema:Ii,BooleanSchemaSchema:Pi,StringSchemaSchema:Ti,NumberSchemaSchema:Ci,UntitledSingleSelectEnumSchemaSchema:Ai,TitledSingleSelectEnumSchemaSchema:Oi,LegacyTitledEnumSchemaSchema:Ni,SingleSelectEnumSchemaSchema:ji,UntitledMultiSelectEnumSchemaSchema:bn,TitledMultiSelectEnumSchemaSchema:$n,MultiSelectEnumSchemaSchema:Ds,EnumSchemaSchema:qs,PrimitiveSchemaDefinitionSchema:Tt,ElicitRequestFormParamsSchema:Ct,ElicitRequestURLParamsSchema:Ui,ElicitRequestParamsSchema:Ht,ElicitRequestSchema:Ls,ElicitationCompleteNotificationParamsSchema:Vs,ElicitationCompleteNotificationSchema:Ks,ElicitResultSchema:Js,ResourceTemplateReferenceSchema:Fs,PromptReferenceSchema:Hs,CompleteRequestParamsSchema:Zs,CompleteRequestSchema:Mi,CompleteResultSchema:Ws,RootSchema:Bs,ListRootsRequestSchema:lo,ListRootsResultSchema:Di,RootsListChangedNotificationSchema:Gs,TaskCreationParamsSchema:Xs,TaskStatusSchema:Ys,TaskSchema:jr,CreateTaskResultSchema:kt,TaskStatusNotificationParamsSchema:Qs,TaskStatusNotificationSchema:wn,GetTaskRequestSchema:po,GetTaskResultSchema:mo,GetTaskPayloadRequestSchema:fo,GetTaskPayloadResultSchema:np,ListTasksRequestSchema:Et,ListTasksResultSchema:et,CancelTaskRequestSchema:zn,CancelTaskResultSchema:m.merge(jr),ClientRequestSchema:re([te,A,Mi,vi,hn,ut,Re,R,ne,Ee,je,gi,ao,po,fo,Et,zn]),ClientNotificationSchema:re([f,Ne,J,Gs,wn]),ClientResultSchema:re([g,xi,Ii,Js,Di,mo,et,kt]),ServerRequestSchema:re([te,Ri,Ls,lo,po,fo,Et,zn]),ServerNotificationSchema:re([f,Ne,Si,nt,me,Us,_n,wn,Ks]),ServerResultSchema:re([g,Z,Ws,oo,Ft,Fe,T,ie,co,so,mo,et,kt]),CallToolResultWireSchema:ue().superRefine((_t,Lk)=>{if(!(typeof _t!="object"||_t===null||Array.isArray(_t)||_t.content!==void 0)){for(let Ey of uw)if(Ey in _t){Lk.addIssue({code:"custom",message:`content is required when the body carries '${Ey}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(Ux).pipe(co)}}function Jh(){return Dx??=Mx()}function lw(e){return e.type!=="object"}function Vx(e){let t=typeof e.$schema=="string"?e.$schema:void 0;if(e.$id!==void 0)return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let r=(n,o)=>{if(Array.isArray(n))return n.map(a=>r(a,!1));if(n===null||typeof n!="object"||!o&&n.$id!==void 0)return n;let i={};for(let[a,s]of Object.entries(n))o?i[a]=r(s,!1):(a==="$ref"||a==="$dynamicRef")&&typeof s=="string"?i[a]=s==="#"?"#/properties/result":s.startsWith("#/")?`#/properties/result${s.slice(1)}`:s:qx.has(a)?i[a]=s:Lx.has(a)?i[a]=r(s,!0):i[a]=r(s,!1);return i};return{...t!==void 0&&{$schema:t},type:"object",properties:{result:r(e,!1)},required:["result"]}}function Ql(){if(Zl)return Zl;let e=Jh();return Zl={requestSchemas:{ping:e.PingRequestSchema,initialize:e.InitializeRequestSchema,"completion/complete":e.CompleteRequestSchema,"logging/setLevel":e.SetLevelRequestSchema,"prompts/get":e.GetPromptRequestSchema,"prompts/list":e.ListPromptsRequestSchema,"resources/list":e.ListResourcesRequestSchema,"resources/templates/list":e.ListResourceTemplatesRequestSchema,"resources/read":e.ReadResourceRequestSchema,"resources/subscribe":e.SubscribeRequestSchema,"resources/unsubscribe":e.UnsubscribeRequestSchema,"tools/call":e.CallToolRequestSchema,"tools/list":e.ListToolsRequestSchema,"tasks/get":e.GetTaskRequestSchema,"tasks/result":e.GetTaskPayloadRequestSchema,"tasks/list":e.ListTasksRequestSchema,"tasks/cancel":e.CancelTaskRequestSchema,"sampling/createMessage":e.CreateMessageRequestSchema,"elicitation/create":e.ElicitRequestSchema,"roots/list":e.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":e.CancelledNotificationSchema,"notifications/progress":e.ProgressNotificationSchema,"notifications/initialized":e.InitializedNotificationSchema,"notifications/roots/list_changed":e.RootsListChangedNotificationSchema,"notifications/tasks/status":e.TaskStatusNotificationSchema,"notifications/message":e.LoggingMessageNotificationSchema,"notifications/resources/updated":e.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":e.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":e.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":e.PromptListChangedNotificationSchema,"notifications/elicitation/complete":e.ElicitationCompleteNotificationSchema},resultSchemas:{ping:e.EmptyResultSchema,initialize:e.InitializeResultSchema,"completion/complete":e.CompleteResultSchema,"logging/setLevel":e.EmptyResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"resources/subscribe":e.EmptyResultSchema,"resources/unsubscribe":e.EmptyResultSchema,"tools/call":e.CallToolResultWireSchema,"tools/list":e.ListToolsResultSchema,"sampling/createMessage":e.CreateMessageResultWithToolsSchema,"elicitation/create":e.ElicitResultSchema,"roots/list":e.ListRootsResultSchema}},Zl}function Jx(){Ql()}function mw(e){return Object.prototype.hasOwnProperty.call(dw,e)}function fw(e){return Object.prototype.hasOwnProperty.call(pw,e)}function Fx(e){return Object.prototype.hasOwnProperty.call(Kx,e)}function Hx(e){return Fx(e)?Ql().resultSchemas[e]:void 0}function Zx(e){return mw(e)?Ql().requestSchemas[e]:void 0}function Wx(e){return fw(e)?Ql().notificationSchemas[e]:void 0}function Nh(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Wl(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}function G$(e){return Nh(e)&&Nh(e.outputSchema)&&lw(e.outputSchema)}function Bx(){let e=Cn(()=>re([p(),F(),ee(),wr(),Y(p(),e),N(e)])),t=Y(p(),e),r=re([p(),F().int()]),n=p(),o=re([p(),F().int()]),i=ve(["user","assistant"]),a=ve(["debug","info","notice","warning","error","critical","alert","emergency"]),s=p().refine(et=>{try{return atob(et),!0}catch{return!1}},{message:"Invalid Base64 string"}),c=x({ttl:F().optional()}),u=x({taskId:p()}),l=pe({progressToken:r.optional(),"io.modelcontextprotocol/related-task":u.optional()}),d=x({_meta:l.optional()}),m=d.extend({task:c.optional()}),v=x({_meta:l.optional()}),g=x({method:p(),params:v.loose().optional()}),h=x({src:p(),mimeType:p().optional(),sizes:N(p()).optional(),theme:ve(["light","dark"]).optional()}),f=x({icons:N(h).optional()}),y=x({name:p(),title:p().optional()}),S=y.extend({...y.shape,...f.shape,version:p(),websiteUrl:p().optional(),description:p().optional()}),_=sr(x({applyDefaults:ee().optional()}),t),$=Zr(et=>et&&typeof et=="object"&&!Array.isArray(et)&&Object.keys(et).length===0?{form:{}}:et,sr(x({form:_.optional(),url:t.optional()}),t.optional())),k=pe({list:t.optional(),cancel:t.optional(),requests:pe({sampling:pe({createMessage:t.optional()}).optional(),elicitation:pe({create:t.optional()}).optional()}).optional()}),w=pe({list:t.optional(),cancel:t.optional(),requests:pe({tools:pe({call:t.optional()}).optional()}).optional()}),b=x({experimental:Y(p(),t).optional(),sampling:x({context:t.optional(),tools:t.optional()}).optional(),elicitation:$.optional(),roots:x({listChanged:ee().optional()}).optional(),tasks:k.optional(),extensions:Y(p(),t).optional()}),E=x({experimental:Y(p(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:x({listChanged:ee().optional()}).optional(),resources:x({subscribe:ee().optional(),listChanged:ee().optional()}).optional(),tools:x({listChanged:ee().optional()}).optional(),tasks:w.optional(),extensions:Y(p(),t).optional()}),j=x({progress:F(),total:le(F()),message:le(p())}),V=x({...v.shape,...j.shape,progressToken:r}),A=g.extend({method:U("notifications/progress"),params:V}),L=v.extend({level:a,logger:p().optional(),data:ue()}),Z=g.extend({method:U("notifications/message"),params:L}),J=x({uri:p(),mimeType:le(p()),_meta:Y(p(),ue()).optional()}),te=J.extend({text:p()}),_e=J.extend({blob:s}),ke=x({audience:N(i).optional(),priority:F().min(0).max(1).optional(),lastModified:Lt.datetime({offset:!0}).optional()}),Ne=x({...y.shape,...f.shape,uri:p(),description:le(p()),mimeType:le(p()),size:le(F()),annotations:ke.optional(),_meta:le(pe({}))}),be=x({...y.shape,...f.shape,uriTemplate:p(),description:le(p()),mimeType:le(p()),annotations:ke.optional(),_meta:le(pe({}))}),P=g.extend({method:U("notifications/resources/list_changed"),params:v.optional()}),M=v.extend({uri:p()}),K=g.extend({method:U("notifications/resources/updated"),params:M}),z=x({name:p(),description:le(p()),required:le(ee())}),I=x({...y.shape,...f.shape,description:le(p()),arguments:le(N(z)),_meta:le(pe({}))}),O=g.extend({method:U("notifications/prompts/list_changed"),params:v.optional()}),W=x({type:U("text"),text:p(),annotations:ke.optional(),_meta:Y(p(),ue()).optional()}),ce=x({type:U("image"),data:s,mimeType:p(),annotations:ke.optional(),_meta:Y(p(),ue()).optional()}),$e=x({type:U("audio"),data:s,mimeType:p(),annotations:ke.optional(),_meta:Y(p(),ue()).optional()}),B=x({type:U("tool_use"),name:p(),id:p(),input:Y(p(),ue()),_meta:Y(p(),ue()).optional()}),Re=x({type:U("resource"),resource:re([te,_e]),annotations:ke.optional(),_meta:Y(p(),ue()).optional()}),Fe=Ne.extend({type:U("resource_link")}),R=re([W,ce,$e,Fe,Re]),T=x({role:i,content:R}),D=x({title:p().optional(),readOnlyHint:ee().optional(),destructiveHint:ee().optional(),idempotentHint:ee().optional(),openWorldHint:ee().optional()}),oe=g.extend({method:U("notifications/tools/list_changed"),params:v.optional()}),ne=x({name:p().optional()}),ie=x({hints:N(ne).optional(),costPriority:F().min(0).max(1).optional(),speedPriority:F().min(0).max(1).optional(),intelligencePriority:F().min(0).max(1).optional()}),me=x({mode:ve(["auto","required","none"]).optional()}),Pe=x({type:U("boolean"),title:p().optional(),description:p().optional(),default:ee().optional()}),Ee=x({type:U("string"),title:p().optional(),description:p().optional(),minLength:F().optional(),maxLength:F().optional(),format:ve(["email","uri","date","date-time"]).optional(),default:p().optional()}),Ze=x({type:ve(["number","integer"]),title:p().optional(),description:p().optional(),minimum:F().optional(),maximum:F().optional(),default:F().optional()}),je=x({type:U("string"),title:p().optional(),description:p().optional(),enum:N(p()),default:p().optional()}),De=x({type:U("string"),title:p().optional(),description:p().optional(),oneOf:N(x({const:p(),title:p()})),default:p().optional()}),nt=x({type:U("string"),title:p().optional(),description:p().optional(),enum:N(p()),enumNames:N(p()).optional(),default:p().optional()}),Jt=re([je,De]),yt=x({type:U("array"),title:p().optional(),description:p().optional(),minItems:F().optional(),maxItems:F().optional(),items:x({type:U("string"),enum:N(p())}),default:N(p()).optional()}),ut=x({type:U("array"),title:p().optional(),description:p().optional(),minItems:F().optional(),maxItems:F().optional(),items:x({anyOf:N(x({const:p(),title:p()}))}),default:N(p()).optional()}),Ft=re([yt,ut]),rr=re([nt,Jt,Ft]),hn=re([rr,Pe,Ee,Ze]),gn=m.extend({mode:U("form").optional(),message:p(),requestedSchema:x({type:U("object"),properties:Y(p(),hn),required:N(p()).optional()}).catchall(ue())}),yn=x({type:U("ref/resource"),uri:p()}),vn=x({type:U("ref/prompt"),name:p()}),mi=x({uri:p().startsWith("file://"),name:p().optional(),_meta:Y(p(),ue()).optional()}),Or=b.shape,fi=x({experimental:Or.experimental,sampling:Or.sampling,elicitation:Or.elicitation,roots:Or.roots,extensions:Or.extensions}),Dt=E.shape,no=x({experimental:Dt.experimental,logging:Dt.logging,completions:Dt.completions,prompts:Dt.prompts,resources:Dt.resources,tools:Dt.tools,extensions:Dt.extensions}),oo=pe({progressToken:r.optional(),[cr]:p(),[On]:S.optional(),[Gr]:fi,[Nn]:a.optional()}),_n=x({...y.shape,...f.shape,description:p().optional(),inputSchema:pe({$schema:p().optional(),type:U("object")}),outputSchema:pe({$schema:p().optional()}).optional(),annotations:D.optional(),_meta:Y(p(),ue()).optional()}),hi=x({type:U("tool_result"),toolUseId:p(),content:N(R),structuredContent:ue().optional(),isError:ee().optional(),_meta:Y(p(),ue()).optional()}),io=re([W,ce,$e,B,hi]),Sn=x({role:i,content:re([io,N(io)]),_meta:Y(p(),ue()).optional()}),ao=p(),so=pe({[ur]:S.optional().catch(void 0)}),co=so.optional();function vt(et){return pe({_meta:co,resultType:ao.default("complete"),...et})}let gi=vt({}),Us=vt({nextCursor:n.optional()}),uo=vt({content:N(R),structuredContent:ue().optional(),isError:ee().optional()}),yi=vt({ttlMs:F().int().min(0),cacheScope:ve(["public","private"]),tools:N(_n),nextCursor:n.optional()}),vi=vt({ttlMs:F().int().min(0),cacheScope:ve(["public","private"]),prompts:N(I),nextCursor:n.optional()}),_i=vt({description:p().optional(),messages:N(T)}),Si=vt({ttlMs:F().int().min(0),cacheScope:ve(["public","private"]),resources:N(Ne),nextCursor:n.optional()}),bi=vt({ttlMs:F().int().min(0),cacheScope:ve(["public","private"]),resourceTemplates:N(be),nextCursor:n.optional()}),$i=vt({ttlMs:F().int().min(0),cacheScope:ve(["public","private"]),contents:N(re([te,_e]))}),wi=vt({completion:x({values:N(p()).max(100),total:F().int().optional(),hasMore:ee().optional()}).loose()}),Ms=vt({ttlMs:F().int().min(0),cacheScope:ve(["public","private"])}),zi=vt({ttlMs:F().int().min(0).catch(0),cacheScope:ve(["public","private"]).catch("private"),supportedVersions:N(p()),capabilities:no,instructions:p().optional()}),Nr=x({messages:N(Sn),modelPreferences:ie.optional(),systemPrompt:p().optional(),includeContext:ve(["none","thisServer","allServers"]).optional(),temperature:F().optional(),maxTokens:F().int(),stopSequences:N(p()).optional(),metadata:t.optional(),tools:N(_n).optional(),toolChoice:me.optional()}),ki=x({method:U("sampling/createMessage"),params:Nr}),Ei=x({method:U("roots/list"),params:x({_meta:Y(p(),ue()).optional()}).optional()}),Ri=x({...Sn.shape,model:p(),stopReason:p().optional()}),xi=x({roots:N(mi)}),Ii=x({action:ve(["accept","decline","cancel"]),content:Y(p(),re([p(),F(),ee(),N(p())])).optional()}),Pi=x({mode:U("url"),message:p(),url:p().url()}),Ti=re([gn,Pi]),Ci=x({method:U("elicitation/create"),params:Ti}),Ai=re([ki,Ei,Ci]),Oi=re([Ri,xi,Ii]),Ni=Y(p(),Ai),ji=Y(p(),Oi),bn=vt({inputRequests:Ni.optional(),requestState:p().optional()}),$n={inputResponses:ji.optional(),requestState:p().optional()},Ds=x({_meta:oo,...$n}),qs=pe({progressToken:r.optional()});function Tt(et,zn){return x({method:U(et),params:x({_meta:oo,...zn})})}function Ct(et,zn){return x({method:U(et),params:x({_meta:qs.optional(),...zn}).optional()})}let Ui={name:p(),arguments:Y(p(),ue()).optional(),...$n},Ht={cursor:n.optional()},Ls=Tt("tools/call",Ui),Vs=Tt("tools/list",Ht),Ks=Tt("prompts/list",Ht),Js=Tt("prompts/get",{name:p(),arguments:Y(p(),p()).optional(),...$n}),Fs=Tt("resources/list",Ht),Hs=Tt("resources/templates/list",Ht),Zs=Tt("resources/read",{uri:p(),...$n}),Mi={ref:re([vn,yn]),argument:x({name:p(),value:p()}),context:x({arguments:Y(p(),p()).optional()}).optional()},Ws=Tt("completion/complete",Mi),Bs=Tt("server/discover",{}),lo=x({toolsListChanged:ee().optional(),promptsListChanged:ee().optional(),resourcesListChanged:ee().optional(),resourceSubscriptions:N(p()).optional()}),Di={notifications:lo},Gs=Tt("subscriptions/listen",Di),Xs=so.extend({"io.modelcontextprotocol/subscriptionId":o}),Ys=pe({_meta:Xs,resultType:ao.default("complete")}),jr={"tools/call":Ct("tools/call",Ui),"tools/list":Ct("tools/list",Ht),"prompts/get":Ct("prompts/get",{name:p(),arguments:Y(p(),p()).optional()}),"prompts/list":Ct("prompts/list",Ht),"resources/list":Ct("resources/list",Ht),"resources/templates/list":Ct("resources/templates/list",Ht),"resources/read":Ct("resources/read",{uri:p()}),"completion/complete":Ct("completion/complete",Mi),"server/discover":Ct("server/discover",{}),"subscriptions/listen":Ct("subscriptions/listen",Di)};function kt(et){return pe({_meta:co,...et})}let Qs={"tools/call":kt({content:N(R),structuredContent:ue().optional(),isError:ee().optional()}),"tools/list":kt({ttlMs:F().int().min(0),cacheScope:ve(["public","private"]),tools:N(_n),nextCursor:n.optional()}),"prompts/get":kt({description:p().optional(),messages:N(T)}),"prompts/list":kt({ttlMs:F().int().min(0),cacheScope:ve(["public","private"]),prompts:N(I),nextCursor:n.optional()}),"resources/list":kt({ttlMs:F().int().min(0),cacheScope:ve(["public","private"]),resources:N(Ne),nextCursor:n.optional()}),"resources/templates/list":kt({ttlMs:F().int().min(0),cacheScope:ve(["public","private"]),resourceTemplates:N(be),nextCursor:n.optional()}),"resources/read":kt({ttlMs:F().int().min(0),cacheScope:ve(["public","private"]),contents:N(re([te,_e]))}),"completion/complete":kt({completion:x({values:N(p()).max(100),total:F().int().optional(),hasMore:ee().optional()}).loose()}),"server/discover":kt({ttlMs:F().int().min(0).catch(0),cacheScope:ve(["public","private"]).catch("private"),supportedVersions:N(p()),capabilities:no,instructions:p().optional()}),"subscriptions/listen":kt({})},wn=pe({"io.modelcontextprotocol/subscriptionId":o.optional()}),po=x({method:U("notifications/subscriptions/acknowledged"),params:x({_meta:wn.optional(),notifications:lo})}),mo=x({_meta:wn.optional(),requestId:o,reason:p().optional()}),fo=x({method:U("notifications/cancelled"),params:mo}),np={"notifications/cancelled":fo,"notifications/progress":A,"notifications/message":Z,"notifications/resources/updated":K,"notifications/resources/list_changed":P,"notifications/tools/list_changed":oe,"notifications/prompts/list_changed":O,"notifications/subscriptions/acknowledged":po},Et=et=>x({jsonrpc:U("2.0"),id:re([p(),F().int()]),result:et}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:r,CursorSchema:n,RequestIdSchema:o,RoleSchema:i,LoggingLevelSchema:a,TaskMetadataSchema:c,RelatedTaskMetadataSchema:u,RequestMetaSchema:l,BaseRequestParamsSchema:d,TaskAugmentedRequestParamsSchema:m,NotificationsParamsSchema:v,NotificationSchema:g,IconSchema:h,IconsSchema:f,BaseMetadataSchema:y,ImplementationSchema:S,ClientTasksCapabilitySchema:k,ServerTasksCapabilitySchema:w,ClientCapabilitiesSchema:b,ServerCapabilitiesSchema:E,ProgressSchema:j,ProgressNotificationParamsSchema:V,ProgressNotificationSchema:A,LoggingMessageNotificationParamsSchema:L,LoggingMessageNotificationSchema:Z,ResourceContentsSchema:J,TextResourceContentsSchema:te,BlobResourceContentsSchema:_e,AnnotationsSchema:ke,ResourceSchema:Ne,ResourceTemplateSchema:be,ResourceListChangedNotificationSchema:P,ResourceUpdatedNotificationParamsSchema:M,ResourceUpdatedNotificationSchema:K,PromptArgumentSchema:z,PromptSchema:I,PromptListChangedNotificationSchema:O,TextContentSchema:W,ImageContentSchema:ce,AudioContentSchema:$e,ToolUseContentSchema:B,EmbeddedResourceSchema:Re,ResourceLinkSchema:Fe,ContentBlockSchema:R,PromptMessageSchema:T,ToolAnnotationsSchema:D,ToolListChangedNotificationSchema:oe,ModelHintSchema:ne,ModelPreferencesSchema:ie,ToolChoiceSchema:me,BooleanSchemaSchema:Pe,StringSchemaSchema:Ee,NumberSchemaSchema:Ze,UntitledSingleSelectEnumSchemaSchema:je,TitledSingleSelectEnumSchemaSchema:De,LegacyTitledEnumSchemaSchema:nt,SingleSelectEnumSchemaSchema:Jt,UntitledMultiSelectEnumSchemaSchema:yt,TitledMultiSelectEnumSchemaSchema:ut,MultiSelectEnumSchemaSchema:Ft,EnumSchemaSchema:rr,PrimitiveSchemaDefinitionSchema:hn,ElicitRequestFormParamsSchema:gn,ResourceTemplateReferenceSchema:yn,PromptReferenceSchema:vn,RootSchema:mi,ClientCapabilities2026Schema:fi,ServerCapabilities2026Schema:no,RequestMetaEnvelopeSchema:oo,ToolSchema:_n,ToolResultContentSchema:hi,SamplingMessageContentBlockSchema:io,SamplingMessageSchema:Sn,ResultTypeSchema:ao,ResultMetaSchema:so,ResultSchema:gi,PaginatedResultSchema:Us,CallToolResultSchema:uo,ListToolsResultSchema:yi,ListPromptsResultSchema:vi,GetPromptResultSchema:_i,ListResourcesResultSchema:Si,ListResourceTemplatesResultSchema:bi,ReadResourceResultSchema:$i,CompleteResultSchema:wi,CacheableResultSchema:Ms,DiscoverResultSchema:zi,CreateMessageRequestParamsSchema:Nr,CreateMessageRequestSchema:ki,ListRootsRequestSchema:Ei,CreateMessageResultSchema:Ri,ListRootsResultSchema:xi,ElicitResultSchema:Ii,ElicitRequestURLParamsSchema:Pi,ElicitRequestParamsSchema:Ti,ElicitRequestSchema:Ci,InputRequestSchema:Ai,InputResponseSchema:Oi,InputRequestsSchema:Ni,InputResponsesSchema:ji,InputRequiredResultSchema:bn,InputResponseRequestParamsSchema:Ds,CallToolRequestSchema:Ls,ListToolsRequestSchema:Vs,ListPromptsRequestSchema:Ks,GetPromptRequestSchema:Js,ListResourcesRequestSchema:Fs,ListResourceTemplatesRequestSchema:Hs,ReadResourceRequestSchema:Zs,CompleteRequestSchema:Ws,DiscoverRequestSchema:Bs,SubscriptionFilterSchema:lo,SubscriptionsListenRequestSchema:Gs,SubscriptionsListenResultMetaSchema:Xs,SubscriptionsListenResultSchema:Ys,dispatchRequestSchemas:jr,dispatchResultSchemas:Qs,NotificationMetaSchema:wn,SubscriptionsAcknowledgedNotificationSchema:po,CancelledNotificationParamsSchema:mo,CancelledNotificationSchema:fo,notificationSchemas2026:np,JSONRPCResultResponseSchema:Et(gi),CallToolResultResponseSchema:Et(re([uo,bn])),ListToolsResultResponseSchema:Et(yi),ListPromptsResultResponseSchema:Et(vi),GetPromptResultResponseSchema:Et(re([_i,bn])),ListResourcesResultResponseSchema:Et(Si),ListResourceTemplatesResultResponseSchema:Et(bi),ReadResourceResultResponseSchema:Et(re([$i,bn])),CompleteResultResponseSchema:Et(wi),DiscoverResultResponseSchema:Et(zi)}}function an(){return Gx??=Bx()}function Yx(e){return Xx.includes(e)}function Qx(e){return e[Hh]}function hw(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function gw(e){return e==="public"||e==="private"}function nI(e,t){let r=t.resultType;if(r===void 0)return{...t,resultType:"complete"};if(r==="complete"||rI.includes(e))return t;throw new Me(fe.InternalError,`Handler for ${e} returned resultType '${String(r)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function oI(e,t){let r=Qx(t);if(t.resultType!=="complete"||!Yx(e))return r===void 0?t:uI(t);let n=t,o=hw(n.ttlMs)?n.ttlMs:sI(r),i=gw(n.cacheScope)?n.cacheScope:cI(r),a={...n,ttlMs:o,cacheScope:i};return delete a[Hh],a}function iI(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function aI(e,t){if(t===void 0)return e;let r=e._meta;return r===void 0?{...e,_meta:{[ur]:t}}:!iI(r)||r[ur]!==void 0?e:{...e,_meta:{...r,[ur]:t}}}function sI(e){return e!==void 0&&hw(e.ttlMs)?e.ttlMs:eI}function cI(e){return e!==void 0&&gw(e.cacheScope)?e.cacheScope:tI}function uI(e){let t={...e};return delete t[Hh],t}function Gh(){if(Bl)return Bl;let e=an();return Bl={request:{"elicitation/create":x({method:U("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":x({method:U("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":x({method:U("roots/list"),params:pe({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},Bl}function dI(){Gh()}function vw(e){return lI.includes(e)}function Ih(e){return vw(e)?Gh().request[e]:void 0}function pI(e){return vw(e)?Gh().response[e]:void 0}function Sw(e){return Object.prototype.hasOwnProperty.call(Xh,e)}function bw(e){return Object.prototype.hasOwnProperty.call(_w,e)}function mI(e){return Object.prototype.hasOwnProperty.call(Xh,e)}function fI(e){return Sw(e)?an().dispatchRequestSchemas[e]:void 0}function hI(e){return mI(e)?an().dispatchResultSchemas[e]:void 0}function gI(e){return bw(e)?an().notificationSchemas2026[e]:void 0}function cs(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function as(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let r=e.safeParse(t);return r.success?{ok:!0,value:r.data}:{ok:!1,reason:"invalid",message:String(r.error)}}function _I(e,t){let r=t,n=!1,o=()=>(n||(r={...r},n=!0),r),i=t.tools;e==="tools/list"&&Array.isArray(i)&&i.some(s=>cs(s)&&"execution"in s)&&(o().tools=i.map(s=>{if(!cs(s)||!("execution"in s))return s;let c={...s};return delete c.execution,c}));let a=t.capabilities;if(cs(a)&&"tasks"in a){let s={...a};delete s.tasks,o().capabilities=s}return r}function $w(){if(Gl)return Gl;let e=an();return Gl={"tools/call":e.CallToolResultSchema,"tools/list":e.ListToolsResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"completion/complete":e.CompleteResultSchema,"server/discover":e.DiscoverResultSchema},Gl}function SI(){$w()}function Er(e){return e!==void 0&&Ir(e)?Yh:Fh}function X$(e){return e.revision!==void 0?Er(e.revision).era:e.era==="modern"?Yh.era:Fh.era}function Ph(e){return ww.some(t=>t.hasRequestMethod(e))}function Th(e){return ww.some(t=>t.hasNotificationMethod(e))}function zw(e){return Bt.parse(e)}function xw(e){if(e.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function Iw(e){if(e.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}function tg(e){let t=[],r=new Map,n=(i,a,s)=>{if(i===null||typeof i!="object")return;let c=i;if(Y$ in c){if(!s||a.length===0)return`${Xl(a)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let l=c[Y$];if(typeof l!="string"||l.length===0)return`${Xl(a)}: x-mcp-header MUST be a non-empty string`;if(!wI.test(l))return`${Xl(a)}: x-mcp-header '${l}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let d=typeof c.type=="string"?c.type:void 0;if(d===void 0||!zI.has(d))return`${Xl(a)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${d??""}`;let m=l.toLowerCase(),v=r.get(m);if(v!==void 0)return`x-mcp-header '${l}' is not case-insensitively unique (also declared as '${v}')`;r.set(m,l),t.push({path:a,headerName:l,type:d})}let u=c.properties;if(u!==null&&typeof u=="object")for(let[l,d]of Object.entries(u)){let m=n(d,[...a,l],s);if(m!==void 0)return m}for(let l of kI){let d=c[l];if(d===void 0)continue;let m=Array.isArray(d)?d:d!==null&&typeof d=="object"&&EI.has(l)?Object.values(d):[d];for(let v of m){let g=n(v,[...a,`<${l}>`],!1);if(g!==void 0)return g}}},o=n(e,[],!0);return o===void 0?{valid:!0,declarations:t}:{valid:!1,reason:o}}function Xl(e){return e.length===0?"":e.join(".")}function RI(e){if(typeof e=="string")return e;if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e)?void 0:String(e)}function xI(e){if(e.length===0||e.startsWith(Pw)&&e.endsWith(Tw)||e!==e.trim())return!0;for(let t=0;t=32&&r<=126))return!0}return!1}function II(e){let t=new TextEncoder().encode(e),r="";for(let n of t)r+=String.fromCodePoint(n);return btoa(r)}function rg(e){return xI(e)?`${Pw}${II(e)}${Tw}`:e}function PI(e,t){let r=e;for(let n of t){if(r===null||typeof r!="object")return;r=r[n]}return r}function Cw(e,t){let r={};for(let n of e){let o=PI(t,n.path);if(o==null)continue;let i=RI(o);i!==void 0&&(r[`${$I}${n.headerName}`]=rg(i))}return r}function nd(e,t){return Jc(e,t)}function ss(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}function jh(e){if(e==null)return!1;let t=typeof e;return t!=="object"&&t!=="function"||!("~standard"in e)?!1:typeof e["~standard"]?.validate=="function"}function TI(e,t="input"){let r=e["~standard"],n;if(r.jsonSchema)n=r.jsonSchema[t]({target:Uh});else if(r.vendor==="zod"){if(!("_zod"in e))throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");Q$||(Q$=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),n=fa(e,{target:Uh,io:t})}else throw new Error(`Schema library "${r.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t==="output")return n.type!==void 0?n:Aw(n)?{type:"object",...n}:n;if(n.type!==void 0&&n.type!=="object")throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(n.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...n}}function Aw(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(let t of["oneOf","anyOf","allOf"]){let r=e[t];if(Array.isArray(r)&&r.length>0)return r.every(n=>n!==null&&typeof n=="object"&&(n.type==="object"||Aw(n)))}return!1}function CI(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}async function Ch(e,t){let r=await e["~standard"].validate(t);return r.issues&&r.issues.length>0?{success:!1,error:r.issues.map(n=>CI(n)).join(", ")}:{success:!0,data:r.value}}function AI(e){let t=fa(e,{target:Uh,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}function NI(e){let t=OI.exec(e),r=[void 0,-1,0];return t&&r.push(Number(t[1])),[!1,!0].flatMap(n=>[!1,!0].flatMap(o=>r.map(i=>Lt.datetime({local:n,offset:o,precision:i}))))}function jI(e,t){let r;switch(e){case"email":r=[Af()];break;case"uri":r=[ba()];break;case"date":r=[Lt.date()];break;case"date-time":r=NI(t);break}return new Set(r.map(n=>AI(n)).filter(n=>n!==void 0))}function UI(e,t,r){return r!=="zod"?!0:jI(e,t).has(t)}function ls(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function MI(e){try{return TI(e,"input")}catch(t){let r=t instanceof Error?t.message:String(t);throw new Me(fe.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${r}`)}}function ng(e){return DI.has(e)||e.startsWith("x-")}function VI(e,t,r,n){if(!ls(e))return e;let o=typeof e.type=="string"&&Object.hasOwn(ew,e.type)?ew[e.type]:void 0;if(o===void 0)return e;let i={};for(let[a,s]of Object.entries(e))o.has(a)||ng(a)?i[a]=s:a==="pattern"&&e.type==="string"&&typeof e.format=="string"?LI.has(e.format)?(typeof s!="string"||!UI(e.format,s,r))&&n.push(`${t}.${a}`):i[a]=s:n.push(`${t}.${a}`);return i}function KI(e,t){let r={},n=[];for(let[o,i]of Object.entries(e))o==="properties"&&ls(i)?r[o]=Object.fromEntries(Object.entries(i).map(([a,s])=>[a,VI(s,`properties.${a}`,t,n)])):qI.has(o)?r[o]=i:ng(o)||n.push(o);if(n.length>0)throw new Me(fe.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${n.join(", ")}`);return r}function JI(e,t){if(!ls(e.properties))return t;let r=Object.entries(e.properties).filter(([,n])=>!nd(ts,n).success).map(([n])=>`properties.${n}`);return r.length>0?r.join(", "):t}function Mh(e,t,r=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((n,o)=>Mh(n,t[o],`${r}[${o}]`)):!ls(e)||!ls(t)?[]:Object.entries(e).flatMap(([n,o])=>{let i=r?`${r}.${n}`:n;return Object.prototype.hasOwnProperty.call(t,n)?Mh(o,t[n],i):ng(n)?[]:[i]})}function FI(e){if(!jh(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,r=KI(MI(e.requestedSchema),t),n=nd(qo.shape.requestedSchema,r);if(!n.success)throw new Me(fe.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${JI(r,n.error.message)}`);let o=Mh(r,n.data);if(o.length>0)throw new Me(fe.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);let i=(n.data.required??[]).filter(a=>!Object.prototype.hasOwnProperty.call(n.data.properties,a));if(i.length>0)throw new Me(fe.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${i.join(", ")}`);return{...e,mode:"form",requestedSchema:n.data}}function HI(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,r=typeof e.requestState=="string";if(!t&&!r)throw new TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}function Ow(e){return{"~standard":{version:1,vendor:"modelcontextprotocol",validate:(t,r)=>td(t)?{value:t}:e["~standard"].validate(t,r)}}}function Nw(e){return{autoFulfill:e?.autoFulfill??ZI,maxRounds:e?.maxRounds??WI}}function GI(e,t,r){let n=t!==void 0&&Object.keys(t).length>0;return!n&&r===void 0?e:{...e,...n&&{inputResponses:t},...r!==void 0&&{requestState:r}}}function XI(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function YI(e,t){return new Promise((r,n)=>{if(t?.aborted){n(t.reason instanceof ae?t.reason:new ae(se.RequestTimeout,String(t.reason)));return}let o=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e),i=()=>{clearTimeout(o),n(t?.reason instanceof ae?t.reason:new ae(se.RequestTimeout,String(t?.reason)))};t?.addEventListener("abort",i,{once:!0})})}function QI(e){let t=new AbortController,r=()=>t.abort(e?.reason);return e?.addEventListener("abort",r,{once:!0}),e?.aborted&&t.abort(e.reason),{signal:t.signal,abort:n=>t.abort(n),dispose:()=>e?.removeEventListener("abort",r)}}async function eP(e){let{config:t,method:r,originalParams:n,requestOptions:o,hooks:i,signal:a}=e,s=e.flowStartedAt??Date.now(),c=e.firstPayload,u=0;for(;;){if(u+=1,u>t.maxRounds)throw new ae(se.InputRequiredRoundsExceeded,XI(r,t.maxRounds),{rounds:t.maxRounds,lastResult:{inputRequests:c.inputRequests,...c.requestState!==void 0&&{requestState:c.requestState}}});o.onprogress?.({progress:u,message:`Fulfilling input required by '${r}' (round ${u})`});let l=Object.entries(c.inputRequests??{}),d;if(l.length>0){let g=QI(a);try{let h=await Promise.all(l.map(async([f,y])=>{try{return[f,await i.dispatchInputRequest(f,y,g.signal)]}catch(S){throw g.abort(S),S}}));d=Object.fromEntries(h)}finally{g.dispose()}}else await YI(BI,a);let m={...o.timeout!==void 0&&{timeout:o.timeout}};if(o.maxTotalTimeout!==void 0){let g=Date.now()-s,h=o.maxTotalTimeout-g;if(h<=0)throw new ae(se.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:o.maxTotalTimeout,totalElapsed:g});m.maxTotalTimeout=h}let v=await i.retry(GI(n,d,c.requestState),m);if(td(v)){c={inputRequests:v.inputRequests??{},...v.requestState!==void 0&&{requestState:v.requestState}};continue}return v}}function Mw(e,t){let r=e.slice(0,-6);jw[r]=t,Uw[r]=n=>t.safeParse(n).success}function nP(e){switch(e){case"initialize":case"notifications/initialized":return Er(void 0);case"server/discover":return Er(ed);default:return}}function tw(e,t){let r=e.params;if(!us(r))return{message:e,lifted:{}};let n=r._meta,o=us(n)?oP.filter(c=>c in n):[],i=t==="request"?iP.filter(c=>c in r):[];if(o.length===0&&i.length===0)return{message:e,lifted:{}};let a={},s={...r};if(o.length>0&&us(n)){let c={},u={...n};for(let l of o)c[l]=n[l],delete u[l];a.envelope=c,Object.keys(u).length>0?s._meta=u:delete s._meta}for(let c of i)c==="inputResponses"&&(a.inputResponses=s[c]),c==="requestState"&&(a.requestState=s[c]),delete s[c];return{message:{...e,params:s},lifted:a}}function rw(e,t){let r=e.validateResult(t,void 0);if(!(!r.ok&&r.reason==="not-in-era"))return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(n){let o=e.validateResult(t,n);return o.ok?{value:o.value}:{issues:[{message:o.reason==="invalid"?o.message:`not-in-era: ${t}`}]}}}}}function ig(e){return()=>e}function us(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function sg(e,t){let r={...e};for(let n in t){let o=n,i=t[o];if(i===void 0)continue;let a=r[o];r[o]=us(a)&&us(i)?{...a,...i}:i}return r}function Yl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function cP(e){let t={},r=[];if(!Yl(e))return{accepted:t,droppedKeys:r};for(let[n,o]of Object.entries(e)){if(!Yl(o)||"method"in o||"result"in o){r.push(n);continue}t[n]=o}return{accepted:t,droppedKeys:r}}function nw(e){throw new ae(se.SendFailed,`ctx.mcpReq.${e} is not available while fulfilling an embedded input request: the request is fulfilled locally and has no related peer request`)}function uP(e,t,r,n,o){return{sessionId:o,mcpReq:{id:e,method:t,_meta:r?._meta,requestState:ig(void 0),signal:n,send:(()=>nw("send")),notify:()=>nw("notify")}}}async function lP(e,t,r,n,o){if(!Yl(n)||typeof n.method!="string")throw new ae(se.InvalidResult,`Invalid input request '${r}': each inputRequests entry must be an embedded request object with a method`,{key:r});let i=n.method;if(!t.hasInputRequestMethod(i))throw new ae(se.InvalidResult,`Invalid input request '${r}': '${i}' is not an embedded request the ${t.era} revision defines (expected elicitation/create, sampling/createMessage, or roots/list)`,{key:r,method:i});let a=e.getRequestHandler(i);if(a===void 0)throw new ae(se.CapabilityNotSupported,`Cannot fulfil input request '${r}': no handler is registered for '${i}' on this client. Declare the corresponding capability and register a handler, or handle input_required results manually.`,{key:r,method:i});let s=Yl(n.params)?n.params:void 0;return await a({jsonrpc:"2.0",id:r,method:i,...s!==void 0&&{params:s}},e.buildContext(uP(r,i,s,o,e.sessionId)))}function dP(e,t){return{...e?.signal!==void 0&&{signal:e.signal},...e?.onprogress!==void 0&&{onprogress:e.onprogress},...e?.resetTimeoutOnProgress!==void 0&&{resetTimeoutOnProgress:e.resetTimeoutOnProgress},...e?.headers!==void 0&&{headers:e.headers},...t.timeout!==void 0&&{timeout:t.timeout},...t.maxTotalTimeout!==void 0&&{maxTotalTimeout:t.maxTotalTimeout},allowInputRequired:!0}}function qw(e,t,r,n){let{codec:o,request:i,options:a,flowStartedAt:s}=n,c={inputRequests:r.inputRequests,...r.requestState!==void 0&&{requestState:r.requestState}},u={dispatchInputRequest:(l,d,m)=>lP(e,o,l,d,m),retry:(l,d)=>n.retry(l,dP(a,d))};return eP({config:t,method:i.method,originalParams:i.params,firstPayload:c,flowStartedAt:s,signal:a?.signal,requestOptions:{...a?.timeout!==void 0&&{timeout:a.timeout},...a?.maxTotalTimeout!==void 0&&{maxTotalTimeout:a.maxTotalTimeout},...a?.onprogress!==void 0&&{onprogress:a.onprogress}},hooks:u})}function pP(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState}}}function cg(e){if(e)try{return fP.parse(e).type}catch{let t=(e.split(";",1)[0]??"").trim().toLowerCase();return t===""||e.slice(t.length).includes(",")?void 0:t}}function Lw(e){return e==="application/json"?!0:cg(e)==="application/json"}function Vw(e){return e.title!==void 0&&e.title!==""?e.title:"annotations"in e&&e.annotations?.title?e.annotations.title:e.name}function lg(e){return Bt.parse(JSON.parse(e))}function Jw(e){return JSON.stringify(e)+` +`}function ds(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function od(e=fetch,t){return t?async(r,n)=>e(r,{...t,...n,headers:n?.headers?{...ds(t.headers),...ds(n.headers)}:t.headers}):e}function Zw(){Jh(),an(),Jx(),dI(),SI()}function Ww(e,t){let r=t.getValidator(e);return{"~standard":{version:1,vendor:"mcp",jsonSchema:{input:()=>e,output:()=>e},validate:n=>{let o=r(n);return o.valid?{value:o.data}:{issues:[{message:o.errorMessage}]}}}}}var Oh,Rr,xr,se,ae,lr,sw,Vh,uw,Dx,qx,Lx,dw,pw,Kx,Zl,nD,oD,B$,Fh,Gx,Xx,Hh,fe,Me,Zh,Wh,ms,Bh,eI,tI,rI,lI,Bl,Xh,_w,iD,aD,yI,vI,Yh,Gl,ed,ww,bI,sn,Qh,qn,Vn,kw,Ew,td,Rw,rd,eg,$I,Y$,wI,zI,kI,EI,Pw,Tw,Vo,sD,cD,Q$,Uh,OI,DI,qI,ew,LI,uD,ZI,WI,BI,tP,rP,jw,Uw,Dw,og,fs,oP,iP,aP,sP,ag,mP,fP,ug,Kw,ow,Ah,iw,hP,Fw,Hw,Bw=q(()=>{cp();W$();ih();Oh=Symbol.for("mcp.sdk.errorBrands");Rr=(function(e){return e.InvalidRequest="invalid_request",e.InvalidClient="invalid_client",e.InvalidGrant="invalid_grant",e.UnauthorizedClient="unauthorized_client",e.UnsupportedGrantType="unsupported_grant_type",e.InvalidScope="invalid_scope",e.AccessDenied="access_denied",e.ServerError="server_error",e.TemporarilyUnavailable="temporarily_unavailable",e.UnsupportedResponseType="unsupported_response_type",e.UnsupportedTokenType="unsupported_token_type",e.InvalidToken="invalid_token",e.MethodNotAllowed="method_not_allowed",e.TooManyRequests="too_many_requests",e.InvalidClientMetadata="invalid_client_metadata",e.InvalidRedirectUri="invalid_redirect_uri",e.InsufficientScope="insufficient_scope",e.InvalidTarget="invalid_target",e})({}),xr=class aw extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return Ut(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Ut(this,t)}constructor(t,r,n){super(r),this.code=t,this.errorUri=n,this.name="OAuthError",Ln(this,new.target)}toResponseObject(){let t={error:this.code,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}static fromResponse(t){return new aw(t.error,t.error_description??t.error,t.error_uri)}},se=(function(e){return e.NotConnected="NOT_CONNECTED",e.AlreadyConnected="ALREADY_CONNECTED",e.NotInitialized="NOT_INITIALIZED",e.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",e.RequestTimeout="REQUEST_TIMEOUT",e.ConnectionClosed="CONNECTION_CLOSED",e.SendFailed="SEND_FAILED",e.InvalidResult="INVALID_RESULT",e.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",e.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",e.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",e.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",e.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",e.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",e.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",e.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",e.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",e.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",e.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",e})({}),ae=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return Ut(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Ut(this,e)}constructor(e,t,r){super(t),this.code=e,this.data=r,this.name="SdkError",Ln(this,new.target)}},lr=class extends ae{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(e,t,r){super(e,t,r),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};sw="2026-07-28",Vh=[sw];uw=["task","inputRequests","requestState"];qx=new Set(["const","enum","default","examples"]),Lx=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas"]);dw={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},pw={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},Kx={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null};nD=Object.keys(dw),oD=Object.keys(pw);B$={ok:!1,reason:"not-in-era"};Fh={era:"2025-11-25",hasRequestMethod:mw,hasNotificationMethod:fw,validateRequest:(e,t)=>Wl(Zx(e),t),validateResult:(e,t)=>Wl(Hx(e),t),validateNotification:(e,t)=>Wl(Wx(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>B$,validateInputResponse:()=>B$,samplingResultVariant:((e,t)=>{let r=Jh();return Wl(e?r.CreateMessageResultWithToolsSchema:r.CreateMessageResultSchema,t)}),outboundEnvelope:e=>{},validateEnvelopeMeta:e=>[],projectCallToolResult(e,t){let r=cw(e),n=r.structuredContent;if(n===void 0)return r;let o=typeof n!="object"||n===null||Array.isArray(n),i=t!==void 0&&lw(t);return!o&&!i?r:{...r,structuredContent:{result:n}}},decodeResult(e,t){if(Nh(t)&&"resultType"in t){let r={...t};return delete r.resultType,{kind:"complete",result:r}}return{kind:"complete",result:t}},encodeResult(e,t){if(e!=="tools/list")return t;let r=t.tools;return!Array.isArray(r)||!r.some(n=>G$(n))?t:{...t,tools:r.map(n=>G$(n)?{...n,outputSchema:Vx(n.outputSchema)}:n)}},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope:e=>{}};Xx=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];Hh=Symbol("modelcontextprotocol.resultCacheHintFallback");fe=(function(e){return e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.ResourceNotFound=-32002]="ResourceNotFound",e[e.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",e[e.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired",e})({}),Me=class yw extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return Ut(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Ut(this,t)}constructor(t,r,n){super(r),this.code=t,this.data=n,this.name="ProtocolError",Ln(this,new.target)}static fromError(t,r,n){if(t===fe.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Wh(o.elicitations,r)}if(t===fe.UnsupportedProtocolVersion&&n){let o=n;if(Array.isArray(o.supported)&&typeof o.requested=="string")return new ms({supported:o.supported,requested:o.requested},r)}if(t===fe.InvalidParams||t===fe.ResourceNotFound){let o=n;if(typeof o?.uri=="string"&&(t===fe.ResourceNotFound||Object.keys(o).length===1))return new Zh(o.uri,r)}if(t===fe.MissingRequiredClientCapability&&n){let o=n;if(o.requiredCapabilities!==null&&typeof o.requiredCapabilities=="object"&&!Array.isArray(o.requiredCapabilities))return new Bh({requiredCapabilities:o.requiredCapabilities},r)}return new yw(t,r,n)}},Zh=class extends Me{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(fe.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},Wh=class extends Me{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(fe.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},ms=class extends Me{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(fe.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},Bh=class extends Me{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(", ")}`){super(fe.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},eI=0,tI="private",rI=["tools/call","prompts/get","resources/read"];lI=["elicitation/create","sampling/createMessage","roots/list"];Xh={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},_w={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};iD=Object.keys(Xh),aD=Object.keys(_w);yI={ok:!1,reason:"not-in-era"},vI=[cr,Gr];Yh={era:"2026-07-28",hasRequestMethod:Sw,hasNotificationMethod:bw,hasInputRequestMethod:e=>Ih(e)!==void 0,validateRequest:(e,t)=>as(fI(e),t),validateResult:(e,t)=>as(hI(e),t),validateNotification:(e,t)=>as(gI(e),t),validateInputRequest:(e,t)=>as(Ih(e),t),validateInputResponse:(e,t)=>as(pI(e),t),samplingResultVariant:()=>yI,outboundEnvelope(e){return{[cr]:e.protocolVersion,[On]:e.clientInfo,[Gr]:e.clientCapabilities,...e.logLevel!==void 0&&{[Nn]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let n of vI)n in e||t.push({key:n,problem:"missing"});let r=an().RequestMetaEnvelopeSchema.safeParse(e);if(!r.success)for(let n of r.error.issues){let o=n.path.map(String),i=o.length>0?o.join("."):"_meta";o.length===1&&t.some(a=>a.key===i&&a.problem==="missing")||t.push({key:i,problem:n.message})}return t},projectCallToolResult:e=>cw(e),inputRequestSchema:Ih,decodeResult(e,t){if(!cs(t))return{kind:"invalid",error:new ae(se.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let r=t.resultType;if(r===void 0)return{kind:"invalid",error:new ae(se.InvalidResult,`Invalid result for ${e}: missing required resultType \u2014 servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:e,violation:"missing-resultType"})};if(typeof r!="string")return{kind:"invalid",error:new ae(se.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:r})};if(r==="input_required"){let a=t.inputRequests,s=cs(a)?a:{},c=t.requestState;return Object.keys(s).length===0&&typeof c!="string"?{kind:"invalid",error:new ae(se.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:"input-required-missing-both"})}:{kind:"input_required",inputRequests:s,...typeof c=="string"&&{requestState:c}}}if(r!=="complete")return{kind:"invalid",error:new ae(se.UnsupportedResultType,`Unsupported result type '${r}' for ${e}`,{resultType:r,method:e})};let n=$w(),o=Object.hasOwn(n,e)?n[e]:void 0;if(o!==void 0){let a=o.safeParse(t);if(!a.success)return{kind:"invalid",error:new ae(se.InvalidResult,`Invalid result for ${e}: ${a.error}`,{method:e})}}let i={...t};return delete i.resultType,{kind:"complete",result:i}},encodeResult(e,t,r){return aI(oI(e,nI(e,_I(e,t))),r)},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope(e){if(e.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let t=an().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(r=>r.message).join("; ")}`}};ed="2026-07-28";ww=[Fh,Yh],bI=Zy({AnnotationsSchema:()=>kr,AudioContentSchema:()=>No,BaseMetadataSchema:()=>zr,BaseRequestParamsSchema:()=>pt,BlobResourceContentsSchema:()=>Ka,BooleanSchemaSchema:()=>Ba,CallToolRequestParamsSchema:()=>sl,CallToolRequestSchema:()=>cl,CallToolResultSchema:()=>Uo,CancelTaskRequestSchema:()=>_h,CancelTaskResultSchema:()=>Sh,CancelledNotificationParamsSchema:()=>mu,CancelledNotificationSchema:()=>Na,ClientCapabilitiesSchema:()=>yu,ClientNotificationSchema:()=>$h,ClientRequestSchema:()=>bh,ClientResultSchema:()=>wh,ClientTasksCapabilitySchema:()=>hu,CompatibilityCallToolResultSchema:()=>uh,CompleteRequestParamsSchema:()=>Nl,CompleteRequestSchema:()=>jl,CompleteResultSchema:()=>Ul,ContentBlockSchema:()=>jo,CreateMessageRequestParamsSchema:()=>Sl,CreateMessageRequestSchema:()=>bl,CreateMessageResultSchema:()=>$l,CreateMessageResultWithToolsSchema:()=>wl,CreateTaskResultSchema:()=>dh,CursorSchema:()=>Ia,DiscoverRequestSchema:()=>Su,DiscoverResultSchema:()=>jn,ElicitRequestFormParamsSchema:()=>qo,ElicitRequestParamsSchema:()=>xl,ElicitRequestSchema:()=>Il,ElicitRequestURLParamsSchema:()=>Rl,ElicitResultSchema:()=>Cl,ElicitationCompleteNotificationParamsSchema:()=>Pl,ElicitationCompleteNotificationSchema:()=>Tl,EmbeddedResourceSchema:()=>Yu,EmptyResultSchema:()=>Oa,EnumSchemaSchema:()=>El,GetPromptRequestParamsSchema:()=>Bu,GetPromptRequestSchema:()=>Gu,GetPromptResultSchema:()=>tl,GetTaskPayloadRequestSchema:()=>hh,GetTaskPayloadResultSchema:()=>gh,GetTaskRequestSchema:()=>mh,GetTaskResultSchema:()=>fh,IconSchema:()=>fu,IconsSchema:()=>en,ImageContentSchema:()=>Oo,ImplementationSchema:()=>To,InitializeRequestParamsSchema:()=>vu,InitializeRequestSchema:()=>ja,InitializeResultSchema:()=>_u,InitializedNotificationSchema:()=>Ma,JSONArraySchema:()=>sh,JSONObjectSchema:()=>Ge,JSONRPCErrorResponseSchema:()=>Po,JSONRPCMessageSchema:()=>Bt,JSONRPCNotificationSchema:()=>Aa,JSONRPCRequestSchema:()=>Ca,JSONRPCResponseSchema:()=>pu,JSONRPCResultResponseSchema:()=>Io,JSONValueSchema:()=>Wr,LegacyTitledEnumSchemaSchema:()=>Ya,ListChangedOptionsBaseSchema:()=>Za,ListPromptsRequestSchema:()=>Zu,ListPromptsResultSchema:()=>Wu,ListResourceTemplatesRequestSchema:()=>Ru,ListResourceTemplatesResultSchema:()=>xu,ListResourcesRequestSchema:()=>ku,ListResourcesResultSchema:()=>Eu,ListRootsRequestSchema:()=>Dl,ListRootsResultSchema:()=>ql,ListTasksRequestSchema:()=>yh,ListTasksResultSchema:()=>vh,ListToolsRequestSchema:()=>il,ListToolsResultSchema:()=>al,LoggingLevelSchema:()=>Wa,LoggingMessageNotificationParamsSchema:()=>pl,LoggingMessageNotificationSchema:()=>ml,ModelHintSchema:()=>fl,ModelPreferencesSchema:()=>hl,MultiSelectEnumSchemaSchema:()=>kl,NotificationSchema:()=>bt,NotificationsParamsSchema:()=>St,NumberSchemaSchema:()=>Do,PaginatedRequestParamsSchema:()=>wu,PaginatedRequestSchema:()=>tn,PaginatedResultSchema:()=>rn,PingRequestSchema:()=>Da,PrimitiveSchemaDefinitionSchema:()=>ts,ProgressNotificationParamsSchema:()=>$u,ProgressNotificationSchema:()=>qa,ProgressSchema:()=>bu,ProgressTokenSchema:()=>xa,PromptArgumentSchema:()=>Fu,PromptListChangedNotificationSchema:()=>rl,PromptMessageSchema:()=>el,PromptReferenceSchema:()=>Ol,PromptSchema:()=>Hu,ReadResourceRequestParamsSchema:()=>Iu,ReadResourceRequestSchema:()=>Pu,ReadResourceResultSchema:()=>Tu,RelatedTaskMetadataSchema:()=>du,RequestIdSchema:()=>Qr,RequestMetaSchema:()=>Pa,RequestSchema:()=>Xe,ResourceContentsSchema:()=>La,ResourceLinkSchema:()=>Qu,ResourceListChangedNotificationSchema:()=>Cu,ResourceRequestParamsSchema:()=>Co,ResourceSchema:()=>Ja,ResourceTemplateReferenceSchema:()=>Al,ResourceTemplateSchema:()=>zu,ResourceUpdatedNotificationParamsSchema:()=>Ku,ResourceUpdatedNotificationSchema:()=>Ju,ResultMetaObjectSchema:()=>Ta,ResultSchema:()=>Ye,RoleSchema:()=>nn,RootSchema:()=>Ml,RootsListChangedNotificationSchema:()=>Ll,SamplingContentSchema:()=>vl,SamplingMessageContentBlockSchema:()=>An,SamplingMessageSchema:()=>_l,ServerCapabilitiesSchema:()=>Ua,ServerNotificationSchema:()=>kh,ServerRequestSchema:()=>zh,ServerResultSchema:()=>Eh,ServerTasksCapabilitySchema:()=>gu,SetLevelRequestParamsSchema:()=>ll,SetLevelRequestSchema:()=>dl,SingleSelectEnumSchemaSchema:()=>zl,StringSchemaSchema:()=>Mo,SubscribeRequestParamsSchema:()=>Au,SubscribeRequestSchema:()=>Ou,SubscriptionFilterSchema:()=>Fa,SubscriptionsAcknowledgedNotificationParamsSchema:()=>Du,SubscriptionsAcknowledgedNotificationSchema:()=>qu,SubscriptionsListenRequestParamsSchema:()=>Uu,SubscriptionsListenRequestSchema:()=>Mu,SubscriptionsListenResultMetaSchema:()=>Lu,SubscriptionsListenResultSchema:()=>Vu,TaskAugmentedRequestParamsSchema:()=>Yr,TaskCreationParamsSchema:()=>lh,TaskMetadataSchema:()=>lu,TaskSchema:()=>on,TaskStatusNotificationParamsSchema:()=>Kl,TaskStatusNotificationSchema:()=>ph,TaskStatusSchema:()=>Vl,TextContentSchema:()=>Ao,TextResourceContentsSchema:()=>Va,TitledMultiSelectEnumSchemaSchema:()=>es,TitledSingleSelectEnumSchemaSchema:()=>Xa,ToolAnnotationsSchema:()=>nl,ToolChoiceSchema:()=>gl,ToolExecutionSchema:()=>ol,ToolListChangedNotificationSchema:()=>ul,ToolResultContentSchema:()=>yl,ToolSchema:()=>Ha,ToolUseContentSchema:()=>Xu,UnsubscribeRequestParamsSchema:()=>Nu,UnsubscribeRequestSchema:()=>ju,UntitledMultiSelectEnumSchemaSchema:()=>Qa,UntitledSingleSelectEnumSchemaSchema:()=>Ga});sn=e=>Ca.safeParse(e).success,Qh=e=>Aa.safeParse(e).success,qn=e=>Io.safeParse(e).success,Vn=e=>Po.safeParse(e).success,kw=e=>pu.safeParse(e).success,Ew=e=>typeof e!="object"||e===null||e.content===void 0?!1:Uo.safeParse(e).success,td=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.resultType==="input_required",Rw=e=>Yr.safeParse(e).success,rd=e=>ja.safeParse(e).success,eg=e=>Ma.safeParse(e).success;$I="Mcp-Param-",Y$="x-mcp-header",wI=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,zI=new Set(["string","integer","boolean","number"]);kI=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],EI=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);Pw="=?base64?",Tw="?=";Vo=-32020,sD=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32e3],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[fe.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[Vo,fe.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[fe.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope \u2014 and a missing envelope on a request whose protocol-version header names a modern revision \u2014 is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[fe.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision\u2019s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[fe.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[Vo],conformance:["http-header-validation"],rationale:"SEP-2243 standard `Mcp-Method` / `Mcp-Name` headers \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[fe.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced \u2014 pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[Vo],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool\u2019s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],cD={[fe.ParseError]:400,[fe.InvalidRequest]:400,[fe.MethodNotFound]:404,[fe.UnsupportedProtocolVersion]:400,[fe.MissingRequiredClientCapability]:400,[Vo]:400};Q$=!1,Uh="draft-2020-12";OI=/\\\.\\d\{(\d+)\}/;DI=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);qI=new Set(["$schema",...Object.keys(qo.shape.requestedSchema.shape)]),ew={string:ss([Mo,Ga,Xa,Ya]),number:ss([Do]),integer:ss([Do]),boolean:ss([Ba]),array:ss([Qa,es])},LI=new Set(Mo.shape.format.unwrap().options);uD=Object.assign(HI,{elicit(e){try{return{method:"elicitation/create",params:FI(e)}}catch(t){throw t instanceof Me?new TypeError(t.message,{cause:t}):t}},elicitUrl(e){return{method:"elicitation/create",params:{...e,mode:"url"}}},createMessage(e){return{method:"sampling/createMessage",params:e}},listRoots(){return{method:"roots/list"}}});ZI=!0,WI=10,BI=250;tP=["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"],rP={IdJagTokenExchangeResponseSchema:os,OAuthClientInformationFullSchema:is,OAuthClientInformationSchema:Hl,OAuthClientMetadataSchema:Fl,OAuthClientRegistrationErrorSchema:Rh,OAuthErrorResponseSchema:Mn,OAuthMetadataSchema:Un,OAuthProtectedResourceMetadataSchema:rs,OAuthTokenRevocationRequestSchema:xh,OAuthTokensSchema:Lo,OpenIdProviderDiscoveryMetadataSchema:ns,OpenIdProviderMetadataSchema:Jl},jw={},Uw={};for(let e of tP)Mw(e,bI[e]);for(let[e,t]of Object.entries(rP))Mw(e,t);Dw=Object.freeze(jw),og=Object.freeze(Uw);fs=6e4,oP=[cr,On,Gr,Nn],iP=["inputResponses","requestState"];aP=ig(void 0),ag=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{sP=(e,t)=>{e._negotiatedProtocolVersion=t}}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??Ea,this.setNotificationHandler("notifications/cancelled",t=>{this._oncancel(t)}),this.setNotificationHandler("notifications/progress",t=>{this._onprogress(t)}),this.setRequestHandler("ping",t=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let r=e.params??{};return{...e,params:{...r,_meta:{...t,...r._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new ae(se.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,n,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new ae(se.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let r=this.transport?.onerror;this._transport.onerror=o=>{r?.(o),this._onerror(o)};let n=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{n?.(o,i),qn(o)||Vn(o)?this._onresponse(o):sn(o)?this._onrequest(o,i):Qh(o)?this._onnotification(o,i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let r=new ae(se.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let n of e.values())n(r);for(let n of t.values())n.abort(r)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:r}=tw(e,"notification"),n=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let a=X$(t.classification);if(a!==n.era){this._onerror(new Error(`Era mismatch on inbound notification '${r.method}': classified as ${a} but this instance serves ${n.era}`));return}}if(Th(r.method)&&!n.hasNotificationMethod(r.method))return;let o=this._notificationHandlers.get(r.method),i=this.fallbackNotificationHandler;o===void 0&&i===void 0||Promise.resolve().then(()=>o===void 0?i(r):o(r,n)).catch(a=>this._onerror(new Error(`Uncaught error in notification handler: ${a}`)))}_onrequest(e,t){let{message:r,lifted:n}=tw(e,"request"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop"){this._onerror(new Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let i=this._transport,a=(h,f,y)=>{let S={jsonrpc:"2.0",id:r.id,error:{code:h,message:f,...y!==void 0&&{data:y}}};i?.send(S).catch(_=>this._onerror(new Error(`Failed to send an error response: ${_}`)))};if(t?.classification!==void 0){let h=X$(t.classification);if(h!==o.era){this._onerror(new Error(`Era mismatch on inbound request '${r.method}': classified as ${h} but this instance serves ${o.era}`));let f=t.classification.revision??h;a(fe.UnsupportedProtocolVersion,`Unsupported protocol version: ${f}`,{supported:this._supportedProtocolVersions,requested:f});return}}if(Ph(r.method)&&!o.hasRequestMethod(r.method)){a(fe.MethodNotFound,"Method not found");return}let s=this._requestHandlers.get(r.method)??this.fallbackRequestHandler;if(s===void 0){a(fe.MethodNotFound,"Method not found");return}let c=o.checkInboundEnvelope(n);if(c!==void 0){a(fe.InvalidParams,c);return}let u=(h,f)=>this._notificationViaCodec(this._resolveOutboundCodec(h.method),h,{...f,relatedRequestId:r.id}),l=(h,f,y)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(h.method),h,f,{...y,relatedRequestId:r.id}),d=new AbortController;this._requestHandlerAbortControllers.set(r.id,d);let m=n.inputResponses===void 0?void 0:cP(n.inputResponses),v={sessionId:i?.sessionId,mcpReq:{id:r.id,method:r.method,_meta:r.params?._meta,...n.envelope!==void 0&&{envelope:n.envelope},...m!==void 0&&{inputResponses:m.accepted},...m!==void 0&&m.droppedKeys.length>0&&{droppedInputResponseKeys:m.droppedKeys},requestState:n.requestState===void 0?aP:ig(n.requestState),signal:d.signal,send:((h,f,y)=>{let S=this._resolveOutboundCodec(h.method);if(this._assertOutboundRequestInEra(S,h.method),jh(f))return l(h,f,y);let _=rw(S,h.method);if(_===void 0)throw new TypeError(`'${h.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return l(h,_,f)}),notify:u},http:t?.authInfo?{authInfo:t.authInfo}:void 0},g=this.buildContext(v,t);Promise.resolve().then(()=>s(r,g)).then(async h=>{if(d.signal.aborted)return;let f;try{f=o.encodeResult(r.method,h,this._outboundServerInfo())}catch(S){this._onerror(new Error(`Failed to encode result for ${r.method}: ${S}`)),a(fe.InternalError,"Internal error");return}let y={result:f,jsonrpc:"2.0",id:r.id};await i?.send(y)},async h=>{if(d.signal.aborted)return;let f=Number.isSafeInteger(h.code)?h.code:fe.InternalError,y={jsonrpc:"2.0",id:r.id,error:{code:o.encodeErrorCode(f),message:h.message??"Internal error",...h.data!==void 0&&{data:h.data}}};await i?.send(y)}).catch(h=>this._onerror(new Error(`Failed to send response: ${h}`))).finally(()=>{this._requestHandlerAbortControllers.get(r.id)===d&&this._requestHandlerAbortControllers.delete(r.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,n=Number(t),o=this._progressHandlers.get(n);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(n),a=this._timeoutInfo.get(n);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(s){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),i(s);return}o(r)}_onresponse(e){let t=Number(e.id),r=this._responseHandlers.get(t);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),qn(e)?r(e):r(Me.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,r){let n=this._resolveOutboundCodec(e.method);if(this._assertOutboundRequestInEra(n,e.method),jh(t))return this._requestWithSchemaViaCodec(n,e,t,r);let o=rw(n,e.method);if(o===void 0)throw new TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(n,e,o,t)}_negotiatedWireCodec(){return Er(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=nP(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(Ph(t)&&!e.hasRequestMethod(t))throw new ae(se.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,r){let n=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(n,e.method),this._requestWithSchemaViaCodec(n,e,t,r)}_requestWithSchemaViaCodec(e,t,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a,headers:s}=n??{},c=Date.now(),u,l;return new Promise((d,m)=>{let v=w=>{m(w)};if(!this._transport){v(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(w){v(w);return}if(n?.signal?.aborted){let w=n.signal.reason;throw w instanceof ae?w:new ae(se.RequestTimeout,String(w))}let g=e.era===ed&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,h=this._requestMessageId++;l=h;let f={...t,jsonrpc:"2.0",id:h};n?.onprogress&&(this._progressHandlers.set(h,n.onprogress),f.params={...t.params,_meta:{...t.params?._meta,progressToken:h}});let y=this._envelopeOutbound(f),S=!1,_=w=>{S||(this._progressHandlers.delete(h),g===void 0?this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:h,reason:String(w)}}),{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a}).catch(b=>this._onerror(new Error(`Failed to send cancellation: ${b}`))):g.abort(),m(w instanceof ae?w:new ae(se.RequestTimeout,String(w))))};this._responseHandlers.set(h,w=>{if(n?.signal?.aborted)return;if(S=!0,w instanceof Error)return m(w);let b;try{b=e.decodeResult(t.method,w.result)}catch(j){return m(j instanceof Error?j:new Error(String(j)))}if(b.kind==="invalid")return m(b.error);if(b.kind==="input_required"){if(n?.allowInputRequired===!0)return d(pP(b));let j={codec:e,request:t,resultSchema:r,options:n,flowStartedAt:c,retry:(V,A)=>this._requestWithSchemaViaCodec(e,V===void 0?{method:t.method}:{method:t.method,params:V},r,A)};return d(this._resolveNonCompleteResult(b,j))}let E=b.result;Ch(r,E).then(j=>{j.success?d(j.data):m(new ae(se.InvalidResult,`Invalid result for ${t.method}: ${j.error}`))},m)}),u=()=>_(n?.signal?.reason),n?.signal?.addEventListener("abort",u,{once:!0});let $=n?.timeout??fs,k=()=>_(new ae(se.RequestTimeout,"Request timed out",{timeout:$}));this._setupTimeout(h,$,n?.maxTotalTimeout,k,n?.resetTimeoutOnProgress??!1),this._transport.send(y,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a,headers:s,requestSignal:g?.signal}).catch(w=>{this._progressHandlers.delete(h),m(w)})}).finally(()=>{u&&n?.signal?.removeEventListener("abort",u),l!==void 0&&(this._responseHandlers.delete(l),this._cleanupTimeout(l))})}async notification(e,t){return this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,r){if(!this._transport)throw new ae(se.NotConnected,"Not connected");if(Th(t.method)&&!e.hasNotificationMethod(t.method))throw new ae(se.MethodNotSupportedByProtocolVersion,`Notification '${t.method}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t.method,era:e.era});this.assertNotificationCapability(t.method);let n=this._envelopeOutbound({jsonrpc:"2.0",...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(t.method),this._transport&&this._transport?.send(n,r).catch(o=>this._onerror(o))});return}await this._transport.send(n,r)}setRequestHandler(e,t,r){this.assertRequestHandlerCapability(e);let n;if(typeof t=="function"){if(!Ph(e))throw new TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);n=(o,i)=>{let a=this._negotiatedWireCodec(),s=a.validateRequest(e,o);if(!s.ok&&s.reason==="not-in-era"&&(s=a.validateInputRequest(e,o)),!s.ok)throw s.reason==="not-in-era"?new Me(fe.InternalError,`No wire schema for ${e} in the resolved era`):new Error(s.message);return Promise.resolve(t(s.value,i))}}else if(r)n=async(o,i)=>{let a=await Ch(t.params,{...o.params});if(!a.success)throw new Me(fe.InvalidParams,`Invalid params for ${e}: ${a.error}`);return r(a.data,i)};else throw new TypeError("setRequestHandler: handler is required");this._requestHandlers.set(e,this._wrapHandler(e,n))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,r){if(typeof t=="function"){if(!Th(e))throw new TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(n,o)=>{let i=o.validateNotification(e,n);if(!i.ok)throw i.reason==="not-in-era"?new Me(fe.InternalError,`No wire schema for ${e} in the resolved era`):new Error(i.message);return Promise.resolve(t(i.value))});return}if(!r)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async n=>{let o=await Ch(t.params,{...n.params});if(!o.success)throw new Me(fe.InvalidParams,`Invalid params for notification ${e}: ${o.error}`);await r(o.data,n)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};mP=H((e=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,r=/\\([\u000b\u0020-\u00ff])/g,n=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=o;function o(s){if(!s)throw new TypeError("argument string is required");var c=typeof s=="object"?i(s):s;if(typeof c!="string")throw new TypeError("argument string is required to be a string");var u=c.indexOf(";"),l=u!==-1?c.slice(0,u).trim():c.trim();if(!n.test(l))throw new TypeError("invalid media type");var d=new a(l.toLowerCase());if(u!==-1){var m,v,g;for(t.lastIndex=u;v=t.exec(c);){if(v.index!==u)throw new TypeError("invalid parameter format");u+=v[0].length,m=v[1].toLowerCase(),g=v[2],g.charCodeAt(0)===34&&(g=g.slice(1,-1),g.indexOf("\\")!==-1&&(g=g.replace(r,"$1"))),d.parameters[m]=g}if(u!==c.length)throw new TypeError("invalid parameter format")}return d}function i(s){var c;if(typeof s.getHeader=="function"?c=s.getHeader("content-type"):typeof s.headers=="object"&&(c=s.headers&&s.headers["content-type"]),typeof c!="string")throw new TypeError("content-type header is missing from object");return c}function a(s){this.parameters=Object.create(null),this.type=s}})),fP=cc(mP(),1);ug=10*1024*1024,Kw=class{_buffer;_maxBufferSize;constructor(e){this._maxBufferSize=e?.maxBufferSize??ug}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){for(;this._buffer;){let e=this._buffer.indexOf(` +`);if(e===-1)return null;let t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");this._buffer=this._buffer.subarray(e+1);try{return lg(t)}catch(r){if(r instanceof SyntaxError)continue;throw r}}return null}clear(){this._buffer=void 0}};ow=1e6,Ah=1e6,iw=1e4,hP=1e6,Fw=class Dn{static isTemplate(t){return/\{[^}\s]+\}/.test(t)}static validateLength(t,r,n){if(t.length>r)throw new Error(`${n} exceeds maximum length of ${r} characters (got ${t.length})`)}template;parts;get variableNames(){return this.parts.flatMap(t=>typeof t=="string"?[]:t.names)}constructor(t){Dn.validateLength(t,ow,"Template"),this.template=t,this.parts=this.parse(t)}toString(){return this.template}parse(t){let r=[],n="",o=0,i=0;for(;oiw)throw new Error(`Template contains too many expressions (max ${iw})`);let s=t.slice(o+1,a),c=this.getOperator(s),u=s.includes("*"),l=this.getNames(s),d=l[0];for(let m of l)Dn.validateLength(m,Ah,"Variable name");r.push({name:d,operator:c,names:l,exploded:u}),o=a+1}else n+=t[o],o++;return n&&r.push(n),r}getOperator(t){return["+","#",".","/","?","&"].find(r=>t.startsWith(r))||""}getNames(t){let r=this.getOperator(t);return t.slice(r.length).split(",").map(n=>n.replace("*","").trim()).filter(n=>n.length>0)}encodeValue(t,r){return Dn.validateLength(t,Ah,"Variable value"),r==="+"||r==="#"?encodeURI(t):encodeURIComponent(t)}expandPart(t,r){if(t.operator==="?"||t.operator==="&"){let i=t.names.map(a=>{let s=r[a];return s===void 0?"":`${a}=${Array.isArray(s)?s.map(c=>this.encodeValue(c,t.operator)).join(","):this.encodeValue(s.toString(),t.operator)}`}).filter(a=>a.length>0);return i.length===0?"":(t.operator==="?"?"?":"&")+i.join("&")}if(t.names.length>1){let i=t.names.map(a=>r[a]).filter(a=>a!==void 0);return i.length===0?"":i.map(a=>Array.isArray(a)?a[0]:a).join(",")}let n=r[t.name];if(n===void 0)return"";let o=(Array.isArray(n)?n:[n]).map(i=>this.encodeValue(i,t.operator));switch(t.operator){case"":return o.join(",");case"+":return o.join(",");case"#":return"#"+o.join(",");case".":return"."+o.join(".");case"/":return"/"+o.join("/");default:return o.join(",")}}expand(t){let r="",n=!1;for(let o of this.parts){if(typeof o=="string"){r+=o;continue}let i=this.expandPart(o,t);i&&(r+=(o.operator==="?"||o.operator==="&")&&n?i.replace("?","&"):i,(o.operator==="?"||o.operator==="&")&&(n=!0))}return r}escapeRegExp(t){return t.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`)}partToRegExp(t){let r=[];for(let i of t.names)Dn.validateLength(i,Ah,"Variable name");if(t.operator==="?"||t.operator==="&"){for(let i=0;i0;){let t=this._messageQueue.shift();this.onmessage?.(t.message,t.extra)}}async close(){if(this._closed)return;this._closed=!0;let t=this._otherTransport;this._otherTransport=void 0;try{await t?.close()}finally{this.onclose?.()}}async send(t,r){if(!this._otherTransport)throw new ae(se.NotConnected,"Not connected");this._otherTransport.onmessage?this._otherTransport.onmessage(t,{authInfo:r?.authInfo}):this._otherTransport._messageQueue.push({message:t,extra:{authInfo:r?.authInfo}})}}});function xT(){let e=new zT.Ajv2020({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return RT(e),e}var ad,Gw,ze,Te,Gt,cd,gP,Xw,Yw,sd,yP,Xt,vP,_P,Qw,SP,ud,hs,ld,gs,dd,bP,ez,$P,wP,zP,tz,kP,dg,rz,EP,RP,xP,IP,PP,TP,CP,AP,pg,OP,NP,jP,nz,oz,iz,UP,MP,DP,mg,qP,az,LP,VP,KP,JP,FP,HP,ZP,WP,sz,BP,cz,uz,GP,XP,lz,YP,dz,pz,mz,QP,eT,tT,rT,nT,oT,iT,aT,sT,cT,uT,lT,dT,pT,mT,fT,hT,gT,yT,vT,_T,ST,bT,$T,wT,zT,kT,ET,RT,pd,SD,fz=q(()=>{cp();ad=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var r=class extends t{constructor(y){if(super(),!e.IDENTIFIER.test(y))throw new Error("CodeGen: name must be a valid identifier");this.str=y}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=r;var n=class extends t{constructor(y){super(),this._items=typeof y=="string"?[y]:y}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let y=this._items[0];return y===""||y==='""'}get str(){var y;return(y=this._str)!==null&&y!==void 0?y:this._str=this._items.reduce((S,_)=>`${S}${_}`,"")}get names(){var y;return(y=this._names)!==null&&y!==void 0?y:this._names=this._items.reduce((S,_)=>(_ instanceof r&&(S[_.str]=(S[_.str]||0)+1),S),{})}};e._Code=n,e.nil=new n("");function o(y,...S){let _=[y[0]],$=0;for(;${Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=ad();var r=class extends Error{constructor(c){super(`CodeGen: "code" for ${c} not defined`),this.value=c.value}},n;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(n||(e.UsedValueState=n={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};var o=class{constructor({prefixes:c,parent:u}={}){this._names={},this._prefixes=c,this._parent=u}toName(c){return c instanceof t.Name?c:this.name(c)}name(c){return new t.Name(this._newName(c))}_newName(c){let u=this._names[c]||this._nameGroup(c);return`${c}${u.index++}`}_nameGroup(c){var u,l;if(!((l=(u=this._parent)===null||u===void 0?void 0:u._prefixes)===null||l===void 0)&&l.has(c)||this._prefixes&&!this._prefixes.has(c))throw new Error(`CodeGen: prefix "${c}" is not allowed in this scope`);return this._names[c]={prefix:c,index:0}}};e.Scope=o;var i=class extends t.Name{constructor(c,u){super(u),this.prefix=c}setValue(c,{property:u,itemIndex:l}){this.value=c,this.scopePath=(0,t._)`.${new t.Name(u)}[${l}]`}};e.ValueScopeName=i;let a=(0,t._)`\n`;var s=class extends o{constructor(c){super(c),this._values={},this._scope=c.scope,this.opts={...c,_n:c.lines?a:t.nil}}get(){return this._scope}name(c){return new i(c,this._newName(c))}value(c,u){var l;if(u.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let d=this.toName(c),{prefix:m}=d,v=(l=u.key)!==null&&l!==void 0?l:u.ref,g=this._values[m];if(g){let y=g.get(v);if(y)return y}else g=this._values[m]=new Map;g.set(v,d);let h=this._scope[m]||(this._scope[m]=[]),f=h.length;return h[f]=u.ref,d.setValue(u,{property:m,itemIndex:f}),d}getValue(c,u){let l=this._values[c];if(l)return l.get(u)}scopeRefs(c,u=this._values){return this._reduceValues(u,l=>{if(l.scopePath===void 0)throw new Error(`CodeGen: name "${l}" has no value`);return(0,t._)`${c}${l.scopePath}`})}scopeCode(c=this._values,u,l){return this._reduceValues(c,d=>{if(d.value===void 0)throw new Error(`CodeGen: name "${d}" has no value`);return d.value.code},u,l)}_reduceValues(c,u,l={},d){let m=t.nil;for(let v in c){let g=c[v];if(!g)continue;let h=l[v]=l[v]||new Map;g.forEach(f=>{if(h.has(f))return;h.set(f,n.Started);let y=u(f);if(y){let S=this.opts.es5?e.varKinds.var:e.varKinds.const;m=(0,t._)`${m}${S} ${f} = ${y};${this.opts._n}`}else if(y=d?.(f))m=(0,t._)`${m}${y}${this.opts._n}`;else throw new r(f);h.set(f,n.Completed)})}return m}};e.ValueScope=s})),ze=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=ad(),r=Gw();var n=ad();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}});var o=Gw();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return o.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};var i=class{optimizeNodes(){return this}optimizeNames(z,I){return this}},a=class extends i{constructor(z,I,O){super(),this.varKind=z,this.name=I,this.rhs=O}render({es5:z,_n:I}){let O=z?r.varKinds.var:this.varKind,W=this.rhs===void 0?"":` = ${this.rhs}`;return`${O} ${this.name}${W};`+I}optimizeNames(z,I){if(z[this.name.str])return this.rhs&&(this.rhs=J(this.rhs,z,I)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends i{constructor(z,I,O){super(),this.lhs=z,this.rhs=I,this.sideEffects=O}render({_n:z}){return`${this.lhs} = ${this.rhs};`+z}optimizeNames(z,I){if(!(this.lhs instanceof t.Name&&!z[this.lhs.str]&&!this.sideEffects))return this.rhs=J(this.rhs,z,I),this}get names(){return Z(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(z,I,O,W){super(z,O,W),this.op=I}render({_n:z}){return`${this.lhs} ${this.op}= ${this.rhs};`+z}},u=class extends i{constructor(z){super(),this.label=z,this.names={}}render({_n:z}){return`${this.label}:`+z}},l=class extends i{constructor(z){super(),this.label=z,this.names={}}render({_n:z}){return`break${this.label?` ${this.label}`:""};`+z}},d=class extends i{constructor(z){super(),this.error=z}render({_n:z}){return`throw ${this.error};`+z}get names(){return this.error.names}},m=class extends i{constructor(z){super(),this.code=z}render({_n:z}){return`${this.code};`+z}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(z,I){return this.code=J(this.code,z,I),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},v=class extends i{constructor(z=[]){super(),this.nodes=z}render(z){return this.nodes.reduce((I,O)=>I+O.render(z),"")}optimizeNodes(){let{nodes:z}=this,I=z.length;for(;I--;){let O=z[I].optimizeNodes();Array.isArray(O)?z.splice(I,1,...O):O?z[I]=O:z.splice(I,1)}return z.length>0?this:void 0}optimizeNames(z,I){let{nodes:O}=this,W=O.length;for(;W--;){let ce=O[W];ce.optimizeNames(z,I)||(te(z,ce.names),O.splice(W,1))}return O.length>0?this:void 0}get names(){return this.nodes.reduce((z,I)=>L(z,I.names),{})}},g=class extends v{render(z){return"{"+z._n+super.render(z)+"}"+z._n}},h=class extends v{},f=class extends g{};f.kind="else";var y=class id extends g{constructor(I,O){super(O),this.condition=I}render(I){let O=`if(${this.condition})`+super.render(I);return this.else&&(O+="else "+this.else.render(I)),O}optimizeNodes(){super.optimizeNodes();let I=this.condition;if(I===!0)return this.nodes;let O=this.else;if(O){let W=O.optimizeNodes();O=this.else=Array.isArray(W)?new f(W):W}if(O)return I===!1?O instanceof id?O:O.nodes:this.nodes.length?this:new id(_e(I),O instanceof id?[O]:O.nodes);if(!(I===!1||!this.nodes.length))return this}optimizeNames(I,O){var W;if(this.else=(W=this.else)===null||W===void 0?void 0:W.optimizeNames(I,O),!!(super.optimizeNames(I,O)||this.else))return this.condition=J(this.condition,I,O),this}get names(){let I=super.names;return Z(I,this.condition),this.else&&L(I,this.else.names),I}};y.kind="if";var S=class extends g{};S.kind="for";var _=class extends S{constructor(z){super(),this.iteration=z}render(z){return`for(${this.iteration})`+super.render(z)}optimizeNames(z,I){if(super.optimizeNames(z,I))return this.iteration=J(this.iteration,z,I),this}get names(){return L(super.names,this.iteration.names)}},$=class extends S{constructor(z,I,O,W){super(),this.varKind=z,this.name=I,this.from=O,this.to=W}render(z){let I=z.es5?r.varKinds.var:this.varKind,{name:O,from:W,to:ce}=this;return`for(${I} ${O}=${W}; ${O}<${ce}; ${O}++)`+super.render(z)}get names(){return Z(Z(super.names,this.from),this.to)}},k=class extends S{constructor(z,I,O,W){super(),this.loop=z,this.varKind=I,this.name=O,this.iterable=W}render(z){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(z)}optimizeNames(z,I){if(super.optimizeNames(z,I))return this.iterable=J(this.iterable,z,I),this}get names(){return L(super.names,this.iterable.names)}},w=class extends g{constructor(z,I,O){super(),this.name=z,this.args=I,this.async=O}render(z){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(z)}};w.kind="func";var b=class extends v{render(z){return"return "+super.render(z)}};b.kind="return";var E=class extends g{render(z){let I="try"+super.render(z);return this.catch&&(I+=this.catch.render(z)),this.finally&&(I+=this.finally.render(z)),I}optimizeNodes(){var z,I;return super.optimizeNodes(),(z=this.catch)===null||z===void 0||z.optimizeNodes(),(I=this.finally)===null||I===void 0||I.optimizeNodes(),this}optimizeNames(z,I){var O,W;return super.optimizeNames(z,I),(O=this.catch)===null||O===void 0||O.optimizeNames(z,I),(W=this.finally)===null||W===void 0||W.optimizeNames(z,I),this}get names(){let z=super.names;return this.catch&&L(z,this.catch.names),this.finally&&L(z,this.finally.names),z}},j=class extends g{constructor(z){super(),this.error=z}render(z){return`catch(${this.error})`+super.render(z)}};j.kind="catch";var V=class extends g{render(z){return"finally"+super.render(z)}};V.kind="finally";var A=class{constructor(z,I={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...I,_n:I.lines?` +`:""},this._extScope=z,this._scope=new r.Scope({parent:z}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(z){return this._scope.name(z)}scopeName(z){return this._extScope.name(z)}scopeValue(z,I){let O=this._extScope.value(z,I);return(this._values[O.prefix]||(this._values[O.prefix]=new Set)).add(O),O}getScopeValue(z,I){return this._extScope.getValue(z,I)}scopeRefs(z){return this._extScope.scopeRefs(z,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(z,I,O,W){let ce=this._scope.toName(I);return O!==void 0&&W&&(this._constants[ce.str]=O),this._leafNode(new a(z,ce,O)),ce}const(z,I,O){return this._def(r.varKinds.const,z,I,O)}let(z,I,O){return this._def(r.varKinds.let,z,I,O)}var(z,I,O){return this._def(r.varKinds.var,z,I,O)}assign(z,I,O){return this._leafNode(new s(z,I,O))}add(z,I){return this._leafNode(new c(z,e.operators.ADD,I))}code(z){return typeof z=="function"?z():z!==t.nil&&this._leafNode(new m(z)),this}object(...z){let I=["{"];for(let[O,W]of z)I.length>1&&I.push(","),I.push(O),(O!==W||this.opts.es5)&&(I.push(":"),(0,t.addCodeArg)(I,W));return I.push("}"),new t._Code(I)}if(z,I,O){if(this._blockNode(new y(z)),I&&O)this.code(I).else().code(O).endIf();else if(I)this.code(I).endIf();else if(O)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(z){return this._elseNode(new y(z))}else(){return this._elseNode(new f)}endIf(){return this._endBlockNode(y,f)}_for(z,I){return this._blockNode(z),I&&this.code(I).endFor(),this}for(z,I){return this._for(new _(z),I)}forRange(z,I,O,W,ce=this.opts.es5?r.varKinds.var:r.varKinds.let){let $e=this._scope.toName(z);return this._for(new $(ce,$e,I,O),()=>W($e))}forOf(z,I,O,W=r.varKinds.const){let ce=this._scope.toName(z);if(this.opts.es5){let $e=I instanceof t.Name?I:this.var("_arr",I);return this.forRange("_i",0,(0,t._)`${$e}.length`,B=>{this.var(ce,(0,t._)`${$e}[${B}]`),O(ce)})}return this._for(new k("of",W,ce,I),()=>O(ce))}forIn(z,I,O,W=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(z,(0,t._)`Object.keys(${I})`,O);let ce=this._scope.toName(z);return this._for(new k("in",W,ce,I),()=>O(ce))}endFor(){return this._endBlockNode(S)}label(z){return this._leafNode(new u(z))}break(z){return this._leafNode(new l(z))}return(z){let I=new b;if(this._blockNode(I),this.code(z),I.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(b)}try(z,I,O){if(!I&&!O)throw new Error('CodeGen: "try" without "catch" and "finally"');let W=new E;if(this._blockNode(W),this.code(z),I){let ce=this.name("e");this._currNode=W.catch=new j(ce),I(ce)}return O&&(this._currNode=W.finally=new V,this.code(O)),this._endBlockNode(j,V)}throw(z){return this._leafNode(new d(z))}block(z,I){return this._blockStarts.push(this._nodes.length),z&&this.code(z).endBlock(I),this}endBlock(z){let I=this._blockStarts.pop();if(I===void 0)throw new Error("CodeGen: not in self-balancing block");let O=this._nodes.length-I;if(O<0||z!==void 0&&O!==z)throw new Error(`CodeGen: wrong number of nodes: ${O} vs ${z} expected`);return this._nodes.length=I,this}func(z,I=t.nil,O,W){return this._blockNode(new w(z,I,O)),W&&this.code(W).endFunc(),this}endFunc(){return this._endBlockNode(w)}optimize(z=1){for(;z-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(z){return this._currNode.nodes.push(z),this}_blockNode(z){this._currNode.nodes.push(z),this._nodes.push(z)}_endBlockNode(z,I){let O=this._currNode;if(O instanceof z||I&&O instanceof I)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${I?`${z.kind}/${I.kind}`:z.kind}"`)}_elseNode(z){let I=this._currNode;if(!(I instanceof y))throw new Error('CodeGen: "else" without "if"');return this._currNode=I.else=z,this}get _root(){return this._nodes[0]}get _currNode(){let z=this._nodes;return z[z.length-1]}set _currNode(z){let I=this._nodes;I[I.length-1]=z}};e.CodeGen=A;function L(z,I){for(let O in I)z[O]=(z[O]||0)+(I[O]||0);return z}function Z(z,I){return I instanceof t._CodeOrName?L(z,I.names):z}function J(z,I,O){if(z instanceof t.Name)return W(z);if(!ce(z))return z;return new t._Code(z._items.reduce(($e,B)=>(B instanceof t.Name&&(B=W(B)),B instanceof t._Code?$e.push(...B._items):$e.push(B),$e),[]));function W($e){let B=O[$e.str];return B===void 0||I[$e.str]!==1?$e:(delete I[$e.str],B)}function ce($e){return $e instanceof t._Code&&$e._items.some(B=>B instanceof t.Name&&I[B.str]===1&&O[B.str]!==void 0)}}function te(z,I){for(let O in I)z[O]=(z[O]||0)-(I[O]||0)}function _e(z){return typeof z=="boolean"||typeof z=="number"||z===null?!z:(0,t._)`!${K(z)}`}e.not=_e;let ke=M(e.operators.AND);function Ne(...z){return z.reduce(ke)}e.and=Ne;let be=M(e.operators.OR);function P(...z){return z.reduce(be)}e.or=P;function M(z){return(I,O)=>I===t.nil?O:O===t.nil?I:(0,t._)`${K(I)} ${z} ${K(O)}`}function K(z){return z instanceof t.Name?z:(0,t._)`(${z})`}})),Te=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;let t=ze(),r=ad();function n(w){let b={};for(let E of w)b[E]=!0;return b}e.toHash=n;function o(w,b){return typeof b=="boolean"?b:Object.keys(b).length===0?!0:(i(w,b),!a(b,w.self.RULES.all))}e.alwaysValidSchema=o;function i(w,b=w.schema){let{opts:E,self:j}=w;if(!E.strictSchema||typeof b=="boolean")return;let V=j.RULES.keywords;for(let A in b)V[A]||k(w,`unknown keyword: "${A}"`)}e.checkUnknownRules=i;function a(w,b){if(typeof w=="boolean")return!w;for(let E in w)if(b[E])return!0;return!1}e.schemaHasRules=a;function s(w,b){if(typeof w=="boolean")return!w;for(let E in w)if(E!=="$ref"&&b.all[E])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:w,schemaPath:b},E,j,V){if(!V){if(typeof E=="number"||typeof E=="boolean")return E;if(typeof E=="string")return(0,t._)`${E}`}return(0,t._)`${w}${b}${(0,t.getProperty)(j)}`}e.schemaRefOrVal=c;function u(w){return m(decodeURIComponent(w))}e.unescapeFragment=u;function l(w){return encodeURIComponent(d(w))}e.escapeFragment=l;function d(w){return typeof w=="number"?`${w}`:w.replace(/~/g,"~0").replace(/\//g,"~1")}e.escapeJsonPointer=d;function m(w){return w.replace(/~1/g,"/").replace(/~0/g,"~")}e.unescapeJsonPointer=m;function v(w,b){if(Array.isArray(w))for(let E of w)b(E);else b(w)}e.eachItem=v;function g({mergeNames:w,mergeToName:b,mergeValues:E,resultToName:j}){return(V,A,L,Z)=>{let J=L===void 0?A:L instanceof t.Name?(A instanceof t.Name?w(V,A,L):b(V,A,L),L):A instanceof t.Name?(b(V,L,A),A):E(A,L);return Z===t.Name&&!(J instanceof t.Name)?j(V,J):J}}e.mergeEvaluated={props:g({mergeNames:(w,b,E)=>w.if((0,t._)`${E} !== true && ${b} !== undefined`,()=>{w.if((0,t._)`${b} === true`,()=>w.assign(E,!0),()=>w.assign(E,(0,t._)`${E} || {}`).code((0,t._)`Object.assign(${E}, ${b})`))}),mergeToName:(w,b,E)=>w.if((0,t._)`${E} !== true`,()=>{b===!0?w.assign(E,!0):(w.assign(E,(0,t._)`${E} || {}`),f(w,E,b))}),mergeValues:(w,b)=>w===!0?!0:{...w,...b},resultToName:h}),items:g({mergeNames:(w,b,E)=>w.if((0,t._)`${E} !== true && ${b} !== undefined`,()=>w.assign(E,(0,t._)`${b} === true ? true : ${E} > ${b} ? ${E} : ${b}`)),mergeToName:(w,b,E)=>w.if((0,t._)`${E} !== true`,()=>w.assign(E,b===!0?!0:(0,t._)`${E} > ${b} ? ${E} : ${b}`)),mergeValues:(w,b)=>w===!0?!0:Math.max(w,b),resultToName:(w,b)=>w.var("items",b)})};function h(w,b){if(b===!0)return w.var("props",!0);let E=w.var("props",(0,t._)`{}`);return b!==void 0&&f(w,E,b),E}e.evaluatedPropsToName=h;function f(w,b,E){Object.keys(E).forEach(j=>w.assign((0,t._)`${b}${(0,t.getProperty)(j)}`,!0))}e.setEvaluated=f;let y={};function S(w,b){return w.scopeValue("func",{ref:b,code:y[b.code]||(y[b.code]=new r._Code(b.code))})}e.useFunc=S;var _;(function(w){w[w.Num=0]="Num",w[w.Str=1]="Str"})(_||(e.Type=_={}));function $(w,b,E){if(w instanceof t.Name){let j=b===_.Num;return E?j?(0,t._)`"[" + ${w} + "]"`:(0,t._)`"['" + ${w} + "']"`:j?(0,t._)`"/" + ${w}`:(0,t._)`"/" + ${w}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return E?(0,t.getProperty)(w).toString():"/"+d(w)}e.getErrorPath=$;function k(w,b,E=w.opts.strictSchema){if(E){if(b=`strict mode: ${b}`,E===!0)throw new Error(b);w.self.logger.warn(b)}}e.checkStrictMode=k})),Gt=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r={data:new t.Name("data"),valCxt:new t.Name("valCxt"),instancePath:new t.Name("instancePath"),parentData:new t.Name("parentData"),parentDataProperty:new t.Name("parentDataProperty"),rootData:new t.Name("rootData"),dynamicAnchors:new t.Name("dynamicAnchors"),vErrors:new t.Name("vErrors"),errors:new t.Name("errors"),this:new t.Name("this"),self:new t.Name("self"),scope:new t.Name("scope"),json:new t.Name("json"),jsonPos:new t.Name("jsonPos"),jsonLen:new t.Name("jsonLen"),jsonPart:new t.Name("jsonPart")};e.default=r})),cd=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=ze(),r=Te(),n=Gt();e.keywordError={message:({keyword:f})=>(0,t.str)`must pass "${f}" keyword validation`},e.keyword$DataError={message:({keyword:f,schemaType:y})=>y?(0,t.str)`"${f}" keyword must be ${y} ($data)`:(0,t.str)`"${f}" keyword is invalid ($data)`};function o(f,y=e.keywordError,S,_){let{it:$}=f,{gen:k,compositeRule:w,allErrors:b}=$,E=d(f,y,S);_??(w||b)?c(k,E):u($,(0,t._)`[${E}]`)}e.reportError=o;function i(f,y=e.keywordError,S){let{it:_}=f,{gen:$,compositeRule:k,allErrors:w}=_;c($,d(f,y,S)),k||w||u(_,n.default.vErrors)}e.reportExtraError=i;function a(f,y){f.assign(n.default.errors,y),f.if((0,t._)`${n.default.vErrors} !== null`,()=>f.if(y,()=>f.assign((0,t._)`${n.default.vErrors}.length`,y),()=>f.assign(n.default.vErrors,null)))}e.resetErrorsCount=a;function s({gen:f,keyword:y,schemaValue:S,data:_,errsCount:$,it:k}){if($===void 0)throw new Error("ajv implementation error");let w=f.name("err");f.forRange("i",$,n.default.errors,b=>{f.const(w,(0,t._)`${n.default.vErrors}[${b}]`),f.if((0,t._)`${w}.instancePath === undefined`,()=>f.assign((0,t._)`${w}.instancePath`,(0,t.strConcat)(n.default.instancePath,k.errorPath))),f.assign((0,t._)`${w}.schemaPath`,(0,t.str)`${k.errSchemaPath}/${y}`),k.opts.verbose&&(f.assign((0,t._)`${w}.schema`,S),f.assign((0,t._)`${w}.data`,_))})}e.extendErrors=s;function c(f,y){let S=f.const("err",y);f.if((0,t._)`${n.default.vErrors} === null`,()=>f.assign(n.default.vErrors,(0,t._)`[${S}]`),(0,t._)`${n.default.vErrors}.push(${S})`),f.code((0,t._)`${n.default.errors}++`)}function u(f,y){let{gen:S,validateName:_,schemaEnv:$}=f;$.$async?S.throw((0,t._)`new ${f.ValidationError}(${y})`):(S.assign((0,t._)`${_}.errors`,y),S.return(!1))}let l={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function d(f,y,S){let{createErrors:_}=f.it;return _===!1?(0,t._)`{}`:m(f,y,S)}function m(f,y,S={}){let{gen:_,it:$}=f,k=[v($,S),g(f,S)];return h(f,y,k),_.object(...k)}function v({errorPath:f},{instancePath:y}){let S=y?(0,t.str)`${f}${(0,r.getErrorPath)(y,r.Type.Str)}`:f;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,S)]}function g({keyword:f,it:{errSchemaPath:y}},{schemaPath:S,parentSchema:_}){let $=_?y:(0,t.str)`${y}/${f}`;return S&&($=(0,t.str)`${$}${(0,r.getErrorPath)(S,r.Type.Str)}`),[l.schemaPath,$]}function h(f,{params:y,message:S},_){let{keyword:$,data:k,schemaValue:w,it:b}=f,{opts:E,propertyName:j,topSchemaRef:V,schemaPath:A}=b;_.push([l.keyword,$],[l.params,typeof y=="function"?y(f):y||(0,t._)`{}`]),E.messages&&_.push([l.message,typeof S=="function"?S(f):S]),E.verbose&&_.push([l.schema,w],[l.parentSchema,(0,t._)`${V}${A}`],[n.default.data,k]),j&&_.push([l.propertyName,j])}})),gP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=cd(),r=ze(),n=Gt(),o={message:"boolean schema is false"};function i(c){let{gen:u,schema:l,validateName:d}=c;l===!1?s(c,!1):typeof l=="object"&&l.$async===!0?u.return(n.default.data):(u.assign((0,r._)`${d}.errors`,null),u.return(!0))}e.topBoolOrEmptySchema=i;function a(c,u){let{gen:l,schema:d}=c;d===!1?(l.var(u,!1),s(c)):l.var(u,!0)}e.boolOrEmptySchema=a;function s(c,u){let{gen:l,data:d}=c,m={gen:l,keyword:"false schema",data:d,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:c};(0,t.reportError)(m,o,void 0,u)}})),Xw=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getRules=e.isJSONType=void 0;let t=new Set(["string","number","integer","boolean","null","object","array"]);function r(o){return typeof o=="string"&&t.has(o)}e.isJSONType=r;function n(){let o={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...o,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},o.number,o.string,o.array,o.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=n})),Yw=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:o,self:i},a){let s=i.RULES.types[a];return s&&s!==!0&&r(o,s)}e.schemaHasRulesForType=t;function r(o,i){return i.rules.some(a=>n(o,a))}e.shouldUseGroup=r;function n(o,i){var a;return o[i.keyword]!==void 0||((a=i.definition.implements)===null||a===void 0?void 0:a.some(s=>o[s]!==void 0))}e.shouldUseRule=n})),sd=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;let t=Xw(),r=Yw(),n=cd(),o=ze(),i=Te();var a;(function(_){_[_.Correct=0]="Correct",_[_.Wrong=1]="Wrong"})(a||(e.DataType=a={}));function s(_){let $=c(_.type);if($.includes("null")){if(_.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!$.length&&_.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');_.nullable===!0&&$.push("null")}return $}e.getSchemaTypes=s;function c(_){let $=Array.isArray(_)?_:_?[_]:[];if($.every(t.isJSONType))return $;throw new Error("type must be JSONType or JSONType[]: "+$.join(","))}e.getJSONTypes=c;function u(_,$){let{gen:k,data:w,opts:b}=_,E=d($,b.coerceTypes),j=$.length>0&&!(E.length===0&&$.length===1&&(0,r.schemaHasRulesForType)(_,$[0]));if(j){let V=h($,w,b.strictNumbers,a.Wrong);k.if(V,()=>{E.length?m(_,$,E):y(_)})}return j}e.coerceAndCheckDataType=u;let l=new Set(["string","number","integer","boolean","null"]);function d(_,$){return $?_.filter(k=>l.has(k)||$==="array"&&k==="array"):[]}function m(_,$,k){let{gen:w,data:b,opts:E}=_,j=w.let("dataType",(0,o._)`typeof ${b}`),V=w.let("coerced",(0,o._)`undefined`);E.coerceTypes==="array"&&w.if((0,o._)`${j} == 'object' && Array.isArray(${b}) && ${b}.length == 1`,()=>w.assign(b,(0,o._)`${b}[0]`).assign(j,(0,o._)`typeof ${b}`).if(h($,b,E.strictNumbers),()=>w.assign(V,b))),w.if((0,o._)`${V} !== undefined`);for(let L of k)(l.has(L)||L==="array"&&E.coerceTypes==="array")&&A(L);w.else(),y(_),w.endIf(),w.if((0,o._)`${V} !== undefined`,()=>{w.assign(b,V),v(_,V)});function A(L){switch(L){case"string":w.elseIf((0,o._)`${j} == "number" || ${j} == "boolean"`).assign(V,(0,o._)`"" + ${b}`).elseIf((0,o._)`${b} === null`).assign(V,(0,o._)`""`);return;case"number":w.elseIf((0,o._)`${j} == "boolean" || ${b} === null + || (${j} == "string" && ${b} && ${b} == +${b})`).assign(V,(0,o._)`+${b}`);return;case"integer":w.elseIf((0,o._)`${j} === "boolean" || ${b} === null + || (${j} === "string" && ${b} && ${b} == +${b} && !(${b} % 1))`).assign(V,(0,o._)`+${b}`);return;case"boolean":w.elseIf((0,o._)`${b} === "false" || ${b} === 0 || ${b} === null`).assign(V,!1).elseIf((0,o._)`${b} === "true" || ${b} === 1`).assign(V,!0);return;case"null":w.elseIf((0,o._)`${b} === "" || ${b} === 0 || ${b} === false`),w.assign(V,null);return;case"array":w.elseIf((0,o._)`${j} === "string" || ${j} === "number" + || ${j} === "boolean" || ${b} === null`).assign(V,(0,o._)`[${b}]`)}}}function v({gen:_,parentData:$,parentDataProperty:k},w){_.if((0,o._)`${$} !== undefined`,()=>_.assign((0,o._)`${$}[${k}]`,w))}function g(_,$,k,w=a.Correct){let b=w===a.Correct?o.operators.EQ:o.operators.NEQ,E;switch(_){case"null":return(0,o._)`${$} ${b} null`;case"array":E=(0,o._)`Array.isArray(${$})`;break;case"object":E=(0,o._)`${$} && typeof ${$} == "object" && !Array.isArray(${$})`;break;case"integer":E=j((0,o._)`!(${$} % 1) && !isNaN(${$})`);break;case"number":E=j();break;default:return(0,o._)`typeof ${$} ${b} ${_}`}return w===a.Correct?E:(0,o.not)(E);function j(V=o.nil){return(0,o.and)((0,o._)`typeof ${$} == "number"`,V,k?(0,o._)`isFinite(${$})`:o.nil)}}e.checkDataType=g;function h(_,$,k,w){if(_.length===1)return g(_[0],$,k,w);let b,E=(0,i.toHash)(_);if(E.array&&E.object){let j=(0,o._)`typeof ${$} != "object"`;b=E.null?j:(0,o._)`!${$} || ${j}`,delete E.null,delete E.array,delete E.object}else b=o.nil;E.number&&delete E.integer;for(let j in E)b=(0,o.and)(b,g(j,$,k,w));return b}e.checkDataTypes=h;let f={message:({schema:_})=>`must be ${_}`,params:({schema:_,schemaValue:$})=>typeof _=="string"?(0,o._)`{type: ${_}}`:(0,o._)`{type: ${$}}`};function y(_){let $=S(_);(0,n.reportError)($,f)}e.reportTypeError=y;function S(_){let{gen:$,data:k,schema:w}=_,b=(0,i.schemaRefOrVal)(_,w,"type");return{gen:$,keyword:"type",data:k,schema:w.type,schemaCode:b,schemaValue:b,parentSchema:w,params:{},it:_}}})),yP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;let t=ze(),r=Te();function n(i,a){let{properties:s,items:c}=i.schema;if(a==="object"&&s)for(let u in s)o(i,u,s[u].default);else a==="array"&&Array.isArray(c)&&c.forEach((u,l)=>o(i,l,u.default))}e.assignDefaults=n;function o(i,a,s){let{gen:c,compositeRule:u,data:l,opts:d}=i;if(s===void 0)return;let m=(0,t._)`${l}${(0,t.getProperty)(a)}`;if(u){(0,r.checkStrictMode)(i,`default is ignored for: ${m}`);return}let v=(0,t._)`${m} === undefined`;d.useDefaults==="empty"&&(v=(0,t._)`${v} || ${m} === null || ${m} === ""`),c.if(v,(0,t._)`${m} = ${(0,t.stringify)(s)}`)}})),Xt=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;let t=ze(),r=Te(),n=Gt(),o=Te();function i(_,$){let{gen:k,data:w,it:b}=_;k.if(d(k,w,$,b.opts.ownProperties),()=>{_.setParams({missingProperty:(0,t._)`${$}`},!0),_.error()})}e.checkReportMissingProp=i;function a({gen:_,data:$,it:{opts:k}},w,b){return(0,t.or)(...w.map(E=>(0,t.and)(d(_,$,E,k.ownProperties),(0,t._)`${b} = ${E}`)))}e.checkMissingProp=a;function s(_,$){_.setParams({missingProperty:$},!0),_.error()}e.reportMissingProp=s;function c(_){return _.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=c;function u(_,$,k){return(0,t._)`${c(_)}.call(${$}, ${k})`}e.isOwnProperty=u;function l(_,$,k,w){let b=(0,t._)`${$}${(0,t.getProperty)(k)} !== undefined`;return w?(0,t._)`${b} && ${u(_,$,k)}`:b}e.propertyInData=l;function d(_,$,k,w){let b=(0,t._)`${$}${(0,t.getProperty)(k)} === undefined`;return w?(0,t.or)(b,(0,t.not)(u(_,$,k))):b}e.noPropertyInData=d;function m(_){return _?Object.keys(_).filter($=>$!=="__proto__"):[]}e.allSchemaProperties=m;function v(_,$){return m($).filter(k=>!(0,r.alwaysValidSchema)(_,$[k]))}e.schemaProperties=v;function g({schemaCode:_,data:$,it:{gen:k,topSchemaRef:w,schemaPath:b,errorPath:E},it:j},V,A,L){let Z=L?(0,t._)`${_}, ${$}, ${w}${b}`:$,J=[[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,E)],[n.default.parentData,j.parentData],[n.default.parentDataProperty,j.parentDataProperty],[n.default.rootData,n.default.rootData]];j.opts.dynamicRef&&J.push([n.default.dynamicAnchors,n.default.dynamicAnchors]);let te=(0,t._)`${Z}, ${k.object(...J)}`;return A!==t.nil?(0,t._)`${V}.call(${A}, ${te})`:(0,t._)`${V}(${te})`}e.callValidateCode=g;let h=(0,t._)`new RegExp`;function f({gen:_,it:{opts:$}},k){let w=$.unicodeRegExp?"u":"",{regExp:b}=$.code,E=b(k,w);return _.scopeValue("pattern",{key:E.toString(),ref:E,code:(0,t._)`${b.code==="new RegExp"?h:(0,o.useFunc)(_,b)}(${k}, ${w})`})}e.usePattern=f;function y(_){let{gen:$,data:k,keyword:w,it:b}=_,E=$.name("valid");if(b.allErrors){let V=$.let("valid",!0);return j(()=>$.assign(V,!1)),V}return $.var(E,!0),j(()=>$.break()),E;function j(V){let A=$.const("len",(0,t._)`${k}.length`);$.forRange("i",0,A,L=>{_.subschema({keyword:w,dataProp:L,dataPropType:r.Type.Num},E),$.if((0,t.not)(E),V)})}}e.validateArray=y;function S(_){let{gen:$,schema:k,keyword:w,it:b}=_;if(!Array.isArray(k))throw new Error("ajv implementation error");if(k.some(V=>(0,r.alwaysValidSchema)(b,V))&&!b.opts.unevaluated)return;let E=$.let("valid",!1),j=$.name("_valid");$.block(()=>k.forEach((V,A)=>{let L=_.subschema({keyword:w,schemaProp:A,compositeRule:!0},j);$.assign(E,(0,t._)`${E} || ${j}`),_.mergeValidEvaluated(L,j)||$.if((0,t.not)(E))})),_.result(E,()=>_.reset(),()=>_.error(!0))}e.validateUnion=S})),vP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=ze(),r=Gt(),n=Xt(),o=cd();function i(v,g){let{gen:h,keyword:f,schema:y,parentSchema:S,it:_}=v,$=g.macro.call(_.self,y,S,_),k=l(h,f,$);_.opts.validateSchema!==!1&&_.self.validateSchema($,!0);let w=h.name("valid");v.subschema({schema:$,schemaPath:t.nil,errSchemaPath:`${_.errSchemaPath}/${f}`,topSchemaRef:k,compositeRule:!0},w),v.pass(w,()=>v.error(!0))}e.macroKeywordCode=i;function a(v,g){var h;let{gen:f,keyword:y,schema:S,parentSchema:_,$data:$,it:k}=v;u(k,g);let w=l(f,y,!$&&g.compile?g.compile.call(k.self,S,_,k):g.validate),b=f.let("valid");v.block$data(b,E),v.ok((h=g.valid)!==null&&h!==void 0?h:b);function E(){if(g.errors===!1)A(),g.modifying&&s(v),L(()=>v.error());else{let Z=g.async?j():V();g.modifying&&s(v),L(()=>c(v,Z))}}function j(){let Z=f.let("ruleErrs",null);return f.try(()=>A((0,t._)`await `),J=>f.assign(b,!1).if((0,t._)`${J} instanceof ${k.ValidationError}`,()=>f.assign(Z,(0,t._)`${J}.errors`),()=>f.throw(J))),Z}function V(){let Z=(0,t._)`${w}.errors`;return f.assign(Z,null),A(t.nil),Z}function A(Z=g.async?(0,t._)`await `:t.nil){let J=k.opts.passContext?r.default.this:r.default.self,te=!("compile"in g&&!$||g.schema===!1);f.assign(b,(0,t._)`${Z}${(0,n.callValidateCode)(v,w,J,te)}`,g.modifying)}function L(Z){var J;f.if((0,t.not)((J=g.valid)!==null&&J!==void 0?J:b),Z)}}e.funcKeywordCode=a;function s(v){let{gen:g,data:h,it:f}=v;g.if(f.parentData,()=>g.assign(h,(0,t._)`${f.parentData}[${f.parentDataProperty}]`))}function c(v,g){let{gen:h}=v;h.if((0,t._)`Array.isArray(${g})`,()=>{h.assign(r.default.vErrors,(0,t._)`${r.default.vErrors} === null ? ${g} : ${r.default.vErrors}.concat(${g})`).assign(r.default.errors,(0,t._)`${r.default.vErrors}.length`),(0,o.extendErrors)(v)},()=>v.error())}function u({schemaEnv:v},g){if(g.async&&!v.$async)throw new Error("async keyword in sync schema")}function l(v,g,h){if(h===void 0)throw new Error(`keyword "${g}" failed to compile`);return v.scopeValue("keyword",typeof h=="function"?{ref:h}:{ref:h,code:(0,t.stringify)(h)})}function d(v,g,h=!1){return!g.length||g.some(f=>f==="array"?Array.isArray(v):f==="object"?v&&typeof v=="object"&&!Array.isArray(v):typeof v==f||h&&typeof v>"u")}e.validSchemaType=d;function m({schema:v,opts:g,self:h,errSchemaPath:f},y,S){if(Array.isArray(y.keyword)?!y.keyword.includes(S):y.keyword!==S)throw new Error("ajv implementation error");let _=y.dependencies;if(_?.some($=>!Object.prototype.hasOwnProperty.call(v,$)))throw new Error(`parent schema must have dependencies of ${S}: ${_.join(",")}`);if(y.validateSchema&&!y.validateSchema(v[S])){let $=`keyword "${S}" value is invalid at path "${f}": `+h.errorsText(y.validateSchema.errors);if(g.validateSchema==="log")h.logger.error($);else throw new Error($)}}e.validateKeywordUsage=m})),_P=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=ze(),r=Te();function n(a,{keyword:s,schemaProp:c,schema:u,schemaPath:l,errSchemaPath:d,topSchemaRef:m}){if(s!==void 0&&u!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(s!==void 0){let v=a.schema[s];return c===void 0?{schema:v,schemaPath:(0,t._)`${a.schemaPath}${(0,t.getProperty)(s)}`,errSchemaPath:`${a.errSchemaPath}/${s}`}:{schema:v[c],schemaPath:(0,t._)`${a.schemaPath}${(0,t.getProperty)(s)}${(0,t.getProperty)(c)}`,errSchemaPath:`${a.errSchemaPath}/${s}/${(0,r.escapeFragment)(c)}`}}if(u!==void 0){if(l===void 0||d===void 0||m===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:u,schemaPath:l,topSchemaRef:m,errSchemaPath:d}}throw new Error('either "keyword" or "schema" must be passed')}e.getSubschema=n;function o(a,s,{dataProp:c,dataPropType:u,data:l,dataTypes:d,propertyName:m}){if(l!==void 0&&c!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:v}=s;if(c!==void 0){let{errorPath:h,dataPathArr:f,opts:y}=s;g(v.let("data",(0,t._)`${s.data}${(0,t.getProperty)(c)}`,!0)),a.errorPath=(0,t.str)`${h}${(0,r.getErrorPath)(c,u,y.jsPropertySyntax)}`,a.parentDataProperty=(0,t._)`${c}`,a.dataPathArr=[...f,a.parentDataProperty]}l!==void 0&&(g(l instanceof t.Name?l:v.let("data",l,!0)),m!==void 0&&(a.propertyName=m)),d&&(a.dataTypes=d);function g(h){a.data=h,a.dataLevel=s.dataLevel+1,a.dataTypes=[],s.definedProperties=new Set,a.parentData=s.data,a.dataNames=[...s.dataNames,h]}}e.extendSubschemaData=o;function i(a,{jtdDiscriminator:s,jtdMetadata:c,compositeRule:u,createErrors:l,allErrors:d}){u!==void 0&&(a.compositeRule=u),l!==void 0&&(a.createErrors=l),d!==void 0&&(a.allErrors=d),a.jtdDiscriminator=s,a.jtdMetadata=c}e.extendSubschemaMode=i})),Qw=H(((e,t)=>{t.exports=function r(n,o){if(n===o)return!0;if(n&&o&&typeof n=="object"&&typeof o=="object"){if(n.constructor!==o.constructor)return!1;var i,a,s;if(Array.isArray(n)){if(i=n.length,i!=o.length)return!1;for(a=i;a--!==0;)if(!r(n[a],o[a]))return!1;return!0}if(n.constructor===RegExp)return n.source===o.source&&n.flags===o.flags;if(n.valueOf!==Object.prototype.valueOf)return n.valueOf()===o.valueOf();if(n.toString!==Object.prototype.toString)return n.toString()===o.toString();if(s=Object.keys(n),i=s.length,i!==Object.keys(o).length)return!1;for(a=i;a--!==0;)if(!Object.prototype.hasOwnProperty.call(o,s[a]))return!1;for(a=i;a--!==0;){var c=s[a];if(!r(n[c],o[c]))return!1}return!0}return n!==n&&o!==o}})),SP=H(((e,t)=>{var r=t.exports=function(i,a,s){typeof a=="function"&&(s=a,a={}),s=a.cb||s;var c=typeof s=="function"?s:s.pre||function(){},u=s.post||function(){};n(a,c,u,i,"",i)};r.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},r.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},r.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},r.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function n(i,a,s,c,u,l,d,m,v,g){if(c&&typeof c=="object"&&!Array.isArray(c)){a(c,u,l,d,m,v,g);for(var h in c){var f=c[h];if(Array.isArray(f)){if(h in r.arrayKeywords)for(var y=0;y{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=Te(),r=Qw(),n=SP(),o=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function i(f,y=!0){return typeof f=="boolean"?!0:y===!0?!s(f):y?c(f)<=y:!1}e.inlineRef=i;let a=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function s(f){for(let y in f){if(a.has(y))return!0;let S=f[y];if(Array.isArray(S)&&S.some(s)||typeof S=="object"&&s(S))return!0}return!1}function c(f){let y=0;for(let S in f){if(S==="$ref")return 1/0;if(y++,!o.has(S)&&(typeof f[S]=="object"&&(0,t.eachItem)(f[S],_=>y+=c(_)),y===1/0))return 1/0}return y}function u(f,y="",S){return S!==!1&&(y=m(y)),l(f,f.parse(y))}e.getFullPath=u;function l(f,y){return f.serialize(y).split("#")[0]+"#"}e._getFullPath=l;let d=/#\/?$/;function m(f){return f?f.replace(d,""):""}e.normalizeId=m;function v(f,y,S){return S=m(S),f.resolve(y,S)}e.resolveUrl=v;let g=/^[a-z_][-a-z0-9._]*$/i;function h(f,y){if(typeof f=="boolean")return{};let{schemaId:S,uriResolver:_}=this.opts,$=m(f[S]||y),k={"":$},w=u(_,$,!1),b={},E=new Set;return n(f,{allKeys:!0},(A,L,Z,J)=>{if(J===void 0)return;let te=w+L,_e=k[J];typeof A[S]=="string"&&(_e=ke.call(this,A[S])),Ne.call(this,A.$anchor),Ne.call(this,A.$dynamicAnchor),k[L]=_e;function ke(be){let P=this.opts.uriResolver.resolve;if(be=m(_e?P(_e,be):be),E.has(be))throw V(be);E.add(be);let M=this.refs[be];return typeof M=="string"&&(M=this.refs[M]),typeof M=="object"?j(A,M.schema,be):be!==m(te)&&(be[0]==="#"?(j(A,b[be],be),b[be]=A):this.refs[be]=te),be}function Ne(be){if(typeof be=="string"){if(!g.test(be))throw new Error(`invalid anchor "${be}"`);ke.call(this,`#${be}`)}}}),b;function j(A,L,Z){if(L!==void 0&&!r(A,L))throw V(Z)}function V(A){return new Error(`reference "${A}" resolves to more than one schema`)}}e.getSchemaRefs=h})),hs=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=gP(),r=sd(),n=Yw(),o=sd(),i=yP(),a=vP(),s=_P(),c=ze(),u=Gt(),l=ud(),d=Te(),m=cd();function v(R){if(w(R)&&(E(R),k(R))){y(R);return}g(R,()=>(0,t.topBoolOrEmptySchema)(R))}e.validateFunctionCode=v;function g({gen:R,validateName:T,schema:D,schemaEnv:oe,opts:ne},ie){ne.code.es5?R.func(T,(0,c._)`${u.default.data}, ${u.default.valCxt}`,oe.$async,()=>{R.code((0,c._)`"use strict"; ${_(D,ne)}`),f(R,ne),R.code(ie)}):R.func(T,(0,c._)`${u.default.data}, ${h(ne)}`,oe.$async,()=>R.code(_(D,ne)).code(ie))}function h(R){return(0,c._)`{${u.default.instancePath}="", ${u.default.parentData}, ${u.default.parentDataProperty}, ${u.default.rootData}=${u.default.data}${R.dynamicRef?(0,c._)`, ${u.default.dynamicAnchors}={}`:c.nil}}={}`}function f(R,T){R.if(u.default.valCxt,()=>{R.var(u.default.instancePath,(0,c._)`${u.default.valCxt}.${u.default.instancePath}`),R.var(u.default.parentData,(0,c._)`${u.default.valCxt}.${u.default.parentData}`),R.var(u.default.parentDataProperty,(0,c._)`${u.default.valCxt}.${u.default.parentDataProperty}`),R.var(u.default.rootData,(0,c._)`${u.default.valCxt}.${u.default.rootData}`),T.dynamicRef&&R.var(u.default.dynamicAnchors,(0,c._)`${u.default.valCxt}.${u.default.dynamicAnchors}`)},()=>{R.var(u.default.instancePath,(0,c._)`""`),R.var(u.default.parentData,(0,c._)`undefined`),R.var(u.default.parentDataProperty,(0,c._)`undefined`),R.var(u.default.rootData,u.default.data),T.dynamicRef&&R.var(u.default.dynamicAnchors,(0,c._)`{}`)})}function y(R){let{schema:T,opts:D,gen:oe}=R;g(R,()=>{D.$comment&&T.$comment&&J(R),A(R),oe.let(u.default.vErrors,null),oe.let(u.default.errors,0),D.unevaluated&&S(R),j(R),te(R)})}function S(R){let{gen:T,validateName:D}=R;R.evaluated=T.const("evaluated",(0,c._)`${D}.evaluated`),T.if((0,c._)`${R.evaluated}.dynamicProps`,()=>T.assign((0,c._)`${R.evaluated}.props`,(0,c._)`undefined`)),T.if((0,c._)`${R.evaluated}.dynamicItems`,()=>T.assign((0,c._)`${R.evaluated}.items`,(0,c._)`undefined`))}function _(R,T){let D=typeof R=="object"&&R[T.schemaId];return D&&(T.code.source||T.code.process)?(0,c._)`/*# sourceURL=${D} */`:c.nil}function $(R,T){if(w(R)&&(E(R),k(R))){b(R,T);return}(0,t.boolOrEmptySchema)(R,T)}function k({schema:R,self:T}){if(typeof R=="boolean")return!R;for(let D in R)if(T.RULES.all[D])return!0;return!1}function w(R){return typeof R.schema!="boolean"}function b(R,T){let{schema:D,gen:oe,opts:ne}=R;ne.$comment&&D.$comment&&J(R),L(R),Z(R);let ie=oe.const("_errs",u.default.errors);j(R,ie),oe.var(T,(0,c._)`${ie} === ${u.default.errors}`)}function E(R){(0,d.checkUnknownRules)(R),V(R)}function j(R,T){if(R.opts.jtd)return ke(R,[],!1,T);let D=(0,r.getSchemaTypes)(R.schema);ke(R,D,!(0,r.coerceAndCheckDataType)(R,D),T)}function V(R){let{schema:T,errSchemaPath:D,opts:oe,self:ne}=R;T.$ref&&oe.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(T,ne.RULES)&&ne.logger.warn(`$ref: keywords ignored in schema at path "${D}"`)}function A(R){let{schema:T,opts:D}=R;T.default!==void 0&&D.useDefaults&&D.strictSchema&&(0,d.checkStrictMode)(R,"default is ignored in the schema root")}function L(R){let T=R.schema[R.opts.schemaId];T&&(R.baseId=(0,l.resolveUrl)(R.opts.uriResolver,R.baseId,T))}function Z(R){if(R.schema.$async&&!R.schemaEnv.$async)throw new Error("async schema in sync schema")}function J({gen:R,schemaEnv:T,schema:D,errSchemaPath:oe,opts:ne}){let ie=D.$comment;if(ne.$comment===!0)R.code((0,c._)`${u.default.self}.logger.log(${ie})`);else if(typeof ne.$comment=="function"){let me=(0,c.str)`${oe}/$comment`,Pe=R.scopeValue("root",{ref:T.root});R.code((0,c._)`${u.default.self}.opts.$comment(${ie}, ${me}, ${Pe}.schema)`)}}function te(R){let{gen:T,schemaEnv:D,validateName:oe,ValidationError:ne,opts:ie}=R;D.$async?T.if((0,c._)`${u.default.errors} === 0`,()=>T.return(u.default.data),()=>T.throw((0,c._)`new ${ne}(${u.default.vErrors})`)):(T.assign((0,c._)`${oe}.errors`,u.default.vErrors),ie.unevaluated&&_e(R),T.return((0,c._)`${u.default.errors} === 0`))}function _e({gen:R,evaluated:T,props:D,items:oe}){D instanceof c.Name&&R.assign((0,c._)`${T}.props`,D),oe instanceof c.Name&&R.assign((0,c._)`${T}.items`,oe)}function ke(R,T,D,oe){let{gen:ne,schema:ie,data:me,allErrors:Pe,opts:Ee,self:Ze}=R,{RULES:je}=Ze;if(ie.$ref&&(Ee.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(ie,je))){ne.block(()=>$e(R,"$ref",je.all.$ref.definition));return}Ee.jtd||be(R,T),ne.block(()=>{for(let nt of je.rules)De(nt);De(je.post)});function De(nt){(0,n.shouldUseGroup)(ie,nt)&&(nt.type?(ne.if((0,o.checkDataType)(nt.type,me,Ee.strictNumbers)),Ne(R,nt),T.length===1&&T[0]===nt.type&&D&&(ne.else(),(0,o.reportTypeError)(R)),ne.endIf()):Ne(R,nt),Pe||ne.if((0,c._)`${u.default.errors} === ${oe||0}`))}}function Ne(R,T){let{gen:D,schema:oe,opts:{useDefaults:ne}}=R;ne&&(0,i.assignDefaults)(R,T.type),D.block(()=>{for(let ie of T.rules)(0,n.shouldUseRule)(oe,ie)&&$e(R,ie.keyword,ie.definition,T.type)})}function be(R,T){R.schemaEnv.meta||!R.opts.strictTypes||(P(R,T),R.opts.allowUnionTypes||M(R,T),K(R,R.dataTypes))}function P(R,T){if(T.length){if(!R.dataTypes.length){R.dataTypes=T;return}T.forEach(D=>{I(R.dataTypes,D)||W(R,`type "${D}" not allowed by context "${R.dataTypes.join(",")}"`)}),O(R,T)}}function M(R,T){T.length>1&&!(T.length===2&&T.includes("null"))&&W(R,"use allowUnionTypes to allow union type keyword")}function K(R,T){let D=R.self.RULES.all;for(let oe in D){let ne=D[oe];if(typeof ne=="object"&&(0,n.shouldUseRule)(R.schema,ne)){let{type:ie}=ne.definition;ie.length&&!ie.some(me=>z(T,me))&&W(R,`missing type "${ie.join(",")}" for keyword "${oe}"`)}}}function z(R,T){return R.includes(T)||T==="number"&&R.includes("integer")}function I(R,T){return R.includes(T)||T==="integer"&&R.includes("number")}function O(R,T){let D=[];for(let oe of R.dataTypes)I(T,oe)?D.push(oe):T.includes("integer")&&oe==="number"&&D.push("integer");R.dataTypes=D}function W(R,T){let D=R.schemaEnv.baseId+R.errSchemaPath;T+=` at "${D}" (strictTypes)`,(0,d.checkStrictMode)(R,T,R.opts.strictTypes)}var ce=class{constructor(R,T,D){if((0,a.validateKeywordUsage)(R,T,D),this.gen=R.gen,this.allErrors=R.allErrors,this.keyword=D,this.data=R.data,this.schema=R.schema[D],this.$data=T.$data&&R.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(R,this.schema,D,this.$data),this.schemaType=T.schemaType,this.parentSchema=R.schema,this.params={},this.it=R,this.def=T,this.$data)this.schemaCode=R.gen.const("vSchema",Fe(this.$data,R));else if(this.schemaCode=this.schemaValue,!(0,a.validSchemaType)(this.schema,T.schemaType,T.allowUndefined))throw new Error(`${D} value must be ${JSON.stringify(T.schemaType)}`);("code"in T?T.trackErrors:T.errors!==!1)&&(this.errsCount=R.gen.const("_errs",u.default.errors))}result(R,T,D){this.failResult((0,c.not)(R),T,D)}failResult(R,T,D){this.gen.if(R),D?D():this.error(),T?(this.gen.else(),T(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(R,T){this.failResult((0,c.not)(R),void 0,T)}fail(R){if(R===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(R),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(R){if(!this.$data)return this.fail(R);let{schemaCode:T}=this;this.fail((0,c._)`${T} !== undefined && (${(0,c.or)(this.invalid$data(),R)})`)}error(R,T,D){if(T){this.setParams(T),this._error(R,D),this.setParams({});return}this._error(R,D)}_error(R,T){(R?m.reportExtraError:m.reportError)(this,this.def.error,T)}$dataError(){(0,m.reportError)(this,this.def.$dataError||m.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,m.resetErrorsCount)(this.gen,this.errsCount)}ok(R){this.allErrors||this.gen.if(R)}setParams(R,T){T?Object.assign(this.params,R):this.params=R}block$data(R,T,D=c.nil){this.gen.block(()=>{this.check$data(R,D),T()})}check$data(R=c.nil,T=c.nil){if(!this.$data)return;let{gen:D,schemaCode:oe,schemaType:ne,def:ie}=this;D.if((0,c.or)((0,c._)`${oe} === undefined`,T)),R!==c.nil&&D.assign(R,!0),(ne.length||ie.validateSchema)&&(D.elseIf(this.invalid$data()),this.$dataError(),R!==c.nil&&D.assign(R,!1)),D.else()}invalid$data(){let{gen:R,schemaCode:T,schemaType:D,def:oe,it:ne}=this;return(0,c.or)(ie(),me());function ie(){if(D.length){if(!(T instanceof c.Name))throw new Error("ajv implementation error");let Pe=Array.isArray(D)?D:[D];return(0,c._)`${(0,o.checkDataTypes)(Pe,T,ne.opts.strictNumbers,o.DataType.Wrong)}`}return c.nil}function me(){if(oe.validateSchema){let Pe=R.scopeValue("validate$data",{ref:oe.validateSchema});return(0,c._)`!${Pe}(${T})`}return c.nil}}subschema(R,T){let D=(0,s.getSubschema)(this.it,R);(0,s.extendSubschemaData)(D,this.it,R),(0,s.extendSubschemaMode)(D,R);let oe={...this.it,...D,items:void 0,props:void 0};return $(oe,T),oe}mergeEvaluated(R,T){let{it:D,gen:oe}=this;D.opts.unevaluated&&(D.props!==!0&&R.props!==void 0&&(D.props=d.mergeEvaluated.props(oe,R.props,D.props,T)),D.items!==!0&&R.items!==void 0&&(D.items=d.mergeEvaluated.items(oe,R.items,D.items,T)))}mergeValidEvaluated(R,T){let{it:D,gen:oe}=this;if(D.opts.unevaluated&&(D.props!==!0||D.items!==!0))return oe.if(T,()=>this.mergeEvaluated(R,c.Name)),!0}};e.KeywordCxt=ce;function $e(R,T,D,oe){let ne=new ce(R,D,T);"code"in D?D.code(ne,oe):ne.$data&&D.validate?(0,a.funcKeywordCode)(ne,D):"macro"in D?(0,a.macroKeywordCode)(ne,D):(D.compile||D.validate)&&(0,a.funcKeywordCode)(ne,D)}let B=/^\/(?:[^~]|~0|~1)*$/,Re=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Fe(R,{dataLevel:T,dataNames:D,dataPathArr:oe}){let ne,ie;if(R==="")return u.default.rootData;if(R[0]==="/"){if(!B.test(R))throw new Error(`Invalid JSON-pointer: ${R}`);ne=R,ie=u.default.rootData}else{let Ze=Re.exec(R);if(!Ze)throw new Error(`Invalid JSON-pointer: ${R}`);let je=+Ze[1];if(ne=Ze[2],ne==="#"){if(je>=T)throw new Error(Ee("property/index",je));return oe[T-je]}if(je>T)throw new Error(Ee("data",je));if(ie=D[T-je],!ne)return ie}let me=ie,Pe=ne.split("/");for(let Ze of Pe)Ze&&(ie=(0,c._)`${ie}${(0,c.getProperty)((0,d.unescapeJsonPointer)(Ze))}`,me=(0,c._)`${me} && ${ie}`);return me;function Ee(Ze,je){return`Cannot access ${Ze} ${je} levels up, current level is ${T}`}}e.getData=Fe})),ld=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=class extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}};e.default=t})),gs=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ud();var r=class extends Error{constructor(n,o,i,a){super(a||`can't resolve reference ${i} from id ${o}`),this.missingRef=(0,t.resolveUrl)(n,o,i),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(n,this.missingRef))}};e.default=r})),dd=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=ze(),r=ld(),n=Gt(),o=ud(),i=Te(),a=hs();var s=class{constructor(y){var S;this.refs={},this.dynamicAnchors={};let _;typeof y.schema=="object"&&(_=y.schema),this.schema=y.schema,this.schemaId=y.schemaId,this.root=y.root||this,this.baseId=(S=y.baseId)!==null&&S!==void 0?S:(0,o.normalizeId)(_?.[y.schemaId||"$id"]),this.schemaPath=y.schemaPath,this.localRefs=y.localRefs,this.meta=y.meta,this.$async=_?.$async,this.refs={}}};e.SchemaEnv=s;function c(y){let S=d.call(this,y);if(S)return S;let _=(0,o.getFullPath)(this.opts.uriResolver,y.root.baseId),{es5:$,lines:k}=this.opts.code,{ownProperties:w}=this.opts,b=new t.CodeGen(this.scope,{es5:$,lines:k,ownProperties:w}),E;y.$async&&(E=b.scopeValue("Error",{ref:r.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let j=b.scopeName("validate");y.validateName=j;let V={gen:b,allErrors:this.opts.allErrors,data:n.default.data,parentData:n.default.parentData,parentDataProperty:n.default.parentDataProperty,dataNames:[n.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:b.scopeValue("schema",this.opts.code.source===!0?{ref:y.schema,code:(0,t.stringify)(y.schema)}:{ref:y.schema}),validateName:j,ValidationError:E,schema:y.schema,schemaEnv:y,rootId:_,baseId:y.baseId||_,schemaPath:t.nil,errSchemaPath:y.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,t._)`""`,opts:this.opts,self:this},A;try{this._compilations.add(y),(0,a.validateFunctionCode)(V),b.optimize(this.opts.code.optimize);let L=b.toString();A=`${b.scopeRefs(n.default.scope)}return ${L}`,this.opts.code.process&&(A=this.opts.code.process(A,y));let Z=new Function(`${n.default.self}`,`${n.default.scope}`,A)(this,this.scope.get());if(this.scope.value(j,{ref:Z}),Z.errors=null,Z.schema=y.schema,Z.schemaEnv=y,y.$async&&(Z.$async=!0),this.opts.code.source===!0&&(Z.source={validateName:j,validateCode:L,scopeValues:b._values}),this.opts.unevaluated){let{props:J,items:te}=V;Z.evaluated={props:J instanceof t.Name?void 0:J,items:te instanceof t.Name?void 0:te,dynamicProps:J instanceof t.Name,dynamicItems:te instanceof t.Name},Z.source&&(Z.source.evaluated=(0,t.stringify)(Z.evaluated))}return y.validate=Z,y}catch(L){throw delete y.validate,delete y.validateName,A&&this.logger.error("Error compiling schema, function code:",A),L}finally{this._compilations.delete(y)}}e.compileSchema=c;function u(y,S,_){var $;_=(0,o.resolveUrl)(this.opts.uriResolver,S,_);let k=y.refs[_];if(k)return k;let w=v.call(this,y,_);if(w===void 0){let b=($=y.localRefs)===null||$===void 0?void 0:$[_],{schemaId:E}=this.opts;b&&(w=new s({schema:b,schemaId:E,root:y,baseId:S}))}if(w!==void 0)return y.refs[_]=l.call(this,w)}e.resolveRef=u;function l(y){return(0,o.inlineRef)(y.schema,this.opts.inlineRefs)?y.schema:y.validate?y:c.call(this,y)}function d(y){for(let S of this._compilations)if(m(S,y))return S}e.getCompilingSchema=d;function m(y,S){return y.schema===S.schema&&y.root===S.root&&y.baseId===S.baseId}function v(y,S){let _;for(;typeof(_=this.refs[S])=="string";)S=_;return _||this.schemas[S]||g.call(this,y,S)}function g(y,S){let _=this.opts.uriResolver.parse(S),$=(0,o._getFullPath)(this.opts.uriResolver,_),k=(0,o.getFullPath)(this.opts.uriResolver,y.baseId,void 0);if(Object.keys(y.schema).length>0&&$===k)return f.call(this,_,y);let w=(0,o.normalizeId)($),b=this.refs[w]||this.schemas[w];if(typeof b=="string"){let E=g.call(this,y,b);return typeof E?.schema!="object"?void 0:f.call(this,_,E)}if(typeof b?.schema=="object"){if(b.validate||c.call(this,b),w===(0,o.normalizeId)(S)){let{schema:E}=b,{schemaId:j}=this.opts,V=E[j];return V&&(k=(0,o.resolveUrl)(this.opts.uriResolver,k,V)),new s({schema:E,schemaId:j,root:y,baseId:k})}return f.call(this,_,b)}}e.resolveSchema=g;let h=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function f(y,{baseId:S,schema:_,root:$}){var k;if(((k=y.fragment)===null||k===void 0?void 0:k[0])!=="/")return;for(let E of y.fragment.slice(1).split("/")){if(typeof _=="boolean")return;let j=_[(0,i.unescapeFragment)(E)];if(j===void 0)return;_=j;let V=typeof _=="object"&&_[this.opts.schemaId];!h.has(E)&&V&&(S=(0,o.resolveUrl)(this.opts.uriResolver,S,V))}let w;if(typeof _!="boolean"&&_.$ref&&!(0,i.schemaHasRulesButRef)(_,this.RULES)){let E=(0,o.resolveUrl)(this.opts.uriResolver,S,_.$ref);w=g.call(this,$,E)}let{schemaId:b}=this.opts;if(w=w||new s({schema:_,schemaId:b,root:$,baseId:S}),w.schema!==w.root.schema)return w}})),bP=H(((e,t)=>{t.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}})),ez=H(((e,t)=>{let r=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),n=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function o(g){let h="",f=0,y=0;for(y=0;y=48&&f<=57||f>=65&&f<=70||f>=97&&f<=102))return"";h+=g[y];break}for(y+=1;y=48&&f<=57||f>=65&&f<=70||f>=97&&f<=102))return"";h+=g[y]}return h}let i=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function a(g){return g.length=0,!0}function s(g,h,f){if(g.length){let y=o(g);if(y!=="")h.push(y);else return f.error=!0,!1;g.length=0}return!0}function c(g){let h=0,f={error:!1,address:"",zone:""},y=[],S=[],_=!1,$=!1,k=s;for(let w=0;w7){f.error=!0;break}w>0&&g[w-1]===":"&&(_=!0),y.push(":");continue}else if(b==="%"){if(!k(S,y,f))break;k=a}else{S.push(b);continue}}return S.length&&(k===a?f.zone=S.join(""):$?y.push(S.join("")):y.push(o(S))),f.address=y.join(""),f}function u(g){if(l(g,":")<2)return{host:g,isIPV6:!1};let h=c(g);if(h.error)return{host:g,isIPV6:!1};{let f=h.address,y=h.address;return h.zone&&(f+="%"+h.zone,y+="%25"+h.zone),{host:f,isIPV6:!0,escapedHost:y}}}function l(g,h){let f=0;for(let y=0;y{let{isUUID:r}=ez(),n=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,o=["http","https","ws","wss","urn","urn:uuid"];function i(b){return o.indexOf(b)!==-1}function a(b){return b.secure===!0?!0:b.secure===!1?!1:b.scheme?b.scheme.length===3&&(b.scheme[0]==="w"||b.scheme[0]==="W")&&(b.scheme[1]==="s"||b.scheme[1]==="S")&&(b.scheme[2]==="s"||b.scheme[2]==="S"):!1}function s(b){return b.host||(b.error=b.error||"HTTP URIs must have a host."),b}function c(b){let E=String(b.scheme).toLowerCase()==="https";return(b.port===(E?443:80)||b.port==="")&&(b.port=void 0),b.path||(b.path="/"),b}function u(b){return b.secure=a(b),b.resourceName=(b.path||"/")+(b.query?"?"+b.query:""),b.path=void 0,b.query=void 0,b}function l(b){if((b.port===(a(b)?443:80)||b.port==="")&&(b.port=void 0),typeof b.secure=="boolean"&&(b.scheme=b.secure?"wss":"ws",b.secure=void 0),b.resourceName){let[E,j]=b.resourceName.split("?");b.path=E&&E!=="/"?E:void 0,b.query=j,b.resourceName=void 0}return b.fragment=void 0,b}function d(b,E){if(!b.path)return b.error="URN can not be parsed",b;let j=b.path.match(n);if(j){let V=E.scheme||b.scheme||"urn";b.nid=j[1].toLowerCase(),b.nss=j[2];let A=w(`${V}:${E.nid||b.nid}`);b.path=void 0,A&&(b=A.parse(b,E))}else b.error=b.error||"URN can not be parsed.";return b}function m(b,E){if(b.nid===void 0)throw new Error("URN without nid cannot be serialized");let j=E.scheme||b.scheme||"urn",V=b.nid.toLowerCase(),A=w(`${j}:${E.nid||V}`);A&&(b=A.serialize(b,E));let L=b,Z=b.nss;return L.path=`${V||E.nid}:${Z}`,E.skipEscape=!0,L}function v(b,E){let j=b;return j.uuid=j.nss,j.nss=void 0,!E.tolerant&&(!j.uuid||!r(j.uuid))&&(j.error=j.error||"UUID is not valid."),j}function g(b){let E=b;return E.nss=(b.uuid||"").toLowerCase(),E}let h={scheme:"http",domainHost:!0,parse:s,serialize:c},f={scheme:"https",domainHost:h.domainHost,parse:s,serialize:c},y={scheme:"ws",domainHost:!0,parse:u,serialize:l},S={scheme:"wss",domainHost:y.domainHost,parse:y.parse,serialize:y.serialize},k={http:h,https:f,ws:y,wss:S,urn:{scheme:"urn",parse:d,serialize:m,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:v,serialize:g,skipNormalize:!0}};Object.setPrototypeOf(k,null);function w(b){return b&&(k[b]||k[b.toLowerCase()])||void 0}t.exports={wsIsSecure:a,SCHEMES:k,isValidSchemeName:i,getSchemeHandler:w}})),wP=H(((e,t)=>{let{normalizeIPv6:r,removeDotSegments:n,recomposeAuthority:o,normalizeComponentEncoding:i,isIPv4:a,nonSimpleDomain:s}=ez(),{SCHEMES:c,getSchemeHandler:u}=$P();function l(S,_){return typeof S=="string"?S=g(f(S,_),_):typeof S=="object"&&(S=f(g(S,_),_)),S}function d(S,_,$){let k=$?Object.assign({scheme:"null"},$):{scheme:"null"},w=m(f(S,k),f(_,k),k,!0);return k.skipEscape=!0,g(w,k)}function m(S,_,$,k){let w={};return k||(S=f(g(S,$),$),_=f(g(_,$),$)),$=$||{},!$.tolerant&&_.scheme?(w.scheme=_.scheme,w.userinfo=_.userinfo,w.host=_.host,w.port=_.port,w.path=n(_.path||""),w.query=_.query):(_.userinfo!==void 0||_.host!==void 0||_.port!==void 0?(w.userinfo=_.userinfo,w.host=_.host,w.port=_.port,w.path=n(_.path||""),w.query=_.query):(_.path?(_.path[0]==="/"?w.path=n(_.path):((S.userinfo!==void 0||S.host!==void 0||S.port!==void 0)&&!S.path?w.path="/"+_.path:S.path?w.path=S.path.slice(0,S.path.lastIndexOf("/")+1)+_.path:w.path=_.path,w.path=n(w.path)),w.query=_.query):(w.path=S.path,_.query!==void 0?w.query=_.query:w.query=S.query),w.userinfo=S.userinfo,w.host=S.host,w.port=S.port),w.scheme=S.scheme),w.fragment=_.fragment,w}function v(S,_,$){return typeof S=="string"?(S=unescape(S),S=g(i(f(S,$),!0),{...$,skipEscape:!0})):typeof S=="object"&&(S=g(i(S,!0),{...$,skipEscape:!0})),typeof _=="string"?(_=unescape(_),_=g(i(f(_,$),!0),{...$,skipEscape:!0})):typeof _=="object"&&(_=g(i(_,!0),{...$,skipEscape:!0})),S.toLowerCase()===_.toLowerCase()}function g(S,_){let $={host:S.host,scheme:S.scheme,userinfo:S.userinfo,port:S.port,path:S.path,query:S.query,nid:S.nid,nss:S.nss,uuid:S.uuid,fragment:S.fragment,reference:S.reference,resourceName:S.resourceName,secure:S.secure,error:""},k=Object.assign({},_),w=[],b=u(k.scheme||$.scheme);b&&b.serialize&&b.serialize($,k),$.path!==void 0&&(k.skipEscape?$.path=unescape($.path):($.path=escape($.path),$.scheme!==void 0&&($.path=$.path.split("%3A").join(":")))),k.reference!=="suffix"&&$.scheme&&w.push($.scheme,":");let E=o($);if(E!==void 0&&(k.reference!=="suffix"&&w.push("//"),w.push(E),$.path&&$.path[0]!=="/"&&w.push("/")),$.path!==void 0){let j=$.path;!k.absolutePath&&(!b||!b.absolutePath)&&(j=n(j)),E===void 0&&j[0]==="/"&&j[1]==="/"&&(j="/%2F"+j.slice(2)),w.push(j)}return $.query!==void 0&&w.push("?",$.query),$.fragment!==void 0&&w.push("#",$.fragment),w.join("")}let h=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function f(S,_){let $=Object.assign({},_),k={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},w=!1;$.reference==="suffix"&&($.scheme?S=$.scheme+":"+S:S="//"+S);let b=S.match(h);if(b){if(k.scheme=b[1],k.userinfo=b[3],k.host=b[4],k.port=parseInt(b[5],10),k.path=b[6]||"",k.query=b[7],k.fragment=b[8],isNaN(k.port)&&(k.port=b[5]),k.host)if(a(k.host)===!1){let j=r(k.host);k.host=j.host.toLowerCase(),w=j.isIPV6}else w=!0;k.scheme===void 0&&k.userinfo===void 0&&k.host===void 0&&k.port===void 0&&k.query===void 0&&!k.path?k.reference="same-document":k.scheme===void 0?k.reference="relative":k.fragment===void 0?k.reference="absolute":k.reference="uri",$.reference&&$.reference!=="suffix"&&$.reference!==k.reference&&(k.error=k.error||"URI is not a "+$.reference+" reference.");let E=u($.scheme||k.scheme);if(!$.unicodeSupport&&(!E||!E.unicodeSupport)&&k.host&&($.domainHost||E&&E.domainHost)&&w===!1&&s(k.host))try{k.host=URL.domainToASCII(k.host.toLowerCase())}catch(j){k.error=k.error||"Host's domain name can not be converted to ASCII: "+j}(!E||E&&!E.skipNormalize)&&(S.indexOf("%")!==-1&&(k.scheme!==void 0&&(k.scheme=unescape(k.scheme)),k.host!==void 0&&(k.host=unescape(k.host))),k.path&&(k.path=escape(unescape(k.path))),k.fragment&&(k.fragment=encodeURI(decodeURIComponent(k.fragment)))),E&&E.parse&&E.parse(k,$)}else k.error=k.error||"URI can not be parsed.";return k}let y={SCHEMES:c,normalize:l,resolve:d,resolveComponent:m,equal:v,serialize:g,parse:f};t.exports=y,t.exports.default=y,t.exports.fastUri=y})),zP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=wP();t.code='require("ajv/dist/runtime/uri").default',e.default=t})),tz=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=hs();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=ze();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});let n=ld(),o=gs(),i=Xw(),a=dd(),s=ze(),c=ud(),u=sd(),l=Te(),d=bP(),m=zP(),v=(P,M)=>new RegExp(P,M);v.code="new RegExp";let g=["removeAdditional","useDefaults","coerceTypes"],h=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),f={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},y={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},S=200;function _(P){var M,K,z,I,O,W,ce,$e,B,Re,Fe,R,T,D,oe,ne,ie,me,Pe,Ee,Ze,je,De,nt,Jt;let yt=P.strict,ut=(M=P.code)===null||M===void 0?void 0:M.optimize,Ft=ut===!0||ut===void 0?1:ut||0,rr=(z=(K=P.code)===null||K===void 0?void 0:K.regExp)!==null&&z!==void 0?z:v,hn=(I=P.uriResolver)!==null&&I!==void 0?I:m.default;return{strictSchema:(W=(O=P.strictSchema)!==null&&O!==void 0?O:yt)!==null&&W!==void 0?W:!0,strictNumbers:($e=(ce=P.strictNumbers)!==null&&ce!==void 0?ce:yt)!==null&&$e!==void 0?$e:!0,strictTypes:(Re=(B=P.strictTypes)!==null&&B!==void 0?B:yt)!==null&&Re!==void 0?Re:"log",strictTuples:(R=(Fe=P.strictTuples)!==null&&Fe!==void 0?Fe:yt)!==null&&R!==void 0?R:"log",strictRequired:(D=(T=P.strictRequired)!==null&&T!==void 0?T:yt)!==null&&D!==void 0?D:!1,code:P.code?{...P.code,optimize:Ft,regExp:rr}:{optimize:Ft,regExp:rr},loopRequired:(oe=P.loopRequired)!==null&&oe!==void 0?oe:S,loopEnum:(ne=P.loopEnum)!==null&&ne!==void 0?ne:S,meta:(ie=P.meta)!==null&&ie!==void 0?ie:!0,messages:(me=P.messages)!==null&&me!==void 0?me:!0,inlineRefs:(Pe=P.inlineRefs)!==null&&Pe!==void 0?Pe:!0,schemaId:(Ee=P.schemaId)!==null&&Ee!==void 0?Ee:"$id",addUsedSchema:(Ze=P.addUsedSchema)!==null&&Ze!==void 0?Ze:!0,validateSchema:(je=P.validateSchema)!==null&&je!==void 0?je:!0,validateFormats:(De=P.validateFormats)!==null&&De!==void 0?De:!0,unicodeRegExp:(nt=P.unicodeRegExp)!==null&&nt!==void 0?nt:!0,int32range:(Jt=P.int32range)!==null&&Jt!==void 0?Jt:!0,uriResolver:hn}}var $=class{constructor(P={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,P=this.opts={...P,..._(P)};let{es5:M,lines:K}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:M,lines:K}),this.logger=L(P.logger);let z=P.validateFormats;P.validateFormats=!1,this.RULES=(0,i.getRules)(),k.call(this,f,P,"NOT SUPPORTED"),k.call(this,y,P,"DEPRECATED","warn"),this._metaOpts=V.call(this),P.formats&&E.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),P.keywords&&j.call(this,P.keywords),typeof P.meta=="object"&&this.addMetaSchema(P.meta),b.call(this),P.validateFormats=z}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:P,meta:M,schemaId:K}=this.opts,z=d;K==="id"&&(z={...d},z.id=z.$id,delete z.$id),M&&P&&this.addMetaSchema(z,z[K],!1)}defaultMeta(){let{meta:P,schemaId:M}=this.opts;return this.opts.defaultMeta=typeof P=="object"?P[M]||P:void 0}validate(P,M){let K;if(typeof P=="string"){if(K=this.getSchema(P),!K)throw new Error(`no schema with key or ref "${P}"`)}else K=this.compile(P);let z=K(M);return"$async"in K||(this.errors=K.errors),z}compile(P,M){let K=this._addSchema(P,M);return K.validate||this._compileSchemaEnv(K)}compileAsync(P,M){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:K}=this.opts;return z.call(this,P,M);async function z(B,Re){await I.call(this,B.$schema);let Fe=this._addSchema(B,Re);return Fe.validate||O.call(this,Fe)}async function I(B){B&&!this.getSchema(B)&&await z.call(this,{$ref:B},!0)}async function O(B){try{return this._compileSchemaEnv(B)}catch(Re){if(!(Re instanceof o.default))throw Re;return W.call(this,Re),await ce.call(this,Re.missingSchema),O.call(this,B)}}function W({missingSchema:B,missingRef:Re}){if(this.refs[B])throw new Error(`AnySchema ${B} is loaded but ${Re} cannot be resolved`)}async function ce(B){let Re=await $e.call(this,B);this.refs[B]||await I.call(this,Re.$schema),this.refs[B]||this.addSchema(Re,B,M)}async function $e(B){let Re=this._loading[B];if(Re)return Re;try{return await(this._loading[B]=K(B))}finally{delete this._loading[B]}}}addSchema(P,M,K,z=this.opts.validateSchema){if(Array.isArray(P)){for(let O of P)this.addSchema(O,void 0,K,z);return this}let I;if(typeof P=="object"){let{schemaId:O}=this.opts;if(I=P[O],I!==void 0&&typeof I!="string")throw new Error(`schema ${O} must be string`)}return M=(0,c.normalizeId)(M||I),this._checkUnique(M),this.schemas[M]=this._addSchema(P,K,M,z,!0),this}addMetaSchema(P,M,K=this.opts.validateSchema){return this.addSchema(P,M,!0,K),this}validateSchema(P,M){if(typeof P=="boolean")return!0;let K;if(K=P.$schema,K!==void 0&&typeof K!="string")throw new Error("$schema must be a string");if(K=K||this.opts.defaultMeta||this.defaultMeta(),!K)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let z=this.validate(K,P);if(!z&&M){let I="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(I);else throw new Error(I)}return z}getSchema(P){let M;for(;typeof(M=w.call(this,P))=="string";)P=M;if(M===void 0){let{schemaId:K}=this.opts,z=new a.SchemaEnv({schema:{},schemaId:K});if(M=a.resolveSchema.call(this,z,P),!M)return;this.refs[P]=M}return M.validate||this._compileSchemaEnv(M)}removeSchema(P){if(P instanceof RegExp)return this._removeAllSchemas(this.schemas,P),this._removeAllSchemas(this.refs,P),this;switch(typeof P){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let M=w.call(this,P);return typeof M=="object"&&this._cache.delete(M.schema),delete this.schemas[P],delete this.refs[P],this}case"object":{let M=P;this._cache.delete(M);let K=P[this.opts.schemaId];return K&&(K=(0,c.normalizeId)(K),delete this.schemas[K],delete this.refs[K]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(P){for(let M of P)this.addKeyword(M);return this}addKeyword(P,M){let K;if(typeof P=="string")K=P,typeof M=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),M.keyword=K);else if(typeof P=="object"&&M===void 0){if(M=P,K=M.keyword,Array.isArray(K)&&!K.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(J.call(this,K,M),!M)return(0,l.eachItem)(K,I=>te.call(this,I)),this;ke.call(this,M);let z={...M,type:(0,u.getJSONTypes)(M.type),schemaType:(0,u.getJSONTypes)(M.schemaType)};return(0,l.eachItem)(K,z.type.length===0?I=>te.call(this,I,z):I=>z.type.forEach(O=>te.call(this,I,z,O))),this}getKeyword(P){let M=this.RULES.all[P];return typeof M=="object"?M.definition:!!M}removeKeyword(P){let{RULES:M}=this;delete M.keywords[P],delete M.all[P];for(let K of M.rules){let z=K.rules.findIndex(I=>I.keyword===P);z>=0&&K.rules.splice(z,1)}return this}addFormat(P,M){return typeof M=="string"&&(M=new RegExp(M)),this.formats[P]=M,this}errorsText(P=this.errors,{separator:M=", ",dataVar:K="data"}={}){return!P||P.length===0?"No errors":P.map(z=>`${K}${z.instancePath} ${z.message}`).reduce((z,I)=>z+M+I)}$dataMetaSchema(P,M){let K=this.RULES.all;P=JSON.parse(JSON.stringify(P));for(let z of M){let I=z.split("/").slice(1),O=P;for(let W of I)O=O[W];for(let W in K){let ce=K[W];if(typeof ce!="object")continue;let{$data:$e}=ce.definition,B=O[W];$e&&B&&(O[W]=be(B))}}return P}_removeAllSchemas(P,M){for(let K in P){let z=P[K];(!M||M.test(K))&&(typeof z=="string"?delete P[K]:z&&!z.meta&&(this._cache.delete(z.schema),delete P[K]))}}_addSchema(P,M,K,z=this.opts.validateSchema,I=this.opts.addUsedSchema){let O,{schemaId:W}=this.opts;if(typeof P=="object")O=P[W];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof P!="boolean")throw new Error("schema must be object or boolean")}let ce=this._cache.get(P);if(ce!==void 0)return ce;K=(0,c.normalizeId)(O||K);let $e=c.getSchemaRefs.call(this,P,K);return ce=new a.SchemaEnv({schema:P,schemaId:W,meta:M,baseId:K,localRefs:$e}),this._cache.set(ce.schema,ce),I&&!K.startsWith("#")&&(K&&this._checkUnique(K),this.refs[K]=ce),z&&this.validateSchema(P,!0),ce}_checkUnique(P){if(this.schemas[P]||this.refs[P])throw new Error(`schema with key or id "${P}" already exists`)}_compileSchemaEnv(P){if(P.meta?this._compileMetaSchema(P):a.compileSchema.call(this,P),!P.validate)throw new Error("ajv implementation error");return P.validate}_compileMetaSchema(P){let M=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,P)}finally{this.opts=M}}};$.ValidationError=n.default,$.MissingRefError=o.default,e.default=$;function k(P,M,K,z="error"){for(let I in P){let O=I;O in M&&this.logger[z](`${K}: option ${I}. ${P[O]}`)}}function w(P){return P=(0,c.normalizeId)(P),this.schemas[P]||this.refs[P]}function b(){let P=this.opts.schemas;if(P)if(Array.isArray(P))this.addSchema(P);else for(let M in P)this.addSchema(P[M],M)}function E(){for(let P in this.opts.formats){let M=this.opts.formats[P];M&&this.addFormat(P,M)}}function j(P){if(Array.isArray(P)){this.addVocabulary(P);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let M in P){let K=P[M];K.keyword||(K.keyword=M),this.addKeyword(K)}}function V(){let P={...this.opts};for(let M of g)delete P[M];return P}let A={log(){},warn(){},error(){}};function L(P){if(P===!1)return A;if(P===void 0)return console;if(P.log&&P.warn&&P.error)return P;throw new Error("logger must implement log, warn and error methods")}let Z=/^[a-z_$][a-z0-9_$:-]*$/i;function J(P,M){let{RULES:K}=this;if((0,l.eachItem)(P,z=>{if(K.keywords[z])throw new Error(`Keyword ${z} is already defined`);if(!Z.test(z))throw new Error(`Keyword ${z} has invalid name`)}),!!M&&M.$data&&!("code"in M||"validate"in M))throw new Error('$data keyword must have "code" or "validate" function')}function te(P,M,K){var z;let I=M?.post;if(K&&I)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:O}=this,W=I?O.post:O.rules.find(({type:$e})=>$e===K);if(W||(W={type:K,rules:[]},O.rules.push(W)),O.keywords[P]=!0,!M)return;let ce={keyword:P,definition:{...M,type:(0,u.getJSONTypes)(M.type),schemaType:(0,u.getJSONTypes)(M.schemaType)}};M.before?_e.call(this,W,ce,M.before):W.rules.push(ce),O.all[P]=ce,(z=M.implements)===null||z===void 0||z.forEach($e=>this.addKeyword($e))}function _e(P,M,K){let z=P.rules.findIndex(I=>I.keyword===K);z>=0?P.rules.splice(z,0,M):(P.rules.push(M),this.logger.warn(`rule ${K} is not defined`))}function ke(P){let{metaSchema:M}=P;M!==void 0&&(P.$data&&this.opts.$data&&(M=be(M)),P.validateSchema=this.compile(M,!0))}let Ne={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function be(P){return{anyOf:[P,Ne]}}})),kP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};e.default=t})),dg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;let t=gs(),r=Xt(),n=ze(),o=Gt(),i=dd(),a=Te(),s={keyword:"$ref",schemaType:"string",code(l){let{gen:d,schema:m,it:v}=l,{baseId:g,schemaEnv:h,validateName:f,opts:y,self:S}=v,{root:_}=h;if((m==="#"||m==="#/")&&g===_.baseId)return k();let $=i.resolveRef.call(S,_,g,m);if($===void 0)throw new t.default(v.opts.uriResolver,g,m);if($ instanceof i.SchemaEnv)return w($);return b($);function k(){if(h===_)return u(l,f,h,h.$async);let E=d.scopeValue("root",{ref:_});return u(l,(0,n._)`${E}.validate`,_,_.$async)}function w(E){u(l,c(l,E),E,E.$async)}function b(E){let j=d.scopeValue("schema",y.code.source===!0?{ref:E,code:(0,n.stringify)(E)}:{ref:E}),V=d.name("valid"),A=l.subschema({schema:E,dataTypes:[],schemaPath:n.nil,topSchemaRef:j,errSchemaPath:m},V);l.mergeEvaluated(A),l.ok(V)}}};function c(l,d){let{gen:m}=l;return d.validate?m.scopeValue("validate",{ref:d.validate}):(0,n._)`${m.scopeValue("wrapper",{ref:d})}.validate`}e.getValidate=c;function u(l,d,m,v){let{gen:g,it:h}=l,{allErrors:f,schemaEnv:y,opts:S}=h,_=S.passContext?o.default.this:n.nil;v?$():k();function $(){if(!y.$async)throw new Error("async schema referenced by sync schema");let E=g.let("valid");g.try(()=>{g.code((0,n._)`await ${(0,r.callValidateCode)(l,d,_)}`),b(d),f||g.assign(E,!0)},j=>{g.if((0,n._)`!(${j} instanceof ${h.ValidationError})`,()=>g.throw(j)),w(j),f||g.assign(E,!1)}),l.ok(E)}function k(){l.result((0,r.callValidateCode)(l,d,_),()=>b(d),()=>w(d))}function w(E){let j=(0,n._)`${E}.errors`;g.assign(o.default.vErrors,(0,n._)`${o.default.vErrors} === null ? ${j} : ${o.default.vErrors}.concat(${j})`),g.assign(o.default.errors,(0,n._)`${o.default.vErrors}.length`)}function b(E){var j;if(!h.opts.unevaluated)return;let V=(j=m?.validate)===null||j===void 0?void 0:j.evaluated;if(h.props!==!0)if(V&&!V.dynamicProps)V.props!==void 0&&(h.props=a.mergeEvaluated.props(g,V.props,h.props));else{let A=g.var("props",(0,n._)`${E}.evaluated.props`);h.props=a.mergeEvaluated.props(g,A,h.props,n.Name)}if(h.items!==!0)if(V&&!V.dynamicItems)V.items!==void 0&&(h.items=a.mergeEvaluated.items(g,V.items,h.items));else{let A=g.var("items",(0,n._)`${E}.evaluated.items`);h.items=a.mergeEvaluated.items(g,A,h.items,n.Name)}}}e.callRef=u,e.default=s})),rz=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=kP(),r=dg(),n=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",t.default,r.default];e.default=n})),EP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r=t.operators,n={maximum:{okStr:"<=",ok:r.LTE,fail:r.GT},minimum:{okStr:">=",ok:r.GTE,fail:r.LT},exclusiveMaximum:{okStr:"<",ok:r.LT,fail:r.GTE},exclusiveMinimum:{okStr:">",ok:r.GT,fail:r.LTE}},o={keyword:Object.keys(n),type:"number",schemaType:"number",$data:!0,error:{message:({keyword:i,schemaCode:a})=>(0,t.str)`must be ${n[i].okStr} ${a}`,params:({keyword:i,schemaCode:a})=>(0,t._)`{comparison: ${n[i].okStr}, limit: ${a}}`},code(i){let{keyword:a,data:s,schemaCode:c}=i;i.fail$data((0,t._)`${s} ${n[a].fail} ${c} || isNaN(${s})`)}};e.default=o})),RP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:n})=>(0,t.str)`must be multiple of ${n}`,params:({schemaCode:n})=>(0,t._)`{multipleOf: ${n}}`},code(n){let{gen:o,data:i,schemaCode:a,it:s}=n,c=s.opts.multipleOfPrecision,u=o.let("res"),l=c?(0,t._)`Math.abs(Math.round(${u}) - ${u}) > 1e-${c}`:(0,t._)`${u} !== parseInt(${u})`;n.fail$data((0,t._)`(${a} === 0 || (${u} = ${i}/${a}, ${l}))`)}};e.default=r})),xP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(r){let n=r.length,o=0,i=0,a;for(;i=55296&&a<=56319&&i{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r=Te(),n=xP(),o={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:i,schemaCode:a}){let s=i==="maxLength"?"more":"fewer";return(0,t.str)`must NOT have ${s} than ${a} characters`},params:({schemaCode:i})=>(0,t._)`{limit: ${i}}`},code(i){let{keyword:a,data:s,schemaCode:c,it:u}=i,l=a==="maxLength"?t.operators.GT:t.operators.LT,d=u.opts.unicode===!1?(0,t._)`${s}.length`:(0,t._)`${(0,r.useFunc)(i.gen,n.default)}(${s})`;i.fail$data((0,t._)`${d} ${l} ${c}`)}};e.default=o})),PP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Xt(),r=Te(),n=ze(),o={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:i})=>(0,n.str)`must match pattern "${i}"`,params:({schemaCode:i})=>(0,n._)`{pattern: ${i}}`},code(i){let{gen:a,data:s,$data:c,schema:u,schemaCode:l,it:d}=i,m=d.opts.unicodeRegExp?"u":"";if(c){let{regExp:v}=d.opts.code,g=v.code==="new RegExp"?(0,n._)`new RegExp`:(0,r.useFunc)(a,v),h=a.let("valid");a.try(()=>a.assign(h,(0,n._)`${g}(${l}, ${m}).test(${s})`),()=>a.assign(h,!1)),i.fail$data((0,n._)`!${h}`)}else{let v=(0,t.usePattern)(i,u);i.fail$data((0,n._)`!${v}.test(${s})`)}}};e.default=o})),TP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:o}){let i=n==="maxProperties"?"more":"fewer";return(0,t.str)`must NOT have ${i} than ${o} properties`},params:({schemaCode:n})=>(0,t._)`{limit: ${n}}`},code(n){let{keyword:o,data:i,schemaCode:a}=n,s=o==="maxProperties"?t.operators.GT:t.operators.LT;n.fail$data((0,t._)`Object.keys(${i}).length ${s} ${a}`)}};e.default=r})),CP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Xt(),r=ze(),n=Te(),o={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:i}})=>(0,r.str)`must have required property '${i}'`,params:({params:{missingProperty:i}})=>(0,r._)`{missingProperty: ${i}}`},code(i){let{gen:a,schema:s,schemaCode:c,data:u,$data:l,it:d}=i,{opts:m}=d;if(!l&&s.length===0)return;let v=s.length>=m.loopRequired;if(d.allErrors?g():h(),m.strictRequired){let S=i.parentSchema.properties,{definedProperties:_}=i.it;for(let $ of s)if(S?.[$]===void 0&&!_.has($)){let k=`required property "${$}" is not defined at "${d.schemaEnv.baseId+d.errSchemaPath}" (strictRequired)`;(0,n.checkStrictMode)(d,k,d.opts.strictRequired)}}function g(){if(v||l)i.block$data(r.nil,f);else for(let S of s)(0,t.checkReportMissingProp)(i,S)}function h(){let S=a.let("missing");if(v||l){let _=a.let("valid",!0);i.block$data(_,()=>y(S,_)),i.ok(_)}else a.if((0,t.checkMissingProp)(i,s,S)),(0,t.reportMissingProp)(i,S),a.else()}function f(){a.forOf("prop",c,S=>{i.setParams({missingProperty:S}),a.if((0,t.noPropertyInData)(a,u,S,m.ownProperties),()=>i.error())})}function y(S,_){i.setParams({missingProperty:S}),a.forOf(S,c,()=>{a.assign(_,(0,t.propertyInData)(a,u,S,m.ownProperties)),a.if((0,r.not)(_),()=>{i.error(),a.break()})},r.nil)}}};e.default=o})),AP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:o}){let i=n==="maxItems"?"more":"fewer";return(0,t.str)`must NOT have ${i} than ${o} items`},params:({schemaCode:n})=>(0,t._)`{limit: ${n}}`},code(n){let{keyword:o,data:i,schemaCode:a}=n,s=o==="maxItems"?t.operators.GT:t.operators.LT;n.fail$data((0,t._)`${i}.length ${s} ${a}`)}};e.default=r})),pg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Qw();t.code='require("ajv/dist/runtime/equal").default',e.default=t})),OP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=sd(),r=ze(),n=Te(),o=pg(),i={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:a,j:s}})=>(0,r.str)`must NOT have duplicate items (items ## ${s} and ${a} are identical)`,params:({params:{i:a,j:s}})=>(0,r._)`{i: ${a}, j: ${s}}`},code(a){let{gen:s,data:c,$data:u,schema:l,parentSchema:d,schemaCode:m,it:v}=a;if(!u&&!l)return;let g=s.let("valid"),h=d.items?(0,t.getSchemaTypes)(d.items):[];a.block$data(g,f,(0,r._)`${m} === false`),a.ok(g);function f(){let $=s.let("i",(0,r._)`${c}.length`),k=s.let("j");a.setParams({i:$,j:k}),s.assign(g,!0),s.if((0,r._)`${$} > 1`,()=>(y()?S:_)($,k))}function y(){return h.length>0&&!h.some($=>$==="object"||$==="array")}function S($,k){let w=s.name("item"),b=(0,t.checkDataTypes)(h,w,v.opts.strictNumbers,t.DataType.Wrong),E=s.const("indices",(0,r._)`{}`);s.for((0,r._)`;${$}--;`,()=>{s.let(w,(0,r._)`${c}[${$}]`),s.if(b,(0,r._)`continue`),h.length>1&&s.if((0,r._)`typeof ${w} == "string"`,(0,r._)`${w} += "_"`),s.if((0,r._)`typeof ${E}[${w}] == "number"`,()=>{s.assign(k,(0,r._)`${E}[${w}]`),a.error(),s.assign(g,!1).break()}).code((0,r._)`${E}[${w}] = ${$}`)})}function _($,k){let w=(0,n.useFunc)(s,o.default),b=s.name("outer");s.label(b).for((0,r._)`;${$}--;`,()=>s.for((0,r._)`${k} = ${$}; ${k}--;`,()=>s.if((0,r._)`${w}(${c}[${$}], ${c}[${k}])`,()=>{a.error(),s.assign(g,!1).break(b)})))}}};e.default=i})),NP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r=Te(),n=pg(),o={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:i})=>(0,t._)`{allowedValue: ${i}}`},code(i){let{gen:a,data:s,$data:c,schemaCode:u,schema:l}=i;c||l&&typeof l=="object"?i.fail$data((0,t._)`!${(0,r.useFunc)(a,n.default)}(${s}, ${u})`):i.fail((0,t._)`${l} !== ${s}`)}};e.default=o})),jP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r=Te(),n=pg(),o={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:i})=>(0,t._)`{allowedValues: ${i}}`},code(i){let{gen:a,data:s,$data:c,schema:u,schemaCode:l,it:d}=i;if(!c&&u.length===0)throw new Error("enum must have non-empty array");let m=u.length>=d.opts.loopEnum,v,g=()=>v??(v=(0,r.useFunc)(a,n.default)),h;if(m||c)h=a.let("valid"),i.block$data(h,f);else{if(!Array.isArray(u))throw new Error("ajv implementation error");let S=a.const("vSchema",l);h=(0,t.or)(...u.map((_,$)=>y(S,$)))}i.pass(h);function f(){a.assign(h,!1),a.forOf("v",l,S=>a.if((0,t._)`${g()}(${s}, ${S})`,()=>a.assign(h,!0).break()))}function y(S,_){let $=u[_];return typeof $=="object"&&$!==null?(0,t._)`${g()}(${s}, ${S}[${_}])`:(0,t._)`${s} === ${$}`}}};e.default=o})),nz=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=EP(),r=RP(),n=IP(),o=PP(),i=TP(),a=CP(),s=AP(),c=OP(),u=NP(),l=jP(),d=[t.default,r.default,n.default,o.default,i.default,a.default,s.default,c.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},u.default,l.default];e.default=d})),oz=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;let t=ze(),r=Te(),n={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:i}})=>(0,t.str)`must NOT have more than ${i} items`,params:({params:{len:i}})=>(0,t._)`{limit: ${i}}`},code(i){let{parentSchema:a,it:s}=i,{items:c}=a;if(!Array.isArray(c)){(0,r.checkStrictMode)(s,'"additionalItems" is ignored when "items" is not an array of schemas');return}o(i,c)}};function o(i,a){let{gen:s,schema:c,data:u,keyword:l,it:d}=i;d.items=!0;let m=s.const("len",(0,t._)`${u}.length`);if(c===!1)i.setParams({len:a.length}),i.pass((0,t._)`${m} <= ${a.length}`);else if(typeof c=="object"&&!(0,r.alwaysValidSchema)(d,c)){let g=s.var("valid",(0,t._)`${m} <= ${a.length}`);s.if((0,t.not)(g),()=>v(g)),i.ok(g)}function v(g){s.forRange("i",a.length,m,h=>{i.subschema({keyword:l,dataProp:h,dataPropType:r.Type.Num},g),d.allErrors||s.if((0,t.not)(g),()=>s.break())})}}e.validateAdditionalItems=o,e.default=n})),iz=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;let t=ze(),r=Te(),n=Xt(),o={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(a){let{schema:s,it:c}=a;if(Array.isArray(s))return i(a,"additionalItems",s);c.items=!0,!(0,r.alwaysValidSchema)(c,s)&&a.ok((0,n.validateArray)(a))}};function i(a,s,c=a.schema){let{gen:u,parentSchema:l,data:d,keyword:m,it:v}=a;f(l),v.opts.unevaluated&&c.length&&v.items!==!0&&(v.items=r.mergeEvaluated.items(u,c.length,v.items));let g=u.name("valid"),h=u.const("len",(0,t._)`${d}.length`);c.forEach((y,S)=>{(0,r.alwaysValidSchema)(v,y)||(u.if((0,t._)`${h} > ${S}`,()=>a.subschema({keyword:m,schemaProp:S,dataProp:S},g)),a.ok(g))});function f(y){let{opts:S,errSchemaPath:_}=v,$=c.length,k=$===y.minItems&&($===y.maxItems||y[s]===!1);if(S.strictTuples&&!k){let w=`"${m}" is ${$}-tuple, but minItems or maxItems/${s} are not specified or different at path "${_}"`;(0,r.checkStrictMode)(v,w,S.strictTuples)}}}e.validateTuple=i,e.default=o})),UP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=iz(),r={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:n=>(0,t.validateTuple)(n,"items")};e.default=r})),MP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r=Te(),n=Xt(),o=oz(),i={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:a}})=>(0,t.str)`must NOT have more than ${a} items`,params:({params:{len:a}})=>(0,t._)`{limit: ${a}}`},code(a){let{schema:s,parentSchema:c,it:u}=a,{prefixItems:l}=c;u.items=!0,!(0,r.alwaysValidSchema)(u,s)&&(l?(0,o.validateAdditionalItems)(a,l):a.ok((0,n.validateArray)(a)))}};e.default=i})),DP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r=Te(),n={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:o,max:i}})=>i===void 0?(0,t.str)`must contain at least ${o} valid item(s)`:(0,t.str)`must contain at least ${o} and no more than ${i} valid item(s)`,params:({params:{min:o,max:i}})=>i===void 0?(0,t._)`{minContains: ${o}}`:(0,t._)`{minContains: ${o}, maxContains: ${i}}`},code(o){let{gen:i,schema:a,parentSchema:s,data:c,it:u}=o,l,d,{minContains:m,maxContains:v}=s;u.opts.next?(l=m===void 0?1:m,d=v):l=1;let g=i.const("len",(0,t._)`${c}.length`);if(o.setParams({min:l,max:d}),d===void 0&&l===0){(0,r.checkStrictMode)(u,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(d!==void 0&&l>d){(0,r.checkStrictMode)(u,'"minContains" > "maxContains" is always invalid'),o.fail();return}if((0,r.alwaysValidSchema)(u,a)){let _=(0,t._)`${g} >= ${l}`;d!==void 0&&(_=(0,t._)`${_} && ${g} <= ${d}`),o.pass(_);return}u.items=!0;let h=i.name("valid");d===void 0&&l===1?y(h,()=>i.if(h,()=>i.break())):l===0?(i.let(h,!0),d!==void 0&&i.if((0,t._)`${c}.length > 0`,f)):(i.let(h,!1),f()),o.result(h,()=>o.reset());function f(){let _=i.name("_valid"),$=i.let("count",0);y(_,()=>i.if(_,()=>S($)))}function y(_,$){i.forRange("i",0,g,k=>{o.subschema({keyword:"contains",dataProp:k,dataPropType:r.Type.Num,compositeRule:!0},_),$()})}function S(_){i.code((0,t._)`${_}++`),d===void 0?i.if((0,t._)`${_} >= ${l}`,()=>i.assign(h,!0).break()):(i.if((0,t._)`${_} > ${d}`,()=>i.assign(h,!1).break()),l===1?i.assign(h,!0):i.if((0,t._)`${_} >= ${l}`,()=>i.assign(h,!0)))}}};e.default=n})),mg=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=ze(),r=Te(),n=Xt();e.error={message:({params:{property:c,depsCount:u,deps:l}})=>{let d=u===1?"property":"properties";return(0,t.str)`must have ${d} ${l} when property ${c} is present`},params:({params:{property:c,depsCount:u,deps:l,missingProperty:d}})=>(0,t._)`{property: ${c}, + missingProperty: ${d}, + depsCount: ${u}, + deps: ${l}}`};let o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(c){let[u,l]=i(c);a(c,u),s(c,l)}};function i({schema:c}){let u={},l={};for(let d in c){if(d==="__proto__")continue;let m=Array.isArray(c[d])?u:l;m[d]=c[d]}return[u,l]}function a(c,u=c.schema){let{gen:l,data:d,it:m}=c;if(Object.keys(u).length===0)return;let v=l.let("missing");for(let g in u){let h=u[g];if(h.length===0)continue;let f=(0,n.propertyInData)(l,d,g,m.opts.ownProperties);c.setParams({property:g,depsCount:h.length,deps:h.join(", ")}),m.allErrors?l.if(f,()=>{for(let y of h)(0,n.checkReportMissingProp)(c,y)}):(l.if((0,t._)`${f} && (${(0,n.checkMissingProp)(c,h,v)})`),(0,n.reportMissingProp)(c,v),l.else())}}e.validatePropertyDeps=a;function s(c,u=c.schema){let{gen:l,data:d,keyword:m,it:v}=c,g=l.name("valid");for(let h in u)(0,r.alwaysValidSchema)(v,u[h])||(l.if((0,n.propertyInData)(l,d,h,v.opts.ownProperties),()=>{let f=c.subschema({keyword:m,schemaProp:h},g);c.mergeValidEvaluated(f,g)},()=>l.var(g,!0)),c.ok(g))}e.validateSchemaDeps=s,e.default=o})),qP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r=Te(),n={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:o})=>(0,t._)`{propertyName: ${o.propertyName}}`},code(o){let{gen:i,schema:a,data:s,it:c}=o;if((0,r.alwaysValidSchema)(c,a))return;let u=i.name("valid");i.forIn("key",s,l=>{o.setParams({propertyName:l}),o.subschema({keyword:"propertyNames",data:l,dataTypes:["string"],propertyName:l,compositeRule:!0},u),i.if((0,t.not)(u),()=>{o.error(!0),c.allErrors||i.break()})}),o.ok(u)}};e.default=n})),az=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Xt(),r=ze(),n=Gt(),o=Te(),i={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:a})=>(0,r._)`{additionalProperty: ${a.additionalProperty}}`},code(a){let{gen:s,schema:c,parentSchema:u,data:l,errsCount:d,it:m}=a;if(!d)throw new Error("ajv implementation error");let{allErrors:v,opts:g}=m;if(m.props=!0,g.removeAdditional!=="all"&&(0,o.alwaysValidSchema)(m,c))return;let h=(0,t.allSchemaProperties)(u.properties),f=(0,t.allSchemaProperties)(u.patternProperties);y(),a.ok((0,r._)`${d} === ${n.default.errors}`);function y(){s.forIn("key",l,w=>{!h.length&&!f.length?$(w):s.if(S(w),()=>$(w))})}function S(w){let b;if(h.length>8){let E=(0,o.schemaRefOrVal)(m,u.properties,"properties");b=(0,t.isOwnProperty)(s,E,w)}else h.length?b=(0,r.or)(...h.map(E=>(0,r._)`${w} === ${E}`)):b=r.nil;return f.length&&(b=(0,r.or)(b,...f.map(E=>(0,r._)`${(0,t.usePattern)(a,E)}.test(${w})`))),(0,r.not)(b)}function _(w){s.code((0,r._)`delete ${l}[${w}]`)}function $(w){if(g.removeAdditional==="all"||g.removeAdditional&&c===!1){_(w);return}if(c===!1){a.setParams({additionalProperty:w}),a.error(),v||s.break();return}if(typeof c=="object"&&!(0,o.alwaysValidSchema)(m,c)){let b=s.name("valid");g.removeAdditional==="failing"?(k(w,b,!1),s.if((0,r.not)(b),()=>{a.reset(),_(w)})):(k(w,b),v||s.if((0,r.not)(b),()=>s.break()))}}function k(w,b,E){let j={keyword:"additionalProperties",dataProp:w,dataPropType:o.Type.Str};E===!1&&Object.assign(j,{compositeRule:!0,createErrors:!1,allErrors:!1}),a.subschema(j,b)}}};e.default=i})),LP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=hs(),r=Xt(),n=Te(),o=az(),i={keyword:"properties",type:"object",schemaType:"object",code(a){let{gen:s,schema:c,parentSchema:u,data:l,it:d}=a;d.opts.removeAdditional==="all"&&u.additionalProperties===void 0&&o.default.code(new t.KeywordCxt(d,o.default,"additionalProperties"));let m=(0,r.allSchemaProperties)(c);for(let y of m)d.definedProperties.add(y);d.opts.unevaluated&&m.length&&d.props!==!0&&(d.props=n.mergeEvaluated.props(s,(0,n.toHash)(m),d.props));let v=m.filter(y=>!(0,n.alwaysValidSchema)(d,c[y]));if(v.length===0)return;let g=s.name("valid");for(let y of v)h(y)?f(y):(s.if((0,r.propertyInData)(s,l,y,d.opts.ownProperties)),f(y),d.allErrors||s.else().var(g,!0),s.endIf()),a.it.definedProperties.add(y),a.ok(g);function h(y){return d.opts.useDefaults&&!d.compositeRule&&c[y].default!==void 0}function f(y){a.subschema({keyword:"properties",schemaProp:y,dataProp:y},g)}}};e.default=i})),VP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Xt(),r=ze(),n=Te(),o=Te(),i={keyword:"patternProperties",type:"object",schemaType:"object",code(a){let{gen:s,schema:c,data:u,parentSchema:l,it:d}=a,{opts:m}=d,v=(0,t.allSchemaProperties)(c),g=v.filter(k=>(0,n.alwaysValidSchema)(d,c[k]));if(v.length===0||g.length===v.length&&(!d.opts.unevaluated||d.props===!0))return;let h=m.strictSchema&&!m.allowMatchingProperties&&l.properties,f=s.name("valid");d.props!==!0&&!(d.props instanceof r.Name)&&(d.props=(0,o.evaluatedPropsToName)(s,d.props));let{props:y}=d;S();function S(){for(let k of v)h&&_(k),d.allErrors?$(k):(s.var(f,!0),$(k),s.if(f))}function _(k){for(let w in h)new RegExp(k).test(w)&&(0,n.checkStrictMode)(d,`property ${w} matches pattern ${k} (use allowMatchingProperties)`)}function $(k){s.forIn("key",u,w=>{s.if((0,r._)`${(0,t.usePattern)(a,k)}.test(${w})`,()=>{let b=g.includes(k);b||a.subschema({keyword:"patternProperties",schemaProp:k,dataProp:w,dataPropType:o.Type.Str},f),d.opts.unevaluated&&y!==!0?s.assign((0,r._)`${y}[${w}]`,!0):!b&&!d.allErrors&&s.if((0,r.not)(f),()=>s.break())})})}}};e.default=i})),KP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Te(),r={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(n){let{gen:o,schema:i,it:a}=n;if((0,t.alwaysValidSchema)(a,i)){n.fail();return}let s=o.name("valid");n.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),n.failResult(s,()=>n.reset(),()=>n.error())},error:{message:"must NOT be valid"}};e.default=r})),JP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Xt().validateUnion,error:{message:"must match a schema in anyOf"}};e.default=t})),FP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r=Te(),n={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:o})=>(0,t._)`{passingSchemas: ${o.passing}}`},code(o){let{gen:i,schema:a,parentSchema:s,it:c}=o;if(!Array.isArray(a))throw new Error("ajv implementation error");if(c.opts.discriminator&&s.discriminator)return;let u=a,l=i.let("valid",!1),d=i.let("passing",null),m=i.name("_valid");o.setParams({passing:d}),i.block(v),o.result(l,()=>o.reset(),()=>o.error(!0));function v(){u.forEach((g,h)=>{let f;(0,r.alwaysValidSchema)(c,g)?i.var(m,!0):f=o.subschema({keyword:"oneOf",schemaProp:h,compositeRule:!0},m),h>0&&i.if((0,t._)`${m} && ${l}`).assign(l,!1).assign(d,(0,t._)`[${d}, ${h}]`).else(),i.if(m,()=>{i.assign(l,!0),i.assign(d,h),f&&o.mergeEvaluated(f,t.Name)})})}}};e.default=n})),HP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Te(),r={keyword:"allOf",schemaType:"array",code(n){let{gen:o,schema:i,it:a}=n;if(!Array.isArray(i))throw new Error("ajv implementation error");let s=o.name("valid");i.forEach((c,u)=>{if((0,t.alwaysValidSchema)(a,c))return;let l=n.subschema({keyword:"allOf",schemaProp:u},s);n.ok(s),n.mergeEvaluated(l)})}};e.default=r})),ZP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r=Te(),n={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:i})=>(0,t.str)`must match "${i.ifClause}" schema`,params:({params:i})=>(0,t._)`{failingKeyword: ${i.ifClause}}`},code(i){let{gen:a,parentSchema:s,it:c}=i;s.then===void 0&&s.else===void 0&&(0,r.checkStrictMode)(c,'"if" without "then" and "else" is ignored');let u=o(c,"then"),l=o(c,"else");if(!u&&!l)return;let d=a.let("valid",!0),m=a.name("_valid");if(v(),i.reset(),u&&l){let h=a.let("ifClause");i.setParams({ifClause:h}),a.if(m,g("then",h),g("else",h))}else u?a.if(m,g("then")):a.if((0,t.not)(m),g("else"));i.pass(d,()=>i.error(!0));function v(){let h=i.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},m);i.mergeEvaluated(h)}function g(h,f){return()=>{let y=i.subschema({keyword:h},m);a.assign(d,m),i.mergeValidEvaluated(y,d),f?a.assign(f,(0,t._)`${h}`):i.setParams({ifClause:h})}}}};function o(i,a){let s=i.schema[a];return s!==void 0&&!(0,r.alwaysValidSchema)(i,s)}e.default=n})),WP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Te(),r={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:n,parentSchema:o,it:i}){o.if===void 0&&(0,t.checkStrictMode)(i,`"${n}" without "if" is ignored`)}};e.default=r})),sz=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=oz(),r=UP(),n=iz(),o=MP(),i=DP(),a=mg(),s=qP(),c=az(),u=LP(),l=VP(),d=KP(),m=JP(),v=FP(),g=HP(),h=ZP(),f=WP();function y(S=!1){let _=[d.default,m.default,v.default,g.default,h.default,f.default,s.default,c.default,a.default,u.default,l.default];return S?_.push(r.default,o.default):_.push(t.default,n.default),_.push(i.default),_}e.default=y})),BP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:n})=>(0,t.str)`must match format "${n}"`,params:({schemaCode:n})=>(0,t._)`{format: ${n}}`},code(n,o){let{gen:i,data:a,$data:s,schema:c,schemaCode:u,it:l}=n,{opts:d,errSchemaPath:m,schemaEnv:v,self:g}=l;if(!d.validateFormats)return;s?h():f();function h(){let y=i.scopeValue("formats",{ref:g.formats,code:d.code.formats}),S=i.const("fDef",(0,t._)`${y}[${u}]`),_=i.let("fType"),$=i.let("format");i.if((0,t._)`typeof ${S} == "object" && !(${S} instanceof RegExp)`,()=>i.assign(_,(0,t._)`${S}.type || "string"`).assign($,(0,t._)`${S}.validate`),()=>i.assign(_,(0,t._)`"string"`).assign($,S)),n.fail$data((0,t.or)(k(),w()));function k(){return d.strictSchema===!1?t.nil:(0,t._)`${u} && !${$}`}function w(){let b=v.$async?(0,t._)`(${S}.async ? await ${$}(${a}) : ${$}(${a}))`:(0,t._)`${$}(${a})`,E=(0,t._)`(typeof ${$} == "function" ? ${b} : ${$}.test(${a}))`;return(0,t._)`${$} && ${$} !== true && ${_} === ${o} && !${E}`}}function f(){let y=g.formats[c];if(!y){k();return}if(y===!0)return;let[S,_,$]=w(y);S===o&&n.pass(b());function k(){if(d.strictSchema===!1){g.logger.warn(E());return}throw new Error(E());function E(){return`unknown format "${c}" ignored in schema at path "${m}"`}}function w(E){let j=E instanceof RegExp?(0,t.regexpCode)(E):d.code.formats?(0,t._)`${d.code.formats}${(0,t.getProperty)(c)}`:void 0,V=i.scopeValue("formats",{key:c,ref:E,code:j});return typeof E=="object"&&!(E instanceof RegExp)?[E.type||"string",E.validate,(0,t._)`${V}.validate`]:["string",E,V]}function b(){if(typeof y=="object"&&!(y instanceof RegExp)&&y.async){if(!v.$async)throw new Error("async format in sync schema");return(0,t._)`await ${$}(${a})`}return typeof _=="function"?(0,t._)`${$}(${a})`:(0,t._)`${$}.test(${a})`}}}};e.default=r})),cz=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=[BP().default];e.default=t})),uz=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],e.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]})),GP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=rz(),r=nz(),n=sz(),o=cz(),i=uz(),a=[t.default,r.default,(0,n.default)(),o.default,i.metadataVocabulary,i.contentVocabulary];e.default=a})),XP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DiscrError=void 0;var t;(function(r){r.Tag="tag",r.Mapping="mapping"})(t||(e.DiscrError=t={}))})),lz=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r=XP(),n=dd(),o=gs(),i=Te(),a={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:s,tagName:c}})=>s===r.DiscrError.Tag?`tag "${c}" must be string`:`value of tag "${c}" must be in oneOf`,params:({params:{discrError:s,tag:c,tagName:u}})=>(0,t._)`{error: ${s}, tag: ${u}, tagValue: ${c}}`},code(s){let{gen:c,data:u,schema:l,parentSchema:d,it:m}=s,{oneOf:v}=d;if(!m.opts.discriminator)throw new Error("discriminator: requires discriminator option");let g=l.propertyName;if(typeof g!="string")throw new Error("discriminator: requires propertyName");if(l.mapping)throw new Error("discriminator: mapping is not supported");if(!v)throw new Error("discriminator: requires oneOf keyword");let h=c.let("valid",!1),f=c.const("tag",(0,t._)`${u}${(0,t.getProperty)(g)}`);c.if((0,t._)`typeof ${f} == "string"`,()=>y(),()=>s.error(!1,{discrError:r.DiscrError.Tag,tag:f,tagName:g})),s.ok(h);function y(){let $=_();c.if(!1);for(let k in $)c.elseIf((0,t._)`${f} === ${k}`),c.assign(h,S($[k]));c.else(),s.error(!1,{discrError:r.DiscrError.Mapping,tag:f,tagName:g}),c.endIf()}function S($){let k=c.name("valid"),w=s.subschema({keyword:"oneOf",schemaProp:$},k);return s.mergeEvaluated(w,t.Name),k}function _(){var $;let k={},w=E(d),b=!0;for(let A=0;A{t.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}})),dz=H(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let r=tz(),n=GP(),o=lz(),i=YP(),a=["/properties"],s="http://json-schema.org/draft-07/schema";var c=class extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(v=>this.addVocabulary(v)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let v=this.opts.$data?this.$dataMetaSchema(i,a):i;this.addMetaSchema(v,s,!1),this.refs["http://json-schema.org/schema"]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var u=hs();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=ze();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return l._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return l.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return l.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return l.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return l.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return l.CodeGen}});var d=ld();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var m=gs();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return m.default}})})),pz=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.dynamicAnchor=void 0;let t=ze(),r=Gt(),n=dd(),o=dg(),i={keyword:"$dynamicAnchor",schemaType:"string",code:c=>a(c,c.schema)};function a(c,u){let{gen:l,it:d}=c;d.schemaEnv.root.dynamicAnchors[u]=!0;let m=(0,t._)`${r.default.dynamicAnchors}${(0,t.getProperty)(u)}`,v=d.errSchemaPath==="#"?d.validateName:s(c);l.if((0,t._)`!${m}`,()=>l.assign(m,v))}e.dynamicAnchor=a;function s(c){let{schemaEnv:u,schema:l,self:d}=c.it,{root:m,baseId:v,localRefs:g,meta:h}=u.root,{schemaId:f}=d.opts,y=new n.SchemaEnv({schema:l,schemaId:f,root:m,baseId:v,localRefs:g,meta:h});return n.compileSchema.call(d,y),(0,o.getValidate)(c,y)}e.default=i})),mz=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.dynamicRef=void 0;let t=ze(),r=Gt(),n=dg(),o={keyword:"$dynamicRef",schemaType:"string",code:a=>i(a,a.schema)};function i(a,s){let{gen:c,keyword:u,it:l}=a;if(s[0]!=="#")throw new Error(`"${u}" only supports hash fragment reference`);let d=s.slice(1);if(l.allErrors)m();else{let g=c.let("valid",!1);m(g),a.ok(g)}function m(g){if(l.schemaEnv.root.dynamicAnchors[d]){let h=c.let("_v",(0,t._)`${r.default.dynamicAnchors}${(0,t.getProperty)(d)}`);c.if(h,v(h,g),v(l.validateName,g))}else v(l.validateName,g)()}function v(g,h){return h?()=>c.block(()=>{(0,n.callRef)(a,g),c.let(h,!0)}):()=>(0,n.callRef)(a,g)}}e.dynamicRef=i,e.default=o})),QP=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=pz(),r=Te(),n={keyword:"$recursiveAnchor",schemaType:"boolean",code(o){o.schema?(0,t.dynamicAnchor)(o,""):(0,r.checkStrictMode)(o.it,"$recursiveAnchor: false is ignored")}};e.default=n})),eT=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=mz(),r={keyword:"$recursiveRef",schemaType:"string",code:n=>(0,t.dynamicRef)(n,n.schema)};e.default=r})),tT=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=pz(),r=mz(),n=QP(),o=eT(),i=[t.default,r.default,n.default,o.default];e.default=i})),rT=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=mg(),r={keyword:"dependentRequired",type:"object",schemaType:"object",error:t.error,code:n=>(0,t.validatePropertyDeps)(n)};e.default=r})),nT=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=mg(),r={keyword:"dependentSchemas",type:"object",schemaType:"object",code:n=>(0,t.validateSchemaDeps)(n)};e.default=r})),oT=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Te(),r={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:n,parentSchema:o,it:i}){o.contains===void 0&&(0,t.checkStrictMode)(i,`"${n}" without "contains" is ignored`)}};e.default=r})),iT=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=rT(),r=nT(),n=oT(),o=[t.default,r.default,n.default];e.default=o})),aT=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r=Te(),n=Gt(),o={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:{message:"must NOT have unevaluated properties",params:({params:i})=>(0,t._)`{unevaluatedProperty: ${i.unevaluatedProperty}}`},code(i){let{gen:a,schema:s,data:c,errsCount:u,it:l}=i;if(!u)throw new Error("ajv implementation error");let{allErrors:d,props:m}=l;m instanceof t.Name?a.if((0,t._)`${m} !== true`,()=>a.forIn("key",c,f=>a.if(g(m,f),()=>v(f)))):m!==!0&&a.forIn("key",c,f=>m===void 0?v(f):a.if(h(m,f),()=>v(f))),l.props=!0,i.ok((0,t._)`${u} === ${n.default.errors}`);function v(f){if(s===!1){i.setParams({unevaluatedProperty:f}),i.error(),d||a.break();return}if(!(0,r.alwaysValidSchema)(l,s)){let y=a.name("valid");i.subschema({keyword:"unevaluatedProperties",dataProp:f,dataPropType:r.Type.Str},y),d||a.if((0,t.not)(y),()=>a.break())}}function g(f,y){return(0,t._)`!${f} || !${f}[${y}]`}function h(f,y){let S=[];for(let _ in f)f[_]===!0&&S.push((0,t._)`${y} !== ${_}`);return(0,t.and)(...S)}}};e.default=o})),sT=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ze(),r=Te(),n={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:{message:({params:{len:o}})=>(0,t.str)`must NOT have more than ${o} items`,params:({params:{len:o}})=>(0,t._)`{limit: ${o}}`},code(o){let{gen:i,schema:a,data:s,it:c}=o,u=c.items||0;if(u===!0)return;let l=i.const("len",(0,t._)`${s}.length`);if(a===!1)o.setParams({len:u}),o.fail((0,t._)`${l} > ${u}`);else if(typeof a=="object"&&!(0,r.alwaysValidSchema)(c,a)){let m=i.var("valid",(0,t._)`${l} <= ${u}`);i.if((0,t.not)(m),()=>d(m,u)),o.ok(m)}c.items=!0;function d(m,v){i.forRange("i",v,l,g=>{o.subschema({keyword:"unevaluatedItems",dataProp:g,dataPropType:r.Type.Num},m),c.allErrors||i.if((0,t.not)(m),()=>i.break())})}}};e.default=n})),cT=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=aT(),r=sT(),n=[t.default,r.default];e.default=n})),uT=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=rz(),r=nz(),n=sz(),o=tT(),i=iT(),a=cT(),s=cz(),c=uz(),u=[o.default,t.default,r.default,(0,n.default)(!0),s.default,c.metadataVocabulary,c.contentVocabulary,i.default,a.default];e.default=u})),lT=H(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}})),dT=H(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}})),pT=H(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}})),mT=H(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}})),fT=H(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}})),hT=H(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}})),gT=H(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}})),yT=H(((e,t)=>{t.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}})),vT=H((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=lT(),r=dT(),n=pT(),o=mT(),i=fT(),a=hT(),s=gT(),c=yT(),u=["/properties"];function l(d){return[t,r,n,o,i,m(this,a),s,m(this,c)].forEach(v=>this.addMetaSchema(v,void 0,!1)),this;function m(v,g){return d?v.$dataMetaSchema(g,u):g}}e.default=l})),_T=H(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv2020=void 0;let r=tz(),n=uT(),o=lz(),i=vT(),a="https://json-schema.org/draft/2020-12/schema";var s=class extends r.default{constructor(m={}){super({...m,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),n.default.forEach(m=>this.addVocabulary(m)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:m,meta:v}=this.opts;v&&(i.default.call(this,m),this.refs["http://json-schema.org/schema"]=a)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(a)?a:void 0)}};e.Ajv2020=s,t.exports=e=s,t.exports.Ajv2020=s,Object.defineProperty(e,"__esModule",{value:!0}),e.default=s;var c=hs();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=ze();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var l=ld();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return l.default}});var d=gs();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return d.default}})})),ST=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(A,L){return{validate:A,compare:L}}e.fullFormats={date:t(i,a),time:t(c(!0),u),"date-time":t(m(!0),v),"iso-time":t(c(),l),"iso-date-time":t(m(),g),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:y,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:V,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:_,int32:{type:"number",validate:w},int64:{type:"number",validate:b},float:{type:"number",validate:E},double:{type:"number",validate:E},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,u),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,v),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,l),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,g),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function r(A){return A%4===0&&(A%100!==0||A%400===0)}let n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,o=[0,31,28,31,30,31,30,31,31,30,31,30,31];function i(A){let L=n.exec(A);if(!L)return!1;let Z=+L[1],J=+L[2],te=+L[3];return J>=1&&J<=12&&te>=1&&te<=(J===2&&r(Z)?29:o[J])}function a(A,L){if(A&&L)return A>L?1:A23||M>59||A&&!Ne)return!1;if(te<=23&&_e<=59&&ke<60)return!0;let K=_e-M*be,z=te-P*be-(K<0?1:0);return(z===23||z===-1)&&(K===59||K===-1)&&ke<61}}function u(A,L){if(!(A&&L))return;let Z=new Date("2020-01-01T"+A).valueOf(),J=new Date("2020-01-01T"+L).valueOf();if(Z&&J)return Z-J}function l(A,L){if(!(A&&L))return;let Z=s.exec(A),J=s.exec(L);if(Z&&J)return A=Z[1]+Z[2]+Z[3],L=J[1]+J[2]+J[3],A>L?1:A=$}function b(A){return Number.isInteger(A)}function E(){return!0}let j=/[^\\]\\Z/;function V(A){if(j.test(A))return!1;try{return new RegExp(A),!0}catch{return!1}}})),bT=H((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;let t=dz(),r=ze(),n=r.operators,o={formatMaximum:{okStr:"<=",ok:n.LTE,fail:n.GT},formatMinimum:{okStr:">=",ok:n.GTE,fail:n.LT},formatExclusiveMaximum:{okStr:"<",ok:n.LT,fail:n.GTE},formatExclusiveMinimum:{okStr:">",ok:n.GT,fail:n.LTE}},i={message:({keyword:s,schemaCode:c})=>(0,r.str)`should be ${o[s].okStr} ${c}`,params:({keyword:s,schemaCode:c})=>(0,r._)`{comparison: ${o[s].okStr}, limit: ${c}}`};e.formatLimitDefinition={keyword:Object.keys(o),type:"string",schemaType:"string",$data:!0,error:i,code(s){let{gen:c,data:u,schemaCode:l,keyword:d,it:m}=s,{opts:v,self:g}=m;if(!v.validateFormats)return;let h=new t.KeywordCxt(m,g.RULES.all.format.definition,"format");h.$data?f():y();function f(){let _=c.scopeValue("formats",{ref:g.formats,code:v.code.formats}),$=c.const("fmt",(0,r._)`${_}[${h.schemaCode}]`);s.fail$data((0,r.or)((0,r._)`typeof ${$} != "object"`,(0,r._)`${$} instanceof RegExp`,(0,r._)`typeof ${$}.compare != "function"`,S($)))}function y(){let _=h.schema,$=g.formats[_];if(!$||$===!0)return;if(typeof $!="object"||$ instanceof RegExp||typeof $.compare!="function")throw new Error(`"${d}": format "${_}" does not define "compare" function`);let k=c.scopeValue("formats",{key:_,ref:$,code:v.code.formats?(0,r._)`${v.code.formats}${(0,r.getProperty)(_)}`:void 0});s.fail$data(S(k))}function S(_){return(0,r._)`${_}.compare(${u}, ${l}) ${o[d].fail} 0`}},dependencies:["format"]};let a=s=>(s.addKeyword(e.formatLimitDefinition),s);e.default=a})),$T=H(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});let r=ST(),n=bT(),o=ze(),i=new o.Name("fullFormats"),a=new o.Name("fastFormats"),s=(u,l={keywords:!0})=>{if(Array.isArray(l))return c(u,l,r.fullFormats,i),u;let[d,m]=l.mode==="fast"?[r.fastFormats,a]:[r.fullFormats,i];return c(u,l.formats||r.formatNames,d,m),l.keywords&&(0,n.default)(u),u};s.get=(u,l="full")=>{let d=(l==="fast"?r.fastFormats:r.fullFormats)[u];if(!d)throw new Error(`Unknown format "${u}"`);return d};function c(u,l,d,m){var v,g;(v=(g=u.opts.code).formats)!==null&&v!==void 0||(g.formats=(0,o._)`require("ajv-formats/dist/formats").${m}`);for(let h of l)u.addFormat(h,d[h])}t.exports=e=s,Object.defineProperty(e,"__esModule",{value:!0}),e.default=s})),wT=dz(),zT=_T(),kT=cc($T(),1),ET=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),RT=kT.default;pd=class{_ajv;_userAjv;constructor(e){this._userAjv=e!==void 0,this._ajv=e}get ajv(){return this._ajv??=xT()}getValidator(e){if(!this._userAjv&&"$schema"in e&&typeof e.$schema=="string"&&!ET.has(e.$schema.replace(/#$/,""))){let n=e.$schema.slice(0,200);throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${n}"). The default validator supports JSON Schema 2020-12 only; pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects.`)}let t=this.ajv,r="$id"in e&&typeof e.$id=="string"?t.getSchema(e.$id)??t.compile(e):t.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:t.errorsText(r.errors)}}},SD=wT.Ajv});var hz,gz=q(()=>{fz();hz=!1});async function IT(e){return(await fg).getRandomValues(new Uint8Array(e))}async function PT(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,n="";for(;n.length128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await TT(e),r=await CT(t);return{code_verifier:t,code_challenge:r}}var fg,yz=q(()=>{fg=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(e=>e.webcrypto)});function gg(e){}function fd(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=gg,onError:r=gg,onRetry:n=gg,onComment:o}=e,i="",a=!0,s,c="",u="";function l(h){let f=a?h.replace(/^\xEF\xBB\xBF/,""):h,[y,S]=AT(`${i}${f}`);for(let _ of y)d(_);i=S,a=!1}function d(h){if(h===""){v();return}if(h.startsWith(":")){o&&o(h.slice(h.startsWith(": ")?2:1));return}let f=h.indexOf(":");if(f!==-1){let y=h.slice(0,f),S=h[f+1]===" "?2:1,_=h.slice(f+S);m(y,_,h);return}m(h,"",h)}function m(h,f,y){switch(h){case"event":u=f;break;case"data":c=`${c}${f} +`;break;case"id":s=f.includes("\0")?void 0:f;break;case"retry":/^\d+$/.test(f)?n(parseInt(f,10)):r(new md(`Invalid \`retry\` value: "${f}"`,{type:"invalid-retry",value:f,line:y}));break;default:r(new md(`Unknown field "${h.length>20?`${h.slice(0,20)}\u2026`:h}"`,{type:"unknown-field",field:h,value:f,line:y}));break}}function v(){c.length>0&&t({id:s,event:u||void 0,data:c.endsWith(` +`)?c.slice(0,-1):c}),s=void 0,c="",u=""}function g(h={}){i&&h.consume&&d(i),a=!0,s=void 0,c="",u="",i=""}return{feed:l,reset:g}}function AT(e){let t=[],r="",n=0;for(;n{md=class extends Error{constructor(t,r){super(t),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}});function OT(e){let t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function vg(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(vg).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${vg(e.cause)}`:e.message:`${e}`}function vz(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}function NT(){let e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}var gd,Sz,Eg,Ce,st,We,Pr,Pt,Kn,Ko,hd,yd,_s,Ho,Ss,cn,Jo,Zo,Fo,ys,Yt,_g,Sg,bg,_z,$g,wg,vs,zg,kg,Jn,bz=q(()=>{yg();gd=class extends Event{constructor(t,r){var n,o;super(t),this.code=(n=r?.code)!=null?n:void 0,this.message=(o=r?.message)!=null?o:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,r,n){return n(vz(this),r)}[Symbol.for("Deno.customInspect")](t,r){return t(vz(this),r)}};Sz=e=>{throw TypeError(e)},Eg=(e,t,r)=>t.has(e)||Sz("Cannot "+r),Ce=(e,t,r)=>(Eg(e,t,"read from private field"),r?r.call(e):t.get(e)),st=(e,t,r)=>t.has(e)?Sz("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),We=(e,t,r,n)=>(Eg(e,t,"write to private field"),t.set(e,r),r),Pr=(e,t,r)=>(Eg(e,t,"access private method"),r),Jn=class extends EventTarget{constructor(t,r){var n,o;super(),st(this,Yt),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,st(this,Pt),st(this,Kn),st(this,Ko),st(this,hd),st(this,yd),st(this,_s),st(this,Ho),st(this,Ss,null),st(this,cn),st(this,Jo),st(this,Zo,null),st(this,Fo,null),st(this,ys,null),st(this,Sg,async i=>{var a;Ce(this,Jo).reset();let{body:s,redirected:c,status:u,headers:l}=i;if(u===204){Pr(this,Yt,vs).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?We(this,Ko,new URL(i.url)):We(this,Ko,void 0),u!==200){Pr(this,Yt,vs).call(this,`Non-200 status code (${u})`,u);return}if(!(l.get("content-type")||"").startsWith("text/event-stream")){Pr(this,Yt,vs).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(Ce(this,Pt)===this.CLOSED)return;We(this,Pt,this.OPEN);let d=new Event("open");if((a=Ce(this,ys))==null||a.call(this,d),this.dispatchEvent(d),typeof s!="object"||!s||!("getReader"in s)){Pr(this,Yt,vs).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}let m=new TextDecoder,v=s.getReader(),g=!0;do{let{done:h,value:f}=await v.read();f&&Ce(this,Jo).feed(m.decode(f,{stream:!h})),h&&(g=!1,Ce(this,Jo).reset(),Pr(this,Yt,zg).call(this))}while(g)}),st(this,bg,i=>{We(this,cn,void 0),!(i.name==="AbortError"||i.type==="aborted")&&Pr(this,Yt,zg).call(this,vg(i))}),st(this,$g,i=>{typeof i.id=="string"&&We(this,Ss,i.id);let a=new MessageEvent(i.event||"message",{data:i.data,origin:Ce(this,Ko)?Ce(this,Ko).origin:Ce(this,Kn).origin,lastEventId:i.id||""});Ce(this,Fo)&&(!i.event||i.event==="message")&&Ce(this,Fo).call(this,a),this.dispatchEvent(a)}),st(this,wg,i=>{We(this,_s,i)}),st(this,kg,()=>{We(this,Ho,void 0),Ce(this,Pt)===this.CONNECTING&&Pr(this,Yt,_g).call(this)});try{if(t instanceof URL)We(this,Kn,t);else if(typeof t=="string")We(this,Kn,new URL(t,NT()));else throw new Error("Invalid URL")}catch{throw OT("An invalid or illegal string was specified")}We(this,Jo,fd({onEvent:Ce(this,$g),onRetry:Ce(this,wg)})),We(this,Pt,this.CONNECTING),We(this,_s,3e3),We(this,yd,(n=r?.fetch)!=null?n:globalThis.fetch),We(this,hd,(o=r?.withCredentials)!=null?o:!1),Pr(this,Yt,_g).call(this)}get readyState(){return Ce(this,Pt)}get url(){return Ce(this,Kn).href}get withCredentials(){return Ce(this,hd)}get onerror(){return Ce(this,Zo)}set onerror(t){We(this,Zo,t)}get onmessage(){return Ce(this,Fo)}set onmessage(t){We(this,Fo,t)}get onopen(){return Ce(this,ys)}set onopen(t){We(this,ys,t)}addEventListener(t,r,n){let o=r;super.addEventListener(t,o,n)}removeEventListener(t,r,n){let o=r;super.removeEventListener(t,o,n)}close(){Ce(this,Ho)&&clearTimeout(Ce(this,Ho)),Ce(this,Pt)!==this.CLOSED&&(Ce(this,cn)&&Ce(this,cn).abort(),We(this,Pt,this.CLOSED),We(this,cn,void 0))}};Pt=new WeakMap,Kn=new WeakMap,Ko=new WeakMap,hd=new WeakMap,yd=new WeakMap,_s=new WeakMap,Ho=new WeakMap,Ss=new WeakMap,cn=new WeakMap,Jo=new WeakMap,Zo=new WeakMap,Fo=new WeakMap,ys=new WeakMap,Yt=new WeakSet,_g=function(){We(this,Pt,this.CONNECTING),We(this,cn,new AbortController),Ce(this,yd)(Ce(this,Kn),Pr(this,Yt,_z).call(this)).then(Ce(this,Sg)).catch(Ce(this,bg))},Sg=new WeakMap,bg=new WeakMap,_z=function(){var e;let t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Ce(this,Ss)?{"Last-Event-ID":Ce(this,Ss)}:void 0},cache:"no-store",signal:(e=Ce(this,cn))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},$g=new WeakMap,wg=new WeakMap,vs=function(e,t){var r;Ce(this,Pt)!==this.CLOSED&&We(this,Pt,this.CLOSED);let n=new gd("error",{code:t,message:e});(r=Ce(this,Zo))==null||r.call(this,n),this.dispatchEvent(n)},zg=function(e,t){var r;if(Ce(this,Pt)===this.CLOSED)return;We(this,Pt,this.CONNECTING);let n=new gd("error",{code:t,message:e});(r=Ce(this,Zo))==null||r.call(this,n),this.dispatchEvent(n),We(this,Ho,setTimeout(Ce(this,kg),Ce(this,_s)))},kg=new WeakMap,Jn.CONNECTING=0,Jn.OPEN=1,Jn.CLOSED=2});var vd,$z=q(()=>{yg();vd=class extends TransformStream{constructor({onError:t,onRetry:r,onComment:n}={}){let o;super({start(i){o=fd({onEvent:a=>{i.enqueue(a)},onError(a){t==="terminate"?i.error(a):typeof t=="function"&&t(a)},onRetry:r,onComment:n})},transform(i){o.feed(i)}})}}});function ot(...e){let t=e.reduce((o,{length:i})=>o+i,0),r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}function Rg(e,t,r){if(t<0||t>=_d)throw new RangeError(`value must be >= 0 and <= ${_d-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],r)}function xg(e){let t=Math.floor(e/_d),r=e%_d,n=new Uint8Array(8);return Rg(n,t,0),Rg(n,r,4),n}function Sd(e){let t=new Uint8Array(4);return Rg(t,e),t}function Qe(e){let t=new Uint8Array(e.length);for(let r=0;r127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}var Fn,ct,_d,gt=q(()=>{Fn=new TextEncoder,ct=new TextDecoder,_d=2**32});function bs(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=32768,r=[];for(let n=0;n{});var $d={};nr($d,{decode:()=>mt,encode:()=>qe});function mt(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e=="string"?e:ct.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=ct.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return bd(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function qe(e){let t=e;return typeof t=="string"&&(t=Fn.encode(t)),Uint8Array.prototype.toBase64?t.toBase64({alphabet:"base64url",omitPadding:!0}):bs(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var ft=q(()=>{gt();Ig()});function jT(e){return parseInt(e.name.slice(4),10)}function wd(e,t){if(jT(e.hash)!==t)throw wt(`SHA-${t}`,"algorithm.hash")}function UT(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function wz(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function zz(e,t,r){switch(t){case"HS256":case"HS384":case"HS512":{if(!dr(e.algorithm,"HMAC"))throw wt("HMAC");wd(e.algorithm,parseInt(t.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!dr(e.algorithm,"RSASSA-PKCS1-v1_5"))throw wt("RSASSA-PKCS1-v1_5");wd(e.algorithm,parseInt(t.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!dr(e.algorithm,"RSA-PSS"))throw wt("RSA-PSS");wd(e.algorithm,parseInt(t.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!dr(e.algorithm,"Ed25519"))throw wt("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!dr(e.algorithm,t))throw wt(t);break}case"ES256":case"ES384":case"ES512":{if(!dr(e.algorithm,"ECDSA"))throw wt("ECDSA");let n=UT(t);if(e.algorithm.namedCurve!==n)throw wt(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}wz(e,r)}function Mt(e,t,r){switch(t){case"A128GCM":case"A192GCM":case"A256GCM":{if(!dr(e.algorithm,"AES-GCM"))throw wt("AES-GCM");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw wt(n,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!dr(e.algorithm,"AES-KW"))throw wt("AES-KW");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw wt(n,"algorithm.length");break}case"ECDH":{switch(e.algorithm.name){case"ECDH":case"X25519":break;default:throw wt("ECDH or X25519")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!dr(e.algorithm,"PBKDF2"))throw wt("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!dr(e.algorithm,"RSA-OAEP"))throw wt("RSA-OAEP");wd(e.algorithm,parseInt(t.slice(9),10)||1);break}default:throw new TypeError("CryptoKey does not support this operation")}wz(e,r)}var wt,dr,Hn=q(()=>{wt=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),dr=(e,t)=>e.name===t});function kz(e,t,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var Vt,Pg,Zn=q(()=>{Vt=(e,...t)=>kz("Key must be ",e,...t),Pg=(e,t,...r)=>kz(`Key for the ${e} algorithm must be `,t,...r)});var Tg={};nr(Tg,{JOSEAlgNotAllowed:()=>un,JOSEError:()=>it,JOSENotSupported:()=>he,JWEDecryptionFailed:()=>Tr,JWEInvalid:()=>Q,JWKInvalid:()=>$s,JWKSInvalid:()=>Bo,JWKSMultipleMatchingKeys:()=>ws,JWKSNoMatchingKey:()=>Wn,JWKSTimeout:()=>zs,JWSInvalid:()=>Ae,JWSSignatureVerificationFailed:()=>Bn,JWTClaimValidationFailed:()=>ht,JWTExpired:()=>Wo,JWTInvalid:()=>tt});var it,ht,Wo,un,he,Tr,Q,Ae,tt,$s,Bo,Wn,ws,zs,Bn,Oe=q(()=>{it=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(t,r){super(t,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},ht=class extends it{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.claim=n,this.reason=o,this.payload=r}},Wo=class extends it{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.claim=n,this.reason=o,this.payload=r}},un=class extends it{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},he=class extends it{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},Tr=class extends it{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(t="decryption operation failed",r){super(t,r)}},Q=class extends it{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},Ae=class extends it{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},tt=class extends it{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},$s=class extends it{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"},Bo=class extends it{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},Wn=class extends it{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(t="no applicable key found in the JSON Web Key Set",r){super(t,r)}},ws=class extends it{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(t="multiple matching keys found in the JSON Web Key Set",r){super(t,r)}},zs=class extends it{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(t="request timed out",r){super(t,r)}},Bn=class extends it{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(t="signature verification failed",r){super(t,r)}}});function Go(e){if(!Qt(e))throw new Error("CryptoKey instance expected")}var Qt,Gn,ks,ln=q(()=>{Qt=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},Gn=e=>e?.[Symbol.toStringTag]==="KeyObject",ks=e=>Qt(e)||Gn(e)});function kd(e){switch(e){case"A128GCM":return 128;case"A192GCM":return 192;case"A256GCM":case"A128CBC-HS256":return 256;case"A192CBC-HS384":return 384;case"A256CBC-HS512":return 512;default:throw new he(`Unsupported JWE Algorithm: ${e}`)}}function zd(e,t){let r=e.byteLength<<3;if(r!==t)throw new Q(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)}function Ez(e){switch(e){case"A128GCM":case"A128GCMKW":case"A192GCM":case"A192GCMKW":case"A256GCM":case"A256GCMKW":return 96;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return 128;default:throw new he(`Unsupported JWE Algorithm: ${e}`)}}function Rz(e,t){if(t.length<<3!==Ez(e))throw new Q("Invalid Initialization Vector length")}async function xz(e,t,r){if(!(t instanceof Uint8Array))throw new TypeError(Vt(t,"Uint8Array"));let n=parseInt(e.slice(1,4),10),o=await crypto.subtle.importKey("raw",t.subarray(n>>3),"AES-CBC",!1,[r]),i=await crypto.subtle.importKey("raw",t.subarray(0,n>>3),{hash:`SHA-${n<<1}`,name:"HMAC"},!1,["sign"]);return{encKey:o,macKey:i,keySize:n}}async function Iz(e,t,r){return new Uint8Array((await crypto.subtle.sign("HMAC",e,t)).slice(0,r>>3))}async function DT(e,t,r,n,o){let{encKey:i,macKey:a,keySize:s}=await xz(e,r,"encrypt"),c=new Uint8Array(await crypto.subtle.encrypt({iv:n,name:"AES-CBC"},i,t)),u=ot(o,n,c,xg(o.length<<3)),l=await Iz(a,u,s);return{ciphertext:c,tag:l,iv:n}}async function qT(e,t){if(!(e instanceof Uint8Array))throw new TypeError("First argument must be a buffer");if(!(t instanceof Uint8Array))throw new TypeError("Second argument must be a buffer");let r={name:"HMAC",hash:"SHA-256"},n=await crypto.subtle.generateKey(r,!1,["sign"]),o=new Uint8Array(await crypto.subtle.sign(r,n,e)),i=new Uint8Array(await crypto.subtle.sign(r,n,t)),a=0,s=-1;for(;++s<32;)a|=o[s]^i[s];return a===0}async function LT(e,t,r,n,o,i){let{encKey:a,macKey:s,keySize:c}=await xz(e,t,"decrypt"),u=ot(i,n,r,xg(i.length<<3)),l=await Iz(s,u,c),d;try{d=await qT(o,l)}catch{}if(!d)throw new Tr;let m;try{m=new Uint8Array(await crypto.subtle.decrypt({iv:n,name:"AES-CBC"},a,r))}catch{}if(!m)throw new Tr;return m}async function VT(e,t,r,n,o){let i;r instanceof Uint8Array?i=await crypto.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):(Mt(r,e,"encrypt"),i=r);let a=new Uint8Array(await crypto.subtle.encrypt({additionalData:o,iv:n,name:"AES-GCM",tagLength:128},i,t)),s=a.slice(-16);return{ciphertext:a.slice(0,-16),tag:s,iv:n}}async function KT(e,t,r,n,o,i){let a;t instanceof Uint8Array?a=await crypto.subtle.importKey("raw",t,"AES-GCM",!1,["decrypt"]):(Mt(t,e,"decrypt"),a=t);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:i,iv:n,name:"AES-GCM",tagLength:128},a,ot(r,o)))}catch{throw new Tr}}async function Ed(e,t,r,n,o){if(!Qt(r)&&!(r instanceof Uint8Array))throw new TypeError(Vt(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));switch(n?Rz(e,n):n=MT(e),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&zd(r,parseInt(e.slice(-3),10)),DT(e,t,r,n,o);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&zd(r,parseInt(e.slice(1,4),10)),VT(e,t,r,n,o);default:throw new he(Pz)}}async function Rd(e,t,r,n,o,i){if(!Qt(t)&&!(t instanceof Uint8Array))throw new TypeError(Vt(t,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!n)throw new Q("JWE Initialization Vector missing");if(!o)throw new Q("JWE Authentication Tag missing");switch(Rz(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return t instanceof Uint8Array&&zd(t,parseInt(e.slice(-3),10)),LT(e,t,r,n,o,i);case"A128GCM":case"A192GCM":case"A256GCM":return t instanceof Uint8Array&&zd(t,parseInt(e.slice(1,4),10)),KT(e,t,r,n,o,i);default:throw new he(Pz)}}var pr,MT,Pz,Xn=q(()=>{gt();Hn();Zn();Oe();ln();pr=e=>crypto.getRandomValues(new Uint8Array(kd(e)>>3));MT=e=>crypto.getRandomValues(new Uint8Array(Ez(e)>>3));Pz="Unsupported JWE Content Encryption Algorithm"});function Be(e,t){if(e)throw new TypeError(`${t} can only be called once`)}function zt(e,t,r){try{return mt(e)}catch{throw new r(`Failed to base64url decode the ${t}`)}}async function Id(e,t){let r=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,t))}var xd,er=q(()=>{ft();xd=Symbol()});function Ue(e){if(!JT(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function mr(...e){let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let o=Object.keys(n);if(!r||r.size===0){r=new Set(o);continue}for(let i of o){if(r.has(i))return!1;r.add(i)}}return!0}var JT,Yn,Tz,Cz,Az,rt=q(()=>{JT=e=>typeof e=="object"&&e!==null;Yn=e=>Ue(e)&&typeof e.kty=="string",Tz=e=>e.kty!=="oct"&&(e.kty==="AKP"&&typeof e.priv=="string"||typeof e.d=="string"),Cz=e=>e.kty!=="oct"&&e.d===void 0&&e.priv===void 0,Az=e=>e.kty==="oct"&&typeof e.k=="string"});function Oz(e,t){if(e.algorithm.length!==parseInt(t.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${t}`)}function Nz(e,t,r){return e instanceof Uint8Array?crypto.subtle.importKey("raw",e,"AES-KW",!0,[r]):(Mt(e,t,r),e)}async function Es(e,t,r){let n=await Nz(t,e,"wrapKey");Oz(n,e);let o=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",o,n,"AES-KW"))}async function Rs(e,t,r){let n=await Nz(t,e,"unwrapKey");Oz(n,e);let o=await crypto.subtle.unwrapKey("raw",r,n,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",o))}var Cg=q(()=>{Hn()});function Ag(e){return ot(Sd(e.length),e)}async function HT(e,t,r){let n=t>>3,o=32,i=Math.ceil(n/o),a=new Uint8Array(i*o);for(let s=1;s<=i;s++){let c=new Uint8Array(4+e.length+r.length);c.set(Sd(s),0),c.set(e,4),c.set(r,4+e.length);let u=await Id("sha256",c);a.set(u,(s-1)*o)}return a.slice(0,n)}async function Og(e,t,r,n,o=new Uint8Array,i=new Uint8Array){Mt(e,"ECDH"),Mt(t,"ECDH","deriveBits");let a=Ag(Qe(r)),s=Ag(o),c=Ag(i),u=Sd(n),l=new Uint8Array,d=ot(a,s,c,u,l),m=new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,ZT(e)));return HT(m,n,d)}function ZT(e){return e.algorithm.name==="X25519"?256:Math.ceil(parseInt(e.algorithm.namedCurve.slice(-3),10)/8)<<3}function Ng(e){switch(e.algorithm.namedCurve){case"P-256":case"P-384":case"P-521":return!0;default:return e.algorithm.name==="X25519"}}var Uz=q(()=>{gt();Hn();er()});function BT(e,t){return e instanceof Uint8Array?crypto.subtle.importKey("raw",e,"PBKDF2",!1,["deriveBits"]):(Mt(e,t,"deriveBits"),e)}async function Mz(e,t,r,n){if(!(e instanceof Uint8Array)||e.length<8)throw new Q("PBES2 Salt Input must be 8 or more octets");let o=GT(t,e),i=parseInt(t.slice(13,16),10),a={hash:`SHA-${t.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:o},s=await BT(n,t);return new Uint8Array(await crypto.subtle.deriveBits(a,s,i))}async function Dz(e,t,r,n=2048,o=crypto.getRandomValues(new Uint8Array(16))){let i=await Mz(o,e,n,t);return{encryptedKey:await Es(e.slice(-6),i,r),p2c:n,p2s:qe(o)}}async function qz(e,t,r,n,o){let i=await Mz(o,e,n,t);return Rs(e.slice(-6),i,r)}var GT,Lz=q(()=>{ft();Cg();Hn();gt();Oe();GT=(e,t)=>ot(Qe(e),Uint8Array.of(0),t)});function xs(e,t){if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function Vz(e,t){let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new he(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Kz(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(Vt(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}return zz(t,e,r),t}async function Jz(e,t,r){let n=await Kz(e,t,"sign");xs(e,n);let o=await crypto.subtle.sign(Vz(e,n.algorithm),n,r);return new Uint8Array(o)}async function Fz(e,t,r,n){let o=await Kz(e,t,"verify");xs(e,o);let i=Vz(e,o.algorithm);try{return await crypto.subtle.verify(i,o,r,n)}catch{return!1}}var Pd=q(()=>{Oe();Hn();Zn()});async function Zz(e,t,r){return Mt(t,e,"encrypt"),xs(e,t),new Uint8Array(await crypto.subtle.encrypt(Hz(e),t,r))}async function Wz(e,t,r){return Mt(t,e,"decrypt"),xs(e,t),new Uint8Array(await crypto.subtle.decrypt(Hz(e),t,r))}var Hz,Bz=q(()=>{Hn();Pd();Oe();Hz=e=>{switch(e){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new he(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}});function QT(e){let t,r;switch(e.kty){case"AKP":{switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},r=e.priv?["sign"]:["verify"];break;default:throw new he(Td)}break}case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new he(Td)}break}case"EC":{switch(e.alg){case"ES256":case"ES384":case"ES512":t={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[e.alg]},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new he(Td)}break}case"OKP":{switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new he(Td)}break}default:throw new he('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}async function Xo(e){if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:r}=QT(e),n={...e};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,t,e.ext??!(e.d||e.priv),e.key_ops??r)}var Td,jg=q(()=>{Oe();Td='Invalid or unsupported JWK "alg" (Algorithm) Parameter value'});async function Kt(e,t){if(e instanceof Uint8Array||Qt(e))return e;if(Gn(e)){if(e.type==="secret")return e.export();if("toCryptoKey"in e&&typeof e.toCryptoKey=="function")try{return eC(e,t)}catch(n){if(n instanceof TypeError)throw n}let r=e.export({format:"jwk"});return Gz(e,r,t)}if(Yn(e))return e.k?mt(e.k):Gz(e,e,t,!0);throw new Error("unreachable")}var Yo,Qo,Gz,eC,Qn=q(()=>{rt();ft();jg();ln();Yo="given KeyObject instance cannot be used for this algorithm",Gz=async(e,t,r,n=!1)=>{Qo||=new WeakMap;let o=Qo.get(e);if(o?.[r])return o[r];let i=await Xo({...t,alg:r});return n&&Object.freeze(e),o?o[r]=i:Qo.set(e,{[r]:i}),i},eC=(e,t)=>{Qo||=new WeakMap;let r=Qo.get(e);if(r?.[t])return r[t];let n=e.type==="public",o=!!n,i;if(e.asymmetricKeyType==="x25519"){switch(t){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError(Yo)}i=e.toCryptoKey(e.asymmetricKeyType,o,n?[]:["deriveBits"])}if(e.asymmetricKeyType==="ed25519"){if(t!=="EdDSA"&&t!=="Ed25519")throw new TypeError(Yo);i=e.toCryptoKey(e.asymmetricKeyType,o,[n?"verify":"sign"])}switch(e.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(t!==e.asymmetricKeyType.toUpperCase())throw new TypeError(Yo);i=e.toCryptoKey(e.asymmetricKeyType,o,[n?"verify":"sign"])}}if(e.asymmetricKeyType==="rsa"){let a;switch(t){case"RSA-OAEP":a="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":a="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":a="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":a="SHA-512";break;default:throw new TypeError(Yo)}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:a},o,n?["encrypt"]:["decrypt"]);i=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:a},o,[n?"verify":"sign"])}if(e.asymmetricKeyType==="ec"){let s=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!s)throw new TypeError(Yo);let c={ES256:"P-256",ES384:"P-384",ES512:"P-521"};c[t]&&s===c[t]&&(i=e.toCryptoKey({name:"ECDSA",namedCurve:s},o,[n?"verify":"sign"])),t.startsWith("ECDH-ES")&&(i=e.toCryptoKey({name:"ECDH",namedCurve:s},o,n?[]:["deriveBits"]))}if(!i)throw new TypeError(Yo);return r?r[t]=i:Qo.set(e,{[t]:i}),i}});function rC(e){fr(e,48,"Invalid PKCS#8 structure"),tr(e),fr(e,2,"Expected version field");let t=tr(e);e.pos+=t,fr(e,48,"Expected algorithm identifier");let r=tr(e);return{algIdStart:e.pos,algIdLength:r}}function nC(e){fr(e,48,"Invalid SPKI structure"),tr(e),fr(e,48,"Expected algorithm identifier");let t=tr(e);return{algIdStart:e.pos,algIdLength:t}}function oC(e){let t=Dg(e);fr(t,48,"Invalid certificate structure"),tr(t),fr(t,48,"Invalid tbsCertificate structure"),tr(t),e[t.pos]===160?Mg(t,6):Mg(t,5);let r=t.pos;fr(t,48,"Invalid SPKI structure");let n=tr(t);return e.subarray(r,r+n+(t.pos-r))}function iC(e){let t=qg(e,/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g);return oC(t)}var Xz,Yz,Qz,e0,Ug,Dg,tr,Mg,fr,t0,tC,r0,n0,qg,o0,Lg,i0,Vg=q(()=>{Zn();Ig();Oe();ln();Xz=(e,t)=>{let r=(e.match(/.{1,64}/g)||[]).join(` +`);return`-----BEGIN ${t}----- +${r} +-----END ${t}-----`},Yz=async(e,t,r)=>{if(Gn(r)){if(r.type!==e)throw new TypeError(`key is not a ${e} key`);return r.export({format:"pem",type:t})}if(!Qt(r))throw new TypeError(Vt(r,"CryptoKey","KeyObject"));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==e)throw new TypeError(`key is not a ${e} key`);return Xz(bs(new Uint8Array(await crypto.subtle.exportKey(t,r))),`${e.toUpperCase()} KEY`)},Qz=e=>Yz("public","spki",e),e0=e=>Yz("private","pkcs8",e),Ug=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let r=0;r({data:e,pos:0}),tr=e=>{let t=e.data[e.pos++];if(t&128){let r=t&127,n=0;for(let o=0;o{if(t<=0)return;e.pos++;let r=tr(e);e.pos+=r,t>1&&Mg(e,t-1)},fr=(e,t,r)=>{if(e.data[e.pos++]!==t)throw new Error(r)},t0=(e,t)=>{let r=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,r},tC=e=>{fr(e,6,"Expected algorithm OID");let t=tr(e);return t0(e,t)};r0=e=>{let t=tC(e);if(Ug(t,[43,101,110]))return"X25519";if(!Ug(t,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");fr(e,6,"Expected curve OID");let r=tr(e),n=t0(e,r);for(let{name:o,oid:i}of[{name:"P-256",oid:[42,134,72,206,61,3,1,7]},{name:"P-384",oid:[43,129,4,0,34]},{name:"P-521",oid:[43,129,4,0,35]}])if(Ug(n,i))return o;throw new Error("Unsupported named curve")},n0=async(e,t,r,n)=>{let o,i,a=e==="spki",s=()=>a?["verify"]:["sign"],c=()=>a?["encrypt","wrapKey"]:["decrypt","unwrapKey"];switch(r){case"PS256":case"PS384":case"PS512":o={name:"RSA-PSS",hash:`SHA-${r.slice(-3)}`},i=s();break;case"RS256":case"RS384":case"RS512":o={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.slice(-3)}`},i=s();break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":o={name:"RSA-OAEP",hash:`SHA-${parseInt(r.slice(-3),10)||1}`},i=c();break;case"ES256":case"ES384":case"ES512":{o={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[r]},i=s();break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{try{let u=n.getNamedCurve(t);o=u==="X25519"?{name:"X25519"}:{name:"ECDH",namedCurve:u}}catch{throw new he("Invalid or unsupported key format")}i=a?[]:["deriveBits"];break}case"Ed25519":case"EdDSA":o={name:"Ed25519"},i=s();break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":o={name:r},i=s();break;default:throw new he('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(e,t,o,n?.extractable??!!a,i)},qg=(e,t)=>bd(e.replace(t,"")),o0=(e,t,r)=>{let n=qg(e,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g),o=r;return t?.startsWith?.("ECDH-ES")&&(o||={},o.getNamedCurve=i=>{let a=Dg(i);return rC(a),r0(a)}),n0("pkcs8",n,t,o)},Lg=(e,t,r)=>{let n=qg(e,/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g),o=r;return t?.startsWith?.("ECDH-ES")&&(o||={},o.getNamedCurve=i=>{let a=Dg(i);return nC(a),r0(a)}),n0("spki",n,t,o)};i0=(e,t,r)=>{let n;try{n=iC(e)}catch(o){throw new TypeError("Failed to parse the X.509 certificate",{cause:o})}return Lg(Xz(bs(n),"PUBLIC KEY"),t,r)}});async function a0(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return Lg(e,t,r)}async function s0(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN CERTIFICATE-----")!==0)throw new TypeError('"x509" must be X.509 formatted string');return i0(e,t,r)}async function c0(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return o0(e,t,r)}async function dn(e,t,r){if(!Ue(e))throw new TypeError("JWK must be an object");let n;switch(t??=e.alg,n??=r?.extractable??e.ext,e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return mt(e.k);case"RSA":if("oth"in e&&e.oth!==void 0)throw new he('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return Xo({...e,alg:t,ext:n});case"AKP":{if(typeof e.alg!="string"||!e.alg)throw new TypeError('missing "alg" (Algorithm) Parameter value');if(t!==void 0&&t!==e.alg)throw new TypeError("JWK alg and alg option value mismatch");return Xo({...e,ext:n})}case"EC":case"OKP":return Xo({...e,alg:t,ext:n});default:throw new he('Unsupported "kty" (Key Type) Parameter value')}}var Is=q(()=>{ft();Vg();jg();Oe();rt()});async function u0(e){if(Gn(e))if(e.type==="secret")e=e.export();else return e.export({format:"jwk"});if(e instanceof Uint8Array)return{kty:"oct",k:qe(e)};if(!Qt(e))throw new TypeError(Vt(e,"CryptoKey","KeyObject","Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:t,key_ops:r,alg:n,use:o,...i}=await crypto.subtle.exportKey("jwk",e);return i.kty==="AKP"&&(i.alg=n),i}var l0=q(()=>{Zn();ft();ln()});async function d0(e){return Qz(e)}async function p0(e){return e0(e)}async function ei(e){return u0(e)}var Cd=q(()=>{Vg();l0()});async function m0(e,t,r,n){let o=e.slice(0,7),i=await Ed(o,r,t,n,new Uint8Array);return{encryptedKey:i.ciphertext,iv:qe(i.iv),tag:qe(i.tag)}}async function f0(e,t,r,n,o){let i=e.slice(0,7);return Rd(i,t,r,n,o,new Uint8Array)}var h0=q(()=>{Xn();ft()});function Ps(e){if(e===void 0)throw new Q("JWE Encrypted Key missing")}async function y0(e,t,r,n,o){switch(e){case"dir":{if(r!==void 0)throw new Q("Encountered unexpected JWE Encrypted Key");return t}case"ECDH-ES":if(r!==void 0)throw new Q("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!Ue(n.epk))throw new Q('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(Go(t),!Ng(t))throw new he("ECDH with the provided key is not allowed or not supported by your javascript runtime");let i=await dn(n.epk,e);Go(i);let a,s;if(n.apu!==void 0){if(typeof n.apu!="string")throw new Q('JOSE Header "apu" (Agreement PartyUInfo) invalid');a=zt(n.apu,"apu",Q)}if(n.apv!==void 0){if(typeof n.apv!="string")throw new Q('JOSE Header "apv" (Agreement PartyVInfo) invalid');s=zt(n.apv,"apv",Q)}let c=await Og(i,t,e==="ECDH-ES"?n.enc:e,e==="ECDH-ES"?kd(n.enc):parseInt(e.slice(-5,-2),10),a,s);return e==="ECDH-ES"?c:(Ps(r),Rs(e.slice(-6),c,r))}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return Ps(r),Go(t),Wz(e,t,r);case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(Ps(r),typeof n.p2c!="number")throw new Q('JOSE Header "p2c" (PBES2 Count) missing or invalid');let i=o?.maxPBES2Count||1e4;if(n.p2c>i)throw new Q('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new Q('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let a;return a=zt(n.p2s,"p2s",Q),qz(e,t,r,n.p2c,a)}case"A128KW":case"A192KW":case"A256KW":return Ps(r),Rs(e,t,r);case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(Ps(r),typeof n.iv!="string")throw new Q('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new Q('JOSE Header "tag" (Authentication Tag) missing or invalid');let i;i=zt(n.iv,"iv",Q);let a;return a=zt(n.tag,"tag",Q),f0(e,t,r,i,a)}default:throw new he(g0)}}async function Ad(e,t,r,n,o={}){let i,a,s;switch(e){case"dir":{s=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(Go(r),!Ng(r))throw new he("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:c,apv:u}=o,l;o.epk?l=await Kt(o.epk,e):l=(await crypto.subtle.generateKey(r.algorithm,!0,["deriveBits"])).privateKey;let{x:d,y:m,crv:v,kty:g}=await ei(l),h=await Og(r,l,e==="ECDH-ES"?t:e,e==="ECDH-ES"?kd(t):parseInt(e.slice(-5,-2),10),c,u);if(a={epk:{x:d,crv:v,kty:g}},g==="EC"&&(a.epk.y=m),c&&(a.apu=qe(c)),u&&(a.apv=qe(u)),e==="ECDH-ES"){s=h;break}s=n||pr(t);let f=e.slice(-6);i=await Es(f,h,s);break}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{s=n||pr(t),Go(r),i=await Zz(e,r,s);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{s=n||pr(t);let{p2c:c,p2s:u}=o;({encryptedKey:i,...a}=await Dz(e,r,s,c,u));break}case"A128KW":case"A192KW":case"A256KW":{s=n||pr(t),i=await Es(e,r,s);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{s=n||pr(t);let{iv:c}=o;({encryptedKey:i,...a}=await m0(e,r,s,c));break}default:throw new he(g0)}return{cek:s,encryptedKey:i,parameters:a}}var g0,Od=q(()=>{Cg();Uz();Lz();Bz();ft();Qn();Oe();er();Xn();Is();Cd();rt();h0();ln();g0='Invalid or unsupported "alg" (JWE Algorithm) header value'});function hr(e,t,r,n,o){if(o.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(a=>typeof a!="string"||a.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...t.entries()]):i=t;for(let a of n.crit){if(!i.has(a))throw new he(`Extension Header Parameter "${a}" is not recognized`);if(o[a]===void 0)throw new e(`Extension Header Parameter "${a}" is missing`);if(i.get(a)&&n[a]===void 0)throw new e(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(n.crit)}var ti=q(()=>{Oe()});function Ts(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}var Kg=q(()=>{});function gr(e,t,r){switch(e.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":aC(e,t,r);break;default:sC(e,t,r)}}var ri,Jg,aC,sC,ni=q(()=>{Zn();ln();rt();ri=e=>e?.[Symbol.toStringTag],Jg=(e,t,r)=>{if(t.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(t.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let n;switch(!0){case(r==="sign"||r==="verify"):case e==="dir":case e.includes("CBC-HS"):n=r;break;case e.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):!e.includes("GCM")&&e.endsWith("KW")?n=r==="encrypt"?"wrapKey":"unwrapKey":n=r;break;case(r==="encrypt"&&e.startsWith("RSA")):n="wrapKey";break;case r==="decrypt":n=e.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&t.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},aC=(e,t,r)=>{if(!(t instanceof Uint8Array)){if(Yn(t)){if(Az(t)&&Jg(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!ks(t))throw new TypeError(Pg(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(t.type!=="secret")throw new TypeError(`${ri(t)} instances for symmetric algorithms must be of type "secret"`)}},sC=(e,t,r)=>{if(Yn(t))switch(r){case"decrypt":case"sign":if(Tz(t)&&Jg(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(Cz(t)&&Jg(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!ks(t))throw new TypeError(Pg(e,t,"CryptoKey","KeyObject","JSON Web Key"));if(t.type==="secret")throw new TypeError(`${ri(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type==="public")switch(r){case"sign":throw new TypeError(`${ri(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${ri(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type==="private")switch(r){case"verify":throw new TypeError(`${ri(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${ri(t)} instances for asymmetric algorithm encryption must be of type "public"`)}}});function v0(e){if(typeof globalThis[e]>"u")throw new he(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function _0(e){v0("CompressionStream");let t=new CompressionStream("deflate-raw"),r=t.writable.getWriter();r.write(e).catch(()=>{}),r.close().catch(()=>{});let n=[],o=t.readable.getReader();for(;;){let{value:i,done:a}=await o.read();if(a)break;n.push(i)}return ot(...n)}async function S0(e,t){v0("DecompressionStream");let r=new DecompressionStream("deflate-raw"),n=r.writable.getWriter();n.write(e).catch(()=>{}),n.close().catch(()=>{});let o=[],i=0,a=r.readable.getReader();for(;;){let{value:s,done:c}=await a.read();if(c)break;if(o.push(s),i+=s.byteLength,t!==1/0&&i>t)throw new Q("Decompressed plaintext exceeded the configured limit")}return ot(...o)}var Fg=q(()=>{Oe();gt()});async function oi(e,t,r){if(!Ue(e))throw new Q("Flattened JWE must be an object");if(e.protected===void 0&&e.header===void 0&&e.unprotected===void 0)throw new Q("JOSE Header missing");if(e.iv!==void 0&&typeof e.iv!="string")throw new Q("JWE Initialization Vector incorrect type");if(typeof e.ciphertext!="string")throw new Q("JWE Ciphertext missing or incorrect type");if(e.tag!==void 0&&typeof e.tag!="string")throw new Q("JWE Authentication Tag incorrect type");if(e.protected!==void 0&&typeof e.protected!="string")throw new Q("JWE Protected Header incorrect type");if(e.encrypted_key!==void 0&&typeof e.encrypted_key!="string")throw new Q("JWE Encrypted Key incorrect type");if(e.aad!==void 0&&typeof e.aad!="string")throw new Q("JWE AAD incorrect type");if(e.header!==void 0&&!Ue(e.header))throw new Q("JWE Shared Unprotected Header incorrect type");if(e.unprotected!==void 0&&!Ue(e.unprotected))throw new Q("JWE Per-Recipient Unprotected Header incorrect type");let n;if(e.protected)try{let $=mt(e.protected);n=JSON.parse(ct.decode($))}catch{throw new Q("JWE Protected Header is invalid")}if(!mr(n,e.header,e.unprotected))throw new Q("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let o={...n,...e.header,...e.unprotected};if(hr(Q,new Map,r?.crit,n,o),o.zip!==void 0&&o.zip!=="DEF")throw new he('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(o.zip!==void 0&&!n?.zip)throw new Q('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:i,enc:a}=o;if(typeof i!="string"||!i)throw new Q("missing JWE Algorithm (alg) in JWE Header");if(typeof a!="string"||!a)throw new Q("missing JWE Encryption Algorithm (enc) in JWE Header");let s=r&&Ts("keyManagementAlgorithms",r.keyManagementAlgorithms),c=r&&Ts("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(s&&!s.has(i)||!s&&i.startsWith("PBES2"))throw new un('"alg" (Algorithm) Header Parameter value not allowed');if(c&&!c.has(a))throw new un('"enc" (Encryption Algorithm) Header Parameter value not allowed');let u;e.encrypted_key!==void 0&&(u=zt(e.encrypted_key,"encrypted_key",Q));let l=!1;typeof t=="function"&&(t=await t(n,e),l=!0),gr(i==="dir"?a:i,t,"decrypt");let d=await Kt(t,i),m;try{m=await y0(i,d,u,o,r)}catch($){if($ instanceof TypeError||$ instanceof Q||$ instanceof he)throw $;m=pr(a)}let v,g;e.iv!==void 0&&(v=zt(e.iv,"iv",Q)),e.tag!==void 0&&(g=zt(e.tag,"tag",Q));let h=e.protected!==void 0?Qe(e.protected):new Uint8Array,f;e.aad!==void 0?f=ot(h,Qe("."),Qe(e.aad)):f=h;let y=zt(e.ciphertext,"ciphertext",Q),S=await Rd(a,m,y,v,g,f),_={plaintext:S};if(o.zip==="DEF"){let $=r?.maxDecompressedLength??25e4;if($===0)throw new he('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if($!==1/0&&(!Number.isSafeInteger($)||$<1))throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");_.plaintext=await S0(S,$).catch(k=>{throw k instanceof Q?k:new Q("Failed to decompress plaintext",{cause:k})})}return e.protected!==void 0&&(_.protectedHeader=n),e.aad!==void 0&&(_.additionalAuthenticatedData=zt(e.aad,"aad",Q)),e.unprotected!==void 0&&(_.sharedUnprotectedHeader=e.unprotected),e.header!==void 0&&(_.unprotectedHeader=e.header),l?{..._,key:d}:_}var Nd=q(()=>{ft();Xn();er();Oe();rt();rt();Od();gt();Xn();ti();Kg();Qn();ni();Fg()});async function jd(e,t,r){if(e instanceof Uint8Array&&(e=ct.decode(e)),typeof e!="string")throw new Q("Compact JWE must be a string or Uint8Array");let{0:n,1:o,2:i,3:a,4:s,length:c}=e.split(".");if(c!==5)throw new Q("Invalid Compact JWE");let u=await oi({ciphertext:a,iv:i||void 0,protected:n,tag:s||void 0,encrypted_key:o||void 0},t,r),l={plaintext:u.plaintext,protectedHeader:u.protectedHeader};return typeof t=="function"?{...l,key:u.key}:l}var Hg=q(()=>{Nd();Oe();gt()});async function b0(e,t,r){if(!Ue(e))throw new Q("General JWE must be an object");if(!Array.isArray(e.recipients)||!e.recipients.every(Ue))throw new Q("JWE Recipients missing or incorrect type");if(!e.recipients.length)throw new Q("JWE Recipients has no members");for(let n of e.recipients)try{return await oi({aad:e.aad,ciphertext:e.ciphertext,encrypted_key:n.encrypted_key,header:n.header,iv:e.iv,protected:e.protected,tag:e.tag,unprotected:e.unprotected},t,r)}catch{}throw new Tr}var $0=q(()=>{Nd();Oe();rt()});var Cr,Ud=q(()=>{ft();er();Xn();Od();Oe();rt();gt();ti();Qn();ni();Fg();Cr=class{#e;#t;#r;#n;#i;#a;#s;#o;constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this.#e=t}setKeyManagementParameters(t){return Be(this.#o,"setKeyManagementParameters"),this.#o=t,this}setProtectedHeader(t){return Be(this.#t,"setProtectedHeader"),this.#t=t,this}setSharedUnprotectedHeader(t){return Be(this.#r,"setSharedUnprotectedHeader"),this.#r=t,this}setUnprotectedHeader(t){return Be(this.#n,"setUnprotectedHeader"),this.#n=t,this}setAdditionalAuthenticatedData(t){return this.#i=t,this}setContentEncryptionKey(t){return Be(this.#a,"setContentEncryptionKey"),this.#a=t,this}setInitializationVector(t){return Be(this.#s,"setInitializationVector"),this.#s=t,this}async encrypt(t,r){if(!this.#t&&!this.#n&&!this.#r)throw new Q("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!mr(this.#t,this.#n,this.#r))throw new Q("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let n={...this.#t,...this.#n,...this.#r};if(hr(Q,new Map,r?.crit,this.#t,n),n.zip!==void 0&&n.zip!=="DEF")throw new he('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(n.zip!==void 0&&!this.#t?.zip)throw new Q('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:o,enc:i}=n;if(typeof o!="string"||!o)throw new Q('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof i!="string"||!i)throw new Q('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let a;if(this.#a&&(o==="dir"||o==="ECDH-ES"))throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${o}`);gr(o==="dir"?i:o,t,"encrypt");let s;{let y,S=await Kt(t,o);({cek:s,encryptedKey:a,parameters:y}=await Ad(o,i,S,this.#a,this.#o)),y&&(r&&xd in r?this.#n?this.#n={...this.#n,...y}:this.setUnprotectedHeader(y):this.#t?this.#t={...this.#t,...y}:this.setProtectedHeader(y))}let c,u,l,d;if(this.#t?(u=qe(JSON.stringify(this.#t)),l=Qe(u)):(u="",l=new Uint8Array),this.#i){d=qe(this.#i);let y=Qe(d);c=ot(l,Qe("."),y)}else c=l;let m=this.#e;n.zip==="DEF"&&(m=await _0(m).catch(y=>{throw new Q("Failed to compress plaintext",{cause:y})}));let{ciphertext:v,tag:g,iv:h}=await Ed(i,m,s,this.#s,c),f={ciphertext:qe(v)};return h&&(f.iv=qe(h)),g&&(f.tag=qe(g)),a&&(f.encrypted_key=qe(a)),d&&(f.aad=d),this.#t&&(f.protected=u),this.#r&&(f.unprotected=this.#r),this.#n&&(f.header=this.#n),f}}});var Zg,Md,w0=q(()=>{Ud();er();Oe();Xn();rt();Od();ft();ti();Qn();ni();Zg=class{#e;unprotectedHeader;keyManagementParameters;key;options;constructor(t,r,n){this.#e=t,this.key=r,this.options=n}setUnprotectedHeader(t){return Be(this.unprotectedHeader,"setUnprotectedHeader"),this.unprotectedHeader=t,this}setKeyManagementParameters(t){return Be(this.keyManagementParameters,"setKeyManagementParameters"),this.keyManagementParameters=t,this}addRecipient(...t){return this.#e.addRecipient(...t)}encrypt(...t){return this.#e.encrypt(...t)}done(){return this.#e}},Md=class{#e;#t=[];#r;#n;#i;constructor(t){this.#e=t}addRecipient(t,r){let n=new Zg(this,t,{crit:r?.crit});return this.#t.push(n),n}setProtectedHeader(t){return Be(this.#r,"setProtectedHeader"),this.#r=t,this}setSharedUnprotectedHeader(t){return Be(this.#n,"setSharedUnprotectedHeader"),this.#n=t,this}setAdditionalAuthenticatedData(t){return this.#i=t,this}async encrypt(){if(!this.#t.length)throw new Q("at least one recipient must be added");if(this.#t.length===1){let[o]=this.#t,i=await new Cr(this.#e).setAdditionalAuthenticatedData(this.#i).setProtectedHeader(this.#r).setSharedUnprotectedHeader(this.#n).setUnprotectedHeader(o.unprotectedHeader).encrypt(o.key,{...o.options}),a={ciphertext:i.ciphertext,iv:i.iv,recipients:[{}],tag:i.tag};return i.aad&&(a.aad=i.aad),i.protected&&(a.protected=i.protected),i.unprotected&&(a.unprotected=i.unprotected),i.encrypted_key&&(a.recipients[0].encrypted_key=i.encrypted_key),i.header&&(a.recipients[0].header=i.header),a}let t;for(let o=0;o{ft();Pd();Oe();gt();er();rt();rt();ni();ti();Kg();Qn()});async function qd(e,t,r){if(e instanceof Uint8Array&&(e=ct.decode(e)),typeof e!="string")throw new Ae("Compact JWS must be a string or Uint8Array");let{0:n,1:o,2:i,length:a}=e.split(".");if(a!==3)throw new Ae("Invalid Compact JWS");let s=await ii({payload:o,protected:n,signature:i},t,r),c={payload:s.payload,protectedHeader:s.protectedHeader};return typeof t=="function"?{...c,key:s.key}:c}var Wg=q(()=>{Dd();Oe();gt()});async function z0(e,t,r){if(!Ue(e))throw new Ae("General JWS must be an object");if(!Array.isArray(e.signatures)||!e.signatures.every(Ue))throw new Ae("JWS Signatures missing or incorrect type");for(let n of e.signatures)try{return await ii({header:n.header,payload:e.payload,protected:n.protected,signature:n.signature},t,r)}catch{}throw new Bn}var k0=q(()=>{Dd();Oe();rt()});function Cs(e){let t=lC.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),n=t[3].toLowerCase(),o;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":o=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":o=Math.round(r*R0);break;case"hour":case"hours":case"hr":case"hrs":case"h":o=Math.round(r*x0);break;case"day":case"days":case"d":o=Math.round(r*Bg);break;case"week":case"weeks":case"w":o=Math.round(r*cC);break;default:o=Math.round(r*uC);break}return t[1]==="-"||t[4]==="ago"?-o:o}function eo(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}function ai(e,t,r={}){let n;try{n=JSON.parse(ct.decode(t))}catch{}if(!Ue(n))throw new tt("JWT Claims Set must be a top-level JSON object");let{typ:o}=r;if(o&&(typeof e.typ!="string"||E0(e.typ)!==E0(o)))throw new ht('unexpected "typ" JWT header value',n,"typ","check_failed");let{requiredClaims:i=[],issuer:a,subject:s,audience:c,maxTokenAge:u}=r,l=[...i];u!==void 0&&l.push("iat"),c!==void 0&&l.push("aud"),s!==void 0&&l.push("sub"),a!==void 0&&l.push("iss");for(let g of new Set(l.reverse()))if(!(g in n))throw new ht(`missing required "${g}" claim`,n,g,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(n.iss))throw new ht('unexpected "iss" claim value',n,"iss","check_failed");if(s&&n.sub!==s)throw new ht('unexpected "sub" claim value',n,"sub","check_failed");if(c&&!dC(n.aud,typeof c=="string"?[c]:c))throw new ht('unexpected "aud" claim value',n,"aud","check_failed");let d;switch(typeof r.clockTolerance){case"string":d=Cs(r.clockTolerance);break;case"number":d=r.clockTolerance;break;case"undefined":d=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:m}=r,v=pn(m||new Date);if((n.iat!==void 0||u)&&typeof n.iat!="number")throw new ht('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new ht('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>v+d)throw new ht('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new ht('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=v-d)throw new Wo('"exp" claim timestamp check failed',n,"exp","check_failed")}if(u){let g=v-n.iat,h=typeof u=="number"?u:Cs(u);if(g-d>h)throw new Wo('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(g<0-d)throw new ht('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}var pn,R0,x0,Bg,cC,uC,lC,E0,dC,mn,si=q(()=>{Oe();gt();rt();pn=e=>Math.floor(e.getTime()/1e3),R0=60,x0=R0*60,Bg=x0*24,cC=Bg*7,uC=Bg*365.25,lC=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;E0=e=>e.includes("/")?e.toLowerCase():`application/${e.toLowerCase()}`,dC=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1;mn=class{#e;constructor(t){if(!Ue(t))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(t)}data(){return Fn.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(t){this.#e.iss=t}get sub(){return this.#e.sub}set sub(t){this.#e.sub=t}get aud(){return this.#e.aud}set aud(t){this.#e.aud=t}set jti(t){this.#e.jti=t}set nbf(t){typeof t=="number"?this.#e.nbf=eo("setNotBefore",t):t instanceof Date?this.#e.nbf=eo("setNotBefore",pn(t)):this.#e.nbf=pn(new Date)+Cs(t)}set exp(t){typeof t=="number"?this.#e.exp=eo("setExpirationTime",t):t instanceof Date?this.#e.exp=eo("setExpirationTime",pn(t)):this.#e.exp=pn(new Date)+Cs(t)}set iat(t){t===void 0?this.#e.iat=pn(new Date):t instanceof Date?this.#e.iat=eo("setIssuedAt",pn(t)):typeof t=="string"?this.#e.iat=eo("setIssuedAt",pn(new Date)+Cs(t)):this.#e.iat=eo("setIssuedAt",t)}}});async function I0(e,t,r){let n=await qd(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new tt("JWTs MUST NOT use unencoded payload");let i={payload:ai(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof t=="function"?{...i,key:n.key}:i}var P0=q(()=>{Wg();si();Oe()});async function T0(e,t,r){let n=await jd(e,t,r),o=ai(n.protectedHeader,n.plaintext,r),{protectedHeader:i}=n;if(i.iss!==void 0&&i.iss!==o.iss)throw new ht('replicated "iss" claim header parameter mismatch',o,"iss","mismatch");if(i.sub!==void 0&&i.sub!==o.sub)throw new ht('replicated "sub" claim header parameter mismatch',o,"sub","mismatch");if(i.aud!==void 0&&JSON.stringify(i.aud)!==JSON.stringify(o.aud))throw new ht('replicated "aud" claim header parameter mismatch',o,"aud","mismatch");let a={payload:o,protectedHeader:i};return typeof t=="function"?{...a,key:n.key}:a}var C0=q(()=>{Hg();si();Oe()});var ci,Gg=q(()=>{Ud();ci=class{#e;constructor(t){this.#e=new Cr(t)}setContentEncryptionKey(t){return this.#e.setContentEncryptionKey(t),this}setInitializationVector(t){return this.#e.setInitializationVector(t),this}setProtectedHeader(t){return this.#e.setProtectedHeader(t),this}setKeyManagementParameters(t){return this.#e.setKeyManagementParameters(t),this}async encrypt(t,r){let n=await this.#e.encrypt(t,r);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(".")}}});var fn,Ld=q(()=>{ft();Pd();rt();Oe();gt();ni();ti();Qn();er();fn=class{#e;#t;#r;constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#e=t}setProtectedHeader(t){return Be(this.#t,"setProtectedHeader"),this.#t=t,this}setUnprotectedHeader(t){return Be(this.#r,"setUnprotectedHeader"),this.#r=t,this}async sign(t,r){if(!this.#t&&!this.#r)throw new Ae("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!mr(this.#t,this.#r))throw new Ae("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this.#t,...this.#r},o=hr(Ae,new Map([["b64",!0]]),r?.crit,this.#t,n),i=!0;if(o.has("b64")&&(i=this.#t.b64,typeof i!="boolean"))throw new Ae('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=n;if(typeof a!="string"||!a)throw new Ae('JWS "alg" (Algorithm) Header Parameter missing or invalid');gr(a,t,"sign");let s,c;i?(s=qe(this.#e),c=Qe(s)):(c=this.#e,s="");let u,l;this.#t?(u=qe(JSON.stringify(this.#t)),l=Qe(u)):(u="",l=new Uint8Array);let d=ot(l,Qe("."),c),m=await Kt(t,a),v=await Jz(a,m,d),g={signature:qe(v),payload:s};return this.#r&&(g.header=this.#r),this.#t&&(g.protected=u),g}}});var ui,Xg=q(()=>{Ld();ui=class{#e;constructor(t){this.#e=new fn(t)}setProtectedHeader(t){return this.#e.setProtectedHeader(t),this}async sign(t,r){let n=await this.#e.sign(t,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}}});var Yg,Vd,A0=q(()=>{Ld();Oe();er();Yg=class{#e;protectedHeader;unprotectedHeader;options;key;constructor(t,r,n){this.#e=t,this.key=r,this.options=n}setProtectedHeader(t){return Be(this.protectedHeader,"setProtectedHeader"),this.protectedHeader=t,this}setUnprotectedHeader(t){return Be(this.unprotectedHeader,"setUnprotectedHeader"),this.unprotectedHeader=t,this}addSignature(...t){return this.#e.addSignature(...t)}sign(...t){return this.#e.sign(...t)}done(){return this.#e}},Vd=class{#e;#t=[];constructor(t){this.#e=t}addSignature(t,r){let n=new Yg(this,t,r);return this.#t.push(n),n}async sign(){if(!this.#t.length)throw new Ae("at least one signature must be added");let t={signatures:[],payload:""};for(let r=0;r{Xg();Oe();si();Kd=class{#e;#t;constructor(t={}){this.#t=new mn(t)}setIssuer(t){return this.#t.iss=t,this}setSubject(t){return this.#t.sub=t,this}setAudience(t){return this.#t.aud=t,this}setJti(t){return this.#t.jti=t,this}setNotBefore(t){return this.#t.nbf=t,this}setExpirationTime(t){return this.#t.exp=t,this}setIssuedAt(t){return this.#t.iat=t,this}setProtectedHeader(t){return this.#e=t,this}async sign(t,r){let n=new ui(this.#t.data());if(n.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===!1)throw new tt("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}}});var Jd,N0=q(()=>{Gg();si();er();Jd=class{#e;#t;#r;#n;#i;#a;#s;#o;constructor(t={}){this.#o=new mn(t)}setIssuer(t){return this.#o.iss=t,this}setSubject(t){return this.#o.sub=t,this}setAudience(t){return this.#o.aud=t,this}setJti(t){return this.#o.jti=t,this}setNotBefore(t){return this.#o.nbf=t,this}setExpirationTime(t){return this.#o.exp=t,this}setIssuedAt(t){return this.#o.iat=t,this}setProtectedHeader(t){return Be(this.#n,"setProtectedHeader"),this.#n=t,this}setKeyManagementParameters(t){return Be(this.#r,"setKeyManagementParameters"),this.#r=t,this}setContentEncryptionKey(t){return Be(this.#e,"setContentEncryptionKey"),this.#e=t,this}setInitializationVector(t){return Be(this.#t,"setInitializationVector"),this.#t=t,this}replicateIssuerAsHeader(){return this.#i=!0,this}replicateSubjectAsHeader(){return this.#a=!0,this}replicateAudienceAsHeader(){return this.#s=!0,this}async encrypt(t,r){let n=new ci(this.#o.data());return this.#n&&(this.#i||this.#a||this.#s)&&(this.#n={...this.#n,iss:this.#i?this.#o.iss:void 0,sub:this.#a?this.#o.sub:void 0,aud:this.#s?this.#o.aud:void 0}),n.setProtectedHeader(this.#n),this.#t&&n.setInitializationVector(this.#t),this.#e&&n.setContentEncryptionKey(this.#e),this.#r&&n.setKeyManagementParameters(this.#r),n.encrypt(t,r)}}});async function Qg(e,t){let r;if(Yn(e))r=e;else if(ks(e))r=await ei(e);else throw new TypeError(Vt(e,"CryptoKey","KeyObject","JSON Web Key"));if(t??="sha256",t!=="sha256"&&t!=="sha384"&&t!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let n;switch(r.kty){case"AKP":yr(r.alg,'"alg" (Algorithm) Parameter'),yr(r.pub,'"pub" (Public key) Parameter'),n={alg:r.alg,kty:r.kty,pub:r.pub};break;case"EC":yr(r.crv,'"crv" (Curve) Parameter'),yr(r.x,'"x" (X Coordinate) Parameter'),yr(r.y,'"y" (Y Coordinate) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":yr(r.crv,'"crv" (Subtype of Key Pair) Parameter'),yr(r.x,'"x" (Public Key) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":yr(r.e,'"e" (Exponent) Parameter'),yr(r.n,'"n" (Modulus) Parameter'),n={e:r.e,kty:r.kty,n:r.n};break;case"oct":yr(r.k,'"k" (Key Value) Parameter'),n={k:r.k,kty:r.kty};break;default:throw new he('"kty" (Key Type) Parameter missing or unsupported')}let o=Qe(JSON.stringify(n));return qe(await Id(t,o))}async function j0(e,t){t??="sha256";let r=await Qg(e,t);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${r}`}var yr,U0=q(()=>{er();ft();Oe();gt();ln();rt();Cd();Zn();yr=(e,t)=>{if(typeof e!="string"||!e)throw new $s(`${t} missing or invalid`)}});async function M0(e,t){let r={...e,...t?.header};if(!Ue(r.jwk))throw new Ae('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let n=await dn({...r.jwk,ext:!0},r.alg);if(n instanceof Uint8Array||n.type!=="public")throw new Ae('"jwk" (JSON Web Key) Header Parameter must be a public key');return n}var D0=q(()=>{Is();rt();Oe()});function pC(e){switch(typeof e=="string"&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new he('Unsupported "alg" value for a JSON Web Key Set')}}function mC(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(fC)}function fC(e){return Ue(e)}async function q0(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){let o=await dn({...t,ext:!0},r);if(o instanceof Uint8Array||o.type!=="public")throw new Bo("JSON Web Key Set members must be public keys");n[r]=o}return n[r]}function As(e){let t=new ey(e),r=async(n,o)=>t.getKey(n,o);return Object.defineProperties(r,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),r}var ey,ty=q(()=>{Is();Oe();rt();ey=class{#e;#t=new WeakMap;constructor(t){if(!mC(t))throw new Bo("JSON Web Key Set malformed");this.#e=structuredClone(t)}jwks(){return this.#e}async getKey(t,r){let{alg:n,kid:o}={...t,...r?.header},i=pC(n),a=this.#e.keys.filter(u=>{let l=i===u.kty;if(l&&typeof o=="string"&&(l=o===u.kid),l&&(typeof u.alg=="string"||i==="AKP")&&(l=n===u.alg),l&&typeof u.use=="string"&&(l=u.use==="sig"),l&&Array.isArray(u.key_ops)&&(l=u.key_ops.includes("verify")),l)switch(n){case"ES256":l=u.crv==="P-256";break;case"ES384":l=u.crv==="P-384";break;case"ES512":l=u.crv==="P-521";break;case"Ed25519":case"EdDSA":l=u.crv==="Ed25519";break}return l}),{0:s,length:c}=a;if(c===0)throw new Wn;if(c!==1){let u=new ws,l=this.#t;throw u[Symbol.asyncIterator]=async function*(){for(let d of a)try{yield await q0(l,d,n)}catch{}},u}return q0(this.#t,s,n)}}});function hC(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}async function gC(e,t,r,n=fetch){let o=await n(e,{method:"GET",signal:r,redirect:"manual",headers:t}).catch(i=>{throw i.name==="TimeoutError"?new zs:i});if(o.status!==200)throw new it("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new it("Failed to parse the JSON Web Key Set HTTP response as JSON")}}function yC(e,t){return!(typeof e!="object"||e===null||!("uat"in e)||typeof e.uat!="number"||Date.now()-e.uat>=t||!("jwks"in e)||!Ue(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,Ue))}function L0(e,t){let r=new ny(e,t),n=async(o,i)=>r.getKey(o,i);return Object.defineProperties(n,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>r.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>r.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}var ry,oy,Os,ny,V0=q(()=>{Oe();ty();rt();(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(ry="jose/v6.2.2");oy=Symbol();Os=Symbol();ny=class{#e;#t;#r;#n;#i;#a;#s;#o;#c;#u;constructor(t,r){if(!(t instanceof URL))throw new TypeError("url must be an instance of URL");this.#e=new URL(t.href),this.#t=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.#r=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.#n=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5,this.#s=new Headers(r?.headers),ry&&!this.#s.has("User-Agent")&&this.#s.set("User-Agent",ry),this.#s.has("accept")||(this.#s.set("accept","application/json"),this.#s.append("accept","application/jwk-set+json")),this.#o=r?.[oy],r?.[Os]!==void 0&&(this.#u=r?.[Os],yC(r?.[Os],this.#n)&&(this.#i=this.#u.uat,this.#c=As(this.#u.jwks)))}pendingFetch(){return!!this.#a}coolingDown(){return typeof this.#i=="number"?Date.now(){this.#c=As(t),this.#u&&(this.#u.uat=Date.now(),this.#u.jwks=t),this.#i=Date.now(),this.#a=void 0}).catch(t=>{throw this.#a=void 0,t}),await this.#a}}});var Fd,K0=q(()=>{ft();gt();Oe();si();Fd=class{#e;constructor(t={}){this.#e=new mn(t)}encode(){let t=qe(JSON.stringify({alg:"none"})),r=qe(this.#e.data());return`${t}.${r}.`}setIssuer(t){return this.#e.iss=t,this}setSubject(t){return this.#e.sub=t,this}setAudience(t){return this.#e.aud=t,this}setJti(t){return this.#e.jti=t,this}setNotBefore(t){return this.#e.nbf=t,this}setExpirationTime(t){return this.#e.exp=t,this}setIssuedAt(t){return this.#e.iat=t,this}static decode(t,r){if(typeof t!="string")throw new tt("Unsecured JWT must be a string");let{0:n,1:o,2:i,length:a}=t.split(".");if(a!==3||i!=="")throw new tt("Invalid Unsecured JWT");let s;try{if(s=JSON.parse(ct.decode(mt(n))),s.alg!=="none")throw new Error}catch{throw new tt("Invalid Unsecured JWT")}return{payload:ai(s,mt(o),r),header:s}}}});function J0(e){let t;if(typeof e=="string"){let r=e.split(".");(r.length===3||r.length===5)&&([t]=r)}else if(typeof e=="object"&&e)if("protected"in e)t=e.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof t!="string"||!t)throw new Error;let r=JSON.parse(ct.decode(mt(t)));if(!Ue(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}var F0=q(()=>{ft();gt();rt()});function H0(e){if(typeof e!="string")throw new tt("JWTs must use Compact JWS serialization, JWT must be a string");let{1:t,length:r}=e.split(".");if(r===5)throw new tt("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new tt("Invalid JWT");if(!t)throw new tt("JWTs must contain a payload");let n;try{n=mt(t)}catch{throw new tt("Failed to base64url decode the payload")}let o;try{o=JSON.parse(ct.decode(n))}catch{throw new tt("Failed to parse the decoded payload as JSON")}if(!Ue(o))throw new tt("Invalid JWT Claims Set");return o}var Z0=q(()=>{ft();gt();rt();Oe()});function iy(e){let t=e?.modulusLength??2048;if(typeof t!="number"||t<2048)throw new he("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function W0(e,t){let r,n;switch(e){case"PS256":case"PS384":case"PS512":r={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:iy(t)},n=["sign","verify"];break;case"RS256":case"RS384":case"RS512":r={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:iy(t)},n=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":r={name:"RSA-OAEP",hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:iy(t)},n=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":r={name:"ECDSA",namedCurve:"P-256"},n=["sign","verify"];break;case"ES384":r={name:"ECDSA",namedCurve:"P-384"},n=["sign","verify"];break;case"ES512":r={name:"ECDSA",namedCurve:"P-521"},n=["sign","verify"];break;case"Ed25519":case"EdDSA":{n=["sign","verify"],r={name:"Ed25519"};break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{n=["sign","verify"],r={name:e};break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{n=["deriveBits"];let o=t?.crv??"P-256";switch(o){case"P-256":case"P-384":case"P-521":{r={name:"ECDH",namedCurve:o};break}case"X25519":r={name:"X25519"};break;default:throw new he("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519")}break}default:throw new he('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return crypto.subtle.generateKey(r,t?.extractable??!1,n)}var B0=q(()=>{Oe()});async function G0(e,t){let r,n,o;switch(e){case"HS256":case"HS384":case"HS512":r=parseInt(e.slice(-3),10),n={name:"HMAC",hash:`SHA-${r}`,length:r},o=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r=parseInt(e.slice(-3),10),crypto.getRandomValues(new Uint8Array(r>>3));case"A128KW":case"A192KW":case"A256KW":r=parseInt(e.slice(1,4),10),n={name:"AES-KW",length:r},o=["wrapKey","unwrapKey"];break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":case"A128GCM":case"A192GCM":case"A256GCM":r=parseInt(e.slice(1,4),10),n={name:"AES-GCM",length:r},o=["encrypt","decrypt"];break;default:throw new he('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return crypto.subtle.generateKey(n,t?.extractable??!1,o)}var X0=q(()=>{Oe()});var Y0={};nr(Y0,{CompactEncrypt:()=>ci,CompactSign:()=>ui,EmbeddedJWK:()=>M0,EncryptJWT:()=>Jd,FlattenedEncrypt:()=>Cr,FlattenedSign:()=>fn,GeneralEncrypt:()=>Md,GeneralSign:()=>Vd,SignJWT:()=>Kd,UnsecuredJWT:()=>Fd,base64url:()=>$d,calculateJwkThumbprint:()=>Qg,calculateJwkThumbprintUri:()=>j0,compactDecrypt:()=>jd,compactVerify:()=>qd,createLocalJWKSet:()=>As,createRemoteJWKSet:()=>L0,cryptoRuntime:()=>vC,customFetch:()=>oy,decodeJwt:()=>H0,decodeProtectedHeader:()=>J0,errors:()=>Tg,exportJWK:()=>ei,exportPKCS8:()=>p0,exportSPKI:()=>d0,flattenedDecrypt:()=>oi,flattenedVerify:()=>ii,generalDecrypt:()=>b0,generalVerify:()=>z0,generateKeyPair:()=>W0,generateSecret:()=>G0,importJWK:()=>dn,importPKCS8:()=>c0,importSPKI:()=>a0,importX509:()=>s0,jwksCache:()=>Os,jwtDecrypt:()=>T0,jwtVerify:()=>I0});var vC,Q0=q(()=>{Hg();Nd();$0();w0();Wg();Dd();k0();P0();C0();Gg();Ud();Xg();Ld();A0();O0();N0();U0();D0();ty();V0();K0();Cd();Is();F0();Z0();Oe();B0();X0();ft();vC="WebCryptoAPI"});var Uk={};nr(Uk,{AuthorizationServerMismatchError:()=>Wd,BAGGAGE_META_KEY:()=>ou,CLIENT_CAPABILITIES_META_KEY:()=>Gr,CLIENT_INFO_META_KEY:()=>On,Client:()=>oA,ClientCredentialsProvider:()=>CC,CrossAppAccessProvider:()=>NC,DEFAULT_NEGOTIATED_PROTOCOL_VERSION:()=>tu,DEFAULT_REQUEST_TIMEOUT_MSEC:()=>fs,INTERNAL_ERROR:()=>uu,INVALID_PARAMS:()=>cu,INVALID_REQUEST:()=>au,InMemoryResponseCacheStore:()=>Ik,InMemoryTransport:()=>Hw,InsecureTokenEndpointError:()=>fy,InsufficientScopeError:()=>dy,IssuerMismatchError:()=>Xd,JSONRPC_VERSION:()=>Xr,LATEST_PROTOCOL_VERSION:()=>Br,LOG_LEVEL_META_KEY:()=>Nn,MAX_CACHE_TTL_MS:()=>Pk,METHOD_NOT_FOUND:()=>su,MissingRequiredClientCapabilityError:()=>Bh,OAuthClientFlowError:()=>di,OAuthError:()=>xr,OAuthErrorCode:()=>Rr,PARSE_ERROR:()=>iu,PROTOCOL_VERSION_META_KEY:()=>cr,PrivateKeyJwtProvider:()=>AC,Protocol:()=>ag,ProtocolError:()=>Me,ProtocolErrorCode:()=>fe,RELATED_TASK_META_KEY:()=>Ra,ReadBuffer:()=>Kw,RegistrationRejectedError:()=>lk,ResourceNotFoundError:()=>Zh,SERVER_INFO_META_KEY:()=>ur,SSEClientTransport:()=>dA,STDIO_DEFAULT_MAX_BUFFER_SIZE:()=>ug,SUBSCRIPTION_ID_META_KEY:()=>xo,SUPPORTED_PROTOCOL_VERSIONS:()=>Ea,SdkError:()=>ae,SdkErrorCode:()=>se,SdkHttpError:()=>lr,SseError:()=>jk,StaticPrivateKeyJwtProvider:()=>OC,StreamableHTTPClientTransport:()=>hA,TRACEPARENT_META_KEY:()=>ru,TRACESTATE_META_KEY:()=>nu,UnauthorizedError:()=>at,UnsupportedProtocolVersionError:()=>ms,UriTemplate:()=>Fw,UrlElicitationRequiredError:()=>Wh,applyMiddlewares:()=>uA,assertCompleteRequestPrompt:()=>xw,assertCompleteRequestResourceTemplate:()=>Iw,assertSecureTokenEndpoint:()=>Qd,auth:()=>li,buildDiscoveryUrls:()=>wk,checkResourceAllowed:()=>Lh,computeScopeUnion:()=>Bd,createFetchWithInit:()=>od,createMiddleware:()=>lA,createPrivateKeyJwtAuth:()=>xk,deserializeMessage:()=>lg,discoverAndRequestJwtAuthGrant:()=>iA,discoverAuthorizationServerMetadata:()=>ep,discoverOAuthMetadata:()=>PC,discoverOAuthProtectedResourceMetadata:()=>gy,discoverOAuthServerInfo:()=>yy,exchangeAuthorization:()=>TC,exchangeJwtAuthGrant:()=>aA,extractResourceMetadataUrl:()=>RC,extractWWWAuthenticateParams:()=>Ar,fetchToken:()=>Ek,fromJsonSchema:()=>yA,getDisplayName:()=>Vw,getSupportedElicitationModes:()=>Ok,isCallToolResult:()=>Ew,isHttpsUrl:()=>hy,isInitializeRequest:()=>rd,isInitializedNotification:()=>eg,isInputRequiredResult:()=>td,isJSONRPCErrorResponse:()=>Vn,isJSONRPCNotification:()=>Qh,isJSONRPCRequest:()=>sn,isJSONRPCResponse:()=>kw,isJSONRPCResultResponse:()=>qn,isJsonContentType:()=>Lw,isSpecType:()=>og,isStrictScopeSuperset:()=>fk,isTaskAugmentedRequestParams:()=>Rw,mergeCapabilities:()=>sg,parseErrorResponse:()=>py,parseJSONRPCMessage:()=>zw,preloadSchemas:()=>Zw,prepareAuthorizationCodeRequest:()=>vy,refreshAuthorization:()=>kk,registerClient:()=>Rk,requestJwtAuthorizationGrant:()=>Nk,resolveClientMetadata:()=>_k,resourceUrlFromServerUrl:()=>qh,selectClientAuthMethod:()=>gk,selectResourceURL:()=>Sk,serializeMessage:()=>Jw,specTypeSchemas:()=>Dw,startAuthorization:()=>zk,validateAuthorizationResponseIssuer:()=>Ns,validateClientMetadataUrl:()=>EC,withInputRequired:()=>Ow,withLogging:()=>cA,withOAuth:()=>sA});function ek(e,t,r){if(e!==void 0)return e.issuer===void 0?(r?.canPersistStamp!==!1&&console.warn("[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ensure your provider round-trips the issuer field."),e):dk(e.issuer,t)?e:void 0}function dk(e,t){return e===t||e.endsWith("/")&&e.slice(0,-1)===t||t.endsWith("/")&&t.slice(0,-1)===e}function pk(e){if(e==null)return!1;let t=e;return typeof t.tokens=="function"&&typeof t.clientInformation=="function"}async function _C(e,t,r){let{resourceMetadataUrl:n,scope:o}=Ar(t.response);if(await li(e,{serverUrl:t.serverUrl,resourceMetadataUrl:n,scope:o,fetchFn:t.fetchFn,...r})!=="AUTHORIZED")throw new at}function mk(e,t){return{token:async()=>(await e.tokens())?.access_token,onUnauthorized:async r=>_C(e,r,t)}}function Yd(e){return e?.authorization_response_iss_parameter_supported===!0}function Ns({iss:e,expectedIssuer:t,issParameterSupported:r}){if(t!==void 0){if(e===void 0){if(r)throw new Xd("authorization_response",t,void 0);return}if(e!==t)throw new Xd("authorization_response",t,e)}}function Bd(...e){let t=new Set;for(let r of e)if(r)for(let n of r.split(/\s+/))n&&t.add(n);return t.size>0?[...t].join(" "):void 0}function fk(e,t){if(!e)return!1;let r=new Set((t??"").split(/\s+/).filter(Boolean));for(let n of e.split(/\s+/))if(n&&!r.has(n))return!0;return!1}async function hk(e,t,r,n,o){if(typeof e=="string")return{authorizationCode:e,iss:t};let i=e.get("iss")??void 0,a=e.get("code");if(a)return{authorizationCode:a,iss:i};let s=(await r.discoveryState?.())?.authorizationServerMetadata;if(!s)try{s=(await yy(n,o)).authorizationServerMetadata}catch{s=void 0}if(!s)throw new at("Authorization callback failed and the issuer could not be verified");Ns({iss:i,expectedIssuer:s.issuer,issParameterSupported:Yd(s)});let c=e.get("error");throw c?new xr(c,e.get("error_description")??c,e.get("error_uri")??void 0):new at("Authorization callback contained neither `code` nor `error`")}function SC(e){return["client_secret_basic","client_secret_post","none"].includes(e)}function gk(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&SC(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function yk(e,t,r,n){let{client_id:o,client_secret:i}=t;switch(e){case"client_secret_basic":bC(o,i,r);return;case"client_secret_post":$C(o,i,n);return;case"none":wC(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function bC(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}function $C(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function wC(e,t){t.set("client_id",e)}function vk(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function Qd(e){let t=new URL(String(e));if(t.protocol!=="https:"&&!vk(t.hostname))throw new fy(t.href);return t}function zC(e){for(let t of e??[]){let r;try{r=new URL(t)}catch{continue}if(r.protocol!=="http:"&&r.protocol!=="https:"||vk(r.hostname))return"native"}return"web"}function _k(e){let t=e.clientMetadata;return{...t,grant_types:t.grant_types??(e.redirectUrl===void 0?void 0:["authorization_code","refresh_token"]),application_type:t.application_type??zC(t.redirect_uris)}}async function py(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let n=Mn.parse(JSON.parse(r));return xr.fromResponse(n)}catch(n){let o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new xr(Rr.ServerError,o)}}async function li(e,t){try{return await cy(e,t)}catch(r){if(r instanceof xr){if(r.code===Rr.InvalidClient||r.code===Rr.UnauthorizedClient)return await e.invalidateCredentials?.("client"),await e.invalidateCredentials?.("tokens"),await cy(e,t);if(r.code===Rr.InvalidGrant)return await e.invalidateCredentials?.("tokens"),await cy(e,t)}throw r}}function kC(e){let{requestedScope:t,resourceMetadata:r,authServerMetadata:n,clientMetadata:o}=e,i=t||r?.scopes_supported?.join(" ")||o.scope;return i&&n?.scopes_supported?.includes("offline_access")&&!i.split(" ").includes("offline_access")&&o.grant_types?.includes("refresh_token")&&(i=`${i} offline_access`),i}async function cy(e,{serverUrl:t,authorizationCode:r,iss:n,scope:o,resourceMetadataUrl:i,fetchFn:a,skipIssuerMetadataValidation:s,forceReauthorization:c}){let u=_k(e),l=await e.discoveryState?.(),d,m,v,g,h=i;if(!h&&l?.resourceMetadataUrl&&(h=new URL(l.resourceMetadataUrl)),l?.authorizationServerUrl){if(m=l.authorizationServerUrl,d=l.resourceMetadata,v=l.authorizationServerMetadata??await ep(m,{fetchFn:a,skipIssuerValidation:s}),!d)try{d=await gy(t,{resourceMetadataUrl:h},a)}catch(A){if(A instanceof TypeError)throw A}(v!==l.authorizationServerMetadata||d!==l.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(m),resourceMetadataUrl:h?.toString(),resourceMetadata:d,authorizationServerMetadata:v})}else{let A=await yy(t,{resourceMetadataUrl:h,fetchFn:a,skipIssuerMetadataValidation:s});m=A.authorizationServerUrl,v=A.authorizationServerMetadata,d=A.resourceMetadata,g={authorizationServerUrl:String(m),resourceMetadataUrl:h?.toString(),resourceMetadata:d,authorizationServerMetadata:v}}let f=v?.issuer??String(m),y={issuer:f};if(await e.saveAuthorizationServerUrl?.(f),r!==void 0){let A=l?.authorizationServerMetadata?.issuer??l?.authorizationServerUrl;if(A===void 0){if(e.saveDiscoveryState!==void 0)throw new Wd("discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier",f);console.warn("[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); the SEP-2352 callback-leg authorization-server binding cannot be checked. Implement discoveryState (persist alongside codeVerifier) \u2014 see docs/migration/upgrade-to-v2.md \xA7SEP-2352.")}else if(!dk(A,f))throw new Wd(A,f)}g&&await e.saveDiscoveryState?.(g);let S=await Sk(t,e,d);S&&await e.saveResourceUrl?.(String(S));let _=kC({requestedScope:o,resourceMetadata:d,authServerMetadata:v,clientMetadata:e.clientMetadata}),$=await Promise.resolve(e.clientInformation(y)),k=ek($,f,{canPersistStamp:e.saveClientInformation!==void 0});if(k===void 0&&$?.issuer&&e.saveClientInformation===void 0)throw new Wd($.issuer,f);if(k&&k.issuer===void 0&&(k={...k,issuer:f},await e.saveClientInformation?.(k,y)),!k){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let A=v?.client_id_metadata_document_supported===!0,L=e.clientMetadataUrl;if(L&&!hy(L))throw new xr(Rr.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${L}`);if(A&&L)k={client_id:L,issuer:f},await e.saveClientInformation?.(k,y);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");k={...await Rk(m,{metadata:v,clientMetadata:u,scope:_,fetchFn:a}),issuer:f},await e.saveClientInformation(k,y)}}let w=!e.redirectUrl;if(r!==void 0||w){r!==void 0&&Ns({iss:n,expectedIssuer:v?.issuer,issParameterSupported:Yd(v)});let A=await Ek(e,m,{metadata:v,resource:S,authorizationCode:r,iss:n,scope:_,fetchFn:a});return await e.saveTokens({...A,issuer:f},y),"AUTHORIZED"}let b=ek(await e.tokens(y),f);if(b&&b.issuer===void 0&&(b={...b,issuer:f},await e.saveTokens(b,y)),b?.refresh_token&&!c)try{let A=await kk(m,{metadata:v,clientInformation:k,refreshToken:b.refresh_token,resource:S,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens({...A,issuer:f},y),"AUTHORIZED"}catch(A){if(A instanceof fy||!(!(A instanceof xr)||A.code===Rr.ServerError))throw A}let E=e.state?await e.state():void 0,{authorizationUrl:j,codeVerifier:V}=await zk(m,{metadata:v,clientInformation:k,state:E,redirectUrl:e.redirectUrl,scope:_,resource:S});return await e.saveCodeVerifier(V),await e.redirectToAuthorization(j),"REDIRECT"}function EC(e){if(e&&!hy(e))throw new xr(Rr.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${e}`)}function hy(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function Sk(e,t,r){let n=qh(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!Lh({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function Ar(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,n]=t.split(" ");if(r?.toLowerCase()!=="bearer"||!n)return{};let o=Hd(e,"resource_metadata")||void 0,i;if(o)try{i=new URL(o)}catch{}let a=Hd(e,"scope")||void 0,s=Hd(e,"error")||void 0,c=Hd(e,"error_description")||void 0;return{resourceMetadataUrl:i,scope:a,error:s,errorDescription:c}}function Hd(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let n=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),o=r.match(n);if(o){let i=o[1]||o[2];if(i)return i}return null}function RC(e){let t=e.headers.get("WWW-Authenticate");if(!t)return;let[r,n]=t.split(" ");if(r?.toLowerCase()!=="bearer"||!n)return;let o=/resource_metadata="([^"]*)"/.exec(t);if(!(!o||!o[1]))try{return new URL(o[1])}catch{return}}async function gy(e,t,r=fetch){let n=await $k(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.text?.().catch(()=>{}),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.text?.().catch(()=>{}),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return rs.parse(await n.json())}async function bk(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(!(n instanceof TypeError)||!hz)throw n;if(t)try{return await r(e,{})}catch(o){if(!(o instanceof TypeError))throw o;return}return}}function xC(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function tk(e,t,r=fetch){return await bk(e,{"MCP-Protocol-Version":t},r)}function IC(e,t){return e?t==="/"?!1:e.status>=400&&e.status<500||e.status===502:!0}async function $k(e,t,r,n){let o=new URL(e),i=n?.protocolVersion??Br,a;if(n?.metadataUrl)a=new URL(n.metadataUrl);else{let c=xC(t,o.pathname);a=new URL(c,n?.metadataServerUrl??o),a.search=o.search}let s=await tk(a,i,r);return!n?.metadataUrl&&IC(s,o.pathname)&&(s=await tk(new URL(`/.well-known/${t}`,o),i,r)),s}async function PC(e,{authorizationServerUrl:t,protocolVersion:r}={},n=fetch){typeof e=="string"&&(e=new URL(e)),t||(t=e),typeof t=="string"&&(t=new URL(t)),r??=Br;let o=await $k(t,"oauth-authorization-server",n,{protocolVersion:r,metadataServerUrl:t});if(!o||o.status===404){await o?.text?.().catch(()=>{});return}if(!o.ok)throw await o.text?.().catch(()=>{}),new Error(`HTTP ${o.status} trying to load well-known OAuth metadata`);return Un.parse(await o.json())}function wk(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"},{url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"},{url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function ep(e,{fetchFn:t=fetch,protocolVersion:r=Br,skipIssuerValidation:n=!1}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},i=wk(e);for(let{url:a,type:s}of i){let c=await bk(a,o,t);if(!c)continue;if(!c.ok){if(await c.text?.().catch(()=>{}),c.status>=400&&c.status<500||c.status===502)continue;throw new Error(`HTTP ${c.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}let u=s==="oauth"?Un.parse(await c.json()):ns.parse(await c.json());if(!n){let l=typeof e=="string"?e:e.href;if(!(u.issuer===l||l.endsWith("/")&&u.issuer===l.slice(0,-1)))throw new Xd("metadata",l,u.issuer)}return u}}async function yy(e,t){let r,n;try{r=await gy(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(n=r.authorization_servers[0])}catch(i){if(i instanceof TypeError)throw i}n||(n=String(new URL("/",e)));let o=await ep(n,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}async function zk(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:i,resource:a}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(ay))throw new Error(`Incompatible auth server: does not support response type ${ay}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(sy))throw new Error(`Incompatible auth server: does not support code challenge method ${sy}`)}else s=new URL("/authorize",e);let c=await hg(),u=c.code_verifier,l=c.code_challenge;return s.searchParams.set("response_type",ay),s.searchParams.set("client_id",r.client_id),s.searchParams.set("code_challenge",l),s.searchParams.set("code_challenge_method",sy),s.searchParams.set("redirect_uri",String(n)),i&&s.searchParams.set("state",i),o&&s.searchParams.set("scope",o),o?.split(" ").includes("offline_access")&&s.searchParams.append("prompt","consent"),a&&s.searchParams.set("resource",a.href),{authorizationUrl:s,codeVerifier:u}}function vy(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function _y(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:i,fetchFn:a}){let s=Qd(t?.token_endpoint??new URL("/token",e)),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});i&&r.set("resource",i.href),o?await o(c,r,s,t):n&&yk(gk(n,t?.token_endpoint_auth_methods_supported??[]),n,c,r);let u=await(a??fetch)(s,{method:"POST",headers:c,body:r});if(!u.ok)throw await py(u);let l=await u.json();try{return Lo.parse(l)}catch(d){throw typeof l=="object"&&l!==null&&"error"in l?await py(JSON.stringify(l)):d}}async function TC(e,{metadata:t,clientInformation:r,authorizationCode:n,iss:o,codeVerifier:i,redirectUri:a,resource:s,addClientAuthentication:c,fetchFn:u}){return Ns({iss:o,expectedIssuer:t?.issuer,issParameterSupported:Yd(t)}),_y(e,{metadata:t,tokenRequestParams:vy(n,i,a),clientInformation:r,addClientAuthentication:c,resource:s,fetchFn:u})}async function kk(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:i,fetchFn:a}){return{refresh_token:n,...await _y(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),clientInformation:r,addClientAuthentication:i,resource:o,fetchFn:a})}}async function Ek(e,t,{metadata:r,resource:n,authorizationCode:o,iss:i,scope:a,fetchFn:s}={}){o!==void 0&&Ns({iss:i,expectedIssuer:r?.issuer,issParameterSupported:Yd(r)});let c=a??e.clientMetadata.scope,u;if(e.prepareTokenRequest&&(u=await e.prepareTokenRequest(c)),!u){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");u=vy(o,await e.codeVerifier(),e.redirectUrl)}let l=await e.clientInformation({issuer:r?.issuer??String(t)});return _y(t,{metadata:r,tokenRequestParams:u,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function Rk(e,{metadata:t,clientMetadata:r,scope:n,fetchFn:o}){let i;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);let a={...r,...n===void 0?{}:{scope:n}},s=await(o??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!s.ok)throw new lk({status:s.status,body:await s.text(),submittedMetadata:a});return is.parse(await s.json())}function xk(e){return async(t,r,n,o)=>{if(globalThis.crypto===void 0)throw new TypeError("crypto is not available, please ensure you have Web Crypto API support for older Node.js versions (see https://github.com/modelcontextprotocol/typescript-sdk#nodejs-web-crypto-globalthiscrypto-compatibility)");let i=await Promise.resolve().then(()=>(Q0(),Y0)),a=String(e.audience??o?.issuer??n),s=e.lifetimeSeconds??300,c=Math.floor(Date.now()/1e3),u=`${Date.now()}-${Math.random().toString(36).slice(2)}`,l={iss:e.issuer,sub:e.subject,aud:a,exp:c+s,iat:c,jti:u},d=e.claims?{...l,...e.claims}:l,m=e.alg,v;if(typeof e.privateKey=="string")if(m.startsWith("RS")||m.startsWith("ES")||m.startsWith("PS"))v=await i.importPKCS8(e.privateKey,m);else if(m.startsWith("HS"))v=new TextEncoder().encode(e.privateKey);else throw new Error(`Unsupported algorithm ${m}`);else e.privateKey instanceof Uint8Array?v=m.startsWith("HS")?e.privateKey:await i.importPKCS8(new TextDecoder().decode(e.privateKey),m):v=await i.importJWK(e.privateKey,m);let g=await new i.SignJWT(d).setProtectedHeader({alg:m,typ:"JWT"}).setIssuer(e.issuer).setSubject(e.subject).setAudience(a).setIssuedAt(c).setExpirationTime(c+s).setJti(u).sign(v);r.set("client_assertion",g),r.set("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer")}}function uy(e){return`${e.method}\0${JSON.stringify([e.partition??"",e.params??""])}`}function ly(e,t){return t===void 0?e:`${e}\0${t}`}function UC(e){let t;try{t=JSON.stringify(e)}catch(r){throw new TypeError(`cache value is not JSON-serializable: ${r instanceof Error?r.message:String(r)}`)}if(typeof t!="string")throw new TypeError("cache value is not JSON-serializable: it has no JSON representation");return t}function qC(e,t){switch(e.kind){case"result":return LC(e.result,t);case"rpc-error":return Tk(e,t);case"http-error":return VC(e,t);case"network-error":return rk(e.error,t);case"auth-required":return{kind:"error",error:e.error};case"closed":return t.transportKind==="stdio"?{kind:"legacy"}:rk(new Error("Connection closed during the version negotiation probe"),t);case"timeout":return t.transportKind==="stdio"?{kind:"legacy"}:{kind:"error",error:new ae(se.RequestTimeout,`Version negotiation probe timed out after ${e.timeoutMs}ms`,{timeout:e.timeoutMs})}}}function LC(e,t){let r=Er(ed).validateResult("server/discover",e);if(!r.ok)return{kind:"legacy"};let n=r.value.supportedVersions,o=t.clientModernVersions.find(i=>n.includes(i));return o!==void 0?{kind:"modern",version:o,discover:r.value}:t.fallbackAvailable?{kind:"legacy"}:{kind:"error",error:new ms({supported:[...n],requested:t.requestedVersion})}}function Tk(e,t){let{code:r,message:n,data:o}=e;if(r===MC){let i=FC(o);if(i===void 0)return{kind:"legacy"};let a=new ms({supported:i,requested:HC(o)??t.requestedVersion},n),s=ps(i),c=t.clientModernVersions.find(u=>s.includes(u));return c!==void 0?{kind:"corrective",version:c,error:a}:s.length>0?{kind:"error",error:a}:t.fallbackAvailable?{kind:"legacy"}:{kind:"error",error:a}}return DC.has(r)?{kind:"legacy"}:{kind:"legacy"}}function VC(e,t){let r=ZC(e.body);return r!==void 0?Tk(r,t):{kind:"legacy"}}function rk(e,t){return t.environment==="browser"&&KC(e)?{kind:"legacy"}:{kind:"error",error:new ae(se.EraNegotiationFailed,`Version negotiation probe failed: ${JC(e)}`,{cause:e})}}function KC(e){return e instanceof TypeError||e instanceof Error&&e.name==="TypeError"}function JC(e){return e instanceof Error?e.message:String(e)}function FC(e){if(typeof e!="object"||e===null)return;let t=e.supported;if(!(!Array.isArray(t)||t.length===0||!t.every(r=>typeof r=="string")))return t}function HC(e){if(typeof e!="object"||e===null)return;let t=e.requested;return typeof t=="string"?t:void 0}function ZC(e){if(e===void 0||e==="")return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!="object"||t===null)return;let r=t.error;if(typeof r!="object"||r===null)return;let{code:n,message:o,data:i}=r;if(typeof n=="number")return{code:n,message:typeof o=="string"?o:"",data:i}}function BC(e,t){let r=e?.mode??WC;if(r==="legacy")return{kind:"legacy"};let n=e?.probe??{};if(typeof r=="object"){if(!Ir(r.pin))throw new TypeError(`versionNegotiation: { pin: '${r.pin}' } is not a modern protocol revision \u2014 pinning is for 2026-07-28 and later; omit versionNegotiation (or use mode: 'legacy') for 2025-era servers.`);return{kind:"pin",version:r.pin,probe:n}}let o=t?ps(t):[];return{kind:"auto",modernVersions:o.length>0?o:[...Vh],fallbackAvailable:t?Kh(t).length>0:!0,probe:n}}function nk(){let e=globalThis;return e.window!==void 0&&e.document!==void 0?"browser":"node"}function ok(e){return"stderr"in e&&"pid"in e?"stdio":"http"}function ik(e){let t=my.get(e);my.delete(e),t?.()}function XC(e,t,r,n){return{jsonrpc:"2.0",id:e,method:"server/discover",params:{_meta:Er(t).outboundEnvelope({protocolVersion:t,clientInfo:r,clientCapabilities:n})}}}function YC(e,t){switch(e.kind){case"response":return e.error===void 0?{kind:"result",result:e.result}:{kind:"rpc-error",...e.error};case"send-error":{let r=e.error;if(r instanceof lr){let n=r.data?.text;return{kind:"http-error",status:r.data.status,body:typeof n=="string"?n:void 0}}return r instanceof at||r instanceof Error&&r.name==="UnauthorizedError"?{kind:"auth-required",error:r}:{kind:"network-error",error:r}}case"closed":return{kind:"closed"};case"timeout":return{kind:"timeout",timeoutMs:t}}}async function Ak(e,t){let r=e.probe.timeoutMs??t.defaultTimeoutMs,n=Math.max(0,e.probe.maxRetries??0),o=e.kind==="pin"?[e.version]:e.modernVersions,i=e.kind==="auto"&&e.fallbackAvailable,a=await GC.open(t.transport),s=async()=>{let u=o[0],l=!1,d=n;for(;;){let m=await a.exchange(h=>XC(h,u,t.clientInfo,t.capabilities),r);if(m.kind==="timeout"&&d>0){d--;continue}let v=YC(m,r),g=qC(v,{clientModernVersions:o,requestedVersion:u,fallbackAvailable:i,environment:t.environment,transportKind:t.transportKind});switch(g.kind){case"modern":return{era:"modern",version:g.version,discover:g.discover};case"corrective":if(l)throw g.error;l=!0,u=g.version;continue;case"legacy":{let h=v.kind==="closed"?"the connection closed during the server/discover probe":void 0;if(e.kind==="pin")throw new ae(se.EraNegotiationFailed,h===void 0?`Version negotiation failed: the server did not offer pinned protocol version ${e.version} via server/discover (no fallback in pin mode)`:`Version negotiation failed: ${h} before the server offered pinned protocol version ${e.version} (no fallback in pin mode)`);if(!e.fallbackAvailable)throw new ae(se.EraNegotiationFailed,h===void 0?"Version negotiation failed: the server gave no modern evidence and this client supports no pre-2026-07-28 protocol version to fall back to":`Version negotiation failed: ${h} and this client supports no pre-2026-07-28 protocol version to fall back to`);if(h!==void 0&&t.disposableProbe!==!0)throw new ae(se.EraNegotiationFailed,`Version negotiation failed: ${h} (this transport probed in place \u2014 the disposable sibling probe requires the SDK's base StdioClientTransport)`);return{era:"legacy"}}case"error":throw g.error}}},c;try{c=await s()}catch(u){throw a.detach(),u}return a.release(),c}function QC(e){let t=Object.getPrototypeOf(e);if(t===null||!Object.prototype.hasOwnProperty.call(t,"_dispose"))return;let r=e._serverParams;return typeof r=="object"&&r!==null&&typeof r.command=="string"?r:void 0}async function eA(e,t,r,n){let o=t.constructor,i=new o({...r,stderr:"ignore"}),a=t.close,s=!1,c,u=new Promise((d,m)=>{c=()=>m(ak())});t.close=async function(){return s=!0,c?.(),a.call(t)};let l;try{let d=Ak(e,{...n,transport:i,transportKind:"stdio",disposableProbe:!0});d.catch(()=>{}),l=await Promise.race([d,u])}finally{await tA(i),t.close=a}if(s)throw ak();return l}function ak(){return new ae(se.EraNegotiationFailed,"Version negotiation failed: the transport was closed during the server/discover probe")}async function tA(e){try{let t=e._dispose;await(typeof t=="function"?t.call(e):e.close())}catch{}}function sk(e){let t=e._meta?.[ur];return og.Implementation(t)?t:void 0}function Gd(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){let r=t,n=e.properties;for(let o of Object.keys(n)){let i=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(r[o]=i.default),r[o]!==void 0&&Gd(i,r[o])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&Gd(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&Gd(r,t)}}function Ok(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}function rA(e){if(typeof e=="object"&&e!==null&&(e.kind==="legacy"&&!("supportedVersions"in e)&&!("discover"in e)||e.kind==="modern"&&jn.safeParse(e.discover).success))return e;throw new ae(se.EraNegotiationFailed,"connect({ prior }): unrecognized prior \u2014 expected { kind: 'modern', discover } or { kind: 'legacy' }")}async function Nk(e){let{tokenEndpoint:t,audience:r,resource:n,idToken:o,clientId:i,clientSecret:a,scope:s,fetchFn:c=fetch}=e,u=Qd(t),l=new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",requested_token_type:"urn:ietf:params:oauth:token-type:id-jag",audience:String(r),resource:String(n),subject_token:o,subject_token_type:"urn:ietf:params:oauth:token-type:id_token",client_id:i});a&&l.set("client_secret",a),s&&l.set("scope",s);let d=await c(u,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:l.toString()});if(!d.ok){let v=await d.json().catch(()=>({})),g=Mn.safeParse(v);if(g.success){let{error:h,error_description:f}=g.data;throw new Error(`Token exchange failed: ${h}${f?` - ${f}`:""}`)}throw new Error(`Token exchange failed with status ${d.status}: ${JSON.stringify(v)}`)}let m=os.safeParse(await d.json());if(!m.success)throw new Error(`Invalid token exchange response: ${m.error.message}`);return{jwtAuthGrant:m.data.access_token,expiresIn:m.data.expires_in,scope:m.data.scope}}async function iA(e){let{idpUrl:t,fetchFn:r=fetch,...n}=e,o=await ep(String(t),{fetchFn:r});if(!o?.token_endpoint)throw new Error(`Failed to discover token endpoint for IdP: ${t}`);return Nk({...n,tokenEndpoint:o.token_endpoint,fetchFn:r})}async function aA(e){let{tokenEndpoint:t,jwtAuthGrant:r,clientId:n,clientSecret:o,authMethod:i="client_secret_basic",fetchFn:a=fetch}=e,s=Qd(t),c=new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:r}),u=new Headers({"Content-Type":"application/x-www-form-urlencoded"});yk(i,{client_id:n,client_secret:o},u,c);let l=await a(s,{method:"POST",headers:u,body:c.toString()});if(!l.ok){let v=await l.json().catch(()=>({})),g=Mn.safeParse(v);if(g.success){let{error:h,error_description:f}=g.data;throw new Error(`JWT grant exchange failed: ${h}${f?` - ${f}`:""}`)}throw new Error(`JWT grant exchange failed with status ${l.status}: ${JSON.stringify(v)}`)}let d=await l.json(),m=Lo.safeParse(d);if(!m.success)throw new Error(`Invalid token response: ${m.error.message}`);return m.data}function uk(e,t){if(typeof AbortSignal.any=="function")return AbortSignal.any([e,t]);let r=new AbortController;if(e.aborted)return r.abort(e.reason),r.signal;if(t.aborted)return r.abort(t.reason),r.signal;let n=()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",i)};function o(){n(),r.abort(e.reason)}function i(){n(),r.abort(t.reason)}return e.addEventListener("abort",o,{once:!0}),t.addEventListener("abort",i,{once:!0}),r.signal}function yA(e,t){return Ww(e,t??(gA??=new pd))}var di,Xd,lk,fy,Wd,dy,at,ay,sy,CC,AC,OC,NC,Zd,Ik,Pk,jC,MC,DC,WC,GC,my,ck,nA,oA,sA,cA,uA,lA,jk,dA,pA,mA,fA,hA,gA,Mk=q(()=>{Bw();gz();yz();bz();$z();di=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthClientFlowError"})}static[Symbol.hasInstance](e){return Ut(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Ut(this,e)}constructor(e){super(e),this.name=new.target.name,Ln(this,new.target)}},Xd=class extends di{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.IssuerMismatchError"})}kind;expected;received;constructor(e,t,r){super(`Issuer mismatch in ${e==="metadata"?"authorization server metadata (RFC 8414 \xA73.3)":"authorization response (RFC 9207)"}: expected ${JSON.stringify(t)}, received ${JSON.stringify(r)}`),this.kind=e,this.expected=t,this.received=r}},lk=class extends di{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.RegistrationRejectedError"})}status;body;submittedMetadata;constructor(e){super(`Dynamic Client Registration rejected (HTTP ${e.status}): ${e.body}`),this.status=e.status,this.body=e.body,this.submittedMetadata=e.submittedMetadata}},fy=class extends di{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsecureTokenEndpointError"})}tokenEndpoint;constructor(e){super(`Refusing to send credentials to non-https token endpoint '${e}'. OAuth token requests MUST use TLS (localhost / 127.0.0.1 / ::1 are exempt).`),this.tokenEndpoint=e}},Wd=class extends di{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.AuthorizationServerMismatchError"})}constructor(e,t){super(`Authorization server changed between redirect and callback (redirected to ${JSON.stringify(e)}, callback resolved ${JSON.stringify(t)}); refusing to send authorization_code/code_verifier to a different token endpoint`),this.recordedIssuer=e,this.currentIssuer=t}},dy=class extends di{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.InsufficientScopeError"})}requiredScope;resourceMetadataUrl;errorDescription;constructor(e){super(`Insufficient scope${e.requiredScope?`: required "${e.requiredScope}"`:""}`),this.requiredScope=e.requiredScope,this.resourceMetadataUrl=e.resourceMetadataUrl,this.errorDescription=e.errorDescription}};at=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnauthorizedError"})}static[Symbol.hasInstance](e){return Ut(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Ut(this,e)}constructor(e){super(e??"Unauthorized"),this.name="UnauthorizedError",Ln(this,new.target)}};ay="code",sy="S256";CC=class{_tokens;_clientInfo;_clientMetadata;constructor(e){this._clientInfo={client_id:e.clientId,client_secret:e.clientSecret,issuer:e.expectedIssuer},this._clientMetadata={client_name:e.clientName??"client-credentials-client",redirect_uris:[],grant_types:["client_credentials"],token_endpoint_auth_method:"client_secret_basic",scope:e.scope}}get redirectUrl(){}get clientMetadata(){return this._clientMetadata}clientInformation(){return this._clientInfo}tokens(){return this._tokens}saveTokens(e){this._tokens=e}redirectToAuthorization(){throw new Error("redirectToAuthorization is not used for client_credentials flow")}saveCodeVerifier(){}codeVerifier(){throw new Error("codeVerifier is not used for client_credentials flow")}prepareTokenRequest(e){let t=new URLSearchParams({grant_type:"client_credentials"});return e&&t.set("scope",e),t}},AC=class{_tokens;_clientInfo;_clientMetadata;addClientAuthentication;constructor(e){this._clientInfo={client_id:e.clientId,issuer:e.expectedIssuer},this._clientMetadata={client_name:e.clientName??"private-key-jwt-client",redirect_uris:[],grant_types:["client_credentials"],token_endpoint_auth_method:"private_key_jwt",scope:e.scope},this.addClientAuthentication=xk({issuer:e.clientId,subject:e.clientId,privateKey:e.privateKey,alg:e.algorithm,lifetimeSeconds:e.jwtLifetimeSeconds,claims:e.claims})}get redirectUrl(){}get clientMetadata(){return this._clientMetadata}clientInformation(){return this._clientInfo}tokens(){return this._tokens}saveTokens(e){this._tokens=e}redirectToAuthorization(){throw new Error("redirectToAuthorization is not used for client_credentials flow")}saveCodeVerifier(){}codeVerifier(){throw new Error("codeVerifier is not used for client_credentials flow")}prepareTokenRequest(e){let t=new URLSearchParams({grant_type:"client_credentials"});return e&&t.set("scope",e),t}},OC=class{_tokens;_clientInfo;_clientMetadata;addClientAuthentication;constructor(e){this._clientInfo={client_id:e.clientId,issuer:e.expectedIssuer},this._clientMetadata={client_name:e.clientName??"static-private-key-jwt-client",redirect_uris:[],grant_types:["client_credentials"],token_endpoint_auth_method:"private_key_jwt",scope:e.scope};let t=e.jwtBearerAssertion;this.addClientAuthentication=async(r,n)=>{n.set("client_assertion",t),n.set("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer")}}get redirectUrl(){}get clientMetadata(){return this._clientMetadata}clientInformation(){return this._clientInfo}tokens(){return this._tokens}saveTokens(e){this._tokens=e}redirectToAuthorization(){throw new Error("redirectToAuthorization is not used for client_credentials flow")}saveCodeVerifier(){}codeVerifier(){throw new Error("codeVerifier is not used for client_credentials flow")}prepareTokenRequest(e){let t=new URLSearchParams({grant_type:"client_credentials"});return e&&t.set("scope",e),t}},NC=class{_tokens;_clientInfo;_clientMetadata;_assertionCallback;_fetchFn;_authorizationServerUrl;_resourceUrl;_scope;constructor(e){this._clientInfo={client_id:e.clientId,client_secret:e.clientSecret,issuer:e.expectedIssuer},this._clientMetadata={client_name:e.clientName??"cross-app-access-client",redirect_uris:[],grant_types:["urn:ietf:params:oauth:grant-type:jwt-bearer"],token_endpoint_auth_method:"client_secret_basic"},this._assertionCallback=e.assertion,this._fetchFn=e.fetchFn??fetch}get redirectUrl(){}get clientMetadata(){return this._clientMetadata}clientInformation(){return this._clientInfo}tokens(){return this._tokens}saveTokens(e){this._tokens=e}redirectToAuthorization(){throw new Error("redirectToAuthorization is not used for jwt-bearer flow")}saveCodeVerifier(){}codeVerifier(){throw new Error("codeVerifier is not used for jwt-bearer flow")}saveAuthorizationServerUrl(e){this._authorizationServerUrl=e}authorizationServerUrl(){return this._authorizationServerUrl}saveResourceUrl(e){this._resourceUrl=e}resourceUrl(){return this._resourceUrl}async prepareTokenRequest(e){let t=this._authorizationServerUrl,r=this._resourceUrl;if(!t)throw new Error("Authorization server URL not available. Ensure auth() has been called first.");if(!r)throw new Error("Resource URL not available \u2014 server may not implement RFC 9728 Protected Resource Metadata (required for Cross-App Access), or auth() has not been called");this._scope=e;let n=await this._assertionCallback({authorizationServerUrl:t,resourceUrl:r,scope:this._scope,fetchFn:this._fetchFn}),o=new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:n});return e&&o.set("scope",e),o}},Zd=new Set(["tools/list","prompts/list","resources/list","resources/templates/list","server/discover"]),Ik=class{_entries=new Map;_maxEntries;_stamp=0;_cappedSize=0;constructor(e){this._maxEntries=e?.maxEntries??512}get size(){return this._entries.size}get(e){return this._entries.get(uy(e))}set(e,t){let r=uy(e),n=Zd.has(e.method),o=!this._entries.has(r);if(!n&&o&&this._maxEntries>0&&this._cappedSize>=this._maxEntries){for(let a of this._entries.keys())if(!Zd.has(a.slice(0,a.indexOf("\0")))){this._entries.delete(a),this._cappedSize--;break}}let i=++this._stamp;return this._entries.set(r,{...t,stamp:i}),o&&!n&&this._cappedSize++,i}delete(e){this._entries.delete(uy(e))&&!Zd.has(e.method)&&this._cappedSize--}evict(e){let t=`${e}\0`,r=Zd.has(e);for(let n of this._entries.keys())n.startsWith(t)&&(this._entries.delete(n),r||this._cappedSize--)}clear(){this._entries.clear(),this._cappedSize=0}};Pk=864e5,jC=class{_evictionGeneration=new Map;_toolIndex;_toolOutputValidatorIndex;_serverIdentity="";constructor(e,t,r=()=>{},n="",o=Date.now){this._store=e,this._isUserSupplied=t,this._reportError=r,this._cachePartition=n,this._now=o}now(){return this._now()}setServerIdentity(e){this._serverIdentity=e}_partitionFor(e){return JSON.stringify([this._serverIdentity,e==="public"?"":this._cachePartition])}async _probe(e,t){let r={method:e,params:t??""},n=this._partitionFor("private"),o=await this._store.get({...r,partition:n});if(o!==void 0)return o;let i=this._partitionFor("public");if(i===n)return;let a=await this._store.get({...r,partition:i});return a?.scope==="public"?a:void 0}async evict(e){this._evictionGeneration.set(e,(this._evictionGeneration.get(e)??0)+1),await this._deleteBoth(e,"")}async _deleteBoth(e,t){let r=this._partitionFor("private"),n=this._partitionFor("public");try{await this._store.delete({method:e,params:t,partition:r})}catch(o){this._reportError(o)}if(n!==r)try{await this._store.delete({method:e,params:t,partition:n})}catch(o){this._reportError(o)}}async evictKey(e,t){let r=ly(e,t),n=this._evictionGeneration.get(r);n!==void 0&&this._evictionGeneration.set(r,n+1),await this._deleteBoth(e,t)}captureGeneration(e,t){let r=ly(e,t),n=this._evictionGeneration.get(r)??0;return this._evictionGeneration.set(r,n),n}async write(e,t,r,n){if((this._evictionGeneration.get(ly(e,n?.params))??0)!==r)return;let o=n?.params??"",i=this._partitionFor("private"),a=this._partitionFor("public"),s=(n?.scope??"private")==="public"?a:i;try{await this._store.set({method:e,params:o,partition:s},{value:UC(t),expiresAt:n?.expiresAt,scope:n?.scope})}catch(c){this._reportError(c)}if(a!==i)try{await this._store.delete({method:e,params:o,partition:s===i?a:i})}catch(c){this._reportError(c)}}async read(e,t){let r=await this._probe(e,t);if(!(r?.expiresAt===void 0||!(r.expiresAt>this.now())))try{let n=JSON.parse(r.value);if(typeof n!="object"||n===null||Array.isArray(n))throw new TypeError("cached document is not an object");return{value:n}}catch(n){this._reportError(n),await this._deleteBoth(e,t??"");return}}resetForReconnect(){this._isUserSupplied||this._store.clear(),this._evictionGeneration.clear(),this._toolIndex=void 0,this._toolOutputValidatorIndex=void 0,this._serverIdentity=""}async toolDefinition(e){let t=await this._probe("tools/list");if(t===void 0){this._toolIndex=void 0;return}if(this._toolIndex?.stamp!==t.stamp){let r=this._decodeListTools(t),n=new Map;if(r!==void 0)for(let o of r.tools)n.set(o.name,o);this._toolIndex={stamp:t.stamp,byName:n}}return this._toolIndex.byName.get(e)}async outputValidator(e,t){let r=await this._probe("tools/list");if(r===void 0){this._toolOutputValidatorIndex=void 0;return}if(this._toolOutputValidatorIndex?.stamp!==r.stamp){let n=this._decodeListTools(r)??{tools:[]},o=new Map;for(let i of n.tools){let a=t(i);a!==void 0&&o.set(i.name,a)}this._toolOutputValidatorIndex={stamp:r.stamp,byName:o}}return this._toolOutputValidatorIndex.byName.get(e)}_decodeListTools(e){try{let t=JSON.parse(e.value);if(!Array.isArray(t?.tools)||!t.tools.every(r=>r!==null&&typeof r=="object"))throw new TypeError("cached tools/list document has a malformed tools array");return t}catch(t){this._reportError(t);return}}};MC=-32022,DC=new Set([-32001,-32020,-32021]);WC="legacy";GC=class Ck{_pending;_probeCounter=0;_savedOnMessage;_savedOnError;_savedOnClose;_closeDelivered=!1;constructor(t){this._transport=t,this._savedOnMessage=t.onmessage,this._savedOnError=t.onerror,this._savedOnClose=t.onclose}static async open(t){let r=new Ck(t);t.onmessage=n=>{let o=r._pending;if(o!==void 0&&(qn(n)||Vn(n))&&n.id===o.id){r._pending=void 0,qn(n)?o.resolve({kind:"response",result:n.result}):o.resolve({kind:"response",error:n.error});return}},t.onerror=n=>{r._savedOnError?.(n)},t.onclose=()=>{let n=r._pending;n!==void 0&&(r._pending=void 0,n.resolve({kind:"closed"})),r._closeDelivered=!0,r._savedOnClose?.()};try{await t.start()}catch(n){throw r.detach(),n}return r}async exchange(t,r){let n=`server-discover-probe-${++this._probeCounter}`;return new Promise(o=>{let i=!1,a=c=>{i||(i=!0,clearTimeout(s),this._pending?.id===n&&(this._pending=void 0),o(c))},s=setTimeout(()=>a({kind:"timeout"}),r);this._pending={id:n,resolve:a},this._transport.send(t(n)).catch(c=>a({kind:"send-error",error:c}))})}detach(){if(this._pending=void 0,this._transport.onmessage=this._savedOnMessage,this._transport.onerror=this._savedOnError,this._closeDelivered&&this._savedOnClose!==void 0){let t=this._savedOnClose,r=this._transport,n=!1,o=()=>{if(!n){n=!0;return}t()};r.onclose=o,my.set(r,()=>{r.onclose===o&&(r.onclose=t)})}else this._transport.onclose=this._savedOnClose}release(){this.detach();let t=this._transport,r=t.start,n=!0;t.start=async function(){if(n){n=!1,t.start=r;return}return r.call(t)}}},my=new WeakMap;ck={"notifications/tools/list_changed":["tools/list"],"notifications/prompts/list_changed":["prompts/list"],"notifications/resources/list_changed":["resources/list","resources/templates/list"]},nA=64,oA=class extends ag{_serverCapabilities;_serverVersion;_capabilities;_instructions;_jsonSchemaValidator;_cache;_defaultCacheTtlMs;_listMaxPages;_listChangedDebounceTimers=new Map;_listChangedConfig;_enforceStrictCapabilities;_versionNegotiation;_supportedProtocolVersionsOption;_inputRequiredDriverConfig;_listenState=new Map;_nextListenId=0;_autoOpenedSubscription;_discoverResult;_resetConnectionState(){if(this._negotiatedProtocolVersion=void 0,this._serverCapabilities=void 0,this._serverVersion=void 0,this._instructions=void 0,this._discoverResult=void 0,this._autoOpenedSubscription=void 0,this._listenState.size>0){let e=new ae(se.ConnectionClosed,"subscriptions/listen: client reconnected or closed; subscription state from the previous connection was reset");for(let t of this._listenState.values())t.settle({cause:"remote",error:e})}this._listenState.clear();for(let e of this._listChangedDebounceTimers.values())clearTimeout(e);this._listChangedDebounceTimers.clear(),this._cache.resetForReconnect()}async close(){try{await super.close()}finally{this._resetConnectionState()}}constructor(e,t){super(t),this._clientInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new pd,this._enforceStrictCapabilities=t?.enforceStrictCapabilities??!1,this._versionNegotiation=t?.versionNegotiation,this._supportedProtocolVersionsOption=t?.supportedProtocolVersions,this._inputRequiredDriverConfig=Nw(t?.inputRequired),this._cache=new jC(t?.responseCacheStore??new Ik,t?.responseCacheStore!==void 0,r=>this._reportStoreError(r),t?.cachePartition??""),this._defaultCacheTtlMs=t?.defaultCacheTtlMs??0,this._listMaxPages=t?.listMaxPages??nA,t?.listChanged&&(this._listChangedConfig=t.listChanged)}buildContext(e,t){return e}_shouldDropInbound(e){if(this._negotiatedProtocolVersion!==void 0&&Ir(this._negotiatedProtocolVersion)&&sn(e))return"drop"}_outboundMetaEnvelope(){let e=this._negotiatedProtocolVersion;if(e!==void 0)return this._wireCodec().outboundEnvelope({protocolVersion:e,clientInfo:this._clientInfo,clientCapabilities:this._capabilities})}_resolveNonCompleteResult(e,t){return this._inputRequiredDriverConfig.autoFulfill?qw({getRequestHandler:r=>this._getRequestHandler(r),buildContext:r=>this.buildContext(r,void 0),sessionId:this.transport?.sessionId},this._inputRequiredDriverConfig,e,t):Promise.reject(new ae(se.UnsupportedResultType,`Unsupported result type 'input_required' for ${t.request.method}: multi-round-trip auto-fulfilment is not enabled on this instance \u2014 pass allowInputRequired: true to handle it manually, or enable inputRequired.autoFulfill`,{resultType:"input_required",method:t.request.method}))}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools","notifications/tools/list_changed",e.tools,async()=>(await this.listTools(void 0,{cacheMode:"refresh"})).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts","notifications/prompts/list_changed",e.prompts,async()=>(await this.listPrompts(void 0,{cacheMode:"refresh"})).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources","notifications/resources/list_changed",e.resources,async()=>(await this.listResources(void 0,{cacheMode:"refresh"})).resources)}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=sg(this._capabilities,e)}setVersionNegotiation(e){if(this.transport)throw new Error("Cannot configure version negotiation after connecting to transport");this._versionNegotiation=e}_wrapHandler(e,t){return e==="elicitation/create"?async(r,n)=>{let o=Er(this._negotiatedProtocolVersion),i=o.validateRequest("elicitation/create",r);if(!i.ok&&i.reason==="not-in-era"&&(i=o.validateInputRequest("elicitation/create",r)),!i.ok)throw new Me(i.reason==="not-in-era"?fe.InternalError:fe.InvalidParams,i.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation request: ${i.message}`);let{params:a}=i.value;a.mode=a.mode??"form";let{supportsFormMode:s,supportsUrlMode:c}=Ok(this._capabilities.elicitation);if(a.mode==="form"&&!s)throw new Me(fe.InvalidParams,"Client does not support form-mode elicitation requests");if(a.mode==="url"&&!c)throw new Me(fe.InvalidParams,"Client does not support URL-mode elicitation requests");let u=await t(r,n),l=o.validateResult("elicitation/create",u);if(!l.ok&&l.reason==="not-in-era"&&(l=o.validateInputResponse("elicitation/create",u)),!l.ok)throw new Me(l.reason==="not-in-era"?fe.InternalError:fe.InvalidParams,l.reason==="not-in-era"?"No wire schema for elicitation/create in the resolved era":`Invalid elicitation result: ${l.message}`);let d=l.value,m=a.mode==="form"?a.requestedSchema:void 0;if(a.mode==="form"&&d.action==="accept"&&d.content&&m&&this._capabilities.elicitation?.form?.applyDefaults)try{Gd(m,d.content)}catch{}return d}:e==="sampling/createMessage"?async(r,n)=>{let o=Er(this._negotiatedProtocolVersion),i=o.validateRequest("sampling/createMessage",r);if(!i.ok&&i.reason==="not-in-era"&&(i=o.validateInputRequest("sampling/createMessage",r)),!i.ok)throw new Me(i.reason==="not-in-era"?fe.InternalError:fe.InvalidParams,i.reason==="not-in-era"?"No wire schema for sampling/createMessage in the resolved era":`Invalid sampling request: ${i.message}`);let{params:a}=i.value,s=await t(r,n),c=!!(a.tools||a.toolChoice),u=o.samplingResultVariant(c,s);if(!u.ok&&u.reason==="not-in-era"&&(u=o.validateInputResponse("sampling/createMessage",s)),!u.ok)throw new Me(u.reason==="not-in-era"?fe.InternalError:fe.InvalidParams,u.reason==="not-in-era"?"No result schema for sampling/createMessage in the resolved era":`Invalid sampling result: ${u.message}`);return u.value}:t}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new ae(se.CapabilityNotSupported,`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(t?.prior!=null)return this._connectFromPrior(e,rA(t.prior),t);let r=BC(this._versionNegotiation,this._supportedProtocolVersionsOption);return r.kind!=="legacy"?this._connectNegotiated(e,r,t):this._connectPlainLegacy(e,t)}async _connectPlainLegacy(e,t){if(await super.connect(e),e.sessionId!==void 0){let r=this._negotiatedProtocolVersion;r!==void 0&&e.setProtocolVersion?.(r);return}this._resetConnectionState(),await this._legacyHandshake(e,t)}async _legacyHandshake(e,t){let r=Kh(this._supportedProtocolVersions);try{let n=r[0];if(n===void 0)throw new ae(se.EraNegotiationFailed,"Cannot run the initialize handshake: supportedProtocolVersions contains no pre-2026-07-28 protocol version");let o=await this.request({method:"initialize",params:{protocolVersion:n,capabilities:this._capabilities,clientInfo:this._clientInfo}},t);if(o===void 0)throw new Error(`Server sent invalid initialize result: ${o}`);if(!r.includes(o.protocolVersion))throw new Error(`Server's protocol version is not supported: ${o.protocolVersion}`);this._serverCapabilities=o.capabilities,this._serverVersion=o.serverInfo,this._cache.setServerIdentity(this._deriveServerIdentity(e)),e.setProtocolVersion&&e.setProtocolVersion(o.protocolVersion),this._instructions=o.instructions,await this.notification({method:"notifications/initialized"}),this._negotiatedProtocolVersion=o.protocolVersion,this._listChangedConfig&&this._setupListChangedHandlers(this._listChangedConfig)}catch(n){throw this.close(),n}}async _connectNegotiated(e,t,r){if(e.sessionId!==void 0){await super.connect(e);let o=this._negotiatedProtocolVersion;o!==void 0&&e.setProtocolVersion&&e.setProtocolVersion(o);return}this._resetConnectionState();let n;try{let o=ok(e),i={clientInfo:this._clientInfo,capabilities:this._capabilities,environment:nk(),defaultTimeoutMs:r?.timeout??fs},a=o==="stdio"?QC(e):void 0;n=a===void 0?await Ak(t,{...i,transport:e,transportKind:o}):await eA(t,e,a,i)}catch(o){throw await e.close().catch(()=>{}),ik(e),o}if(ik(e),await super.connect(e),n.era==="legacy"){await this._legacyHandshake(e,r);return}if(this._serverCapabilities=n.discover.capabilities,this._serverVersion=sk(n.discover),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=n.discover.instructions,this._discoverResult=n.discover,this._negotiatedProtocolVersion=n.version,e.setProtocolVersion&&e.setProtocolVersion(n.version),this._listChangedConfig){let o=this._listChangedConfig,i=this._serverCapabilities,a={...o.tools&&i?.tools?.listChanged&&{tools:o.tools},...o.prompts&&i?.prompts?.listChanged&&{prompts:o.prompts},...o.resources&&i?.resources?.listChanged&&{resources:o.resources}},s=!0;try{this._setupListChangedHandlers(a)}catch(u){s=!1,this.onerror?.(u instanceof Error?u:new Error(String(u)))}let c=s?{...a.tools&&{toolsListChanged:!0},...a.prompts&&{promptsListChanged:!0},...a.resources&&{resourcesListChanged:!0}}:{};if(Object.keys(c).length>0){let u=new AbortController,l=()=>u.abort(r?.signal?.reason);r?.signal?.aborted&&l(),r?.signal?.addEventListener("abort",l);try{this._autoOpenedSubscription=await this.listen(c,{timeout:r?.timeout,signal:u.signal})}catch(d){if(r?.signal?.aborted)throw await this.close().catch(()=>{}),d;this.onerror?.(d instanceof Error?d:new Error(String(d)))}finally{r?.signal?.removeEventListener("abort",l)}}}}async _connectFromPrior(e,t,r){if(t.kind==="legacy")return this._connectPlainLegacy(e,r);let n=t.discover;this._resetConnectionState();let o=this._supportedProtocolVersionsOption,i=(o&&ps(o).length>0?ps(o):Vh).find(a=>n.supportedVersions.includes(a));if(i===void 0)throw new ae(se.EraNegotiationFailed,"connect({ prior }) with a modern verdict requires a 2026-07-28+ mutual protocol version; the supplied DiscoverResult and this client's supportedProtocolVersions have no modern overlap. For a server known to be legacy, pass prior: { kind: 'legacy' } to skip the probe and initialize directly, or use versionNegotiation: { mode: 'auto' } to re-probe with legacy fallback.");if(await super.connect(e),this._discoverResult=n,this._serverCapabilities=n.capabilities,this._serverVersion=sk(n),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=n.instructions,this._negotiatedProtocolVersion=i,e.setProtocolVersion?.(i),this._listChangedConfig)try{this._setupListChangedHandlers(this._listChangedConfig)}catch(a){this.onerror?.(a instanceof Error?a:new Error(String(a)))}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}_deriveServerIdentity(e){let t=this._serverVersion;return t!==void 0?`${t.name}@${t.version}`:e.sessionId??`anonymous:${Date.now()}-${Math.random().toString(36).slice(2)}`}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}getProtocolEra(){let e=this._negotiatedProtocolVersion;if(e!==void 0)return Ir(e)?"modern":"legacy"}getInstructions(){return this._instructions}getDiscoverResult(){return this._discoverResult}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new ae(se.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new ae(se.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new ae(se.CapabilityNotSupported,`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new ae(se.CapabilityNotSupported,`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new ae(se.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new ae(se.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case"initialize":break;case"server/discover":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new ae(se.CapabilityNotSupported,`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new ae(se.CapabilityNotSupported,`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new ae(se.CapabilityNotSupported,`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new ae(se.CapabilityNotSupported,`Client does not support roots capability (required for ${e})`);break;case"ping":break}}async ping(e){return this.request({method:"ping"},e)}async discover(e){let t=await this._requestWithSchema({method:"server/discover"},jn,e);return this._discoverResult=t,t}async complete(e,t){return this.request({method:"completion/complete",params:e},t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},t)}async listPrompts(e,t){if(!this._serverCapabilities?.prompts&&!this._enforceStrictCapabilities)return console.debug("Client.listPrompts() called but server does not advertise prompts capability - returning empty list"),{prompts:[]};if(e?.cursor!==void 0)return this.request({method:"prompts/list",params:e},t);let r=await this._serveFromCache("prompts/list",void 0,t);return r!==void 0?r:this._listAllPages("prompts/list",e,t,(n,o)=>n.prompts.push(...o.prompts))}async listResources(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResources() called but server does not advertise resources capability - returning empty list"),{resources:[]};if(e?.cursor!==void 0)return this.request({method:"resources/list",params:e},t);let r=await this._serveFromCache("resources/list",void 0,t);return r!==void 0?r:this._listAllPages("resources/list",e,t,(n,o)=>n.resources.push(...o.resources))}async listResourceTemplates(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug("Client.listResourceTemplates() called but server does not advertise resources capability - returning empty list"),{resourceTemplates:[]};if(e?.cursor!==void 0)return this.request({method:"resources/templates/list",params:e},t);let r=await this._serveFromCache("resources/templates/list",void 0,t);return r!==void 0?r:this._listAllPages("resources/templates/list",e,t,(n,o)=>n.resourceTemplates.push(...o.resourceTemplates))}async _listAllPages(e,t,r,n,o){let i=r?.cacheMode==="bypass",a=this._cache.captureGeneration(e),s=await this.request({method:e,...t&&{params:{...t}}},r),c=s.nextCursor,u=new Set,l=1;for(;c!==void 0&&!u.has(c);){if(this._listMaxPages!==0&&l>=this._listMaxPages)throw new ae(se.ListPaginationExceeded,`${e}: exceeded listMaxPages (${this._listMaxPages}); server pagination did not terminate`,{method:e,listMaxPages:this._listMaxPages});u.add(c);let d=await this.request({method:e,params:{...t,cursor:c}},r);n(s,d),c=d.nextCursor,l++}return delete s.nextCursor,o?.(s),i||await this._cache.write(e,s,a,this._freshness(s)),s}_freshness(e,t){let r=e,n=typeof r.ttlMs=="number"?r.ttlMs:this._defaultCacheTtlMs,o=r.cacheScope==="public"?"public":"private";return{expiresAt:this._cache.now()+Math.min(Math.max(0,n),Pk),scope:o,params:t}}async _serveFromCache(e,t,r){if(r?.cacheMode==="bypass"||r?.cacheMode==="refresh")return;let n=await this._cache.read(e,t).catch(o=>{this._reportStoreError(o)});if(n!==void 0){if(r?.signal?.aborted){let o=r.signal.reason;throw o instanceof ae?o:new ae(se.RequestTimeout,String(o))}return n.value}}_reportStoreError(e){this.onerror?.(e instanceof Error?e:new Error(String(e)))}_compileOutputValidator(e){if(e.outputSchema)try{return{ok:!0,validator:this._jsonSchemaValidator.getValidator(e.outputSchema)}}catch(t){return{ok:!1,compileError:t}}}async _resolveXMcpHeaderScan(e,t){let r=t??await this._cache.toolDefinition(e);return r===void 0?void 0:tg(r.inputSchema)}async readResource(e,t){let r=await this._serveFromCache("resources/read",e.uri,t);if(r!==void 0)return r;let n=this._cache.captureGeneration("resources/read",e.uri),o=await this.request({method:"resources/read",params:e},t);if(t?.cacheMode!=="bypass"){let i=this._freshness(o,e.uri);i.expiresAt>this._cache.now()?await this._cache.write("resources/read",o,n,i):t?.cacheMode==="refresh"&&await this._cache.evictKey("resources/read",e.uri)}return o}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},t)}async listen(e,t){if(this.transport===void 0)throw new ae(se.NotConnected,"Not connected");let r=this._negotiatedProtocolVersion;if(r===void 0||!Ir(r))throw new ae(se.MethodNotSupportedByProtocolVersion,`subscriptions/listen requires a 2026-07-28-era connection (negotiated: ${r??"none"}). On a 2025-era connection, change notifications are delivered unsolicited: use ClientOptions.listChanged and resources/subscribe instead.`,{method:"subscriptions/listen",protocolVersion:r});if(t?.signal?.aborted){let S=t.signal.reason;throw S instanceof ae?S:new ae(se.RequestTimeout,String(S))}let n=new AbortController,o=`listen:${this._nextListenId++}`,i="opening",a,s,c,u,l=new Promise((S,_)=>{c=S,u=_}),d,m=new Promise(S=>{d=S}),v=S=>{if(i==="closed")return;let _=i==="opening";if(a!==void 0&&(clearTimeout(a),a=void 0),"ack"in S){i="open",c(S.ack);return}i="closed",s!==void 0&&t?.signal?.removeEventListener("abort",s),this._listenState.delete(o),n.abort(),d(S.cause),_&&u(S.error??new ae(se.ConnectionClosed,"subscriptions/listen closed before the server acknowledged"))},g=async()=>{n.abort(),await this.notification({method:"notifications/cancelled",params:{requestId:o}}).catch(()=>{})},h=async()=>{i!=="closed"&&(v({cause:"local"}),await g())};this._listenState.set(o,{settle:v});let f=t?.timeout??fs;if(a=setTimeout(()=>{v({cause:"remote",error:new ae(se.RequestTimeout,"subscriptions/listen ack timed out",{timeout:f})}),g().catch(()=>{})},f),t?.signal){let S=t.signal;s=()=>{if(i==="closed")return;let _=S.reason;v({cause:"local",error:_ instanceof Error?_:new Error(String(_??"Aborted"))}),g().catch(()=>{})},S.addEventListener("abort",s,{once:!0})}let y={jsonrpc:"2.0",id:o,method:"subscriptions/listen",params:{_meta:{...this._outboundMetaEnvelope()},notifications:e}};try{await this.transport.send(y,{requestSignal:n.signal,onRequestStreamEnd:()=>v({cause:"remote",error:new Error("subscriptions/listen: stream ended")})})}catch(S){v({cause:"remote",error:S instanceof Error?S:new Error(String(S))})}return{honoredFilter:await l,close:h,closed:m}}get autoOpenedSubscription(){return this._autoOpenedSubscription}_onnotification(e,t){let r=Object.hasOwn(ck,e.method)?ck[e.method]:void 0;if(e.method==="notifications/resources/updated"){let n=e.params?.uri;typeof n=="string"&&this._cache.evictKey("resources/read",n)}else if(r!==void 0)for(let n of r)this._cache.evict(n);if(e.method==="notifications/subscriptions/acknowledged"){let n=e.params?._meta?.[xo],o=typeof n=="string"?this._listenState.get(n):void 0;if(o!==void 0){let i=this._wireCodec().validateNotification("notifications/subscriptions/acknowledged",e);o.settle({ack:i.ok?i.value.params.notifications:{}});return}}if(e.method==="notifications/cancelled"){let n=e.params?.requestId,o=typeof n=="string"?this._listenState.get(n):void 0;if(o!==void 0){o.settle({cause:"remote",error:new Error("subscriptions/listen: server cancelled the subscription")});return}}super._onnotification(e,t)}_onresponse(e){let t=e.id,r=typeof t=="string"?this._listenState.get(t):void 0;if(r!==void 0){Vn(e)?r.settle({cause:"remote",error:Me.fromError(e.error.code,e.error.message,e.error.data)}):r.settle({cause:"graceful",error:new ae(se.ConnectionClosed,"subscriptions/listen: server closed the subscription gracefully before acknowledging")});return}super._onresponse(e)}_onclose(){if(this._listenState.size>0){let e=new ae(se.ConnectionClosed,"Connection closed");for(let t of this._listenState.values())t.settle({cause:"remote",error:e});this._listenState.clear()}super._onclose()}async callTool(e,t){let r=this.getProtocolEra()==="modern"&&nk()!=="browser",n=async()=>{if(!r)return t;let c;try{c=await this._resolveXMcpHeaderScan(e.name,t?.toolDefinition)}catch(l){this._reportStoreError(l)}if(!c?.valid||c.declarations.length===0)return t;let u=Cw(c.declarations,e.arguments);return Object.keys(u).length===0?t:{...t,headers:{...t?.headers,...u}}},o=t?.toolDefinition===void 0?await this._cache.outputValidator(e.name,c=>this._compileOutputValidator(c)).catch(c=>{this._reportStoreError(c)}):this._compileOutputValidator(t.toolDefinition),i=()=>{if(o===void 0||o.ok)return;let c=o.compileError,u=(c instanceof Error?c.message:String(c)).slice(0,200);throw new Me(fe.InvalidParams,`Tool '${e.name}' has an invalid outputSchema: ${u}`)};i();let a;try{a=await this.request({method:"tools/call",params:e},await n())}catch(c){let u=c instanceof Me&&c.code===Vo;if(!r||!u||t?.toolDefinition!==void 0)throw c;let l={signal:t?.signal,timeout:t?.timeout,cacheMode:"refresh"};await this._cache.evict("tools/list"),await this.listTools(void 0,l).catch(d=>this._reportStoreError(d)),o=await this._cache.outputValidator(e.name,d=>this._compileOutputValidator(d)).catch(d=>{this._reportStoreError(d)}),i(),a=await this.request({method:"tools/call",params:e},await n())}let s=o!==void 0&&o.ok?o.validator:void 0;if(s){if(a.structuredContent===void 0&&!a.isError)throw new Me(fe.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(a.structuredContent!==void 0&&!a.isError)try{let c=s(a.structuredContent);if(!c.valid)throw new Me(fe.InvalidParams,`Structured content does not match the tool's output schema: ${c.errorMessage}`)}catch(c){throw c instanceof Me?c:new Me(fe.InvalidParams,`Failed to validate structured content: ${c instanceof Error?c.message:String(c)}`)}}return a}async listTools(e,t){if(!this._serverCapabilities?.tools&&!this._enforceStrictCapabilities)return console.debug("Client.listTools() called but server does not advertise tools capability - returning empty list"),{tools:[]};if(e?.cursor!==void 0){let n=await this.request({method:"tools/list",params:e},t);return this._excludeInvalidXMcpHeaderTools(n),n}let r=await this._serveFromCache("tools/list",void 0,t);return r!==void 0?r:this._listAllPages("tools/list",e,t,(n,o)=>n.tools.push(...o.tools),n=>this._excludeInvalidXMcpHeaderTools(n))}_excludeInvalidXMcpHeaderTools(e){if(this.getProtocolEra()!=="modern"||!this.transport||ok(this.transport)==="stdio")return;let t=e.tools.filter(r=>{let n=tg(r.inputSchema);return n.valid?!0:(console.warn(`[mcp-sdk] excluding tool '${r.name}' from tools/list: invalid x-mcp-header declaration \u2014 ${n.reason}`),!1)});t.length!==e.tools.length&&(e.tools=t)}_setupListChangedHandler(e,t,r,n){let o=nd(Za,r);if(!o.success)throw new Error(`Invalid ${e} listChanged options: ${o.error.message}`);if(typeof r.onChanged!="function")throw new TypeError(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:i,debounceMs:a}=o.data,{onChanged:s}=r,c=async()=>{if(!i){s(null,null);return}try{s(null,await n())}catch(l){s(l instanceof Error?l:new Error(String(l)),null)}},u=()=>{if(a){let l=this._listChangedDebounceTimers.get(e);l&&clearTimeout(l);let d=setTimeout(c,a);this._listChangedDebounceTimers.set(e,d)}else c()};this.setNotificationHandler(t,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};sA=(e,t)=>r=>async(n,o)=>{let i=async()=>{let s=new Headers(o?.headers),c=await e.tokens();return c&&s.set("Authorization",`Bearer ${c.access_token}`),await r(n,{...o,headers:s})},a=await i();if(a.status===401)try{let{resourceMetadataUrl:s,scope:c}=Ar(a),u=await li(e,{serverUrl:t||(typeof n=="string"?new URL(n).origin:n.origin),resourceMetadataUrl:s,scope:c,fetchFn:r});if(u==="REDIRECT")throw new at("Authentication requires user authorization - redirect initiated");if(u!=="AUTHORIZED")throw new at(`Authentication failed with result: ${u}`);a=await i()}catch(s){throw s instanceof at?s:new at(`Failed to re-authenticate: ${s instanceof Error?s.message:String(s)}`)}if(a.status===401)throw new at(`Authentication failed for ${typeof n=="string"?n:n.toString()}`);return a},cA=(e={})=>{let{logger:t,includeRequestHeaders:r=!1,includeResponseHeaders:n=!1,statusLevel:o=0}=e,a=t||(s=>{let{method:c,url:u,status:l,statusText:d,duration:m,requestHeaders:v,responseHeaders:g,error:h}=s,f=h?`HTTP ${c} ${u} failed: ${h.message} (${m}ms)`:`HTTP ${c} ${u} ${l} ${d} (${m}ms)`;if(r&&v){let y=[...v.entries()].map(([S,_])=>`${S}: ${_}`).join(", ");f+=` + Request Headers: {${y}}`}if(n&&g){let y=[...g.entries()].map(([S,_])=>`${S}: ${_}`).join(", ");f+=` + Response Headers: {${y}}`}h||l>=400?console.error(f):console.log(f)});return s=>async(c,u)=>{let l=performance.now(),d=u?.method||"GET",m=typeof c=="string"?c:c.toString(),v=r?new Headers(u?.headers):void 0;try{let g=await s(c,u),h=performance.now()-l;return g.status>=o&&a({method:d,url:m,status:g.status,statusText:g.statusText,duration:h,requestHeaders:v,responseHeaders:n?g.headers:void 0}),g}catch(g){throw a({method:d,url:m,status:0,statusText:"Network Error",duration:performance.now()-l,requestHeaders:v,error:g}),g}}},uA=(...e)=>t=>{let r=t;for(let n of e)r=n(r);return r},lA=e=>t=>(r,n)=>e(t,r,n),jk=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SseError"})}static[Symbol.hasInstance](e){return Ut(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return Ut(this,e)}constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r,Ln(this,new.target)}},dA=class{_eventSource;_endpoint;_abortController;_url;_resourceMetadataUrl;_scope;_eventSourceInit;_requestInit;_authProvider;_oauthProvider;_skipIssuerMetadataValidation;_fetch;_fetchWithInit;_protocolVersion;onclose;onerror;onmessage;constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit,this._skipIssuerMetadataValidation=t?.skipIssuerMetadataValidation,pk(t?.authProvider)?(this._oauthProvider=t.authProvider,this._authProvider=mk(t.authProvider,{skipIssuerMetadataValidation:t.skipIssuerMetadataValidation})):this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=od(t?.fetch,t?.requestInit)}_last401Response;async _commonHeaders(){let e={},t=await this._authProvider?.token();t&&(e.Authorization=`Bearer ${t}`),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=ds(this._requestInit?.headers);return new Headers({...e,...r})}_startOrAuth(){let e=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((t,r)=>{this._eventSource=new Jn(this._url.href,{...this._eventSourceInit,fetch:async(n,o)=>{let i=await this._commonHeaders();i.set("Accept","text/event-stream");let a=await e(n,{...o,headers:i});if(a.status===401&&(this._last401Response=a,a.headers.has("www-authenticate"))){let{resourceMetadataUrl:s,scope:c}=Ar(a);this._resourceMetadataUrl=s,this._scope=c}return a}}),this._abortController=new AbortController,this._eventSource.onerror=n=>{if(n.code===401&&this._authProvider){if(this._authProvider.onUnauthorized&&this._last401Response){let a=this._last401Response;this._last401Response=void 0,this._eventSource?.close(),this._authProvider.onUnauthorized({response:a,serverUrl:this._url,fetchFn:this._fetchWithInit}).then(()=>this._startOrAuth().then(t,r),s=>{this.onerror?.(s),r(s)});return}let i=new at;r(i),this.onerror?.(i);return}let o=new jk(n.code,n.message,n);r(o),this.onerror?.(o)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",n=>{let o=n;try{if(this._endpoint=new URL(o.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(i){r(i),this.onerror?.(i),this.close();return}t()}),this._eventSource.onmessage=n=>{let o=n,i;try{i=Bt.parse(JSON.parse(o.data))}catch(a){this.onerror?.(a);return}this.onmessage?.(i)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e,t){if(!this._oauthProvider)throw new at("finishAuth requires an OAuthClientProvider");let{authorizationCode:r,iss:n}=await hk(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await li(this._oauthProvider,{serverUrl:this._url,authorizationCode:r,iss:n,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!=="AUTHORIZED")throw new at("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){return this._send(e,!1)}async _send(e,t){if(!this._endpoint)throw new ae(se.NotConnected,"Not connected");try{let r=await this._commonHeaders();r.set("content-type","application/json");let n={...this._requestInit,method:"POST",headers:r,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._endpoint,n);if(!o.ok){if(o.status===401&&this._authProvider){if(o.headers.has("www-authenticate")){let{resourceMetadataUrl:a,scope:s}=Ar(o);this._resourceMetadataUrl=a,this._scope=s}if(this._authProvider.onUnauthorized&&!t)return await this._authProvider.onUnauthorized({response:o,serverUrl:this._url,fetchFn:this._fetchWithInit}),await o.text?.().catch(()=>{}),this._send(e,!0);throw await o.text?.().catch(()=>{}),t?new lr(se.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:o.statusText}):new at}let i=await o.text?.().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${o.status}): ${i}`)}await o.text?.().catch(()=>{})}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(e){this._protocolVersion=e}},pA=1,mA={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},fA=new Set(["authorization","content-type","mcp-protocol-version","mcp-method","mcp-name","mcp-session-id"]);hA=class{_abortController;_url;_resourceMetadataUrl;_scope;_requestInit;_authProvider;_oauthProvider;_skipIssuerMetadataValidation;_fetch;_fetchWithInit;_sessionId;_reconnectionOptions;_protocolVersion;_onInsufficientScope;_maxStepUpRetries;_serverRetryMs;_reconnectionScheduler;_cancelReconnection;onclose;onerror;onmessage;hasPerRequestStream=!0;constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._skipIssuerMetadataValidation=t?.skipIssuerMetadataValidation,pk(t?.authProvider)?(this._oauthProvider=t.authProvider,this._authProvider=mk(t.authProvider,{skipIssuerMetadataValidation:t.skipIssuerMetadataValidation})):this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=od(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._protocolVersion=t?.protocolVersion,this._reconnectionOptions=t?.reconnectionOptions??mA,this._reconnectionScheduler=t?.reconnectionScheduler,this._onInsufficientScope=t?.onInsufficientScope??"reauthorize",this._maxStepUpRetries=Math.max(0,t?.maxStepUpRetries??pA)}async _stepUpAuthorize(e,t){if(this._onInsufficientScope==="throw")throw new dy({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(!this._oauthProvider)throw new dy({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(t>=this._maxStepUpRetries)throw new lr(se.ClientHttpForbidden,`Server returned 403 insufficient_scope after step-up re-authorization (retry limit ${this._maxStepUpRetries} reached)`,{status:403,statusText:e.statusText??"Forbidden",text:e.text});e.resourceMetadataUrl&&(this._resourceMetadataUrl=e.resourceMetadataUrl);let r=await this._oauthProvider.tokens(),n=Bd(this._scope,r?.scope,e.scope);this._scope=n;let o=fk(n,r?.scope);return li(this._oauthProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:n,forceReauthorization:o,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})}async _commonHeaders(){let e={},t=await this._authProvider?.token();t&&(e.Authorization=`Bearer ${t}`),this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=ds(this._requestInit?.headers);return new Headers({...e,...r})}_applyBodyDerivedHeaders(e,t){if(Array.isArray(t)||!sn(t))return;let r=t.params?._meta?.[cr];if(typeof r!="string")return;e.set("mcp-protocol-version",r),e.set("mcp-method",t.method);let n=t.params,o=t.method==="resources/read"?typeof n?.uri=="string"?n.uri:void 0:typeof n?.name=="string"?n.name:void 0;o!==void 0&&e.set("mcp-name",rg(o))}_isModernEnvelopedRequest(e){if(Array.isArray(e)||!sn(e))return!1;let t=e.params?._meta?.[cr];return typeof t=="string"&&Ir(t)}async _startOrAuthSse(e,t=!1,r=0){let{resumptionToken:n,requestSignal:o}=e,i=()=>this._abortController?.signal.aborted===!0||o?.aborted===!0;try{let a=await this._commonHeaders(),s=[...a.get("accept")?.split(",").map(d=>d.trim().toLowerCase())??[],"text/event-stream"];a.set("accept",[...new Set(s)].join(", ")),n&&a.set("last-event-id",n);let c=this._abortController?.signal,u=o!==void 0&&c!==void 0?uk(c,o):o??c,l=await(this._fetch??fetch)(this._url,{...this._requestInit,method:"GET",headers:a,signal:u});if(!l.ok){if(l.status===401&&this._authProvider){if(l.headers.has("www-authenticate")){let{resourceMetadataUrl:d,scope:m}=Ar(l);this._resourceMetadataUrl=d,this._scope=Bd(this._scope,m)}if(this._authProvider.onUnauthorized&&!t)return await this._authProvider.onUnauthorized({response:l,serverUrl:this._url,fetchFn:this._fetchWithInit}),await l.text?.().catch(()=>{}),this._startOrAuthSse(e,!0,r);throw await l.text?.().catch(()=>{}),t?new lr(se.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:l.statusText}):new at}if(l.status===403){let{resourceMetadataUrl:d,scope:m,error:v,errorDescription:g}=Ar(l);if(v==="insufficient_scope"){let h=await l.text?.().catch(()=>null);if(await this._stepUpAuthorize({scope:m,resourceMetadataUrl:d,errorDescription:g,statusText:l.statusText,text:h},r)!=="AUTHORIZED")throw new at;return this._startOrAuthSse(e,t,r+1)}}if(await l.text?.().catch(()=>{}),l.status===405){e.onRequestStreamEnd?.();return}throw new lr(se.ClientHttpFailedToOpenStream,`Failed to open SSE stream: ${l.statusText}`,{status:l.status,statusText:l.statusText})}this._handleSseStream(l.body,e,!0)}catch(a){throw i()||this.onerror?.(a),a}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(r,e),n)}_scheduleReconnection(e,t=0){let r=this._reconnectionOptions.maxRetries;if(t>=r){this.onerror?.(new Error(`Maximum reconnection attempts (${r}) exceeded.`)),e.onRequestStreamEnd?.();return}let n=this._getNextReconnectionDelay(t),o=()=>{this._cancelReconnection=void 0,!(this._abortController?.signal.aborted||e.requestSignal?.aborted)&&this._startOrAuthSse(e).catch(i=>{if(!(this._abortController?.signal.aborted||e.requestSignal?.aborted)){this.onerror?.(new Error(`Failed to reconnect SSE stream: ${i instanceof Error?i.message:String(i)}`));try{this._scheduleReconnection(e,t+1)}catch(a){this.onerror?.(a instanceof Error?a:new Error(String(a)))}}})};if(this._reconnectionScheduler){let i=this._reconnectionScheduler(o,n,t);this._cancelReconnection=typeof i=="function"?i:void 0}else{let i=setTimeout(o,n);this._cancelReconnection=()=>clearTimeout(i)}}_handleSseStream(e,t,r){if(!e){t.onRequestStreamEnd?.();return}let{onresumptiontoken:n,replayMessageId:o,requestSignal:i,onRequestStreamEnd:a}=t,s=()=>this._abortController?.signal.aborted===!0||i?.aborted===!0,c,u=!1,l=!1;(async()=>{try{let m=e.pipeThrough(new TextDecoderStream).pipeThrough(new vd({onRetry:v=>{this._serverRetryMs=v}})).getReader();for(;;){let{value:v,done:g}=await m.read();if(g)break;if(v.id&&(c=v.id,u=!0,n?.(v.id)),!!v.data&&(!v.event||v.event==="message"))try{let h=Bt.parse(JSON.parse(v.data));(qn(h)||Vn(h))&&(l=!0,o!==void 0&&(h.id=o)),this.onmessage?.(h)}catch(h){this.onerror?.(h)}}(r||u)&&!l&&this._abortController&&!s()?this._scheduleReconnection({resumptionToken:c,onresumptiontoken:n,replayMessageId:o,requestSignal:i,onRequestStreamEnd:a},0):s()||a?.()}catch(m){if(s())return;if(this.onerror?.(new Error(`SSE stream disconnected: ${m}`)),(r||u)&&!l&&this._abortController&&!s())try{this._scheduleReconnection({resumptionToken:c,onresumptiontoken:n,replayMessageId:o,requestSignal:i,onRequestStreamEnd:a},0)}catch(v){this.onerror?.(new Error(`Failed to reconnect: ${v instanceof Error?v.message:String(v)}`)),a?.()}else a?.()}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e,t){if(!this._oauthProvider)throw new at("finishAuth requires an OAuthClientProvider");let{authorizationCode:r,iss:n}=await hk(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await li(this._oauthProvider,{serverUrl:this._url,authorizationCode:r,iss:n,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!=="AUTHORIZED")throw new at("Failed to authorize")}async close(){try{this._cancelReconnection?.()}finally{this._cancelReconnection=void 0,this._abortController?.abort(),this.onclose?.()}}async send(e,t){return this._send(e,t,!1)}async _send(e,t,r,n=0){try{let{resumptionToken:o,onresumptiontoken:i}=t||{};if(o){this._startOrAuthSse({resumptionToken:o,replayMessageId:sn(e)?e.id:void 0,requestSignal:t?.requestSignal}).catch(f=>this.onerror?.(f));return}let a=await this._commonHeaders();this._applyBodyDerivedHeaders(a,e);let s=Array.isArray(e)?e.some(f=>rd(f)):rd(e);if(s&&a.delete("mcp-session-id"),t?.headers!==void 0)for(let[f,y]of Object.entries(t.headers))fA.has(f.toLowerCase())||a.set(f,y);a.set("content-type","application/json");let c=[...a.get("accept")?.split(",").map(f=>f.trim().toLowerCase())??[],"application/json","text/event-stream"];a.set("accept",[...new Set(c)].join(", "));let u=this._abortController?.signal,l=t?.requestSignal!==void 0&&u!==void 0?uk(u,t.requestSignal):t?.requestSignal??u,d={...this._requestInit,method:"POST",headers:a,body:JSON.stringify(e),signal:l},m=await(this._fetch??fetch)(this._url,d);if(s&&m.ok&&(this._sessionId=m.headers.get("mcp-session-id")||void 0),!m.ok){if(m.status===401&&this._authProvider){if(m.headers.has("www-authenticate")){let{resourceMetadataUrl:y,scope:S}=Ar(m);this._resourceMetadataUrl=y,this._scope=Bd(this._scope,S)}if(this._authProvider.onUnauthorized&&!r)return await this._authProvider.onUnauthorized({response:m,serverUrl:this._url,fetchFn:this._fetchWithInit}),await m.text?.().catch(()=>{}),this._send(e,t,!0,n);throw await m.text?.().catch(()=>{}),r?new lr(se.ClientHttpAuthentication,"Server returned 401 after re-authentication",{status:401,statusText:m.statusText}):new at}let f=await m.text?.().catch(()=>null);if(m.status===403){let{resourceMetadataUrl:y,scope:S,error:_,errorDescription:$}=Ar(m);if(_==="insufficient_scope"){if(await this._stepUpAuthorize({scope:S,resourceMetadataUrl:y,errorDescription:$,statusText:m.statusText,text:f},n)!=="AUTHORIZED")throw new at;return this._send(e,t,r,n+1)}}if(m.status===400&&typeof f=="string"&&this._isModernEnvelopedRequest(e))try{let y=Bt.parse(JSON.parse(f)),S=(Array.isArray(e)?e:[e]).filter(_=>sn(_));if(Vn(y)&&S.some(_=>_.id===y.id)){this.onmessage?.(y);return}}catch{}throw new lr(se.ClientHttpNotImplemented,`Error POSTing to endpoint: ${f}`,{status:m.status,statusText:m.statusText,text:f})}if(m.status===202){await m.text?.().catch(()=>{}),eg(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>this.onerror?.(f));return}let v=(Array.isArray(e)?e:[e]).some(f=>"method"in f&&"id"in f&&f.id!==void 0),g=m.headers.get("content-type"),h=cg(g);if(v)if(h==="text/event-stream")this._handleSseStream(m.body,{onresumptiontoken:i,requestSignal:t?.requestSignal,onRequestStreamEnd:t?.onRequestStreamEnd},!1);else if(h==="application/json"){let f=await m.json(),y=Array.isArray(f)?f.map(S=>Bt.parse(S)):[Bt.parse(f)];for(let S of y)this.onmessage?.(S)}else throw await m.text?.().catch(()=>{}),new ae(se.ClientHttpUnexpectedContent,`Unexpected content type: ${g}`,{contentType:g});else await m.text?.().catch(()=>{})}catch(o){throw t?.requestSignal?.aborted!==!0&&this.onerror?.(o),o}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await(this._fetch??fetch)(this._url,t);if(await r.text?.().catch(()=>{}),!r.ok&&r.status!==405)throw new lr(se.ClientHttpFailedToTerminateSession,`Failed to terminate session: ${r.statusText}`,{status:r.status,statusText:r.statusText});this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}}});function Ry(e,t){return{id:e.id,config:e,deploymentId:t,createdAt:new Date,updatedAt:new Date}}function Ur(e,t,r,n){return{id:e,agentId:t,userId:r,transportId:n,messages:[],status:"active",turnCount:0,createdAt:new Date,updatedAt:new Date,metadata:{}}}function Mr(e,t){return{...e,messages:[...e.messages,t],turnCount:t.role==="assistant"?e.turnCount+1:e.turnCount,updatedAt:new Date}}function ho(e,t,r){return{id:e,role:"user",content:t,timestamp:new Date,transportOrigin:r,metadata:{}}}function or(e,t,r){return{id:e,role:"assistant",content:t,timestamp:new Date,transportOrigin:"agent",toolInvocations:r,metadata:{}}}function He(e,t,r,n,o){return{id:e,type:t,timestamp:new Date,agentId:r,sessionId:o,payload:n}}function qi(e){let{config:t,ontology:r,memories:n,messages:o,tools:i,ontologyRenderer:a,transport:s}=e,c=[];c.push(t.systemPrompt),s&&c.push(` + +[Channel: ${s}]`);let u=a.render(r);if(u&&r.entityTypes.length>0&&(c.push(` +--- +`),c.push(u)),n.length>0){c.push(` +--- +# Relevant Context from Memory +`);for(let g of n)c.push(`[${g.entityType}] ${g.content}`)}let l=c.join(` +`),d=Math.ceil(l.length/4),m=o.reduce((g,h)=>g+Math.ceil(h.content.length/4),0),v=i.reduce((g,h)=>g+Math.ceil(JSON.stringify(h.inputSchema).length/4),0);return{systemPrompt:l,messages:o,tools:i,tokenEstimate:d+m+v}}var Kk={"claude-sonnet-4-6":[3,15],"claude-opus-4-6":[15,75],"claude-haiku-4-5-20251001":[.25,1.25],"anthropic.claude-sonnet-4-6-20251022-v1:0":[3,15],"anthropic.claude-opus-4-6-20251022-v1:0":[15,75],"anthropic.claude-haiku-4-5-20251001-v1:0":[.25,1.25]},xy=1.25,Iy=.1;function vr(e,t,r){let n=typeof t=="number"?{inputTokens:t,outputTokens:r??0}:t,o=Kk[e];if(!o)return 0;let[i,a]=o,s=v=>Math.max(0,Number.isFinite(v)?v:0),c=s(n.inputTokens),u=s(n.outputTokens),l=s(n.cacheReadTokens),d=s(n.cacheWriteTokens);return(c*i+u*a+l*i*Iy+d*i*xy)/1e6}var Jk=.003,Fk=.015;function Li(e,t={}){let r="now"in t&&typeof t.now=="function"?{clock:t}:t,n=r.clock??{now:()=>Date.now()},o=r.modelId,i=0,a=0,s=0,c=0,u=0,l=0,d=n.now(),m=v=>Math.max(0,Number.isFinite(v)?v:0);return{recordCall(v){i++;let g=m(v.inputTokens),h=m(v.outputTokens),f=m(v.cacheReadTokens),y=m(v.cacheWriteTokens);s+=g,c+=h,u+=f,l+=y,a+=g+h+f+y},isExhausted(){return this.getStatus().exhausted},getStatus(){let v=n.now()-d,g=o!==void 0?vr(o,{inputTokens:s,outputTokens:c,cacheReadTokens:u,cacheWriteTokens:l}):s*Jk/1e3+c*Fk/1e3,h=!1,f;return e.maxCalls!==void 0&&i>=e.maxCalls?(h=!0,f=`LLM call limit reached (${i}/${e.maxCalls})`):e.maxTokens!==void 0&&a>=e.maxTokens?(h=!0,f=`Token limit reached (${a}/${e.maxTokens})`):e.maxTimeMs!==void 0&&v>=e.maxTimeMs?(h=!0,f=`Time limit reached (${v}ms/${e.maxTimeMs}ms)`):e.maxCostUsd!==void 0&&g>=e.maxCostUsd&&(h=!0,f=`Cost limit reached ($${g.toFixed(4)}/$${e.maxCostUsd})`),{calls:i,tokens:a,timeMs:v,estimatedCostUsd:g,exhausted:h,...f?{exhaustedReason:f}:{}}}}}function Vi(e){return{maxCalls:e}}var Py=100,kn=class{byPhase=new Map;register(t){let r=this.byPhase.get(t.phase)??[];if(r.some(n=>n.name===t.name))throw new Error(`Hook with name "${t.name}" is already registered for phase "${t.phase}"`);r.push(t),this.byPhase.set(t.phase,r)}unregister(t){for(let[r,n]of this.byPhase){let o=n.filter(i=>i.name!==t);o.length!==n.length&&this.byPhase.set(r,o)}}hooksFor(t){return[...this.byPhase.get(t)??[]].sort((o,i)=>(o.priority??Py)-(i.priority??Py))}},_r=class extends Error{hookName;phase;cause;constructor(t,r,n){let o=n instanceof Error?n.message:String(n);super(`Hook "${t}" failed in phase "${r}": ${o}`),this.hookName=t,this.phase=r,this.cause=n,this.name="HookExecutionError"}};function Ki(e){let t=e.onAnnotation??(()=>{});return async function(n,o){let i=e.registry.hooksFor(n),a=o;for(let s of i){let c={phase:n,agent:e.agent,sessionId:e.sessionId,turnId:e.turnId,userContext:e.userContext,payload:a,emit:e.onEvent,annotate:t},u;try{u=await s.run(c)}catch(l){throw new _r(s.name,n,l)}if(u.kind==="short_circuit")return e.onEvent(He(crypto.randomUUID(),"turn.short_circuited",e.agent.id,{hookName:s.name,phase:n,reason:u.reason},e.sessionId)),{payload:a,shortCircuited:!0,correctionRequested:!1,reason:u.reason,finalResponse:u.finalResponse,hookName:s.name};if(u.kind==="request_correction"){if(n!=="pre_capture")throw new _r(s.name,n,new Error(`request_correction outcome is only valid from "pre_capture", got "${n}"`));return{payload:a,shortCircuited:!1,correctionRequested:!0,correctionPrompt:u.correctionPrompt,hookName:s.name}}u.payload&&(a={...a,...u.payload})}return{payload:a,shortCircuited:!1,correctionRequested:!1}}}function ec(e,t){if(t.entityTypes.length===0)return[];let r=[];for(let n of t.entityTypes){let o=n.name,i=new RegExp(`\\b${op(o)}\\b`,"gi"),a=[...e.matchAll(i)];if(a.length!==0)for(let s of a){let c=s.index,u=Math.max(0,c-20),l=Math.min(e.length,c+o.length+200),d=e.slice(u,l),m=Hk(d,n);r.push({text:d.trim(),entityType:o,properties:Object.keys(m).length>0?m:void 0})}}return r}function Hk(e,t){let r={};for(let n of t.properties){let o=[new RegExp(`\\b${op(n.name)}\\s+(?:is|:|=)\\s+(\\S+)`,"i"),new RegExp(`\\b${op(n.name)}\\s+(\\S+)`,"i")];for(let i of o){let a=e.match(i);if(a){let s=a[1].replace(/[.,;!?)]+$/,"");if(s){r[n.name]=s;break}}}}return r}function tc(e,t){let r={valid:[],fixable:[],friction:[]};for(let n of e)Zk(n,t,r);return r}function Zk(e,t,r){let n=Wk(e.entityType,t);if(n.status==="unknown"){r.friction.push({claim:e,frictionType:"unknown_entity",context:`Entity type "${e.entityType}" is not defined in the ontology. Known types: ${t.entityTypes.map(a=>a.name).join(", ")}`});return}if(n.status==="fixable"){r.fixable.push({claim:e,suggestion:`Use "${n.resolved.name}" instead of "${e.entityType}"`});return}let o=n.resolved;if(!e.properties||Object.keys(e.properties).length===0){r.valid.push(e);return}let i=!1;for(let[a,s]of Object.entries(e.properties)){let c=Bk(a,s,o);if(c.status==="fixable"){r.fixable.push({claim:e,suggestion:c.suggestion}),i=!0;break}if(c.status==="unknown_property"){r.friction.push({claim:e,frictionType:"unknown_property",context:`Property "${a}" does not exist on entity type "${o.name}". Known properties: ${o.properties.map(u=>u.name).join(", ")}`,propertyName:a,availableProperties:o.properties.map(u=>u.name)}),i=!0;continue}if(c.status==="invalid_value"){let u=o.properties.find(l=>l.name===a)??o.properties.find(l=>l.name.toLowerCase()===a.toLowerCase());r.friction.push({claim:e,frictionType:"invalid_value",context:c.context,propertyName:a,allowedValues:u?.enumValues??[]}),i=!0;continue}}i||r.valid.push(e)}function Wk(e,t){if(!e)return{status:"exact"};let r=t.entityTypes.find(o=>o.name===e);if(r)return{status:"exact",resolved:r};let n=t.entityTypes.find(o=>o.name.toLowerCase()===e.toLowerCase());if(n)return{status:"exact",resolved:n};for(let o of t.entityTypes){let i=e.toLowerCase(),a=o.name.toLowerCase();if(i.includes(a)||a.includes(i))return{status:"fixable",resolved:o}}for(let o of t.entityTypes)if(Cy(e.toLowerCase(),o.name.toLowerCase())<=2)return{status:"fixable",resolved:o};return{status:"unknown"}}function Bk(e,t,r){let n=r.properties.find(i=>i.name===e);if(n)return Ty(n,t,r);let o=r.properties.find(i=>i.name.toLowerCase()===e.toLowerCase());if(o)return Ty(o,t,r);for(let i of r.properties)if(Cy(e.toLowerCase(),i.name.toLowerCase())<=2)return{status:"fixable",suggestion:`Use property "${i.name}" instead of "${e}" on entity type "${r.name}"`};return{status:"unknown_property"}}function Ty(e,t,r){if(e.type==="enum"&&e.enumValues){let n=t.toLowerCase();if(!e.enumValues.find(i=>i.toLowerCase()===n))return{status:"invalid_value",context:`Property "${e.name}" on "${r.name}" only allows: ${e.enumValues.join(", ")}. Got: "${t}"`}}return{status:"valid"}}function Cy(e,t){if(e.length===0)return t.length;if(t.length===0)return e.length;let r=[];for(let n=0;n<=t.length;n++)r[n]=[n];for(let n=0;n<=e.length;n++)r[0][n]=n;for(let n=1;n<=t.length;n++)for(let o=1;o<=e.length;o++)t[n-1]===e[o-1]?r[n][o]=r[n-1][o-1]:r[n][o]=Math.min(r[n-1][o-1]+1,r[n][o-1]+1,r[n-1][o]+1);return r[t.length][e.length]}function op(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Ay=.7,Gk=new RegExp(["\\bmight\\b","\\bmaybe\\b","\\bperhaps\\b","\\bpossibly\\b","\\bI\\s+think\\b","\\bI\\s+believe\\b","\\bnot\\s+sure\\b","\\bnot\\s+certain\\b","\\bprobably\\b","\\bunlikely\\b","\\bsomewhat\\b","\\bsort\\s+of\\b","\\bkind\\s+of\\b","\\bappears\\s+to\\b","\\bseems\\s+to\\b","\\bcould\\s+be\\b"].join("|"),"gi"),Xk=.15,Yk=3,Qk=.1;function eE(e){if(!e)return 0;let t=e.match(Gk);return t?Math.min(t.length,Yk):0}function Oy(e){let t=e.properties?Object.keys(e.properties).length:0,r=.5+.1*Math.min(t,5),n=eE(e.text),o=Xk*n,i=r-o;return Math.min(1,Math.max(Qk,i))}function tE(e,t){let r={};if(!e.properties)return r;for(let[n,o]of Object.entries(e.properties)){let i=t.properties.find(a=>a.name===n||a.name.toLowerCase()===n.toLowerCase());if(!i){r[n]=o;continue}if(i.type==="number"){let a=Number(o);r[i.name]=Number.isFinite(a)?a:o}else if(i.type==="boolean"){let a=o.toLowerCase();a==="true"?r[i.name]=!0:a==="false"?r[i.name]=!1:r[i.name]=o}else r[i.name]=o}return r}function Ny(e){let{response:t,ontology:r,agent:n,sessionId:o,turnId:i}=e;if(r.entityTypes.length===0||t.length===0)return{toCapture:[],dropped:[]};let a=n.config.captureConfidenceThreshold??Ay,s=ec(t,r);if(s.length===0)return{toCapture:[],dropped:[]};let{valid:c}=tc(s,r),u=[],l=[],d=new Set;for(let m of c){if(!m.entityType)continue;let v=r.entityTypes.find(k=>k.name===m.entityType);if(!v)continue;let g=Oy(m),h=tE(m,v),f=m.text,y=jy(h,v),S=y?`${v.name}::${y.key}::${Ji(y.value)}`:`${v.name}::__no_key__::${f}`;if(d.has(S))continue;if(d.add(S),g0?{structured:h}:{}});continue}if(v.properties.find(k=>k.required&&!(k.name in h))){l.push({entityType:v.name,content:f,confidence:g,threshold:a,reason:"missing_required_property",...Object.keys(h).length>0?{structured:h}:{}});continue}let $={type:"auto_capture",sessionId:o,turnId:i,author:`memory-capture-service:${n.id}`};u.push({id:crypto.randomUUID(),agentId:n.id,scope:"namespace",scopeId:n.config.memoryNamespaces[0]??"default",entityType:v.name,content:f,structured:h,confidence:g,source:$,status:"active",portable:!1,createdAt:new Date,version:1})}return{toCapture:u,dropped:l}}function jy(e,t){return ip(e,t)[0]??null}function ip(e,t){let r=[];"id"in e&&Fi(e.id)&&r.push({key:"id",value:e.id});let n=Object.keys(e).sort();for(let o of n){if(o==="id")continue;let i=e[o];if(Fi(i)){if(t){let a=t.properties.find(s=>s.name===o||s.name.toLowerCase()===o.toLowerCase());if(a&&a.type==="enum")continue}r.push({key:o,value:i})}}return r}function Fi(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Ji(e){return typeof e=="string"?e.toLowerCase():String(e)}async function Uy(e,t,r){let n=r?.entityTypes.find(u=>u.name===e.entityType),o=ip(e.structured,n);if(o.length===0)return{kind:"none"};let i;try{i=await t.getByEntityType(e.agentId,e.entityType)}catch{return{kind:"none"}}let a=i.filter(u=>u.scope===e.scope&&u.scopeId===e.scopeId),s=e.structured.id,c=Fi(s);for(let u of o){let l=Ji(u.value),d=a.filter(v=>{if(v.id===e.id||v.status!=="active")return!1;let g=v.structured[u.key];if(g===void 0||!Fi(g)||Ji(g)!==l)return!1;if(u.key!=="id"&&c){let h=v.structured.id;if(Fi(h)&&Ji(h)!==Ji(s))return!1}return!0});if(d.length===0)continue;let m=[...d].sort((v,g)=>{let h=g.createdAt.getTime()-v.createdAt.getTime();if(h!==0)return h;let f=(g.version??0)-(v.version??0);return f!==0?f:v.id.localeCompare(g.id)});return m.length>=2?{kind:"ambiguous",entries:m}:{kind:"one",entry:m[0]}}return{kind:"none"}}async function Hi(e){let{memory:t,...r}=e,{toCapture:n,dropped:o}=Ny(r),i=[],a=[],s=[],c=r.ontology.entityTypes.map(u=>u.name);for(let u of n)try{let l=await Uy(u,t,r.ontology);switch(await t.store(u),i.push(u),l.kind){case"none":break;case"one":{try{await t.supersede(l.entry.id,u.id)}catch(d){a.push(`supersede(${l.entry.id} \u2192 ${u.id}) failed: ${d instanceof Error?d.message:String(d)}`)}break}case"ambiguous":{let d=l.entries.map(g=>g.id).sort(),m=`conflicting_facts:${r.sessionId}:${r.agent.id}:${u.entityType}:${d.join(",")}`,v;try{v=JSON.stringify({entityType:u.entityType,candidate:u.structured,conflictingEntryIds:d})}catch{v=""}s.push(He(m,"ontology.friction",r.agent.id,{claim:v,attemptedEntityType:u.entityType,availableEntityTypes:c,frictionType:"conflicting_facts",count:l.entries.length,conflictingEntryIds:d},r.sessionId));break}}}catch(l){a.push(`store(${u.id}) failed: ${l instanceof Error?l.message:String(l)}`)}return{captured:i,dropped:o,errors:a,frictionEvents:s}}var My=2;async function ap(e,t,r,n,o){let i=[],a=[],s=0,c=0,u=0,l=0,d=0,m=n.trace===!0,v=[],g=crypto.randomUUID(),h=[],f="init",y=Ki({registry:n.hooks??new kn,agent:e,sessionId:t,turnId:g,onEvent:J=>i.push(J),onAnnotation:(J,te)=>h.push({phase:f,key:J,value:te})}),S=async(J,te)=>{f=J;try{return await y(J,te)}catch(_e){if(!(_e instanceof _r))throw _e;let ke=_e.message;return h.push({phase:J,key:"blocking.hook_exception",value:ke}),i.push({id:crypto.randomUUID(),type:"turn.annotated",agentId:e.id,sessionId:t,timestamp:new Date,payload:{key:"blocking.hook_exception",phase:J,error:ke}}),{payload:te,shortCircuited:!1,correctionRequested:!1}}},_=await n.sessions.get(t);_||(_=Ur(t,e.id,r.metadata.userId??"unknown",r.transportOrigin)),_=Mr(_,r),i.push(He(crypto.randomUUID(),"message.received",e.id,{messageId:r.id},t));let $=await n.ontologyService.compose(e.id),k=await n.memory.recall({agentId:e.id,query:r.content,limit:20}),w=k.entries,b=o??Vi(e.config.maxTurns||10),E=Li(b,{modelId:e.config.modelId}),j=Math.max(b.maxCalls!=null?b.maxCalls*2:100,1),V=0,A=null,L=!1,Z=null;try{let J=await S("pre_turn",{userMessage:r,ontology:$,memories:w,session:_});J.shortCircuited?Z={finalResponse:J.finalResponse??null,reason:J.reason}:($=J.payload.ontology,w=J.payload.memories);let te=[];if(!Z)for(let T of e.config.toolScopes){let D=await n.tools.discoverTools(T);te.push(...D)}let _e=20,ke=_.messages.length>_e?_.messages.slice(-_e):_.messages,Ne=Z?{systemPrompt:"",messages:[],tools:[],tokenEstimate:0}:qi({config:e.config,ontology:$,memories:w,messages:ke,tools:te,ontologyRenderer:n.ontologyRenderer,transport:r.transportOrigin});if(!Z){let T=await S("pre_context",{context:Ne,recall:k,recallQuery:r.content,availableEntityTypes:$.entityTypes.map(D=>D.name)});T.shortCircuited?Z={finalResponse:T.finalResponse??null,reason:T.reason}:Ne=T.payload.context}let be=[...ke];m&&v.push({step:"start",timestamp:Date.now(),data:{sessionMessages:_.messages.length,windowedMessages:ke.length,hardCap:j,budget:b}});let P=0;t:for(;!Z;){A=null;e:for(;V0){let Ee=!1;for(let Ze of Pe.toolCalls){let je=await S("pre_tool",{call:Ze});if(je.shortCircuited){Z={finalResponse:je.finalResponse??null,reason:je.reason},A=Pe,Ee=!0;break}let De=je.payload.call;i.push(He(crypto.randomUUID(),"tool.invoked",e.id,{tool:De.toolName},t));let nt=await n.tools.execute(De),Jt=$.entityTypes.map(rr=>rr.name),yt=await S("post_tool",{call:De,result:nt,availableEntityTypes:Jt}),ut=yt.payload.result;a.push(ut),i.push(He(crypto.randomUUID(),"tool.completed",e.id,{tool:De.toolName,status:ut.status},t));let Ft=De.id;if(be=[...be,{id:crypto.randomUUID(),role:"assistant",content:Pe.content,timestamp:new Date,transportOrigin:"agent",toolInvocations:[{toolName:De.toolName,input:De.input,output:ut.output,durationMs:ut.durationMs,status:ut.status}],metadata:{toolUseId:Ft}},{id:crypto.randomUUID(),role:"tool",content:typeof ut.output=="string"?ut.output:JSON.stringify(ut.output),timestamp:new Date,transportOrigin:"tool",metadata:{toolName:De.toolName,callId:Ft}}],yt.shortCircuited){Z={finalResponse:yt.finalResponse??null,reason:yt.reason},A=Pe,Ee=!0;break}}if(Ee)break e;if(E.isExhausted()){m&&v.push({step:"budget_check",timestamp:Date.now(),data:{exhausted:!0,status:E.getStatus()}}),A=Pe,L=!0;break e}m&&v.push({step:"budget_check",timestamp:Date.now(),data:{exhausted:!1,status:E.getStatus()}})}else{A=Pe;break e}}if(Z)break t;let T=A?.content??(E.getStatus().exhausted||L?"[Agent budget exhausted]":"[Agent reached max turns without completing]"),D=or(crypto.randomUUID(),T,a.map(ne=>({toolName:ne.toolName,input:{},output:ne.output,durationMs:ne.durationMs,status:ne.status}))),oe=await S("pre_capture",{response:D,toolResults:a,ontology:$});if(oe.correctionRequested){if(P({toolName:T.toolName,input:{},output:T.output,durationMs:T.durationMs,status:T.status})));_=Mr(_,O),await n.sessions.save(_),i.push(He(crypto.randomUUID(),"message.sent",e.id,{messageId:O.id},t));let W=[],ce=[];try{let T=await Hi({response:O.content,ontology:$,agent:e,sessionId:t,turnId:g,memory:n.memory});W=T.captured,ce=T.dropped;for(let D of T.errors)h.push({phase:"post_capture",key:"memory.capture_error",value:D});for(let D of T.frictionEvents)i.push(D)}catch(T){h.push({phase:"post_capture",key:"memory.capture_error",value:T instanceof Error?T.message:String(T)})}let $e=$.entityTypes.map(T=>T.name),B;if(W.length>0)for(let T of W)try{let D=await n.memory.getSupersedeChain(T.id);if(D.length===0)continue;let oe=Object.keys(T.structured).sort(),ie=oe.filter(Ee=>Ee!=="id")[0]??oe[0];if(!ie||D.filter(Ee=>ie in Ee.structured).lengthEe.structured[ie]);B={chainAnchor:T.id,entityType:T.entityType,propertyName:ie,currentValue:T.structured[ie],priorValues:Pe};break}catch{continue}let Re=await S("post_capture",{captured:W,availableEntityTypes:$e,droppedCandidates:ce,...B?{recentlyCaptured:B}:{}});Re.shortCircuited&&!Z&&(Z={finalResponse:Re.finalResponse??null,reason:Re.reason});let Fe=vr(e.config.modelId,{inputTokens:s,outputTokens:c,cacheReadTokens:u,cacheWriteTokens:l});m&&v.push({step:"complete",timestamp:Date.now(),data:{budgetExhausted:K,responseLength:O.content.length,totalLLMCalls:V,hardCap:j}});let R={response:O,session:_,memoriesCaptured:W,events:i,toolResults:a,usage:{inputTokens:s,outputTokens:c,llmCalls:d,estimatedCostUSD:Fe},budgetExhausted:K,budgetStatus:{calls:M.calls,tokens:M.tokens,timeMs:M.timeMs,...M.exhaustedReason?{reason:M.exhaustedReason}:{}},...m?{trace:v}:{}};return await S("post_turn",{result:R,availableEntityTypes:$e}),R}catch(J){let te={response:or(crypto.randomUUID(),`[Agent error: ${J instanceof Error?J.message:String(J)}]`,[]),session:_,memoriesCaptured:[],events:i,toolResults:a,usage:{inputTokens:s,outputTokens:c,llmCalls:d,estimatedCostUSD:vr(e.config.modelId,{inputTokens:s,outputTokens:c,cacheReadTokens:u,cacheWriteTokens:l})}};try{await S("post_turn",{result:te,availableEntityTypes:$.entityTypes.map(_e=>_e.name)})}catch{}throw J}}var eO=new RegExp("\\b[A-Za-z0-9]{32,}\\b","g");async function*Dy(e,t,r,n,o,i){let a=[],s=[],c=0,u=0,l=0,d=0,m=0,v=o??Vi(e.config.maxTurns||10),g=Li(v,{modelId:e.config.modelId}),h=Math.max(v.maxCalls!=null?v.maxCalls*2:100,1),f=!1,y=crypto.randomUUID(),S=[],_="init",$=Ki({registry:n.hooks??new kn,agent:e,sessionId:t,turnId:y,onEvent:te=>a.push(te),onAnnotation:(te,_e)=>S.push({phase:_,key:te,value:_e})}),k=async(te,_e)=>{_=te;try{return await $(te,_e)}catch(ke){if(!(ke instanceof _r))throw ke;let Ne=ke.message;return S.push({phase:te,key:"streaming.hook_exception",value:Ne}),a.push(Zt(e.id,t,"streaming.hook_exception",{phase:te,error:Ne})),{payload:_e,shortCircuited:!1,correctionRequested:!1}}},w=r.metadata?.userId??"unknown",b=await n.sessions.get(t);b||(b=Ur(t,e.id,w,r.transportOrigin)),b=Mr(b,r),a.push(He(crypto.randomUUID(),"message.received",e.id,{messageId:r.id},t));let E=await n.ontologyService.compose(e.id),j=await n.memory.recall({agentId:e.id,query:r.content,limit:20}),V=j.entries,A=!1,L,Z=null,J=!1;try{let te=await k("pre_turn",{userMessage:r,ontology:E,memories:V,session:b});te.shortCircuited?(L=te.reason,Z=te.finalResponse??null,yield sp("pre_turn",te.reason,te.finalResponse),J=!0):(E=te.payload.ontology,V=te.payload.memories);let _e=[];if(!J)for(let B of e.config.toolScopes){let Re=await n.tools.discoverTools(B);_e.push(...Re)}let ke=20,Ne=b.messages.length>ke?b.messages.slice(-ke):b.messages,be=J?{systemPrompt:"",messages:[],tools:[],tokenEstimate:0}:qi({config:e.config,ontology:E,memories:V,messages:Ne,tools:_e,ontologyRenderer:n.ontologyRenderer,transport:r.transportOrigin});if(!J){let B=await k("pre_context",{context:be,recall:j,recallQuery:r.content,availableEntityTypes:E.entityTypes.map(Re=>Re.name)});B.shortCircuited?(L=B.reason,Z=B.finalResponse??null,yield sp("pre_context",B.reason,B.finalResponse),J=!0):be=B.payload.context}let P=[...Ne],M="";for(;!J&&m0?"tool_use":"end_turn"};g.recordCall(T.usage);let D=await k("post_llm",{response:T,callNumber:m});c+=T.usage.inputTokens,u+=T.usage.outputTokens,l+=T.usage.cacheReadTokens??0,d+=T.usage.cacheWriteTokens??0;let oe=D.payload.response;if(D.shortCircuited){a.push(Zt(e.id,t,"streaming.short_circuit_after_emit",{phase:"post_llm",reason:D.reason}));break}if(oe.toolCalls.length===0)break;let ne=E.entityTypes.map(me=>me.name),ie=!1;for(let me of oe.toolCalls){let Pe=await k("pre_tool",{call:me});if(Pe.shortCircuited){a.push(Zt(e.id,t,"streaming.short_circuit_after_emit",{phase:"pre_tool",reason:Pe.reason})),ie=!0;break}let Ee=Pe.payload.call;a.push(He(crypto.randomUUID(),"tool.invoked",e.id,{tool:Ee.toolName},t));let Ze=await n.tools.execute(Ee),je=await k("post_tool",{call:Ee,result:Ze,availableEntityTypes:ne}),De=je.payload.result;if(s.push(De),a.push(He(crypto.randomUUID(),"tool.completed",e.id,{tool:Ee.toolName,status:De.status},t)),P=[...P,{id:crypto.randomUUID(),role:"assistant",content:Re,timestamp:new Date,transportOrigin:"agent",toolInvocations:[{toolName:Ee.toolName,input:Ee.input,output:De.output,durationMs:De.durationMs,status:De.status}],metadata:{toolUseId:Ee.id}},{id:crypto.randomUUID(),role:"tool",content:typeof De.output=="string"?De.output:JSON.stringify(De.output),timestamp:new Date,transportOrigin:"tool",metadata:{toolName:Ee.toolName,callId:Ee.id}}],je.shortCircuited){a.push(Zt(e.id,t,"streaming.short_circuit_after_emit",{phase:"post_tool",reason:je.reason})),ie=!0;break}}if(ie)break;if(g.isExhausted()){f=!0;let me=g.getStatus();a.push(Zt(e.id,t,"streaming.budget_exhausted",{reason:me.exhaustedReason,calls:me.calls})),yield` +[Agent budget exhausted${me.exhaustedReason?`: ${me.exhaustedReason}`:""}]`;break}}let K=J?Z??or(crypto.randomUUID(),`[Agent short-circuited${L?`: ${L}`:""}]`,[]):or(crypto.randomUUID(),f&&M.trim().length===0?"[Agent budget exhausted]":M,s.map(B=>({toolName:B.toolName,input:{},output:B.output,durationMs:B.durationMs,status:B.status}))),z=K,I=[],O=[];if(!J){let B=await k("pre_capture",{response:K,toolResults:s,ontology:E});B.correctionRequested?a.push(Zt(e.id,t,"streaming.correction_requested",{hookName:B.hookName,correctionPrompt:B.correctionPrompt})):B.shortCircuited&&a.push(Zt(e.id,t,"streaming.short_circuit_after_emit",{phase:"pre_capture",reason:B.reason})),z=B.shortCircuited&&B.finalResponse?B.finalResponse:K;try{let T=await Hi({response:z.content,ontology:E,agent:e,sessionId:t,turnId:y,memory:n.memory});I=T.captured,O=T.dropped;for(let D of T.errors)a.push(Zt(e.id,t,"streaming.memory_capture_error",{error:D}));for(let D of T.frictionEvents)a.push(D)}catch(T){a.push(Zt(e.id,t,"streaming.memory_capture_error",{error:T instanceof Error?T.message:String(T)}))}let Re=E.entityTypes.map(T=>T.name),Fe;if(I.length>0)for(let T of I)try{let D=await n.memory.getSupersedeChain(T.id);if(D.length===0)continue;let oe=Object.keys(T.structured).sort(),ie=oe.filter(Ee=>Ee!=="id")[0]??oe[0];if(!ie||D.filter(Ee=>ie in Ee.structured).lengthEe.structured[ie]);Fe={chainAnchor:T.id,entityType:T.entityType,propertyName:ie,currentValue:T.structured[ie],priorValues:Pe};break}catch{continue}let R=await k("post_capture",{captured:I,availableEntityTypes:Re,droppedCandidates:O,...Fe?{recentlyCaptured:Fe}:{}});R.shortCircuited&&a.push(Zt(e.id,t,"streaming.short_circuit_after_emit",{phase:"post_capture",reason:R.reason}))}b=Mr(b,z),await n.sessions.save(b),a.push(He(crypto.randomUUID(),"message.sent",e.id,{messageId:z.id},t));let W=g.getStatus(),ce=f||W.exhausted,$e={response:z,session:b,memoriesCaptured:I,events:a,toolResults:s,usage:{inputTokens:c,outputTokens:u,llmCalls:m,estimatedCostUSD:vr(e.config.modelId,{inputTokens:c,outputTokens:u,cacheReadTokens:l,cacheWriteTokens:d})},budgetExhausted:ce,budgetStatus:{calls:W.calls,tokens:W.tokens,timeMs:W.timeMs,...W.exhaustedReason?{reason:W.exhaustedReason}:{}}};try{await k("post_turn",{result:$e,availableEntityTypes:E.entityTypes.map(B=>B.name)})}catch{}}catch(te){let _e=g.getStatus(),ke={response:or(crypto.randomUUID(),`[Agent error: ${te instanceof Error?te.message:String(te)}]`,[]),session:b,memoriesCaptured:[],events:a,toolResults:s,usage:{inputTokens:c,outputTokens:u,llmCalls:m,estimatedCostUSD:vr(e.config.modelId,{inputTokens:c,outputTokens:u,cacheReadTokens:l,cacheWriteTokens:d})},budgetExhausted:f||_e.exhausted,budgetStatus:{calls:_e.calls,tokens:_e.tokens,timeMs:_e.timeMs,..._e.exhaustedReason?{reason:_e.exhaustedReason}:{}}};try{await k("post_turn",{result:ke,availableEntityTypes:E.entityTypes.map(Ne=>Ne.name)})}catch{}throw te}}function sp(e,t,r){return r?.content?r.content:`[Agent short-circuited at ${e}${t?`: ${t}`:""}]`}function Zt(e,t,r,n){return{id:crypto.randomUUID(),type:"turn.annotated",agentId:e,sessionId:t,timestamp:new Date,payload:{key:r,...n}}}function Ly(e,t=new Map){let r=new Map(t),n={async compose(a){let s=r.get(a);if(!s)throw new Error(`Agent not found: ${a}`);let c=s.config.ontologyScopes;return e.ontologyRepo.compose(c)},render(a){return qy(a)},async validate(a,s){let c=r.values().next().value;if(!c)return!0;let u=await e.ontologyRepo.compose(c.config.ontologyScopes);return e.ontologyRepo.validateEntry(a,s,u).valid}},o={render:qy};return{async handleMessage({agentId:a,sessionId:s,message:c,budget:u}){let l=r.get(a);if(!l)throw new Error(`Agent not found: ${a}`);let d=await ap(l,s,c,{llm:e.llm,tools:e.toolExecutor,memory:e.memory,sessions:e.sessions,ontologyService:n,ontologyRenderer:o,transport:e.transport??nE,embedding:e.embedding},u);return{message:d.response,session:d.session,memoriesCaptured:d.memoriesCaptured,delegations:[],usage:d.usage}},handleMessageStream({agentId:a,sessionId:s,message:c,budget:u,hooks:l,signal:d}){let m=r.get(a);if(!m)throw new Error(`Agent not found: ${a}`);return Dy(m,s,c,{llm:e.llm,tools:e.toolExecutor,memory:e.memory,sessions:e.sessions,ontologyService:n,ontologyRenderer:o,embedding:e.embedding,...l?{hooks:l}:{}},u,d)},async startSession({agentId:a,userId:s,transportId:c}){let u=Ur(crypto.randomUUID(),a,s,c);return await e.sessions.save(u),u},async getAgent(a){return r.get(a)??null},registry:{async getAgent(a){return r.get(a)??null},async listAgents(){return Array.from(r.values())},async registerAgent(a,s){let c=Ry(a,s);return r.set(c.id,c),c}}}}function qy(e){if(e.entityTypes.length===0)return"";let t=["# Domain Ontology"];for(let r of e.entityTypes){let n=r.properties.map(a=>a.name).join(", "),o=e.relationships.filter(a=>a.fromType===r.name).map(a=>`${a.name}\u2192${a.toType}`).join(", "),i=`## ${r.name}: [${n}]`;o&&(i+=` | ${o}`),r.description&&r.description!==r.name&&(i+=` +${r.description}`),t.push(i)}return t.join(` +`)}var nE={async send(){},async stream(){}};function Vy(e){let t=[];for(let r of e)if(r.role==="user")t.push({role:"user",content:r.content});else if(r.role==="assistant")if(r.toolInvocations&&r.toolInvocations.length>0){let n=[];r.content&&n.push({type:"text",text:r.content});let o=r.metadata?.toolUseId||r.toolInvocations[0].toolName+"_"+Math.random().toString(36).slice(2);for(let i of r.toolInvocations)n.push({type:"tool_use",id:o,name:i.toolName,input:i.input});t.push({role:"assistant",content:n})}else t.push({role:"assistant",content:r.content});else if(r.role==="tool"){let n=r.metadata?.toolName||"unknown",o=r.metadata?.callId||n+"_"+Date.now();t.push({role:"user",content:[{type:"tool_result",tool_use_id:o,content:r.content}]})}return t}function Ky(e){return e.map(t=>({name:t.name,description:t.description,input_schema:t.inputSchema}))}var rc=class{config;constructor(t){this.config=t}async complete(t){let r={model:t.model||this.config.defaultModel||"claude-sonnet-4-6",max_tokens:t.maxTokens||this.config.maxTokens||4096,system:t.systemPrompt,messages:Vy(t.messages)};t.temperature!==void 0&&(r.temperature=t.temperature),t.tools&&t.tools.length>0&&(r.tools=Ky(t.tools));let n=this.config.baseUrl||"https://api.anthropic.com",o=await fetch(`${n}/v1/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.config.apiKey,"anthropic-version":"2023-06-01"},body:JSON.stringify(r)});if(!o.ok){let c=await o.text();throw new Error(`Anthropic API error: ${o.status} ${c}`)}let i=await o.json(),a="",s=[];for(let c of i.content||[])c.type==="text"?a+=c.text:c.type==="tool_use"&&s.push({id:c.id,toolName:c.name,input:c.input,timestamp:new Date});return{content:a,toolCalls:s,usage:{inputTokens:i.usage?.input_tokens||0,outputTokens:i.usage?.output_tokens||0},stopReason:i.stop_reason==="tool_use"?"tool_use":i.stop_reason==="max_tokens"?"max_tokens":"end_turn"}}async*stream(t){let r={model:t.model||this.config.defaultModel||"claude-sonnet-4-6",max_tokens:t.maxTokens||this.config.maxTokens||4096,system:t.systemPrompt,messages:Vy(t.messages),stream:!0};t.temperature!==void 0&&(r.temperature=t.temperature),t.tools&&t.tools.length>0&&(r.tools=Ky(t.tools));let n=this.config.baseUrl||"https://api.anthropic.com",o=await fetch(`${n}/v1/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.config.apiKey,"anthropic-version":"2023-06-01"},body:JSON.stringify(r),signal:t.signal});if(!o.ok){let f=await o.text();throw new Error(`Anthropic streaming error: ${o.status} ${f}`)}let i=o.body?.getReader();if(!i)throw new Error("No response body for streaming");let a=new TextDecoder,s="",c=0,u=0,l=0,d=0,m=!1,v=new Map,g=f=>typeof f!="number"||!Number.isFinite(f)||f<0?null:f,h=()=>{if(!m)return{type:"done"};let f={inputTokens:c,outputTokens:u};return l>0&&(f.cacheReadTokens=l),d>0&&(f.cacheWriteTokens=d),{type:"done",usage:f}};for(;;){let{done:f,value:y}=await i.read();if(f)break;s+=a.decode(y,{stream:!0});let S=s.split(` +`);s=S.pop()||"";for(let _ of S){if(!_.startsWith("data: "))continue;let $=_.slice(6).trim();if($==="[DONE]"){yield h();return}try{let k=JSON.parse($);if(k.type==="message_start"){let w=k.message?.usage;if(w){let b=g(w.input_tokens),E=g(w.output_tokens),j=g(w.cache_read_input_tokens),V=g(w.cache_creation_input_tokens);(b!==null||E!==null||j!==null||V!==null)&&(m=!0,b!==null&&(c=b),E!==null&&(u=E),j!==null&&(l=j),V!==null&&(d=V))}}else if(k.type==="content_block_delta"){if(k.delta?.type==="text_delta")yield{type:"text",content:k.delta.text};else if(k.delta?.type==="input_json_delta"){let w=k.index,b=w!==void 0?v.get(w):void 0;b&&typeof k.delta.partial_json=="string"&&(b.jsonBuffer+=k.delta.partial_json)}}else if(k.type==="content_block_start"){if(k.content_block?.type==="tool_use"){let w=k.index;w!==void 0&&v.set(w,{id:k.content_block.id,toolName:k.content_block.name,jsonBuffer:""})}}else if(k.type==="content_block_stop"){let w=k.index,b=w!==void 0?v.get(w):void 0;if(b){let E={};if(b.jsonBuffer.trim().length>0)try{let j=JSON.parse(b.jsonBuffer);j!==null&&typeof j=="object"&&!Array.isArray(j)&&(E=j)}catch{}yield{type:"tool_call",toolCall:{id:b.id,toolName:b.toolName,input:E,timestamp:new Date}},v.delete(w)}}else if(k.type==="message_delta"){let w=k.usage;if(w){let b=g(w.output_tokens);b!==null&&(m=!0,u=b)}}else if(k.type==="message_stop"){yield h();return}}catch{}}}if(s.length>0)for(let f of s.split(` +`)){if(!f.startsWith("data: "))continue;let y=f.slice(6).trim();if(!(y==="[DONE]"||y.length===0))try{let S=JSON.parse(y);if(S.type==="message_delta"){let _=S.usage;if(_){let $=g(_.output_tokens);$!==null&&(m=!0,u=$)}}}catch{}}yield h()}};var nc=class{callCount=0;async embed(t){this.callCount++;let r=new Array(8).fill(0);for(let o=0;oo+i*i,0));return n>0?r.map(o=>o/n):r}async embedBatch(t){return Promise.all(t.map(r=>this.embed(r)))}getCallCount(){return this.callCount}};var oc=class{entries=[];events=[];async store(t){this.entries.push(t),this.events.push({id:crypto.randomUUID(),entryId:t.id,action:"created",newValue:t.content,author:t.source.author,timestamp:new Date})}async recall(t){let r=t.limit??10,n=t.query.toLowerCase(),o=this.entries.filter(a=>a.agentId!==t.agentId||a.status!=="active"||t.scope&&a.scope!==t.scope||t.scopeId&&a.scopeId!==t.scopeId||t.entityType&&a.entityType!==t.entityType?!1:a.content.toLowerCase().includes(n)).slice(0,r),i=o.length;return{entries:o,source:i>0?"text":"none",vectorCapable:!1,vectorMatchCount:0,textMatchCount:i}}async supersede(t,r){let n=this.entries.find(o=>o.id===t);if(n){let o=this.entries.indexOf(n);this.entries[o]={...n,status:"superseded",supersededBy:r},this.events.push({id:crypto.randomUUID(),entryId:t,action:"superseded",previousValue:n.content,author:"system",timestamp:new Date})}}async getEventLog(t){return this.events.filter(r=>r.entryId===t)}async getByEntityType(t,r){return this.entries.filter(n=>n.agentId===t&&n.entityType===r&&n.status==="active")}async getSupersedeChain(t){let n=[],o=new Set,i=t;o.add(i);let a=this.entries.find(s=>s.id===t);if(a===void 0)return[];for(;n.length<50;){let s=this.entries.filter(u=>u.supersededBy===i&&u.agentId===a.agentId&&u.scope===a.scope&&u.scopeId===a.scopeId&&u.status==="superseded").sort((u,l)=>l.createdAt.getTime()-u.createdAt.getTime());if(s.length===0)break;let c=s[0];if(o.has(c.id))break;o.add(c.id),n.push(c),i=c.id}return n}getAll(){return[...this.entries]}getAllEvents(){return[...this.events]}clear(){this.entries=[],this.events=[]}};var ic=class{sessions=new Map;async get(t){return this.sessions.get(t)??null}async save(t){this.sessions.set(t.id,t)}async findByUser(t,r,n){let o=Array.from(this.sessions.values()).filter(i=>i.userId===t&&i.agentId===r).sort((i,a)=>a.createdAt.getTime()-i.createdAt.getTime());return n?o.slice(0,n):o}async findByUserLightweight(t,r,n){let o=Array.from(this.sessions.values()).filter(a=>a.userId===t&&a.agentId===r).sort((a,s)=>s.updatedAt.getTime()-a.updatedAt.getTime());return(n?o.slice(0,n):o).map(a=>{let s=a.messages.find(u=>u.role==="user"),c=a.messages.length>0?a.messages[a.messages.length-1]:void 0;return{id:a.id,agentId:a.agentId,userId:a.userId,status:a.status,turnCount:a.turnCount,messageCount:a.messages.length,createdAt:a.createdAt,updatedAt:a.updatedAt,firstMessage:s?s.content.substring(0,100):void 0,lastMessage:c?c.content.substring(0,100):void 0}})}clear(){this.sessions.clear()}getAll(){return Array.from(this.sessions.values())}};function Jy(e){let t=new Map,r=[];for(let o of e){for(let i of o.entityTypes){let a=t.get(i.name);if(a){let s=new Set(a.properties.map(u=>u.name)),c=i.properties.filter(u=>!s.has(u.name));t.set(i.name,{...a,properties:[...a.properties,...c],description:i.description||a.description})}else t.set(i.name,i)}r.push(...o.relationships)}let n=new Map;for(let o of r)n.set(o.id,o);return{layers:e,entityTypes:Array.from(t.values()),relationships:Array.from(n.values()),version:e.map(o=>`${o.name}@${o.version}`).join("+")}}function Fy(e,t,r){let n=[],o=[],i=r.entityTypes.find(a=>a.name===e);if(!i)return{valid:!1,errors:[{field:"entityType",message:`Unknown entity type: ${e}`,code:"unknown_entity"}],warnings:[]};for(let a of i.properties)a.required&&!(a.name in t)&&n.push({field:a.name,message:`Required property missing: ${a.name}`,code:"missing_required"});for(let[a,s]of Object.entries(t)){let c=i.properties.find(u=>u.name===a);if(!c){o.push(`Property "${a}" not defined in ontology for ${e}`);continue}c.type==="enum"&&c.enumValues&&s!==void 0&&(c.enumValues.includes(String(s))||n.push({field:a,message:`Invalid value "${s}" for enum ${a}. Expected one of: ${c.enumValues.join(", ")}`,code:"invalid_enum"})),s!=null&&(oE(s,c.type)||n.push({field:a,message:`Expected ${c.type} for ${a}, got ${typeof s}`,code:"invalid_type"}))}return{valid:n.length===0,errors:n,warnings:o}}function oE(e,t){switch(t){case"string":case"enum":return typeof e=="string";case"number":return typeof e=="number";case"boolean":return typeof e=="boolean";case"date":return typeof e=="string"||e instanceof Date;case"reference":return typeof e=="string";default:return!0}}var ac=class{layers=new Map;async getLayer(t){return this.layers.get(t)??null}async getLayersByScope(t){return Array.from(this.layers.values()).filter(r=>r.scope===t)}async compose(t){let r=t.map(n=>this.layers.get(n)).filter(n=>n!=null);return Jy(r)}validateEntry(t,r,n){let o=Fy(t,r,n);return{valid:o.valid,errors:o.errors.map(i=>i.message)}}addLayer(t){this.layers.set(t.id,t)}clear(){this.layers.clear()}};function Hy(e,t){let r=[],n=[];for(let[o,i]of Object.entries(t.entities||{})){let a=[];if(i.properties)for(let c of i.properties)a.push({name:c,type:"string",required:!1,description:""});for(let[c,u]of Object.entries(i))Array.isArray(u)&&c!=="properties"&&c!=="belongs_to"&&c!=="has_many"&&c!=="connects"&&u.every(l=>typeof l=="string")&&a.push({name:c,type:"enum",enumValues:u,required:!1,description:`${c} for ${o}`});r.push({id:`${e}:${o}`,layerId:e,name:o,properties:a,description:i.description||o});let s=i.belongs_to?Array.isArray(i.belongs_to)?i.belongs_to:[i.belongs_to]:[];for(let c of s)n.push({id:`${e}:${o}:belongs_to:${c}`,layerId:e,name:"belongs_to",fromType:o,toType:c,cardinality:"many_to_many",description:`${o} belongs to ${c}`});for(let c of i.has_many||[])n.push({id:`${e}:${o}:has_many:${c}`,layerId:e,name:"has_many",fromType:o,toType:c,cardinality:"one_to_many",description:`${o} has many ${c}`});for(let c of i.connects||[])n.push({id:`${e}:${o}:connects:${c}`,layerId:e,name:"connects",fromType:o,toType:c,cardinality:"many_to_many",description:`${o} connects to ${c}`})}return{id:e,name:t.name,scope:t.scope,version:1,entityTypes:r,relationships:n,createdAt:new Date,updatedAt:new Date}}function Sy(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)}var tp=e=>typeof e=="string"?e.toLowerCase():"",js=class{servers;scopePrefix;mode;clientFactory;clients=new Map;connecting=new Map;toolCache=new Map;routes=new Map;constructor(t){this.servers=new Map(t.servers.map(r=>[r.id,r])),this.scopePrefix=t.scopePrefix??"mcp",this.mode=t.mode??"direct",this.clientFactory=t.clientFactory??vA}serverForScope(t){let r=`${this.scopePrefix}:`;return t.startsWith(r)?this.servers.get(t.slice(r.length))??null:null}async getClient(t){let r=this.clients.get(t.id);if(r)return r;let n=this.connecting.get(t.id);if(n)return n;let o=(async()=>{let i=this.clientFactory(t);return await i.connect(),this.clients.set(t.id,i),this.connecting.delete(t.id),i})().catch(i=>{throw this.connecting.delete(t.id),i});return this.connecting.set(t.id,o),o}async fetchRawTools(t){let r=this.toolCache.get(t.id);if(r)return r;let i=(await(await this.getClient(t)).listTools()).tools??[];return this.toolCache.set(t.id,i),i}async discoverTools(t){let r=this.serverForScope(t);return r?this.mode==="proxy"?this.discoverProxy(r,t):this.discoverDirect(r,t):[]}discoverProxy(t,r){let n=Sy(`${t.id}__list_tools`),o=Sy(`${t.id}__call_tool`);return this.routes.set(n,{serverId:t.id,proxy:"list"}),this.routes.set(o,{serverId:t.id,proxy:"call"}),[{name:n,description:`List or search the tools available from the "${t.id}" MCP server. Returns each tool's name, description, and input schema. Call this to discover what "${t.id}" can do before using ${o}.`,inputSchema:{type:"object",properties:{query:{type:"string",description:"Optional filter over tool name/description."}},additionalProperties:!1},source:r,requiresApproval:!1,permissionScope:`${r}:list`},{name:o,description:`Invoke a tool on the "${t.id}" MCP server. Use ${n} first to find the exact tool name and its required arguments.`,inputSchema:{type:"object",properties:{tool:{type:"string",description:`Tool name from ${n}.`},arguments:{type:"object",description:"Arguments object matching that tool's input schema."}},required:["tool"],additionalProperties:!1},source:r,requiresApproval:!1,permissionScope:`${r}:call`}]}async discoverDirect(t,r){let n;try{n=await this.fetchRawTools(t)}catch(a){return console.log(`mcp-client: discover failed for ${t.id}:`,a instanceof Error?a.message:String(a)),[]}let o=[],i=new Set;for(let a of n){let s=Sy(`${t.id}__${a.name}`);if(i.has(s)){let c=s.slice(0,61),u=1;for(;i.has(`${c}_${u}`);)u++;s=`${c}_${u}`}i.add(s),this.routes.set(s,{serverId:t.id,toolName:a.name}),o.push({name:s,description:a.description??`${a.name} (via ${t.id})`,inputSchema:a.inputSchema??{type:"object",properties:{}},source:r,requiresApproval:!1,permissionScope:`${r}:call`})}return o}async execute(t){let r=Date.now(),n=(s,c,u)=>({callId:t.id,toolName:t.toolName,output:s,status:c,...u?{error:u}:{},durationMs:Date.now()-r,timestamp:new Date}),o=this.routes.get(t.toolName);if(!o)return n(null,"error",`unknown MCP tool: ${t.toolName}`);let i=this.servers.get(o.serverId);if(!i)return n(null,"error",`unknown MCP server: ${o.serverId}`);let a=t.input??{};try{if(o.proxy==="list"){let v=typeof a.query=="string"?a.query:"",g=(await this.fetchRawTools(i)).filter(h=>!v||tp(h.name).includes(tp(v))||tp(h.description).includes(tp(v))).slice(0,40).map(h=>({tool:h.name,description:h.description??"",inputSchema:h.inputSchema??{type:"object"}}));return n({server:i.id,count:g.length,tools:g},"success")}let s=o.proxy==="call"?typeof a.tool=="string"?a.tool:"":o.toolName??"";if(!s)return n(null,"error",`no tool name provided for ${t.toolName}`);let c=o.proxy==="call"?a.arguments??{}:a,l=await(await this.getClient(i)).callTool({name:s,arguments:c}),m=(l.content??[]).filter(v=>v.type==="text"&&typeof v.text=="string").map(v=>v.text).join(` +`).trim()||l.content||null;return n(m,l.isError?"error":"success")}catch(s){return n(null,"error",s instanceof Error?s.message:String(s))}}async close(){for(let t of this.clients.values())try{await t.close?.()}catch{}this.clients.clear()}};function vA(e){let t=null,r=async()=>{let{Client:n,StreamableHTTPClientTransport:o}=await Promise.resolve().then(()=>(Mk(),Uk)),i=new n({name:"freya-mcp-client",version:"0.1.0"}),a=new o(new URL(e.url),e.headers?{requestInit:{headers:e.headers}}:void 0);return await i.connect(a),{listTools:()=>i.listTools(),callTool:s=>i.callTool(s),close:()=>i.close()}};return{async connect(){t=r(),await t},async listTools(){return t||(t=r()),(await t).listTools()},async callTool(n){return t||(t=r()),(await t).callTool(n)},async close(){t&&await(await t).close()}}}var $y="frigg-web",by="netlify-web",_A={name:"frigg",scope:"domain",entities:{Platform:{description:"A third-party software product Frigg integrates with (e.g. HubSpot, Salesforce, Attio).",properties:["name","vendor"]},ApiModule:{description:"A prebuilt Frigg connector for a platform API, installed with `frigg install ` and drawn from the api-module-library.",properties:["name","provider","authType"],category:["ai","analytics","commerce","communication","crm","devtools","finance","hr","marketing","other","productivity","storage","support"],complexity:["Low","Medium","High"],status:["Active","Beta","Planned"],belongs_to:"Platform"},Integration:{description:"A running integration a developer builds by extending IntegrationBase, wiring API modules to events (USER_ACTION, CRON, QUEUE, WEBHOOK).",properties:["name","useCase"],connects:["ApiModule","Primitive"]},Primitive:{description:"A Frigg building block exposed to developers and their agents: an Endpoint, a Queue, a Provider-native backend, or a Fenestra in-app UI experience.",properties:["name"],kind:["Endpoint","Queue","ProviderNative","Fenestra"]},Capability:{description:"A typed declaration of what a module or integration can do, pointing at a spec and its implementation (the mcp-tool / agent-tooling surface).",properties:["name","spec"],belongs_to:"ApiModule"},Adr:{description:'A Frigg architecture decision record shaping the roadmap, tracked on the "next" branch and surfaced at /roadmap/.',properties:["num","title","theme"],status:["Accepted","Proposed","Superseded","Draft"]},Visitor:{description:"A person chatting with the assistant on the site.",properties:["name","stack","interest"]}}},ro={adrs:[],apis:[],categories:[],builtCount:0},pi=e=>typeof e=="string"?e.toLowerCase():"",to=(e,t)=>!t||pi(e).includes(pi(t)),wy=class{async discoverTools(t){return t!=="roadmap"?[]:[{name:"catalog_stats",description:'Frigg roadmap catalog summary: number of ADRs, number of API modules, how many are already built, and the list of API categories. Call this first for any "how many / what categories" question.',inputSchema:{type:"object",properties:{},additionalProperties:!1},source:"roadmap",requiresApproval:!1,permissionScope:"roadmap:read"},{name:"search_adrs",description:"Search Frigg architecture decision records (ADRs). Filter by free-text query (matches title/summary/theme) and/or status (e.g. Accepted, Proposed). Returns matching ADRs with number, title, status, theme, one-line summary, and URL.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Free-text filter over title/summary/theme"},status:{type:"string",description:'Exact status filter, e.g. "Accepted"'}},additionalProperties:!1},source:"roadmap",requiresApproval:!1,permissionScope:"roadmap:read"},{name:"search_apis",description:"Search the Frigg API module catalog (224 integrations). Filter by free-text query (matches name/provider/description/tags), category, or built=true to only return modules that already exist in api-module-library. Returns a capped list plus the total match count so you can point people to /roadmap/ for the full set.",inputSchema:{type:"object",properties:{query:{type:"string"},category:{type:"string",description:"One of the catalog categories"},built:{type:"boolean",description:"If true, only modules already built"}},additionalProperties:!1},source:"roadmap",requiresApproval:!1,permissionScope:"roadmap:read"}]}async execute(t){let r=Date.now(),n=(o,i="success",a)=>({callId:t.id,toolName:t.toolName,output:o,status:i,error:a,durationMs:Date.now()-r,timestamp:new Date});try{let o=t.input||{};if(t.toolName==="catalog_stats")return n({adrCount:ro.adrs.length,apiCount:ro.apis.length,builtCount:ro.builtCount,categories:ro.categories});if(t.toolName==="search_adrs"){let i=ro.adrs.filter(a=>(to(a.title,o.query)||to(a.summary,o.query)||to(a.theme,o.query))&&(!o.status||pi(a.status)===pi(o.status)));return n({total:i.length,adrs:i.slice(0,12).map(a=>({num:a.num,title:a.title,status:a.status,theme:a.theme,summary:a.summary,url:a.url}))})}if(t.toolName==="search_apis"){let i=ro.apis.filter(a=>(to(a.name,o.query)||to(a.provider,o.query)||to(a.description,o.query)||Array.isArray(a.tags)&&a.tags.some(s=>to(s,o.query)))&&(!o.category||pi(a.category)===pi(o.category))&&(o.built===void 0||!!a.built==!!o.built));return n({total:i.length,showing:Math.min(i.length,15),apis:i.slice(0,15).map(a=>({slug:a.slug,name:a.name,provider:a.provider,category:a.category,status:a.status,complexity:a.complexity,built:!!a.built,library:a.library}))})}return n(null,"error",`unknown tool: ${t.toolName}`)}catch(o){return n(null,"error",o&&o.message?o.message:String(o))}}};function SA(){let e=[];process.env.CONTEXT7_API_KEY&&e.push({id:"frigg-docs",url:process.env.CONTEXT7_MCP_URL||"https://mcp.context7.com/mcp",headers:{CONTEXT7_API_KEY:process.env.CONTEXT7_API_KEY}});let t=process.env.GITHUB_MCP_TOKEN;return t&&e.push({id:"frigg-repo",url:process.env.GITHUB_MCP_URL||"https://api.githubcopilot.com/mcp/",headers:{Authorization:`Bearer ${t}`}}),e}var zy=class{constructor(t){this.executors=t,this.owner=new Map}async discoverTools(t){for(let r of this.executors){let n=await r.discoverTools(t);if(n&&n.length){for(let o of n)this.owner.set(o.name,r);return n}}return[]}async execute(t){let r=this.owner.get(t.toolName);return r?r.execute(t):{callId:t.id,toolName:t.toolName,output:null,status:"error",error:`no executor for tool: ${t.toolName}`,durationMs:0,timestamp:new Date}}},rp=null,ky=null,Dk=!1,qk=[];function bA(){if(rp)return rp;ky=new ic;let e=process.env.ANTHROPIC_API_KEY||"",t=process.env.ANTHROPIC_BASE_URL||void 0,r=[new wy],n=SA();n.length&&(r.push(new js({servers:n,mode:"proxy"})),qk=n.map(i=>`mcp:${i.id}`));let o=new zy(r);return rp=Ly({llm:new rc({apiKey:e,baseUrl:t,defaultModel:process.env.ASSISTANT_MODEL||"claude-opus-4-8",maxTokens:900}),toolExecutor:o,memory:new oc,ontologyRepo:(()=>{let i=new ac;return i.addLayer(Hy("frigg",_A)),i})(),sessions:ky,embedding:new nc}),rp}async function $A(e,t,r){Dk||(await e.registry.registerAgent({id:$y,name:"Freya",type:"shared",systemPrompt:t,ontologyScopes:["frigg"],memoryNamespaces:["default"],toolScopes:["roadmap",...qk],routines:[],delegationTargets:[],modelId:r||process.env.ASSISTANT_MODEL||"claude-opus-4-8",maxTurns:6},"friggframework-org"),Dk=!0)}async function EV({systemPrompt:e,model:t,messages:r,data:n}){if(n){let l=n.apis||{};ro={adrs:n.adrs&&n.adrs.adrs||n.adrs||[],apis:l.apis||(Array.isArray(l)?l:[]),categories:l.categories||[],builtCount:l.builtCount||0}}let o=bA();await $A(o,e,t);let i=r.slice(0,-1),a=r[r.length-1],s=crypto.randomUUID(),c=Ur(s,$y,"web-visitor",by);for(let l of i){let d=l.role==="assistant"?or(crypto.randomUUID(),l.content):ho(crypto.randomUUID(),l.content,by);c=Mr(c,d)}await ky.save(c);let u=await o.handleMessage({agentId:$y,sessionId:s,message:ho(crypto.randomUUID(),a.content,by)});return u&&u.message&&u.message.content||""}export{EV as runTurn}; diff --git a/website/tools/freya-vendor/build.mjs b/website/tools/freya-vendor/build.mjs index 76cb72dee..5ae5e46bf 100644 --- a/website/tools/freya-vendor/build.mjs +++ b/website/tools/freya-vendor/build.mjs @@ -81,6 +81,10 @@ await esbuild.build({ platform: 'node', format: 'esm', target: 'node18', + // Minify — the vendored bundle is a generated artifact (not read/diffed by + // hand, and Sonar-excluded), and the MCP SDK + zod + jose it inlines are + // large. Minifying roughly halves the shipped size with no behavior change. + minify: true, // Resolve bare @freyaframework/* specifiers against the Freya checkout. nodePaths: [freyaModules], // Lazily-imported optional deps the assistant path never touches. diff --git a/website/tools/freya-vendor/entry.mjs b/website/tools/freya-vendor/entry.mjs index 6bac20114..073d2ec5e 100644 --- a/website/tools/freya-vendor/entry.mjs +++ b/website/tools/freya-vendor/entry.mjs @@ -24,6 +24,7 @@ import { createSession, addMessage, } from '@freyaframework/core'; +import { McpClientToolExecutor } from '@freyaframework/mcp-client'; const AGENT_ID = 'frigg-web'; const TRANSPORT = 'netlify-web'; @@ -225,15 +226,93 @@ class RoadmapTools { } } +/** + * Configure the MCP servers the assistant can reach, from env. Each is offered + * only when its credential is present, so the widget degrades gracefully: + * - frigg-docs → Context7 (semantic docs), pinned to the next branch via the + * repo's context7.json. Needs CONTEXT7_API_KEY. + * - frigg-repo → GitHub's MCP server (branch-accurate file/code on next). + * Needs GITHUB_MCP_TOKEN (a read-only token); URL overridable via GITHUB_MCP_URL. + */ +function mcpServersFromEnv() { + const servers = []; + if (process.env.CONTEXT7_API_KEY) { + servers.push({ + id: 'frigg-docs', + url: process.env.CONTEXT7_MCP_URL || 'https://mcp.context7.com/mcp', + headers: { CONTEXT7_API_KEY: process.env.CONTEXT7_API_KEY }, + }); + } + // Dedicated var only — do NOT fall back to an ambient GITHUB_TOKEN, which is + // commonly present in host/CI envs and would half-activate this server with a + // wrong-scoped token. + const ghToken = process.env.GITHUB_MCP_TOKEN; + if (ghToken) { + servers.push({ + id: 'frigg-repo', + url: process.env.GITHUB_MCP_URL || 'https://api.githubcopilot.com/mcp/', + headers: { Authorization: `Bearer ${ghToken}` }, + }); + } + return servers; +} + +/** + * Fans discovery/execution across sub-executors (roadmap tools + MCP client). + * Each sub-executor returns [] for scopes it doesn't own, so exactly one claims + * a given scope; the owning executor for each discovered tool is remembered so + * execute() routes straight back to it. + */ +class CompositeToolExecutor { + constructor(executors) { + this.executors = executors; + this.owner = new Map(); + } + async discoverTools(scope) { + for (const ex of this.executors) { + const defs = await ex.discoverTools(scope); + if (defs && defs.length) { + for (const d of defs) this.owner.set(d.name, ex); + return defs; + } + } + return []; + } + async execute(call) { + const ex = this.owner.get(call.toolName); + if (ex) return ex.execute(call); + return { + callId: call.id, + toolName: call.toolName, + output: null, + status: 'error', + error: `no executor for tool: ${call.toolName}`, + durationMs: 0, + timestamp: new Date(), + }; + } +} + let runtime = null; let sessionsRepo = null; let registered = false; +let mcpScopes = []; function getRuntime() { if (runtime) return runtime; sessionsRepo = new InMemorySessionRepository(); const apiKey = process.env.ANTHROPIC_API_KEY || ''; const baseUrl = process.env.ANTHROPIC_BASE_URL || undefined; + + // Roadmap tools always; MCP servers (Context7 docs, GitHub repo) when keyed. + const executors = [new RoadmapTools()]; + const mcpServers = mcpServersFromEnv(); + if (mcpServers.length) { + executors.push(new McpClientToolExecutor({ servers: mcpServers, mode: 'proxy' })); + mcpScopes = mcpServers.map((sv) => `mcp:${sv.id}`); + } + const toolExecutor = new CompositeToolExecutor(executors); + runtime = createAgentRuntime({ llm: new AnthropicLLM({ apiKey, @@ -241,7 +320,7 @@ function getRuntime() { defaultModel: process.env.ASSISTANT_MODEL || 'claude-opus-4-8', maxTokens: 900, }), - toolExecutor: new RoadmapTools(), + toolExecutor, memory: new InMemoryMemoryRepository(), ontologyRepo: (() => { const repo = new InMemoryOntologyRepository(); @@ -264,7 +343,7 @@ async function ensureAgent(rt, systemPrompt, model) { systemPrompt, ontologyScopes: ['frigg'], memoryNamespaces: ['default'], - toolScopes: ['roadmap'], + toolScopes: ['roadmap', ...mcpScopes], routines: [], delegationTargets: [], modelId: model || process.env.ASSISTANT_MODEL || 'claude-opus-4-8',