import { Attributes } from "@opentelemetry/api";
import type { CallToolRequest } from "@modelcontextprotocol/server";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { KeyLike } from "jose";
import type { ValidateFunction } from "ajv";

/**
 * The request/response **schema dialect** a policy is dealing with — named after
 * the schema, not the provider or the URL path. `openai-chat` is the OpenAI Chat
 * Completions schema regardless of the downstream provider (Zuplo translates
 * chat↔provider underneath); `openai-responses` and `anthropic-messages` are
 * pass-through schemas whose native shape reaches the provider unchanged.
 *
 * Determined by the route, never sniffed from the body. New dialects
 * (`openai-embeddings`, `openai-images`, …) extend this union.
 * @public
 */
export declare type AiFormat =
  | "openai-chat"
  | "openai-responses"
  | "anthropic-messages";

/**
 * Akamai AI Firewall Inbound Policy
 * @title Akamai AI Firewall
 * @product ai-gateway
 * @requiresAI
 *
 * Detects and blocks malicious AI inputs and outputs via Akamai's AI Firewall
 * service. Settings come from the policy options (configurationId, api-key,
 * applicationId, streamingAccumulation), and presence in the route's
 * `inbound[]` chain is what enables it.
 *
 * Options are validated at request time and invalid options fail closed with a
 * ConfigurationError. Detect-call failures (invalid credentials, rate limits,
 * outages) also fail closed by default, returning a 502 in the route's native
 * error format; set `onError: "allow"` to fail open and prioritize
 * availability over inspection.
 *
 * For streaming responses it uses a transform stream that can block content
 * mid-stream if harmful content is detected.
 *
 * Do not add this policy to the inbound chain of an app used as a Smart
 * Router classifier (`classifier.app`). The firewall would inspect Smart
 * Router's internal classification call as if it were a completion request,
 * and Smart Router fails open on the resulting denial — so this is rejected
 * with a `ConfigurationError` rather than silently degrading classification.
 *
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
declare function AIGatewayAkamaiFirewallInboundPolicy(
  request: ZuploRequest,
  context: ZuploContext,
  unparsedOptions: unknown,
  policyName: string
): Promise<ZuploRequest | Response>;
export { AIGatewayAkamaiFirewallInboundPolicy };
export { AIGatewayAkamaiFirewallInboundPolicy as AkamaiAIFirewallV2InboundPolicy };

/**
 * The options for the Akamai AI Firewall policy.
 * @public
 */
declare interface AIGatewayAkamaiFirewallInboundPolicyOptions {
  configurationId: ConfigurationID;
  "api-key": APIKey;
  applicationId?: ApplicationID;
  streamingAccumulation?: StreamingAccumulationSettings;
  endpoints?: ApplicableEndpoints;
  onUnknownShape?: OnUnknownShape;
  onError?: OnFirewallError;
}
export { AIGatewayAkamaiFirewallInboundPolicyOptions };
export { AIGatewayAkamaiFirewallInboundPolicyOptions as AkamaiAIFirewallV2PolicyOptions };

/**
 * Authenticates requests to an AI Gateway endpoint with application API keys.
 *
 * Add this policy to an application's `inboundPolicyChain` to require a key
 * for that app only, or place it on the route before the configuration
 * executor to require a key for every application on the route. The policies
 * that follow can read the authenticated application from `request.user`
 * (`sub` is the application name, `data` its metadata), and the application's
 * AI Gateway configuration takes effect for the request. Use `authHeader` and
 * `authScheme` when clients send their app key somewhere other than the
 * default `Authorization: Bearer` header. Enable `credentialPassthrough`, with
 * the application key in a separate header, to forward the caller's
 * `Authorization` header to the primary provider as its credential.
 *
 * When the matched route captures an `app_id` path parameter (platform catch-all
 * `/:app_id/(.*)`), this policy also requires
 * the stored configuration ID to match the URL (adding `config_` for `/a`).
 * It returns 403 on mismatch.
 *
 * On a User App route (`/u/{app_id}`), only a personal API key issued for
 * that User App authenticates. `request.user.sub` is then the key owner's
 * user ID. An application API key on a User App route, or a personal API key
 * on any other route, returns 403. Validation results are cached for
 * `cacheTtlSeconds`, so a revoked key stops working within that window.
 *
 * @title AI Gateway Authentication
 * @product ai-gateway
 * @requiresAI
 * @public
 *
 * @param request - The incoming ZuploRequest
 * @param context - The ZuploContext
 * @param unparsedOptions - The policy configuration options
 * @param policyName - The name of the policy instance
 * @returns The authenticated request with user info, or a 401/403 response if unauthorized
 *
 * @example
 * ```json
 * // policies.json - Authenticate an AI Gateway route
 * {
 *   "name": "ai-gateway-auth",
 *   "policyType": "ai-gateway-auth",
 *   "handler": {
 *     "export": "AIGatewayAuthInboundPolicy",
 *     "module": "$import(@zuplo/runtime)",
 *     "options": {
 *        "cacheTtlSeconds": 300
 *     }
 *   }
 * }
 * ```
 *
 * @example
 * ```json
 * // Accept an app key from a custom header
 * {
 *   "handler": {
 *     "export": "AIGatewayAuthInboundPolicy",
 *     "module": "$import(@zuplo/runtime)",
 *     "options": {
 *       "authHeader": "x-api-key",
 *       "authScheme": ""
 *     }
 *   }
 * }
 * ```
 *
 */
declare function AIGatewayAuthInboundPolicy(
  request: ZuploRequest,
  context: ZuploContext,
  unparsedOptions: AIGatewayAuthInboundPolicyOptions,
  policyName: string
): Promise<Response | ZuploRequest<RequestGeneric>>;
export { AIGatewayAuthInboundPolicy };
export { AIGatewayAuthInboundPolicy as AIGatewayAuthV2InboundPolicy };

/**
 * The options for this policy.
 * @public
 */
declare interface AIGatewayAuthInboundPolicyOptions {
  /**
   * The time to cache authentication results for a particular key. Higher values will decrease latency. Cached results will be valid until the cache expires even in the event the key is deleted, etc.
   */
  cacheTtlSeconds?: number;
  /**
   * The request header that carries the Zuplo application key. When credentialPassthrough is enabled, use a header other than Authorization, such as zp-gateway-api-key.
   */
  authHeader?: string;
  /**
   * The scheme that prefixes the key in the authHeader header, for example Bearer. Set to an empty string when the header contains only the key. The scheme must be a single HTTP token such as Bearer, or empty for a bare key. $env(NAME) is accepted and validated after substitution.
   */
  authScheme?: string;
  /**
   * Forward the caller's Authorization header to the primary provider as its credential. Zuplo reads the application key from authHeader, which must be a header other than Authorization.
   */
  credentialPassthrough?: boolean;
}
export { AIGatewayAuthInboundPolicyOptions };
export { AIGatewayAuthInboundPolicyOptions as AIGatewayAuthV2InboundPolicyOptions };

/**
 * An AI Gateway capability that can have a resolved model selection.
 *
 * @public
 * @example
 * ```typescript
 * const capability: AIGatewayCapability = "completions";
 * ```
 */
export declare type AIGatewayCapability =
  | "completions"
  | "embeddings"
  | "rerank"
  | "moderations"
  | "images"
  | "audio_speech"
  | "audio_transcriptions";

/**
 * Loads the app configuration for the request (when auth or the configuration
 * loader has not already), runs the inbound policy chain from that
 * configuration, and enforces limits inherited from parent teams or the
 * gateway root.
 *
 * Place this policy on AI Gateway routes after optional authentication and
 * optional `ai-gateway-configuration-loader-inbound`. When either of those
 * already populated the app-configuration channel, this policy reuses it.
 * Otherwise it loads the configuration with the route's `app_id` path
 * parameter. Applications select from policies pre-declared by the gateway.
 * Applications without a `inboundPolicyChain`, or with an empty chain, run no
 * application-selected policies. Entry options replace the declaration's
 * options as a complete object; omit them to inherit the declaration,
 * including environment-backed credentials. Each occurrence receives a private
 * deep copy of its entry options, so a policy mutating its options cannot
 * corrupt the cached app configuration.
 *
 * @title AI Gateway Configuration Executor
 * @product ai-gateway
 * @requiresAI
 */
declare class AIGatewayConfigurationExecutorInboundPolicy extends InboundPolicy<AIGatewayConfigurationExecutorInboundPolicyOptions> {
  #private;
  static readonly policyType = "ai-gateway-configuration-executor";
  constructor(
    options: AIGatewayConfigurationExecutorInboundPolicyOptions,
    policyName: string
  );
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
  private checkHierarchyLimits;
  private enforceHierarchyLimits;
  private blockOnViolation;
  private emitHierarchyWarning;
  private getConsumerSub;
  private createQuotaExceededResponse;
}
export { AIGatewayConfigurationExecutorInboundPolicy };
export { AIGatewayConfigurationExecutorInboundPolicy as AIGatewayConfigurationExecutorV2InboundPolicy };

/**
 * Options for loading each application's AI Gateway configuration and running its inbound policy chain.
 * @public
 */
declare interface AIGatewayConfigurationExecutorInboundPolicyOptions {
  /**
   * The time in seconds to cache app configurations loaded by app_id. Defaults to 10 seconds when omitted. Higher values decrease latency; lower values pick up portal changes sooner. Cached results remain valid until the cache expires even if the configuration changes in the portal. This cache is only used when neither ai-gateway-auth-inbound nor ai-gateway-configuration-loader-inbound already loaded the configuration for the request.
   */
  cacheTtlSeconds?: number;
}
export { AIGatewayConfigurationExecutorInboundPolicyOptions };
export { AIGatewayConfigurationExecutorInboundPolicyOptions as AIGatewayConfigurationExecutorV2InboundPolicyOptions };

/**
 * Loads the AI Gateway app configuration for the request into the
 * request-scoped channel and does nothing else.
 *
 * Place this policy on AI Gateway routes before
 * `ai-gateway-configuration-executor-inbound` when you want configuration
 * loading separated from chain execution. When `ai-gateway-auth-inbound`
 * already populated the channel, this policy reuses it. Otherwise it loads
 * the configuration with the route's `app_id` path parameter.
 *
 * If this policy is omitted, the configuration executor still loads
 * configuration itself before running the application chain.
 *
 * @title AI Gateway Configuration Loader
 * @product ai-gateway
 * @requiresAI
 */
declare class AIGatewayConfigurationLoaderInboundPolicy extends InboundPolicy<AIGatewayConfigurationLoaderInboundPolicyOptions> {
  #private;
  static readonly policyType = "ai-gateway-configuration-loader";
  constructor(
    options: AIGatewayConfigurationLoaderInboundPolicyOptions,
    policyName: string
  );
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
}
export { AIGatewayConfigurationLoaderInboundPolicy };
export { AIGatewayConfigurationLoaderInboundPolicy as AIGatewayConfigurationLoaderV2InboundPolicy };

/**
 * Options for loading each application's AI Gateway configuration into the request-scoped channel.
 * @public
 */
declare interface AIGatewayConfigurationLoaderInboundPolicyOptions {
  /**
   * The time in seconds to cache app configurations loaded by app_id. Defaults to 10 seconds when omitted. Higher values decrease latency; lower values pick up portal changes sooner. Cached results remain valid until the cache expires even if the configuration changes in the portal. When ai-gateway-auth-inbound already loaded the configuration for the request, this cache is not used.
   */
  cacheTtlSeconds?: number;
}
export { AIGatewayConfigurationLoaderInboundPolicyOptions };
export { AIGatewayConfigurationLoaderInboundPolicyOptions as AIGatewayConfigurationLoaderV2InboundPolicyOptions };

/**
 * Data Loss Prevention (DLP) Inbound Policy for the AI Gateway
 * @title Data Loss Prevention (DLP)
 * @product ai-gateway
 * @requiresAI
 *
 * Scans the content of AI requests and responses — system prompts, message
 * text, and tool-call arguments — for sensitive data (credit cards, national
 * identifiers, API keys and other credentials) using the in-gateway DLP
 * engine, and applies per-rule actions: mask, block, or log. Detection runs
 * entirely inside the gateway; nothing is sent to a third-party scanning
 * service. Streaming responses are scanned as they stream by default (chunk
 * by chunk with a sliding boundary window); `streaming.mode: "buffer"`
 * instead collects the whole response and scans it once as one document.
 *
 * Options are validated at request time and invalid options fail closed with
 * a ConfigurationError. Content that cannot be inspected is denied by
 * default (`onUnknownShape: "deny"`), and internal scan failures fail closed
 * by default (`onError: "block"`).
 *
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare function AIGatewayDlpInboundPolicy(
  request: ZuploRequest,
  context: ZuploContext,
  unparsedOptions: unknown,
  policyName: string
): Promise<ZuploRequest | Response>;

/**
 * The options for the Data Loss Prevention (DLP) policy. Scans the content of AI requests and responses — system prompts, messages, and tool-call arguments — for sensitive data such as credit cards, national identifiers, and API keys, applying a per-rule action (mask, block, or log). Detection runs entirely inside the gateway; streaming responses are scanned as they stream (or collected and scanned whole with `streaming.mode: "buffer"`).
 * @public
 */
export declare interface AIGatewayDlpInboundPolicyOptions {
  rules: DlpRules;
  /**
   * Your own detectors: a `name`, a regex `pattern`, and optional `context` words. A detector does nothing by itself — activate it by name inside `rules.inbound` or `rules.outbound`, exactly like a built-in type, with its own action, detection level, and mask per direction.
   */
  customRules?: DlpCustomRule[];
  /**
   * Exact strings that are never flagged by any rule — documentation samples like Stripe's public test card `4242 4242 4242 4242`, or your own support email address. Matching is case-sensitive against the exact detected text, including when a value arrives split across streaming chunks.
   */
  allowValues?: string[];
  /**
   * Default evidence level for rules that do not set their own. See the per-rule `detection` description for the level semantics. There are no numeric confidence thresholds to tune — levels are the whole dial.
   */
  detection?: "corroborated" | "standard" | "aggressive";
  /**
   * Also scan tool/function-call argument payloads — in requests, buffered responses, and streamed tool-call deltas. Tool arguments are user and model content; disabling this exempts them from every rule.
   */
  scanToolArguments?: boolean;
  streaming?: DlpStreamingSettings;
  endpoints?: ApplicableEndpoints_2;
  onUnknownShape?: OnUnknownShape_2;
  onError?: OnEngineError;
  /**
   * The detection engine. Only `builtin` (in-gateway regex + checksum detection with context-word scoring; no data egress) is available today. Declaring the discriminator now keeps future engines an additive, non-breaking change.
   */
  engine?: "builtin";
}

/**
 * Adds failure and quota fallbacks to an existing AI Gateway model selection.
 *
 * Place this policy after AI Gateway Model Filtering. It never creates a
 * model selection, so a misplaced policy cannot bypass filtering.
 *
 * @title AI Gateway Fallback Model
 * @product ai-gateway
 * @requiresAI
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns The unchanged request after enriching an existing model selection
 * @example
 * ```json
 * {
 *   "models": {
 *     "completions": {
 *       "fallback": "anthropic/claude-haiku-4-5",
 *       "quotaFallback": "openai/gpt-4o-mini"
 *     }
 *   },
 *   "fallbackTimeoutSeconds": 60
 * }
 * ```
 */
declare class AIGatewayFallbackModelInboundPolicy extends InboundPolicy<AIGatewayFallbackModelInboundPolicyOptions> {
  #private;
  static readonly policyType = "ai-gateway-fallback-model";
  constructor(
    options: AIGatewayFallbackModelInboundPolicyOptions,
    policyName: string
  );
  handler(request: ZuploRequest, context: ZuploContext): Promise<ZuploRequest>;
}
export { AIGatewayFallbackModelInboundPolicy };
export { AIGatewayFallbackModelInboundPolicy as AIGatewayFallbackModelV2InboundPolicy };

/**
 * Options for adding failure and quota fallbacks to an existing AI Gateway model selection.
 * @public
 */
declare interface AIGatewayFallbackModelInboundPolicyOptions {
  models: FallbackModels;
  fallbackTimeoutSeconds?: FallbackTimeoutSeconds;
}
export { AIGatewayFallbackModelInboundPolicyOptions };
export { AIGatewayFallbackModelInboundPolicyOptions as AIGatewayFallbackModelV2InboundPolicyOptions };

/**
 * Galileo Tracing Inbound Policy
 * @title Galileo Tracing
 * @product ai-gateway
 * @requiresAI
 *
 * Traces both streaming and non-streaming AI Gateway responses to Galileo's LLM
 * observability platform, creating complete traces with workflow and LLM spans
 * when responses complete. Credentials (apiKey, projectId, logStreamId, baseUrl)
 * come from the policy options. The authenticated app configuration is used
 * only to label the model; presence in the route's chain is what enables the
 * policy.
 *
 * For streaming responses, it clones the response stream and processes it in
 * the background using `waitUntil`, allowing the original stream to pass through
 * unmodified while still capturing the complete content for tracing.
 *
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
declare function AIGatewayGalileoTracingInboundPolicy(
  request: ZuploRequest,
  context: ZuploContext,
  options: AIGatewayGalileoTracingInboundPolicyOptions,
  _policyName: string
): Promise<ZuploRequest | Response>;
export { AIGatewayGalileoTracingInboundPolicy };
export { AIGatewayGalileoTracingInboundPolicy as GalileoTracingV2InboundPolicy };

/**
 * Track AI Gateway requests and responses using Galileo's LLM observability platform.
 * @public
 */
declare interface AIGatewayGalileoTracingInboundPolicyOptions {
  /**
   * The Galileo API key for authentication.
   */
  apiKey: string;
  /**
   * The Galileo project ID (UUID) for organizing traces.
   */
  projectId: string;
  /**
   * The Galileo log stream ID (UUID) for organizing traces.
   */
  logStreamId: string;
  /**
   * The base URL for the Galileo API (optional, defaults to https://api.galileo.ai).
   */
  baseUrl?: string;
  endpoints?: ApplicableEndpoints_3;
  onUnknownShape?: OnUnknownShape_3;
}
export { AIGatewayGalileoTracingInboundPolicyOptions };
export { AIGatewayGalileoTracingInboundPolicyOptions as GalileoTracingV2PolicyOptions };

/**
 * Handler that routes AI/LLM requests through Zuplo's LLM Translation Layer.
 * This handler forwards requests to the translation layer that handles provider-specific
 * API transformations, parameter validation, and response normalization to provide
 * a unified OpenAI-compatible interface across multiple LLM providers.
 *
 * @param request - The incoming ZuploRequest containing AI/LLM API call
 * @param context - The ZuploContext containing route configuration
 * @returns A Response from the AI provider via the translation layer
 *
 * @public
 * @example
 * ```json
 * {
 *   "handler": {
 *     "export": "aiGatewayHandler",
 *     "module": "$import(@zuplo/runtime)"
 *   }
 * }
 * ```
 */
export declare function aiGatewayHandler(
  request: ZuploRequest,
  context: ZuploContext
): Promise<Response>;

/**
 * Routes AI requests using a model selection stored in request context by a
 * filtering or custom-routing policy. When no policy selected routing, the
 * handler uses the request's `providerName/model` as the route target. Requests
 * without preselected routing must include a qualified model.
 *
 * @beta
 * @param request - The incoming AI Gateway request.
 * @param context - The ZuploContext containing the model selection.
 * @returns A response from the selected AI provider.
 *
 * @public
 * @example
 * ```json
 * {
 *   "handler": {
 *     "export": "aiGatewayHandlerV2",
 *     "module": "$import(@zuplo/runtime)"
 *   }
 * }
 * ```
 */
export declare function aiGatewayHandlerV2(
  request: ZuploRequest,
  context: ZuploContext
): Promise<Response>;

/**
 * @deprecated Use InternalOnlyInboundPolicy instead. This name is from before
 * the policy moved out of the AI Gateway.
 * @public
 */
export declare const AIGatewayInternalOnlyInboundPolicy: typeof InternalOnlyInboundPolicy;

/**
 * @deprecated Use InternalOnlyInboundPolicyOptions instead. This name is from
 * before the policy moved out of the AI Gateway.
 * @public
 */
export declare type AIGatewayInternalOnlyInboundPolicyOptions =
  InternalOnlyInboundPolicyOptions;

/**
 * Spreads AI requests across a list of models. The policy cycles through the
 * list, or keeps requests that share a key, such as a user or a conversation,
 * on the same model. Most requests also get a retry model from the list. A
 * request moves there when the chosen model stays rate limited. Chat
 * completions and embeddings requests also move there when the model returns a
 * server error, can't be reached, or times out.
 *
 * The policy picks the model for every request it handles and ignores the
 * request's own `model`, so the list also limits which models clients can
 * reach. An earlier policy's model selection is never overwritten.
 *
 * @title Model Load Balancing
 * @product ai-gateway
 * @requiresAI
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns The request with model routing stored in context, or a refusal
 * @example
 * ```json
 * {
 *   "strategy": "round-robin",
 *   "models": {
 *     "completions": [
 *       "azure-eastus/gpt-5",
 *       "azure-westus/gpt-5",
 *       "openai/gpt-5"
 *     ]
 *   }
 * }
 * ```
 */
export declare class AIGatewayLoadBalancingInboundPolicy extends InboundPolicy<AIGatewayLoadBalancingInboundPolicyOptions> {
  #private;
  static readonly policyType = "ai-gateway-load-balancing";
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
}

/**
 * Options for spreading AI Gateway requests across a list of models.
 * @public
 */
export declare interface AIGatewayLoadBalancingInboundPolicyOptions {
  strategy?: Strategy;
  stickyBy?: StickyBy;
  expression?: Expression;
  models: Models;
  fallbackTimeoutSeconds?: FallbackTimeoutSeconds_2;
}

/* Excluded from this release type: AIGatewayMeterIncrements */

/**
 * Meters AI Gateway usage for the application.
 *
 * The authentication policy must run before this policy so the app
 * configuration id is available for meter storage and analytics. Budgets are
 * declared with `budgetRules` and enforced by the configuration executor.
 *
 * @title AI Gateway Metering
 * @product ai-gateway
 * @requiresAI
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns The request
 */
declare class AIGatewayMeteringInboundPolicy extends InboundPolicy<AIGatewayMeteringInboundPolicyOptions> {
  #private;
  static readonly policyType = "ai-gateway-metering";
  constructor(
    options: AIGatewayMeteringInboundPolicyOptions,
    policyName: string
  );
  /** Set the meter increments accumulated for this request. */
  static setIncrements(
    context: ZuploContext,
    increments: AIGatewayMeterIncrements
  ): void;
  /** Read the meter increments accumulated for this request. */
  static getIncrements(context: ZuploContext): AIGatewayMeterIncrements;
  /** Set the quota-fallback marker for this request. */
  static setQuotaFallback(
    context: ZuploContext,
    quotaFallback: QuotaFallbackModels
  ): void;
  /** Read the quota-fallback marker for this request. */
  static getQuotaFallback(
    context: ZuploContext
  ): QuotaFallbackModels | undefined;
  /** Increment meters directly, for example after a streaming response. */
  static incrementMeters(
    configurationId: string,
    increments: AIGatewayMeterIncrements,
    context: ZuploContext
  ): Promise<void>;
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
  private resolveConfiguration;
}
export { AIGatewayMeteringInboundPolicy };
export { AIGatewayMeteringInboundPolicy as AIGatewayMeteringV2InboundPolicy };

/**
 * Options for metering AI Gateway usage and declaring budget rules.
 * @public
 */
declare interface AIGatewayMeteringInboundPolicyOptions {
  /**
   * Fail the request instead of logging the error when recording usage with the metering service fails.
   */
  throwOnFailure?: boolean;
  /**
   * Budget rules for this application. Each rule budgets the whole app ("app") or each distinct value of an expression ("expression"), with warn and block thresholds per meter and period.
   *
   * @maxItems 5
   */
  budgetRules?:
    | []
    | [MeteringBudgetRule]
    | [MeteringBudgetRule, MeteringBudgetRule]
    | [MeteringBudgetRule, MeteringBudgetRule, MeteringBudgetRule]
    | [
        MeteringBudgetRule,
        MeteringBudgetRule,
        MeteringBudgetRule,
        MeteringBudgetRule,
      ]
    | [
        MeteringBudgetRule,
        MeteringBudgetRule,
        MeteringBudgetRule,
        MeteringBudgetRule,
        MeteringBudgetRule,
      ];
  /**
   * @deprecated
   * Deprecated and not enforced. Declare budgets with budgetRules.
   */
  limits?: {
    costs?: QuotaLimit;
    tokens?: QuotaLimit;
    requests?: QuotaLimit;
  };
}
export { AIGatewayMeteringInboundPolicyOptions };
export { AIGatewayMeteringInboundPolicyOptions as AIGatewayMeteringV2InboundPolicyOptions };

/**
 * Shape of the deprecated `options.limits` policy option. It is not enforced;
 * declare budgets with `budgetRules`.
 *
 * @deprecated Use `budgetRules`.
 */
declare interface AIGatewayMeteringLimitOverrides {
  costs?: AIGatewayMeteringMeterLimitOverrides;
  tokens?: AIGatewayMeteringMeterLimitOverrides;
  requests?: AIGatewayMeteringMeterLimitOverrides;
}
export { AIGatewayMeteringLimitOverrides };
export { AIGatewayMeteringLimitOverrides as AIGatewayMeteringV2LimitOverrides };

/** Daily and monthly settings for one usage meter. */
declare interface AIGatewayMeteringMeterLimitOverrides {
  daily?: AIGatewayMeteringPeriodLimitOverride;
  monthly?: AIGatewayMeteringPeriodLimitOverride;
}

/** Settings for one usage-limit period. */
declare interface AIGatewayMeteringPeriodLimitOverride {
  enabled?: boolean;
  limit?: number;
  warning?: AIGatewayMeteringWarningLimitOverride;
}

/** Warning settings for one usage-limit period. */
declare interface AIGatewayMeteringWarningLimitOverride {
  enabled?: boolean;
  threshold?: number;
}

/**
 * Matches AI Gateway requests against curated allow lists or open block lists,
 * then stores the winning model reference for the route handler.
 *
 * @title AI Gateway Model Filtering
 * @product ai-gateway
 * @requiresAI
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns The request with model routing stored in context, or a 4xx response
 * @example
 * ```json
 * {
 *   "models": {
 *     "completions": {
 *       "allowList": [
 *         "openai/gpt-5",
 *         "anthropic/claude-sonnet-4-6"
 *       ]
 *     }
 *   }
 * }
 * ```
 */
declare class AIGatewayModelFilteringInboundPolicy extends InboundPolicy<AIGatewayModelFilteringInboundPolicyOptions> {
  #private;
  static readonly policyType = "ai-gateway-model-filtering";
  constructor(
    options: AIGatewayModelFilteringInboundPolicyOptions,
    policyName: string
  );
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
}
export { AIGatewayModelFilteringInboundPolicy };
export { AIGatewayModelFilteringInboundPolicy as AIGatewayModelFilteringV2InboundPolicy };

/**
 * Options for allowing or blocking providerName/model references for each AI Gateway capability.
 * @public
 */
declare interface AIGatewayModelFilteringInboundPolicyOptions {
  models: Models_2;
}
export { AIGatewayModelFilteringInboundPolicyOptions };
export { AIGatewayModelFilteringInboundPolicyOptions as AIGatewayModelFilteringV2InboundPolicyOptions };

/**
 * Catalog information about an AI Gateway model.
 *
 * @public
 * @example
 * ```typescript
 * const model: AIGatewayModelInfo = {
 *   model: "gpt-5",
 *   capability: "completions",
 *   status: "active",
 *   tokenRateCard: {
 *     revision: "aimod_123:2026-10-12T17:42:10.031877Z",
 *     currency: "USD",
 *     rates: [
 *       { category: "input", costPerToken: 0.00000125 },
 *       { category: "cache-read-input", costPerToken: 0.000000125 },
 *       { category: "output", costPerToken: 0.00001 },
 *     ],
 *   },
 * };
 * ```
 */
export declare interface AIGatewayModelInfo {
  /** The provider-specific model identifier. */
  model: string;
  /** The AI Gateway capability supported by the model. */
  capability: "completions" | "embeddings";
  /** Whether the model is available for new routing or has been deprecated. */
  status: "active" | "deprecated";
  /**
   * The prices the AI Gateway charges for this model. Absent when the catalog
   * has no valid prices for it; its requests are then recorded as unpriced.
   */
  tokenRateCard?: AIGatewayTokenRateCard;
}

/**
 * Forces one model for every request, or supplies a default model when a
 * request omits one, then stores that selection for the AI Gateway handler.
 *
 * An earlier policy's model selection is never overwritten, so a custom
 * routing policy placed before this one stays authoritative.
 *
 * @title AI Gateway Model Override
 * @beta
 * @product ai-gateway
 * @requiresAI
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns The request with model routing stored in context
 * @example
 * ```json
 * {
 *   "models": {
 *     "completions": {
 *       "force": "openai/gpt-5"
 *     },
 *     "embeddings": {
 *       "default": "openai/text-embedding-3-small"
 *     }
 *   }
 * }
 * ```
 */
export declare class AIGatewayModelOverrideInboundPolicy extends InboundPolicy<AIGatewayModelOverrideInboundPolicyOptions> {
  #private;
  static readonly policyType = "ai-gateway-model-override";
  constructor(
    options: AIGatewayModelOverrideInboundPolicyOptions,
    policyName: string
  );
  handler(request: ZuploRequest, context: ZuploContext): Promise<ZuploRequest>;
}

/**
 * Options for forcing one model or supplying a default model for each AI Gateway capability.
 * @public
 */
export declare interface AIGatewayModelOverrideInboundPolicyOptions {
  models: Models_3;
}

/**
 * Sets and reads the model routing selected for an AI Gateway request.
 *
 * The built-in model-routing policy matches the request against its allowList
 * of {@link AIGatewayRouteTarget} items, then `set()`s the winning target.
 * Custom policies can call `set()` directly instead. If neither kind of policy
 * selects routing, `aiGatewayHandlerV2` calls `set()` with the request's
 * `providerName/model`. Provider API keys are resolved internally and are never
 * returned by `get()`.
 *
 * @public
 * @example
 * ```typescript
 * import { AIGatewayModelRouting } from "@zuplo/runtime";
 *
 * await AIGatewayModelRouting.set(context, {
 *   completions: {
 *     main: "openai/gpt-5",
 *     backup: "anthropic/claude-sonnet-4-6",
 *   },
 * });
 * const routing = AIGatewayModelRouting.get(context);
 * ```
 */
export declare const AIGatewayModelRouting: {
  set(context: ZuploContext, routing: AIGatewayRouting): Promise<void>;
  get(context: ZuploContext): AIGatewayRouting | undefined;
};

/**
 * Accesses the live AI Gateway provider and model catalog.
 *
 * Results use the existing 60-second catalog cache. Credentials and the names
 * of their environment-variable bindings are never returned.
 *
 * @public
 * @example
 * ```typescript
 * import { AIGatewayModels } from "@zuplo/runtime";
 *
 * const providers = await AIGatewayModels.load(context);
 * ```
 */
export declare const AIGatewayModels: {
  load(context: ZuploContext): Promise<AIGatewayProviderInfo[]>;
};

/**
 * Comet Opik Tracing Inbound Policy
 * @title Comet Opik Tracing
 * @product ai-gateway
 * @requiresAI
 *
 * Traces both streaming and non-streaming AI Gateway responses to Comet Opik,
 * creating traces when requests start and spans when responses complete.
 * Credentials (apiKey, projectName, workspace, baseUrl) come from the policy
 * options. The authenticated app configuration is used only to label the
 * model; presence in the route's chain is what enables the policy.
 *
 * For streaming responses, it clones the response stream and processes it in
 * the background using `waitUntil`, allowing the original stream to pass through
 * unmodified while still capturing the complete content for tracing.
 *
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
declare function AIGatewayOpikTracingInboundPolicy(
  request: ZuploRequest,
  context: ZuploContext,
  options: AIGatewayOpikTracingInboundPolicyOptions,
  _policyName: string
): Promise<ZuploRequest | Response>;
export { AIGatewayOpikTracingInboundPolicy };
export { AIGatewayOpikTracingInboundPolicy as CometOpikTracingV2InboundPolicy };

/**
 * Track AI Gateway requests and responses using Comet Opik's LLM observability platform.
 * @public
 */
declare interface AIGatewayOpikTracingInboundPolicyOptions {
  /**
   * The Comet Opik API key for authentication.
   */
  apiKey: string;
  /**
   * The Comet Opik project name for organizing traces.
   */
  projectName: string;
  /**
   * The Comet Opik workspace name.
   */
  workspace: string;
  /**
   * The base URL for the Comet Opik API (optional, defaults to https://www.comet.com/opik/api).
   */
  baseUrl?: string;
  endpoints?: ApplicableEndpoints_4;
  onUnknownShape?: OnUnknownShape_4;
}
export { AIGatewayOpikTracingInboundPolicyOptions };
export { AIGatewayOpikTracingInboundPolicyOptions as CometOpikTracingV2PolicyOptions };

/**
 * Prompt Injection Protection Policy
 * @title Prompt Injection Protection
 * @product ai-gateway
 * @requiresAI
 *
 * Uses a small tool-calling LLM to detect prompt injection attempts in AI
 * Gateway requests and blocks them before they reach the upstream model. The
 * classifier runs on any OpenAI-compatible API and is forced (via
 * `tool_choice`) to answer through a single SAFE/UNSAFE function call, so one
 * bounded, non-streaming completion at temperature 0 yields a deterministic
 * verdict. Requests whose inspected messages carry no text skip the classifier
 * entirely.
 *
 * This policy inspects the request only, so it adds no time-to-first-token
 * cost on responses and works with streaming untouched.
 *
 * By default only the newest message of the conversation is inspected
 * (`recentMessageCount: 1`): earlier turns were screened when they were the
 * newest, so a chat session pays for one classification per turn rather than
 * for its whole transcript on every turn. System and developer messages,
 * Anthropic's top-level `system` and the Responses `instructions` field are
 * never inspected — they are the application's own instructions, not where an
 * injection arrives — while tool results are, because retrieved documents and
 * tool output are the main indirect-injection vector. `classifierPrompt`
 * replaces the built-in system prompt; the inspected text always travels as a
 * separate user message and the verdict always comes back through the fixed
 * SAFE/UNSAFE tool call, so a custom prompt changes what is flagged, never how
 * the verdict is read.
 *
 * With `appId`, the classifier runs on another AI Gateway app instead of an
 * external API. The gateway invokes that app in-process through
 * `context.invokeRoute`, so there is no outbound HTTP hop and the
 * classification inherits that app's provider credentials, model routing,
 * fallbacks and quotas. The target app must not run this policy itself: being
 * asked to classify a classification request is rejected as a configuration
 * error rather than silently skipped, so a guardrail never looks configured
 * while inspecting nothing.
 *
 * With `execution: "parallel"`, the classifier is registered as a pre-request
 * handler and runs concurrently with the remaining inbound policies instead of
 * blocking the chain. The runtime enforces the verdict before the request is
 * dispatched upstream, so a prompt is never forwarded unchecked; what changes
 * is that a safe prompt no longer pays for the classifier serially. A verdict
 * that stops mattering (another response is already being served) aborts the
 * in-flight classifier call and is neither logged as a failure nor counted.
 * Omitting `execution` means `"sequential"`, while the generated example sets
 * `"parallel"` — an existing configuration never changes behaviour under it.
 *
 * Options are validated at request time and invalid options fail closed with a
 * ConfigurationError.
 * Classifier-call failures (invalid credentials, rate limits, timeouts,
 * outages) also fail closed by default, returning a 502 in the route's native
 * error format; set `onError: "allow"` to fail open and prioritize
 * availability over inspection.
 *
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare function AIGatewayPromptInjectionPolicy(
  request: ZuploRequest,
  context: ZuploContext,
  unparsedOptions: unknown,
  policyName: string
): Promise<ZuploRequest | Response>;

/**
 * The options for the Prompt Injection Protection policy.
 * @public
 */
export declare interface AIGatewayPromptInjectionPolicyOptions {
  apiKey?: APIKey_2;
  appId?: ClassifierAppID;
  execution?: Execution;
  recentMessageCount?: RecentMessageCount;
  model?: ClassifierModel;
  classifierPrompt?: ClassifierPrompt;
  baseUrl?: BaseURL;
  timeoutMs?: ClassifierTimeoutMs;
  endpoints?: ApplicableEndpoints_5;
  onUnknownShape?: OnUnknownShape_5;
  onError?: OnClassifierError;
}

/**
 * Public metadata for an AI Gateway provider name and its models.
 *
 * Credentials and environment-variable names are never exposed.
 *
 * @public
 * @example
 * ```typescript
 * const providers = await AIGatewayModels.load(context);
 * const activeOpenAIModels = providers
 *   .find((provider) => provider.providerName === "openai")
 *   ?.models.filter((model) => model.status === "active");
 * ```
 */
export declare interface AIGatewayProviderInfo {
  /** The provider name used in `providerName/model` request references. */
  providerName: string;
  /** The provider's request base URL, when supplied by the catalog. */
  baseUrl?: string;
  /** Whether this provider was defined by the customer. */
  isCustom?: boolean;
  /** The built-in provider type implemented by an assignment, when present. */
  providerType?: string;
  /** Models currently listed for this provider in the live catalog. */
  models: AIGatewayModelInfo[];
}

/**
 * A single AI Gateway routing target.
 *
 * Model references use `providerName/model`; the string form is shorthand
 * for `{ main: "openai/gpt-5" }`. The built-in model-routing policy uses this
 * same type for each allow-list item: it matches the request against its
 * allowList and `set()`s the winning target.
 *
 * @public
 * @example
 * ```typescript
 * const target: AIGatewayRouteTarget = {
 *   main: "openai/gpt-5",
 *   backup: "anthropic/claude-sonnet-4-6",
 *   fallbackTimeoutSeconds: 30,
 *   quotaFallback: "openai/gpt-5-mini",
 * };
 * ```
 */
export declare type AIGatewayRouteTarget =
  | string
  | {
      main: string;
      backup?: string;
      fallbackTimeoutSeconds?: number;
      quotaFallback?: string;
    };

/**
 * The model routing selected for the current AI Gateway request.
 *
 * Each capability accepts the same {@link AIGatewayRouteTarget} used by an
 * allow-list item in the built-in policy. The policy matches its allowList and
 * `set()`s the one winning target for the request.
 *
 * @public
 * @example
 * ```typescript
 * const routing: AIGatewayRouting = {
 *   completions: "openai/gpt-5",
 *   embeddings: { main: "openai/text-embedding-3-small" },
 * };
 * ```
 */
export declare interface AIGatewayRouting {
  /** Routing for chat completions, Responses, and Anthropic Messages. */
  completions?: AIGatewayRouteTarget;
  /** Routing for embedding requests. */
  embeddings?: AIGatewayRouteTarget;
}

/**
 * AI Gateway Semantic Cache policy. This inbound policy looks up the semantic
 * cache on entry and, on a miss, registers a response-sending hook to write the
 * upstream response back into the cache.
 *
 * Caching parameters (semanticTolerance, expirationSecondsTtl, namespace,
 * recentMessageCount) come from the policy options, and presence in the
 * route's chain is what enables it. An id from the authenticated app
 * configuration always provides the cache namespace so application-supplied
 * options cannot cross tenant partitions. The cache key covers the system
 * prompt plus the last `recentMessageCount` messages (default 1) — applied
 * when storing and when matching — so multi-turn conversations can hit
 * entries cached from earlier, shorter ones.
 *
 * Cache outcomes are reported on the response via the RFC 9211 `Cache-Status`
 * header under the cache name `zp-aigw-sem-cache` (hit:
 * `zp-aigw-sem-cache; hit; detail="similarity=0.93"`; miss:
 * `zp-aigw-sem-cache; fwd=miss; stored`). Responses also include the
 * `x-ai-gateway-cache: HIT|MISS` and `x-ai-gateway-cache-similarity` headers.
 *
 * @title AI Gateway Semantic Cache
 * @product ai-gateway
 * @enterprise
 * @requiresAI
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
declare function AIGatewaySemanticCacheInboundPolicy(
  request: ZuploRequest,
  context: ZuploContext,
  options: AIGatewaySemanticCacheInboundPolicyOptions,
  policyName: string
): Promise<Response | ZuploRequest<RequestGeneric>>;
export { AIGatewaySemanticCacheInboundPolicy };
export { AIGatewaySemanticCacheInboundPolicy as AIGatewaySemanticCacheV2InboundPolicy };

/**
 * Options for the AI Gateway Semantic Cache policy. Configured inline in policies.json; the policy reads nothing from the AI Gateway configuration to decide whether to cache.
 * @public
 */
declare interface AIGatewaySemanticCacheInboundPolicyOptions {
  semanticTolerance?: SemanticTolerance;
  expirationSecondsTtl?: CacheTTLSeconds;
  namespace?: CacheNamespace;
  recentMessageCount?: RecentMessageCount_2;
  maxConversationLength?: MaxConversationLength;
  endpoints?: ApplicableEndpoints_6;
  onUnknownShape?: OnUnknownShape_6;
}
export { AIGatewaySemanticCacheInboundPolicyOptions };
export { AIGatewaySemanticCacheInboundPolicyOptions as AIGatewaySemanticCacheV2InboundPolicyOptions };

/**
 * Reads and writes the Smart Router result for an AI Gateway request.
 *
 * The built-in Smart Router policy `set()`s this after a successful
 * classification. Custom policies can `get()` it later in the same request,
 * or `set()` a compatible result of their own.
 *
 * @public
 * @example
 * ```typescript
 * import { AIGatewaySmartRouter } from "@zuplo/runtime";
 *
 * const result = AIGatewaySmartRouter.get(context);
 * if (result?.profile.intent === "code") {
 *   // ...
 * }
 * ```
 */
export declare const AIGatewaySmartRouter: {
  set(context: ZuploContext, result: AIGatewaySmartRouterResult): void;
  get(context: ZuploContext): AIGatewaySmartRouterResult | undefined;
};

/**
 * Prompt-complexity label produced by Smart Router.
 *
 * @public
 */
export declare type AIGatewaySmartRouterComplexity = "low" | "medium" | "high";

/**
 * Smart Router Inbound Policy for the AI Gateway
 * @title Smart Router
 * @product ai-gateway
 * @requiresAI
 *
 * Classifies the last user prompt with the classifier set in `classifier` —
 * another AI Gateway app, an OpenAI-compatible Chat Completions API, or Jev
 * from TypeSafe — stores the result on `AIGatewaySmartRouter`, and optionally
 * overwrites completions routing from `modelsByComplexity`. Classification
 * failures, timeouts, and incomplete options fail open: the original request
 * is forwarded.
 *
 * Some misconfigurations are rejected with a `ConfigurationError` — thrown,
 * not logged and failed open like every other classifier failure — because
 * failing open on them would look like smart routing that is simply doing
 * nothing: more than one classifier, a deprecated `classifierAppID`-style
 * option beside `classifier`, or `classifierPrompt` with Jev; a
 * `classifier.app.appId` that is this app's own id; and a classifier app that
 * runs this policy itself.
 *
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare function AIGatewaySmartRouterInboundPolicy(
  request: ZuploRequest,
  context: ZuploContext,
  unparsedOptions: unknown,
  policyName: string
): Promise<ZuploRequest | Response>;

/**
 * Options for the Smart Router policy: classify the last user prompt with an AI Gateway app, a Chat Completions API, or Jev, then optionally route by complexity.
 * @public
 */
export declare interface AIGatewaySmartRouterInboundPolicyOptions {
  classifier?: Classifier;
  modelsByComplexity: ModelsByComplexity;
  smartRoutingEnabled?: SmartRoutingEnabled;
  intents?: Intents;
  classifierPrompt?: ClassifierPrompt_2;
  minConfidenceForRouting?: MinimumConfidenceForRouting;
  classifierTimeoutMs?: ClassifierTimeoutMs_2;
  maxPromptChars?: MaxPromptCharacters;
  classifierAppID?: ClassifierAppIDDeprecated;
  classifierModel?: ClassifierModelDeprecated;
  classifierAppApiKey?: ClassifierAppAPIKeyDeprecated;
}

/**
 * Structured classification of the last user prompt.
 *
 * With the Jev classifier, `confidence` is the lower of Jev's confidence in
 * the intent and in the complexity, and `reasons` is empty: Jev answers typed
 * questions and writes no reasons.
 *
 * @public
 */
export declare interface AIGatewaySmartRouterProfile {
  intent: string;
  complexity: AIGatewaySmartRouterComplexity;
  confidence: number;
  reasons: string[];
}

/**
 * Where the classified text was taken from on the request.
 *
 * @public
 */
export declare type AIGatewaySmartRouterPromptSource = "user" | "prior-user";

/**
 * Why Smart Router did or did not change the request's model.
 *
 * @public
 */
export declare type AIGatewaySmartRouterReason =
  | "applied"
  | "disabled"
  | "low-confidence"
  | "no-model"
  | "internal-error"
  | "unknown-intent";

/**
 * Result produced by the Smart Router policy for the current request.
 * Custom inbound policies can read this after Smart Router runs.
 *
 * @public
 */
export declare interface AIGatewaySmartRouterResult {
  profile: AIGatewaySmartRouterProfile;
  usage: AIGatewaySmartRouterTokenUsage;
  classifierModel: string;
  routing: AIGatewaySmartRouterRoutingDecision;
  durationMs: number;
  promptSource: AIGatewaySmartRouterPromptSource;
  promptLength: number;
  promptTruncated: boolean;
  unknownIntent: boolean;
  smartRouting: {
    enabled: boolean;
    applied: boolean;
    reason: AIGatewaySmartRouterReason;
    minConfidence: number;
  };
}

/**
 * Model chosen from `modelsByComplexity` for the classified complexity, if any.
 *
 * @public
 */
export declare interface AIGatewaySmartRouterRoutingDecision {
  model?: string;
}

/**
 * Classifier token usage reported in the classifier response body. For Jev,
 * input and output tokens map directly to these fields.
 *
 * @public
 */
export declare interface AIGatewaySmartRouterTokenUsage {
  inputTokens: number;
  outputTokens: number;
  totalTokens: number;
}

/**
 * One USD-per-token rate in an {@link AIGatewayTokenRateCard}.
 *
 * A rate applies to a request whose total input token count is within
 * `minInputTokens` and `maxInputTokens`, inclusive; an absent bound is open.
 *
 * @public
 * @example
 * ```typescript
 * const longContextInput: AIGatewayTokenRate = {
 *   category: "input",
 *   costPerToken: 0.000006,
 *   minInputTokens: 200001,
 * };
 * ```
 */
export declare interface AIGatewayTokenRate {
  /** The token category this rate prices. */
  category: AIGatewayTokenRateCategory;
  /** The price in USD for one token. */
  costPerToken: number;
  /** The cache lifetime a `cache-write-input` rate applies to. */
  cacheTtl?: "5m" | "1h";
  /** The smallest total input token count this rate applies to. */
  minInputTokens?: number;
  /** The largest total input token count this rate applies to. */
  maxInputTokens?: number;
}

/**
 * The prices the AI Gateway charges for a model: the catalog's list prices
 * with your project's prices applied.
 *
 * @public
 * @example
 * ```typescript
 * const card: AIGatewayTokenRateCard = {
 *   revision: "aimod_123:2026-10-12T17:42:10.031877Z",
 *   currency: "USD",
 *   rates: [
 *     { category: "input", costPerToken: 0.00000125 },
 *     { category: "output", costPerToken: 0.00001 },
 *   ],
 * };
 * ```
 */
export declare interface AIGatewayTokenRateCard {
  /** Identifies the prices this card was built from. */
  revision: string;
  /** The currency of every rate. */
  currency: "USD";
  /** The rates, one per category, cache lifetime and input-size tier. */
  rates: AIGatewayTokenRate[];
}

/**
 * The token category a rate in an {@link AIGatewayTokenRateCard} prices.
 *
 * @public
 * @example
 * ```typescript
 * const category: AIGatewayTokenRateCategory = "cache-read-input";
 * ```
 */
export declare type AIGatewayTokenRateCategory =
  | "input"
  | "cache-read-input"
  | "cache-write-input"
  | "output";

/**
 * Common options every AI Gateway policy understands for scoping itself across
 * the multi-endpoint surface. A policy reads these from its own `options`.
 * @public
 */
export declare interface AiPolicyScopeOptions {
  /**
   * The endpoint shapes this policy applies to. When set, the policy is inert on
   * any other shape. Omit to apply to all shapes.
   */
  endpoints?: AiFormat[];
  /**
   * What to do when the policy meets a shape it cannot read. `skip` (the default
   * for observers) passes through; guardrails MUST use `deny` so uninspectable
   * content is never served.
   */
  onUnknownShape?: "deny" | "skip";
}

/**
 * The request body for an AI Gateway endpoint, discriminated by {@link AiFormat}.
 * A policy reads `getFormat(request)` and then narrows to the matching member —
 * no field is normalized away, so tool calls, content blocks, images, and
 * thinking are all preserved.
 * @public
 */
export declare type AiRequestBody =
  | {
      format: "openai-chat";
      body: ChatCompletionRequest;
    }
  | {
      format: "openai-responses";
      body: ResponsesRequest;
    }
  | {
      format: "anthropic-messages";
      /**
       * `/v1/messages` bodies carry a required `max_tokens`;
       * `/v1/messages/count_tokens` bodies never do, and both classify as
       * `anthropic-messages` because they are the same schema dialect. The union
       * keeps a policy from reading `max_tokens` as if it were always present —
       * narrow on it (or on `getFormat`'s endpoint) before relying on it.
       */
      body: AnthropicMessagesRequest | AnthropicCountTokensRequest;
    };

/**
 * The response body for an AI Gateway endpoint, discriminated by {@link AiFormat}.
 * For the Anthropic Messages pass-through the native response is returned as an
 * opaque record (the runtime has no dedicated Anthropic response interface).
 * @public
 */
export declare type AiResponseBody =
  | {
      format: "openai-chat";
      body: ChatCompletionResponse;
    }
  | {
      format: "openai-responses";
      body: ResponsesResponse;
    }
  | {
      format: "anthropic-messages";
      body: Record<string, unknown>;
    };

/**
 * A decoded streaming event, normalized just enough for an observer or guardrail
 * to act without re-implementing per-dialect SSE parsing. `textDelta` is the
 * incremental text in this event (if any); `usage` appears on the terminal
 * event(s); `done` marks the end of the stream.
 * @public
 */
export declare interface AiStreamEvent {
  /** The raw SSE `data:` payload, parsed from JSON when possible. */
  raw: unknown;
  /** Incremental assistant text carried by this event, if any. */
  textDelta?: string;
  /** Usage totals, present on the terminal event(s) for the shape. */
  usage?: AiUsage;
  /** True for the stream-terminating event (`[DONE]` or shape equivalent). */
  done?: boolean;
}

/**
 * A normalized usage record. Consolidates the per-shape token field names
 * (`prompt_tokens`/`completion_tokens` for chat, `input_tokens`/`output_tokens`
 * for responses and Anthropic) into one set.
 * @public
 */
export declare interface AiUsage {
  promptTokens: number;
  completionTokens: number;
  totalTokens: number;
}

/**
 * Entry format for Akamai API Security logger
 * @public
 */
export declare interface AkamaiApiSecurityLoggerEntry {
  ip: {
    v: string;
    src: string;
    dst: string;
  };
  tcp: {
    src: number;
    dst: number;
  };
  http: {
    v?: string;
    request: {
      ts: number;
      method: string;
      url: string;
      headers: Record<string, string>;
      body: string;
    };
    response: {
      ts: number;
      status: number;
      headers: Record<string, string>;
      body: string;
    };
  };
  metadata?: Record<string, string>;
  source: {
    type: number;
    index: number;
    key: string;
    version: string;
    resource: {
      type: string;
      properties: {
        account: string;
        project: string;
        environment: string;
        route: string;
      };
    };
  };
}

/**
 * Plugin for integrating with Akamai API Security service for request logging and protection
 * @public
 */
export declare class AkamaiApiSecurityPlugin extends SystemRuntimePlugin {
  #private;
  constructor(options: AkamaiApiSecurityPluginOptions);
  initialize(runtime: RuntimeExtensions): Promise<void>;
}

/**
 * Configuration options for the Akamai API Security plugin
 * @public
 */
export declare interface AkamaiApiSecurityPluginOptions {
  /**
   * The hostname of the Akamai API Security service
   */
  hostname: string;
  /**
   * The source index identifier for the Akamai API Security service
   */
  index: number;
  /**
   * The configuration key for authenticating with the Akamai API Security service
   */
  key: string;
  /**
   * When true, enables request blocking based on protection rules
   */
  enableProtection?: boolean;
  /**
   * When true, enables additional debug logging output (use in production with caution)
   */
  debug?: boolean;
  /**
   * Maximum number of entries to queue before sending to the API
   */
  maxQueueSize?: number;
  /**
   * Optional function that determines if a request should be logged
   */
  shouldLog?: ShouldLogFunction;
}

/**
 * Inspects each incoming request with Akamai's Firewall for AI detect API
 * and blocks the request if Akamai returns a `deny` rule. Useful in front of
 * AI-powered APIs to filter prompt injection, jailbreaks, and other unsafe
 * inputs before they reach the model.
 *
 * The body, headers, URL, and query string sent to Akamai are configurable;
 * by default only the request body is captured. Bodies are read from a clone
 * so the upstream handler still sees the original.
 *
 * @title Akamai Firewall for AI
 * @public
 * @requiresAI
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const AkamaiFirewallForAiInboundPolicy: InboundPolicyHandler<AkamaiFirewallForAiInboundPolicyOptions>;

/**
 * The options for the Akamai Firewall for AI inbound policy. Sends the incoming request to Akamai's Firewall for AI detect endpoint and blocks the request if any rule returns a 'deny' action.
 * @public
 */
export declare interface AkamaiFirewallForAiInboundPolicyOptions {
  /**
   * Your Akamai Firewall for AI Configuration ID. This is the ID of the configuration in the Akamai Control Center that defines which detection rules to apply.
   */
  configurationId: string;
  /**
   * Your Akamai Firewall for AI API key, sent as the `Fai-Api-Key` header on each detect call.
   */
  "api-key": string;
  capture?: CaptureSettings;
  /**
   * Behavior when Akamai returns a rule with `action: "alert"` (Akamai's Monitor mode). `log` writes a warning and lets the request through, `block` treats the alert like a deny, `none` is silent.
   */
  onWarn?: "log" | "block" | "none";
  /**
   * If true (the default), the policy throws when the Akamai detect call itself fails (network error, 5xx, malformed response). Set to false to fail open and allow the request through when Akamai is unreachable.
   */
  throwOnError?: boolean;
  /**
   * Override the Akamai Firewall for AI detect endpoint URL. The literal `{configurationId}` is replaced with the configured ID. Defaults to `https://aisec.akamai.com/fai/v1/fai-configurations/{configurationId}/detect`. Useful for regional Akamai endpoints or for pointing tests at a mock server.
   */
  detectUrl?: string;
}

/**
 * Inspects each upstream response with Akamai's Firewall for AI detect API
 * and replaces the response with a `403 Forbidden` if Akamai returns a `deny`
 * rule. Useful behind AI-powered APIs to filter unsafe completions, sensitive
 * data exposure, and toxic content before they reach the client.
 *
 * The body, headers, URL, and query string sent to Akamai are configurable;
 * by default only the response body is captured. Bodies are read from a clone
 * so the client still receives the original.
 *
 * @title Akamai Firewall for AI
 * @public
 * @requiresAI
 * @param response - The outgoing Response from the handler
 * @param request - The original incoming Request
 * @param context - The current context of the Request
 * @param options - The configuration options for the policy
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Response
 */
export declare const AkamaiFirewallForAiOutboundPolicy: OutboundPolicyHandler<AkamaiFirewallForAiOutboundPolicyOptions>;

/**
 * The options for the Akamai Firewall for AI outbound policy. Sends the upstream response to Akamai's Firewall for AI detect endpoint and blocks the response if any rule returns a 'deny' action.
 * @public
 */
export declare interface AkamaiFirewallForAiOutboundPolicyOptions {
  /**
   * Your Akamai Firewall for AI Configuration ID. This is the ID of the configuration in the Akamai Control Center that defines which detection rules to apply.
   */
  configurationId: string;
  /**
   * Your Akamai Firewall for AI API key, sent as the `Fai-Api-Key` header on each detect call.
   */
  "api-key": string;
  capture?: CaptureSettings_2;
  /**
   * Behavior when Akamai returns a rule with `action: "alert"` (Akamai's Monitor mode). `log` writes a warning and lets the response through, `block` treats the alert like a deny, `none` is silent.
   */
  onWarn?: "log" | "block" | "none";
  /**
   * If true (the default), the policy throws when the Akamai detect call itself fails (network error, 5xx, malformed response). Set to false to fail open and allow the response through when Akamai is unreachable.
   */
  throwOnError?: boolean;
  /**
   * Override the Akamai Firewall for AI detect endpoint URL. The literal `{configurationId}` is replaced with the configured ID. Defaults to `https://aisec.akamai.com/fai/v1/fai-configurations/{configurationId}/detect`. Useful for regional Akamai endpoints or for pointing tests at a mock server.
   */
  detectUrl?: string;
}

/**
 * Models clients may select; the first entry is the default when model is omitted.
 *
 * @minItems 1
 * @public
 */
declare type AllowedModels = [ProviderAndModel_2, ...ProviderAndModel_2[]];

/**
 * @minItems 1
 * @public
 */
declare type AllowedModels1 = [ProviderAndModel_2, ...ProviderAndModel_2[]];

/**
 * Amberflo is a usage metering and billing service. This policy allows
 * you to send metering calls for each API to their meter ingest endpoint.
 *
 * @title Amberflo Metering / Billing
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare function AmberfloMeteringInboundPolicy(
  request: ZuploRequest,
  context: ZuploContext,
  options: AmberfloMeteringInboundPolicyOptions,
  policyName: string
): Promise<ZuploRequest<RequestGeneric>>;

/**
 * The options for this policy. Many of them can be overridden at the code level in a request using the `AmberfloMeteringPolicy.setRequestProperties` method.
 * @public
 */
export declare interface AmberfloMeteringInboundPolicyOptions {
  /**
   * The API key to use when sending metering calls to Amberflo.
   */
  apiKey: string;
  /**
   * The name of the meter to use when sending metering calls to Amberflo (overridable in code).
   */
  meterApiName?: string;
  /**
   * The value to use when sending metering calls to Amberflo (overridable in code).
   */
  meterValue?: number;
  /**
   * The path to the property on `request.user` contains the customer ID. For example `.data.accountNumber` would read the `request.user.data.accountNumber` property.
   */
  customerIdPropertyPath?: string;
  /**
   * The default customerId for all metering calls - overridable in code and by `customerIdPropertyPath`.
   */
  customerId?: string;
  /**
   * A dictionary of dimensions to be sent to Amberflo (extensible in code).
   */
  dimensions?: {
    [k: string]: string;
  };
  /**
   * A list of successful status codes and ranges "200-299, 304" that should trigger a metering call to Amberflo.
   */
  statusCodes?: string | number[];
  /**
   * The URL to send metering events. This is useful for testing purposes.
   */
  url?: string;
}

declare interface AmberfloMeteringIngestPayload {
  customerId: string;
  meterApiName: string;
  meterValue: number;
  meterTimeInMillis: number;
  dimensions: Record<string, string>;
}

/**
 * Helper class for Amberflo metering policy
 * @public
 */
export declare class AmberfloMeteringPolicy {
  static setRequestProperties(
    context: ZuploContext,
    properties: AmberfloMeteringProperties
  ): void;
}

declare interface AmberfloMeteringProperties extends Omit<
  AmberfloMeteringIngestPayload,
  "meterTimeInMillis"
> {
  customerId: string;
}

declare interface AndRule {
  /**
   * Nested rules that must all pass.
   *
   * @minItems 1
   */
  and: [NestedRule, ...NestedRule[]];
}

/**
 * A request to Anthropic's token-counting operation
 * (`/v1/messages/count_tokens`).
 *
 * The request uses the Messages body shape but does not require `max_tokens`.
 * The index signature preserves evolving Anthropic fields verbatim.
 */
declare interface AnthropicCountTokensRequest {
  model: string;
  messages: AnthropicMessage[];
  [key: string]: unknown;
}

declare interface AnthropicMessage {
  role: "user" | "assistant";
  content:
    | string
    | Array<{
        type: "text" | "image";
        text?: string;
        source?: unknown;
      }>;
}

/**
 * A request to the Anthropic Messages API (`/v1/messages`).
 *
 * The gateway forwards this body to Anthropic verbatim on the native passthrough
 * path, so the shape mirrors Anthropic's API rather than an internal contract.
 * The index signature carries evolving Anthropic fields (`thinking`,
 * `tool_choice`, `top_k`, structured `system` blocks, …) through unchanged.
 */
declare interface AnthropicMessagesRequest {
  model: string;
  messages: AnthropicMessage[];
  max_tokens: number;
  system?: string;
  temperature?: number;
  top_p?: number;
  stop_sequences?: string[];
  stream?: boolean;
  metadata?: Record<string, unknown>;
  tools?: unknown[];
  [key: string]: unknown;
}

/**
 * Authenticates requests based on API Keys using Zuplo API Management.
 *
 * @deprecated Please use the new {@link https://zuplo.com/docs/policies/api-key-inbound|API Key Authentication} policy
 * instead. This policy will continue to work but will be removed in a future
 * version of Zuplo.
 * @hidden
 * @title API Key Authentication
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param unparsedOptions - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const ApiAuthKeyInboundPolicy: typeof ApiKeyInboundPolicy;

/**
 * @deprecated
 * The options for this policy.
 * @public
 */
export declare interface ApiAuthKeyInboundPolicyOptions {
  /**
   * If 'true' allows the request to continue even if authenticated. When 'false' (the default) any unauthenticated request is automatically rejected with a 401.
   */
  allowUnauthenticatedRequests?: boolean;
}

/**
 * The API key for the AI Firewall.
 * @public
 */
declare type APIKey = string;

/**
 * Credential used to run the classifier. Without `appId` this is the API key for the OpenAI-compatible service at `baseUrl`, and it is required. With `appId` it is optional: omit it when the classifier app runs the Internal Only policy, which authorizes the in-process invocation itself, and set it only when that app authenticates callers with API keys, in which case it is sent as `Authorization: Bearer`.
 * @public
 */
declare type APIKey_2 = string;

/**
 * Represents a consumer in the API Key service.
 * @public
 */
export declare interface ApiKeyConsumer {
  /** The unique consumer identifier, e.g. csmr_f9HGke8lQHi2HgxFa4OIst9W */
  id: string;
  /** The consumer name */
  name: string;
  /** Optional description of the consumer */
  description?: string;
  /** Custom metadata stored with the consumer */
  metadata?: unknown;
  /** ISO timestamp when the consumer was created */
  createdOn: string;
  /** ISO timestamp when the consumer was last updated */
  updatedOn: string;
}

/**
 * A client for retrieving consumer data from the Zuplo API key service.
 *
 * @example
 * ```typescript
 * import { ApiKeyConsumerClient, ZuploContext, ZuploRequest } from "@zuplo/runtime";
 *
 * // Configure once (e.g., at module level)
 * const consumers = new ApiKeyConsumerClient({
 *   cacheDurationSeconds: 300,
 * });
 *
 * export async function myHandler(request: ZuploRequest, context: ZuploContext) {
 *   const consumer = await consumers.get("csmr_f9HGke8lQHi2HgxFa4OIst9W");
 *
 *   context.log.info(`Consumer: ${consumer.name}`);
 *   const metadata = consumer.metadata as { plan: string };
 *
 *   return Response.json({ consumer });
 * }
 * ```
 *
 * @beta
 * @public
 */
export declare class ApiKeyConsumerClient {
  private readonly bucketId;
  private readonly cacheDurationSeconds;
  private cacheNamePromise;
  constructor(options?: ApiKeyConsumerClientOptions);
  private getCacheName;
  /**
   * Get consumer data by consumer ID.
   *
   * @param consumerId - The unique identifier of the consumer
   * @returns The consumer data including metadata
   */
  get(consumerId: string): Promise<ApiKeyConsumer>;
}

/**
 * Configuration options for {@link ApiKeyConsumerClient}.
 * @public
 */
export declare interface ApiKeyConsumerClientOptions {
  /**
   * The bucket ID for the API key service. Must start with `bckt_`
   * (e.g. `bckt_2HaK3odRyJle6NJSu8mzNKBC30BYxllxL`) — a bucket name is not
   * accepted. Defaults to the bucket configured for the current environment.
   */
  bucketId?: string;
  /**
   * Cache duration in seconds. Set to 0 to disable caching.
   * Defaults to 60.
   */
  cacheDurationSeconds?: number;
}

/**
 * Authenticates requests based on API Keys using Zuplo's built-in API key management.
 * This policy validates API keys against Zuplo's key storage, caches results for performance,
 * and automatically adds user information to authenticated requests.
 *
 * @title API Key Authentication
 * @product api-gateway
 * @public
 *
 * @param request - The incoming ZuploRequest
 * @param context - The ZuploContext
 * @param unparsedOptions - The policy configuration options
 * @param policyName - The name of the policy instance
 * @returns The authenticated request with user info, or a 401 response if unauthorized
 *
 * @example
 * ```json
 * // policies.json - API key authentication using bucketId (preferred)
 * {
 *   "name": "api-key-auth",
 *   "policyType": "api-key-inbound",
 *   "handler": {
 *     "export": "ApiKeyInboundPolicy",
 *     "module": "$import(@zuplo/runtime)",
 *     "options": {
 *       "bucketId": "$env(API_KEY_BUCKET_ID)",
 *       "cacheTtlSeconds": 300
 *     }
 *   }
 * }
 * ```
 *
 * @example
 * ```json
 * // Custom header and auth scheme
 * {
 *   "handler": {
 *     "export": "ApiKeyInboundPolicy",
 *     "module": "$import(@zuplo/runtime)",
 *     "options": {
 *       "bucketId": "$env(API_KEY_BUCKET_ID)",
 *       "authHeader": "x-api-key",
 *       "authScheme": "",
 *       "allowUnauthenticatedRequests": false
 *     }
 *   }
 * }
 * ```
 *
 * @example
 * ```typescript
 * // Access authenticated user data in handler
 * export function myHandler(request: ZuploRequest, context: ZuploContext) {
 *   // User is automatically added by API key policy
 *   const user = request.user;
 *   context.log.info(`Request from API key: ${user.sub}`);
 *
 *   // Access custom metadata stored with the key
 *   const metadata = user.data as { plan: string; limit: number };
 *
 *   return Response.json({
 *     message: `Hello ${user.sub}`,
 *     plan: metadata.plan
 *   });
 * }
 * ```
 */
export declare function ApiKeyInboundPolicy(
  request: ZuploRequest,
  context: ZuploContext,
  unparsedOptions: ApiKeyInboundPolicyOptions | undefined,
  policyName: string
): Promise<Response | ZuploRequest<RequestGeneric>>;

/**
 * The options for this policy.
 * @public
 */
export declare interface ApiKeyInboundPolicyOptions {
  /**
   * The time to cache authentication results for a particular key. Higher values will decrease latency. Cached results will be valid until the cache expires even in the event the key is deleted, etc.
   */
  cacheTtlSeconds?: number;
  /**
   * The name of the header with the key.
   */
  authHeader?: string;
  /**
   * The scheme used on the header.
   */
  authScheme?: string;
  /**
   * The ID of the API Key service bucket. Defaults to the autogenerated bucket ID for your project.
   */
  bucketId?: string;
  /**
   * @deprecated
   * **Deprecated**: Use `bucketId` instead. The name of the API Key service bucket.
   */
  bucketName?: string;
  /**
   * If requests should proceed even if the policy does not successfully authenticate the request. Defaults to false and rejects any request without a valid API key (returning a `401 - Unauthorized` response). Set to `true` to support multiple authentication methods or support both authenticated and anonymous requests.
   */
  allowUnauthenticatedRequests?: boolean;
  /**
   * Zuplo will automatically document your API key header within your OpenAPI specification & Developer Portal. Set this to `true` to disable this behavior.
   */
  disableAutomaticallyAddingKeyHeaderToOpenApi?: boolean;
}

declare interface ApiRuntimeConfig {
  urls: UrlConfig | undefined;
}

/**
 * NOTE: This function is in beta and may change in the future.
 * It is not recommended for use in production code.
 * @beta
 * @param path - url path
 * @param options - request's HTTP options, which is "GET" by default
 * @returns ZuploResponse
 */
export declare function apiServices<TResponse, TRequest = unknown>(
  path: string,
  options?: FetchOptions<TRequest>
): Promise<TResponse | undefined>;

/**
 * Authentication options for api token authentication.
 * @public
 */
declare interface APITokenCredentialConfig {
  /**
   * The type of authentication to use.
   */
  method: "api-token";
  /**
   * The token key to use for authentication.
   */
  token: string;
  /**
   * The name of the header to use for authentication.
   */
  headerName?: string;
  /**
   * The prefix to use for the header value.
   */
  headerValuePrefix?: string;
}

/**
 * The endpoint shapes this policy applies to. Omit to apply to all (openai-chat, openai-responses, anthropic-messages).
 * @public
 */
declare type ApplicableEndpoints = (
  | "openai-chat"
  | "openai-responses"
  | "anthropic-messages"
)[];

/**
 * The endpoint shapes this policy applies to. Omit to apply to all (openai-chat, openai-responses, anthropic-messages).
 * @public
 */
declare type ApplicableEndpoints_2 = (
  | "openai-chat"
  | "openai-responses"
  | "anthropic-messages"
)[];

/**
 * The endpoint shapes this policy applies to. Omit to apply to all (openai-chat, openai-responses, anthropic-messages).
 * @public
 */
declare type ApplicableEndpoints_3 = (
  | "openai-chat"
  | "openai-responses"
  | "anthropic-messages"
)[];

/**
 * The endpoint shapes this policy applies to. Omit to apply to all (openai-chat, openai-responses, anthropic-messages).
 * @public
 */
declare type ApplicableEndpoints_4 = (
  | "openai-chat"
  | "openai-responses"
  | "anthropic-messages"
)[];

/**
 * The endpoint shapes this policy applies to. Omit to apply to all (openai-chat, openai-responses, anthropic-messages).
 *
 * @minItems 1
 * @public
 */
declare type ApplicableEndpoints_5 = [
  "openai-chat" | "openai-responses" | "anthropic-messages",
  ...("openai-chat" | "openai-responses" | "anthropic-messages")[],
];

/**
 * The endpoint shapes to cache. Defaults to all shapes: ['openai-chat', 'anthropic-messages', 'openai-responses'].
 * @public
 */
declare type ApplicableEndpoints_6 = (
  | "openai-chat"
  | "openai-responses"
  | "anthropic-messages"
)[];

/**
 * The application ID to identify this usage of the AI Firewall (optional).
 * @public
 */
declare type ApplicationID = string;

/**
 * A list of attributes that will be included in the authorization request.
 * @public
 */
declare type Attribute = {
  /**
   * The attribute ID that will be used in the PDP request.
   */
  attributeId: string;
  /**
   * The value of the attribute.
   */
  value: string;
}[];

/**
 * A list of attributes that will be included in the authorization request.
 * @public
 */
declare type Attribute1 = {
  /**
   * The attribute ID that will be used in the PDP request.
   */
  attributeId: string;
  /**
   * The value of the attribute.
   */
  value: string;
}[];

/**
 * A list of attributes that will be included in the authorization request.
 * @public
 */
declare type Attribute2 = {
  /**
   * The attribute ID that will be used in the PDP request.
   */
  attributeId: string;
  /**
   * The value of the attribute.
   */
  value: string;
}[];

declare interface Attribute_2 {
  AttributeId: string;
  Value: string | boolean | number | string[] | boolean[] | number[];
  Issuer?: string;
  DataType?: string;
  IncludeInResult?: boolean;
}

/**
 * Configuration for DataStax audit log provider
 * @public
 */
export declare interface AuditLogDataStaxInit {
  url: string;
  xCassandraToken: string;
}

/**
 * DataStax audit log output provider
 * @public
 */
export declare class AuditLogDataStaxProvider implements AuditLogOutputProvider {
  #private;
  constructor(options: AuditLogDataStaxInit);
  writeLogBatch: (entries: AuditLogEntry[]) => Promise<void>;
}

/**
 * Represents an audit log entry
 * @public
 */
declare interface AuditLogEntry {
  timestamp: Date;
  durationMs: number;
  routePath: string;
  requestId: string;
  userSub?: string;
  request: {
    url: string;
    method: HttpMethod;
    headers?: Record<string, string>;
    body?: string;
  };
  response: {
    status: number;
    statusText: string;
    headers?: Record<string, string>;
    body?: string;
  };
}

/**
 * A CloudEvent 1.0 audit log entry. Most fields are auto-populated by the
 * runtime; user code only supplies the type/subject/resources/data fields when
 * calling `AuditLogInboundPolicy.log()`.
 *
 * @public
 */
export declare interface AuditLogEvent {
  specversion: "1.0";
  id: string;
  source: string;
  type: string;
  time: string;
  datacontenttype?: "application/json";
  subject?: string;
  bucketid: string;
  actorsub?: string;
  actortype?: "user" | "service" | "apikey" | "anonymous";
  actoremail?: string;
  actorconnection?: string;
  resources?: AuditLogResource[];
  requestid?: string;
  success?: boolean;
  httpmethod?: string;
  httpurl?: string;
  httpstatus?: number;
  ipaddress?: string;
  useragent?: string;
  country?: string;
  region?: string;
  city?: string;
  mcpserver?: string;
  mcpvirtualserver?: string;
  mcptool?: string;
  data?: Record<string, unknown>;
  extensions?: Record<string, unknown>;
}

/**
 * Fields a caller may supply when emitting a custom audit event via
 * `AuditLogInboundPolicy.log()`. Everything else is filled in by the runtime
 * from the request context.
 *
 * @public
 */
export declare interface AuditLogEventInput {
  type: string;
  subject?: string;
  resources?: AuditLogResource[];
  success?: boolean;
  data?: Record<string, unknown>;
  /**
   * Geolocation of the caller. When omitted, these default to the current
   * request's geo data (from the request context), so custom events carry the
   * same location information as the auto-emitted per-request event.
   */
  country?: string;
  region?: string;
  city?: string;
  /** Override the auto-derived actor (rare). */
  actor?: {
    sub?: string;
    type?: "user" | "service" | "apikey" | "anonymous";
    email?: string;
    connection?: string;
  };
  /** MCP-specific helpers. */
  mcp?: {
    server?: string;
    virtualServer?: string;
    tool?: string;
  };
}

/**
 * Capture detailed logs of requests for auditing purposes. The policy emits
 * one structured CloudEvent per request, and user code can emit additional
 * events via the static `log()` method.
 *
 * @title Audit Logs
 * @product api-gateway
 * @public
 * @enterprise
 */
export declare class AuditLogInboundPolicy extends InboundPolicy<AuditLogInboundPolicyOptions> {
  #private;
  static readonly policyType = "audit-logs";
  /**
   * Emit an audit event for the current request.
   *
   * Fields not provided are filled in from the request context (bucket id,
   * request id, time, actor, IP, user agent, etc).
   *
   * @param context - The current ZuploContext.
   * @param event - The event details to record.
   */
  static log(context: ZuploContext, event: AuditLogEventInput): void;
  constructor(options: AuditLogInboundPolicyOptions, policyName: string);
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
}

/**
 * The options for the Audit Log Inbound policy.
 * @public
 */
export declare interface AuditLogInboundPolicyOptions {
  /**
   * Reverse-DNS prefix used for the auto-emitted request event type. Defaults to 'com.zuplo.api'.
   */
  eventTypeBase?: string;
  /**
   * Override the bucket id this policy emits events for. Defaults to the bucket id from the runtime environment.
   */
  bucketId?: string;
  /**
   * Fraction of requests to capture, between 0 (none) and 1 (all). Defaults to 1.
   */
  samplingRate?: number;
  /**
   * Controls which potentially-sensitive parts of each request are captured in the auto-emitted audit event. Disable fields to satisfy your own data-handling and PII policies. All are enabled by default.
   */
  include?: {
    /**
     * Include the request's query-string parameters in the logged URL. Disable if query strings may contain sensitive data.
     */
    queryParams?: boolean;
    /**
     * Include the authenticated user / actor identity (subject, email, connection).
     */
    user?: boolean;
    /**
     * Include the caller's IP address.
     */
    ipAddress?: boolean;
    /**
     * Include the caller's geolocation (country, region, city).
     */
    geolocation?: boolean;
  };
}

/**
 * Configuration options for audit logging
 * @public
 */
export declare interface AuditLogInit {
  requestFilter?: AuditLogRequestFilter;
  include?: {
    request?: {
      headers?: boolean;
      body?: boolean;
    };
    response?: {
      headers?: boolean;
      body?: boolean;
    };
  };
}

/**
 * Interface for audit log output providers
 * @public
 */
declare interface AuditLogOutputProvider {
  writeLogBatch: (entries: AuditLogEntry[]) => Promise<void>;
}

/**
 * Audit log plugin for tracking API requests and responses
 * @public
 */
export declare class AuditLogPlugin extends SystemRuntimePlugin {
  #private;
  constructor(outputProvider: AuditLogOutputProvider, init?: AuditLogInit);
  initialize(runtimeInit: RuntimeExtensions): Promise<void>;
}

/**
 * Filter function to determine if a request should be audited
 * @public
 */
declare interface AuditLogRequestFilter {
  (request: ZuploRequest, context: ZuploContext): Promise<boolean>;
}

/**
 * A resource affected by an audit event.
 * @public
 */
export declare interface AuditLogResource {
  type: string;
  id: string;
  metadata?: Record<string, unknown>;
}

/**
 * Authenticate users using Auth0 issued JWT tokens.
 *
 * @title Auth0 JWT Auth
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const Auth0JwtInboundPolicy: InboundPolicyHandler<Auth0JwtInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface Auth0JwtInboundPolicyOptions {
  /**
   * Your Auth0 domain. For example, `my-company.auth0.com`.
   */
  auth0Domain: string;
  /**
   * The Auth0 audience of your API, for example `https://api.example.com/`.
   */
  audience?: string;
  /**
   * Allow unauthenticated requests to proceed. This is use useful if you want to use multiple authentication policies or if you want to allow both authenticated and non-authenticated traffic.
   */
  allowUnauthenticatedRequests?: boolean;
  /**
   * Enables OAuth 2.0 Protected Resource Metadata discovery (RFC 9728). When `true`, requests without a bearer token receive a 401 whose `WWW-Authenticate` header points `resource_metadata` at the `/.well-known/oauth-protected-resource` document for the request path and, when the `OAuthProtectedResourcePlugin` declares `scopesSupported`, lists those scopes in `scope`. Requires the `OAuthProtectedResourcePlugin` in `zuplo.runtime.ts` or a user-defined route at that path.
   */
  oAuthResourceMetadataEnabled?: boolean;
}

/**
 * Authorize requests using an AuthZEN compatible PDP
 *
 * @title AuthZEN Authorization
 * @product api-gateway
 * @public
 * @enterprise
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare class AuthZenInboundPolicy extends InboundPolicy<AuthZenInboundPolicyOptions> {
  #private;
  static readonly policyType = "authzen";
  constructor(options: AuthZenInboundPolicyOptions, policyName: string);
  /**
   * The handler that is called each time this policy is invoked
   *
   * @param request - The incoming Request
   * @param context - The current context of the Request
   * @returns A Response or Request object
   */
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
  /**
   * Set the authorization payload for the current request.
   *
   * @param context - The ZuploContext for the current request
   * @param payload - The AuthZEN payload to send to the PDP service
   */
  static setAuthorizationPayload(
    context: ZuploContext,
    payload: Partial<AuthZenPayload>
  ): void;
  /**
   * Get the authorization payload for the current request.
   *
   * @param context - The ZuploContext for the current request
   * @returns The AuthZEN payload to send to the PDP service
   */
  static getAuthorizationPayload(
    context: ZuploContext
  ): Partial<AuthZenPayload> | undefined;
}

/**
 * The options for this policy.
 * @public
 */
export declare interface AuthZenInboundPolicyOptions {
  /**
   * The hostname of the AuthZen PDP service.
   */
  authorizerHostname: string;
  /**
   * The subject of the request.
   */
  subject: {
    /**
     * The type of the resource.
     */
    type: string;
    /**
     * The id of the resource. Note you can use the `$authzen-prop()` syntax to reference the resource id.
     */
    id: string;
    [k: string]: unknown;
  };
  /**
   * The resource of the request. Note you can use the `$authzen-prop()` syntax to reference the resource id.
   */
  resource: {
    /**
     * The type of the resource.
     */
    type: string;
    /**
     * The id of the resource. Note you can use the `$authzen-prop()` syntax to reference the resource id.
     */
    id: string;
    [k: string]: unknown;
  };
  /**
   * The action of the request. Note you can use the `$authzen-prop()` syntax to reference the action.
   */
  action: {
    /**
     * The name of the action. Note you can use the `$authzen-prop()` syntax to reference the action name.
     */
    name: string;
    [k: string]: unknown;
  };
  /**
   * The authorization header to use when communicating with the AuthZen PDP service.
   */
  authorizerAuthorizationHeader?: string;
  /**
   * If explicitly set to false, the policy will not throw an error if there is any problem communicating with the AuthZen PDP service and allow calls through. By default throwOnError is assumed to be on/true.
   */
  throwOnError?: boolean;
}

/* Excluded from this release type: AuthZenPayload */

export declare interface AuthZenPayloadSettings {
  subject?: AuthZenTypeIdPair;
  resource?: AuthZenTypeIdPair;
  action?: {
    name: string;
  };
}

export declare interface AuthZenTypeIdPair {
  type: string;
  id: string;
}

/**
 * AWS Lambda Event format version 1.0
 * @public
 */
declare interface AwsLambdaEventV1 {
  [key: string]: string | null | undefined | number | boolean | object;
  version: "1.0";
  resource: string;
  path: string;
  httpMethod: string;
  headers: Record<string, string>;
  multiValueHeaders: Record<string, string[]>;
  queryStringParameters: Record<string, string>;
  multiValueQueryStringParameters: Record<string, string[]>;
  requestContext: {
    accountId: string | null;
    apiId: string | null;
    authorizer: {
      claims: Record<string, string>;
      scopes: string[];
    };
    domainName: string;
    domainPrefix: string | null;
    extendedRequestId: string;
    httpMethod: string;
    identity: {
      accessKey: null | string;
      accountId: null | string;
      caller: null | string;
      cognitoAuthenticationProvider: null | string;
      cognitoAuthenticationType: null | string;
      cognitoIdentityId: null | string;
      cognitoIdentityPoolId: null | string;
      principalOrgId: null | string;
      sourceIp: string | null;
      user: null | string;
      userAgent: string | null;
      userArn: null | string;
      clientCert: {
        clientCertPem: null | string;
        subjectDN: null | string;
        issuerDN: null | string;
        serialNumber: null | string;
        validity: {
          notBefore: null | string;
          notAfter: null | string;
        };
      };
    };
    path: string;
    protocol: string;
    requestId: string;
    requestTime: string;
    requestTimeEpoch: number;
    resourceId: string | null;
    resourcePath: string;
    stage: null | string;
  };
  pathParameters: Record<string, string>;
  stageVariables: null | Record<string, string>;
}

/**
 * AWS Lambda Event format version 2.0
 * @public
 */
declare interface AwsLambdaEventV2 {
  [key: string]: string | null | undefined | number | boolean | object;
  version: "2.0";
  routeKey: string | null;
  rawPath: string;
  rawQueryString: string;
  cookies: string[];
  headers: Record<string, string>;
  queryStringParameters: Record<string, string>;
  requestContext: {
    accountId: string | null;
    apiId: string | null;
    authentication: {
      clientCert: {
        clientCertPem: string | null;
        subjectDN: string | null;
        issuerDN: string | null;
        serialNumber: string | null;
        validity: {
          notBefore: string | null;
          notAfter: string | null;
        };
      };
    };
    authorizer: {
      jwt: {
        claims: Record<string, string>;
        scopes: string[];
      };
    };
    domainName: string | null;
    domainPrefix: string | null;
    http: {
      method: string;
      path: string;
      protocol: string;
      sourceIp: string | null;
      userAgent: string | null;
    };
    requestId: string;
    routeKey: string | null;
    stage: null;
    time: string;
    timeEpoch: number;
  };
  pathParameters: Record<string, string>;
  stageVariables: string | null;
}

/**
 * Handler that proxies requests to AWS Lambda functions.
 * Supports both Lambda proxy integration formats (v1.0 and v2.0).
 *
 * @param request - The incoming ZuploRequest
 * @param context - The ZuploContext
 * @returns A Response from the Lambda function
 *
 * @public
 * @example
 * ```json
 * // routes.oas.json
 * {
 *   "paths": {
 *     "/api/lambda-function": {
 *       "x-zuplo-route": {
 *         "handler": {
 *           "export": "awsLambdaHandler",
 *           "module": "$import(@zuplo/runtime)",
 *           "options": {
 *             "accessKeyId": "$env(AWS_ACCESS_KEY_ID)",
 *             "secretAccessKey": "$env(AWS_SECRET_ACCESS_KEY)",
 *             "region": "us-east-1",
 *             "functionName": "my-lambda-function",
 *             "useLambdaProxyIntegration": true,
 *             "payloadFormatVersion": "2.0",
 *             "binaryMediaTypes": ["image/*", "application/pdf"]
 *           }
 *         }
 *       }
 *     }
 *   }
 * }
 * ```
 */
export declare function awsLambdaHandler(
  request: ZuploRequest,
  context: ZuploContext
): Promise<Response>;

/**
 * Extensions for customizing AWS Lambda handler behavior.
 * @public
 * @example
 * ```typescript
 * import { AwsLambdaHandlerExtensions } from "@zuplo/runtime";
 *
 * // In zuplo.runtime.ts
 * export function runtimeInit(runtime: RuntimeExtensions) {
 *   AwsLambdaHandlerExtensions.addSendingAwsLambdaEventHook(
 *     async (request, context, event) => {
 *       // Add custom headers or modify the event
 *       event.headers["X-Custom-Header"] = "value";
 *       return event;
 *     }
 *   );
 * }
 * ```
 */
export declare const AwsLambdaHandlerExtensions: {
  addSendingAwsLambdaEventHook: (hook: OnSendingAwsLambdaEventHook) => void;
};

declare interface AWSLoggingOptions {
  region: string;
  accessKeyId: string;
  secretAccessKey: string;
  logGroupName: string;
  logStreamName: string;
  /**
   * Any custom log fields to include in each log entry.
   */
  fields?: CustomLogFields;
}

/**
 * AWS CloudWatch logging plugin
 * @public
 */
export declare class AWSLoggingPlugin extends LogPlugin {
  private options;
  constructor(options: AWSLoggingOptions);
  /* Excluded from this release type: getTransport */
}

/**
 * Authorize requests using Axiomatics Policy Server.
 *
 * @title Axiomatics Authorization
 * @product api-gateway
 * @public
 * @enterprise
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare class AxiomaticsAuthZInboundPolicy extends InboundPolicy<AxiomaticsAuthZInboundPolicyOptions> {
  #private;
  static readonly policyType = "axiomatics-authz";
  private pdpService;
  static setAuthAttributes(
    context: ZuploContext,
    attributes: XacmlRequest["Request"]
  ): void;
  constructor(options: AxiomaticsAuthZInboundPolicyOptions, policyName: string);
  /**
   * The handler that is called each time this policy is invoked
   *
   * @param request - The incoming Request
   * @param context - The current context of the Request
   * @returns A Response or Request object
   */
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
  /**
   * Gets the attributes for the authz request from the policy options
   */
  populateOptionAttributes({
    optionName,
    authzRequestCategory,
    authzRequest,
    context,
  }: {
    optionName: keyof Pick<
      AxiomaticsAuthZInboundPolicyOptions,
      "accessSubjectAttributes" | "resourceAttributes" | "actionAttributes"
    >;
    authzRequestCategory: keyof Omit<
      XacmlRequest["Request"],
      | "ReturnPolicyIdList"
      | "CombinedDecision"
      | "XPathVersion"
      | "MultiRequests"
      | "Category"
    >;
    authzRequest: XacmlRequest;
    context: ZuploContext;
  }): void;
  addAttributesToCategory(
    authzRequest: XacmlRequest,
    authzRequestCategory: keyof Omit<
      XacmlRequest["Request"],
      | "ReturnPolicyIdList"
      | "CombinedDecision"
      | "XPathVersion"
      | "MultiRequests"
      | "Category"
    >,
    attributes: Attribute_2[]
  ): void;
}

/**
 * The options for this policy.
 * @public
 */
export declare interface AxiomaticsAuthZInboundPolicyOptions {
  /**
   * The URL to which the plugin will make a JSON POST request before proxying the original request.
   */
  pdpUrl: string;
  /**
   * The username to use when authenticating with the PDP.
   */
  pdpUsername: string;
  /**
   * The password to use when authenticating with the PDP.
   */
  pdpPassword: string;
  /**
   * Indicates whether the request should continue if authorization fails. Default is `false` which means unauthorized users will automatically receive a 403 response.
   */
  allowUnauthorizedRequests?: boolean;
  /**
   * Indicates whether the plugin should include default action attributes in the authorization request.
   */
  includeDefaultActionAttributes?: boolean;
  /**
   * Indicates whether the plugin should include default resource attributes in the authorization request.
   */
  includeDefaultResourceAttributes?: boolean;
  /**
   * Indicates whether the plugin should include default subject attributes in the authorization request.
   */
  includeDefaultSubjectAttributes?: boolean;
  /**
   * The name of the header that carries the JWT.
   */
  tokenHeaderName?: string;
  accessSubjectAttributes?: Attribute;
  resourceAttributes?: Attribute1;
  actionAttributes?: Attribute2;
}

/**
 * Function to generate blob names
 * @public
 */
export declare interface AzureBlobGenerateName<T> {
  (entries: T[]): string;
}

/**
 * Azure Blob Storage request logger plugin
 * @public
 */
export declare class AzureBlobPlugin<
  T extends BasicDictionary,
> extends SystemRuntimePlugin {
  #private;
  constructor(options: AzureBlobPluginOptions<T>);
  initialize(runtime: RuntimeExtensions): Promise<void>;
}

/**
 * Options for Azure Blob request logger plugin
 * @public
 */
export declare interface AzureBlobPluginOptions<T> {
  sasUrl: string;
  batchPeriodSeconds: number;
  generateLogEntry: GenerateRequestLoggerEntry<T>;
  generateBlobName?: AzureBlobGenerateName<T>;
}

/**
 * Azure Event Hubs request logger plugin
 * @public
 */
export declare class AzureEventHubsRequestLoggerPlugin<
  T extends BasicDictionary,
> extends SystemRuntimePlugin {
  #private;
  constructor(options: AzureEventHubsRequestLoggerPluginOptions<T>);
  /**
   * In Zuplo, a plugin must implement initialize() to add a RequestLoggerCore
   * that handles batching requests for us.
   */
  initialize(runtime: RuntimeExtensions): Promise<void>;
}

/**
 * Options for Azure Event Hubs request logger plugin
 * @public
 */
export declare interface AzureEventHubsRequestLoggerPluginOptions<T> {
  /** Full connection string from Azure Portal (with Endpoint=..., etc.) */
  connectionString: string;
  /**
   * If your connection string includes an EntityPath=..., that's used by default.
   * Otherwise, specify eventHubName here.
   */
  eventHubName?: string;
  generateLogEntry: GenerateRequestLoggerEntry<T>;
  /** How often to flush batched logs, in seconds. */
  batchPeriodSeconds: number;
}

/* Excluded from this release type: BackgroundDispatchDebugLog */

/**
 * Utility for batching and dispatching events in the background.
 * Useful for aggregating logs, metrics, or other data before sending to external services.
 * The dispatcher automatically batches items and sends them after a configurable delay.
 *
 * @public
 * @example
 * ```typescript
 * import { BackgroundDispatcher, ZuploContext } from "@zuplo/runtime";
 *
 * // Define your payload type
 * interface LogEntry {
 *   timestamp: string;
 *   level: string;
 *   message: string;
 *   metadata?: Record<string, any>;
 * }
 *
 * // Create a dispatcher function
 * const sendLogs = async (logs: LogEntry[]) => {
 *   await fetch("https://logging.example.com/bulk", {
 *     method: "POST",
 *     headers: { "Content-Type": "application/json" },
 *     body: JSON.stringify({ logs })
 *   });
 * };
 *
 * // Initialize the dispatcher
 * const logDispatcher = new BackgroundDispatcher(sendLogs, {
 *   msDelay: 1000, // Batch logs every 1 second
 *   name: "log-dispatcher"
 * });
 *
 * // Use in your handler
 * export function myHandler(request: ZuploRequest, context: ZuploContext) {
 *   // Queue logs for batched sending
 *   logDispatcher.enqueue({
 *     timestamp: new Date().toISOString(),
 *     level: "info",
 *     message: "Request processed",
 *     metadata: {
 *       userId: request.user?.sub,
 *       path: request.url
 *     }
 *   });
 *
 *   return new Response("OK");
 * }
 * ```
 */
export declare class BackgroundDispatcher<TPayload> {
  #private;
  constructor(
    dispatcher: DispatchFunction<TPayload>,
    options: BatchDispatcherOptions
  );
  enqueue: (payload: TPayload) => void;
  /**
   * Dispatches whatever is queued right now and waits for it — plus any
   * dispatch already in flight — to settle, without waiting out the batching
   * delay. Use this to drain deterministically at a shutdown or flush point.
   */
  flush: () => Promise<void>;
  /**
   * Total payloads dropped because the queue was full (`maxQueueSize`).
   *
   * Dropping is silent data loss, so a caller that must report delivery
   * honestly can compare this before and after an {@link enqueue} to learn
   * whether that particular payload was accepted.
   */
  get totalDropped(): number;
}

/**
 * A background dispatch failure with an optional diagnostic that is
 * safe to write at debug level.
 *
 * @public
 */
export declare class BackgroundDispatchError extends Error {
  readonly debugLog: BackgroundDispatchDebugLog | undefined;
  constructor(
    message: string,
    options?: ErrorOptions & {
      debugLog?: BackgroundDispatchDebugLog;
    }
  );
}

/**
 * A utility for loading and caching data in the background with automatic refresh
 *
 * When a cache entry expires and the loader then fails — it rejects, or it
 * exceeds `loaderTimeoutSeconds` — {@link BackgroundLoader.get} falls back to
 * the last value it successfully loaded rather than throwing, for up to
 * `staleIfErrorSeconds` past expiry. A loader whose upstream is briefly
 * unavailable therefore keeps serving the previous value instead of failing
 * every caller. The error is surfaced when there is no previously loaded value
 * to fall back to, or when that value is older than `staleIfErrorSeconds`.
 * @public
 */
export declare class BackgroundLoader<T = unknown> {
  #private;
  constructor(
    loader: BackgroundLoaderFunction<T>,
    options: BackgroundLoaderOptions
  );
  /**
   * @deprecated Use constructor(loader: BackgroundLoaderFunction<T>, options: BackgroundLoaderOptions) instead
   */
  constructor(loader: BackgroundLoaderFunction<T>, ttlSeconds: number);
  get(key: string): Promise<T>;
}

/**
 * Function to load data in the background
 * @public
 */
export declare interface BackgroundLoaderFunction<T> {
  (key: string): Promise<T>;
}

/**
 * Options for background loader
 * @public
 */
declare interface BackgroundLoaderOptions {
  ttlSeconds: number;
  loaderTimeoutSeconds?: number;
  /**
   * How long past `ttlSeconds` the last successfully loaded value may still be
   * served while refreshes keep failing, so that a brief upstream outage does
   * not fail every caller.
   *
   * Set to `0` to always surface the error instead of serving an expired
   * value. Defaults to unbounded — an expired value is served for as long as
   * refreshes keep failing.
   *
   * @example
   * ```ts
   * // Serve the last known-good value for up to 5 minutes past expiry
   * const loader = new BackgroundLoader(fetchConfig, {
   *   ttlSeconds: 60,
   *   staleIfErrorSeconds: 300,
   * });
   * ```
   */
  staleIfErrorSeconds?: number;
}

/**
 * @beta
 */
declare abstract class BaseCryptoBeta {
  abstract digest(algorithm: string, data: string): Promise<string>;
}

declare class BaseOpenFGAAuthZInboundPolicy extends InboundPolicy<OpenFGAAuthZInboundPolicyOptions> {
  private client;
  private authorizer;
  private cache;
  static setContextChecks(
    context: ZuploContext,
    checks: OpenFGACheck | OpenFGACheck[]
  ): void;
  constructor(options: OpenFGAAuthZInboundPolicyOptions, policyName: string);
  /**
   * The handler that is called each time this policy is invoked
   *
   * @param request - The incoming Request
   * @param context - The current context of the Request
   * @returns A Response or Request object
   */
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
  private getAuthorizer;
}

/**
 * Base URL of the OpenAI-compatible API that runs the classifier model. Mutually exclusive with `appId`, which routes the classifier through an AI Gateway app instead.
 * @public
 */
declare type BaseURL = string;

/**
 * An account object.
 * @public
 */
declare interface BasicAuthAccount {
  /**
   * The username for the account (this will be the `sub` property on `request.user`.
   */
  username: string;
  /**
   * The password for the account - note we recommend storing this in environment variables.
   */
  password: string;
  /**
   * The data payload you want associated with this account (this will be the `data` property on `request.user`).
   */
  data?: {
    [k: string]: unknown;
  };
}

/**
 * Authenticate requests using basic auth (i.e. username and password)
 *
 * @title Basic Auth
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const BasicAuthInboundPolicy: InboundPolicyHandler<BasicAuthInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface BasicAuthInboundPolicyOptions {
  /**
   * An array of account objects (username, password and data properties).
   */
  accounts: BasicAuthAccount[];
  /**
   * If 'true' allows the request to continue even if unauthenticated. When 'false' (the default) any unauthenticated request is automatically rejected with a 401.
   */
  allowUnauthenticatedRequests?: boolean;
}

/**
 * Basic dictionary type for log entries
 * @public
 */
declare type BasicDictionary = Record<
  string,
  string | number | boolean | null | undefined
>;

/* Excluded from this release type: BatchDispatch */

/**
 * Options for configuring a BackgroundDispatcher.
 * @public
 */
declare interface BatchDispatcherOptions {
  msDelay: number;
  name?: string;
  /**
   * Flush immediately once this many payloads are queued instead of waiting
   * the full `msDelay`. Bounds the size of a single dispatched batch.
   * @defaultValue 1000
   */
  maxBatchSize?: number;
  /**
   * Hard cap on queued payloads. Payloads enqueued beyond this limit are
   * dropped rather than growing memory without bound.
   * @defaultValue 10000
   */
  maxQueueSize?: number;
}

/* Excluded from this release type: BatchDispatchLimits */

/* Excluded from this release type: BatchDispatchOptions */

/**
 * Models rejected in open-but-filtered mode.
 *
 * @minItems 1
 * @public
 */
declare type BlockedModels = [ProviderAndModel_2, ...ProviderAndModel_2[]];

/**
 * @minItems 1
 * @public
 */
declare type BlockedModels1 = [ProviderAndModel_2, ...ProviderAndModel_2[]];

/**
 * The brownout policy allows performing scheduled downtime on your API
 *
 * @title Brown Out
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare class BrownoutInboundPolicy extends InboundPolicy<BrownoutInboundPolicyOptions> {
  static readonly policyType = "brownout";
  crons: Cron[];
  constructor(options: BrownoutInboundPolicyOptions, policyName: string);
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
}

/**
 * The options for this policy.
 * @public
 */
export declare interface BrownoutInboundPolicyOptions {
  /**
   * The cron schedule for when this policy is enabled. This can be a single cron string or an array of multiple cron strings.
   */
  cronSchedule: string | string[];
  /**
   * The problem that is returned in the response body when this policy is enabled.
   */
  problem?: {
    /**
     * The type of problem.
     */
    type?: string;
    /**
     * The title of problem.
     */
    title?: string;
    /**
     * The detail of problem.
     */
    detail?: string;
    /**
     * Http status code of the problem.
     */
    status?: number;
    [k: string]: unknown;
  };
}

/* Excluded from this release type: buildCacheOperationBase */

/* Excluded from this release type: BuildEnvironment */

/**
 * @public
 */
declare interface BuildRouteConfiguration {
  path: string;
  methods: HttpMethod[];
  /**
   * @deprecated This property is not used and will be removed in future versions
   */
  label?: string;
  /**
   * @deprecated This property is not used and will be removed in future versions
   */
  key?: string;
  handler: HandlerDefinition;
  corsPolicy?: CorsPolicy;
  /**
   * @deprecated This property is deprecated. Use route.raw() instead.
   */
  custom?: any;
  mcp?: {
    enabled?: boolean;
  };
  policies?: {
    inbound?: string[];
    outbound?: string[];
  };
  /**
   * @deprecated This property is not used and will be removed in future versions
   */
  excludeFromOpenApi?: boolean;
  pathPattern?: string;
  /**
   * Build-time metadata for this route.
   */
  metadata?: {
    /**
     * The source file this route was generated from.
     */
    filepath: string;
  };
  /* Excluded from this release type: raw */
}

/**
 * Partitions the cache when the authenticated application has no configuration id. Applications with a configuration id always use it, so cache entries stay isolated per application.
 * @public
 */
declare type CacheNamespace = string;

/**
 * The shared per-request dimensions every `cache_operation` event from a
 * policy carries; outcome-specific fields are added at each emission site.
 */
declare type CacheOperationBase = Pick<
  CacheOperationParams,
  | "cacheType"
  | "policyType"
  | "policyName"
  | "configId"
  | "consumerSub"
  | "routePath"
  | "method"
>;

/** The kind of cache a `cache_operation` event describes. */
declare type CacheOperationCacheType = "semantic" | "http";

/**
 * The outcome of a single cache lookup or write attempt:
 * - `hit` / `miss`: lookup outcomes.
 * - `store`: a write-back stored the response.
 * - `not_stored`: a write-back declined to store (see `reason`).
 * - `skip`: the lookup never ran (uncacheable shape, missing identity, ...).
 * - `error`: the lookup or store failed (see `reason`).
 */
declare type CacheOperationOutcome =
  | "hit"
  | "miss"
  | "store"
  | "skip"
  | "error"
  | "not_stored";

/**
 * Emitter-facing params for a `cache_operation` event. Everything the emitter
 * doesn't know may be omitted; {@link buildCacheOperationMetadata} normalizes
 * omissions to explicit `null`s so every event carries the full contract.
 */
declare interface CacheOperationParams {
  cacheType: CacheOperationCacheType;
  policyType: string;
  policyName: string;
  outcome: CacheOperationOutcome;
  reason?: string | null;
  latencyMs?: number | null;
  similarity?: number | null;
  configId?: string | null;
  consumerSub?: string | null;
  routePath?: string | null;
  method?: string | null;
  statusCode?: number | null;
  savedPromptTokens?: number | null;
  savedCompletionTokens?: number | null;
}

/**
 * Internal
 */
declare interface CacheOptions {
  logger?: Logger;
}

/**
 * How long a cached response lives, in whole seconds. Defaults to 3600 (1 hour); maximum 2592000 (30 days).
 * @public
 */
declare type CacheTTLSeconds = number;

/**
 * Respond to matched incoming requests with cached content
 *
 * @title Caching
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare function CachingInboundPolicy(
  request: ZuploRequest,
  context: ZuploContext,
  options: CachingInboundPolicyOptions,
  policyName: string
): Promise<Response | ZuploRequest<RequestGeneric>>;

/**
 * The options for this policy.
 * @public
 */
export declare interface CachingInboundPolicyOptions {
  /**
   * The timeout of the cache in seconds.
   */
  expirationSecondsTtl?: number;
  /**
   * The headers to be considered when caching.
   */
  headers?: string[];
  /**
   * HTTP Methods to be cached. Valid methods are: GET, POST, PUT, PATCH, DELETE, HEAD.
   */
  cacheHttpMethods?: ("GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD")[];
  /**
   * Response status codes to be cached.
   */
  statusCodes?: number[];
  /**
   * Specifies an id or 'key' for this policy to store cache. This is useful for cache-busting. For example, set this property to an env var and if you change that env var value, you invalidate the cache.
   */
  cacheId?: string;
  /**
   * By default, the Authorization header is always considered in the caching policy. You can disable by setting this to `true`.
   */
  dangerouslyIgnoreAuthorizationHeader?: boolean;
}

/**
 * Controls which parts of the incoming request are sent to Akamai for inspection. Akamai's detect endpoint receives the captured fields concatenated into a single labeled text payload as `llmInput`.
 * @public
 */
declare interface CaptureSettings {
  /**
   * Include the request body. Only text-based content types (JSON, XML, form-encoded, text/*) are sent; binary bodies are skipped. The body is read from a clone of the request so the upstream still receives it unchanged.
   */
  body?: boolean;
  /**
   * Include the request headers. By default `Authorization`, `Proxy-Authorization`, `Cookie`, and `Set-Cookie` are stripped — see the `dangerouslyInclude*` flags to override.
   */
  headers?: boolean;
  /**
   * Include the request URL (origin and path, query string excluded). Enable `queryString` separately if you also want the query string.
   */
  url?: boolean;
  /**
   * Include the request query string. Query strings sometimes contain credentials or session tokens — leave this off unless you want Akamai to see them.
   */
  queryString?: boolean;
  /**
   * If `headers` is true, also include the `Authorization` and `Proxy-Authorization` headers. Off by default because these typically contain bearer tokens.
   */
  dangerouslyIncludeAuthorizationHeader?: boolean;
  /**
   * If `headers` is true, also include the `Cookie` header. Off by default because cookies often carry session credentials.
   */
  dangerouslyIncludeCookieHeader?: boolean;
}

/**
 * Controls which parts of the upstream response (and the originating request URL) are sent to Akamai for inspection. Akamai's detect endpoint receives the captured fields concatenated into a single labeled text payload as `llmOutput`.
 * @public
 */
declare interface CaptureSettings_2 {
  /**
   * Include the response body. Only text-based content types (JSON, XML, form-encoded, text/*) are sent; binary bodies are skipped. The body is read from a clone of the response so the client still receives it unchanged.
   */
  body?: boolean;
  /**
   * Include the response headers. By default `Set-Cookie` is stripped — see `dangerouslyIncludeCookieHeader` to override.
   */
  headers?: boolean;
  /**
   * Include the originating request URL (origin and path, query string excluded). Useful as context for the response.
   */
  url?: boolean;
  /**
   * Include the originating request's query string. Query strings sometimes contain credentials or session tokens — leave this off unless you want Akamai to see them.
   */
  queryString?: boolean;
  /**
   * If `headers` is true, also include any `Authorization` or `Proxy-Authorization` headers on the response. Rarely set on responses but stripped by default for safety.
   */
  dangerouslyIncludeAuthorizationHeader?: boolean;
  /**
   * If `headers` is true, also include the `Set-Cookie` header on the response. Off by default because Set-Cookie typically carries session credentials.
   */
  dangerouslyIncludeCookieHeader?: boolean;
}

declare interface Category {
  Id?: string;
  CategoryId?: string;
  Content?: string;
  Attribute: Attribute_2[];
}

/**
 * How to combine the configured client policy with a `Cache-Control` the upstream already sent. `strictest` (default) emits the more conservative of the two — the lower `max-age` and the union of restrictive directives. `replace` overwrites whatever upstream sent. `preserve` leaves the upstream header untouched and only adds the CDN headers.
 * @public
 */
declare type CdnCacheControlClientMode = "strictest" | "replace" | "preserve";

/**
 * The `Cache-Control` sent to the browser or app. Separate from `edge` so the CDN can absorb load without clients holding stale data.
 * @public
 */
declare interface CdnCacheControlClientOptions {
  /**
   * Seconds the client may reuse this response. Omit to send no `max-age`.
   */
  maxAge?: number;
  visibility?: CdnCacheControlClientVisibility;
  /**
   * Adds `no-cache`, so the client must revalidate before reusing the response. Distinct from `visibility: no-store`, which forbids storing it at all.
   */
  noCache?: boolean;
  /**
   * Adds `must-revalidate`, so the client may not serve the response once stale.
   */
  mustRevalidate?: boolean;
  mode?: CdnCacheControlClientMode;
}

/**
 * `public` allows any cache to store the response, `private` restricts it to the client's own cache, `no-store` forbids client caching entirely. With `strategy: targeted` a `private`/`no-store` client policy still permits edge caching, because the CDN reads its own header.
 * @public
 */
declare type CdnCacheControlClientVisibility =
  | "public"
  | "private"
  | "no-store";

/**
 * A cache policy for one response: what the static options normalise into, and
 * what a `cacheConfig` function returns.
 *
 * A function's return value **replaces** this wholesale rather than being merged
 * field by field. Returning nothing falls back to the static options, which is
 * how a route enforces defaults and overrides them in only the few cases that
 * need it.
 */
export declare interface CdnCacheControlConfig {
  /** Set to false to emit no edge headers or tags for this response. */
  cache?: boolean;
  edge?: EdgeCacheDirectives;
  client?: ClientCacheDirectives;
  tags?: string[];
}

/**
 * A `cacheConfig` function: returns the CDN cache policy for one response.
 *
 * Return `undefined` or `null` to fall back to the static options, which is how
 * a route enforces defaults and overrides them only where it needs to.
 *
 * @public
 */
export declare type CdnCacheControlConfigFn = (
  response: Response,
  request: ZuploRequest,
  context: ZuploContext
) =>
  | CdnCacheControlConfig
  | undefined
  | null
  | Promise<CdnCacheControlConfig | undefined | null>;

/**
 * A function that overrides the cache configuration per response, for rules that cannot be expressed statically (per-entity purge tags, a TTL that depends on a response header, or skipping an empty result set). Returning nothing (`undefined` or `null`) falls back to the `edge`, `client` and `tags` options, so those stay the enforced default and the function only handles exceptions. A returned config **replaces** those options wholesale rather than being merged directive by directive, so include every directive the response needs. Return `{ cache: false }` to skip caching a response entirely — note that also sends `Cache-Control: no-store` to the client unless `client.mode` is `preserve`. The function receives the live response: it must not consume the body, and should call `response.clone()` if it needs to read it.
 * @public
 */
declare interface CdnCacheControlConfigFunction {
  /**
   * Specifies the export that holds your cache config function, e.g. `default`, `cdnCacheConfig`.
   */
  export: string;
  /**
   * Specifies the module that holds your cache config function, in the format `$import(./modules/my-module)`.
   */
  module: string;
}

/**
 * How long the CDN may serve this response. These directives are sent only to the CDN, never to the browser (unless `strategy` is `s-maxage`).
 * @public
 */
declare interface CdnCacheControlEdgeOptions {
  /**
   * Seconds the CDN may serve this response without revalidating.
   */
  maxAge: number;
  /**
   * Seconds the CDN may keep serving a stale response while it revalidates in the background. Not expressible in Akamai's `Edge-Control` — configure it in Property Manager, or use `strategy: s-maxage`.
   */
  staleWhileRevalidate?: number;
  /**
   * Seconds the CDN may serve a stale response when the gateway returns an error. Not expressible in Akamai's `Edge-Control` — configure it in Property Manager, or use `strategy: s-maxage`.
   */
  staleIfError?: number;
}

/**
 * Sets the response headers that tell a CDN how long it may cache a response and
 * which purge tags it belongs to, separately from what the browser is told.
 *
 * @title CDN Cache Control
 * @product api-gateway
 * @public
 * @param response - The Response
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Response
 */
export declare const CdnCacheControlOutboundPolicy: OutboundPolicyHandler<CdnCacheControlOutboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface CdnCacheControlOutboundPolicyOptions {
  cdn: CdnCacheControlVendor;
  strategy?: CdnCacheControlStrategy;
  edge?: CdnCacheControlEdgeOptions;
  client?: CdnCacheControlClientOptions;
  /**
   * Purge tags, rendered in the target CDN's format: comma-joined `Edge-Cache-Tag` (Akamai), space-joined `Surrogate-Key` (Fastly), comma-joined `Cache-Tag` (Cloudflare). CloudFront has no tag purge and rejects this option. Tags are validated against the CDN's length and character limits, because an over-long tag header is silently truncated rather than rejected.
   */
  tags?: string[];
  /**
   * Request headers that vary this response, unioned with any `Vary` the upstream already sent and emitted as `Vary`. The union is deliberate: replacing an upstream `Vary: Authorization` would stop a shared cache keying on it and let it serve one user's response to another. Off by default: Akamai skips caching any response carrying `Vary` until Cache ID Modification is configured, so enabling this can silently disable edge caching entirely.
   */
  vary?: string[];
  /**
   * When true (default), an upstream `Cache-Control` of `no-store`/`no-cache`/`private`, or a `Set-Cookie` on the response, suppresses all edge headers and purge tags. This keeps the application's ability to mark a response uncacheable. Set to false to override it — on Akamai this emits `Edge-Control: !no-store`.
   */
  respectUpstream?: boolean;
  cacheConfig?: CdnCacheControlConfigFunction;
}

/**
 * How the edge TTL is carried. `targeted` uses the CDN's own header (`Edge-Control`, `Surrogate-Control`, `CDN-Cache-Control`) and is the only way to cache at the edge without also caching in the browser. `s-maxage` folds the edge TTL into `Cache-Control` instead, for a property that honors origin `Cache-Control` but not the targeted header. Defaults to `targeted`, except on a CDN that reads no targeted header — CloudFront defaults to `s-maxage`, which is the only thing it supports.
 * @public
 */
declare type CdnCacheControlStrategy = "targeted" | "s-maxage";

/**
 * The CDN in front of this gateway. Required, with no default — each CDN reads a different header for shared-cache TTL and purge tags, and a wrong guess fails silently. Use `generic` for an RFC 9213 CDN that is not listed.
 * @public
 */
declare type CdnCacheControlVendor =
  | "akamai"
  | "fastly"
  | "cloudflare"
  | "cloudfront"
  | "generic";

/**
 * Changes the HTTP method of the incoming request.
 *
 * @title Change Method
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const ChangeMethodInboundPolicy: InboundPolicyHandler<ChangeMethodInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface ChangeMethodInboundPolicyOptions {
  /**
   * The HTTP Method to be used, e.g. POST, GET, PUT, PATCH, etc.
   */
  method: string;
}

declare interface ChatCompletionChoice {
  index: number;
  message: ChatCompletionMessage;
  logprobs?: {
    content: Array<{
      token: string;
      logprob: number;
      bytes?: number[];
      top_logprobs?: Array<{
        token: string;
        logprob: number;
        bytes?: number[];
      }>;
    }> | null;
  } | null;
  finish_reason:
    | "stop"
    | "length"
    | "function_call"
    | "tool_calls"
    | "content_filter";
}

declare interface ChatCompletionMessage {
  role: "system" | "user" | "assistant" | "function" | "tool";
  content: string | null;
  name?: string;
  function_call?: {
    name: string;
    arguments: string;
  };
  tool_calls?: Array<{
    id: string;
    type: "function";
    function: {
      name: string;
      arguments: string;
    };
  }>;
  tool_call_id?: string;
}

declare interface ChatCompletionRequest {
  model: string;
  messages: ChatCompletionMessage[];
  temperature?: number;
  top_p?: number;
  n?: number;
  stream?: boolean;
  stop?: string | string[];
  max_tokens?: number;
  presence_penalty?: number;
  frequency_penalty?: number;
  user?: string;
  seed?: number;
  functions?: FunctionDefinition[];
  function_call?:
    | string
    | {
        name: string;
      };
  tools?: ToolDefinition[];
  tool_choice?: string | ToolChoice;
  parallel_tool_calls?: boolean;
  response_format?: {
    type: "text" | "json_object" | "json_schema";
    json_schema?: {
      name: string;
      strict?: boolean;
      schema: Record<string, unknown>;
    };
  };
  logit_bias?: Record<string, number>;
  logprobs?: boolean;
  top_logprobs?: number;
  max_completion_tokens?: number;
  service_tier?: "auto" | "default";
  stream_options?: {
    include_usage?: boolean;
  };
}

declare interface ChatCompletionResponse {
  id: string;
  object: "chat.completion";
  created: number;
  model: string;
  system_fingerprint?: string;
  choices: ChatCompletionChoice[];
  usage: Usage;
  service_tier?: string;
  provider?: string;
}

/**
 * @deprecated
 * Deprecated: use `classifier.app` instead. Classify by calling an OpenAI-compatible Chat Completions API directly, outside the gateway. The model must support structured outputs (`response_format` with a JSON schema).
 * @public
 */
declare interface ChatCompletionsAPI {
  apiKey: ChatCompletionsAPIKey;
  model: ChatCompletionsModel;
  baseUrl?: ChatCompletionsBaseURL;
}

/**
 * API key for the service at `baseUrl`, sent as `Authorization: Bearer`.
 * @public
 */
declare type ChatCompletionsAPIKey = string;

/**
 * Base URL of the OpenAI-compatible API. The classifier request is sent to `{baseUrl}/chat/completions`.
 * @public
 */
declare type ChatCompletionsBaseURL = string;

/**
 * The model id the service expects, such as `gpt-4o-mini`. This is sent to the service as-is, not as a `providerName/model` reference.
 * @public
 */
declare type ChatCompletionsModel = string;

/**
 * Time interval in milliseconds for periodic checks (alternative to chunk count).
 * @public
 */
declare type CheckIntervalMs = number;

/**
 * A light JSON-path selector into the authenticated user's claims (request.user.data). Use dot notation for nested claims, e.g. 'address.country'. Use bracket notation with quotes for claim names that contain dots or slashes — namespaced claims — e.g. ["https://sts.amazonaws.com/"]["lambda_source_function_arn"]; the two notations may be mixed. A missing claim always fails the check.
 * @public
 */
declare type Claim = string;

/**
 * A single claim check using exactly one operator: eq, in, or startsWith.
 * @public
 */
declare type ClaimCheck = EqualsRule | InRule | StartsWithRule;

/**
 * Where the prompt is classified. Set `app.dialect` to select the API that classifier app exposes.
 * @public
 */
declare interface Classifier {
  app?: ClassifierApp;
  chatCompletions?: ChatCompletionsAPI;
  jev?: JevTypeSafe;
}

/**
 * Classify with another AI Gateway app in this project. The call runs in-process and never leaves the gateway, so the classifier uses that app's providers, routing, and quotas.
 * @public
 */
declare interface ClassifierApp {
  appId: ClassifierAppID_2;
  model: ClassifierModel_2;
  apiKey?: ClassifierAppAPIKey;
  dialect?: ClassifierAppDialect;
  adapter?: ClassifierAppAdapterDeprecated;
}

/**
 * **Deprecated**: use `classifier.app.dialect` instead. Still honored when `dialect` is not set; setting both is a configuration error.
 * @public
 */
declare type ClassifierAppAdapterDeprecated =
  | "chat-completions"
  | "messages"
  | "system-one";

/**
 * API key sent as `Authorization: Bearer` when invoking the classifier app. Omit it when the classifier app runs the Internal Only policy: the classifier call never leaves the gateway, so that policy accepts it and rejects everything arriving over the network, and no credential is sent. Set it only when the classifier app authenticates callers with API keys.
 * @public
 */
declare type ClassifierAppAPIKey = string;

/**
 * **Deprecated**: use `classifier.app.apiKey` instead. Still honored when `classifier` is not set; setting both is a configuration error.
 * @public
 */
declare type ClassifierAppAPIKeyDeprecated = string;

/**
 * API contract exposed by the classifier app. `chat-completions` calls /v1/chat/completions; `messages` calls /v1/messages for Claude models that support structured outputs (`output_config.format`), such as `claude-haiku-4-5`, on a provider whose Messages endpoint accepts them (not Amazon Bedrock Mantle); `system-one` calls /v1/systemone for models such as Jev. The app owns provider credentials, pricing, metering and analytics.
 * @public
 */
declare type ClassifierAppDialect =
  | "chat-completions"
  | "messages"
  | "system-one";

/**
 * Run the classifier on another AI Gateway app instead of calling an external API directly. The gateway invokes that app in-process — no outbound HTTP hop — so the classifier inherits its provider credentials, model routing, fallbacks and quotas, and provider keys stay on one app. Give that app the Internal Only policy and `apiKey` is not needed at all. When set, `model` must name a routed model as `provider/model` and `baseUrl` must not be set. The target app must not itself run this policy: it would be asked to classify its own classification request, which is rejected as a configuration error rather than silently skipped. Omit to call `baseUrl` directly.
 * @public
 */
declare type ClassifierAppID = string;

/**
 * The id of the AI Gateway app that runs the classifier. It must not be this app, and that app must not run this policy.
 * @public
 */
declare type ClassifierAppID_2 = string;

/**
 * **Deprecated**: use `classifier.app.appId` instead. Still honored when `classifier` is not set; setting both is a configuration error.
 * @public
 */
declare type ClassifierAppIDDeprecated = string;

/**
 * Tool-calling capable model used to classify prompts. Prefer a small, fast model; the classification runs before every inspected request reaches the upstream model. With `appId` set this must name a model the classifier app routes, written as `provider/model` (for example `openai/gpt-4o-mini`), and has no default.
 * @public
 */
declare type ClassifierModel = string;

/**
 * The model (`providerName/model`) the classifier app uses to evaluate the user's request. `providerName` is the name of the provider as configured on the classifier app, not a fixed vendor id. E.g. `openai/gpt-4o-mini`, `anthropic/claude-haiku-4-5` with the `messages` dialect, or `jev/jev-latest` when the Jev provider is named `jev`.
 * @public
 */
declare type ClassifierModel_2 = string;

/**
 * **Deprecated**: use `classifier.app.model` instead. Still honored when `classifier` is not set; setting both is a configuration error.
 * @public
 */
declare type ClassifierModelDeprecated = string;

/**
 * Replaces the built-in system prompt that tells the classifier what counts as a prompt injection. A string, or an array of lines joined with newlines. The inspected text is always sent as a separate user message and the verdict always comes back through the fixed SAFE/UNSAFE tool call, so a custom prompt changes what is flagged, never how the verdict is read. Omit to use the built-in prompt, which the policy documentation shows in full.
 * @public
 */
declare type ClassifierPrompt = string | [string, ...string[]];

/**
 * Prompt for classifier.app (its default `chat-completions` dialect or the `messages` dialect, where it is sent as the system prompt) and classifier.chatCompletions. Omit to use the built-in prompt. classifier.app.dialect `system-one` and classifier.jev take no prompt; combining them with classifierPrompt is a configuration error.
 * @public
 */
declare type ClassifierPrompt_2 = string | [string, ...string[]];

/**
 * Maximum time in milliseconds to wait for the classifier before applying the onError action.
 * @public
 */
declare type ClassifierTimeoutMs = number;

/**
 * Timeout configured for the classifier task. When exceeded, the request is forwarded without classification to the original model.
 * @public
 */
declare type ClassifierTimeoutMs_2 = number;

/**
 * Removes all headers from the incoming request except for those in the exclude list.
 *
 * @title Clear Request Headers
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const ClearHeadersInboundPolicy: InboundPolicyHandler<ClearHeadersInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface ClearHeadersInboundPolicyOptions {
  /**
   * The headers that should not be removed.
   */
  exclude?: string[];
}

/**
 * Removes all headers from the response except for those in the exclude list.
 *
 * @title Clear Response Headers
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const ClearHeadersOutboundPolicy: OutboundPolicyHandler<ClearHeadersOutboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface ClearHeadersOutboundPolicyOptions {
  /**
   * The headers that should not be removed.
   */
  exclude?: string[];
}

/**
 * Authenticate users using Clerk issued JWT tokens.
 *
 * @title Clerk JWT Auth
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const ClerkJwtInboundPolicy: InboundPolicyHandler<ClerkJwtInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface ClerkJwtInboundPolicyOptions {
  /**
   * Your Clerk Frontend API URL, i.e. `https://verb-noun-00.clerk.accounts.dev`. Can be found in the Clerk portal: https://dashboard.clerk.com/last-active?path=api-keys.
   */
  frontendApiUrl: string;
  /**
   * Allow unauthenticated requests to proceed. This is use useful if you want to use multiple authentication policies or if you want to allow both authenticated and non-authenticated traffic.
   */
  allowUnauthenticatedRequests?: boolean;
  /**
   * Enables OAuth 2.0 Protected Resource Metadata discovery (RFC 9728). When `true`, requests without a bearer token receive a 401 whose `WWW-Authenticate` header points `resource_metadata` at the `/.well-known/oauth-protected-resource` document for the request path and, when the `OAuthProtectedResourcePlugin` declares `scopesSupported`, lists those scopes in `scope`. Requires the `OAuthProtectedResourcePlugin` in `zuplo.runtime.ts` or a user-defined route at that path.
   */
  oAuthResourceMetadataEnabled?: boolean;
}

/** The client (browser/app) half of the policy. */
export declare interface ClientCacheDirectives {
  maxAge?: number;
  visibility?: CdnCacheControlClientVisibility;
  mustRevalidate?: boolean;
  noCache?: boolean;
}

/**
 * Authentication options for OIDC authentication.
 * @public
 */
declare interface ClientCredentialsConfig {
  /**
   * The type of authentication to use.
   */
  method: "client-credentials";
  /**
   * The client ID.
   */
  clientId: string;
  /**
   * The client secret.
   */
  clientSecret: string;
  /**
   * The oauth endpoint url.
   */
  oauthTokenEndpointUrl: string;
  /**
   * API Audience.
   */
  apiAudience?: string;
}

/**
 * Code interpreter tool
 */
declare interface CodeInterpreterTool {
  type: "code_interpreter";
  container:
    | string
    | {
        type: "auto";
        file_ids?: string[];
      };
}

/**
 * Authenticate requests with JWT tokens issued by AWS Cognito.
 *
 * @title AWS Cognito JWT Auth
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const CognitoJwtInboundPolicy: InboundPolicyHandler<CognitoJwtInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface CognitoJwtInboundPolicyOptions {
  /**
   * The AWS region where your Cognito instance is deployed.
   */
  region: string;
  /**
   * The user pool identifier.
   */
  userPoolId: string;
  /**
   * Allow unauthenticated requests to proceed. This is use useful if you want to use multiple authentication policies or if you want to allow both authenticated and non-authenticated traffic.
   */
  allowUnauthenticatedRequests?: boolean;
  /**
   * Enables OAuth 2.0 Protected Resource Metadata discovery (RFC 9728). When `true`, requests without a bearer token receive a 401 whose `WWW-Authenticate` header points `resource_metadata` at the `/.well-known/oauth-protected-resource` document for the request path and, when the `OAuthProtectedResourcePlugin` declares `scopesSupported`, lists those scopes in `scope`. Requires the `OAuthProtectedResourcePlugin` in `zuplo.runtime.ts` or a user-defined route at that path.
   */
  oAuthResourceMetadataEnabled?: boolean;
}

/**
 * The compatibility date on which to run the gateway
 */
declare type CompatibilityDate =
  | "2023-03-14"
  | "2024-01-15"
  | "2024-03-14"
  | "2024-09-02"
  | "2025-02-06"
  | "2026-03-01";

declare interface CompatibilityFlags {
  /**
   * Whether or not outbound policies should run if the response from the
   * handlers is not `response.ok`
   *
   * @compatibilityDate 2024-01-15
   */
  runOutboundPoliciesOnHandlerOnAllStatuses: boolean;
  /**
   * Whether or not hooks run on system routes
   *
   * @compatibilityDate 2024-01-15
   */
  doNotRunHooksOnSystemRoutes: boolean;
  /**
   * Remove all vendor (cf-, zp-) headers except for the specific
   * list of allowed headers
   *
   * @compatibilityDate 2024-01-15
   */
  removeAllVendorHeadersExceptListed: boolean;
  /**
   * Allow specifying a custom port when making a subrequest with
   * the fetch() API.
   *
   * This flag doesn't actually do anything in the runtime. It is a
   * workerd change. The flag is here only to generate a new compatibility
   * date.
   *
   * @compatibilityDate 2024-09-02
   */
  allowCustomPorts: boolean;
  /**
   * Whether or not to use the new logging system
   *
   * @compatibilityDate 2025-02-06
   */
  removeLegacyLogInitialization: boolean;
  /**
   * Whether or not to enable the followRedirects option on the URL Forward handler
   * NOTE: This flag was documented, but never implimented so its a breaking
   * change to enable it.
   * @compatibilityDate 2025-02-06
   */
  useForwardRedirectsPropOnUrlForwardHandler: boolean;
  /**
   * Whether response sending hooks should chain properly, where each hook
   * receives the response from the previous hook instead of the original response.
   *
   * Before this flag: All hooks received the original response, so only the last
   * hook's output was returned.
   *
   * After this flag: Hooks are chained properly, each receiving the previous
   * hook's response.
   *
   * @compatibilityDate 2026-03-01
   */
  chainResponseSendingHooks: boolean;
  /**
   * Whether to return 501 Not Implemented for unsupported HTTP methods
   * (e.g., WebDAV methods like PROPFIND, MKCOL, COPY).
   *
   * Before this flag: Unsupported HTTP methods returned 500 Internal Server Error.
   *
   * After this flag: Unsupported HTTP methods return 501 Not Implemented.
   *
   * @compatibilityDate 2026-03-01
   */
  return501ForUnsupportedHttpMethods: boolean;
  /**
   * Whether the MCP server handler leaves the non-standard
   * `capabilities.tools.supported` and `capabilities.tools.available` fields
   * out of its `initialize` response.
   *
   * Before this flag: `initialize` returns `supported: true` and lists every
   * registered tool name in `available`, to every caller.
   *
   * After this flag: `initialize` returns `capabilities.tools: {}`. Clients
   * discover tools with `tools/list`, as the MCP spec defines.
   */
  removeMcpToolsCapabilityExtension: boolean;
  /**
   * Whether the MCP server handler reports a `tools/call` whose arguments fail
   * the tool's `inputSchema` as a tool result with `isError: true`, as
   * MCP 2025-11-25 specifies for input validation errors.
   *
   * Before this flag: Invalid arguments return a JSON-RPC `-32602` error.
   *
   * After this flag: When the request's `MCP-Protocol-Version` header is
   * `2025-11-25` or later, invalid arguments return a result with
   * `isError: true` and the validation message as text content, and the tool
   * is not called. Earlier or missing protocol versions still return
   * `-32602`. Unknown tools and malformed requests return `-32602` either way.
   */
  returnMcpToolInputErrorsAsToolResults: boolean;
  /**
   * Before this flag: MCP input schemas are converted to Zod and back to JSON
   * Schema, and Zod may insert defaults or discard undeclared properties.
   * After this flag: the MCP SDK validates JSON Schema directly, preserving
   * constraints and input values. Defaults remain annotations. HTTP validation is unchanged.
   * Opt in only on the JavaScript runtimes (workerd and Zeno).
   */
  useMcpDirectSchemaValidation: boolean;
}

declare interface CompletionsFallbacks {
  fallback?: FallbackModel;
  quotaFallback?: QuotaFallbackModel;
}

/**
 * Models for chat completions, Responses, Messages, and System One requests, as `providerName/model`. From 1 through 32 models, each listed once. Provider names aren't case-sensitive, so `openai/gpt-5` and `OpenAI/gpt-5` are the same model. Write each model ID exactly as your provider spells it.
 *
 * @minItems 1
 * @maxItems 32
 * @public
 */
declare type CompletionsModels = [ProviderAndModel, ...ProviderAndModel[]];

/**
 * Rules for chat completions, Responses, and Anthropic Messages requests.
 * @public
 */
declare type CompletionsModels_2 =
  | {
      allowList: AllowedModels;
    }
  | {
      blockList: BlockedModels;
    };

/**
 * Rule for chat completions, Responses, and Anthropic Messages requests.
 * @public
 */
declare type CompletionsOverride =
  | {
      force: ForcedModel;
    }
  | {
      default: DefaultModel;
    };

/**
 * @public
 */
export declare interface ComplexCustomRateLimitDetails extends CustomRateLimitDetailsBase {
  limits?: Record<string, number>;
}

/**
 * Function type for complex rate limiting
 * @public
 */
export declare type ComplexRateLimitFunction =
  RateLimitFunction<ComplexCustomRateLimitDetails>;

/**
 * The Complex Rate Limiting policy is an advanced rate limiting policy that
 * let's you set rate limits based on custom counters (not just requests)
 *
 * @title Complex Rate Limiting
 * @product api-gateway
 * @enterprise
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare class ComplexRateLimitInboundPolicy extends InboundPolicy<ComplexRateLimitInboundPolicyOptions> {
  static readonly policyType = "complex-rate-limit";
  /**
   * Override the increments for a limit in the current request.
   *
   * @param context - The ZuploContext
   * @param increments - The increments to set.
   */
  static setIncrements(
    context: ZuploContext,
    increments: Record<string, number>
  ): void;
  static getIncrements(context: ZuploContext): Record<string, number>;
  constructor(
    options: ComplexRateLimitInboundPolicyOptions,
    policyName: string
  );
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<Response | ZuploRequest<RequestGeneric>>;
}

/**
 * The options for this policy.
 * @public
 */
export declare interface ComplexRateLimitInboundPolicyOptions {
  rateLimitBy: RateLimitByType;
  /**
   * A dictionary (string: number) of limits to be enforced across custom counters for this policy.
   */
  limits: {
    [k: string]: number;
  };
  /**
   * The time window in which the requests are rate-limited. The count restarts after each window expires.
   */
  timeWindowMinutes: number;
  /**
   * The function that returns dynamic configuration data. Used only with `rateLimitBy=function`.
   */
  identifier?: {
    /**
     * used only with rateLimitBy=function. Specifies the export to load your custom bucket function, e.g. `default`, `rateLimitIdentifier`.
     */
    export: string;
    /**
     * Specifies the module to load your custom bucket function, in the format `$import(./modules/my-module)`.
     */
    module: string;
  };
  headerMode?: RateLimitHeaderMode;
  /**
   * If true, the policy will throw an error in the event there is a problem connecting to the rate limit service.
   */
  throwOnFailure?: boolean;
  mode?: RateLimitMode;
}

/**
 * Creates a composite, or group policy - composed of other inbound policies. For reuse across routes.
 *
 * @title Composite Inbound (Group Policies)
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const CompositeInboundPolicy: InboundPolicyHandler<CompositeInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface CompositeInboundPolicyOptions {
  /**
   * The list of policy references (beware circular references).
   */
  policies?: string[];
}

/**
 * Creates a composite, or group policy - composed of other outbound policies. For reuse across routes.
 *
 * @title Composite Outbound (Group Policies)
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const CompositeOutboundPolicy: OutboundPolicyHandler<CompositeOutboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface CompositeOutboundPolicyOptions {
  /**
   * The list of policy references (beware circular references).
   */
  policies?: string[];
}

/**
 * Computer use tool (preview)
 */
declare interface ComputerUseTool {
  type: "computer_use_preview";
  display_height: number;
  display_width: number;
  environment: "windows" | "mac" | "linux" | "ubuntu" | "browser";
}

/**
 * Errors caused by invalid user configuration such as invalid parameters on policies,
 * handlers that are not functions, or missing required configuration values.
 *
 * @public
 * @example
 * ```typescript
 * import { ConfigurationError } from "@zuplo/runtime";
 *
 * // In a policy
 * export const myPolicy: InboundPolicy = async (request, context, options) => {
 *   if (!options.apiKey) {
 *     throw new ConfigurationError(
 *       "API key is required in policy configuration"
 *     );
 *   }
 *
 *   if (typeof options.timeout !== "number" || options.timeout < 0) {
 *     throw new ConfigurationError(
 *       "Timeout must be a positive number"
 *     );
 *   }
 *
 *   // Policy logic...
 * };
 * ```
 */
export declare class ConfigurationError extends RuntimeError {
  constructor(message: string, options?: ErrorOptions);
}

/**
 * The configuration ID of the AI Firewall.
 * @public
 */
declare type ConfigurationID = string;

/* Excluded from this release type: ContentTypes */

/**
 * Utility for storing data across the lifecycle of a request. This class is
 * useful for storing and retrieving data that is shared between policies.
 *
 * @public
 *
 * @example
 * Using static methods
 * ```typescript
 * import { ContextData, ZuploContext } from "@zuplo/runtime";
 *
 * // In a policy or handler
 * ContextData.set(context, "my-data", { prop1: "hello world" });
 *
 * // Later in the pipeline
 * const data = ContextData.get(context, "my-data");
 * console.log(data?.prop1); // "hello world"
 * ```
 *
 * @example
 * Reusable class shared across modules
 *
 * The shared module allows other modules to access the same storage without
 * passing the string name or type around.
 *
 * ```typescript
 * // shared-data.ts
 * import { ContextData } from "@zuplo/runtime";
 *
 * interface UserData {
 *   userId: string;
 *   roles: string[];
 * }
 *
 * export const userData = new ContextData<UserData>("user-data");
 * ```
 *
 * Then use the class in another module.
 *
 * ```typescript
 * // policy.ts
 * import { userData } from "./shared-data.js";
 * import { InboundPolicy, ZuploContext, ZuploRequest } from "@zuplo/runtime";
 *
 * export const authenticateUser: InboundPolicy = async (
 *   request: ZuploRequest,
 *   context: ZuploContext
 * ) => {
 *   // Store user data after authentication
 *   userData.set(context, {
 *     userId: "user-123",
 *     roles: ["admin", "user"]
 *   });
 *
 *   return request;
 * };
 *
 * // handler.ts
 * import { userData } from "./shared-data.js";
 *
 * export function myHandler(request: ZuploRequest, context: ZuploContext) {
 *   const user = userData.get(context);
 *   if (user?.roles.includes("admin")) {
 *     // Handle admin access
 *   }
 * }
 * ```
 */
export declare class ContextData<T = any> {
  #private;
  /**
   * Creates a new ContextData instance for type-safe context storage.
   * @param name - A unique string or symbol identifier for this data
   */
  constructor(name: string | symbol);
  /**
   * Retrieves data from the context stored under this instance's name.
   * @param context - The ZuploContext to retrieve data from
   * @returns The stored data or undefined if not found
   */
  get(context: ZuploContext): T | undefined;
  /**
   * Retrieves data from the context stored under the specified name.
   * @param context - The ZuploContext to retrieve data from
   * @param name - The unique identifier for the data
   * @returns The stored data or undefined if not found
   */
  static get<T = any>(
    context: ZuploContext,
    name: string | symbol
  ): T | undefined;
  /**
   * Stores data in the context under this instance's name.
   * @param context - The ZuploContext to store data in
   * @param data - The data to store
   */
  set(context: ZuploContext, data: T): void;
  /**
   * Stores data in the context under the specified name.
   * @param context - The ZuploContext to store data in
   * @param name - The unique identifier for this data
   * @param data - The data to store
   */
  static set<T = any>(
    context: ZuploContext,
    name: string | symbol,
    data: T
  ): void;
}

/**
 * The 2-letter continent codes Cloudflare uses
 * @public
 */
declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA";

/**
 * @public
 */
export declare type CorsPolicy = string | "anything-goes" | "none";

/**
 * @public
 */
export declare interface CorsPolicyConfiguration {
  name: string;
  allowCredentials?: boolean;
  maxAge?: number;
  allowedOrigins: string[] | string;
  allowedMethods?: HttpMethod[] | string;
  allowedHeaders?: string[] | string;
  exposeHeaders?: string[] | string;
}

declare class Cron {
  readonly seconds: readonly number[];
  readonly minutes: readonly number[];
  readonly hours: readonly number[];
  readonly days: readonly number[];
  readonly months: readonly number[];
  readonly weekdays: readonly number[];
  readonly reversed: {
    seconds: readonly number[];
    minutes: readonly number[];
    hours: readonly number[];
    days: readonly number[];
    months: readonly number[];
    weekdays: readonly number[];
  };
  constructor({
    seconds,
    minutes,
    hours,
    days,
    months,
    weekdays,
  }: CronDefinition);
  /**
   * Find the next or previous hour, starting from the given start hour that matches the hour constraint.
   * startHour itself might also be allowed.
   */
  private findAllowedHour;
  /**
   * Find the next or previous minute, starting from the given start minute that matches the minute constraint.
   * startMinute itself might also be allowed.
   */
  private findAllowedMinute;
  /**
   * Find the next or previous second, starting from the given start second that matches the second constraint.
   * startSecond itself IS NOT allowed.
   */
  private findAllowedSecond;
  /**
   * Find the next or previous time, starting from the given start time that matches the hour, minute
   * and second constraints. startTime itself might also be allowed.
   */
  private findAllowedTime;
  /**
   * Find the next or previous day in the given month, starting from the given startDay
   * that matches either the day or the weekday constraint. startDay itself might also be allowed.
   */
  private findAllowedDayInMonth;
  /** Gets the next date starting from the given start date or now. */
  getNextDate(startDate?: Date): Date;
  /** Gets the specified amount of future dates starting from the given start date or now. */
  getNextDates(amount: number, startDate?: Date): Date[];
  /**
   * Get an ES6 compatible iterator which iterates over the next dates starting from startDate or now.
   * The iterator runs until the optional endDate is reached or forever.
   */
  getNextDatesIterator(
    startDate?: Date,
    endDate?: Date
  ): Generator<Date, undefined, undefined>;
  /** Gets the previous date starting from the given start date or now. */
  getPrevDate(startDate?: Date): Date;
  /** Gets the specified amount of previous dates starting from the given start date or now. */
  getPrevDates(amount: number, startDate?: Date): Date[];
  /**
   * Get an ES6 compatible iterator which iterates over the previous dates starting from startDate or now.
   * The iterator runs until the optional endDate is reached or forever.
   */
  getPrevDatesIterator(
    startDate?: Date,
    endDate?: Date
  ): Generator<Date, undefined, undefined>;
  /** Returns true when there is a cron date at the given date. */
  matchDate(date: Date): boolean;
}

/**
 * An object with contains for each element of a date, which values are allowed.
 * Everything starting at 0, except for days.
 */
declare interface CronDefinition {
  readonly seconds: Set<number>;
  readonly minutes: Set<number>;
  readonly hours: Set<number>;
  readonly days: Set<number>;
  readonly months: Set<number>;
  readonly weekdays: Set<number>;
}

/**
 * @deprecated Use standard `crypto` API instead.
 * @public
 */
export declare class CryptoBeta extends BaseCryptoBeta {
  digest(algorithm: string, data: string): Promise<string>;
}

/**
 * Authenticate users using the Curity Phantom Token Pattern.
 *
 * @title Curity Phantom Token Auth
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const CurityPhantomTokenInboundPolicy: InboundPolicyHandler<CurityPhantomTokenInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface CurityPhantomTokenInboundPolicyOptions {
  /**
   * The client ID of the Curity application.
   */
  clientId: string;
  /**
   * The client secret of the Curity application.
   */
  clientSecret: string;
  /**
   * The introspection URL of the Curity application.
   */
  introspectionUrl: string;
  /**
   * The duration in seconds to cache the introspected response.
   */
  cacheDurationSeconds?: number;
}

declare type CustomLogFields = Record<string, number | string | boolean>;

/**
 * Custom rate limit details that can override policy options.
 * @public
 */
export declare interface CustomRateLimitDetails extends CustomRateLimitDetailsBase {
  requestsAllowed?: number;
}

declare interface CustomRateLimitDetailsBase {
  key: string;
  timeWindowMinutes?: number;
}

/**
 * Function type for custom rate limiting
 * @public
 */
export declare type CustomRateLimitFunction =
  RateLimitFunction<CustomRateLimitDetails>;

/**
 * Custom tool
 */
declare interface CustomTool {
  name: string;
  type: "custom";
  description?: string;
  format?: Record<string, unknown>;
}

declare interface DataDogLoggingOptions {
  url?: string;
  apiKey: string;
  /**
   * The source of the logs. This is typically the name of the application or service.
   */
  source?: string;
  /**
   * Any custom log fields to include in each log entry.
   */
  fields?: CustomLogFields;
  /**
   * Any custom tags to include in each log entry.
   */
  tags?: Record<string, unknown>;
}

/**
 * DataDog logging plugin
 * @public
 */
export declare class DataDogLoggingPlugin extends LogPlugin {
  private options;
  constructor(options: DataDogLoggingOptions);
  /* Excluded from this release type: getTransport */
}

declare interface DataDogMetricsContext {
  tags: string[];
}

declare interface DataDogMetricsOptions {
  url?: string;
  apiKey: string;
  tags?: string[];
  metrics?: MetricsType;
  include?: IncludeMetrics;
  metricMode?: "seriesMode" | "distributionMode";
}

/**
 * DataDog metrics plugin
 * @public
 */
export declare class DataDogMetricsPlugin extends MetricsPlugin {
  #private;
  private options;
  constructor(options: DataDogMetricsOptions);
  /* Excluded from this release type: getTransport */
  static setContext(context: ZuploContext, data: DataDogMetricsContext): void;
}

/**
 * Scans the incoming request body for sensitive data — PII, secrets, and
 * financial identifiers — using an extensible catalog of built-in recognizers
 * plus any custom patterns, and takes a configurable action when a match is
 * found.
 *
 * The action is one of `mask` (redact matches before forwarding the request),
 * `block` (reject with a `422` listing the detected entity names only), or
 * `log` (record a warning and forward unchanged). Only text content types are
 * inspected; binary bodies pass through untouched, and the body is read from a
 * clone so the upstream still receives the original stream.
 *
 * @title Data Loss Prevention
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const DataLossPreventionInboundPolicy: InboundPolicyHandler<DataLossPreventionInboundPolicyOptions>;

/**
 * The options for the Data Loss Prevention inbound policy. Scans the incoming request body for sensitive data and applies the configured action (mask, block, or log).
 * @public
 */
export declare interface DataLossPreventionInboundPolicyOptions {
  /**
   * The detection engine. Only `builtin` (in-isolate regex + checksum detection with context-word scoring) is available today. This is the extension point for a future hosted `presidio-service` mode; declaring it now keeps adding that mode an additive, non-breaking change.
   */
  engine?: "builtin";
  /**
   * Built-in recognizer ids and/or group selectors to enable. Entity ids follow a {category}-{scope}-{name} taxonomy, and any dash-aligned id prefix acts as a selector (for example `secret` is every secret, `id-au` is Australia's identifiers, `secret-aws` is both AWS entities), plus the named groups `pii` and `region-eu`. Available selectors: `contact`, `finance`, `finance-us`, `id`, `id-au`, `id-br`, `id-ca`, `id-es`, `id-fr`, `id-in`, `id-it`, `id-nl`, `id-pl`, `id-sg`, `id-uk`, `id-us`, `network`, `pii`, `region-eu`, `secret`, `secret-aws`. When omitted, the full built-in catalog is used.
   */
  entities?: (
    | "contact"
    | "finance"
    | "finance-us"
    | "id"
    | "id-au"
    | "id-br"
    | "id-ca"
    | "id-es"
    | "id-fr"
    | "id-in"
    | "id-it"
    | "id-nl"
    | "id-pl"
    | "id-sg"
    | "id-uk"
    | "id-us"
    | "network"
    | "pii"
    | "region-eu"
    | "secret"
    | "secret-aws"
    | "contact-email"
    | "contact-phone"
    | "finance-credit-card"
    | "finance-crypto-wallet"
    | "finance-cvv"
    | "finance-iban"
    | "finance-swift-bic"
    | "finance-us-aba-routing"
    | "finance-us-bank-account"
    | "id-au-abn"
    | "id-au-acn"
    | "id-au-medicare"
    | "id-au-tfn"
    | "id-br-cpf"
    | "id-ca-sin"
    | "id-es-nif"
    | "id-fr-nir"
    | "id-in-aadhaar"
    | "id-in-pan"
    | "id-it-fiscal-code"
    | "id-nl-bsn"
    | "id-pl-pesel"
    | "id-sg-nric"
    | "id-uk-nhs"
    | "id-uk-nino"
    | "id-us-itin"
    | "id-us-passport"
    | "id-us-ssn"
    | "network-ipv4"
    | "network-ipv6"
    | "network-mac"
    | "secret-anthropic"
    | "secret-aws-access-key"
    | "secret-aws-bedrock"
    | "secret-azure-client"
    | "secret-databricks"
    | "secret-digitalocean"
    | "secret-discord-webhook"
    | "secret-github"
    | "secret-gitlab"
    | "secret-google-api-key"
    | "secret-heroku"
    | "secret-hugging-face"
    | "secret-jwt"
    | "secret-mailchimp"
    | "secret-mailgun"
    | "secret-npm"
    | "secret-openai"
    | "secret-perplexity"
    | "secret-postman"
    | "secret-private-key"
    | "secret-pypi"
    | "secret-sendgrid"
    | "secret-sentry"
    | "secret-shopify"
    | "secret-slack"
    | "secret-square"
    | "secret-stripe"
    | "secret-telegram-bot"
    | "secret-terraform"
    | "secret-twilio"
    | "secret-zuplo"
  )[];
  /**
   * What to do when sensitive data is detected. `mask` redacts matches before forwarding the request, `block` rejects with a 422 listing only the detected entity names, and `log` records a warning and forwards the request unchanged.
   */
  action?: "mask" | "block" | "log";
  /**
   * The string that replaces detected values when `action` is `mask`.
   */
  mask?: string;
  /**
   * Additional customer-defined regex recognizers. Invalid patterns are logged and skipped rather than failing the request.
   */
  customPatterns?: DlpCustomPattern[];
  /**
   * Values that are never reported as findings, compared against the exact matched text (case-sensitive, separators included). Use this to exempt well-known non-sensitive values that share a sensitive shape — for example the Stripe test card number `4242 4242 4242 4242` in a payments sandbox, or a public support email address. List every written form you want to allow (a spaced and an unspaced card number are different matches).
   */
  allowValues?: string[];
  /**
   * Minimum confidence (0-1) a match must reach to count as a finding. Every match starts at its recognizer's base confidence and gains a fixed boost of 0.45 when one of the recognizer's context words appears near it. Ambiguous shapes (for example `finance-us-bank-account` or `finance-cvv`) have a low base confidence and only cross the default threshold of 0.5 with that boost; lower the threshold to surface them without context. Raising the threshold is not a precision filter: any recognizer whose base confidence falls below it stops matching entirely except near its context words, and most checksum-validated recognizers run at 0.85, so values above 0.85 disable most of the catalog. To narrow detection, scope the `entities` list instead.
   */
  minConfidence?: number;
  /**
   * Override the set of scannable content-type prefixes. When omitted, the built-in text content-type allow-list (JSON, XML, form-encoded, text/*) is used.
   */
  contentTypes?: string[];
}

/**
 * Scans the upstream response body for sensitive data — PII, secrets, and
 * financial identifiers — using an extensible catalog of built-in recognizers
 * plus any custom patterns, and takes a configurable action when a match is
 * found.
 *
 * The action is one of `mask` (redact matches before returning the response),
 * `block` (replace the response with a `422` listing the detected entity names
 * only), or `log` (record a warning and return unchanged). Only text content
 * types are inspected; binary bodies pass through untouched, and the body is
 * read from a clone so the client still receives the original stream.
 *
 * @title Data Loss Prevention
 * @product api-gateway
 * @public
 * @param response - The outgoing Response from the handler
 * @param request - The original incoming Request
 * @param context - The current context of the Request
 * @param options - The configuration options for the policy
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Response
 */
export declare const DataLossPreventionOutboundPolicy: OutboundPolicyHandler<DataLossPreventionOutboundPolicyOptions>;

/**
 * The options for the Data Loss Prevention outbound policy. Scans the upstream response body for sensitive data and applies the configured action (mask, block, or log).
 * @public
 */
export declare interface DataLossPreventionOutboundPolicyOptions {
  /**
   * The detection engine. Only `builtin` (in-isolate regex + checksum detection with context-word scoring) is available today. This is the extension point for a future hosted `presidio-service` mode; declaring it now keeps adding that mode an additive, non-breaking change.
   */
  engine?: "builtin";
  /**
   * Built-in recognizer ids and/or group selectors to enable. Entity ids follow a {category}-{scope}-{name} taxonomy, and any dash-aligned id prefix acts as a selector (for example `secret` is every secret, `id-au` is Australia's identifiers, `secret-aws` is both AWS entities), plus the named groups `pii` and `region-eu`. Available selectors: `contact`, `finance`, `finance-us`, `id`, `id-au`, `id-br`, `id-ca`, `id-es`, `id-fr`, `id-in`, `id-it`, `id-nl`, `id-pl`, `id-sg`, `id-uk`, `id-us`, `network`, `pii`, `region-eu`, `secret`, `secret-aws`. When omitted, the full built-in catalog is used.
   */
  entities?: (
    | "contact"
    | "finance"
    | "finance-us"
    | "id"
    | "id-au"
    | "id-br"
    | "id-ca"
    | "id-es"
    | "id-fr"
    | "id-in"
    | "id-it"
    | "id-nl"
    | "id-pl"
    | "id-sg"
    | "id-uk"
    | "id-us"
    | "network"
    | "pii"
    | "region-eu"
    | "secret"
    | "secret-aws"
    | "contact-email"
    | "contact-phone"
    | "finance-credit-card"
    | "finance-crypto-wallet"
    | "finance-cvv"
    | "finance-iban"
    | "finance-swift-bic"
    | "finance-us-aba-routing"
    | "finance-us-bank-account"
    | "id-au-abn"
    | "id-au-acn"
    | "id-au-medicare"
    | "id-au-tfn"
    | "id-br-cpf"
    | "id-ca-sin"
    | "id-es-nif"
    | "id-fr-nir"
    | "id-in-aadhaar"
    | "id-in-pan"
    | "id-it-fiscal-code"
    | "id-nl-bsn"
    | "id-pl-pesel"
    | "id-sg-nric"
    | "id-uk-nhs"
    | "id-uk-nino"
    | "id-us-itin"
    | "id-us-passport"
    | "id-us-ssn"
    | "network-ipv4"
    | "network-ipv6"
    | "network-mac"
    | "secret-anthropic"
    | "secret-aws-access-key"
    | "secret-aws-bedrock"
    | "secret-azure-client"
    | "secret-databricks"
    | "secret-digitalocean"
    | "secret-discord-webhook"
    | "secret-github"
    | "secret-gitlab"
    | "secret-google-api-key"
    | "secret-heroku"
    | "secret-hugging-face"
    | "secret-jwt"
    | "secret-mailchimp"
    | "secret-mailgun"
    | "secret-npm"
    | "secret-openai"
    | "secret-perplexity"
    | "secret-postman"
    | "secret-private-key"
    | "secret-pypi"
    | "secret-sendgrid"
    | "secret-sentry"
    | "secret-shopify"
    | "secret-slack"
    | "secret-square"
    | "secret-stripe"
    | "secret-telegram-bot"
    | "secret-terraform"
    | "secret-twilio"
    | "secret-zuplo"
  )[];
  /**
   * What to do when sensitive data is detected. `mask` redacts matches before returning the response, `block` replaces the response with a 422 listing only the detected entity names, and `log` records a warning and returns the response unchanged.
   */
  action?: "mask" | "block" | "log";
  /**
   * The string that replaces detected values when `action` is `mask`.
   */
  mask?: string;
  /**
   * Additional customer-defined regex recognizers. Invalid patterns are logged and skipped rather than failing the response.
   */
  customPatterns?: DlpCustomPattern_2[];
  /**
   * Values that are never reported as findings, compared against the exact matched text (case-sensitive, separators included). Use this to exempt well-known non-sensitive values that share a sensitive shape — for example the Stripe test card number `4242 4242 4242 4242` in a payments sandbox, or a public support email address. List every written form you want to allow (a spaced and an unspaced card number are different matches).
   */
  allowValues?: string[];
  /**
   * Minimum confidence (0-1) a match must reach to count as a finding. Every match starts at its recognizer's base confidence and gains a fixed boost of 0.45 when one of the recognizer's context words appears near it. Ambiguous shapes (for example `finance-us-bank-account` or `finance-cvv`) have a low base confidence and only cross the default threshold of 0.5 with that boost; lower the threshold to surface them without context. Raising the threshold is not a precision filter: any recognizer whose base confidence falls below it stops matching entirely except near its context words, and most checksum-validated recognizers run at 0.85, so values above 0.85 disable most of the catalog. To narrow detection, scope the `entities` list instead.
   */
  minConfidence?: number;
  /**
   * Override the set of scannable content-type prefixes. When omitted, the built-in text content-type allow-list (JSON, XML, form-encoded, text/*) is used.
   */
  contentTypes?: string[];
}

/**
 * Default function to generate Hydrolix log entries
 * @public
 */
export declare const defaultGenerateHydrolixEntry: GenerateRequestLoggerEntry<HydrolixDefaultEntry>;

/**
 * The model used only when a request does not select one.
 * @public
 */
declare type DefaultModel = string;

/**
 * The model used only when a request does not select one.
 * @public
 */
declare type DefaultModel1 = string;

/* Excluded from this release type: DevPortalRuntimeConfig */

declare type DevPortalType = "legacy" | "zudoku";

/**
 * @public
 */
export declare type DispatchFunction<TPayload> = (
  batch: TPayload[]
) => Promise<void>;

/**
 * Function to dispatch request logger entries
 * @public
 */
export declare interface DispatchRequestLoggerEntries<T> {
  (entries: T[]): Promise<void>;
}

declare interface DlpCustomPattern {
  /**
   * Identifier reported in findings and block details for this pattern.
   */
  name: string;
  /**
   * A JavaScript regular expression source string. Remember to escape backslashes for JSON (for example `\\d` for a digit).
   */
  pattern: string;
  /**
   * Base confidence (0-1) for matches of this pattern. The default of 0.85 is above the default detection threshold; combine a low value with `context` words for patterns that are only sensitive in context.
   */
  confidence?: number;
  /**
   * Context words that boost a match's confidence by 0.45 when one appears near the match (in the surrounding field, label, or key).
   */
  context?: string[];
}

declare interface DlpCustomPattern_2 {
  /**
   * Identifier reported in findings and block details for this pattern.
   */
  name: string;
  /**
   * A JavaScript regular expression source string. Remember to escape backslashes for JSON (for example `\\d` for a digit).
   */
  pattern: string;
  /**
   * Base confidence (0-1) for matches of this pattern. The default of 0.85 is above the default detection threshold; combine a low value with `context` words for patterns that are only sensitive in context.
   */
  confidence?: number;
  /**
   * Context words that boost a match's confidence by 0.45 when one appears near the match (in the surrounding field, label, or key).
   */
  context?: string[];
}

declare interface DlpCustomRule {
  /**
   * The detector's name — the key you use to activate it inside `rules.inbound` or `rules.outbound`, exactly like a built-in type id. Must be distinct and must not reuse a built-in type id or group selector.
   */
  name: string;
  /**
   * A JavaScript regular expression source string. Remember to escape backslashes for JSON (for example `\\d` for a digit). An invalid pattern fails the configuration at request time — a broken guardrail never degrades into a silent pass-through.
   */
  pattern: string;
  /**
   * Context words for this detector. An activation with `detection: "corroborated"` then only fires when one of these words appears near the match.
   */
  context?: string[];
}

/**
 * What to find in this direction and what to do about it. Each key is a built-in data type id (like `id-us-ssn`), a group selector (like `pii` or `secret`, plus any dash-aligned id prefix such as `secret-aws`), or one of your custom detectors by name; each value is a rule object whose required `action` says what happens on a match. Types you do not mention are not scanned in this direction. The most specific key wins — an exact id beats a prefix beats a group — and the winning entry decides everything for its type in this direction. When one stretch of text matches multiple rules, the severest action wins (block > mask > log).
 * @public
 */
declare interface DlpDirectionRules {
  contact?: DlpRule;
  finance?: DlpRule;
  "finance-us"?: DlpRule;
  id?: DlpRule;
  "id-au"?: DlpRule;
  "id-br"?: DlpRule;
  "id-ca"?: DlpRule;
  "id-es"?: DlpRule;
  "id-fr"?: DlpRule;
  "id-in"?: DlpRule;
  "id-it"?: DlpRule;
  "id-nl"?: DlpRule;
  "id-pl"?: DlpRule;
  "id-sg"?: DlpRule;
  "id-uk"?: DlpRule;
  "id-us"?: DlpRule;
  network?: DlpRule;
  pii?: DlpRule;
  "region-eu"?: DlpRule;
  secret?: DlpRule;
  "secret-aws"?: DlpRule;
  "contact-email"?: DlpRule;
  "contact-phone"?: DlpRule;
  "finance-credit-card"?: DlpRule;
  "finance-crypto-wallet"?: DlpRule;
  "finance-cvv"?: DlpRule;
  "finance-iban"?: DlpRule;
  "finance-swift-bic"?: DlpRule;
  "finance-us-aba-routing"?: DlpRule;
  "finance-us-bank-account"?: DlpRule;
  "id-au-abn"?: DlpRule;
  "id-au-acn"?: DlpRule;
  "id-au-medicare"?: DlpRule;
  "id-au-tfn"?: DlpRule;
  "id-br-cpf"?: DlpRule;
  "id-ca-sin"?: DlpRule;
  "id-es-nif"?: DlpRule;
  "id-fr-nir"?: DlpRule;
  "id-in-aadhaar"?: DlpRule;
  "id-in-pan"?: DlpRule;
  "id-it-fiscal-code"?: DlpRule;
  "id-nl-bsn"?: DlpRule;
  "id-pl-pesel"?: DlpRule;
  "id-sg-nric"?: DlpRule;
  "id-uk-nhs"?: DlpRule;
  "id-uk-nino"?: DlpRule;
  "id-us-itin"?: DlpRule;
  "id-us-passport"?: DlpRule;
  "id-us-ssn"?: DlpRule;
  "network-ipv4"?: DlpRule;
  "network-ipv6"?: DlpRule;
  "network-mac"?: DlpRule;
  "secret-anthropic"?: DlpRule;
  "secret-aws-access-key"?: DlpRule;
  "secret-aws-bedrock"?: DlpRule;
  "secret-azure-client"?: DlpRule;
  "secret-databricks"?: DlpRule;
  "secret-digitalocean"?: DlpRule;
  "secret-discord-webhook"?: DlpRule;
  "secret-github"?: DlpRule;
  "secret-gitlab"?: DlpRule;
  "secret-google-api-key"?: DlpRule;
  "secret-heroku"?: DlpRule;
  "secret-hugging-face"?: DlpRule;
  "secret-jwt"?: DlpRule;
  "secret-mailchimp"?: DlpRule;
  "secret-mailgun"?: DlpRule;
  "secret-npm"?: DlpRule;
  "secret-openai"?: DlpRule;
  "secret-perplexity"?: DlpRule;
  "secret-postman"?: DlpRule;
  "secret-private-key"?: DlpRule;
  "secret-pypi"?: DlpRule;
  "secret-sendgrid"?: DlpRule;
  "secret-sentry"?: DlpRule;
  "secret-shopify"?: DlpRule;
  "secret-slack"?: DlpRule;
  "secret-square"?: DlpRule;
  "secret-stripe"?: DlpRule;
  "secret-telegram-bot"?: DlpRule;
  "secret-terraform"?: DlpRule;
  "secret-twilio"?: DlpRule;
  "secret-zuplo"?: DlpRule;
  [k: string]: unknown;
}

declare interface DlpPartialMask {
  /**
   * Keep the last N characters of the matched value unmasked and replace the rest with `*`, preserving length (for example `**** **** **** 4242`). Values no longer than N characters are fully masked.
   */
  keepLast: number;
}

declare interface DlpRule {
  /**
   * What happens when this rule matches in this direction. `mask` replaces the matched text with a placeholder and the conversation continues; `block` rejects the request or terminates the response with an error naming only the detected types (never the values); `log` records a finding and lets the traffic pass unchanged — use it to trial a rule before enforcing it; `off` excludes this type from a group enabled by a broader key in the same section.
   */
  action: "mask" | "block" | "log" | "off";
  /**
   * How much evidence a match needs before this rule acts. `corroborated` additionally requires one of the type's context words near the match (types that define no context words behave as `standard`); `standard` uses the catalog as tuned — distinctive shapes act on their own while ambiguous shapes need nearby context; `aggressive` counts every pattern match and is false-positive-prone — pair it with the `log` action for audits. Overrides the policy-level `detection` for this rule.
   */
  detection?: "corroborated" | "standard" | "aggressive";
  /**
   * Replacement text for this rule's masked matches. The `{type}` token inserts the detected type id in UPPER_SNAKE form, so the default turns a matched email into `[CONTACT_EMAIL]` — typed placeholders keep masked conversations legible to the model. Set a literal like `[REDACTED]` to hide the type.
   */
  mask?: string;
  partialMask?: DlpPartialMask;
}

/**
 * The scan configuration, split by direction: `inbound` covers what callers send the model (system prompt, message text, and tool-call arguments); `outbound` covers what the model sends back (buffered responses whole, streaming responses as they stream). Each direction you include is scanned; each you omit is left untouched — there is no "both" shorthand and no mirroring, so wanting the same behavior on both sides means stating it in both sections. At least one section must enable at least one rule.
 * @public
 */
declare interface DlpRules {
  inbound?: DlpDirectionRules;
  outbound?: DlpDirectionRules;
}

/**
 * How streaming (SSE) responses are inspected. `stream` (the default) scans deltas as they flow, holding each chunk until the boundary scan that includes its successor passes — values split across chunks stay maskable at the cost of one chunk of latency. `buffer` collects the entire response and scans it once as one document — exact detection for values of any length, and a blocked response is a clean 400 because nothing has been delivered yet — at the cost of the client waiting for the full generation. `off` passes streaming responses through unscanned.
 * @public
 */
declare interface DlpStreamingSettings {
  /**
   * `stream` scans deltas in flight with the windowed scanner. `buffer` holds the entire response and scans it once, exactly like a non-streaming response: values of any length are caught (no carry window) and a block is a native 400 error instead of a mid-stream termination, but the client receives nothing until the model finishes. `off` skips scanning of streaming responses entirely, even when rules cover the outbound direction.
   */
  mode?: "stream" | "buffer" | "off";
  /**
   * Scan across chunk boundaries using a carried tail of already-scanned text. When false, each chunk is scanned alone and released immediately — lower cost, but values split across two chunks are missed. Applies to `stream` mode only.
   */
  boundaryScan?: boolean;
  /**
   * How many trailing characters are carried from one chunk into the next boundary scan. Bounds memory and re-scan cost; must be larger than the longest value you need to catch. Applies to `stream` mode only — `buffer` mode always scans the complete text.
   */
  maxCarryChars?: number;
}

declare interface DynaTraceLoggingOptions {
  url: string;
  apiToken: string;
  /**
   * Any custom log fields to include in each log entry.
   */
  fields?: CustomLogFields;
}

/**
 * Dynatrace logging plugin
 * @public
 */
export declare class DynaTraceLoggingPlugin extends LogPlugin {
  private options;
  constructor(options: DynaTraceLoggingOptions);
  /* Excluded from this release type: getTransport */
}

declare interface DynatraceMetricsContext {
  dimensions: string[];
}

declare interface DynatraceMetricsOptions {
  url: string;
  apiToken: string;
  dimensions?: string[];
  metrics?: MetricsType;
  include?: IncludeMetrics;
}

/**
 * Dynatrace metrics plugin
 * @public
 */
export declare class DynatraceMetricsPlugin extends MetricsPlugin {
  #private;
  private options;
  constructor(options: DynatraceMetricsOptions);
  /* Excluded from this release type: getTransport */
  static setContext(context: ZuploContext, data: DynatraceMetricsContext): void;
}

/** The edge (shared cache) half of the policy. */
export declare interface EdgeCacheDirectives {
  maxAge: number;
  staleWhileRevalidate?: number;
  staleIfError?: number;
}

declare interface EmbeddingsFallbacks {
  fallback?: FallbackModel;
  quotaFallback?: QuotaFallbackModel;
}

/**
 * Models for embeddings requests, as `providerName/model`. From 1 through 32 models, each listed once. Provider names aren't case-sensitive. Write each model ID exactly as your provider spells it. Every entry must be the same embedding model, such as one model on several accounts.
 *
 * @minItems 1
 * @maxItems 32
 * @public
 */
declare type EmbeddingsModels = [ProviderAndModel, ...ProviderAndModel[]];

/**
 * Rules for embedding requests.
 * @public
 */
declare type EmbeddingsModels_2 =
  | {
      allowList: AllowedModels1;
    }
  | {
      blockList: BlockedModels1;
    };

/**
 * Rule for embedding requests.
 * @public
 */
declare type EmbeddingsOverride =
  | {
      force: ForcedModel1;
    }
  | {
      default: DefaultModel1;
    };

/* Excluded from this release type: emitCacheOperation */

/* Excluded from this release type: emitCacheOperationLate */

/**
 * Enable accumulation and validation of streaming responses.
 * @public
 */
declare type EnableStreamingAccumulation = boolean;

/**
 * @beta
 * Object exposing environment variables
 */
export declare const environment: Record<string, string | undefined>;

declare interface EqualsRule {
  claim: Claim;
  /**
   * The exact value the claim must equal. Comparison is strict and type-sensitive: the string '42' does not equal the number 42. When the claim value is an array, the check passes if any element equals this value.
   */
  eq: string | number | boolean;
}

/**
 * @beta
 */
export declare interface ErrorHandler {
  (
    request: ZuploRequest,
    context: ZuploContext,
    err: Error
  ): Response | Promise<Response>;
}

/**
 * Number of SSE events to accumulate before checking with Akamai (default: 5).
 * @public
 */
declare type EventsInterval = number;

declare const EventType: {
  readonly AI_GATEWAY_COST_SUM: "ai_gateway_cost_sum";
  readonly AI_GATEWAY_REQUEST_COUNT: "ai_gateway_request_count";
  readonly AI_GATEWAY_TOKEN_SUM: "ai_gateway_token_sum";
  readonly AI_GATEWAY_LATENCY_HISTOGRAM: "ai_gateway_latency_histogram";
  readonly AI_GATEWAY_WARNING_COUNT: "ai_gateway_warning_count";
  readonly AI_GATEWAY_BLOCKED_COUNT: "ai_gateway_blocked_count";
  readonly AI_GATEWAY_FALLBACK_COUNT: "ai_gateway_fallback_count";
  readonly MCP_REQUEST_RECEIVED: "mcp_request_received";
  readonly MCP_REQUEST_COMPLETED: "mcp_request_completed";
  readonly MCP_REQUEST_REJECTED: "mcp_request_rejected";
  readonly MCP_INITIALIZE_NEGOTIATED: "mcp_initialize_negotiated";
  readonly MCP_CLIENT_UNSUPPORTED_BEHAVIOR: "mcp_client_unsupported_behavior";
  readonly MCP_CAPABILITY_LISTED: "mcp_capability_listed";
  readonly MCP_CAPABILITY_INVOKED: "mcp_capability_invoked";
  readonly MCP_CAPABILITY_COMPLETED: "mcp_capability_completed";
  readonly MCP_CAPABILITY_FAILED: "mcp_capability_failed";
  readonly MCP_CAPABILITY_CONNECT_REQUIRED: "mcp_capability_connect_required";
  readonly MCP_AUTH_DOWNSTREAM_TOKEN_VALIDATED: "mcp_auth_downstream_token_validated";
  readonly MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED: "mcp_auth_downstream_token_rejected";
  readonly MCP_OAUTH_CLIENT_REGISTERED: "mcp_oauth_client_registered";
  readonly MCP_OAUTH_AUTHORIZE_STARTED: "mcp_oauth_authorize_started";
  readonly MCP_OAUTH_AUTHORIZE_AWAITING_SETUP: "mcp_oauth_authorize_awaiting_setup";
  readonly MCP_OAUTH_TOKEN_ISSUED: "mcp_oauth_token_issued";
  readonly MCP_OAUTH_TOKEN_REFRESH_ROTATED: "mcp_oauth_token_refresh_rotated";
  readonly MCP_OAUTH_TOKEN_REVOKED: "mcp_oauth_token_revoked";
  readonly MCP_AUTH_UPSTREAM_CONNECT_REQUIRED: "mcp_auth_upstream_connect_required";
  readonly MCP_AUTH_UPSTREAM_CONNECT_STARTED: "mcp_auth_upstream_connect_started";
  readonly MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED: "mcp_auth_upstream_callback_received";
  readonly MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED: "mcp_auth_upstream_token_exchange_succeeded";
  readonly MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED: "mcp_auth_upstream_token_exchange_failed";
  readonly MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED: "mcp_auth_upstream_credential_resolved";
  readonly MCP_AUTH_UPSTREAM_CREDENTIAL_MISSING: "mcp_auth_upstream_credential_missing";
  readonly MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED: "mcp_auth_upstream_reconsent_required";
  readonly GRAPHQL_OPERATION: "graphql_operation";
  readonly CACHE_OPERATION: "cache_operation";
  readonly HANDLER_EXECUTION: "handler_execution";
};

declare type EventType = (typeof EventType)[keyof typeof EventType];

/**
 * How the classifier runs relative to the rest of the inbound policy chain. 'sequential' classifies inline, so later policies wait for the verdict; this is the behaviour when the option is omitted. 'parallel' classifies while the remaining inbound policies run — the verdict is still enforced before the request reaches the model, so no prompt is forwarded unchecked, but on a safe prompt the classifier's latency overlaps the rest of the chain instead of adding to it.
 * @public
 */
declare type Execution = "sequential" | "parallel";

/**
 * The value to key on, written like a {@link https://zuplo.com/docs/policies/ai-gateway-metering-inbound#budget-expressions|Metering budget expression}, such as `request.headers.get("x-end-user-id")`. Required when `stickyBy` is `expression`, and not allowed otherwise.
 * @public
 */
declare type Expression = string;

/**
 * Best-effort flatten of ALL human/assistant text in a request OR response body,
 * across every shape — the one sanctioned cross-shape helper. Intended for
 * guardrails that just need "all the text to scan/moderate"; it is deliberately
 * lossy (drops roles, structure, tool calls). Everything else should read the
 * typed body via {@link getRequestBody} / {@link getResponseBody}.
 *
 * For "the most recent messages" rather than all of the text, use
 * `conversation-window.ts` (`getConversationItems` + `selectRecentTurns`):
 * the one definition of a message window that the semantic cache and the
 * prompt injection guardrail share.
 * @public
 */
export declare function extractAllText(body: unknown): string;

/**
 * Parse a response body and extract its GraphQL `errors[]`, including
 * across an Apollo-style batched (array) response.
 *
 * Returns `null` when the body isn't a GraphQL response shape at all
 * (unparseable JSON, or a JSON scalar), and `[]` for a well-formed
 * response with no errors — callers treat both as "nothing to report"
 * but the distinction keeps the function testable.
 */
export declare function extractGraphqlErrors(
  bodyText: string
): GraphqlResponseError[] | null;

/**
 * Pull the incremental ASSISTANT TEXT from a parsed stream event per shape. The
 * single source of truth for "is this delta assistant text" — chat
 * `choices[].delta.content`, Responses `response.output_text.delta` only (NOT
 * tool-args / audio / refusal / code deltas), Anthropic `content_block_delta`.
 * Stream-scanning policies (e.g. the firewall accumulator) should call this
 * rather than re-deriving the per-shape extraction.
 * @public
 */
export declare function extractStreamTextDelta(
  parsed: unknown,
  format: AiFormat
): string | undefined;

/**
 * The model attempted after a retryable error or timeout.
 * @public
 */
declare type FallbackModel = string;

/**
 * Fallbacks grouped by AI Gateway capability.
 * @public
 */
declare interface FallbackModels {
  completions?: CompletionsFallbacks;
  embeddings?: EmbeddingsFallbacks;
}

/**
 * How long to wait for primary-model response headers before attempting the failure fallback. The timeout does not bound a streaming response body after its headers arrive.
 * @public
 */
declare type FallbackTimeoutSeconds = number;

/**
 * How long to wait for a model to start responding before retrying the request on another model. Applies to chat completions and embeddings. The timeout ends when the response starts, so it doesn't cut off a long streaming response. A response that doesn't stream starts only when it's complete, so the timeout covers the whole response. From 1 through 300.
 * @public
 */
declare type FallbackTimeoutSeconds_2 = number;

declare interface FetchOptions<T> {
  method?: HttpMethod_2;
  data?: T;
  headers?: Record<string, string>;
}

/**
 * File search tool
 */
declare interface FileSearchTool {
  type: "file_search";
  vector_store_ids: string[];
  filters?: Record<string, unknown> | null;
  max_num_results?: number;
  ranking_options?: {
    ranker?: "auto" | "default-2024-11-15";
    score_threshold?: number;
  };
}

/**
 * Authenticate users using Firebase issued JWT tokens.
 *
 * @title Firebase JWT Auth
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const FirebaseJwtInboundPolicy: InboundPolicyHandler<FirebaseJwtInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface FirebaseJwtInboundPolicyOptions {
  /**
   * Your Firebase Project ID.
   */
  projectId: string;
  /**
   * Allow unauthenticated requests to proceed. This is use useful if you want to use multiple authentication policies or if you want to allow both authenticated and non-authenticated traffic.
   */
  allowUnauthenticatedRequests?: boolean;
  /**
   * Enables OAuth 2.0 Protected Resource Metadata discovery (RFC 9728). When `true`, requests without a bearer token receive a 401 whose `WWW-Authenticate` header points `resource_metadata` at the `/.well-known/oauth-protected-resource` document for the request path and, when the `OAuthProtectedResourcePlugin` declares `scopesSupported`, lists those scopes in `scope`. Requires the `OAuthProtectedResourcePlugin` in `zuplo.runtime.ts` or a user-defined route at that path.
   */
  oAuthResourceMetadataEnabled?: boolean;
}

/**
 * Flatten a single message's `content` field to plain text. Content may be a
 * string (OpenAI chat / simple Anthropic) or an array of content blocks
 * (Anthropic Messages, OpenAI multi-modal vision, Responses input items). Use
 * this anywhere a policy needs the text of one message without assuming the
 * content is a string — a bare `${msg.content}` stringifies array content to
 * `[object Object]`.
 * @public
 */
export declare function flattenMessageContent(content: unknown): string;

/**
 * The model every request uses; a request-selected model is ignored.
 * @public
 */
declare type ForcedModel = string;

/**
 * The model every request uses; a request-selected model is ignored.
 * @public
 */
declare type ForcedModel1 = string;

/**
 * Converts form data in the incoming request to JSON.
 *
 * @title Form Data to JSON
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const FormDataToJsonInboundPolicy: InboundPolicyHandler<FormDataToJsonInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface FormDataToJsonInboundPolicyOptions {
  /**
   * Should the policy return an error if the request is not of the type form data.
   */
  badRequestIfNotFormData?: boolean;
  /**
   * The name of the honeypot field. Used to provide basic spam filtering.
   */
  optionalHoneypotName?: string;
}

declare interface FunctionDefinition {
  name: string;
  description?: string;
  parameters: Record<string, unknown>;
}

/**
 * Function tool for Responses API
 */
declare interface FunctionTool {
  name: string;
  type: "function";
  parameters: Record<string, unknown> | null;
  strict: boolean | null;
  description?: string | null;
}

/**
 * Function to generate request logger entries
 * @public
 */
export declare interface GenerateRequestLoggerEntry<T> {
  (
    response: Response,
    request: ZuploRequest,
    context: ZuploContext,
    metadata: RequestLoggerMetaData
  ): Promise<T>;
}

/**
 * Block requests based on geo-location parameters: country, region code, and ASN
 *
 * @title Geo-location filtering
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const GeoFilterInboundPolicy: InboundPolicyHandler<GeoFilterInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface GeoFilterInboundPolicyOptions {
  block?: GeoSpec;
  allow?: GeoSpec;
  /**
   * Specifies whether unknown geo-location parameters should be ignored (allowed through).
   */
  ignoreUnknown?: boolean;
}

declare interface GeoSpec {
  /**
   * comma separated string of country codes to allow (e.g. "US, CA").
   */
  countries?: string;
  /**
   * comma separated string of region codes to allow (e.g. "TX, WA").
   */
  regionCodes?: string;
  /**
   * comma separated string of ASNs to allow (e.g. "395747, 28304").
   */
  asns?: string;
}

/**
 * Resolve the AI shape for a request from its endpoint. Mirrors the handler's
 * base-path resolution so routes mounted under a prefix
 * (`/{prefix}/v1/chat/completions`) classify the same as the bare path. Returns
 * `null` for an endpoint that carries no AI body shape (e.g. `/v1/embeddings`).
 *
 * The shape is NEVER sniffed from the body — sniffing `!!body.input` misclassifies
 * an Anthropic body as chat.
 * @public
 */
export declare function getFormat(request: ZuploRequest): AiFormat | null;

/* Excluded from this release type: getIdForParameterSchema */

/* Excluded from this release type: getIdForRefSchema */

/* Excluded from this release type: getIdForRequestBodySchema */

/**
 * The function to get the anchor date for the quota.
 * @public
 */
export declare type GetQuotaAnchorDateFunction = (
  request: ZuploRequest,
  context: ZuploContext,
  policyName: string
) => Promise<Date | undefined>;

/**
 * The function to get the quota details for the quota.
 * @public
 */
export declare type GetQuotaDetailFunction = (
  request: ZuploRequest,
  context: ZuploContext,
  policyName: string
) => Promise<QuotaDetail>;

declare interface GetQuotaResult {
  anchorDate: string;
  nextResetDate: string;
  meters: Record<string, number>;
}

/* Excluded from this release type: getRawOperationDataIdentifierName */

/**
 * Read the request body, typed and discriminated by endpoint shape. Returns
 * `null` for a non-AI endpoint. The body is the native shape — no field is
 * flattened away.
 * @public
 */
export declare function getRequestBody(
  request: ZuploRequest
): Promise<AiRequestBody | null>;

/**
 * Read the response body, typed and discriminated by endpoint shape. Returns
 * `null` for a non-AI endpoint or an unparseable body.
 * @public
 */
export declare function getResponseBody(
  request: ZuploRequest,
  response: Response
): Promise<AiResponseBody | null>;

/**
 * Decode a streamed AI response into normalized {@link AiStreamEvent}s, hiding
 * the per-shape SSE dialect. A `post_call`-style streaming hook reads
 * `textDelta` / `usage` / `done` without re-writing SSE parsing per endpoint.
 * Reads a `clone()` of the response, so the original stream is untouched (the
 * caller can still return/pipe `response` as-is) — the same observe-via-clone
 * pattern the tracing policies use.
 * @public
 */
export declare function getStreamEvents(
  request: ZuploRequest,
  response: Response
): AsyncIterable<AiStreamEvent>;

/**
 * Normalize the usage record from a (non-streaming) response body, regardless of
 * shape. Chat reports `prompt_tokens`/`completion_tokens`; responses and
 * Anthropic report `input_tokens`/`output_tokens`. Returns `undefined` when no
 * usage is present.
 * @public
 */
export declare function getUsage(body: unknown): AiUsage | undefined;

declare interface GoogleCloudLoggingOptions {
  serviceAccountJson: string;
  logName: string;
  /**
   * Any custom log fields to include in each log entry.
   */
  fields?: CustomLogFields;
}

/**
 * Google Cloud logging plugin
 * @public
 */
export declare class GoogleCloudLoggingPlugin extends LogPlugin {
  private options;
  constructor(options: GoogleCloudLoggingOptions);
  /* Excluded from this release type: getTransport */
}

/**
 * Reports GraphQL errors returned in response bodies to Zuplo's GraphQL
 * analytics. GraphQL servers following the standard Apollo / graphql-yoga
 * pattern return `200 OK` with an `errors[]` array in the body when an
 * operation fails, which HTTP-level analytics alone report as a success —
 * add this policy to a GraphQL route and failed operations show up as
 * failures on the GraphQL dashboard, classified by error type.
 *
 * Each error in `errors[]` is classified from its `extensions.code`
 * following the Apollo Server conventions (`GRAPHQL_PARSE_FAILED` →
 * `syntax`, `GRAPHQL_VALIDATION_FAILED` → `validation`, `UNAUTHENTICATED` /
 * `FORBIDDEN` → `auth`, timeout codes → `timeout`); custom codes can be
 * mapped with `errorCodeClassification`, and anything unrecognized falls
 * back to `defaultErrorClass` (`resolver`). Optionally set `logErrors` to
 * also write a structured warning per errored response. The policy reads
 * up to `maxScanBytes` of the body (128 KiB by default, 5 MiB maximum),
 * scanning it for the `errors` token; a response larger than that is
 * treated as error-free. When the token is found and the body fits, it is
 * parsed and its errors reported.
 *
 * The response always passes through unchanged — the body is read from a
 * clone, and any internal failure is swallowed so reporting can never
 * break the request. The route must be marked `x-graphql: true` in
 * `routes.oas.json` (which enables GraphQL analytics for the route);
 * without the marker the policy logs a warning and does nothing.
 *
 * @title GraphQL Analytics
 * @product api-gateway
 * @beta
 * @public
 * @param response - The outgoing Response from the handler
 * @param request - The original incoming Request
 * @param context - The current context of the Request
 * @param options - The configuration options for the policy
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Response
 */
export declare const GraphqlAnalyticsOutboundPolicy: OutboundPolicyHandler<GraphqlAnalyticsOutboundPolicyOptions>;

/**
 * The options for the GraphQL Analytics outbound policy. Reads GraphQL `errors[]` from the response body and reports them to Zuplo's GraphQL analytics.
 * @public
 */
export declare interface GraphqlAnalyticsOutboundPolicyOptions {
  /**
   * Additional `extensions.code` → error-class mappings for codes your GraphQL server emits. Entries are merged over (and win against) the built-in Apollo-convention map (`GRAPHQL_PARSE_FAILED` → `syntax`, `GRAPHQL_VALIDATION_FAILED` / `BAD_USER_INPUT` → `validation`, `UNAUTHENTICATED` / `FORBIDDEN` → `auth`, timeout codes → `timeout`, `INTERNAL_SERVER_ERROR` → `resolver`). Keys are matched case-sensitively; built-in codes are matched case-insensitively.
   */
  errorCodeClassification?: {
    [k: string]: "syntax" | "validation" | "auth" | "timeout" | "resolver";
  };
  /**
   * The error class reported for a GraphQL error whose `extensions.code` is missing or not in the classification map.
   */
  defaultErrorClass?: "syntax" | "validation" | "auth" | "timeout" | "resolver";
  /**
   * When `true`, also write a structured warning to the request log (message, `extensions.code`, and path of each error — capped at the first 10) whenever a response contains GraphQL errors.
   */
  logErrors?: boolean;
  /**
   * How many bytes of the response body the policy reads to look for GraphQL errors. The body is read and scanned for the `errors` token up to this limit; a body larger than the limit — by `Content-Length`, or measured while reading when the header is absent — is treated as error-free, so any errors it carries go unreported. The default of 128 KiB suits the common case, where servers emit `errors` near the front of the body. Raise it (up to the 5 MiB maximum) to detect errors in larger responses, at the cost of reading more of every response. When the token is found and the body fits within the limit, the body is parsed and its errors are reported.
   */
  maxScanBytes?: number;
}

/**
 * GraphQL response-cache outcome, as decided by the Zuplo-provided GraphQL
 * Cache policy (`graphql-cache-inbound`) and reported on its `x-cache`
 * response header:
 *  - `"hit"`  — the response was served from cache.
 *  - `"miss"` — a cache-eligible query that was not in cache (forwarded to
 *               the origin).
 *
 * Operations that are not cache-eligible (mutations, subscriptions,
 * uncacheable/credentialed requests) — or that ran on a route without the
 * GraphQL Cache policy — carry no cache state (`null`), and are excluded
 * from the cache-hit-rate denominator.
 */
export declare type GraphqlCacheState = "hit" | "miss";

/**
 * One GraphQL error extracted from a response body, reduced to the
 * fields the GraphQL Analytics outbound policy consumes for
 * classification and (opt-in) logging.
 */
export declare interface GraphqlResponseError {
  /** The error's `message`, or `""` when missing/non-string. */
  message: string;
  /** The error's `extensions.code`, or `null` when absent. */
  code: string | null;
  /** The error's `path` joined with `.` (e.g. `user.posts.0.title`), or `null`. */
  path: string | null;
}

/**
 * The main request handler for the Zuplo runtime. This class initializes the gateway
 * and handles all incoming HTTP requests through the configured pipeline.
 *
 * @public
 * @example
 * ```typescript
 * import { Handler } from "@zuplo/runtime";
 *
 * // This is typically used internally by Zuplo runtime,
 * // but can be useful for testing or custom deployments
 * const handler = new Handler(
 *   routeLoader,
 *   buildEnvironment,
 *   runtimeSettings,
 *   serviceProvider,
 *   schemaValidations,
 *   runtimeInit
 * );
 *
 * // Handle a request
 * const response = await handler.requestHandler(
 *   request,
 *   runtimeEnvironment,
 *   event
 * );
 * ```
 */
export declare class Handler {
  routeLoader: () => Promise<RouteData>;
  buildEnvironment: BuildEnvironment;
  runtimeSettings: RuntimeSettings;
  private serviceProvider;
  private schemaValidations;
  private runtimeInit;
  constructor(
    routeLoader: () => Promise<RouteData>,
    buildEnvironment: BuildEnvironment,
    runtimeSettings: RuntimeSettings,
    serviceProvider: ServiceProvider,
    schemaValidations: any,
    runtimeInit: RuntimeExtensionsFunction | undefined
  );
  requestHandler: (
    request: Request,
    runtimeEnvironment: RuntimeEnvironment,
    event: ZuploEventContext
  ) => Promise<Response>;
  handleError(err: Error, detail: string, request: Request): Response;
}

/**
 * @public
 */
export declare interface HandlerDefinition {
  module: any;
  export: string;
  options?: unknown;
}

/**
 * Request header authentication.
 * @public
 */
declare interface HeaderCredentialsConfig {
  /**
   * The type of authentication to use.
   */
  method: "header";
  /**
   * The name of the header to use for authentication.
   */
  headerName: string;
}

/**
 * Model used for prompts classified as high complexity.
 * @public
 */
declare type HighComplexityModel = string;

/**
 * Sets HTTP deprecation headers on the outgoing response following the IETF
 * HTTP Deprecation Header standard. Supports the Deprecation, Sunset, and Link
 * headers.
 *
 * @title HTTP Deprecation
 * @product api-gateway
 * @public
 * @param response - The Response
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Response with deprecation headers
 */
export declare const HttpDeprecationOutboundPolicy: OutboundPolicyHandler<HttpDeprecationOutboundPolicyOptions>;

/**
 * The options for the HTTP Deprecation outbound policy.
 * @public
 */
export declare interface HttpDeprecationOutboundPolicyOptions {
  /**
   * The deprecation value. Use `true` for already deprecated, an ISO 8601 date string for a specific date, or a Unix timestamp number.
   */
  deprecation: true | string | number;
  /**
   * An ISO 8601 date string indicating when the endpoint will be removed. Sets the Sunset header.
   */
  sunset?: string;
  /**
   * A URL to documentation about the deprecation or migration guide. Sets the Link header.
   */
  link?: string;
}

/**
 * @public
 */
export declare type HttpMethod =
  | "GET"
  | "HEAD"
  | "POST"
  | "PUT"
  | "DELETE"
  | "CONNECT"
  | "OPTIONS"
  | "TRACE"
  | "PATCH";

declare type HttpMethod_2 = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";

/**
 * Utility class for generating standardized HTTP problem responses following RFC 7807.
 * Provides static methods for all standard HTTP status codes with automatic request tracking,
 * trace information, and consistent error formatting.
 *
 * @public
 * @see {@link https://datatracker.ietf.org/doc/html/rfc7807|RFC 7807 - Problem Details for HTTP APIs}
 *
 * @example
 * ```typescript
 * import { HttpProblems, ZuploContext, ZuploRequest } from "@zuplo/runtime";
 *
 * export function myHandler(request: ZuploRequest, context: ZuploContext) {
 *   // Simple 404 response
 *   if (!resource) {
 *     return HttpProblems.notFound(request, context);
 *   }
 *
 *   // 400 with custom detail
 *   if (!request.headers.get("x-api-key")) {
 *     return HttpProblems.badRequest(request, context, {
 *       detail: "Missing required header: x-api-key"
 *     });
 *   }
 *
 *   // 401 with additional headers
 *   if (!authenticated) {
 *     return HttpProblems.unauthorized(request, context, {
 *       detail: "Invalid credentials"
 *     }, {
 *       "WWW-Authenticate": "Bearer realm=\"api\""
 *     });
 *   }
 *
 *   // 429 with retry information
 *   if (rateLimited) {
 *     return HttpProblems.tooManyRequests(request, context, {
 *       detail: "Rate limit exceeded",
 *       extensions: {
 *         limit: 100,
 *         remaining: 0,
 *         reset: new Date(Date.now() + 60000).toISOString()
 *       }
 *     }, {
 *       "Retry-After": "60"
 *     });
 *   }
 * }
 * ```
 *
 * @example
 * ```typescript
 * // Custom problem formatter
 * import { HttpProblems, ProblemResponseDetails } from "@zuplo/runtime";
 *
 * // Format a custom problem
 * const problem: ProblemResponseDetails = {
 *   problem: {
 *     type: "https://example.com/probs/out-of-credit",
 *     title: "Out of credit",
 *     status: 402,
 *     detail: "Your current balance is 30, but that costs 50.",
 *     instance: "/account/12345/msgs/abc",
 *     extensions: {
 *       balance: 30,
 *       accounts: ["/account/12345", "/account/67890"]
 *     }
 *   }
 * };
 *
 * return HttpProblems.format(problem.problem, request, context);
 * ```
 */
export declare class HttpProblems extends HttpProblemsBase {
  #private;
  /**
   * The server has received the request headers and the client should proceed to send the request body
   * (in the case of a request for which a body needs to be sent; for example, a POST request).
   * Sending a large request body to a server after a request has been rejected for inappropriate headers would be inefficient.
   * To have a server check the request's headers, a client must send Expect: 100-continue as a header in its initial request
   * and receive a 100 Continue status code in response before sending the body. The response 417 Expectation Failed indicates the request should not be continued.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static continue: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The requester has asked the server to switch protocols and the server has agreed to do so.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static switchingProtocols: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * A WebDAV request may contain many sub-requests involving file operations, requiring a long time to complete the request. This code indicates that the server has received and is processing the request, but no response is available yet. This prevents the client from timing out and assuming the request was lost.
   * @deprecated — This status code is deprecated and shouldn't be sent any more. Clients may still accept it, but simply ignore them.
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static processing: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * This response may be sent by a server while it is still preparing a
   * response, with hints about the resources that the server is expecting
   * the final response will link. This allows a browser to start preloading
   * resources even before the server has prepared and sent that final response.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static earlyHints: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * Standard response for successful HTTP requests.
   * The actual response will depend on the request method used.
   * In a GET request, the response will contain an entity corresponding to the requested resource.
   * In a POST request, the response will contain an entity describing or containing the result of the action.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static ok: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The request has been fulfilled, resulting in the creation of a new resource.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static created: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The request has been accepted for processing, but the processing has not been completed.
   * The request might or might not be eventually acted upon, and may be disallowed when processing occurs.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static accepted: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * SINCE HTTP/1.1
   * The server is a transforming proxy that received a 200 OK from its origin,
   * but is returning a modified version of the origin's response.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static nonAuthoritativeInformation: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The server successfully processed the request and is not returning any content.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static noContent: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The server successfully processed the request, but is not returning any content.
   * Unlike a 204 response, this response requires that the requester reset the document view.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static resetContent: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The server is delivering only part of the resource (byte serving) due to a range header sent by the client.
   * The range header is used by HTTP clients to enable resuming of interrupted downloads,
   * or split a download into multiple simultaneous streams.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static partialContent: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The message body that follows is an XML message and can contain a number of separate response codes,
   * depending on how many sub-requests were made.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static multiStatus: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The members of a DAV binding have already been enumerated in a preceding part of the (multistatus) response,
   * and are not being included again.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static alreadyReported: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The server has fulfilled a request for the resource,
   * and the response is a representation of the result of one or more instance-manipulations applied to the current instance.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static imUsed: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * Indicates multiple options for the resource from which the client may choose (via agent-driven content negotiation).
   * For example, this code could be used to present multiple video format options,
   * to list files with different filename extensions, or to suggest word-sense disambiguation.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static multipleChoices: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * This and all future requests should be directed to the given URI.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static movedPermanently: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * This is an example of industry practice contradicting the standard.
   * The HTTP/1.0 specification (RFC 1945) required the client to perform a temporary redirect
   * (the original describing phrase was "Moved Temporarily"), but popular browsers implemented 302
   * with the functionality of a 303 See Other. Therefore, HTTP/1.1 added status codes 303 and 307
   * to distinguish between the two behaviours. However, some Web applications and frameworks
   * use the 302 status code as if it were the 303.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static found: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * SINCE HTTP/1.1
   * The response to the request can be found under another URI using a GET method.
   * When received in response to a POST (or PUT/DELETE), the client should presume that
   * the server has received the data and should issue a redirect with a separate GET message.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static seeOther: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * Indicates that the resource has not been modified since the version specified by the request headers If-Modified-Since or If-None-Match.
   * In such case, there is no need to retransmit the resource since the client still has a previously-downloaded copy.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static notModified: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * SINCE HTTP/1.1
   * The requested resource is available only through a proxy, the address for which is provided in the response.
   * Many HTTP clients (such as Mozilla and Internet Explorer) do not correctly handle responses with this status code, primarily for security reasons.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static useProxy: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * No longer used. Originally meant "Subsequent requests should use the specified proxy."
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   * @deprecated No longer used
   */
  static switchProxy: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * SINCE HTTP/1.1
   * In this case, the request should be repeated with another URI; however, future requests should still use the original URI.
   * In contrast to how 302 was historically implemented, the request method is not allowed to be changed when reissuing the original request.
   * For example, a POST request should be repeated using another POST request.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static temporaryRedirect: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The request and all future requests should be repeated using another URI.
   * 307 and 308 parallel the behaviors of 302 and 301, but do not allow the HTTP method to change.
   * So, for example, submitting a form to a permanently redirected resource may continue smoothly.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static permanentRedirect: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The server cannot or will not process the request due to an apparent client error
   * (e.g., malformed request syntax, too large size, invalid request message framing, or deceptive request routing).
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static badRequest: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * Similar to 403 Forbidden, but specifically for use when authentication is required and has failed or has not yet
   * been provided. The response must include a WWW-Authenticate header field containing a challenge applicable to the
   * requested resource. See Basic access authentication and Digest access authentication. 401 semantically means
   * "unauthenticated",i.e. the user does not have the necessary credentials.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static unauthorized: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * Reserved for future use. The original intention was that this code might be used as part of some form of digital
   * cash or micro payment scheme, but that has not happened, and this code is not usually used.
   * Google Developers API uses this status if a particular developer has exceeded the daily limit on requests.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static paymentRequired: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The request was valid, but the server is refusing action.
   * The user might not have the necessary permissions for a resource.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static forbidden: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The requested resource could not be found but may be available in the future.
   * Subsequent requests by the client are permissible.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static notFound: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * A request method is not supported for the requested resource;
   * for example, a GET request on a form that requires data to be presented via POST, or a PUT request on a read-only resource.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static methodNotAllowed: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The requested resource is capable of generating only content not acceptable according to the Accept headers sent in the request.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static notAcceptable: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The client must first authenticate itself with the proxy.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static proxyAuthenticationRequired: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The server timed out waiting for the request.
   * According to HTTP specifications:
   * "The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time."
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static requestTimeout: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * Indicates that the request could not be processed because of conflict in the request,
   * such as an edit conflict between multiple simultaneous updates.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static conflict: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * Indicates that the resource requested is no longer available and will not be available again.
   * This should be used when a resource has been intentionally removed and the resource should be purged.
   * Upon receiving a 410 status code, the client should not request the resource in the future.
   * Clients such as search engines should remove the resource from their indices.
   * Most use cases do not require clients and search engines to purge the resource, and a "404 Not Found" may be used instead.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static gone: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The request did not specify the length of its content, which is required by the requested resource.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static lengthRequired: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The server does not meet one of the preconditions that the requester put on the request.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static preconditionFailed: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The request is larger than the server is willing or able to process. Previously called "Request Entity Too Large".
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static contentTooLarge: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The URI provided was too long for the server to process. Often the result of too much data being encoded as a query-string of a GET request,
   * in which case it should be converted to a POST request.
   * Called "Request-URI Too Long" previously.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static uriTooLong: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The request entity has a media type which the server or resource does not support.
   * For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static unsupportedMediaType: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The client has asked for a portion of the file (byte serving), but the server cannot supply that portion.
   * For example, if the client asked for a part of the file that lies beyond the end of the file.
   * Called "Requested Range Not Satisfiable" previously.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static rangeNotSatisfiable: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The server cannot meet the requirements of the Expect request-header field.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static expectationFailed: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * This code was defined in 1998 as one of the traditional IETF April Fools' jokes, in RFC 2324, Hyper Text Coffee Pot Control Protocol,
   * and is not expected to be implemented by actual HTTP servers. The RFC specifies this code should be returned by
   * teapots requested to brew coffee. This HTTP status is used as an Easter egg in some websites, including Google.com.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static imATeapot: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The request was directed at a server that is not able to produce a response (for example because a connection reuse).
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static misdirectedRequest: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The request was well-formed but was unable to be followed due to semantic errors.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static unprocessableContent: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The resource that is being accessed is locked.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static locked: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The request failed due to failure of a previous request (e.g., a PROPPATCH).
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static failedDependency: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The server is unwilling to risk processing a request that might be
   * replayed, which creates the potential for a replay attack.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static tooEarly: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The client should switch to a different protocol such as TLS/1.0, given in the Upgrade header field.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static upgradeRequired: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The origin server requires the request to be conditional.
   * Intended to prevent "the 'lost update' problem, where a client
   * GETs a resource's state, modifies it, and PUTs it back to the server,
   * when meanwhile a third party has modified the state on the server, leading to a conflict."
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static preconditionRequired: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The user has sent too many requests in a given amount of time. Intended for use with rate-limiting schemes.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static tooManyRequests: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The server is unwilling to process the request because either an individual header field,
   * or all the header fields collectively, are too large.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static requestHeaderFieldsTooLarge: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * A server operator has received a legal demand to deny access to a resource or to a set of resources
   * that includes the requested resource. The code 451 was chosen as a reference to the novel Fahrenheit 451.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static unavailableForLegalReasons: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * A generic error message, given when an unexpected condition was encountered and no more specific message is suitable.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static internalServerError: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The server either does not recognize the request method, or it lacks the ability to fulfill the request.
   * Usually this implies future availability (e.g., a new feature of a web-service API).
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static notImplemented: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The server was acting as a gateway or proxy and received an invalid response from the upstream server.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static badGateway: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The server is currently unavailable (because it is overloaded or down for maintenance).
   * Generally, this is a temporary state.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static serviceUnavailable: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The server was acting as a gateway or proxy and did not receive a timely response from the upstream server.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static gatewayTimeout: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The server does not support the HTTP protocol version used in the request
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static httpVersionNotSupported: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * Transparent content negotiation for the request results in a circular reference.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static variantAlsoNegotiates: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The server is unable to store the representation needed to complete the request.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static insufficientStorage: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The server detected an infinite loop while processing the request.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static loopDetected: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * Further extensions to the request are required for the server to fulfill it.
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static notExtended: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
  /**
   * The client needs to authenticate to gain network access.
   * Intended for use by intercepting proxies used to control access to the network (e.g., "captive portals" used
   * to require agreement to Terms of Service before granting full Internet access via a Wi-Fi hotspot).
   *
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @param overrides - Overrides to the problem
   * @param additionalHeaders - Additional headers to send in the outgoing response
   * @returns A HTTP response promise
   */
  static networkAuthenticationRequired: (
    request: ZuploRequest,
    context: ZuploContext,
    overrides?: Partial<ProblemDetails>,
    additionalHeaders?: HeadersInit
  ) => Promise<Response>;
}

declare class HttpProblemsBase {
  /**
   * Creates a Response in the standard format from a problem detail
   * @param details - The details of the problem
   * @param request - The ZuploRequest object
   * @param context - The ZuploContext object
   * @returns A HTTP Response promise
   */
  static format: (
    details: ProblemDetails | ProblemResponseDetails,
    request: ZuploRequest,
    context: ZuploContext
  ) => Promise<Response>;
  /**
   * Creates a problem from the status code
   */
  static getProblemFromStatus(
    status: HttpStatusCode,
    problem?: Partial<Omit<ProblemDetails, "status" | "title">>
  ): ProblemDetails;
}

/**
 * @beta
 */
export declare enum HttpStatusCode {
  /**
   * The server has received the request headers and the client should proceed to send the request body
   * (in the case of a request for which a body needs to be sent; for example, a POST request).
   * Sending a large request body to a server after a request has been rejected for inappropriate headers would be inefficient.
   * To have a server check the request's headers, a client must send Expect: 100-continue as a header in its initial request
   * and receive a 100 Continue status code in response before sending the body. The response 417 Expectation Failed indicates the request should not be continued.
   */
  CONTINUE = 100,
  /**
   * The requester has asked the server to switch protocols and the server has agreed to do so.
   */
  SWITCHING_PROTOCOLS = 101,
  /**
   * A WebDAV request may contain many sub-requests involving file operations, requiring a long time to complete the request.
   * This code indicates that the server has received and is processing the request, but no response is available yet.
   * This prevents the client from timing out and assuming the request was lost.
   * @deprecated This status code is deprecated and shouldn't be sent any more. Clients may still accept it, but simply ignore them.
   */
  PROCESSING = 102,
  /**
   * This response may be sent by a server while it is still preparing a
   * response, with hints about the resources that the server is expecting
   * the final response will link. This allows a browser to start preloading
   * resources even before the server has prepared and sent that final response.
   */
  EARLY_HINTS = 103,
  /**
   * Standard response for successful HTTP requests.
   * The actual response will depend on the request method used.
   * In a GET request, the response will contain an entity corresponding to the requested resource.
   * In a POST request, the response will contain an entity describing or containing the result of the action.
   */
  OK = 200,
  /**
   * The request has been fulfilled, resulting in the creation of a new resource.
   */
  CREATED = 201,
  /**
   * The request has been accepted for processing, but the processing has not been completed.
   * The request might or might not be eventually acted upon, and may be disallowed when processing occurs.
   */
  ACCEPTED = 202,
  /**
   * SINCE HTTP/1.1
   * The server is a transforming proxy that received a 200 OK from its origin,
   * but is returning a modified version of the origin's response.
   */
  NON_AUTHORITATIVE_INFORMATION = 203,
  /**
   * The server successfully processed the request and is not returning any content.
   */
  NO_CONTENT = 204,
  /**
   * The server successfully processed the request, but is not returning any content.
   * Unlike a 204 response, this response requires that the requester reset the document view.
   */
  RESET_CONTENT = 205,
  /**
   * The server is delivering only part of the resource (byte serving) due to a range header sent by the client.
   * The range header is used by HTTP clients to enable resuming of interrupted downloads,
   * or split a download into multiple simultaneous streams.
   */
  PARTIAL_CONTENT = 206,
  /**
   * The message body that follows is an XML message and can contain a number of separate response codes,
   * depending on how many sub-requests were made.
   */
  MULTI_STATUS = 207,
  /**
   * The members of a DAV binding have already been enumerated in a preceding part of the (multistatus) response,
   * and are not being included again.
   */
  ALREADY_REPORTED = 208,
  /**
   * The server has fulfilled a request for the resource,
   * and the response is a representation of the result of one or more instance-manipulations applied to the current instance.
   */
  IM_USED = 226,
  /**
   * Indicates multiple options for the resource from which the client may choose (via agent-driven content negotiation).
   * For example, this code could be used to present multiple video format options,
   * to list files with different filename extensions, or to suggest word-sense disambiguation.
   */
  MULTIPLE_CHOICES = 300,
  /**
   * This and all future requests should be directed to the given URI.
   */
  MOVED_PERMANENTLY = 301,
  /**
   * This is an example of industry practice contradicting the standard.
   * The HTTP/1.0 specification (RFC 1945) required the client to perform a temporary redirect
   * (the original describing phrase was "Moved Temporarily"), but popular browsers implemented 302
   * with the functionality of a 303 See Other. Therefore, HTTP/1.1 added status codes 303 and 307
   * to distinguish between the two behaviours. However, some Web applications and frameworks
   * use the 302 status code as if it were the 303.
   */
  FOUND = 302,
  /**
   * SINCE HTTP/1.1
   * The response to the request can be found under another URI using a GET method.
   * When received in response to a POST (or PUT/DELETE), the client should presume that
   * the server has received the data and should issue a redirect with a separate GET message.
   */
  SEE_OTHER = 303,
  /**
   * Indicates that the resource has not been modified since the version specified by the request headers If-Modified-Since or If-None-Match.
   * In such case, there is no need to retransmit the resource since the client still has a previously-downloaded copy.
   */
  NOT_MODIFIED = 304,
  /**
   * SINCE HTTP/1.1
   * The requested resource is available only through a proxy, the address for which is provided in the response.
   * Many HTTP clients (such as Mozilla and Internet Explorer) do not correctly handle responses with this status code, primarily for security reasons.
   */
  USE_PROXY = 305,
  /**
   * No longer used. Originally meant "Subsequent requests should use the specified proxy."
   * @deprecated No longer used
   */
  SWITCH_PROXY = 306,
  /**
   * SINCE HTTP/1.1
   * In this case, the request should be repeated with another URI; however, future requests should still use the original URI.
   * In contrast to how 302 was historically implemented, the request method is not allowed to be changed when reissuing the original request.
   * For example, a POST request should be repeated using another POST request.
   */
  TEMPORARY_REDIRECT = 307,
  /**
   * The request and all future requests should be repeated using another URI.
   * 307 and 308 parallel the behaviors of 302 and 301, but do not allow the HTTP method to change.
   * So, for example, submitting a form to a permanently redirected resource may continue smoothly.
   */
  PERMANENT_REDIRECT = 308,
  /**
   * The server cannot or will not process the request due to an apparent client error
   * (e.g., malformed request syntax, too large size, invalid request message framing, or deceptive request routing).
   */
  BAD_REQUEST = 400,
  /**
   * Similar to 403 Forbidden, but specifically for use when authentication is required and has failed or has not yet
   * been provided. The response must include a WWW-Authenticate header field containing a challenge applicable to the
   * requested resource. See Basic access authentication and Digest access authentication. 401 semantically means
   * "unauthenticated",i.e. the user does not have the necessary credentials.
   */
  UNAUTHORIZED = 401,
  /**
   * Reserved for future use. The original intention was that this code might be used as part of some form of digital
   * cash or micro payment scheme, but that has not happened, and this code is not usually used.
   * Google Developers API uses this status if a particular developer has exceeded the daily limit on requests.
   */
  PAYMENT_REQUIRED = 402,
  /**
   * The request was valid, but the server is refusing action.
   * The user might not have the necessary permissions for a resource.
   */
  FORBIDDEN = 403,
  /**
   * The requested resource could not be found but may be available in the future.
   * Subsequent requests by the client are permissible.
   */
  NOT_FOUND = 404,
  /**
   * A request method is not supported for the requested resource;
   * for example, a GET request on a form that requires data to be presented via POST, or a PUT request on a read-only resource.
   */
  METHOD_NOT_ALLOWED = 405,
  /**
   * The requested resource is capable of generating only content not acceptable according to the Accept headers sent in the request.
   */
  NOT_ACCEPTABLE = 406,
  /**
   * The client must first authenticate itself with the proxy.
   */
  PROXY_AUTHENTICATION_REQUIRED = 407,
  /**
   * The server timed out waiting for the request.
   * According to HTTP specifications:
   * "The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time."
   */
  REQUEST_TIMEOUT = 408,
  /**
   * Indicates that the request could not be processed because of conflict in the request,
   * such as an edit conflict between multiple simultaneous updates.
   */
  CONFLICT = 409,
  /**
   * Indicates that the resource requested is no longer available and will not be available again.
   * This should be used when a resource has been intentionally removed and the resource should be purged.
   * Upon receiving a 410 status code, the client should not request the resource in the future.
   * Clients such as search engines should remove the resource from their indices.
   * Most use cases do not require clients and search engines to purge the resource, and a "404 Not Found" may be used instead.
   */
  GONE = 410,
  /**
   * The request did not specify the length of its content, which is required by the requested resource.
   */
  LENGTH_REQUIRED = 411,
  /**
   * The server does not meet one of the preconditions that the requester put on the request.
   */
  PRECONDITION_FAILED = 412,
  /**
   * The request is larger than the server is willing or able to process. Previously called "Request Entity Too Large".
   */
  CONTENT_TOO_LARGE = 413,
  /* Excluded from this release type: PAYLOAD_TOO_LARGE */
  /**
   * The URI provided was too long for the server to process. Often the result of too much data being encoded as a query-string of a GET request,
   * in which case it should be converted to a POST request.
   * Called "Request-URI Too Long" previously.
   */
  URI_TOO_LONG = 414,
  /**
   * The request entity has a media type which the server or resource does not support.
   * For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format.
   */
  UNSUPPORTED_MEDIA_TYPE = 415,
  /**
   * The client has asked for a portion of the file (byte serving), but the server cannot supply that portion.
   * For example, if the client asked for a part of the file that lies beyond the end of the file.
   * Called "Requested Range Not Satisfiable" previously.
   */
  RANGE_NOT_SATISFIABLE = 416,
  /**
   * The server cannot meet the requirements of the Expect request-header field.
   */
  EXPECTATION_FAILED = 417,
  /**
   * This code was defined in 1998 as one of the traditional IETF April Fools' jokes, in RFC 2324, Hyper Text Coffee Pot Control Protocol,
   * and is not expected to be implemented by actual HTTP servers. The RFC specifies this code should be returned by
   * teapots requested to brew coffee. This HTTP status is used as an Easter egg in some websites, including Google.com.
   */
  I_AM_A_TEAPOT = 418,
  /**
   * The request was directed at a server that is not able to produce a response (for example because a connection reuse).
   */
  MISDIRECTED_REQUEST = 421,
  /* Excluded from this release type: UNPROCESSABLE_ENTITY */
  /**
   * The request was well-formed but was unable to be followed due to semantic errors.
   */
  UNPROCESSABLE_CONTENT = 422,
  /**
   * The resource that is being accessed is locked.
   */
  LOCKED = 423,
  /**
   * The request failed due to failure of a previous request (e.g., a PROPPATCH).
   */
  FAILED_DEPENDENCY = 424,
  /**
   * The server is unwilling to risk processing a request that might be
   * replayed, which creates the potential for a replay attack.
   */
  TOO_EARLY = 425,
  /**
   * The client should switch to a different protocol such as TLS/1.0, given in the Upgrade header field.
   */
  UPGRADE_REQUIRED = 426,
  /**
   * The origin server requires the request to be conditional.
   * Intended to prevent "the 'lost update' problem, where a client
   * GETs a resource's state, modifies it, and PUTs it back to the server,
   * when meanwhile a third party has modified the state on the server, leading to a conflict."
   */
  PRECONDITION_REQUIRED = 428,
  /**
   * The user has sent too many requests in a given amount of time. Intended for use with rate-limiting schemes.
   */
  TOO_MANY_REQUESTS = 429,
  /**
   * The server is unwilling to process the request because either an individual header field,
   * or all the header fields collectively, are too large.
   */
  REQUEST_HEADER_FIELDS_TOO_LARGE = 431,
  /**
   * A server operator has received a legal demand to deny access to a resource or to a set of resources
   * that includes the requested resource. The code 451 was chosen as a reference to the novel Fahrenheit 451.
   */
  UNAVAILABLE_FOR_LEGAL_REASONS = 451,
  /**
   * A generic error message, given when an unexpected condition was encountered and no more specific message is suitable.
   */
  INTERNAL_SERVER_ERROR = 500,
  /**
   * The server either does not recognize the request method, or it lacks the ability to fulfill the request.
   * Usually this implies future availability (e.g., a new feature of a web-service API).
   */
  NOT_IMPLEMENTED = 501,
  /**
   * The server was acting as a gateway or proxy and received an invalid response from the upstream server.
   */
  BAD_GATEWAY = 502,
  /**
   * The server is currently unavailable (because it is overloaded or down for maintenance).
   * Generally, this is a temporary state.
   */
  SERVICE_UNAVAILABLE = 503,
  /**
   * The server was acting as a gateway or proxy and did not receive a timely response from the upstream server.
   */
  GATEWAY_TIMEOUT = 504,
  /**
   * The server does not support the HTTP protocol version used in the request
   */
  HTTP_VERSION_NOT_SUPPORTED = 505,
  /**
   * Transparent content negotiation for the request results in a circular reference.
   */
  VARIANT_ALSO_NEGOTIATES = 506,
  /**
   * The server is unable to store the representation needed to complete the request.
   */
  INSUFFICIENT_STORAGE = 507,
  /**
   * The server detected an infinite loop while processing the request.
   */
  LOOP_DETECTED = 508,
  /**
   * Further extensions to the request are required for the server to fulfill it.
   */
  NOT_EXTENDED = 510,
  /**
   * The client needs to authenticate to gain network access.
   * Intended for use by intercepting proxies used to control access to the network (e.g., "captive portals" used
   * to require agreement to Terms of Service before granting full Internet access via a Wi-Fi hotspot).
   */
  NETWORK_AUTHENTICATION_REQUIRED = 511,
}

declare type HttpStatusCodeRangeDefinition =
  | "1XX"
  | "2XX"
  | "3XX"
  | "4XX"
  | "5XX";

/* Excluded from this release type: httpStatuses */

/**
 * Default entry structure for Hydrolix logs
 * @public
 */
export declare interface HydrolixDefaultEntry extends BasicDictionary {
  deploymentName: string;
  timestamp: string;
  requestId: string;
  routePath: string;
  operationId?: string;
  url?: string;
  statusCode?: number;
  durationMs?: number;
  method: string;
  userSub?: string;
  instanceId?: string;
  colo?: string;
  city?: string;
  country?: string;
  continent?: string;
  latitude?: string;
  longitude?: string;
  postalCode?: string;
  metroCode?: string;
  region?: string;
  regionCode?: string;
  timezone?: string;
  asn?: string;
  asOrganization?: string;
  clientIP?: string;
  zuploUserAgent?: string;
}

/**
 * Hydrolix request logger plugin
 * @public
 */
export declare class HydrolixRequestLoggerPlugin<
  T extends BasicDictionary,
> extends SystemRuntimePlugin {
  #private;
  constructor(options: HydrolixRequestLoggerPluginOptions<T>);
  initialize(runtime: RuntimeExtensions): Promise<void>;
}

/**
 * Options for Hydrolix request logger plugin
 * @public
 */
export declare interface HydrolixRequestLoggerPluginOptions<T> {
  hostname: string;
  username: string;
  password: string;
  token?: string;
  table: string;
  transform: string;
  generateLogEntry: GenerateRequestLoggerEntry<T>;
  batchPeriodSeconds?: number;
}

/**
 * Hand-written mirror of {@link idJagConfigSchema}'s parsed output. Keeping
 * the type hand-written keeps zod out of the public policy class signatures
 * (this type is part of {@link McpOAuthRuntimeConfig}); the assertion below
 * fails to compile on drift.
 */
declare type IdJagRuntimeConfig =
  | {
      enabled: false;
    }
  | {
      enabled: true;
      trustedIssuers: {
        issuer: string;
        jwksUrl: string;
        expectedClientIds?: string[];
        subjectMapping: "iss_prefix" | "iss_tenant_prefix" | "sub_id_only";
      }[];
      authorizationDetailsTypesAllowed?: string[];
    };

/**
 * Image generation tool
 */
declare interface ImageGenerationTool {
  type: "image_generation";
  model?: "gpt-image-1" | "gpt-image-1-mini";
  background?: "transparent" | "opaque" | "auto";
  input_fidelity?: "high" | "low" | null;
  input_image_mask?: {
    file_id?: string;
    image_url?: string;
  };
  moderation?: "auto" | "low";
  output_compression?: number;
  output_format?: "png" | "webp" | "jpeg";
  partial_images?: number;
  quality?: "low" | "medium" | "high" | "auto";
  size?: "1024x1024" | "1024x1536" | "1536x1024" | "auto";
}

/**
 * A policy that can modify the incoming HTTP request before it is sent to
 * the handler. If a response is returned, the request is short-circuited and
 * the response is returned to the client. If a Request is returned, policies
 * or a handler that follow are executed.
 *
 * @public
 * @example
 * ```typescript
 * import { InboundPolicy, ZuploContext, ZuploRequest } from "@zuplo/runtime";
 *
 * interface MyPolicyOptions {
 *   headerName: string;
 *   headerValue: string;
 * }
 *
 * export class AddHeaderPolicy extends InboundPolicy<MyPolicyOptions> {
 *   async handler(request: ZuploRequest, context: ZuploContext) {
 *     // Add a custom header
 *     request.headers.set(this.options.headerName, this.options.headerValue);
 *
 *     // Log the action
 *     context.log.info(`Added header ${this.options.headerName}`);
 *
 *     // Continue to next policy/handler
 *     return request;
 *   }
 * }
 *
 * // Usage in policies.json:
 * // {
 * //   "name": "add-custom-header",
 * //   "policyType": "custom-add-header-policy",
 * //   "handler": {
 * //     "export": "AddHeaderPolicy",
 * //     "module": "$import(./policies/add-header)",
 * //     "options": {
 * //       "headerName": "X-Custom-Header",
 * //       "headerValue": "My Value"
 * //     }
 * //   }
 * // }
 * ```
 */
export declare abstract class InboundPolicy<
  TOptions = any,
> extends PolicyBase<TOptions> {
  readonly direction: PolicyDirection;
  /**
   * The handler that is called each time this policy is invoked
   *
   * @param request - The incoming Request
   * @param context - The current context of the Request
   * @returns A Response or Request object
   */
  abstract handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
}

/**
 * A function-based inbound policy that can modify the incoming HTTP request.
 * This is the simplest way to create custom policies without extending a class.
 *
 * @param request - The incoming Request
 * @param context - The current context of the Request
 * @param options - The configuration options for the policy
 * @param policyName - The name set on the policy in the configuration
 * @returns A Response to short-circuit or a Request to continue
 *
 * @public
 * @example
 * ```typescript
 * import { InboundPolicyHandler } from "@zuplo/runtime";
 *
 * interface RateLimitOptions {
 *   requests: number;
 *   windowMs: number;
 * }
 *
 * export const rateLimitPolicy: InboundPolicyHandler<RateLimitOptions> = async (
 *   request,
 *   context,
 *   options,
 *   policyName
 * ) => {
 *   const key = request.headers.get("x-api-key") || "anonymous";
 *   const count = await incrementCounter(key, options.windowMs);
 *
 *   if (count > options.requests) {
 *     return new Response("Too Many Requests", { status: 429 });
 *   }
 *
 *   // Add rate limit headers
 *   request.headers.set("X-RateLimit-Limit", options.requests.toString());
 *   request.headers.set("X-RateLimit-Remaining", (options.requests - count).toString());
 *
 *   return request;
 * };
 * ```
 */
export declare interface InboundPolicyHandler<TOptions = any> {
  (
    request: ZuploRequest,
    context: ZuploContext,
    options: TOptions,
    policyName: string
  ): Promise<ZuploRequest | Response>;
}

declare interface IncludeMetrics {
  country?: boolean;
  httpMethod?: boolean;
  statusCode?: boolean;
  path?: boolean;
}

/**
 * @public
 */
declare interface IncomingRequestProperties {
  /**
   * The IP address of the client that made the incoming request, for example,
   * "203.0.113.7".
   *
   * Use this rather than reading an IP header off `request` yourself. Which
   * header carries the address differs by deployment, and some are removed
   * from the request before your code runs, so reading one directly is either
   * empty or wrong depending on where the gateway is running.
   *
   * The value is `undefined` when the caller could not be identified, so
   * handle that case rather than substituting a placeholder, which would
   * become one shared identity for every unidentified caller. During local
   * development, where nothing identifies the caller, it falls back to
   * `"127.0.0.1"` instead.
   *
   * If your own CDN or load balancer sits in front of Zuplo, this is the
   * address of that hop rather than the end user's.
   *
   * @see {@link https://zuplo.com/docs/articles/check-ip-address} for when
   * this address can be trusted on each deployment type.
   *
   * @example
   * ```ts
   * export default async function (request: ZuploRequest, context: ZuploContext) {
   *   const ip = context.incomingRequestProperties.ip;
   *   return new Response(ip ?? "unknown");
   * }
   * ```
   */
  readonly ip: string | undefined;
  /**
   * ASN of the incoming request, for example, 395747.
   */
  readonly asn: number | undefined;
  /**
   * The organization which owns the ASN of the incoming request,
   * for example, Google Cloud.
   */
  readonly asOrganization: string | undefined;
  /**
   * City of the incoming request, for example, "Austin".
   */
  readonly city: string | undefined;
  /**
   * Continent of the incoming request, for example, "NA".
   */
  readonly continent: ContinentCode | undefined;
  /**
   * The two-letter country code in the request.
   * @see {@link https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2|ISO 3166-1 alpha-2}
   */
  readonly country: Iso3166Alpha2Code | undefined;
  /**
   * Latitude of the incoming request, for example, "30.27130".
   */
  readonly latitude: string | undefined;
  /**
   * Longitude of the incoming request, for example, "-97.74260".
   */
  readonly longitude: string | undefined;
  /**
   * The three-letter IATA airport code of the data center that the request hit,
   * for example, "DFW".
   * @see {@link https://en.wikipedia.org/wiki/IATA_airport_code|IATA airport code}
   */
  readonly colo: string | undefined;
  /**
   * Postal code of the incoming request, for example, "78701".
   */
  readonly postalCode: string | undefined;
  /**
   * Metro code (DMA) of the incoming request, for example, "635".
   */
  readonly metroCode: string | undefined;
  /**
   * If known, the ISO 3166-2 name for the first level region associated with
   * the IP address of the incoming request, for example, "Texas".
   * @see {@link https://en.wikipedia.org/wiki/ISO_3166-2|ISO 3166-2}
   */
  readonly region: string | undefined;
  /**
   * If known, the ISO 3166-2 code for the first-level region associated with
   * the IP address of the incoming request, for example, "TX".
   * @see {@link https://en.wikipedia.org/wiki/ISO_3166-2|ISO 3166-2}
   */
  readonly regionCode: string | undefined;
  /**
   * Timezone of the incoming request, for example, "America/Chicago".
   */
  readonly timezone: string | undefined;
  /**
   * If available, the HTTP protocol of the incoming request, for example, "HTTP/1.1".
   */
  readonly httpProtocol: string | undefined;
  /* Excluded from this release type: clientCert */
  /* Excluded from this release type: clientMtlsVerificationStatus */
  /* Excluded from this release type: clientMtlsVerificationReason */
  /* Excluded from this release type: clientCertFingerprintSha256 */
  /* Excluded from this release type: clientCertNotBefore */
  /* Excluded from this release type: clientCertNotAfter */
  /* Excluded from this release type: clientCertIssuerDn */
  /* Excluded from this release type: clientCertSubjectDn */
}

declare interface InnermostAndRule {
  /**
   * Claim checks that must all pass. The maximum combinator nesting depth is reached, so entries must be single claim checks.
   *
   * @minItems 1
   */
  and: [ClaimCheck, ...ClaimCheck[]];
}

declare interface InnermostOrRule {
  /**
   * Claim checks of which at least one must pass. The maximum combinator nesting depth is reached, so entries must be single claim checks.
   *
   * @minItems 1
   */
  or: [ClaimCheck, ...ClaimCheck[]];
}

/**
 * A third-level rule: a single claim check or an and/or combination of claim checks. Combinators cannot nest any deeper.
 * @public
 */
declare type InnermostRule =
  | InnermostAndRule
  | InnermostOrRule
  | EqualsRule
  | InRule
  | StartsWithRule;

declare interface InRule {
  claim: Claim;
  /**
   * Allowed values for the claim. The check passes when the claim value equals any listed value (strict, type-sensitive comparison). When the claim value is an array, the check passes if any element equals any listed value.
   *
   * @minItems 1
   */
  in: [string | number | boolean, ...(string | number | boolean)[]];
}

/**
 * Short description of the intent label.
 * @public
 */
declare type IntentDescription = string;

/**
 * Label used to classify the intent of the user message being evaluated.
 * @public
 */
declare type IntentID = string;

/**
 * Dictionary of intents used to classify the user message being evaluated. Omit to use the built-in dictionary (code, summarization, translation, qa, conversation, classification, creative_writing, agentic, document_qa, other).
 *
 * @minItems 1
 * @public
 */
declare type Intents = [
  {
    id: IntentID;
    description: IntentDescription;
  },
  ...{
    id: IntentID;
    description: IntentDescription;
  }[],
];

/**
 * Accepts only requests that this gateway made itself with
 * `context.invokeRoute`, and rejects every request that arrived over the
 * network.
 *
 * Use it on a route that only other routes, handlers, and policies on the same
 * gateway call: a REST endpoint that an MCP server exposes as a tool, or the
 * classifier application behind the Smart Router or Prompt Injection
 * Protection policies. Those calls never leave the gateway, so an API key on
 * them protects nothing. This policy asserts the one thing that matters: the
 * request originated inside the deployment.
 *
 * The check reads `context.parentContext`, which the runtime sets only on the
 * child context that `context.invokeRoute` creates. A client cannot supply it
 * through a header, the URL, or the body. The policy makes no network calls,
 * reads no body, and leaves `request.user` unset.
 *
 * A rejected request gets a `403 Forbidden` problem response with no `detail`
 * by default, so the caller learns nothing about how the gateway works; the
 * reason goes to the request log. Set `status` to answer with another client
 * error, such as `404` to hide the route or `401`, `statusText` to change the
 * status text, and `detail` to add a message.
 *
 * @title Internal Only
 * @product api-gateway
 * @product ai-gateway
 * @public
 *
 * @param request - The incoming ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns The request when the gateway made it with `context.invokeRoute`, otherwise the rejection response
 *
 * @example
 * ```json
 * // policies.json - Hide a REST route that an MCP server calls as a tool
 * {
 *   "name": "internal-only-inbound",
 *   "policyType": "internal-only-inbound",
 *   "handler": {
 *     "export": "InternalOnlyInboundPolicy",
 *     "module": "$import(@zuplo/runtime)",
 *     "options": {
 *       "status": 404
 *     }
 *   }
 * }
 * ```
 */
export declare function InternalOnlyInboundPolicy(
  request: ZuploRequest,
  context: ZuploContext,
  options: InternalOnlyInboundPolicyOptions,
  policyName: string
): Promise<ZuploRequest | Response>;

/**
 * The options for this policy.
 * @public
 */
export declare interface InternalOnlyInboundPolicyOptions {
  /**
   * The HTTP status code returned to a request that did not come from inside the gateway. Any client error status from 400 to 499 is allowed. Use `404` to answer as if the route did not exist, or `401` to answer as an authentication policy does.
   */
  status?: number;
  /**
   * The status text returned with `status`, such as `Not Found` for a `404`. When it is omitted, the response uses the standard text for the status. Clients don't always receive it: HTTP/2 and HTTP/3 have no status text, and Managed Dedicated and self-hosted gateways always send the standard text.
   */
  statusText?: string;
  /**
   * The `detail` of the problem response returned to a rejected request. Every caller outside the gateway receives it, so don't describe how the route is called. When it is omitted, the response has no `detail`, and a `404` matches the response for a route that does not exist.
   */
  detail?: string;
}

/**
 * Restricts which client IP addresses can call a route using an allow list, a
 * deny list, or both. Entries are individual IP addresses or CIDR ranges, in
 * IPv4 or IPv6.
 *
 * @title IP Address Restriction
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare class IpAddressRestrictionInboundPolicy extends InboundPolicy<IpAddressRestrictionInboundPolicyOptions> {
  #private;
  static readonly policyType = "ip-address-restriction";
  constructor(
    options: IpAddressRestrictionInboundPolicyOptions,
    policyName: string
  );
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
}

/**
 * The options for this policy.
 * @public
 */
export declare interface IpAddressRestrictionInboundPolicyOptions {
  /**
   * The IP addresses and CIDR ranges that are allowed to call the route. When set, requests from every other address are rejected with a `403 Forbidden`.
   *
   * @minItems 1
   */
  allow?: [string, ...string[]];
  /**
   * The IP addresses and CIDR ranges that are rejected with a `403 Forbidden`. Evaluated before `allow`, so an address matching both lists is rejected.
   *
   * @minItems 1
   */
  deny?: [string, ...string[]];
  /**
   * Read the client IP address from this header instead of the standard forwarding headers (`x-real-ip`, `true-client-ip`, `cf-connecting-ip`, then the first entry of `x-forwarded-for`). Only set this when a proxy in front of the gateway reports the client address in a non-standard header.
   */
  clientIpHeader?: string;
  /**
   * Allow requests whose client IP address cannot be determined. By default these requests are rejected when an `allow` list is set, because an unknown address cannot be on it.
   */
  allowUnknownIpAddress?: boolean;
}

/**
 * ISO 3166-1 Alpha-2 codes
 * @public
 */
declare type Iso3166Alpha2Code =
  | "AD"
  | "AE"
  | "AF"
  | "AG"
  | "AI"
  | "AL"
  | "AM"
  | "AO"
  | "AQ"
  | "AR"
  | "AS"
  | "AT"
  | "AU"
  | "AW"
  | "AX"
  | "AZ"
  | "BA"
  | "BB"
  | "BD"
  | "BE"
  | "BF"
  | "BG"
  | "BH"
  | "BI"
  | "BJ"
  | "BL"
  | "BM"
  | "BN"
  | "BO"
  | "BQ"
  | "BR"
  | "BS"
  | "BT"
  | "BV"
  | "BW"
  | "BY"
  | "BZ"
  | "CA"
  | "CC"
  | "CD"
  | "CF"
  | "CG"
  | "CH"
  | "CI"
  | "CK"
  | "CL"
  | "CM"
  | "CN"
  | "CO"
  | "CR"
  | "CU"
  | "CV"
  | "CW"
  | "CX"
  | "CY"
  | "CZ"
  | "DE"
  | "DJ"
  | "DK"
  | "DM"
  | "DO"
  | "DZ"
  | "EC"
  | "EE"
  | "EG"
  | "EH"
  | "ER"
  | "ES"
  | "ET"
  | "FI"
  | "FJ"
  | "FK"
  | "FM"
  | "FO"
  | "FR"
  | "GA"
  | "GB"
  | "GD"
  | "GE"
  | "GF"
  | "GG"
  | "GH"
  | "GI"
  | "GL"
  | "GM"
  | "GN"
  | "GP"
  | "GQ"
  | "GR"
  | "GS"
  | "GT"
  | "GU"
  | "GW"
  | "GY"
  | "HK"
  | "HM"
  | "HN"
  | "HR"
  | "HT"
  | "HU"
  | "ID"
  | "IE"
  | "IL"
  | "IM"
  | "IN"
  | "IO"
  | "IQ"
  | "IR"
  | "IS"
  | "IT"
  | "JE"
  | "JM"
  | "JO"
  | "JP"
  | "KE"
  | "KG"
  | "KH"
  | "KI"
  | "KM"
  | "KN"
  | "KP"
  | "KR"
  | "KW"
  | "KY"
  | "KZ"
  | "LA"
  | "LB"
  | "LC"
  | "LI"
  | "LK"
  | "LR"
  | "LS"
  | "LT"
  | "LU"
  | "LV"
  | "LY"
  | "MA"
  | "MC"
  | "MD"
  | "ME"
  | "MF"
  | "MG"
  | "MH"
  | "MK"
  | "ML"
  | "MM"
  | "MN"
  | "MO"
  | "MP"
  | "MQ"
  | "MR"
  | "MS"
  | "MT"
  | "MU"
  | "MV"
  | "MW"
  | "MX"
  | "MY"
  | "MZ"
  | "NA"
  | "NC"
  | "NE"
  | "NF"
  | "NG"
  | "NI"
  | "NL"
  | "NO"
  | "NP"
  | "NR"
  | "NU"
  | "NZ"
  | "OM"
  | "PA"
  | "PE"
  | "PF"
  | "PG"
  | "PH"
  | "PK"
  | "PL"
  | "PM"
  | "PN"
  | "PR"
  | "PS"
  | "PT"
  | "PW"
  | "PY"
  | "QA"
  | "RE"
  | "RO"
  | "RS"
  | "RU"
  | "RW"
  | "SA"
  | "SB"
  | "SC"
  | "SD"
  | "SE"
  | "SG"
  | "SH"
  | "SI"
  | "SJ"
  | "SK"
  | "SL"
  | "SM"
  | "SN"
  | "SO"
  | "SR"
  | "SS"
  | "ST"
  | "SV"
  | "SX"
  | "SY"
  | "SZ"
  | "TC"
  | "TD"
  | "TF"
  | "TG"
  | "TH"
  | "TJ"
  | "TK"
  | "TL"
  | "TM"
  | "TN"
  | "TO"
  | "TR"
  | "TT"
  | "TV"
  | "TW"
  | "TZ"
  | "UA"
  | "UG"
  | "UM"
  | "US"
  | "UY"
  | "UZ"
  | "VA"
  | "VC"
  | "VE"
  | "VG"
  | "VI"
  | "VN"
  | "VU"
  | "WF"
  | "WS"
  | "YE"
  | "YT"
  | "ZA"
  | "ZM"
  | "ZW";

/**
 * API key for the service at `baseUrl`, sent as `Authorization: Bearer`: a TypeSafe key by default, or an OpenRouter key when `baseUrl` is OpenRouter.
 * @public
 */
declare type JevAPIKey = string;

/**
 * API root of the System One API that serves Jev, the same value the TypeSafe SDK's `baseURL` takes. The classifier request is sent to `{baseUrl}/v1/systemone`. Set it to `https://openrouter.ai/api` to call Jev through OpenRouter.
 * @public
 */
declare type JevBaseURL = string;

/**
 * The Jev model to call. `jev-latest` follows the newest stable release on both TypeSafe and OpenRouter. Pin a versioned id to keep answers stable after tuning `minConfidenceForRouting`: `jev-1.13.0` on TypeSafe, or `jev-1.13` on OpenRouter.
 * @public
 */
declare type JevModel = string;

/**
 * @deprecated
 * Deprecated: use `classifier.app` with `dialect` `system-one` instead. Classify with Jev, TypeSafe's classification model, by calling a System One API directly: TypeSafe's by default, or another host such as OpenRouter through `baseUrl`. Jev answers typed questions instead of generating text, so it takes no `classifierPrompt`.
 * @public
 */
declare interface JevTypeSafe {
  apiKey: JevAPIKey;
  model?: JevModel;
  baseUrl?: JevBaseURL;
}

declare type JsonArray = JsonValue[] | readonly JsonValue[];

/**
 Matches a JSON object.
 This type can be useful to enforce some input to be JSON-compatible or as a super-type to be extended from. Don't use this as a direct return type as the user would have to double-cast it: `jsonObject as unknown as CustomResponse`. Instead, you could extend your CustomResponse type from it to ensure your type only uses JSON-compatible types: `interface CustomResponse extends JsonObject { … }`.
 */
declare type JsonObject = {
  [Key in string]: JsonValue;
} & {
  [Key in string]?: JsonValue | undefined;
};

declare type JsonPrimitive = string | number | boolean | null;

/**
 Matches any valid JSON value.
 @see `Jsonify` if you need to transform a type to one that is assignable to `JsonValue`.
 */
declare type JsonValue = JsonPrimitive | JsonObject | JsonArray;

/**
 * Validates that the JWT token includes specific scopes
 *
 * @title JWT Scope Validation
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const JWTScopeValidationInboundPolicy: InboundPolicyHandler<JWTScopeValidationInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface JWTScopeValidationInboundPolicyOptions {
  /**
   * An array of of JWT scopes.
   */
  scopes: string[];
}

/**
 * Asymmetric JWT signing algorithms supported by {@link JwtServicePlugin}.
 *
 * Symmetric algorithms (e.g. `HS256`) are intentionally not supported because
 * this plugin publishes a JWKS endpoint — symmetric keys cannot be safely
 * exposed as public keys.
 *
 * - `EdDSA` — Edwards-curve (Ed25519). Modern, fast, small keys and signatures.
 * - `RS256` / `RS384` / `RS512` — RSASSA-PKCS1-v1_5 with SHA-2. Broadly interoperable.
 * - `PS256` / `PS384` / `PS512` — RSASSA-PSS with SHA-2. Recommended over `RS*` for new keys.
 * - `ES256` / `ES384` / `ES512` — ECDSA on P-256 / P-384 / P-521.
 */
export declare type JwtServiceAlgorithm =
  | "EdDSA"
  | "RS256"
  | "RS384"
  | "RS512"
  | "PS256"
  | "PS384"
  | "PS512"
  | "ES256"
  | "ES384"
  | "ES512";

export declare class JwtServicePlugin extends SystemRuntimePlugin {
  #private;
  static signJwt({
    audience,
    subject,
    expiresIn,
    ...payload
  }: JWTSignPayload): Promise<string>;
  constructor(options?: JwtServicePluginOptions);
  registerRoutes({
    runtimeSettings,
    router,
  }: {
    runtimeSettings: RuntimeSettings;
    router: Router;
  }): void;
}

export declare interface JwtServicePluginOptions {
  /**
   * The base path for the JWT issuer endpoint.
   * The default value is "/__zuplo/issuer".
   */
  basePath?: string;
  /**
   * The asymmetric signing algorithm used for issued JWTs. Must match the
   * configured key pair — e.g. an RSA key requires an `RS*` or `PS*` value,
   * a P-256 EC key requires `ES256`, and an Ed25519 key requires `EdDSA`.
   *
   * The selected value is advertised via `id_token_signing_alg_values_supported`
   * in the published OpenID configuration.
   *
   * @default "EdDSA"
   *
   * @example
   * ```ts
   * new JwtServicePlugin({ algorithm: "RS256" });
   * ```
   */
  algorithm?: JwtServiceAlgorithm;
  /**
   * Sets the default time for the "exp" (Expiration Time) Claim in the JWT.
   * This value can be overridden when signing a JWT.
   *
   * - If a `number` is passed as an argument it is treated as seconds and added to the current time.
   * - If a `string` is passed as an argument it is resolved to a time span, and then added to the
   *   current unix timestamp and used as the claim.
   *
   * Format used for time span should be a number followed by a unit, such as "5 minutes" or "1
   * day".
   *
   * Valid units are: "sec", "secs", "second", "seconds", "s", "minute", "minutes", "min", "mins",
   * "m", "hour", "hours", "hr", "hrs", "h", "day", "days", "d", "week", "weeks", "w", "year",
   * "years", "yr", "yrs", and "y". It is not possible to specify months. 365.25 days is used as an
   * alias for a year.
   *
   * If the string is suffixed with "ago", or prefixed with a "-", the resulting time span gets
   * subtracted from the current unix timestamp. A "from now" suffix can also be used for
   * readability when adding to the current unix timestamp.
   */
  expiresIn?: number | string;
}

declare interface JWTSignPayload {
  /**
   * The subject of the JWT.
   * This is typically the user ID or a unique identifier for the entity the JWT represents.
   * It is used to identify the principal that the JWT is issued to.
   * If not provided, the JWT will not have a subject claim.
   */
  subject?: string;
  /**
   * The audience of the JWT.
   * This is typically the intended recipient of the JWT, i.e. the URL of the service.
   * If not provided, the JWT will not have an audience claim.
   */
  audience?: string;
  /**
   * Sets time for the "exp" (Expiration Time) Claim in the JWT.
   *
   * - If a `number` is passed as an argument it is treated as seconds and added to the current time.
   * - If a `string` is passed as an argument it is resolved to a time span, and then added to the
   *   current unix timestamp and used as the claim.
   *
   * Format used for time span should be a number followed by a unit, such as "5 minutes" or "1
   * day".
   *
   * Valid units are: "sec", "secs", "second", "seconds", "s", "minute", "minutes", "min", "mins",
   * "m", "hour", "hours", "hr", "hrs", "h", "day", "days", "d", "week", "weeks", "w", "year",
   * "years", "yr", "yrs", and "y". It is not possible to specify months. 365.25 days is used as an
   * alias for a year.
   *
   * If the string is suffixed with "ago", or prefixed with a "-", the resulting time span gets
   * subtracted from the current unix timestamp. A "from now" suffix can also be used for
   * readability when adding to the current unix timestamp.
   */
  expiresIn?: number | string;
  [key: string]: any;
}

export declare const legacyDevPortalHandler: (
  request: ZuploRequest,
  context: ZuploContext
) => Response | Promise<Response>;

/**
 * Local shell tool
 */
declare interface LocalShellTool {
  type: "local_shell";
}

/**
 * @beta
 */
declare interface LogEntry {
  logId: string;
  logOwner: LogOwnerType;
  logSource: LogSourceType;
  level: LogLevel;
  timestamp: Date;
  loggingId: string;
  buildId: string;
  rayId: string | null;
  messages: unknown[];
  requestId: string;
  /**
   * A counter that increments each time a log is sent
   * This is to get around the issue where logs in workers often have the
   * same timestamp. We can use this number to sort order.
   */
  vectorClock: number;
}

declare interface LogField {
  name: string;
  content: Primitive;
}

/**
 * @beta
 */
declare type LogFormat = "pretty" | "json" | "gcp" | "cloudflare";

/**
 * Logger to be used in the runtime via context.log.
 * You can set per-request properties that will be included in all log entries for this request.
 * @beta
 */
export declare interface Logger extends SystemLogger {
  /**
   * Set properties for this request. They are added to every later log entry
   * for this request that a log plugin ships (Datadog, Splunk, Loki and the
   * others), and to the request's row in Zuplo's request log, which the log
   * viewer in the Zuplo Portal shows in the request's details.
   *
   * Properties apply only to the current request. Each call merges into the
   * properties already set, and a later value for the same key overwrites an
   * earlier one. In log entries, a per-request property takes precedence over
   * a static field with the same name configured in the logging plugin. A
   * request made with `context.invokeRoute` has its own properties and its
   * own row.
   *
   * To keep request rows small, a row holds at most 64 properties, a key can
   * be at most 128 characters, and a value at most 2048 characters. A longer
   * value is truncated on the row, and a property over the other limits is
   * left off the row. Log entries are not limited this way.
   *
   * @param properties - Key-value pairs for this request. Values must be string, number, or boolean.
   *
   * @example
   * ```ts
   * export default async function (request: ZuploRequest, context: ZuploContext) {
   *   // Set properties that will be included in all logs for this request
   *   context.log.setLogProperties({ http_status_code: 400, user_id: "123" });
   *
   *   context.log.error("Request failed"); // Will include http_status_code and user_id
   *
   *   return new Response("Error", { status: 400 });
   * }
   * ```
   */
  setLogProperties?(
    properties: Record<string, string | number | boolean>
  ): void;
}

/* Excluded from this release type: LoggingContext */

declare type LoggingEnvironmentStage =
  | "working-copy"
  | "preview"
  | "production"
  | "local"
  | "unknown";

/**
 * This type exists mostly because we can't break existing loggers,
 * it is probably better to have environment stage and something indicating
 * runtime (which more closely resembles what we actually use internally)
 */
declare type LoggingEnvironmentType =
  | "edge"
  | "working-copy"
  | "local"
  | "unknown";

declare interface LogInsightLogEntry {
  text: string;
  timestamp: number;
  fields: LogField[];
}

/**
 * @beta
 */
export declare type LogLevel = "debug" | "info" | "warn" | "error";

/**
 * @beta
 */
declare type LogOwnerType = "system" | "user";

declare abstract class LogPlugin extends RuntimePlugin {
  /* Excluded from this release type: getTransport */
}

declare type LogSourceType = "runtime" | "request";

/* Excluded from this release type: LogTransport */

/**
 * A logging plugin that sends logs to a Loki server.
 * @public
 */
export declare class LokiLoggingPlugin extends LogPlugin {
  private options;
  constructor(options: LokiLoggingPluginOptions);
  /* Excluded from this release type: getTransport */
}

/**
 * Options for the Loki logging plugin.
 */
declare interface LokiLoggingPluginOptions {
  /**
   * The version of the Loki transport to use.
   */
  version?: LokiTransportVersion;
  /**
   * Optional job name to include in the log stream. Defaults to "zuplo".
   */
  job?: string;
  /**
   * The URL of the Loki server.
   */
  url: string;
  /**
   * The username to authenticate with the Loki server.
   */
  username: string;
  /**
   * The password to authenticate with the Loki server.
   */
  password: string;
  /**
   * Any custom log fields to include in each log entry.
   */
  fields?: CustomLogFields;
}

/**
 * Version 1: requestId is included in the stream object
 * Version 2: requestId is included as a value in the stream object
 */
declare type LokiTransportVersion = 1 | 2;

/* Excluded from this release type: LookupResult */

/**
 * Model used for prompts classified as low complexity.
 * @public
 */
declare type LowComplexityModel = string;

/**
 * Skip caching entirely when the conversation has more than this many messages. Unset by default (no limit). Set a bound to guard against topic drift: the cache key covers only the last recentMessageCount messages, so the deeper a conversation goes, the more likely a match on recent messages alone ignores earlier context that should change the answer.
 * @public
 */
declare type MaxConversationLength = number;

/**
 * Maximum characters of user message sent to the classifier. Longer messages get truncated.
 * @public
 */
declare type MaxPromptCharacters = number;

/**
 * Authenticate MCP gateway requests using a gateway-issued OAuth access token,
 * with browser login delegated to Auth0.
 *
 * Auth0-friendly wrapper around `McpOAuthInboundPolicy`. Provide `auth0Domain`
 * and `clientId`; the constructor derives the OIDC issuer, JWKS URL, and Auth0
 * authorize/token endpoints automatically and runs the resulting shape through
 * the same Zod schema as the generic policy.
 *
 * Validation runs lazily inside the policy constructor, which the runtime
 * caches per policy name — so a misconfigured policy fails the first request
 * with a `ConfigurationError` (surfaced in the 500 problem body) rather than
 * crashing boot.
 *
 * @public
 * @title MCP Auth0 OAuth
 * @product mcp-gateway
 */
export declare class McpAuth0OAuthInboundPolicy extends InboundPolicy<McpAuth0OAuthInboundPolicyOptions> {
  #private;
  static readonly policyType = "mcp-auth0-oauth";
  constructor(rawOptions: unknown, policyName: string);
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
}

/**
 * The options for this policy.
 * @public
 */
export declare interface McpAuth0OAuthInboundPolicyOptions {
  /**
   * Your Auth0 tenant domain. The OIDC issuer, JWKS URL, /authorize URL, and /oauth/token URL are derived from this.
   */
  auth0Domain: string;
  /**
   * Optional Auth0 API audience. When set, the gateway sends it as the Auth0 authorize?audience= parameter and validates returned provider access tokens against it. Leave unset when Auth0 is only used for browser identity.
   */
  audience?: string;
  /**
   * The Auth0 client_id registered for the gateway's browser login flow.
   */
  clientId: string;
  /**
   * The Auth0 client_secret. Use $env(...) to source from a secret environment variable.
   */
  clientSecret: string;
  /**
   * OIDC scopes requested during browser login.
   */
  scope?: string;
  /**
   * Gateway-side OAuth token settings. The gateway issuer and advertised URLs are derived from the incoming request origin.
   */
  gateway?: {
    /**
     * Lifetime of access tokens issued by /oauth/token.
     */
    accessTokenTtlSeconds?: number;
    /**
     * Lifetime of refresh tokens issued by /oauth/token.
     */
    refreshTokenTtlSeconds?: number;
    /**
     * Whether to advertise client_id_metadata_document_supported in AS metadata.
     */
    cimdEnabled?: boolean;
  };
  /**
   * Optional Identity Assertion JWT Authorization Grant (ID-JAG / XAA) support for the gateway token endpoint.
   */
  idJag?:
    | {
        /**
         * Disable ID-JAG support.
         */
        enabled: false;
      }
    | {
        /**
         * Enable ID-JAG support.
         */
        enabled: true;
        /**
         * Trusted ID-JAG issuers. These values are never published in OAuth metadata. Omit to trust this policy's browser-login IdP.
         *
         * @minItems 1
         */
        trustedIssuers?: [
          {
            /**
             * Exact issuer URL expected in the ID-JAG iss claim. Provide together with jwksUrl, or omit both to default to this policy's browser-login IdP.
             */
            issuer?: string;
            /**
             * JWKS URL used to verify ID-JAG signatures from this issuer. Provide together with issuer, or omit both to default to this policy's browser-login IdP.
             */
            jwksUrl?: string;
            /**
             * Optional allow-list of client IDs accepted from this issuer. The ID-JAG client_id must still match the authenticated token-endpoint client.
             */
            expectedClientIds?: string[];
            /**
             * How the ID-JAG subject is mapped into the gateway subject ID.
             */
            subjectMapping?: "iss_prefix" | "iss_tenant_prefix" | "sub_id_only";
          },
          ...{
            /**
             * Exact issuer URL expected in the ID-JAG iss claim. Provide together with jwksUrl, or omit both to default to this policy's browser-login IdP.
             */
            issuer?: string;
            /**
             * JWKS URL used to verify ID-JAG signatures from this issuer. Provide together with issuer, or omit both to default to this policy's browser-login IdP.
             */
            jwksUrl?: string;
            /**
             * Optional allow-list of client IDs accepted from this issuer. The ID-JAG client_id must still match the authenticated token-endpoint client.
             */
            expectedClientIds?: string[];
            /**
             * How the ID-JAG subject is mapped into the gateway subject ID.
             */
            subjectMapping?: "iss_prefix" | "iss_tenant_prefix" | "sub_id_only";
          }[],
        ];
        /**
         * Optional allow-list of RFC 9396 authorization_details type values accepted from ID-JAGs.
         */
        authorizationDetailsTypesAllowed?: string[];
      };
  /**
   * Optional overrides for the derived browser-login settings.
   */
  browserLoginOverrides?: {
    remoteTimeoutMs?: number;
    stateTtlSeconds?: number;
    sessionTtlSeconds?: number;
    /**
     * Whether to send S256 PKCE on the federated browser-login authorization request and replay the verifier at the token exchange. Defaults to "none". Set to "S256" when the identity provider mandates PKCE on the authorization-code flow.
     */
    pkce?: "S256" | "none";
  };
}

/**
 * Authenticate MCP gateway requests using a gateway-issued OAuth access token,
 * with browser login delegated to Clerk.
 *
 * Clerk-friendly wrapper around `McpOAuthInboundPolicy`. Provide Clerk's
 * Frontend API URL plus the OAuth application client id and secret; the
 * constructor derives the Clerk issuer, JWKS URL, authorize URL, and token URL.
 *
 * @title MCP Clerk OAuth
 * @public
 * @product mcp-gateway
 */
export declare class McpClerkOAuthInboundPolicy extends InboundPolicy<McpClerkOAuthInboundPolicyOptions> {
  #private;
  static readonly policyType = "mcp-clerk-oauth";
  constructor(rawOptions: unknown, policyName: string);
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
}

/**
 * The options for this policy.
 * @public
 */
export declare interface McpClerkOAuthInboundPolicyOptions {
  /**
   * The Clerk Frontend API URL origin, without a trailing path, query string, or fragment.
   */
  frontendApiUrl: string;
  /**
   * The Clerk OAuth application client_id registered for the gateway's browser login flow.
   */
  clientId: string;
  /**
   * The Clerk OAuth application client_secret. Use $env(...) to source from a secret environment variable.
   */
  clientSecret: string;
  /**
   * OIDC scopes requested during browser login.
   */
  scope?: string;
  /**
   * Gateway-side OAuth token settings. The gateway issuer and advertised URLs are derived from the incoming request origin.
   */
  gateway?: {
    /**
     * Lifetime of access tokens issued by /oauth/token.
     */
    accessTokenTtlSeconds?: number;
    /**
     * Lifetime of refresh tokens issued by /oauth/token.
     */
    refreshTokenTtlSeconds?: number;
    /**
     * Whether to advertise client_id_metadata_document_supported in AS metadata.
     */
    cimdEnabled?: boolean;
  };
  /**
   * Optional Identity Assertion JWT Authorization Grant (ID-JAG / XAA) support for the gateway token endpoint.
   */
  idJag?:
    | {
        /**
         * Disable ID-JAG support.
         */
        enabled: false;
      }
    | {
        /**
         * Enable ID-JAG support.
         */
        enabled: true;
        /**
         * Trusted ID-JAG issuers. These values are never published in OAuth metadata. Omit to trust this policy's browser-login IdP.
         *
         * @minItems 1
         */
        trustedIssuers?: [
          {
            /**
             * Exact issuer URL expected in the ID-JAG iss claim. Provide together with jwksUrl, or omit both to default to this policy's browser-login IdP.
             */
            issuer?: string;
            /**
             * JWKS URL used to verify ID-JAG signatures from this issuer. Provide together with issuer, or omit both to default to this policy's browser-login IdP.
             */
            jwksUrl?: string;
            /**
             * Optional allow-list of client IDs accepted from this issuer. The ID-JAG client_id must still match the authenticated token-endpoint client.
             */
            expectedClientIds?: string[];
            /**
             * How the ID-JAG subject is mapped into the gateway subject ID.
             */
            subjectMapping?: "iss_prefix" | "iss_tenant_prefix" | "sub_id_only";
          },
          ...{
            /**
             * Exact issuer URL expected in the ID-JAG iss claim. Provide together with jwksUrl, or omit both to default to this policy's browser-login IdP.
             */
            issuer?: string;
            /**
             * JWKS URL used to verify ID-JAG signatures from this issuer. Provide together with issuer, or omit both to default to this policy's browser-login IdP.
             */
            jwksUrl?: string;
            /**
             * Optional allow-list of client IDs accepted from this issuer. The ID-JAG client_id must still match the authenticated token-endpoint client.
             */
            expectedClientIds?: string[];
            /**
             * How the ID-JAG subject is mapped into the gateway subject ID.
             */
            subjectMapping?: "iss_prefix" | "iss_tenant_prefix" | "sub_id_only";
          }[],
        ];
        /**
         * Optional allow-list of RFC 9396 authorization_details type values accepted from ID-JAGs.
         */
        authorizationDetailsTypesAllowed?: string[];
      };
  /**
   * Optional overrides for the derived browser-login settings.
   */
  browserLoginOverrides?: {
    remoteTimeoutMs?: number;
    stateTtlSeconds?: number;
    sessionTtlSeconds?: number;
  };
}

/**
 * Authenticate MCP gateway requests using a gateway-issued OAuth access token,
 * with browser login delegated to Amazon Cognito.
 *
 * Cognito-friendly wrapper around `McpOAuthInboundPolicy`. Provide an AWS
 * region, user pool id, user pool domain, client id, and client secret; the
 * constructor derives the Cognito issuer, JWKS URL, authorize URL, and token
 * URL.
 *
 * @title MCP Amazon Cognito OAuth
 * @public
 * @product mcp-gateway
 */
export declare class McpCognitoOAuthInboundPolicy extends InboundPolicy<McpCognitoOAuthInboundPolicyOptions> {
  #private;
  static readonly policyType = "mcp-cognito-oauth";
  constructor(rawOptions: unknown, policyName: string);
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
}

/**
 * The options for this policy.
 * @public
 */
export declare interface McpCognitoOAuthInboundPolicyOptions {
  /**
   * The AWS region that contains the Amazon Cognito user pool.
   */
  awsRegion: string;
  /**
   * The Amazon Cognito user pool ID.
   */
  userPoolId: string;
  /**
   * The hosted UI domain for the user pool, without https://, a trailing slash, or a path.
   */
  userPoolDomain: string;
  /**
   * The Cognito app client_id registered for the gateway's browser login flow.
   */
  clientId: string;
  /**
   * The Cognito app client_secret. Use $env(...) to source from a secret environment variable.
   */
  clientSecret: string;
  /**
   * OIDC scopes requested during browser login.
   */
  scope?: string;
  /**
   * Gateway-side OAuth token settings. The gateway issuer and advertised URLs are derived from the incoming request origin.
   */
  gateway?: {
    /**
     * Lifetime of access tokens issued by /oauth/token.
     */
    accessTokenTtlSeconds?: number;
    /**
     * Lifetime of refresh tokens issued by /oauth/token.
     */
    refreshTokenTtlSeconds?: number;
    /**
     * Whether to advertise client_id_metadata_document_supported in AS metadata.
     */
    cimdEnabled?: boolean;
  };
  /**
   * Optional Identity Assertion JWT Authorization Grant (ID-JAG / XAA) support for the gateway token endpoint.
   */
  idJag?:
    | {
        /**
         * Disable ID-JAG support.
         */
        enabled: false;
      }
    | {
        /**
         * Enable ID-JAG support.
         */
        enabled: true;
        /**
         * Trusted ID-JAG issuers. These values are never published in OAuth metadata. Omit to trust this policy's browser-login IdP.
         *
         * @minItems 1
         */
        trustedIssuers?: [
          {
            /**
             * Exact issuer URL expected in the ID-JAG iss claim. Provide together with jwksUrl, or omit both to default to this policy's browser-login IdP.
             */
            issuer?: string;
            /**
             * JWKS URL used to verify ID-JAG signatures from this issuer. Provide together with issuer, or omit both to default to this policy's browser-login IdP.
             */
            jwksUrl?: string;
            /**
             * Optional allow-list of client IDs accepted from this issuer. The ID-JAG client_id must still match the authenticated token-endpoint client.
             */
            expectedClientIds?: string[];
            /**
             * How the ID-JAG subject is mapped into the gateway subject ID.
             */
            subjectMapping?: "iss_prefix" | "iss_tenant_prefix" | "sub_id_only";
          },
          ...{
            /**
             * Exact issuer URL expected in the ID-JAG iss claim. Provide together with jwksUrl, or omit both to default to this policy's browser-login IdP.
             */
            issuer?: string;
            /**
             * JWKS URL used to verify ID-JAG signatures from this issuer. Provide together with issuer, or omit both to default to this policy's browser-login IdP.
             */
            jwksUrl?: string;
            /**
             * Optional allow-list of client IDs accepted from this issuer. The ID-JAG client_id must still match the authenticated token-endpoint client.
             */
            expectedClientIds?: string[];
            /**
             * How the ID-JAG subject is mapped into the gateway subject ID.
             */
            subjectMapping?: "iss_prefix" | "iss_tenant_prefix" | "sub_id_only";
          }[],
        ];
        /**
         * Optional allow-list of RFC 9396 authorization_details type values accepted from ID-JAGs.
         */
        authorizationDetailsTypesAllowed?: string[];
      };
  /**
   * Optional overrides for the derived browser-login settings.
   */
  browserLoginOverrides?: {
    remoteTimeoutMs?: number;
    stateTtlSeconds?: number;
    sessionTtlSeconds?: number;
    /**
     * Whether to send S256 PKCE on the federated browser-login authorization request and replay the verifier at the token exchange. Defaults to "none". Set to "S256" when the identity provider mandates PKCE on the authorization-code flow.
     */
    pkce?: "S256" | "none";
  };
}

/**
 * Authenticate MCP gateway requests using a gateway-issued OAuth access token,
 * with browser login delegated to Microsoft Entra ID.
 *
 * Entra-friendly wrapper around `McpOAuthInboundPolicy`. Provide a tenant UUID,
 * application client id, and client secret; the constructor derives the Entra
 * v2 issuer, JWKS URL, authorize URL, and token URL.
 *
 * @title MCP Microsoft Entra OAuth
 * @public
 * @product mcp-gateway
 */
export declare class McpEntraOAuthInboundPolicy extends InboundPolicy<McpEntraOAuthInboundPolicyOptions> {
  #private;
  static readonly policyType = "mcp-entra-oauth";
  constructor(rawOptions: unknown, policyName: string);
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
}

/**
 * The options for this policy.
 * @public
 */
export declare interface McpEntraOAuthInboundPolicyOptions {
  /**
   * The Microsoft Entra tenant UUID. Multi-tenant aliases like common and organizations are not supported by this policy yet.
   */
  tenantId: string;
  /**
   * The Microsoft Entra application (client) ID UUID registered for the gateway's browser login flow.
   */
  clientId: string;
  /**
   * The Microsoft Entra client secret. Use $env(...) to source from a secret environment variable.
   */
  clientSecret: string;
  /**
   * OIDC scopes requested during browser login.
   */
  scope?: string;
  /**
   * Gateway-side OAuth token settings. The gateway issuer and advertised URLs are derived from the incoming request origin.
   */
  gateway?: {
    /**
     * Lifetime of access tokens issued by /oauth/token.
     */
    accessTokenTtlSeconds?: number;
    /**
     * Lifetime of refresh tokens issued by /oauth/token.
     */
    refreshTokenTtlSeconds?: number;
    /**
     * Whether to advertise client_id_metadata_document_supported in AS metadata.
     */
    cimdEnabled?: boolean;
  };
  /**
   * Optional Identity Assertion JWT Authorization Grant (ID-JAG / XAA) support for the gateway token endpoint.
   */
  idJag?:
    | {
        /**
         * Disable ID-JAG support.
         */
        enabled: false;
      }
    | {
        /**
         * Enable ID-JAG support.
         */
        enabled: true;
        /**
         * Trusted ID-JAG issuers. These values are never published in OAuth metadata. Omit to trust this policy's browser-login IdP.
         *
         * @minItems 1
         */
        trustedIssuers?: [
          {
            /**
             * Exact issuer URL expected in the ID-JAG iss claim. Provide together with jwksUrl, or omit both to default to this policy's browser-login IdP.
             */
            issuer?: string;
            /**
             * JWKS URL used to verify ID-JAG signatures from this issuer. Provide together with issuer, or omit both to default to this policy's browser-login IdP.
             */
            jwksUrl?: string;
            /**
             * Optional allow-list of client IDs accepted from this issuer. The ID-JAG client_id must still match the authenticated token-endpoint client.
             */
            expectedClientIds?: string[];
            /**
             * How the ID-JAG subject is mapped into the gateway subject ID.
             */
            subjectMapping?: "iss_prefix" | "iss_tenant_prefix" | "sub_id_only";
          },
          ...{
            /**
             * Exact issuer URL expected in the ID-JAG iss claim. Provide together with jwksUrl, or omit both to default to this policy's browser-login IdP.
             */
            issuer?: string;
            /**
             * JWKS URL used to verify ID-JAG signatures from this issuer. Provide together with issuer, or omit both to default to this policy's browser-login IdP.
             */
            jwksUrl?: string;
            /**
             * Optional allow-list of client IDs accepted from this issuer. The ID-JAG client_id must still match the authenticated token-endpoint client.
             */
            expectedClientIds?: string[];
            /**
             * How the ID-JAG subject is mapped into the gateway subject ID.
             */
            subjectMapping?: "iss_prefix" | "iss_tenant_prefix" | "sub_id_only";
          }[],
        ];
        /**
         * Optional allow-list of RFC 9396 authorization_details type values accepted from ID-JAGs.
         */
        authorizationDetailsTypesAllowed?: string[];
      };
  /**
   * Optional overrides for the derived browser-login settings.
   */
  browserLoginOverrides?: {
    remoteTimeoutMs?: number;
    stateTtlSeconds?: number;
    sessionTtlSeconds?: number;
    /**
     * Whether to send S256 PKCE on the federated browser-login authorization request and replay the verifier at the token exchange. Defaults to "none". Set to "S256" when the identity provider mandates PKCE on the authorization-code flow.
     */
    pkce?: "S256" | "none";
  };
}

/* Excluded from this release type: McpGatewayOAuthProtectedResourcePlugin */

/**
 * Authenticate MCP gateway requests using a gateway-issued OAuth access token,
 * with browser login delegated to Google.
 *
 * Google-friendly wrapper around `McpOAuthInboundPolicy`. Provide `clientId`
 * and `clientSecret`; the constructor uses Google's fixed OIDC issuer, JWKS
 * URL, authorize URL, and token URL, then runs the resulting shape through the
 * same Zod schema as the generic policy.
 *
 * @title MCP Google OAuth
 * @public
 * @product mcp-gateway
 */
export declare class McpGoogleOAuthInboundPolicy extends InboundPolicy<McpGoogleOAuthInboundPolicyOptions> {
  #private;
  static readonly policyType = "mcp-google-oauth";
  constructor(rawOptions: unknown, policyName: string);
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
}

/**
 * The options for this policy.
 * @public
 */
export declare interface McpGoogleOAuthInboundPolicyOptions {
  /**
   * The Google OAuth client_id registered for the gateway's browser login flow. Google uses a fixed OIDC issuer and discovery endpoint.
   */
  clientId: string;
  /**
   * The Google OAuth client_secret. Use $env(...) to source from a secret environment variable.
   */
  clientSecret: string;
  /**
   * OIDC scopes requested during browser login.
   */
  scope?: string;
  /**
   * Gateway-side OAuth token settings. The gateway issuer and advertised URLs are derived from the incoming request origin.
   */
  gateway?: {
    /**
     * Lifetime of access tokens issued by /oauth/token.
     */
    accessTokenTtlSeconds?: number;
    /**
     * Lifetime of refresh tokens issued by /oauth/token.
     */
    refreshTokenTtlSeconds?: number;
    /**
     * Whether to advertise client_id_metadata_document_supported in AS metadata.
     */
    cimdEnabled?: boolean;
  };
  /**
   * Optional Identity Assertion JWT Authorization Grant (ID-JAG / XAA) support for the gateway token endpoint.
   */
  idJag?:
    | {
        /**
         * Disable ID-JAG support.
         */
        enabled: false;
      }
    | {
        /**
         * Enable ID-JAG support.
         */
        enabled: true;
        /**
         * Trusted ID-JAG issuers. These values are never published in OAuth metadata. Omit to trust this policy's browser-login IdP.
         *
         * @minItems 1
         */
        trustedIssuers?: [
          {
            /**
             * Exact issuer URL expected in the ID-JAG iss claim. Provide together with jwksUrl, or omit both to default to this policy's browser-login IdP.
             */
            issuer?: string;
            /**
             * JWKS URL used to verify ID-JAG signatures from this issuer. Provide together with issuer, or omit both to default to this policy's browser-login IdP.
             */
            jwksUrl?: string;
            /**
             * Optional allow-list of client IDs accepted from this issuer. The ID-JAG client_id must still match the authenticated token-endpoint client.
             */
            expectedClientIds?: string[];
            /**
             * How the ID-JAG subject is mapped into the gateway subject ID.
             */
            subjectMapping?: "iss_prefix" | "iss_tenant_prefix" | "sub_id_only";
          },
          ...{
            /**
             * Exact issuer URL expected in the ID-JAG iss claim. Provide together with jwksUrl, or omit both to default to this policy's browser-login IdP.
             */
            issuer?: string;
            /**
             * JWKS URL used to verify ID-JAG signatures from this issuer. Provide together with issuer, or omit both to default to this policy's browser-login IdP.
             */
            jwksUrl?: string;
            /**
             * Optional allow-list of client IDs accepted from this issuer. The ID-JAG client_id must still match the authenticated token-endpoint client.
             */
            expectedClientIds?: string[];
            /**
             * How the ID-JAG subject is mapped into the gateway subject ID.
             */
            subjectMapping?: "iss_prefix" | "iss_tenant_prefix" | "sub_id_only";
          }[],
        ];
        /**
         * Optional allow-list of RFC 9396 authorization_details type values accepted from ID-JAGs.
         */
        authorizationDetailsTypesAllowed?: string[];
      };
  /**
   * Optional overrides for the derived browser-login settings.
   */
  browserLoginOverrides?: {
    remoteTimeoutMs?: number;
    stateTtlSeconds?: number;
    sessionTtlSeconds?: number;
    /**
     * Whether to send S256 PKCE on the federated browser-login authorization request and replay the verifier at the token exchange. Defaults to "none". Set to "S256" when the identity provider mandates PKCE on the authorization-code flow.
     */
    pkce?: "S256" | "none";
  };
}

/**
 * Authenticate MCP gateway requests using a gateway-issued OAuth access token,
 * with browser login delegated to Keycloak.
 *
 * Keycloak-friendly wrapper around `McpOAuthInboundPolicy`. Provide the
 * Keycloak server root, realm, client id, and client secret; the constructor
 * derives the realm issuer, JWKS URL, authorize URL, and token URL from
 * Keycloak's documented OIDC endpoint layout.
 *
 * @title MCP Keycloak OAuth
 * @public
 * @product mcp-gateway
 */
export declare class McpKeycloakOAuthInboundPolicy extends InboundPolicy<McpKeycloakOAuthInboundPolicyOptions> {
  #private;
  static readonly policyType = "mcp-keycloak-oauth";
  constructor(rawOptions: unknown, policyName: string);
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
}

/**
 * The options for this policy.
 * @public
 */
export declare interface McpKeycloakOAuthInboundPolicyOptions {
  /**
   * The absolute URL for the Keycloak server root. Do not include /realms/{realm}; set the realm option separately.
   */
  keycloakBaseUrl: string;
  /**
   * The Keycloak realm name.
   */
  realm: string;
  /**
   * The Keycloak OIDC client_id registered for the gateway's browser login flow.
   */
  clientId: string;
  /**
   * The Keycloak OIDC client_secret. Use $env(...) to source from a secret environment variable.
   */
  clientSecret: string;
  /**
   * OIDC scopes requested during browser login.
   */
  scope?: string;
  /**
   * Gateway-side OAuth token settings. The gateway issuer and advertised URLs are derived from the incoming request origin.
   */
  gateway?: {
    /**
     * Lifetime of access tokens issued by /oauth/token.
     */
    accessTokenTtlSeconds?: number;
    /**
     * Lifetime of refresh tokens issued by /oauth/token.
     */
    refreshTokenTtlSeconds?: number;
    /**
     * Whether to advertise client_id_metadata_document_supported in AS metadata.
     */
    cimdEnabled?: boolean;
  };
  /**
   * Optional Identity Assertion JWT Authorization Grant (ID-JAG / XAA) support for the gateway token endpoint.
   */
  idJag?:
    | {
        /**
         * Disable ID-JAG support.
         */
        enabled: false;
      }
    | {
        /**
         * Enable ID-JAG support.
         */
        enabled: true;
        /**
         * Trusted ID-JAG issuers. These values are never published in OAuth metadata. Omit to trust this policy's browser-login IdP.
         *
         * @minItems 1
         */
        trustedIssuers?: [
          {
            /**
             * Exact issuer URL expected in the ID-JAG iss claim. Provide together with jwksUrl, or omit both to default to this policy's browser-login IdP.
             */
            issuer?: string;
            /**
             * JWKS URL used to verify ID-JAG signatures from this issuer. Provide together with issuer, or omit both to default to this policy's browser-login IdP.
             */
            jwksUrl?: string;
            /**
             * Optional allow-list of client IDs accepted from this issuer. The ID-JAG client_id must still match the authenticated token-endpoint client.
             */
            expectedClientIds?: string[];
            /**
             * How the ID-JAG subject is mapped into the gateway subject ID.
             */
            subjectMapping?: "iss_prefix" | "iss_tenant_prefix" | "sub_id_only";
          },
          ...{
            /**
             * Exact issuer URL expected in the ID-JAG iss claim. Provide together with jwksUrl, or omit both to default to this policy's browser-login IdP.
             */
            issuer?: string;
            /**
             * JWKS URL used to verify ID-JAG signatures from this issuer. Provide together with issuer, or omit both to default to this policy's browser-login IdP.
             */
            jwksUrl?: string;
            /**
             * Optional allow-list of client IDs accepted from this issuer. The ID-JAG client_id must still match the authenticated token-endpoint client.
             */
            expectedClientIds?: string[];
            /**
             * How the ID-JAG subject is mapped into the gateway subject ID.
             */
            subjectMapping?: "iss_prefix" | "iss_tenant_prefix" | "sub_id_only";
          }[],
        ];
        /**
         * Optional allow-list of RFC 9396 authorization_details type values accepted from ID-JAGs.
         */
        authorizationDetailsTypesAllowed?: string[];
      };
  /**
   * Optional overrides for the derived browser-login settings.
   */
  browserLoginOverrides?: {
    remoteTimeoutMs?: number;
    stateTtlSeconds?: number;
    sessionTtlSeconds?: number;
    /**
     * Whether to send S256 PKCE on the federated browser-login authorization request and replay the verifier at the token exchange. Defaults to "none". Set to "S256" when the identity provider mandates PKCE on the authorization-code flow.
     */
    pkce?: "S256" | "none";
  };
}

/**
 * Authenticate MCP gateway requests using a gateway-issued OAuth access token,
 * with browser login delegated to Logto.
 *
 * Logto-friendly wrapper around `McpOAuthInboundPolicy`. Provide the Logto
 * tenant endpoint, client id, and client secret; the constructor derives the
 * Logto `/oidc` issuer, JWKS URL, authorize URL, and token URL.
 *
 * @title MCP Logto OAuth
 * @public
 * @product mcp-gateway
 */
export declare class McpLogtoOAuthInboundPolicy extends InboundPolicy<McpLogtoOAuthInboundPolicyOptions> {
  #private;
  static readonly policyType = "mcp-logto-oauth";
  constructor(rawOptions: unknown, policyName: string);
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
}

/**
 * The options for this policy.
 * @public
 */
export declare interface McpLogtoOAuthInboundPolicyOptions {
  /**
   * Your Logto tenant endpoint or custom domain, without the /oidc path. The OIDC issuer, JWKS URL, authorization URL, and token URL are derived from this.
   */
  logtoEndpoint: string;
  /**
   * The Logto application client_id registered for the gateway's browser login flow.
   */
  clientId: string;
  /**
   * The Logto application client_secret. Use $env(...) to source from a secret environment variable.
   */
  clientSecret: string;
  /**
   * OIDC scopes requested during browser login.
   */
  scope?: string;
  /**
   * Gateway-side OAuth token settings. The gateway issuer and advertised URLs are derived from the incoming request origin.
   */
  gateway?: {
    /**
     * Lifetime of access tokens issued by /oauth/token.
     */
    accessTokenTtlSeconds?: number;
    /**
     * Lifetime of refresh tokens issued by /oauth/token.
     */
    refreshTokenTtlSeconds?: number;
    /**
     * Whether to advertise client_id_metadata_document_supported in AS metadata.
     */
    cimdEnabled?: boolean;
  };
  /**
   * Optional Identity Assertion JWT Authorization Grant (ID-JAG / XAA) support for the gateway token endpoint.
   */
  idJag?:
    | {
        /**
         * Disable ID-JAG support.
         */
        enabled: false;
      }
    | {
        /**
         * Enable ID-JAG support.
         */
        enabled: true;
        /**
         * Trusted ID-JAG issuers. These values are never published in OAuth metadata. Omit to trust this policy's browser-login IdP.
         *
         * @minItems 1
         */
        trustedIssuers?: [
          {
            /**
             * Exact issuer URL expected in the ID-JAG iss claim. Provide together with jwksUrl, or omit both to default to this policy's browser-login IdP.
             */
            issuer?: string;
            /**
             * JWKS URL used to verify ID-JAG signatures from this issuer. Provide together with issuer, or omit both to default to this policy's browser-login IdP.
             */
            jwksUrl?: string;
            /**
             * Optional allow-list of client IDs accepted from this issuer. The ID-JAG client_id must still match the authenticated token-endpoint client.
             */
            expectedClientIds?: string[];
            /**
             * How the ID-JAG subject is mapped into the gateway subject ID.
             */
            subjectMapping?: "iss_prefix" | "iss_tenant_prefix" | "sub_id_only";
          },
          ...{
            /**
             * Exact issuer URL expected in the ID-JAG iss claim. Provide together with jwksUrl, or omit both to default to this policy's browser-login IdP.
             */
            issuer?: string;
            /**
             * JWKS URL used to verify ID-JAG signatures from this issuer. Provide together with issuer, or omit both to default to this policy's browser-login IdP.
             */
            jwksUrl?: string;
            /**
             * Optional allow-list of client IDs accepted from this issuer. The ID-JAG client_id must still match the authenticated token-endpoint client.
             */
            expectedClientIds?: string[];
            /**
             * How the ID-JAG subject is mapped into the gateway subject ID.
             */
            subjectMapping?: "iss_prefix" | "iss_tenant_prefix" | "sub_id_only";
          }[],
        ];
        /**
         * Optional allow-list of RFC 9396 authorization_details type values accepted from ID-JAGs.
         */
        authorizationDetailsTypesAllowed?: string[];
      };
  /**
   * Optional overrides for the derived browser-login settings.
   */
  browserLoginOverrides?: {
    remoteTimeoutMs?: number;
    stateTtlSeconds?: number;
    sessionTtlSeconds?: number;
    /**
     * Whether to send S256 PKCE on the federated browser-login authorization request and replay the verifier at the token exchange. Defaults to "none". Set to "S256" when the identity provider mandates PKCE on the authorization-code flow.
     */
    pkce?: "S256" | "none";
  };
}

/**
 * Authenticate MCP gateway requests using a gateway-issued OAuth access token.
 *
 * The gateway hosts its own OAuth authorization server endpoints (DCR,
 * `/authorize`, `/token`, `/callback`) — registered automatically when this
 * policy is present in `policies.json`. End-user browser login is delegated
 * to the OpenID Connect identity provider configured via the `oidc` and
 * `browserLogin` policy options.
 *
 * Validation runs lazily inside the policy constructor, which the runtime
 * caches per policy name — so a misconfigured policy fails the first request
 * with a `ConfigurationError` (surfaced in the 500 problem body) rather than
 * crashing boot.
 *
 * @public
 * @title MCP OAuth
 * @product mcp-gateway
 */
export declare class McpOAuthInboundPolicy extends InboundPolicy<McpOAuthRuntimeConfig> {
  static readonly policyType = "mcp-oauth";
  constructor(rawOptions: unknown, policyName: string);
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
}

/**
 * The options for this policy.
 * @public
 */
export declare interface McpOAuthInboundPolicyOptions {
  /**
   * OpenID Connect identity provider that authenticates end-users before the gateway issues its own OAuth access token.
   */
  oidc: {
    /**
     * The OIDC issuer URL of the identity provider.
     */
    issuer: string;
    /**
     * The JWKS endpoint used to verify ID tokens issued by the identity provider.
     */
    jwksUrl: string;
    /**
     * Optional IdP audience value. Leave unset when browser login ID tokens use the OIDC client_id as their audience.
     */
    audience?: string;
  };
  /**
   * Browser-side OAuth/OIDC settings used when the gateway redirects the user to the identity provider for login.
   */
  browserLogin: {
    /**
     * The IdP /authorize endpoint to redirect the user to. For local development on loopback, use http://127.0.0.1:9000/__zuplo/oauth/dev-login (the gateway's default basePath is /__zuplo; adjust if the plugin is configured with a different one).
     */
    url: string;
    /**
     * The IdP token endpoint used for the federated authorization code exchange. Required for federated_oidc browser login.
     */
    tokenUrl?: string;
    /**
     * The OIDC client_id registered with the identity provider for the gateway's browser login flow.
     */
    clientId?: string;
    /**
     * The OIDC client_secret. Required for federated browser login. Use $env(...) to source from a secret environment variable.
     */
    clientSecret?: string;
    /**
     * The OIDC scopes requested during browser login.
     */
    scope?: string;
    /**
     * Optional audience parameter for the IdP authorization request (Auth0-style API audiences).
     */
    audience?: string;
    /**
     * Whether to send S256 PKCE on the federated browser-login authorization request and replay the verifier at the token exchange. Defaults to "none". Set to "S256" when the identity provider mandates PKCE on the authorization-code flow (e.g. OAuth 2.1 IdPs, hardened Okta/Entra tenants). Leave as "none" for IdPs that may reject unexpected PKCE parameters.
     */
    pkce?: "S256" | "none";
    /**
     * Timeout for outbound calls to the IdP (token exchange, JWKS fetch).
     */
    remoteTimeoutMs?: number;
    /**
     * Lifetime of an in-flight browser-login state record.
     */
    stateTtlSeconds?: number;
    /**
     * Lifetime of the gateway browser-login session cookie issued after a successful login.
     */
    sessionTtlSeconds?: number;
  };
  /**
   * Gateway-side OAuth token settings. The gateway issuer and advertised URLs are derived from the incoming request origin.
   */
  gateway?: {
    /**
     * Lifetime of access tokens issued by /oauth/token.
     */
    accessTokenTtlSeconds?: number;
    /**
     * Lifetime of refresh tokens issued by /oauth/token.
     */
    refreshTokenTtlSeconds?: number;
    /**
     * Whether to advertise client_id_metadata_document_supported in AS metadata.
     */
    cimdEnabled?: boolean;
  };
  /**
   * Optional Identity Assertion JWT Authorization Grant (ID-JAG / XAA) support for the gateway token endpoint.
   */
  idJag?:
    | {
        /**
         * Disable ID-JAG support.
         */
        enabled: false;
      }
    | {
        /**
         * Enable ID-JAG support.
         */
        enabled: true;
        /**
         * Trusted ID-JAG issuers. These values are never published in OAuth metadata. Omit to trust this policy's browser-login IdP.
         *
         * @minItems 1
         */
        trustedIssuers?: [
          {
            /**
             * Exact issuer URL expected in the ID-JAG iss claim. Provide together with jwksUrl, or omit both to default to this policy's browser-login IdP.
             */
            issuer?: string;
            /**
             * JWKS URL used to verify ID-JAG signatures from this issuer. Provide together with issuer, or omit both to default to this policy's browser-login IdP.
             */
            jwksUrl?: string;
            /**
             * Optional allow-list of client IDs accepted from this issuer. The ID-JAG client_id must still match the authenticated token-endpoint client.
             */
            expectedClientIds?: string[];
            /**
             * How the ID-JAG subject is mapped into the gateway subject ID.
             */
            subjectMapping?: "iss_prefix" | "iss_tenant_prefix" | "sub_id_only";
          },
          ...{
            /**
             * Exact issuer URL expected in the ID-JAG iss claim. Provide together with jwksUrl, or omit both to default to this policy's browser-login IdP.
             */
            issuer?: string;
            /**
             * JWKS URL used to verify ID-JAG signatures from this issuer. Provide together with issuer, or omit both to default to this policy's browser-login IdP.
             */
            jwksUrl?: string;
            /**
             * Optional allow-list of client IDs accepted from this issuer. The ID-JAG client_id must still match the authenticated token-endpoint client.
             */
            expectedClientIds?: string[];
            /**
             * How the ID-JAG subject is mapped into the gateway subject ID.
             */
            subjectMapping?: "iss_prefix" | "iss_tenant_prefix" | "sub_id_only";
          }[],
        ];
        /**
         * Optional allow-list of RFC 9396 authorization_details type values accepted from ID-JAGs.
         */
        authorizationDetailsTypesAllowed?: string[];
      };
}

/**
 * The gateway's resolved OAuth runtime configuration — the parsed, defaulted
 * output of {@link mcpOAuthRuntimeConfigSchema}. Hand-written so the public
 * MCP OAuth policy class signatures contain no zod types; the assertion below
 * fails to compile if this interface drifts from the schema.
 */
declare interface McpOAuthRuntimeConfig {
  oidc: {
    issuer: string;
    jwksUrl: string;
    audience?: string;
  };
  browserLogin: {
    url: string;
    tokenUrl?: string;
    clientId?: string;
    clientSecret?: string;
    scope: string;
    audience?: string;
    pkce: "S256" | "none";
    remoteTimeoutMs: number;
    stateTtlSeconds: number;
    sessionTtlSeconds: number;
  };
  gateway: {
    accessTokenTtlSeconds: number;
    refreshTokenTtlSeconds: number;
    downstreamCimdEnabled: boolean;
  };
  idJag: IdJagRuntimeConfig;
}

/**
 * Authenticate MCP gateway requests using a gateway-issued OAuth access token,
 * with browser login delegated to Okta.
 *
 * Okta-friendly wrapper around `McpOAuthInboundPolicy`. Provide an Okta org
 * domain, optional authorization server id, client id, and client secret; the
 * constructor derives the Okta issuer, JWKS URL, authorize URL, and token URL.
 *
 * @title MCP Okta OAuth
 * @public
 * @product mcp-gateway
 */
export declare class McpOktaOAuthInboundPolicy extends InboundPolicy<McpOktaOAuthInboundPolicyOptions> {
  #private;
  static readonly policyType = "mcp-okta-oauth";
  constructor(rawOptions: unknown, policyName: string);
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
}

/**
 * The options for this policy.
 * @public
 */
export declare interface McpOktaOAuthInboundPolicyOptions {
  /**
   * The Okta org domain, without https://, a trailing slash, or a path.
   */
  oktaDomain: string;
  /**
   * Optional Okta custom authorization server id. Omit this to use the org authorization server.
   */
  authorizationServerId?: string;
  /**
   * The Okta OIDC application client_id registered for the gateway's browser login flow.
   */
  clientId: string;
  /**
   * The Okta OIDC application client_secret. Use $env(...) to source from a secret environment variable.
   */
  clientSecret: string;
  /**
   * OIDC scopes requested during browser login.
   */
  scope?: string;
  /**
   * Gateway-side OAuth token settings. The gateway issuer and advertised URLs are derived from the incoming request origin.
   */
  gateway?: {
    /**
     * Lifetime of access tokens issued by /oauth/token.
     */
    accessTokenTtlSeconds?: number;
    /**
     * Lifetime of refresh tokens issued by /oauth/token.
     */
    refreshTokenTtlSeconds?: number;
    /**
     * Whether to advertise client_id_metadata_document_supported in AS metadata.
     */
    cimdEnabled?: boolean;
  };
  /**
   * Optional Identity Assertion JWT Authorization Grant (ID-JAG / XAA) support for the gateway token endpoint.
   */
  idJag?:
    | {
        /**
         * Disable ID-JAG support.
         */
        enabled: false;
      }
    | {
        /**
         * Enable ID-JAG support.
         */
        enabled: true;
        /**
         * Trusted ID-JAG issuers. These values are never published in OAuth metadata. Omit to trust this policy's browser-login IdP.
         *
         * @minItems 1
         */
        trustedIssuers?: [
          {
            /**
             * Exact issuer URL expected in the ID-JAG iss claim. Provide together with jwksUrl, or omit both to default to this policy's browser-login IdP.
             */
            issuer?: string;
            /**
             * JWKS URL used to verify ID-JAG signatures from this issuer. Provide together with issuer, or omit both to default to this policy's browser-login IdP.
             */
            jwksUrl?: string;
            /**
             * Optional allow-list of client IDs accepted from this issuer. The ID-JAG client_id must still match the authenticated token-endpoint client.
             */
            expectedClientIds?: string[];
            /**
             * How the ID-JAG subject is mapped into the gateway subject ID.
             */
            subjectMapping?: "iss_prefix" | "iss_tenant_prefix" | "sub_id_only";
          },
          ...{
            /**
             * Exact issuer URL expected in the ID-JAG iss claim. Provide together with jwksUrl, or omit both to default to this policy's browser-login IdP.
             */
            issuer?: string;
            /**
             * JWKS URL used to verify ID-JAG signatures from this issuer. Provide together with issuer, or omit both to default to this policy's browser-login IdP.
             */
            jwksUrl?: string;
            /**
             * Optional allow-list of client IDs accepted from this issuer. The ID-JAG client_id must still match the authenticated token-endpoint client.
             */
            expectedClientIds?: string[];
            /**
             * How the ID-JAG subject is mapped into the gateway subject ID.
             */
            subjectMapping?: "iss_prefix" | "iss_tenant_prefix" | "sub_id_only";
          }[],
        ];
        /**
         * Optional allow-list of RFC 9396 authorization_details type values accepted from ID-JAGs.
         */
        authorizationDetailsTypesAllowed?: string[];
      };
  /**
   * Optional overrides for the derived browser-login settings.
   */
  browserLoginOverrides?: {
    remoteTimeoutMs?: number;
    stateTtlSeconds?: number;
    sessionTtlSeconds?: number;
    /**
     * Whether to send S256 PKCE on the federated browser-login authorization request and replay the verifier at the token exchange. Defaults to "none". Set to "S256" when the identity provider mandates PKCE on the authorization-code flow.
     */
    pkce?: "S256" | "none";
  };
}

/**
 * Authenticate MCP gateway requests using a gateway-issued OAuth access token,
 * with browser login delegated to OneLogin.
 *
 * OneLogin-friendly wrapper around `McpOAuthInboundPolicy`. Provide the
 * OneLogin account subdomain, client id, and client secret; the constructor
 * derives OneLogin's OIDC issuer, JWKS URL, authorize URL, and token URL.
 *
 * @title MCP OneLogin OAuth
 * @public
 * @product mcp-gateway
 */
export declare class McpOneLoginOAuthInboundPolicy extends InboundPolicy<McpOneLoginOAuthInboundPolicyOptions> {
  #private;
  static readonly policyType = "mcp-onelogin-oauth";
  constructor(rawOptions: unknown, policyName: string);
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
}

/**
 * The options for this policy.
 * @public
 */
export declare interface McpOneLoginOAuthInboundPolicyOptions {
  /**
   * The OneLogin account subdomain, without https://, .onelogin.com, a trailing slash, or a path.
   */
  oneLoginSubdomain: string;
  /**
   * The OneLogin OIDC application client_id registered for the gateway's browser login flow.
   */
  clientId: string;
  /**
   * The OneLogin OIDC application client_secret. Use $env(...) to source from a secret environment variable.
   */
  clientSecret: string;
  /**
   * OIDC scopes requested during browser login.
   */
  scope?: string;
  /**
   * Gateway-side OAuth token settings. The gateway issuer and advertised URLs are derived from the incoming request origin.
   */
  gateway?: {
    /**
     * Lifetime of access tokens issued by /oauth/token.
     */
    accessTokenTtlSeconds?: number;
    /**
     * Lifetime of refresh tokens issued by /oauth/token.
     */
    refreshTokenTtlSeconds?: number;
    /**
     * Whether to advertise client_id_metadata_document_supported in AS metadata.
     */
    cimdEnabled?: boolean;
  };
  /**
   * Optional Identity Assertion JWT Authorization Grant (ID-JAG / XAA) support for the gateway token endpoint.
   */
  idJag?:
    | {
        /**
         * Disable ID-JAG support.
         */
        enabled: false;
      }
    | {
        /**
         * Enable ID-JAG support.
         */
        enabled: true;
        /**
         * Trusted ID-JAG issuers. These values are never published in OAuth metadata. Omit to trust this policy's browser-login IdP.
         *
         * @minItems 1
         */
        trustedIssuers?: [
          {
            /**
             * Exact issuer URL expected in the ID-JAG iss claim. Provide together with jwksUrl, or omit both to default to this policy's browser-login IdP.
             */
            issuer?: string;
            /**
             * JWKS URL used to verify ID-JAG signatures from this issuer. Provide together with issuer, or omit both to default to this policy's browser-login IdP.
             */
            jwksUrl?: string;
            /**
             * Optional allow-list of client IDs accepted from this issuer. The ID-JAG client_id must still match the authenticated token-endpoint client.
             */
            expectedClientIds?: string[];
            /**
             * How the ID-JAG subject is mapped into the gateway subject ID.
             */
            subjectMapping?: "iss_prefix" | "iss_tenant_prefix" | "sub_id_only";
          },
          ...{
            /**
             * Exact issuer URL expected in the ID-JAG iss claim. Provide together with jwksUrl, or omit both to default to this policy's browser-login IdP.
             */
            issuer?: string;
            /**
             * JWKS URL used to verify ID-JAG signatures from this issuer. Provide together with issuer, or omit both to default to this policy's browser-login IdP.
             */
            jwksUrl?: string;
            /**
             * Optional allow-list of client IDs accepted from this issuer. The ID-JAG client_id must still match the authenticated token-endpoint client.
             */
            expectedClientIds?: string[];
            /**
             * How the ID-JAG subject is mapped into the gateway subject ID.
             */
            subjectMapping?: "iss_prefix" | "iss_tenant_prefix" | "sub_id_only";
          }[],
        ];
        /**
         * Optional allow-list of RFC 9396 authorization_details type values accepted from ID-JAGs.
         */
        authorizationDetailsTypesAllowed?: string[];
      };
  /**
   * Optional overrides for the derived browser-login settings.
   */
  browserLoginOverrides?: {
    remoteTimeoutMs?: number;
    stateTtlSeconds?: number;
    sessionTtlSeconds?: number;
  };
}

/**
 * Authenticate MCP gateway requests using a gateway-issued OAuth access token,
 * with browser login delegated to PingOne.
 *
 * PingOne-friendly wrapper around `McpOAuthInboundPolicy`. Provide a PingOne
 * environment ID plus optional region, or a PingOne custom domain, with client
 * ID and client secret; the constructor derives the PingOne issuer, JWKS URL,
 * authorize URL, and token URL.
 *
 * @title MCP Ping OAuth
 * @public
 * @product mcp-gateway
 */
export declare class McpPingOAuthInboundPolicy extends InboundPolicy<McpPingOAuthInboundPolicyOptions> {
  #private;
  static readonly policyType = "mcp-ping-oauth";
  constructor(rawOptions: unknown, policyName: string);
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
}

/**
 * The options for this policy.
 * @public
 */
export declare interface McpPingOAuthInboundPolicyOptions {
  /**
   * The PingOne environment ID. Required unless customDomain is set.
   */
  environmentId?: string;
  /**
   * The PingOne geography for the environment. Ignored when customDomain is set.
   */
  region?:
    | "north-america"
    | "canada"
    | "europe"
    | "singapore"
    | "australia"
    | "asia-pacific";
  /**
   * Optional PingOne custom domain, without https://, a trailing slash, or a path. When set, environmentId and region are not used.
   */
  customDomain?: string;
  /**
   * The PingOne OIDC application client_id registered for the gateway's browser login flow.
   */
  clientId: string;
  /**
   * The PingOne OIDC application client_secret. Use $env(...) to source from a secret environment variable.
   */
  clientSecret: string;
  /**
   * OIDC scopes requested during browser login.
   */
  scope?: string;
  /**
   * Gateway-side OAuth token settings. The gateway issuer and advertised URLs are derived from the incoming request origin.
   */
  gateway?: {
    /**
     * Lifetime of access tokens issued by /oauth/token.
     */
    accessTokenTtlSeconds?: number;
    /**
     * Lifetime of refresh tokens issued by /oauth/token.
     */
    refreshTokenTtlSeconds?: number;
    /**
     * Whether to advertise client_id_metadata_document_supported in AS metadata.
     */
    cimdEnabled?: boolean;
  };
  /**
   * Optional Identity Assertion JWT Authorization Grant (ID-JAG / XAA) support for the gateway token endpoint.
   */
  idJag?:
    | {
        /**
         * Disable ID-JAG support.
         */
        enabled: false;
      }
    | {
        /**
         * Enable ID-JAG support.
         */
        enabled: true;
        /**
         * Trusted ID-JAG issuers. These values are never published in OAuth metadata. Omit to trust this policy's browser-login IdP.
         *
         * @minItems 1
         */
        trustedIssuers?: [
          {
            /**
             * Exact issuer URL expected in the ID-JAG iss claim. Provide together with jwksUrl, or omit both to default to this policy's browser-login IdP.
             */
            issuer?: string;
            /**
             * JWKS URL used to verify ID-JAG signatures from this issuer. Provide together with issuer, or omit both to default to this policy's browser-login IdP.
             */
            jwksUrl?: string;
            /**
             * Optional allow-list of client IDs accepted from this issuer. The ID-JAG client_id must still match the authenticated token-endpoint client.
             */
            expectedClientIds?: string[];
            /**
             * How the ID-JAG subject is mapped into the gateway subject ID.
             */
            subjectMapping?: "iss_prefix" | "iss_tenant_prefix" | "sub_id_only";
          },
          ...{
            /**
             * Exact issuer URL expected in the ID-JAG iss claim. Provide together with jwksUrl, or omit both to default to this policy's browser-login IdP.
             */
            issuer?: string;
            /**
             * JWKS URL used to verify ID-JAG signatures from this issuer. Provide together with issuer, or omit both to default to this policy's browser-login IdP.
             */
            jwksUrl?: string;
            /**
             * Optional allow-list of client IDs accepted from this issuer. The ID-JAG client_id must still match the authenticated token-endpoint client.
             */
            expectedClientIds?: string[];
            /**
             * How the ID-JAG subject is mapped into the gateway subject ID.
             */
            subjectMapping?: "iss_prefix" | "iss_tenant_prefix" | "sub_id_only";
          }[],
        ];
        /**
         * Optional allow-list of RFC 9396 authorization_details type values accepted from ID-JAGs.
         */
        authorizationDetailsTypesAllowed?: string[];
      };
  /**
   * Optional overrides for the derived browser-login settings.
   */
  browserLoginOverrides?: {
    remoteTimeoutMs?: number;
    stateTtlSeconds?: number;
    sessionTtlSeconds?: number;
    /**
     * Whether to send S256 PKCE on the federated browser-login authorization request and replay the verifier at the token exchange. Defaults to "none". Set to "S256" when the identity provider mandates PKCE on the authorization-code flow.
     */
    pkce?: "S256" | "none";
  };
}

/**
 * An MCP Server handler for Zuplo
 * Only POST requests are supported for the HTTP streamable MCP transport.
 *
 * @beta
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @returns ZuploResponse
 */
export declare function mcpServerHandler(
  request: ZuploRequest,
  context: ZuploContext
): Promise<Response>;

/**
 * MCP (Model Context Protocol) tool
 */
declare interface McpTool {
  server_label: string;
  type: "mcp";
  allowed_tools?: string[] | Record<string, unknown> | null;
  authorization?: string;
  connector_id?:
    | "connector_dropbox"
    | "connector_gmail"
    | "connector_googlecalendar"
    | "connector_googledrive"
    | "connector_microsoftteams"
    | "connector_outlookcalendar"
    | "connector_outlookemail"
    | "connector_sharepoint";
  headers?: Record<string, string> | null;
  require_approval?: Record<string, unknown> | "always" | "never" | null;
  server_description?: string;
  server_url?: string;
}

/**
 * Authenticate MCP gateway requests using a gateway-issued OAuth access token,
 * with browser login delegated to WorkOS.
 *
 * WorkOS-friendly wrapper around `McpOAuthInboundPolicy`. Provide `clientId`
 * and `clientSecret`; the constructor derives the WorkOS OIDC issuer, JWKS URL,
 * authorize URL, and token URL automatically and runs the resulting shape
 * through the same Zod schema as the generic policy.
 *
 * @title MCP WorkOS OAuth
 * @public
 * @product mcp-gateway
 */
export declare class McpWorkosOAuthInboundPolicy extends InboundPolicy<McpWorkosOAuthInboundPolicyOptions> {
  #private;
  static readonly policyType = "mcp-workos-oauth";
  constructor(rawOptions: unknown, policyName: string);
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
}

/**
 * The options for this policy.
 * @public
 */
export declare interface McpWorkosOAuthInboundPolicyOptions {
  /**
   * The WorkOS client_id registered for the gateway's browser login flow. The OIDC issuer and JWKS URL are derived from this client ID.
   */
  clientId: string;
  /**
   * The WorkOS client_secret. Use $env(...) to source from a secret environment variable.
   */
  clientSecret: string;
  /**
   * OIDC scopes requested during browser login.
   */
  scope?: string;
  /**
   * Gateway-side OAuth token settings. The gateway issuer and advertised URLs are derived from the incoming request origin.
   */
  gateway?: {
    /**
     * Lifetime of access tokens issued by /oauth/token.
     */
    accessTokenTtlSeconds?: number;
    /**
     * Lifetime of refresh tokens issued by /oauth/token.
     */
    refreshTokenTtlSeconds?: number;
    /**
     * Whether to advertise client_id_metadata_document_supported in AS metadata.
     */
    cimdEnabled?: boolean;
  };
  /**
   * Optional Identity Assertion JWT Authorization Grant (ID-JAG / XAA) support for the gateway token endpoint.
   */
  idJag?:
    | {
        /**
         * Disable ID-JAG support.
         */
        enabled: false;
      }
    | {
        /**
         * Enable ID-JAG support.
         */
        enabled: true;
        /**
         * Trusted ID-JAG issuers. These values are never published in OAuth metadata. Omit to trust this policy's browser-login IdP.
         *
         * @minItems 1
         */
        trustedIssuers?: [
          {
            /**
             * Exact issuer URL expected in the ID-JAG iss claim. Provide together with jwksUrl, or omit both to default to this policy's browser-login IdP.
             */
            issuer?: string;
            /**
             * JWKS URL used to verify ID-JAG signatures from this issuer. Provide together with issuer, or omit both to default to this policy's browser-login IdP.
             */
            jwksUrl?: string;
            /**
             * Optional allow-list of client IDs accepted from this issuer. The ID-JAG client_id must still match the authenticated token-endpoint client.
             */
            expectedClientIds?: string[];
            /**
             * How the ID-JAG subject is mapped into the gateway subject ID.
             */
            subjectMapping?: "iss_prefix" | "iss_tenant_prefix" | "sub_id_only";
          },
          ...{
            /**
             * Exact issuer URL expected in the ID-JAG iss claim. Provide together with jwksUrl, or omit both to default to this policy's browser-login IdP.
             */
            issuer?: string;
            /**
             * JWKS URL used to verify ID-JAG signatures from this issuer. Provide together with issuer, or omit both to default to this policy's browser-login IdP.
             */
            jwksUrl?: string;
            /**
             * Optional allow-list of client IDs accepted from this issuer. The ID-JAG client_id must still match the authenticated token-endpoint client.
             */
            expectedClientIds?: string[];
            /**
             * How the ID-JAG subject is mapped into the gateway subject ID.
             */
            subjectMapping?: "iss_prefix" | "iss_tenant_prefix" | "sub_id_only";
          }[],
        ];
        /**
         * Optional allow-list of RFC 9396 authorization_details type values accepted from ID-JAGs.
         */
        authorizationDetailsTypesAllowed?: string[];
      };
  /**
   * Optional overrides for the derived browser-login settings.
   */
  browserLoginOverrides?: {
    remoteTimeoutMs?: number;
    stateTtlSeconds?: number;
    sessionTtlSeconds?: number;
    /**
     * Whether to send S256 PKCE on the federated browser-login authorization request and replay the verifier at the token exchange. Defaults to "none". Set to "S256" when the identity provider mandates PKCE on the authorization-code flow.
     */
    pkce?: "S256" | "none";
  };
}

/**
 * Model used for prompts classified as medium complexity.
 * @public
 */
declare type MediumComplexityModel = string;

declare interface MemoryCacheOptions {
  maxSize: number;
}

/**
 * A two-tier cache that combines in-memory caching with zone-level caching.
 * Data is first checked in memory cache for fastest access, then falls back to
 * zone cache if not found. Writes update both cache tiers.
 *
 * The in memory cache is an LRU cache that will evict the least recently used items
 * when the cache is full. The in memory cache is also periodically purged of
 * expired items.
 *
 * In the event that two MemoryZoneReadThroughCache instances are created
 * with the same name, they will share the same underlying in-memory cache. This
 * allows for multiple instances to be created in different parts of the codebase
 * without having to pass the cache instance around. If two instances are created
 * with the same name, but different memory cache options, the options of the
 * first instance created will be used.
 *
 *
 *
 * @public
 * @example
 * ```typescript
 * import { MemoryZoneReadThroughCache, ZuploContext } from "@zuplo/runtime";
 *
 * export async function myHandler(request: ZuploRequest, context: ZuploContext) {
 *   // Create cache with default memory size (1000 items)
 *   const cache = new MemoryZoneReadThroughCache<UserData>("user-cache", context);
 *
 *   // Or create cache with custom memory size (500 items max)
 *   // Note that maxSize controls the number of items in the in-memory cache,
 *   // but does not limit the number of items in the zone cache.
 *   const limitedCache = new MemoryZoneReadThroughCache<UserData>(
 *     "limited-cache",
 *     context,
 *     { maxSize: 500 }
 *   );
 *
 *   // Try to get cached data
 *   const cachedUser = await cache.get("user-123");
 *   if (cachedUser) {
 *     return Response.json(cachedUser);
 *   }
 *
 *   // Fetch fresh data
 *   const user = await fetchUserFromDatabase("user-123");
 *
 *   // Cache for 5 minutes (300 seconds)
 *   cache.put("user-123", user, 300);
 *
 *   return Response.json(user);
 * }
 * ```
 */
export declare class MemoryZoneReadThroughCache<T = unknown> {
  #private;
  /**
   * Creates a new MemoryZoneReadThroughCache instance.
   * @param name - A unique name for this cache instance
   * @param context - The ZuploContext from the current request
   * @param options - Optional configuration for the memory cache
   */
  constructor(
    name: string,
    context: ZuploContext,
    options?: MemoryCacheOptions
  );
  /**
   * Retrieves a value from the cache by key. First checks memory cache,
   * then falls back to zone cache if not found in memory.
   * @param key - The cache key to retrieve
   * @returns The cached value or undefined if not found or expired
   */
  get(key: string): Promise<T | undefined>;
  /**
   * Stores a value in both memory and zone cache with the specified TTL.
   * The write to zone cache is performed asynchronously in the background.
   * @param key - The cache key
   * @param data - The value to cache
   * @param ttlSeconds - Time to live in seconds
   */
  put(key: string, data: T, ttlSeconds: number): void;
  /* Excluded from this release type: delete */
}

declare interface Meter {
  /**
   * The event type. This is used to match the event to a meter.
   */
  type: string;
  /**
   * A dictionary of additional data to be sent to OpenMeter (extensible in code).
   */
  data?: {
    [k: string]: unknown;
  };
}

/**
 * Represents a meter event that will be sent to OpenMeter.
 * You can optionally override the CloudEvents fields like id, time, source, and subject.
 *
 * @example
 * ```typescript
 * const meter: Meter = {
 *   type: "api-call",
 *   data: {
 *     endpoint: "/api/users",
 *     method: "POST",
 *     responseTime: 123
 *   }
 * };
 * ```
 *
 * @example
 * ```typescript
 * // With custom CloudEvents fields
 * const meter: Meter = {
 *   type: "llm-usage",
 *   id: "custom-event-id-123",
 *   subject: "user-456",
 *   data: {
 *     model: "gpt-4",
 *     tokens: 1500
 *   }
 * };
 * ```
 * @public
 */
declare type Meter_2 = Partial<OpenMeterEvent> & Meter;

declare interface MeteringBudgetRule {
  /**
   * Budget the application as a whole ("app"), or give every distinct value of an expression its own budget ("expression").
   */
  budgetBy: "app" | "expression";
  /**
   * Required when budgetBy is "expression"; forbidden for "app". Each distinct value gets its own budget. Select one value from the request or its context: request.headers.get("x-user-id"), request.query.tenant, request.params.customerId, request.user.sub, request.user.data.organizationId, request.method, request.url, context.custom.tenantId, context.route.path, or context.incomingRequestProperties.country. Comparisons, arithmetic, string methods, and request body values are not supported.
   */
  expression?: string;
  /**
   * Thresholds this rule enforces. Add one entry per meter, period, and action you want. An "app" rule needs at least one entry. An "expression" rule may leave this empty to track usage per value without enforcing a limit.
   *
   * @maxItems 24
   */
  meters: MeteringBudgetRuleMeter[];
}

declare interface MeteringBudgetRuleMeter {
  /**
   * What to measure: US dollars spent ("cost"), requests made ("requests"), or tokens used ("tokens").
   */
  meter: "cost" | "requests" | "tokens";
  /**
   * How often usage resets.
   */
  period: "hourly" | "daily" | "weekly" | "monthly";
  /**
   * The threshold for this meter and period. Cost is in US dollars.
   */
  value: number;
  /**
   * What happens at the threshold: "warn" notifies and lets the request through, "block" uses the configured quota fallback model or returns 429 Too Many Requests.
   */
  action: "warn" | "block";
}

declare interface MeterUsageMap {
  [meter: string]: number;
}

/**
 * @public
 */
declare interface MetricsData {
  timestamp: Date;
  durationMs: number;
  statusCode: number;
  requestContentLength?: number;
  responseContentLength?: number;
  contextId: string;
  parentContextId?: string;
  requestId: string;
  parentRequestId?: string;
  /**
   * The full URL, query string included, of the request as the gateway
   * received it for this route invocation. For a request made with
   * `context.invokeRoute` this is the invoked URL, for example
   * `http://localhost/some/path`.
   */
  url?: string;
  /**
   * Free-form properties attached with `context.log.setLogProperties`.
   * Omitted when none were set.
   */
  properties?: Record<string, RequestLogPropertyValue>;
  routePath: string;
  systemRouteName?: string;
  method: HttpMethod;
  rayId?: string;
  instanceId: string;
  userSub?: string;
  clientIp?: string;
  asn?: number;
  asOrganization?: string;
  colo?: string;
  continent?: string;
  country?: string;
  city?: string;
  latitude?: string;
  longitude?: string;
  deploymentName?: string;
  projectId?: string;
}

declare abstract class MetricsPlugin extends RuntimePlugin {
  /* Excluded from this release type: getTransport */
}

declare interface MetricsTransport {
  pushMetrics(entry: MetricsData, context: ZuploContext): void;
}

declare interface MetricsType {
  latency?: boolean;
  requestContentLength?: boolean;
  responseContentLength?: boolean;
}

/**
 * Minimum confidence (0–1) required before applying model routing. Unknown intents are capped strictly below this threshold.
 * @public
 */
declare type MinimumConfidenceForRouting = number;

/**
 * The options for this policy.
 * @public
 */
export declare interface MockApiInboundOptions {
  /**
   * Indicates whether the response should be selected randomly, from the available examples (that match any filter criteria). If `false` the first matching example is used.
   */
  random?: boolean;
  /**
   * Specifies a prefix to match the responses to select from. Typically this is a status code like "200" or "2XX". If you want the policy to select randomly from all 2XX codes, set this property to "2" and random to `true`.
   */
  responsePrefixFilter?: string;
  /**
   * Specify the content-type of the response to select from. If not specified, the first matching response is used (or random).
   */
  contentType?: string;
  /**
   * Specify the name of the example to select. If not specified, the first matching response is used (or random).
   */
  exampleName?: string;
}

/**
 * Returns example responses from the OpenAPI document associated with this route.
 *
 * @title Mock API Response
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const MockApiInboundPolicy: InboundPolicyHandler<MockApiInboundOptions>;

declare interface ModelConfiguration {
  environmentVariable: string;
  model: string;
  provider: string;
}

/**
 * The models to spread requests across, by request type. Set at least one list.
 * @public
 */
declare interface Models {
  completions?: CompletionsModels;
  embeddings?: EmbeddingsModels;
}

/**
 * Model filtering rules grouped by AI Gateway capability.
 * @public
 */
declare interface Models_2 {
  completions?: CompletionsModels_2;
  embeddings?: EmbeddingsModels_2;
}

/**
 * Override rules grouped by AI Gateway capability.
 * @public
 */
declare interface Models_3 {
  completions?: CompletionsOverride;
  embeddings?: EmbeddingsOverride;
}

/**
 * Enables which model will be used based on the classifier results (`low`, `medium` and `high`). This configuration is applied only when `smartRoutingEnabled` is true and confidence score meets the `minConfidenceForRouting` threshold.
 * @public
 */
declare interface ModelsByComplexity {
  low: LowComplexityModel;
  medium: MediumComplexityModel;
  high: HighComplexityModel;
}

declare type Modify<T, R> = Omit<T, keyof R> & R;

declare interface MoesifContext {
  apiVersion?: string;
  userId?: string;
  companyId?: string;
  sessionToken?: string;
  metadata?: unknown;
}

/**
 * Moesif is an API analytics and billing service. This policy allows you to
 * send metering calls for each API to their events batch endpoint.
 *
 * @title Moesif Analytics & Billing
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare function MoesifInboundPolicy(
  request: ZuploRequest,
  context: ZuploContext,
  passedOptions: MoesifInboundPolicyOptions,
  policyName: string
): Promise<ZuploRequest<RequestGeneric>>;

/**
 * The options for this policy. Many of them can be overridden at the code level in a request using the `AmberfloMeteringPolicy.setRequestProperties` method.
 * @public
 */
export declare interface MoesifInboundPolicyOptions {
  /**
   * Your Moesif application ID.
   */
  applicationId: string;
  /**
   * Set to false to disable sending the request body to Moesif.
   */
  logRequestBody?: boolean;
  /**
   * Set to false to disable sending the response body to Moesif.
   */
  logResponseBody?: boolean;
}

/**
 * Monetization inbound policy for API key validation and usage metering.
 *
 * @title Monetization
 * @product api-gateway
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare class MonetizationInboundPolicy extends InboundPolicy<MonetizationInboundPolicyOptions> {
  #private;
  static readonly policyType = "monetization";
  /**
   * Set the monetization subscription data for the current request.
   *
   * @param context - The ZuploContext
   * @param subscription - The subscription to set.
   */
  static setSubscriptionData(
    context: ZuploContext,
    subscription: MonetizationSubscription
  ): void;
  /**
   * Get the monetization subscription data for the current request.
   *
   * @param context - The ZuploContext
   * @returns The subscription data or undefined
   */
  static getSubscriptionData(
    context: ZuploContext
  ): MonetizationSubscription | undefined;
  /**
   * Set meter increments for this request.
   *
   * @param context - The ZuploContext
   * @param meters - The meters to set.
   */
  static setMeters(context: ZuploContext, meters: MeterUsageMap): void;
  /**
   * Add meter increments for this request.
   *
   * @param context - The ZuploContext
   * @param meters - The meters to add.
   */
  static addMeters(context: ZuploContext, meters: MeterUsageMap): void;
  /**
   * Get currently configured runtime meters for this request.
   *
   * @param context - The ZuploContext
   * @returns The current meter increments.
   */
  static getMeters(context: ZuploContext): MeterUsageMap;
  /**
   * Send accumulated runtime meters to the backend immediately and clear them.
   *
   * Only runtime meters set via `setMeters` / `addMeters` are sent. Static
   * `options.meters` are still applied in the final response hook. Runtime
   * meters are cleared before the backend send begins so a concurrent final
   * hook cannot double-count them; meters are restored if the send fails.
   *
   * @param context - The ZuploContext
   */
  static flushMeters(context: ZuploContext): Promise<void>;
  constructor(options: MonetizationInboundPolicyOptions, policyName: string);
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
}

/**
 * The options for this policy.
 * @public
 */
export declare interface MonetizationInboundPolicyOptions {
  /**
   * The meters to be used by the policy against the subscription quota.
   */
  meters?: {
    [k: string]: number;
  };
  /**
   * A list of entitlement keys that the subscription must have access to (hasAccess=true) for the request to be allowed. If any required entitlement is missing or does not have access, the request will be rejected with a 403 Forbidden.
   */
  requiredEntitlements?: string[];
  /**
   * The name of the header with the key.
   */
  authHeader?: string;
  /**
   * The scheme used on the header.
   */
  authScheme?: string;
  /**
   * The time to cache authentication results for a particular key. Higher values will decrease latency. Cached results will be valid until the cache expires even in the event the key is deleted, etc.
   */
  cacheTtlSeconds?: number;
  /**
   * A list of successful status codes and ranges "200-299, 304" that should trigger a metering call.
   */
  meterOnStatusCodes?: string | number[];
}

/**
 * Subscription details returned by Zuplo monetization services.
 * @public
 */
export declare interface MonetizationSubscription {
  paymentStatus?: {
    isFirstPayment: boolean;
    lastPaymentFailedAt?: string;
    lastPaymentSucceededAt?: string;
    status: "paid" | "not_required" | "pending" | "failed" | "uncollectible";
  };
  id: string;
  customerId: string;
  name: string;
  status: string;
  currency: string;
  /**
   * The billing cadence (e.g., P1M for monthly)
   */
  billingCadence: string;
  /**
   * The anchor date used to compute billing cycles
   */
  billingAnchor: string;
  /**
   * The next billing date derived from billing anchor and cadence
   */
  nextBillingDate: string;
  activeFrom: string;
  activeTo?: string;
  plan: {
    id: string;
    name: string;
    key: string;
    version: number;
    description?: string;
  };
  entitlements: Record<
    string,
    {
      balance: number;
      hasAccess: boolean;
      overage: number;
      usage: number;
    }
  >;
  /**
   * The maximum number of days a subscription can have overdue payments
   * before requests are blocked, even if the subscription has valid meters and
   * balance. Set to 0 to block immediately when payment is overdue.
   * Defaults to 3 days.
   */
  maxPaymentOverdueDays: number;
  /**
   * If true, end-user API requests for this subscription have been
   * administratively blocked by the Zuplo customer. The policy returns 403
   * regardless of payment / entitlement status. Toggled via the
   * block-access / unblock-access endpoints.
   */
  accessBlocked?: boolean;
  createdAt: string;
  updatedAt: string;
}

/**
 * Authenticate requests based on the mTLS protocol.
 *
 * @title mTLS Auth
 * @product api-gateway
 * @public
 * @enterprise
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const MTLSAuthInboundPolicy: InboundPolicyHandler<MTLSAuthInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare type MTLSAuthInboundPolicyOptions = (
  | {
      [k: string]: unknown;
    }
  | {
      allowUnauthenticatedRequests: true;
      [k: string]: unknown;
    }
) & {
  /**
   * Fully qualified issuer distinguished name to require on the client certificate. The policy rejects certificates whose parsed issuer DN does not match this string exactly. Required unless `allowUnauthenticatedRequests` is `true`. The expected format matches the parsed metadata issuer, e.g. "CN=example-ca, O=Example, C=US".
   */
  certIssuerDN?: string;
  /**
   * Allows requests to continue even when mTLS verification fails, no client certificate is presented, or the certificate metadata cannot be parsed. Defaults to false.
   */
  allowUnauthenticatedRequests?: boolean;
};

/**
 * Parsed client certificate metadata attached by the mTLS auth policy.
 *
 * @public
 */
export declare interface MTLSAuthMetadata {
  /**
   * Certificate subject distinguished name.
   */
  subject: string;
  /**
   * Certificate issuer distinguished name.
   */
  issuer: string;
  /**
   * Certificate validity start time in ISO 8601 format.
   */
  notBefore: string;
  /**
   * Certificate validity end time in ISO 8601 format.
   */
  notAfter: string;
  /**
   * Certificate SHA-256 fingerprint formatted as uppercase colon-separated hex.
   * Omitted when the upstream proxy did not provide the fingerprint and the
   * full certificate body is unavailable.
   */
  sha256Fingerprint?: string;
}

declare interface MultiRequests {
  RequestReference: RequestReference;
}

declare interface NestedAndRule {
  /**
   * Nested rules that must all pass.
   *
   * @minItems 1
   */
  and: [InnermostRule, ...InnermostRule[]];
}

declare interface NestedOrRule {
  /**
   * Nested rules of which at least one must pass.
   *
   * @minItems 1
   */
  or: [InnermostRule, ...InnermostRule[]];
}

/**
 * A second-level rule: a single claim check or an and/or combination of third-level rules.
 * @public
 */
declare type NestedRule =
  | NestedAndRule
  | NestedOrRule
  | EqualsRule
  | InRule
  | StartsWithRule;

declare interface NewRelicLoggingOptions {
  url?: string;
  apiKey: string;
  /**
   * Any custom log fields to include in each log entry.
   */
  fields?: CustomLogFields;
  /**
   * Service name to identify the source of the logs.
   */
  service?: string;
}

/**
 * New Relic logging plugin
 * @public
 */
export declare class NewRelicLoggingPlugin extends LogPlugin {
  private options;
  constructor(options: NewRelicLoggingOptions);
  /* Excluded from this release type: getTransport */
}

declare interface NewRelicMetricsContext {
  attributes: Record<string, string | number | boolean | null | undefined>;
}

declare interface NewRelicMetricsOptions {
  url?: string;
  apiKey: string;
  attributes?: Record<string, string | number | boolean | null | undefined>;
  metrics?: MetricsType;
  include?: IncludeMetrics;
}

/**
 * New Relic metrics plugin
 * @public
 */
export declare class NewRelicMetricsPlugin extends MetricsPlugin {
  #private;
  private options;
  constructor(options: NewRelicMetricsOptions);
  /* Excluded from this release type: getTransport */
  static setContext(context: ZuploContext, data: NewRelicMetricsContext): void;
}

declare interface NotFoundOptions {
  routesMatchedByPathOnly: RouteConfiguration[];
}

/**
 * Where the client credentials are sent on the token request. `body` sends `client_id` and `client_secret` as form parameters. `header` sends them with HTTP Basic authentication as described in RFC 6749 section 2.3.1.
 * @public
 */
declare type OAuthClientCredentialsLocation = "body" | "header";

/* Excluded from this release type: OAuthProtectedResourceBasePlugin */

/* Excluded from this release type: OAuthProtectedResourceMetadataOptions */

/**
 * Plugin for adding a route for a subset of OAuth protected resource metadata to Zuplo according to
 * RFC9728. Mostly useful for MCP Server OAuth support.
 *
 * @public
 */
export declare class OAuthProtectedResourcePlugin extends OAuthProtectedResourceBasePlugin {
  private options;
  private readonly scopes;
  constructor(options: OAuthProtectedResourcePluginOptions);
  /**
   * The scope values configured through `scopesSupported`, or `undefined` when
   * the option was not set. OAuth policies read this to populate the `scope`
   * parameter of their `WWW-Authenticate` challenge.
   */
  get scopesSupported(): readonly string[] | undefined;
  protected getMetadataOptions(
    _request: ZuploRequest,
    _context: ZuploContext
  ): Promise<OAuthProtectedResourceMetadataOptions>;
}

/**
 * Options for the OAuthProtectedResourcePlugin
 *
 * @public
 */
export declare interface OAuthProtectedResourcePluginOptions {
  /**
   * List of OAuth authorization server issuer identifiers that can be used with this protected resource.
   * These should be the base URLs of authorization servers (e.g., "https://auth.example.com"). Note that
   * the authorization servers should be compliant with RFC8414 (see https://datatracker.ietf.org/doc/html/rfc8414)
   */
  authorizationServers?: string[];
  /**
   * Human-readable name of the protected resource intended for display to end users.
   * This field is recommended by RFC 9728.
   */
  resourceName?: string;
  /**
   * Scope values that clients should request when obtaining an access token for
   * this protected resource. Emitted as `scopes_supported` in the metadata
   * document (RFC 9728) and, when an OAuth policy on the route has
   * `oAuthResourceMetadataEnabled` set, as the `scope` parameter of the
   * `WWW-Authenticate` challenge on 401 responses. MCP clients use these values
   * to build their authorization request instead of asking for every scope the
   * authorization server advertises.
   *
   * Each entry must be a single OAuth scope token (RFC 6749 §3.3): printable
   * ASCII with no spaces, double quotes, or backslashes. The list must not be
   * empty; omit the option to advertise no scopes.
   *
   * @example
   * ```ts
   * new OAuthProtectedResourcePlugin({
   *   authorizationServers: ["https://acme.okta.com/oauth2/aus1a2b3c"],
   *   resourceName: "Acme MCP",
   *   scopesSupported: ["mcp:access", "openid", "offline_access"],
   * });
   * ```
   */
  scopesSupported?: string[];
}

/**
 * Authorize requests using Okta FGA.
 *
 * @title Okta FGA Authorization
 * @product api-gateway
 * @public
 * @enterprise
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare class OktaFGAAuthZInboundPolicy extends BaseOpenFGAAuthZInboundPolicy {
  static readonly policyType = "oktafga-authz";
  constructor(options: OktaFGAAuthZInboundPolicyOptions, policyName: string);
}

/**
 * The options for this policy.
 * @public
 */
export declare interface OktaFGAAuthZInboundPolicyOptions {
  /**
   * The region your store is deployed.
   */
  region: "us1" | "eu1" | "au1";
  /**
   * The ID of the store.
   */
  storeId: string;
  /**
   * The ID of the authorization model.
   */
  authorizationModelId: string;
  credentials: {
    /**
     * The client ID.
     */
    clientId: string;
    /**
     * The client secret.
     */
    clientSecret: string;
    [k: string]: unknown;
  };
  /**
   * Indicates whether the request should continue if authorization fails. Default is `false` which means unauthorized users will automatically receive a 403 response.
   */
  allowUnauthorizedRequests?: boolean;
}

/**
 * Authenticate users using Okta issued JWT tokens.
 *
 * @title Okta JWT Auth
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const OktaJwtInboundPolicy: InboundPolicyHandler<OktaJwtInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface OktaJwtInboundPolicyOptions {
  /**
   * Your Okta authorization server's issuer URL. For example, `https://dev-12345.okta.com/oauth2/abc`.
   */
  issuerUrl: string;
  /**
   * The Okta audience of your API, for example `api://my-api`.
   */
  audience?: string;
  /**
   * Allow unauthenticated requests to proceed. This is use useful if you want to use multiple authentication policies or if you want to allow both authenticated and non-authenticated traffic.
   */
  allowUnauthenticatedRequests?: boolean;
  /**
   * Enables OAuth 2.0 Protected Resource Metadata discovery (RFC 9728). When `true`, requests without a bearer token receive a 401 whose `WWW-Authenticate` header points `resource_metadata` at the `/.well-known/oauth-protected-resource` document for the request path and, when the `OAuthProtectedResourcePlugin` declares `scopesSupported`, lists those scopes in `scope`. Requires the `OAuthProtectedResourcePlugin` in `zuplo.runtime.ts` or a user-defined route at that path.
   */
  oAuthResourceMetadataEnabled?: boolean;
}

/**
 * What to do when the classifier call itself fails (invalid API key, rate limit, timeout, outage). 'block' (the default) fails closed and returns a 502 so unverified prompts are never forwarded; 'allow' fails open and lets the request through without inspection.
 * @public
 */
declare type OnClassifierError = "block" | "allow";

/**
 * What to do if the scanner itself throws. The engine is a local in-gateway scanner, so this is effectively unreachable outside of a runtime defect — but a guardrail must declare its failure posture. `block` (the default) fails closed with a 500 in the route's native error format; `allow` fails open and serves the content uninspected.
 * @public
 */
declare type OnEngineError = "block" | "allow";

/**
 * What to do when the Akamai detect call itself fails (invalid API key, rate limit, outage). 'block' (the default) fails closed and returns a 502 so unverified content is never served; 'allow' fails open and lets the request through without inspection.
 * @public
 */
declare type OnFirewallError = "block" | "allow";

/**
 * @public
 */
declare interface OnRequestHook {
  (
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response> | (ZuploRequest | Response);
}

/**
 * @public
 */
declare interface OnResponseSendingFinalHook {
  (
    response: Response,
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<void> | void;
}

/**
 * @public
 */
declare interface OnResponseSendingHook {
  (
    response: Response,
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<Response> | Response;
}

/**
 * Hook function called before sending an AWS Lambda event.
 * Allows modification of the event before it's sent to Lambda.
 * @public
 */
declare interface OnSendingAwsLambdaEventHook {
  (
    request: ZuploRequest,
    context: ZuploContext,
    event: AwsLambdaEventV1 | AwsLambdaEventV2
  ): Promise<AwsLambdaEventV1 | AwsLambdaEventV2>;
}

/**
 * What to do when the request shape cannot be inspected. As a guardrail, this policy defaults to 'deny' (fail closed) so uninspectable content is never served.
 * @public
 */
declare type OnUnknownShape = "deny" | "skip";

/**
 * What to do when the request shape cannot be inspected. As a guardrail this policy defaults to `deny` (fail closed) so uninspectable content is never served.
 * @public
 */
declare type OnUnknownShape_2 = "deny" | "skip";

/**
 * What to do on a shape the policy cannot read. As an observer this defaults to 'skip' (fail open — pass through untraced).
 * @public
 */
declare type OnUnknownShape_3 = "deny" | "skip";

/**
 * What to do on a shape the policy cannot read. As an observer this defaults to 'skip' (fail open — pass through untraced).
 * @public
 */
declare type OnUnknownShape_4 = "deny" | "skip";

/**
 * What to do when the request shape cannot be inspected. As a guardrail, this policy defaults to 'deny' (fail closed) so uninspectable content is never forwarded.
 * @public
 */
declare type OnUnknownShape_5 = "deny" | "skip";

/**
 * Unused by the cache (a cache miss is never unsafe, so it always fails open). Present for interface consistency.
 * @public
 */
declare type OnUnknownShape_6 = "deny" | "skip";

/**
 * Handler that serves OpenAPI specification files.
 * Use this to expose your API documentation in a standard format that can be
 * consumed by tools like Swagger UI, Postman, or API documentation generators.
 *
 * @param request - The incoming ZuploRequest
 * @param context - The ZuploContext
 * @returns A Response containing the OpenAPI specification
 *
 * @public
 * @example
 * ```json
 * // routes.oas.json - Serve OpenAPI spec at /openapi
 * {
 *   "paths": {
 *     "/openapi": {
 *       "get": {
 *         "summary": "Get OpenAPI specification",
 *         "x-zuplo-route": {
 *           "handler": {
 *             "export": "openApiSpecHandler",
 *             "module": "$import(@zuplo/runtime)",
 *             "options": {
 *               "openApiFilePath": "./config/api-spec.oas.json"
 *             }
 *           }
 *         }
 *       }
 *     }
 *   }
 * }
 * ```
 *
 * @example
 * ```json
 * // Serve different specs based on environment
 * {
 *   "handler": {
 *     "export": "openApiSpecHandler",
 *     "module": "$import(@zuplo/runtime)",
 *     "options": {
 *       "openApiFilePath": "./config/$env(API_VERSION).oas.json"
 *     }
 *   }
 * }
 * ```
 */
export declare function openApiSpecHandler(
  request: ZuploRequest,
  context: ZuploContext
): Promise<Response>;

declare namespace OpenAPIV3 {
  interface Document<T extends {} = {}> {
    openapi: string;
    info: InfoObject;
    servers?: ServerObject[];
    paths: PathsObject<T>;
    components?: ComponentsObject;
    security?: SecurityRequirementObject[];
    tags?: TagObject[];
    externalDocs?: ExternalDocumentationObject;
    "x-express-openapi-additional-middleware"?: (
      | ((request: any, response: any, next: any) => Promise<void>)
      | ((request: any, response: any, next: any) => void)
    )[];
    "x-express-openapi-validation-strict"?: boolean;
  }
  interface InfoObject {
    title: string;
    description?: string;
    termsOfService?: string;
    contact?: ContactObject;
    license?: LicenseObject;
    version: string;
  }
  interface ContactObject {
    name?: string;
    url?: string;
    email?: string;
  }
  interface LicenseObject {
    name: string;
    url?: string;
  }
  interface ServerObject {
    url: string;
    description?: string;
    variables?: {
      [variable: string]: ServerVariableObject;
    };
  }
  interface ServerVariableObject {
    enum?: string[];
    default: string;
    description?: string;
  }
  interface PathsObject<T extends {} = {}, P extends {} = {}> {
    [pattern: string]: (PathItemObject<T> & P) | undefined;
  }
  enum HttpMethods {
    GET = "get",
    PUT = "put",
    POST = "post",
    DELETE = "delete",
    OPTIONS = "options",
    HEAD = "head",
    PATCH = "patch",
    TRACE = "trace",
  }
  type PathItemObject<T extends {} = {}> = {
    $ref?: string;
    summary?: string;
    description?: string;
    servers?: ServerObject[];
    parameters?: (ReferenceObject | ParameterObject)[];
  } & {
    [method in HttpMethods]?: OperationObject<T>;
  };
  type OperationObject<T extends {} = {}> = {
    tags?: string[];
    summary?: string;
    description?: string;
    externalDocs?: ExternalDocumentationObject;
    operationId?: string;
    parameters?: (ReferenceObject | ParameterObject)[];
    requestBody?: ReferenceObject | RequestBodyObject;
    responses: ResponsesObject;
    callbacks?: {
      [callback: string]: ReferenceObject | CallbackObject;
    };
    deprecated?: boolean;
    security?: SecurityRequirementObject[];
    servers?: ServerObject[];
  } & T;
  interface ExternalDocumentationObject {
    description?: string;
    url: string;
  }
  interface ParameterObject extends ParameterBaseObject {
    name: string;
    in: string;
  }
  interface HeaderObject extends ParameterBaseObject {}
  interface ParameterBaseObject {
    description?: string;
    required?: boolean;
    deprecated?: boolean;
    allowEmptyValue?: boolean;
    style?: string;
    explode?: boolean;
    allowReserved?: boolean;
    schema?: ReferenceObject | SchemaObject;
    example?: any;
    examples?: {
      [media: string]: ReferenceObject | ExampleObject;
    };
    content?: {
      [media: string]: MediaTypeObject;
    };
  }
  type NonArraySchemaObjectType =
    | "boolean"
    | "object"
    | "number"
    | "string"
    | "integer";
  type ArraySchemaObjectType = "array";
  type SchemaObject = ArraySchemaObject | NonArraySchemaObject;
  interface ArraySchemaObject extends BaseSchemaObject {
    type: ArraySchemaObjectType;
    items: ReferenceObject | SchemaObject;
  }
  interface NonArraySchemaObject extends BaseSchemaObject {
    type?: NonArraySchemaObjectType;
  }
  interface BaseSchemaObject {
    title?: string;
    description?: string;
    format?: string;
    default?: any;
    multipleOf?: number;
    maximum?: number;
    exclusiveMaximum?: boolean;
    minimum?: number;
    exclusiveMinimum?: boolean;
    maxLength?: number;
    minLength?: number;
    pattern?: string;
    additionalProperties?: boolean | ReferenceObject | SchemaObject;
    maxItems?: number;
    minItems?: number;
    uniqueItems?: boolean;
    maxProperties?: number;
    minProperties?: number;
    required?: string[];
    enum?: any[];
    properties?: {
      [name: string]: ReferenceObject | SchemaObject;
    };
    allOf?: (ReferenceObject | SchemaObject)[];
    oneOf?: (ReferenceObject | SchemaObject)[];
    anyOf?: (ReferenceObject | SchemaObject)[];
    not?: ReferenceObject | SchemaObject;
    nullable?: boolean;
    discriminator?: DiscriminatorObject;
    readOnly?: boolean;
    writeOnly?: boolean;
    xml?: XMLObject;
    externalDocs?: ExternalDocumentationObject;
    example?: any;
    deprecated?: boolean;
  }
  interface DiscriminatorObject {
    propertyName: string;
    mapping?: {
      [value: string]: string;
    };
  }
  interface XMLObject {
    name?: string;
    namespace?: string;
    prefix?: string;
    attribute?: boolean;
    wrapped?: boolean;
  }
  interface ReferenceObject {
    $ref: string;
  }
  interface ExampleObject {
    summary?: string;
    description?: string;
    value?: any;
    externalValue?: string;
  }
  interface MediaTypeObject {
    schema?: ReferenceObject | SchemaObject;
    example?: any;
    examples?: {
      [media: string]: ReferenceObject | ExampleObject;
    };
    encoding?: {
      [media: string]: EncodingObject;
    };
  }
  interface EncodingObject {
    contentType?: string;
    headers?: {
      [header: string]: ReferenceObject | HeaderObject;
    };
    style?: string;
    explode?: boolean;
    allowReserved?: boolean;
  }
  interface RequestBodyObject {
    description?: string;
    content: {
      [media: string]: MediaTypeObject;
    };
    required?: boolean;
  }
  interface ResponsesObject {
    [code: string]: ReferenceObject | ResponseObject;
  }
  interface ResponseObject {
    description: string;
    headers?: {
      [header: string]: ReferenceObject | HeaderObject;
    };
    content?: {
      [media: string]: MediaTypeObject;
    };
    links?: {
      [link: string]: ReferenceObject | LinkObject;
    };
  }
  interface LinkObject {
    operationRef?: string;
    operationId?: string;
    parameters?: {
      [parameter: string]: any;
    };
    requestBody?: any;
    description?: string;
    server?: ServerObject;
  }
  interface CallbackObject {
    [url: string]: PathItemObject;
  }
  interface SecurityRequirementObject {
    [name: string]: string[];
  }
  interface ComponentsObject {
    schemas?: {
      [key: string]: ReferenceObject | SchemaObject;
    };
    responses?: {
      [key: string]: ReferenceObject | ResponseObject;
    };
    parameters?: {
      [key: string]: ReferenceObject | ParameterObject;
    };
    examples?: {
      [key: string]: ReferenceObject | ExampleObject;
    };
    requestBodies?: {
      [key: string]: ReferenceObject | RequestBodyObject;
    };
    headers?: {
      [key: string]: ReferenceObject | HeaderObject;
    };
    securitySchemes?: {
      [key: string]: ReferenceObject | SecuritySchemeObject;
    };
    links?: {
      [key: string]: ReferenceObject | LinkObject;
    };
    callbacks?: {
      [key: string]: ReferenceObject | CallbackObject;
    };
  }
  type SecuritySchemeObject =
    | HttpSecurityScheme
    | ApiKeySecurityScheme
    | OAuth2SecurityScheme
    | OpenIdSecurityScheme;
  interface HttpSecurityScheme {
    type: "http";
    description?: string;
    scheme: string;
    bearerFormat?: string;
  }
  interface ApiKeySecurityScheme {
    type: "apiKey";
    description?: string;
    name: string;
    in: string;
  }
  interface OAuth2SecurityScheme {
    type: "oauth2";
    description?: string;
    flows: {
      implicit?: {
        authorizationUrl: string;
        refreshUrl?: string;
        scopes: {
          [scope: string]: string;
        };
      };
      password?: {
        tokenUrl: string;
        refreshUrl?: string;
        scopes: {
          [scope: string]: string;
        };
      };
      clientCredentials?: {
        tokenUrl: string;
        refreshUrl?: string;
        scopes: {
          [scope: string]: string;
        };
      };
      authorizationCode?: {
        authorizationUrl: string;
        tokenUrl: string;
        refreshUrl?: string;
        scopes: {
          [scope: string]: string;
        };
      };
    };
  }
  interface OpenIdSecurityScheme {
    type: "openIdConnect";
    description?: string;
    openIdConnectUrl: string;
  }
  interface TagObject {
    name: string;
    description?: string;
    externalDocs?: ExternalDocumentationObject;
  }
}

declare namespace OpenAPIV3_1 {
  type Modify<T, R> = Omit<T, keyof R> & R;
  type PathsWebhooksComponents<T extends {} = {}> = {
    paths: PathsObject<T>;
    webhooks: Record<string, PathItemObject | ReferenceObject>;
    components: ComponentsObject;
  };
  type Document<T extends {} = {}> = Modify<
    Omit<OpenAPIV3.Document<T>, "paths" | "components">,
    {
      info: InfoObject;
      jsonSchemaDialect?: string;
      servers?: ServerObject[];
    } & (
      | (Pick<PathsWebhooksComponents<T>, "paths"> &
          Omit<Partial<PathsWebhooksComponents<T>>, "paths">)
      | (Pick<PathsWebhooksComponents<T>, "webhooks"> &
          Omit<Partial<PathsWebhooksComponents<T>>, "webhooks">)
      | (Pick<PathsWebhooksComponents<T>, "components"> &
          Omit<Partial<PathsWebhooksComponents<T>>, "components">)
    )
  >;
  type InfoObject = Modify<
    OpenAPIV3.InfoObject,
    {
      summary?: string;
      license?: LicenseObject;
    }
  >;
  type ContactObject = OpenAPIV3.ContactObject;
  type LicenseObject = Modify<
    OpenAPIV3.LicenseObject,
    {
      identifier?: string;
    }
  >;
  type ServerObject = Modify<
    OpenAPIV3.ServerObject,
    {
      url: string;
      description?: string;
      variables?: Record<string, ServerVariableObject>;
    }
  >;
  type ServerVariableObject = Modify<
    OpenAPIV3.ServerVariableObject,
    {
      enum?: [string, ...string[]];
    }
  >;
  type PathsObject<T extends {} = {}, P extends {} = {}> = Record<
    string,
    (PathItemObject<T> & P) | undefined
  >;
  type HttpMethods = OpenAPIV3.HttpMethods;
  type PathItemObject<T extends {} = {}> = Modify<
    OpenAPIV3.PathItemObject<T>,
    {
      servers?: ServerObject[];
      parameters?: (ReferenceObject | ParameterObject)[];
    }
  > & {
    [method in HttpMethods]?: OperationObject<T>;
  };
  type OperationObject<T extends {} = {}> = Modify<
    OpenAPIV3.OperationObject<T>,
    {
      parameters?: (ReferenceObject | ParameterObject)[];
      requestBody?: ReferenceObject | RequestBodyObject;
      responses?: ResponsesObject;
      callbacks?: Record<string, ReferenceObject | CallbackObject>;
      servers?: ServerObject[];
    }
  > &
    T;
  type ExternalDocumentationObject = OpenAPIV3.ExternalDocumentationObject;
  type ParameterObject = OpenAPIV3.ParameterObject;
  type HeaderObject = OpenAPIV3.HeaderObject;
  type ParameterBaseObject = OpenAPIV3.ParameterBaseObject;
  type NonArraySchemaObjectType = OpenAPIV3.NonArraySchemaObjectType | "null";
  type ArraySchemaObjectType = OpenAPIV3.ArraySchemaObjectType;
  /**
   * There is no way to tell typescript to require items when type is either 'array' or array containing 'array' type
   * 'items' will be always visible as optional
   * Casting schema object to ArraySchemaObject or NonArraySchemaObject will work fine
   */
  type SchemaObject =
    | ArraySchemaObject
    | NonArraySchemaObject
    | MixedSchemaObject;
  interface ArraySchemaObject extends BaseSchemaObject {
    type: ArraySchemaObjectType;
    items: ReferenceObject | SchemaObject;
  }
  interface NonArraySchemaObject extends BaseSchemaObject {
    type?: NonArraySchemaObjectType;
  }
  interface MixedSchemaObject extends BaseSchemaObject {
    type?: (ArraySchemaObjectType | NonArraySchemaObjectType)[];
    items?: ReferenceObject | SchemaObject;
  }
  type BaseSchemaObject = Modify<
    Omit<OpenAPIV3.BaseSchemaObject, "nullable">,
    {
      examples?: OpenAPIV3.BaseSchemaObject["example"][];
      exclusiveMinimum?: boolean | number;
      exclusiveMaximum?: boolean | number;
      contentMediaType?: string;
      $schema?: string;
      additionalProperties?: boolean | ReferenceObject | SchemaObject;
      properties?: {
        [name: string]: ReferenceObject | SchemaObject;
      };
      allOf?: (ReferenceObject | SchemaObject)[];
      oneOf?: (ReferenceObject | SchemaObject)[];
      anyOf?: (ReferenceObject | SchemaObject)[];
      not?: ReferenceObject | SchemaObject;
      discriminator?: DiscriminatorObject;
      externalDocs?: ExternalDocumentationObject;
      xml?: XMLObject;
      const?: any;
    }
  >;
  type DiscriminatorObject = OpenAPIV3.DiscriminatorObject;
  type XMLObject = OpenAPIV3.XMLObject;
  type ReferenceObject = Modify<
    OpenAPIV3.ReferenceObject,
    {
      summary?: string;
      description?: string;
    }
  >;
  type ExampleObject = OpenAPIV3.ExampleObject;
  type MediaTypeObject = Modify<
    OpenAPIV3.MediaTypeObject,
    {
      schema?: SchemaObject | ReferenceObject;
      examples?: Record<string, ReferenceObject | ExampleObject>;
    }
  >;
  type EncodingObject = OpenAPIV3.EncodingObject;
  type RequestBodyObject = Modify<
    OpenAPIV3.RequestBodyObject,
    {
      content: {
        [media: string]: MediaTypeObject;
      };
    }
  >;
  type ResponsesObject = Record<string, ReferenceObject | ResponseObject>;
  type ResponseObject = Modify<
    OpenAPIV3.ResponseObject,
    {
      headers?: {
        [header: string]: ReferenceObject | HeaderObject;
      };
      content?: {
        [media: string]: MediaTypeObject;
      };
      links?: {
        [link: string]: ReferenceObject | LinkObject;
      };
    }
  >;
  type LinkObject = Modify<
    OpenAPIV3.LinkObject,
    {
      server?: ServerObject;
    }
  >;
  type CallbackObject = Record<string, PathItemObject | ReferenceObject>;
  type SecurityRequirementObject = OpenAPIV3.SecurityRequirementObject;
  type ComponentsObject = Modify<
    OpenAPIV3.ComponentsObject,
    {
      schemas?: Record<string, SchemaObject>;
      responses?: Record<string, ReferenceObject | ResponseObject>;
      parameters?: Record<string, ReferenceObject | ParameterObject>;
      examples?: Record<string, ReferenceObject | ExampleObject>;
      requestBodies?: Record<string, ReferenceObject | RequestBodyObject>;
      headers?: Record<string, ReferenceObject | HeaderObject>;
      securitySchemes?: Record<string, ReferenceObject | SecuritySchemeObject>;
      links?: Record<string, ReferenceObject | LinkObject>;
      callbacks?: Record<string, ReferenceObject | CallbackObject>;
      pathItems?: Record<string, ReferenceObject | PathItemObject>;
    }
  >;
  type SecuritySchemeObject = OpenAPIV3.SecuritySchemeObject;
  type HttpSecurityScheme = OpenAPIV3.HttpSecurityScheme;
  type ApiKeySecurityScheme = OpenAPIV3.ApiKeySecurityScheme;
  type OAuth2SecurityScheme = OpenAPIV3.OAuth2SecurityScheme;
  type OpenIdSecurityScheme = OpenAPIV3.OpenIdSecurityScheme;
  type TagObject = OpenAPIV3.TagObject;
  export {};
}

/**
 * Authorize requests using OpenFGA.
 *
 * @title OpenFGA Authorization
 * @product api-gateway
 * @public
 * @enterprise
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare class OpenFGAAuthZInboundPolicy extends BaseOpenFGAAuthZInboundPolicy {
  static readonly policyType = "openfga-authz";
}

/**
 * The options for this policy.
 * @public
 */
export declare interface OpenFGAAuthZInboundPolicyOptions {
  /**
   * The URL of the OpenFGA service.
   */
  apiUrl: string;
  /**
   * The ID of the store.
   */
  storeId: string;
  /**
   * The ID of the authorization model.
   */
  authorizationModelId: string;
  credentials:
    | UnauthenticatedCredentialConfig
    | APITokenCredentialConfig
    | HeaderCredentialsConfig
    | ClientCredentialsConfig;
  /**
   * Indicates whether the request should continue if authorization fails. Default is `false` which means unauthorized users will automatically receive a 403 response.
   */
  allowUnauthorizedRequests?: boolean;
}

declare interface OpenFGACheck {
  /**
   * The user to check the relation for. If not provided, the user will be set to the request user.
   */
  user: string;
  /**
   * The relation to check.
   */
  relation: string;
  /**
   * The object to check the relation for.
   */
  object: string;
  /**
   * Additional request context that will be used to evaluate any ABAC conditions encountered in the query evaluation.
   */
  context?: object;
  contextualTuples?: TupleKey[];
}

/**
 * The Open ID JWT Authentication policy allows you to authenticate incoming
 * requests using an Open ID compliant bearer token.
 *
 * @title JWT Auth
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const OpenIdJwtInboundPolicy: InboundPolicyHandler<OpenIdJwtInboundPolicyInternalOptions>;

declare interface OpenIdJwtInboundPolicyInternalOptions extends Omit<
  OpenIdJwtInboundPolicyOptions,
  "secret"
> {
  secret?: string | KeyLike;
}

/**
 * The options for this policy.
 * @public
 */
export declare interface OpenIdJwtInboundPolicyOptions {
  /**
   * The expected issuer claim in the JWT token.
   */
  issuer?: string;
  /**
   * The expected audience claim in the JWT token.
   */
  audience?: string;
  /**
   * the url of the JSON Web Key Set (JWKS) - this is used to validate the JWT token signature (either this or `secret` must be set).
   */
  jwkUrl?: string;
  /**
   * The key used to verify the signature of the JWT token (either this or `jwkUrl` must be set).
   */
  secret?: string;
  /**
   * The name of the header with the key.
   */
  authHeader?: string;
  /**
   * indicates whether the request should continue if authentication fails. Defaults is `false` which means unauthenticated users will automatically receive a 401 response.
   */
  allowUnauthenticatedRequests?: boolean;
  /**
   * The name of the property in the JWT token that contains the user's unique identifier.
   */
  subPropertyName?: string;
  /**
   * Additional headers to send with the JWK request.
   */
  headers?: {
    [k: string]: string;
  };
  /**
   * Enables OAuth 2.0 Protected Resource Metadata discovery (RFC 9728). When `true`, requests without a bearer token receive a 401 whose `WWW-Authenticate` header points `resource_metadata` at the `/.well-known/oauth-protected-resource` document for the request path and, when the `OAuthProtectedResourcePlugin` declares `scopesSupported`, lists those scopes in `scope`. Requires the `OAuthProtectedResourcePlugin` in `zuplo.runtime.ts` or a user-defined route at that path.
   */
  oAuthResourceMetadataEnabled?: boolean;
}

/* Excluded from this release type: OpenMeterEvent */

/**
 * OpenMeter is a usage metering service. This policy allows
 * you to send metering calls for each API to their event ingest endpoint.
 * It also supports entitlement checking to verify if a subject has access to a feature.
 *
 * @title OpenMeter
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare class OpenMeterInboundPolicy extends InboundPolicy<OpenMeterInboundPolicyOptions> {
  #private;
  static readonly policyType = "openmeter-metering";
  constructor(options: OpenMeterInboundPolicyOptions, policyName: string);
  handler(
    request: ZuploRequest<RequestGeneric>,
    context: ZuploContext
  ): Promise<ZuploRequest<RequestGeneric> | Response>;
  /**
   * Extracts the subject identifier from the request based on the configured subjectPath.
   * The subject is used as the customer/user identifier in OpenMeter events.
   *
   * @param request - The incoming request
   * @returns The subject identifier if found, undefined otherwise
   * @throws RuntimeError if subjectPath is configured but request.user is undefined
   */
  private getSubject;
  /**
   * Checks if a subject has access to a specific feature by querying the OpenMeter entitlements API.
   *
   * @param subject - The subject/customer identifier
   * @param featureKey - The feature key to check entitlements for
   * @param context - The Zuplo context for logging
   * @returns The entitlement result including access status and usage information
   */
  private checkEntitlement;
  /**
   * Sets up metering to send events to OpenMeter when the response matches the configured status codes.
   * Events are batched and sent asynchronously after the response is sent.
   *
   * @param request - The incoming request
   * @param context - The Zuplo context
   */
  private setupMetering;
  /**
   * Sets custom meters for the current request. This allows other policies or handlers
   * to define specific metering events that should be sent to OpenMeter.
   *
   * @param context - The Zuplo context
   * @param value - Array of meter configurations to use for this request
   *
   * @example
   * ```typescript
   * // In a custom policy or handler
   * OpenMeterInboundPolicy.setMeters(context, [
   *   {
   *     type: "api-call",
   *     data: {
   *       endpoint: request.url,
   *       method: request.method,
   *       tokens: 150
   *     }
   *   },
   *   {
   *     type: "llm-usage",
   *     data: {
   *       model: "gpt-4",
   *       prompt_tokens: 100,
   *       completion_tokens: 50
   *     }
   *   }
   * ]);
   * ```
   */
  static setMeters(context: ZuploContext, value: Meter_2 | Meter_2[]): void;
}

/**
 * Send usage metrics to OpenMeter.
 * @public
 */
export declare interface OpenMeterInboundPolicyOptions {
  /**
   * The API key to use when sending metering calls to OpenMeter.
   */
  apiKey: string;
  /**
   * A single meter configuration or an array of meter configurations for OpenMeter.
   */
  meter?: Meter | Meter[];
  /**
   * A list of entitlements (feature keys) required in order for the call to be allowed.
   */
  requiredEntitlements?: string[];
  /**
   * The URL of the OpenMeter API endpoint.
   */
  apiUrl?: string;
  /**
   * A list of successful status codes and ranges "200-299, 304" that should trigger a metering event.
   */
  meterOnStatusCodes?: string | number[];
  /**
   * The event's source (e.g. the service name).
   */
  eventSource?: string;
  /**
   * The path to the property on `request.user` that contains the subject used for meters and entitlements. For example `.data.accountId` would read the `request.user.data.accountId` property.
   */
  subjectPath?: string;
}

declare interface OrRule {
  /**
   * Nested rules of which at least one must pass.
   *
   * @minItems 1
   */
  or: [NestedRule, ...NestedRule[]];
}

/**
 * Context for adding per-request attributes to OTel metrics
 * @public
 */
declare interface OTelMetricsContext {
  attributes: Attributes;
}

/**
 * Options for the OpenTelemetry metrics plugin
 * @public
 */
declare interface OTelMetricsOptions {
  /**
   * The OTLP HTTP endpoint URL (e.g., "https://otel-collector:4318/v1/metrics")
   */
  url: string;
  /**
   * Additional headers to send with the request (e.g., for authentication)
   */
  headers?: Record<string, string>;
  /**
   * Resource attributes to include with all metrics
   */
  attributes?: Attributes;
  /**
   * Which metrics to send
   */
  metrics?: MetricsType;
  /**
   * Which request properties to include as metric attributes
   */
  include?: IncludeMetrics;
}

/**
 * OpenTelemetry metrics plugin
 * @public
 */
export declare class OTelMetricsPlugin extends MetricsPlugin {
  #private;
  private options;
  constructor(options: OTelMetricsOptions);
  /* Excluded from this release type: getTransport */
  /**
   * Set per-request context for OTel metrics
   * @param context - The Zuplo context
   * @param data - The OTel metrics context with attributes to add
   */
  static setContext(context: ZuploContext, data: OTelMetricsContext): void;
}

/**
 * A policy that can modify the outgoing HTTP response before it is returned
 * to the client. Outbound policies run after the handler has generated a response.
 *
 * @public
 * @example
 * ```typescript
 * import { OutboundPolicy, ZuploContext, ZuploRequest } from "@zuplo/runtime";
 *
 * interface ResponseHeadersOptions {
 *   headers: Record<string, string>;
 * }
 *
 * export class AddResponseHeadersPolicy extends OutboundPolicy<ResponseHeadersOptions> {
 *   async handler(
 *     response: Response,
 *     request: ZuploRequest,
 *     context: ZuploContext
 *   ) {
 *     // Clone the response to make headers mutable
 *     const newResponse = new Response(response.body, response);
 *
 *     // Add configured headers
 *     for (const [name, value] of Object.entries(this.options.headers)) {
 *       newResponse.headers.set(name, value);
 *     }
 *
 *     return newResponse;
 *   }
 * }
 * ```
 */
export declare abstract class OutboundPolicy<
  TOptions = any,
> extends PolicyBase<TOptions> {
  readonly direction: PolicyDirection;
  /**
   * The handler that is called each time this policy is invoked
   *
   * @param response - The outgoing Response
   * @param request - The incoming Request
   * @param context - The current context of the Request
   */
  abstract handler(
    response: Response,
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<Response>;
}

/**
 * A function-based outbound policy that can modify the outgoing HTTP response.
 * This is the simplest way to create custom outbound policies without extending a class.
 *
 * @param response - The outgoing Response from the handler
 * @param request - The original incoming Request
 * @param context - The current context of the Request
 * @param options - The configuration options for the policy
 * @param policyName - The name set on the policy in the configuration
 * @returns A modified Response object
 *
 * @public
 * @example
 * ```typescript
 * import { OutboundPolicyHandler } from "@zuplo/runtime";
 *
 * interface CacheControlOptions {
 *   maxAge: number;
 *   sMaxAge?: number;
 *   public?: boolean;
 * }
 *
 * export const cacheControlPolicy: OutboundPolicyHandler<CacheControlOptions> = async (
 *   response,
 *   request,
 *   context,
 *   options
 * ) => {
 *   // Only cache successful responses
 *   if (response.status !== 200) {
 *     return response;
 *   }
 *
 *   // Build cache control header
 *   const directives = [`max-age=${options.maxAge}`];
 *   if (options.sMaxAge !== undefined) {
 *     directives.push(`s-maxage=${options.sMaxAge}`);
 *   }
 *   if (options.public) {
 *     directives.push("public");
 *   }
 *
 *   // Clone and modify response
 *   const newResponse = new Response(response.body, response);
 *   newResponse.headers.set("Cache-Control", directives.join(", "));
 *
 *   return newResponse;
 * };
 * ```
 */
export declare interface OutboundPolicyHandler<TOptions = any> {
  (
    response: Response,
    request: ZuploRequest,
    context: ZuploContext,
    options: TOptions,
    policyName: string
  ): Promise<Response>;
}

/**
 * Base object for parameter definitions
 * @public
 */
export declare type ParameterBaseObject = Modify<
  Omit<
    OpenAPIV3_1.ParameterBaseObject,
    | "content"
    | "allowEmptyValue"
    | "style"
    | "allowReserved"
    | "explode"
    | "example"
    | "examples"
  >,
  {
    schema: OpenAPIV3_1.SchemaObject;
  }
>;

/**
 * Definition of a parameter
 * @public
 */
export declare interface ParameterDefinition extends ParameterBaseObject {
  name: string;
  in: string;
}

/**
 * This is the parsed values of the Cors configuration. All
 * values in the parsed configuration are in the format that the headers
 * use them (i.e. everything is converted to a string)
 */
declare interface ParsedCorsPolicyConfiguration {
  name: string;
  allowCredentials: string | undefined;
  maxAge: string | undefined;
  allowedOrigins: string[];
  allowedMethods?: string;
  allowedHeaders?: string;
  exposeHeaders?: string;
}

/**
 * @public
 */
declare interface ParsedRouteData extends Omit<RouteData, "corsPolicies"> {
  corsPolicies: ParsedCorsPolicyConfiguration[];
  /* Excluded from this release type: getInboundPolicyInstance */
}

declare abstract class PolicyBase<TOptions = any> {
  options: TOptions;
  policyName: string;
  /* Excluded from this release type: policyType */
  /* Excluded from this release type: direction */
  /* Excluded from this release type: __constructor */
}

/**
 * @public
 */
export declare interface PolicyConfiguration {
  name: string;
  policyType: string;
  handler: HandlerDefinition;
  options?: unknown;
}

/**
 * The base class for inbound and outbound policies.
 * Provides common functionality for all policy types.
 *
 * @public
 */
/**
 * The pipeline phase a policy runs in. Inbound policies run on the request
 * before the handler; outbound policies run on the response after it. This is
 * determined structurally by whether a policy extends {@link InboundPolicy} or
 * {@link OutboundPolicy}, so it can never drift from the policy's real phase.
 *
 * @public
 */
declare type PolicyDirection = "inbound" | "outbound";

/**
 * Runs only if its handler's verdict wins, after the inbound chain has
 * stopped — the one place a pre-request handler may touch shared context
 * state. Resolve a `Response` to serve it, or `undefined` to withdraw the
 * verdict and let the pipeline proceed.
 * @beta
 */
export declare interface PreRequestCommit {
  (): Promise<Response | undefined>;
}

/**
 * Work started by an inbound policy that runs concurrently with the rest of
 * the inbound policy chain. Registered with
 * {@link ZuploContext.addPreRequestHandler}, started immediately.
 *
 * Resolve `undefined` to let the request proceed, a `Response` to
 * short-circuit the pipeline with it, or a {@link PreRequestCommit} for a
 * verdict that needs exclusive serve-time work.
 *
 * Handlers run out of order relative to the policies they overlap, so they
 * must never mutate or consume the live request — capture what they need
 * (for example via `request.clone()`) before registering.
 * @beta
 */
export declare interface PreRequestHandler {
  (api: PreRequestHandlerApi): Promise<Response | PreRequestCommit | undefined>;
}

/**
 * The API handed to a {@link PreRequestHandler} when it starts.
 * @beta
 */
export declare interface PreRequestHandlerApi {
  /**
   * Aborted when this handler's verdict can no longer win — another verdict
   * was served, or the pipeline resolved with the chain's own response or an
   * error. Pass it to `fetch()` so the external call is actually cancelled.
   */
  readonly signal: AbortSignal;
}

/**
 * @public
 */
export declare interface PreRoutingHook {
  (request: Request): Promise<Request> | Request;
}

declare type Primitive =
  | null
  | undefined
  | string
  | number
  | boolean
  | symbol
  | bigint;

/**
 * Problem Details for HTTP APIs
 * @see {@link https://www.rfc-editor.org/rfc/rfc7807 |RFC7807}
 * @public
 */
export declare interface ProblemDetails {
  /**
   * A URI reference [RFC3986] that identifies the problem type.
   *
   * @remarks
   *
   * This specification encourages that, when dereferenced, it provide
   * human-readable documentation for the  problem type
   * (e.g., using HTML [W3C.REC-html5-20141028]).  When this member is not
   * present, its value is assumed to be "about:blank".
   *
   * @see {@link https://www.rfc-editor.org/rfc/rfc3986|RFC3986}
   *
   * @example
   * https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429
   */
  type: string;
  /**
   * A short, human-readable summary of the problem type.
   *
   * @remarks
   *
   * It SHOULD NOT change from occurrence to occurrence of the problem, except
   * for purposes of localization (e.g., using proactive content negotiation;
   *
   * @see {@link https://www.rfc-editor.org/rfc/rfc7231#section-3.4|RFC7231, Section 3.4}.
   *
   * @example
   * Too many requests
   */
  title: string;
  /**
   * The HTTP status code () generated by the origin server for this occurrence
   * of the problem.
   *
   * @see {@link https://www.rfc-editor.org/rfc/rfc7231#section-6|RFC7231, Section 6}
   *
   * @example
   * 429
   */
  status: HttpStatusCode;
  /**
   * A human-readable explanation specific to this occurrence of the problem.
   *
   * @example
   * Rate limit exceeded, try again later
   */
  detail?: string;
  /**
   * A URI reference that identifies the specific occurrence of the problem.
   * It may or may not yield further information if dereferenced.
   *
   * @example
   * josh-twist::test::main::prod::4edc99c/pizza/size/large/type/pepperoni
   */
  instance?: string;
  /**
   * Identifiers useful to zuplo and the customer to locate more information in
   * logs. To reduce the number of properties these strings are concated
   *
   * @example
   * requestId:6384105d-1d34-4a7f-8ad7-5c428e97ab49/ray:lcielfnuuclvh/buildId:293908c3-e359-4037-874f-d9c71d4a7263
   */
  trace?: Record<string, string>;
  /**
   * Problem type definitions MAY extend the problem details object with
   * additional members.
   */
  [extensionMembers: string]: any;
}

/**
 * @public
 */
export declare interface ProblemResponseDetails {
  problem: ProblemDetails;
  /**
   * statusText used in the response to accompany the
   */
  statusText?: string;
  /**
   * Additional headers to be sent with the standard response. Used for things
   * like rate-limit retry-after headers (to meet other standards)
   */
  additionalHeaders?: HeadersInit;
}

/**
 * @public
 */
export declare interface ProblemResponseFormat {
  (
    problemDetails: ProblemResponseDetails,
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<Response> | Response;
}

/**
 * @public
 */
export declare class ProblemResponseFormatter {
  static format(
    problemDetails: ProblemResponseDetails,
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<Response>;
}

/**
 * Uses an LLM agent to detect prompt injection attempts in user provided content
 * or potentially poisoned response bodies. This is primarily intended to be used
 * with downstream LLM agents who are at risk of having prompt injection attacks
 * executed against them.
 *
 * @title Prompt Injection Detection
 * @product ai-gateway
 * @product mcp-gateway
 * @public
 * @enterprise
 * @requiresAI
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const PromptInjectionDetectionOutboundPolicy: OutboundPolicyHandler<PromptInjectionDetectionOutboundPolicyOptions>;

/**
 * The options for Prompt Injection Detection Outbound policy.
 * @public
 */
export declare interface PromptInjectionDetectionOutboundPolicyOptions {
  /**
   * API key for an OpenAI compatible service.
   */
  apiKey: string;
  /**
   * Model to use for classification.
   */
  model?: string;
  /**
   * Whether to block traffic if the classifier fails. When disabled, allows traffic flow if the classifier or inference API is unavailable.
   */
  strict?: boolean;
  /**
   * Base URL for the OpenAI compatible API.
   */
  baseUrl?: string;
}

/**
 * Authenticate users using PropelAuth issued JWT tokens.
 *
 * @title PropelAuth JWT Auth
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const PropelAuthJwtInboundPolicy: InboundPolicyHandler<PropelAuthJwtInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface PropelAuthJwtInboundPolicyOptions {
  /**
   * Your PropelAuth authUrl. For example, `https://12345678.propelauthtest.com`.
   */
  authUrl: string;
  /**
   * Your public (verifier) key that is used to verify access tokens. This key has a value that begins with '-----BEGIN PUBLIC KEY-----'. Make sure to remove all line breaks from the key before saving the variable.
   */
  verifierKey: string;
  /**
   * Allow unauthenticated requests to proceed. This is use useful if you want to use multiple authentication policies or if you want to allow both authenticated and non-authenticated traffic.
   */
  allowUnauthenticatedRequests?: boolean;
  /**
   * Enables OAuth 2.0 Protected Resource Metadata discovery (RFC 9728). When `true`, requests without a bearer token receive a 401 whose `WWW-Authenticate` header points `resource_metadata` at the `/.well-known/oauth-protected-resource` document for the request path and, when the `OAuthProtectedResourcePlugin` declares `scopesSupported`, lists those scopes in `scope`. Requires the `OAuthProtectedResourcePlugin` in `zuplo.runtime.ts` or a user-defined route at that path.
   */
  oAuthResourceMetadataEnabled?: boolean;
}

/**
 * A model reference in providerName/model form, split on the first slash.
 * @public
 */
declare type ProviderAndModel = string;

/**
 * A model reference in providerName/model form, split on the first slash.
 * @public
 */
declare type ProviderAndModel_2 = string;

/**
 * Extracts a query parameter and sets it as a header in the request.
 *
 * @title Query Parameter to Header
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const QueryParamToHeaderInboundPolicy: InboundPolicyHandler<QueryParamToHeaderInboundPolicyOptions>;

/**
 * The options for the query parameter to header inbound policy.
 * @public
 */
export declare interface QueryParamToHeaderInboundPolicyOptions {
  /**
   * The name of the query parameter to extract.
   */
  queryParam: string;
  /**
   * The name of the header to set.
   */
  headerName: string;
  /**
   * The {value} template for the header. Use {value} to substitute the query parameter value.
   */
  headerValue: string;
  /**
   * Whether to remove the query parameter from the URL after extracting it.
   */
  removeFromUrl?: boolean;
}

export declare interface QuotaDetail {
  key: string;
  allowances: {
    [k: string]: number;
  };
}

/**
 * The model selected after a usage-limit-exceeded signal.
 * @public
 */
declare type QuotaFallbackModel = string;

/**
 * Global quota fallback models, keyed by capability. Applied whenever any
 * configured quota limit (any meter/period) is exceeded.
 */
declare interface QuotaFallbackModels {
  completions?: ModelConfiguration;
  embeddings?: ModelConfiguration;
}

/**
 * The Quota policy enables you to set monthly, weekly, daily or hourly quotas on your API.
 *
 * @title Quota
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare class QuotaInboundPolicy extends InboundPolicy<QuotaInboundPolicyOptions> {
  #private;
  static readonly policyType = "quota";
  handler(
    request: ZuploRequest<RequestGeneric>,
    context: ZuploContext
  ): Promise<ZuploRequest<RequestGeneric> | Response>;
  static setMeters(context: ZuploContext, meters: Record<string, number>): void;
  static getUsage(context: ZuploContext, policyName: string): GetQuotaResult;
}

/**
 * The options for this policy.
 * @public
 */
export declare interface QuotaInboundPolicyOptions {
  /**
   * The period of the quota.
   */
  period: "hourly" | "daily" | "weekly" | "monthly";
  /**
   * The quota by.
   */
  quotaBy: "user" | "function";
  /**
   * The allowances for the quota.
   */
  allowances?: {
    [k: string]: number;
  };
  /**
   * How the policy determines the anchor date for ongoing quota cycles - defaults to `first-api-call` which uses the first API call for this key.
   */
  quotaAnchorMode?: "first-api-call" | "function";
  /**
   * A list of successful status codes and ranges "200-299, 304" that should trigger a quota increment.
   */
  quotaOnStatusCodes?: string | number[];
  /**
   * The module and functions to dynamically set the anchor date and/or the key/allowances for this request.
   */
  identifier?: {
    /**
     * Specifies the module to load your custom functions, in the format `$import(./modules/my-module)`.
     */
    module: string;
    /**
     * used when quotaAnchorMode is `function`. Specifies the export to load your custom function to get the anchor date.
     */
    getAnchorDateExport?: string;
    /**
     * used when quotaBy is `function`. Specifies the export to load your custom function to get the quota detail.
     */
    getQuotaDetailExport?: string;
  };
}

declare interface QuotaLimit {
  daily?: QuotaSettings;
  monthly?: QuotaSettings;
}

declare interface QuotaSettings {
  enabled: boolean;
  limit?: number;
  warning?: WarningSettings;
}

/**
 * The identifying element of the request that enforces distinct rate limits. For example, you can limit by `user`, `ip`, `function` or `all` - function allows you to specify a simple function to create a string identifier to create a rate-limit group.
 * @public
 */
declare type RateLimitByType = "user" | "ip" | "function" | "all";

/**
 * The identifying element of the request that enforces distinct rate limits. For example, you can limit by `user`, `ip`, `function` or `all` - function allows you to specify a simple function to create a string identifier to create a rate-limit group.
 * @public
 */
declare type RateLimitByType_2 = "user" | "ip" | "function" | "all";

declare type RateLimitFunction<T extends CustomRateLimitDetailsBase> = (
  request: ZuploRequest,
  context: ZuploContext,
  policyName: string
) =>
  | (Partial<T> & CustomRateLimitDetailsBase)
  | undefined
  | null
  | Promise<(Partial<T> & CustomRateLimitDetailsBase) | undefined | null>;

/**
 * Adds the retry-after header.
 * @public
 */
declare type RateLimitHeaderMode = "none" | "retry-after";

/**
 * Adds the retry-after header.
 * @public
 */
declare type RateLimitHeaderMode_2 = "none" | "retry-after";

/**
 * Rate limiting policy to control the number of requests to your API.
 * Supports multiple identification strategies (by user, IP, header, etc.) and
 * can operate in strict or async mode for different performance characteristics.
 *
 * @title Rate Limiting
 * @product api-gateway
 * @public
 *
 * @param request - The incoming ZuploRequest
 * @param context - The ZuploContext
 * @param options - The rate limiting configuration
 * @param policyName - The name of the policy instance
 * @returns The request if allowed, or a 429 Too Many Requests response
 *
 * @example
 * ```json
 * // policies.json - Rate limit by authenticated user
 * {
 *   "name": "rate-limit-by-user",
 *   "policyType": "rate-limit-inbound",
 *   "handler": {
 *     "export": "RateLimitInboundPolicy",
 *     "module": "$import(@zuplo/runtime)",
 *     "options": {
 *       "rateLimitBy": "user",
 *       "requestsAllowed": 100,
 *       "timeWindowMinutes": 1
 *     }
 *   }
 * }
 * ```
 *
 * @example
 * ```json
 * // Rate limit by custom header
 * {
 *   "handler": {
 *     "export": "RateLimitInboundPolicy",
 *     "module": "$import(@zuplo/runtime)",
 *     "options": {
 *       "rateLimitBy": "header",
 *       "headerName": "x-customer-id",
 *       "requestsAllowed": 1000,
 *       "timeWindowMinutes": 60,
 *       "mode": "strict"
 *     }
 *   }
 * }
 * ```
 *
 * @example
 * ```typescript
 * // Custom rate limit function
 * import { CustomRateLimitFunction } from "@zuplo/runtime";
 *
 * export const customRateLimit: CustomRateLimitFunction = async (
 *   request,
 *   context
 * ) => {
 *   // Different limits for different plan tiers
 *   const user = request.user;
 *   const plan = (user?.data as any)?.plan || "free";
 *
 *   switch (plan) {
 *     case "enterprise":
 *       return {
 *         key: user.sub,
 *         requestsAllowed: 10000,
 *         timeWindowMinutes: 60
 *       };
 *     case "pro":
 *       return {
 *         key: user.sub,
 *         requestsAllowed: 1000,
 *         timeWindowMinutes: 60
 *       };
 *     default:
 *       return {
 *         key: user?.sub || request.headers.get("cf-connecting-ip") || "anonymous",
 *         requestsAllowed: 100,
 *         timeWindowMinutes: 60
 *       };
 *   }
 * };
 * ```
 *
 * @example
 * ```typescript
 * // Skip rate limiting for specific conditions (return undefined)
 * import { CustomRateLimitFunction, CustomRateLimitDetails } from "@zuplo/runtime";
 *
 * export const customRateLimitWithSkip: CustomRateLimitFunction = async (
 *   request,
 *   context
 * ): Promise<CustomRateLimitDetails | undefined> => {
 *   // Skip rate limiting for whitelisted IPs or internal services
 *   const clientIp = request.headers.get("cf-connecting-ip");
 *   if (isWhitelisted(clientIp)) {
 *     return undefined;  // Skip rate limiting entirely - no Redis call
 *   }
 *   return { key: `user-${request.user?.sub}` };
 * };
 * ```
 */
declare const RateLimitInboundPolicy: InboundPolicyHandler<RateLimitInboundPolicyOptions>;
export { RateLimitInboundPolicy as BasicRateLimitInboundPolicy };
export { RateLimitInboundPolicy };

/**
 * The options for this policy.
 * @public
 */
declare interface RateLimitInboundPolicyOptions {
  rateLimitBy: RateLimitByType_2;
  /**
   * The max number of requests allowed in the given time window.
   */
  requestsAllowed: number;
  /**
   * The time window in which the requests are rate-limited. The count restarts after each window expires.
   */
  timeWindowMinutes: number;
  /**
   * The function that returns dynamic configuration data. Used only with `rateLimitBy=function`.
   */
  identifier?: {
    /**
     * used only with rateLimitBy=function. Specifies the export to load your custom bucket function, e.g. `default`, `rateLimitIdentifier`.
     */
    export: string;
    /**
     * Specifies the module to load your custom bucket function, in the format `$import(./modules/my-module)`.
     */
    module: string;
  };
  headerMode?: RateLimitHeaderMode_2;
  /**
   * If true, the policy will throw an error in the event there is a problem connecting to the rate limit service.
   */
  throwOnFailure?: boolean;
  mode?: RateLimitMode_2;
}
export { RateLimitInboundPolicyOptions as BasicRateLimitInboundPolicyOptions };
export { RateLimitInboundPolicyOptions };

/**
 * The mode of the policy. If set to `async`, the policy will check if the request is over the rate limit without blocking. This can result in some requests allowed over the rate limit.
 * @public
 */
declare type RateLimitMode = "strict" | "async";

/**
 * The mode of the policy. If set to `async`, the policy will check if the request is over the rate limit without blocking. This can result in some requests allowed over the rate limit.
 * @public
 */
declare type RateLimitMode_2 = "strict" | "async";

/**
 * The options for this policy. Many of them can be overridden at the code level in a request using the `AmberfloMeteringPolicy.setRequestProperties` method.
 * @public
 */
declare interface ReadmeMeteringInboundPolicyOptions {
  /**
   * The API key to use when sending metrics calls to Readme.
   */
  apiKey: string;
  /**
   * This is the path to the property on `request.user` that contains the e-mail of the user. For example `.data.email` would read the `request.user.data.email` property.
   */
  userEmailPropertyPath?: string;
  /**
   * This is the path to the property on `request.user` that contains the label you want to use. For example `.data.accountNumber` would read the `request.user.data.accountNumber` property.
   */
  userLabelPropertyPath?: string;
  /**
   * Whether the data should be ingested as 'development' mode or not. Defaults to true for working-copy and false for all other environments.
   */
  development?: boolean;
  /**
   * When true, Zuplo sends the full request path (which might contain sensitive information). By default, we only send the route path which should not contain sensitive information.
   */
  useFullRequestPath?: boolean;
  /**
   * The URL to send metering events. This is useful for testing purposes.
   */
  url?: string;
}

/**
 * Readme is a developer documentation and API metrics company. This
 * policy pushes logs to their API calls dashboard.
 *
 * @title Readme Metrics
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare function ReadmeMetricsInboundPolicy(
  request: ZuploRequest,
  context: ZuploContext,
  options: ReadmeMeteringInboundPolicyOptions,
  policyName: string
): Promise<ZuploRequest<RequestGeneric>>;

/**
 * How many of the conversation's most recent messages the classifier inspects (input items on the Responses endpoint). Earlier messages are not re-inspected: each was screened when it was the newest, so a chat session pays for one classification per turn instead of one per transcript. System and developer messages, Anthropic's top-level `system` and the Responses `instructions` field never count and are never inspected — they are your application's own instructions, not where an injection arrives. Tool results count as messages and are inspected. Raise this when clients send conversation history that was assembled outside the gateway. Defaults to 1 (the newest message only).
 * @public
 */
declare type RecentMessageCount = number;

/**
 * How many of the conversation's most recent messages (input items on the Responses endpoint) form the cache key, both when storing a response and when matching later requests. Earlier messages are ignored, so a multi-turn conversation can hit an entry cached from a shorter one; system messages are always included. Requests whose keyed window contains no user message (for example a conversation ending in an assistant prefill) are not cached. Defaults to 1 (match on the newest message only).
 * @public
 */
declare type RecentMessageCount_2 = number;

/**
 * Record the GraphQL response-cache outcome for the in-flight operation so
 * the analytics middleware can emit it as the `cacheState` dimension on the
 * `graphql_operation` event.
 *
 * Called by the Zuplo-provided GraphQL Cache policy (`graphql-cache-inbound`,
 * in the `@zuplo/graphql` package) the moment it resolves a cache hit or
 * miss — synchronously during inbound processing, before the analytics
 * middleware finalizes the event. Mirrors how the GraphQL Analytics outbound
 * policy feeds errors through {@link getOperationContext}.
 *
 * No-op when the request isn't running the GraphQL analytics middleware (the
 * route lacks the `x-graphql: true` marker, so there's no operation context to
 * write to), so it's always safe to call.
 *
 * @public
 */
export declare function recordGraphqlCacheState(
  context: ZuploContext,
  cacheState: GraphqlCacheState
): void;

/**
 * Handler that returns HTTP redirects.
 * Useful for URL shortening, legacy URL handling, or routing to external services.
 *
 * @param request - The incoming ZuploRequest
 * @param context - The ZuploContext
 * @returns A redirect Response with the specified status code
 *
 * @public
 * @example
 * ```json
 * // routes.oas.json
 * {
 *   "paths": {
 *     "/old-api": {
 *       "x-zuplo-route": {
 *         "handler": {
 *           "export": "redirectHandler",
 *           "module": "$import(@zuplo/runtime)",
 *           "options": {
 *             "location": "https://api.example.com/v2",
 *             "status": 301
 *           }
 *         }
 *       }
 *     }
 *   }
 * }
 * ```
 *
 * @example
 * ```json
 * // Temporary redirect (302 is default)
 * {
 *   "handler": {
 *     "export": "redirectHandler",
 *     "module": "$import(@zuplo/runtime)",
 *     "options": {
 *       "location": "https://maintenance.example.com"
 *     }
 *   }
 * }
 * ```
 */
export declare function redirectHandler(
  request: ZuploRequest,
  context: ZuploContext
): Promise<Response>;

/**
 * @deprecated Use `legacyDevPortalHandler` instead.
 */
export declare const redirectLegacyDevPortal: (
  request: ZuploRequest,
  context: ZuploContext
) => Response | Promise<Response>;

/**
 *
 * @export
 * @interface RelationshipCondition
 */
declare interface RelationshipCondition {
  /**
   * A reference (by name) of the relationship condition defined in the authorization model.
   * @type {string}
   * @memberof RelationshipCondition
   */
  name: string;
  /**
   * Additional context/data to persist along with the condition. The keys must match the parameters defined by the condition, and the value types must match the parameter type definitions.
   * @type {object}
   * @memberof RelationshipCondition
   */
  context?: object;
}

/**
 * Remove headers from the incoming request.
 *
 * @title Remove Request Headers
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const RemoveHeadersInboundPolicy: InboundPolicyHandler<RemoveHeadersInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface RemoveHeadersInboundPolicyOptions {
  /**
   * An array of headers to remove from the incoming request.
   */
  headers: string[];
}

/**
 * Remove configured headers from the outgoing response.
 *
 * @title Remove Response Headers
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const RemoveHeadersOutboundPolicy: OutboundPolicyHandler<RemoveHeadersOutboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface RemoveHeadersOutboundPolicyOptions {
  /**
   * An array of headers to be removed from the outgoing response.
   */
  headers: string[];
}

/**
 * Remove query parameters from the incoming request
 *
 * @title Remove Query Parameters
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const RemoveQueryParamsInboundPolicy: InboundPolicyHandler<RemoveQueryParamsInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface RemoveQueryParamsInboundPolicyOptions {
  /**
   * An array of query parameters to be removed from the incoming request.
   */
  params: string[];
}

/**
 * Replace a string in the incoming request body
 *
 * @title Replace String in Response Body
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const ReplaceStringOutboundPolicy: OutboundPolicyHandler<ReplaceStringOutboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface ReplaceStringOutboundPolicyOptions {
  /**
   * The type of string replacement to perform.
   */
  mode: "regexp" | "string";
  /**
   * The pattern to match.
   */
  match: string;
  /**
   * The value to each match is replaced with.
   */
  replaceWith: string;
}

/**
 * Generic type parameters for a request.
 * Extends RequestInitGeneric and adds query parameter typing.
 * @public
 */
export declare interface RequestGeneric extends RequestInitGeneric {
  Query?: RequestQueryDefault;
}

/* Excluded from this release type: RequestHandlerFunction */

/* Excluded from this release type: RequestHandlerProxy */

/**
 * Generic type parameters for request initialization.
 * Used to strongly type the user data and path parameters.
 * @public
 */
export declare interface RequestInitGeneric {
  UserData?: UserDataDefault;
  Params?: RequestParamsDefault;
}

/**
 * Metadata for request logger entries
 * @public
 */
export declare interface RequestLoggerMetaData {
  requestStartTime: Date;
  durationMs: number;
  instanceId: string;
  deploymentName: string;
  systemUserAgent: string;
}

/**
 * Options for request logger
 * @public
 */
export declare interface RequestLoggerOptions<T> {
  name: string;
  dispatchFunction: DispatchRequestLoggerEntries<T>;
  generateLogEntry: GenerateRequestLoggerEntry<T>;
  batchPeriodSeconds?: number;
}

/**
 * Request logger plugin
 * @public
 */
export declare class RequestLoggerPlugin<
  T extends BasicDictionary,
> extends SystemRuntimePlugin {
  #private;
  constructor(options: RequestLoggerOptions<T>);
  initialize(runtime: RuntimeExtensions): Promise<void>;
}

/* Excluded from this release type: RequestLogPropertyValue */

declare type RequestParamsDefault = Record<string, string>;

/* Excluded from this release type: RequestProcessor */

declare type RequestQueryDefault = Record<string, string>;

declare interface RequestReference {
  ReferenceId: string[];
}

/**
 * Enforces a maximum size in bytes of the incoming request.
 *
 * @title Request Size Limit
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const RequestSizeLimitInboundPolicy: InboundPolicyHandler<RequestSizeLimitInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface RequestSizeLimitInboundPolicyOptions {
  /**
   * The maximum size of the request in bytes.
   */
  maxSizeInBytes: number;
  /**
   * If true, the policy will reject any request with a `content-length` header in excess of `maxSizeInBytes` bytes value, but will not verify the actual size of the request. This is more efficient and offers slightly better memory usage but should only be used if you trust/control the clients calling the gateway to send an accurate content-length. If false, the gateway will actually verify the request size and reject any request with a size in excess of the stated maximum.
   */
  trustContentLengthHeader?: boolean;
}

/**
 * Represents an authenticated user on the request.
 * Set by authentication policies like API key, JWT, or OAuth.
 *
 * @public
 * @example
 * ```typescript
 * // Access user info in a handler
 * export function myHandler(request: ZuploRequest, context: ZuploContext) {
 *   if (!request.user) {
 *     return new Response("Unauthorized", { status: 401 });
 *   }
 *
 *   const userId = request.user.sub;
 *   const customData = request.user.data as { role: string; tenantId: string };
 *
 *   context.log.info(`Request from user ${userId} with role ${customData.role}`);
 * }
 * ```
 */
export declare interface RequestUser<TUserData> {
  sub: string;
  data: TUserData;
}

/**
 * Validates incoming requests against your OpenAPI specification.
 * Checks query parameters, path parameters, headers, and request body
 * to ensure they match the defined schema before processing.
 *
 * @title Request Validation
 * @product api-gateway
 * @public
 *
 * @param request - The incoming ZuploRequest
 * @param context - The ZuploContext
 * @param options - Validation configuration options
 * @param policyName - The name of the policy instance
 * @returns The validated request or a 400 Bad Request response with validation errors
 *
 * @example
 * ```json
 * // policies.json - Validate all request components
 * {
 *   "name": "validate-request",
 *   "policyType": "request-validation-inbound",
 *   "handler": {
 *     "export": "RequestValidationInboundPolicy",
 *     "module": "$import(@zuplo/runtime)",
 *     "options": {
 *       "validateBody": true,
 *       "validateQueryParameters": true,
 *       "validatePathParameters": true,
 *       "validateHeaders": true
 *     }
 *   }
 * }
 * ```
 *
 * @example
 * ```json
 * // Validate only body with custom error handling
 * {
 *   "handler": {
 *     "export": "RequestValidationInboundPolicy",
 *     "module": "$import(@zuplo/runtime)",
 *     "options": {
 *       "validateBody": {
 *         "enabled": true,
 *         "logging": true,
 *         "requestSizeLimit": 1048576
 *       },
 *       "validateQueryParameters": false,
 *       "validatePathParameters": false,
 *       "validateHeaders": false
 *     }
 *   }
 * }
 * ```
 *
 * @example
 * ```yaml
 * # OpenAPI schema definition
 * paths:
 *   /users/{userId}:
 *     post:
 *       parameters:
 *         - name: userId
 *           in: path
 *           required: true
 *           schema:
 *             type: string
 *             format: uuid
 *         - name: include
 *           in: query
 *           schema:
 *             type: array
 *             items:
 *               type: string
 *               enum: [profile, settings, history]
 *       requestBody:
 *         required: true
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               required: [name, email]
 *               properties:
 *                 name:
 *                   type: string
 *                   minLength: 1
 *                   maxLength: 100
 *                 email:
 *                   type: string
 *                   format: email
 * ```
 */
export declare const RequestValidationInboundPolicy: InboundPolicyHandler<RequestValidationInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface RequestValidationInboundPolicyOptions {
  validateBody?: ValidationOptions;
  validateQueryParameters?: ValidationOptions1;
  validatePathParameters?: ValidationOptions2;
  validateHeaders?: ValidationOptions3;
  /**
   * The log level to use when logging validation errors.
   */
  logLevel?: "error" | "warn" | "info" | "debug";
  /**
   * Whether to include the request in the logs.
   */
  includeRequestInLogs?: boolean;
}

/**
 * Sets an allow-list for an origin header
 *
 * @title Require Origin
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const RequireOriginInboundPolicy: InboundPolicyHandler<RequireOriginInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface RequireOriginInboundPolicyOptions {
  /**
   * A comma separated string containing valid origins.
   */
  origins: string;
  /**
   * The `detail` of the HTTP Problem response, if the origin is missing or disallowed.
   */
  failureDetail?: string;
}

/**
 * Authorizes requests by validating claims on the authenticated user
 * (`request.user`) against a configurable rule of `and`/`or` combinators and
 * per-claim `eq`, `in`, and `startsWith` checks. Run it after any
 * authentication policy that populates `request.user` — a JWT auth policy, API
 * key auth, mTLS, and so on — to allow only specific callers (service
 * accounts, OAuth clients, tenants, groups) without writing custom code.
 *
 * Every check fails closed: a missing or non-primitive claim never matches,
 * comparisons are strict and type-sensitive, and requests without an
 * authenticated user receive a 401 response. Denied requests receive a 403
 * response that does not echo claim values or expected values; the failing
 * checks are written to the request log instead.
 *
 * Validation of the options runs lazily inside the policy constructor, which
 * the runtime caches per policy name. Misconfigured options therefore fail on
 * first use with a customer-facing `ConfigurationError` instead of failing at
 * module load.
 *
 * @title Require User Claims
 * @product api-gateway
 * @public
 */
export declare class RequireUserClaimsInboundPolicy extends InboundPolicy<RequireUserClaimsInboundPolicyOptions> {
  #private;
  static readonly policyType = "require-user-claims";
  constructor(rawOptions: unknown, policyName: string);
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
}

/**
 * The options for this policy.
 * @public
 */
export declare interface RequireUserClaimsInboundPolicyOptions {
  rule: Rule;
}

declare type ResolveRequestParams<
  TParams extends RequestParamsDefault | undefined,
> = TParams extends RequestParamsDefault ? TParams : RequestParamsDefault;

declare type ResolveRequestQuery<
  TQuery extends RequestQueryDefault | undefined,
> = TQuery extends RequestQueryDefault ? TQuery : RequestQueryDefault;

declare type ResolveUserData<TUserData extends UserDataDefault | undefined> =
  TUserData extends UserDataDefault ? TUserData : UserDataDefault;

/**
 * Reports whether a `Response` carries GraphQL errors — a `200 OK` with a
 * top-level `errors[]` array, as Apollo / graphql-yoga servers return on a
 * failed operation. Reads the body from a clone, so the original response
 * stream still flows to the client untouched.
 *
 * The result is cached against the `response` object: the body is read,
 * scanned, and parsed at most once per response, and every later call
 * (including concurrent ones) resolves to the same cached boolean without
 * touching the stream again.
 *
 * Detection reads at most `maxScanBytes` of the body, scanning it for the
 * `errors` token; a response larger than that — whether by declared
 * `Content-Length` or as measured while reading — is treated as error-free
 * and resolves to `false`. Non-JSON responses also resolve to `false`
 * without reading. Any internal failure is swallowed and reported as
 * `false` — detection is best-effort and never throws.
 *
 * @param response - The response to inspect; left unconsumed.
 * @param maxScanBytes - How many bytes of the body to read and scan.
 *   Defaults to {@link DEFAULT_GRAPHQL_SCAN_BYTES} (128 KiB); a body larger
 *   than this goes unreported. Only the first call for a given `response`
 *   observes this value; later calls return the cached result.
 * @returns `true` when the body contains a top-level `errors[]` with at
 *   least one entry, otherwise `false`.
 */
export declare function responseHasGraphqlErrors(
  response: Response,
  maxScanBytes?: number
): Promise<boolean>;

declare interface ResponseInputItem {
  type?: "message";
  role: "user" | "assistant" | "system" | "developer";
  content:
    | string
    | Array<{
        type: "text" | "image_url" | "audio";
        text?: string;
        image_url?: {
          url: string;
        };
        audio?: {
          data: string;
          format: string;
        };
      }>;
}

declare interface ResponsesChoice {
  index: number;
  id?: string;
  type?: "message";
  role?: "assistant";
  content?: Array<{
    type: "output_text";
    text: string;
    annotations?: Array<unknown>;
  }>;
  status?: string | null;
  finish_reason?:
    | "stop"
    | "length"
    | "function_call"
    | "tool_calls"
    | "content_filter";
}

/**
 * Definition of responses for a route
 * @public
 */
export declare type ResponsesDefinition = Record<
  HttpStatusCode | HttpStatusCodeRangeDefinition,
  Modify<
    Omit<OpenAPIV3_1.ResponseObject, "links">,
    {
      headers?: {
        [header: string]: ParameterBaseObject;
      };
    }
  >
>;

/**
 * Event fired before a response is sent
 * @public
 */
export declare class ResponseSendingEvent extends Event {
  constructor(request: ZuploRequest, response: Response);
  readonly request: ZuploRequest;
  mutableResponse: Response | Promise<Response>;
}

/**
 * Event fired after a response has been sent
 * @public
 */
export declare class ResponseSentEvent extends Event {
  constructor(request: ZuploRequest, response: Response);
  readonly request: ZuploRequest;
  readonly response: Response;
}

declare interface ResponsesRequest {
  input?: string | ResponseInputItem[];
  model?: string;
  instructions?: string;
  previous_response_id?: string;
  temperature?: number;
  top_p?: number;
  stream?: boolean;
  max_output_tokens?: number;
  tools?: ResponsesToolDefinition[];
  tool_choice?: ResponsesToolChoice;
  parallel_tool_calls?: boolean;
  reasoning?: {
    effort: "low" | "medium" | "high";
  };
  service_tier?: "auto" | "default" | "flex" | "scale" | "priority";
  stream_options?: {
    include_usage?: boolean;
  };
  background?: boolean;
  conversation?: string;
  include?: string[];
  metadata?: Record<string, unknown>;
  store?: boolean;
  truncation?: "auto" | "disabled";
  text?: {
    format?: Record<string, unknown>;
    verbosity?: "low" | "medium" | "high";
  };
  client_metadata?: Record<string, unknown>;
  prompt_cache_key?: string;
  safety_identifier?: string;
}

declare interface ResponsesResponse {
  id: string;
  object: "response";
  created: number;
  model: string;
  status:
    | "queued"
    | "in_progress"
    | "completed"
    | "failed"
    | "cancelled"
    | "incomplete";
  system_fingerprint?: string;
  output?: ResponsesChoice[];
  usage?: ResponsesUsage;
  error?: {
    type: string;
    message: string;
  };
  service_tier?: string;
  provider?: string;
}

declare type ResponsesToolChoice =
  | "none"
  | "auto"
  | "required"
  | {
      mode: "auto" | "required";
      tools: Array<Record<string, unknown>>;
      type: "allowed_tools";
    }
  | {
      name: string;
      type: "custom";
    }
  | {
      name: string;
      type: "function";
    }
  | {
      server_label: string;
      type: "mcp";
      name?: string | null;
    }
  | {
      type:
        | "file_search"
        | "web_search_preview"
        | "computer_use_preview"
        | "web_search_preview_2025_03_11"
        | "image_generation"
        | "code_interpreter"
        | "mcp";
    };

declare type ResponsesToolDefinition =
  | FunctionTool
  | WebSearchTool
  | WebSearchPreviewTool
  | CodeInterpreterTool
  | FileSearchTool
  | ComputerUseTool
  | ImageGenerationTool
  | LocalShellTool
  | CustomTool
  | McpTool;

declare interface ResponsesUsage {
  input_tokens: number;
  output_tokens: number;
  total_tokens: number;
  input_tokens_details?: {
    cached_tokens?: number;
    cache_write_tokens?: number;
  };
  output_tokens_details?: {
    reasoning_tokens?: number;
  };
}

/**
 * @public
 */
export declare interface RouteConfiguration extends Omit<
  BuildRouteConfiguration,
  "raw"
> {
  /**
   * @deprecated Please switch to "raw().operationId"
   */
  operationId?: string;
  /**
   * @deprecated Please switch to "raw().summary"
   */
  summary?: string;
  /**
   * @deprecated Please switch to "raw().tags"
   */
  tags?: string[];
  /**
   * @deprecated Please switch to "raw().parameters"
   */
  parameters?: ParameterDefinition[];
  /**
   * @deprecated Please switch to "raw().responses"
   */
  responses?: ResponsesDefinition;
  /**
   * Gets the raw route configuration object
   */
  raw<T = any>(): T;
}

/**
 * @public
 */
export declare interface RouteData {
  /**
   * @deprecated This property is not used and will be removed in future versions
   */
  info?: OpenAPIV3_1.InfoObject;
  routes: RouteConfiguration[];
  policies: PolicyConfiguration[];
  corsPolicies: CorsPolicyConfiguration[];
}

/**
 * @beta
 */
export declare interface RouteHandler<T = unknown> {
  (request: ZuploRequest, context: ZuploContext): Promise<T>;
}

/* Excluded from this release type: Router */

/**
 * The authorization rule evaluated against the authenticated user's claims (request.user.data, populated by the authentication policy that runs before this one — a JWT policy, API key auth, mTLS, etc.). A rule is either a single claim check (eq, in, or startsWith) or an and/or combination of nested rules. Combinators may nest up to three levels deep. Requests that fail the rule receive a 403 Forbidden response.
 * @public
 */
declare type Rule = AndRule | OrRule | EqualsRule | InRule | StartsWithRule;

/* Excluded from this release type: RuntimeEnvironment */

/**
 * Used to indicate errors that are caused by user input or runtime conditions.
 * These errors are shown to the user and logged in user logs.
 * They are NOT fatal and will not cause monitoring alerts.
 *
 * @public
 * @example
 * ```typescript
 * import { RuntimeError } from "@zuplo/runtime";
 *
 * // Simple error
 * throw new RuntimeError("Invalid API key format");
 *
 * // Error with cause
 * try {
 *   await someOperation();
 * } catch (err) {
 *   throw new RuntimeError("Failed to process request", { cause: err });
 * }
 *
 * // Error with extension members for additional context
 * throw new RuntimeError({
 *   message: "Rate limit exceeded",
 *   extensionMembers: {
 *     limit: 100,
 *     window: "1m",
 *     retryAfter: 60
 *   }
 * });
 * ```
 */
export declare class RuntimeError extends Error {
  extensionMembers: Record<string, unknown> | undefined;
  constructor(message: string, options?: ErrorOptions);
  constructor(
    info: {
      message: string;
      extensionMembers?: Record<string, unknown>;
    },
    options?: ErrorOptions
  );
}

/**
 * Zuplo global runtime customization
 * @beta
 */
export declare interface RuntimeExtensions {
  /**
   * Custom response formatter
   */
  problemResponseFormat?: ProblemResponseFormat;
  /**
   * Register runtime plugins
   */
  addPlugin: (plugin: RuntimePlugin) => void;
  /**
   * Set a custom not found handler
   */
  notFoundHandler?: (
    request: ZuploRequest,
    context: ZuploContext,
    notFoundOptions: NotFoundOptions
  ) => Promise<Response>;
  addRequestHook(hook: OnRequestHook): void;
  addResponseSendingHook(hook: OnResponseSendingHook): void;
  addResponseSendingFinalHook(hook: OnResponseSendingFinalHook): void;
  /**
   * Add a hook that runs before route matching occurs
   * @param hook - The pre-routing hook function
   */
  addPreRoutingHook(hook: PreRoutingHook): void;
}

/**
 * Function to configure runtime extensions
 * @public
 */
export declare interface RuntimeExtensionsFunction {
  (runtime: RuntimeExtensions): Promise<void>;
}

/**
 * @public
 */
declare abstract class RuntimePlugin {}

/* Excluded from this release type: RuntimeSettings */

declare type RuntimeType = "deno" | "cloudflare";

/* Excluded from this release type: sanitizedIdentifierName */

/**
 * @deprecated Use RequestValidationInboundPolicy instead
 * @public
 */
export declare const SchemaBasedRequestValidation: InboundPolicyHandler<RequestValidationInboundPolicyOptions>;

/**
 * Masks common secrets like Zuplo API keys, GitHub tokens, or SSH private key
 * in the response body.
 *
 * @title Secret Masking
 * @product api-gateway
 * @public
 * @deprecated Use the {@link https://zuplo.com/docs/policies/data-loss-prevention-outbound|Data Loss Prevention}
 * policy instead. It detects the same Zuplo API keys, GitHub tokens, and private
 * key blocks via its `secret-zuplo`, `secret-github`, and `secret-private-key`
 * recognizers, plus 60+ more built-in entities, and can block or log a response
 * rather than only masking it. This policy will continue to work but will be
 * removed in a future version of Zuplo.
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Response
 */
export declare const SecretMaskingOutboundPolicy: OutboundPolicyHandler<SecretMaskingOutboundPolicyOptions>;

/**
 * @deprecated
 * The options for the secret masking policy. Deprecated - use the Data Loss Prevention outbound policy instead.
 * @public
 */
export declare interface SecretMaskingOutboundPolicyOptions {
  /**
   * The string to replace detected secrets with. Equivalent to the Data Loss Prevention policy's `mask` option.
   */
  mask?: string;
  /**
   * Extra regex patterns for secrets to mask. Replaced by the Data Loss Prevention policy's `customPatterns` option, which also accepts a name, confidence, and context words per pattern.
   */
  additionalPatterns?: string[];
}

/* Excluded from this release type: SemanticAttributes */

/**
 * Respond to matched incoming requests with semantically cached content
 *
 * The Semantic Cache Inbound policy caches responses based on semantic similarity
 * of cache keys rather than exact matches. This allows for more flexible caching
 * where similar requests can return cached responses even if the cache key is not
 * exactly the same.
 *
 * The policy uses Large Language Model (LLM) embeddings to determine semantic
 * similarity between cache keys based on a configurable similarity tolerance.
 *
 * Options:
 * - semanticTolerance: The semantic similarity threshold for semantic cache matches (0-1, default: 0.2). Values closer to 0 require higher similarity. Can be overridden by custom functions.
 * - expirationSecondsTtl: The timeout of the cache in seconds (default: 3600, 1 hour). Can be overridden by custom functions.
 * - namespace: Optional namespace to isolate cache entries (default: "default"). Useful for multi-tenant scenarios or different cache contexts.
 * - cacheBy: Determines how cache keys are generated: 'function' for custom logic or 'propertyPath' to extract from JSON body.
 *
 * @title Semantic Cache
 * @product ai-gateway
 * @public
 * @enterprise
 * @requiresAI
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare function SemanticCacheInboundPolicy(
  request: ZuploRequest,
  context: ZuploContext,
  options: SemanticCacheInboundPolicyOptions,
  policyName: string
): Promise<Response | ZuploRequest<RequestGeneric>>;

/**
 * The options for this policy.
 * @public
 */
export declare type SemanticCacheInboundPolicyOptions = {
  [k: string]: unknown;
} & {
  /**
   * The semantic similarity threshold for semantic cache matches. Values closer to 0 require closer similarity, while larger values allow more flexible matching. Default is 0.2.
   */
  semanticTolerance?: number;
  /**
   * The timeout of the cache in seconds. Defaults to 1 hour.
   */
  expirationSecondsTtl?: number;
  /**
   * Optional namespace to isolate cache entries. Useful for multi-tenant scenarios or different cache contexts.
   */
  namespace?: string;
  /**
   * Determines how the cache key is generated. Use 'function' for custom logic or 'propertyPath' to extract from JSON body.
   */
  cacheBy: "function" | "propertyPath";
  /**
   * A light path selector into the JSON request body to use as the cache key. Start with `.` for dot notation or `[` for a quoted key containing dots or slashes, for example `.userId`, `.data.customerId`, or `["https://example.com/cache-key"]`. Only works with cacheBy=propertyPath.
   */
  cacheByPropertyPath?: string;
  /**
   * The function that returns dynamic cache key data. Used only with `cacheBy=function`.
   */
  cacheByFunction?: {
    /**
     * Specifies the export to load your custom cache key function, e.g. `default`, `cacheKeyIdentifier`.
     */
    export: string;
    /**
     * Specifies the module to load your custom cache key function, in the format `$import(./modules/my-module)`.
     */
    module: string;
  };
  /**
   * Response status codes to be cached.
   */
  statusCodes?: number[];
  /**
   * If true, the policy will return a custom header with the cache status. The default header name is `zp-semantic-cache`.
   */
  returnCacheStatusHeader?: boolean;
  /**
   * The name of the header to return the cache status. Only used if `returnCacheStatusHeader` is true.
   */
  cacheStatusHeaderName?: string;
};

/**
 * The semantic similarity threshold for semantic cache matches. Values closer to 0 require closer similarity, while larger values allow more flexible matching. Default is 0.2.
 * @public
 */
declare type SemanticTolerance = number;

/* Excluded from this release type: serialize */

/**
 * @beta
 */
export declare interface ServiceProvider {
  addService<T>(name: string, service: T): void;
  getService<T>(name: string): T;
}

/* Excluded from this release type: ServiceProviderImpl */

/**
 * Sets the body of the request in the inbound pipeline - make sure to convert
 * a GET/HEAD request to another method when using this policy.
 *
 * @title Set Body
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const SetBodyInboundPolicy: InboundPolicyHandler<SetBodyInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface SetBodyInboundPolicyOptions {
  /**
   * The value to set for the body.
   */
  body: string;
}

/**
 * Adds or sets headers on the incoming request.
 *
 * @title Add or Set Request Headers
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const SetHeadersInboundPolicy: InboundPolicyHandler<SetHeadersInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface SetHeadersInboundPolicyOptions {
  /**
   * An array of headers to set in the request. By default, headers will be overwritten if they already exists in the request, specify the overwrite property to change this behavior.
   */
  headers: {
    /**
     * The name of the header.
     */
    name: string;
    /**
     * The value of the header.
     */
    value: string;
    /**
     * Overwrite the value if the header is already present in the request.
     */
    overwrite?: boolean;
  }[];
}

/**
 * Adds or sets headers on the on the outgoing response.
 *
 * @title Set Headers
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const SetHeadersOutboundPolicy: OutboundPolicyHandler<SetHeadersOutboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface SetHeadersOutboundPolicyOptions {
  /**
   * An array of headers to set on the response. By default, headers will be overwritten if they already exists in the response, specify the overwrite property to change this behavior.
   */
  headers: {
    /**
     * The name of the header.
     */
    name: string;
    /**
     * The value of the header.
     */
    value: string;
    /**
     * Overwrite the value if the header is already present in the response.
     */
    overwrite?: boolean;
  }[];
}

/**
 * Sets custom context data that will be included with Moesif analytics events
 * @public
 * @param context - The ZuploContext for the current request
 * @param moesifContext - Custom data to include with Moesif events (userId, companyId, metadata, etc.)
 */
export declare function setMoesifContext(
  context: ZuploContext,
  moesifContext: MoesifContext
): void;

/**
 * Adds or sets query parameters on the incoming request.
 *
 * @title Add or Set Query Parameters
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const SetQueryParamsInboundPolicy: InboundPolicyHandler<SetQueryParamsInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface SetQueryParamsInboundPolicyOptions {
  /**
   * An array of query params to set in the request. By default, query parameters will be overwritten if they already exist in the request, specify the overwrite property to change this behavior.
   */
  params: {
    /**
     * The name of the param.
     */
    name: string;
    /**
     * The value of the param.
     */
    value: string;
    /**
     * Overwrite the value if the param is already present in the request.
     */
    overwrite?: boolean;
  }[];
}

/**
 * Sets the status code on the on the outgoing response.
 *
 * @title Set Status Code
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const SetStatusOutboundPolicy: OutboundPolicyHandler<SetStatusOutboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface SetStatusOutboundPolicyOptions {
  /**
   * The status code to be used in the response.
   */
  status?: number;
  /**
   * The statusText to be used in the response.
   */
  statusText?: string;
}

/**
 * Sets a single header on the incoming request, typically used to attach an
 * API key for the upstream service. A more directed version of the
 * `SetHeadersInboundPolicy` that defaults the header name to `Authorization`
 * and is intended to be used with an `$env()` reference for the value.
 *
 * @title Set Upstream API Key
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const SetUpstreamApiKeyInboundPolicy: InboundPolicyHandler<SetUpstreamApiKeyInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface SetUpstreamApiKeyInboundPolicyOptions {
  /**
   * The value of the header. Most commonly an environment variable reference such as `Bearer $env(UPSTREAM_API_KEY)` so the secret is sourced from your environment.
   */
  value: string;
  /**
   * The name of the header to set on the request. Defaults to `Authorization`.
   */
  header?: string;
  /**
   * Overwrite the value if the header is already present in the request.
   */
  overwrite?: boolean;
}

/**
 * Function type for determining if a request should be logged
 * @public
 * @param request - The HTTP request
 * @param context - The Zuplo context
 * @returns Promise resolving to true if the request should be logged, false otherwise
 */
declare type ShouldLogFunction = (
  request: ZuploRequest,
  context: ZuploContext
) => Promise<boolean>;

/**
 * Add a delay to the incoming request. Useful for testing.
 *
 * @title Sleep / Delay
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const SleepInboundPolicy: InboundPolicyHandler<SleepInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface SleepInboundPolicyOptions {
  /**
   * The number of milliseconds to delay the request.
   */
  sleepInMs: number;
}

/**
 * When true, apply model routing based on the models set in `modelsByComplexity` when confidence score meets the `minConfidenceForRouting` threshold. When set to false, classification still runs but model routing is not applied, useful for debugging or testing the classifier prompt.
 * @public
 */
declare type SmartRoutingEnabled = boolean;

declare interface SplunkLoggingOptions {
  /**
   * The URL for the Splunk HTTP Event Collector (HEC) endpoint.
   * For self-hosted: https://<splunk-host>:8088/services/collector
   * For cloud: https://<your-instance>.splunkcloud.com:8088/services/collector
   * For Splunk Cloud with HTTP inputs: https://http-inputs-<your-instance>.splunkcloud.com:8088/services/collector
   */
  url: string;
  /**
   * The Splunk HEC token for authentication
   */
  token: string;
  /**
   * The Splunk index to send logs to. Defaults to "main"
   */
  index?: string;
  /**
   * The source type of the logs. Defaults to "json"
   */
  sourcetype?: string;
  /**
   * The host identifier for the logs. Defaults to "zuplo-api"
   */
  host?: string;
  /**
   * Any custom log fields to include in each log entry.
   */
  fields?: CustomLogFields;
  /**
   * Channel identifier for Splunk HEC with indexer acknowledgment.
   * If not provided, the X-Splunk-Request-Channel header will not be sent.
   * Required only if your Splunk HEC token has indexer acknowledgment enabled.
   */
  channel?: string;
}

/**
 * Splunk logging plugin
 * @public
 */
export declare class SplunkLoggingPlugin extends LogPlugin {
  private options;
  constructor(options: SplunkLoggingOptions);
  /* Excluded from this release type: getTransport */
}

/* Excluded from this release type: StandardEnv */

declare interface StartsWithRule {
  claim: Claim;
  /**
   * The prefix the claim's string value must start with. Non-string claim values never match. Must not be empty — an empty prefix would match every value. When the claim value is an array, the check passes if any string element starts with this prefix.
   */
  startsWith: string;
}

/**
 * The key that `sticky` uses. `user` uses the authenticated caller, `request.user.sub`. `conversation` uses the conversation's system prompt and its first user message with text. `expression` uses the value that `expression` selects. Required when `strategy` is `sticky`, and not allowed with `round-robin`.
 * @public
 */
declare type StickyBy = "user" | "conversation" | "expression";

/**
 * How the policy picks a model for each request. `round-robin` cycles through the list in order. `sticky` sends every request with the same key to the same model.
 * @public
 */
declare type Strategy = "round-robin" | "sticky";

/**
 * Configuration for accumulating and validating streaming responses.
 * @public
 */
declare interface StreamingAccumulationSettings {
  enabled?: EnableStreamingAccumulation;
  eventsInterval?: EventsInterval;
  checkIntervalMs?: CheckIntervalMs;
}

/**
 * A specialized zone cache for storing and retrieving ReadableStreams.
 * Unlike regular ZoneCache which serializes to JSON, this cache stores raw stream data,
 * making it ideal for caching response bodies, file uploads, or other streaming content.
 *
 * @public
 * @example
 * ```typescript
 * import { StreamingZoneCache, ZuploContext } from "@zuplo/runtime";
 *
 * export async function cacheStreamingResponse(
 *   request: ZuploRequest,
 *   context: ZuploContext
 * ) {
 *   const cache = new StreamingZoneCache("stream-cache", context);
 *   const cacheKey = `api-response-${request.url}`;
 *
 *   // Check cache first
 *   const cachedStream = await cache.get(cacheKey);
 *   if (cachedStream) {
 *     return new Response(cachedStream, {
 *       headers: { "X-Cache": "HIT" }
 *     });
 *   }
 *
 *   // Fetch fresh data
 *   const response = await fetch("https://api.example.com/large-file");
 *
 *   // Clone the response so we can cache and return it
 *   const [cacheStream, returnStream] = response.body!.tee();
 *
 *   // Cache for 5 minutes
 *   await cache.put(cacheKey, cacheStream, 300);
 *
 *   return new Response(returnStream, {
 *     headers: { "X-Cache": "MISS" }
 *   });
 * }
 * ```
 */
export declare class StreamingZoneCache {
  #private;
  /**
   * Construct a new StreamingZoneCache with a ZuploContext.
   * This will log debug messages using the provided context.
   * @param name - The name of the cache
   * @param context - The ZuploContext to use
   */
  constructor(name: string, context: ZuploContext);
  /**
   * Construct a new StreamingZoneCache with CacheOptions.
   * Useful if the system is constructing this behind the scenes.
   * @param name - The name of the cache
   * @param context - The CacheOptions to use
   */
  constructor(name: string, options: CacheOptions);
  /**
   * Retrieve a stream from the cache. If not found or expired, returns undefined.
   * Otherwise, returns the ReadableStream from the cached Response body.
   * @param key - The key to retrieve from the cache
   */
  get(key: string): Promise<ReadableStream<Uint8Array> | undefined>;
  /**
   * Store a stream in the cache for a given TTL (in seconds). We wrap it in a Response
   * with a custom expiry header so we can handle local expiry.
   * @param key - The key to store in the cache
   * @param stream - The stream to store
   * @param ttlSeconds - The time-to-live in seconds
   */
  put(
    key: string,
    stream: ReadableStream<Uint8Array>,
    ttlSeconds: number
  ): Promise<void>;
  /**
   * Remove an entry from the cache if it exists. If there's an error, we try a fallback
   * approach that sets the local expiry to now.
   * @param key - The key to delete from the cache
   */
  delete(key: string): Promise<void>;
  /**
   * In case we can't properly delete from the cache,
   * we overwrite it with an empty, immediately-expired Response.
   * @param key - The key to delete from the cache
   */
  private deleteFallback;
  /**
   * Log internal debug messages to either the ZuploContext logger or the console.
   */
  private logDebug;
}

/**
 * The Stripe Webhook policy validates the authenticity of an incoming Stripe webhook.
 *
 * @title Stripe Webhook Auth
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare class StripeWebhookVerificationInboundPolicy extends InboundPolicy<StripeWebhookVerificationInboundPolicyOptions> {
  static readonly policyType = "stripe-webhook-verification";
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<Response | ZuploRequest<RequestGeneric>>;
}

/**
 * The options for this policy.
 * @public
 */
export declare interface StripeWebhookVerificationInboundPolicyOptions {
  /**
   * The signing secret for the webhook.
   */
  signingSecret: string;
  /**
   * The allowed clock skew in seconds between the time the webhook signature was created and the current time.
   */
  tolerance?: number;
}

declare interface SumoLogicLoggingOptions {
  url: string;
  name?: string;
  category?: string;
  /**
   * Any custom log fields to include in each log entry.
   */
  fields?: CustomLogFields;
}

/**
 * Sumo Logic logging plugin
 * @public
 */
export declare class SumoLogicLoggingPlugin extends LogPlugin {
  private options;
  constructor(options: SumoLogicLoggingOptions);
  /* Excluded from this release type: getTransport */
}

/**
 * The Supabase JWT Authentication policy supports user JWT tokens created
 * by Supabase.
 *
 * @title Supabase JWT Auth
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const SupabaseJwtInboundPolicy: InboundPolicyHandler<SupabaseJwtInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface SupabaseJwtInboundPolicyOptions {
  /**
   * The key used to verify the signature of the JWT token.
   */
  secret: string;
  /**
   * Any claims that must be present for authentication to succeed - multiple valid values can be specified for each claim.
   */
  requiredClaims?: {
    [k: string]: string[];
  };
  /**
   * Indicates whether the request should continue if authentication fails. Default is `false` which means unauthenticated users will automatically receive a 401 response.
   */
  allowUnauthenticatedRequests?: boolean;
  /**
   * Enables OAuth 2.0 Protected Resource Metadata discovery (RFC 9728). When `true`, requests without a bearer token receive a 401 whose `WWW-Authenticate` header points `resource_metadata` at the `/.well-known/oauth-protected-resource` document for the request path and, when the `OAuthProtectedResourcePlugin` declares `scopesSupported`, lists those scopes in `scope`. Requires the `OAuthProtectedResourcePlugin` in `zuplo.runtime.ts` or a user-defined route at that path.
   */
  oAuthResourceMetadataEnabled?: boolean;
}

/* Excluded from this release type: SYSTEM_LOGGER */

/**
 * Base logger interface with methods for each log level.
 * @beta
 */
export declare interface SystemLogger {
  debug(...messages: unknown[]): void;
  info(...messages: unknown[]): void;
  log(...messages: unknown[]): void;
  warn(...messages: unknown[]): void;
  error(...messages: unknown[]): void;
}

/* Excluded from this release type: SystemRouteName */

/**
 * Plugins for registering system capabilities
 * @public
 */
declare abstract class SystemRuntimePlugin extends RuntimePlugin {
  /* Excluded from this release type: initialize */
  /* Excluded from this release type: registerRoutes */
}

/* Excluded from this release type: TelemetryInitializationOptions */

/**
 * Base class for determining type of plugin
 * @public
 */
export declare abstract class TelemetryPlugin extends RuntimePlugin {
  /* Excluded from this release type: instrument */
}

declare interface ToolChoice {
  type: "function";
  function: {
    name: string;
  };
}

declare interface ToolDefinition {
  type: "function";
  function: FunctionDefinition;
}

/* Excluded from this release type: trackFeature */

/**
 * Splits traffic randomly across a set of weighted base paths. On each request
 * one base path is selected (weighted by `weight`) and written to the request
 * custom context at `customOutputProperty`. Reference it from a later URL
 * Rewrite `rewritePattern` or URL Forward `baseUrl`, e.g.
 * `${context.custom.trafficSplitting.basePath}`.
 *
 * @title Traffic Splitting
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const TrafficSplittingInboundPolicy: InboundPolicyHandler<TrafficSplittingInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface TrafficSplittingInboundPolicyOptions {
  /**
   * The set of base paths (URLs) to split traffic across. One entry is selected at random per request, weighted by its `weight`.
   */
  basePaths: {
    /**
     * The base path (URL) to route to when this entry is selected. Supports environment variables, e.g. `$env(BASE_URL)/v2`.
     */
    url: string;
    /**
     * The relative weight for this base path. Higher weights receive proportionally more traffic. Weights are relative and do not need to add up to 100.
     */
    weight: number;
  }[];
  /**
   * A simple dotted property path under the request custom context where the selected URL is written (e.g. `trafficSplitting.basePath`). Reference it later in a URL Rewrite `rewritePattern` or URL Forward `baseUrl` as `${context.custom.trafficSplitting.basePath}`. Only one value is in effect; if multiple Traffic Splitting policies write the same property, the last one to run wins. Array indexes and brackets are not allowed.
   */
  customOutputProperty: string;
  /**
   * When `true`, logs which base path was selected for each request. Defaults to `false`.
   */
  logSelection?: boolean;
}

/**
 *
 * @export
 * @interface TupleKey
 */
declare interface TupleKey {
  /**
   *
   * @type {string}
   * @memberof TupleKey
   */
  user: string;
  /**
   *
   * @type {string}
   * @memberof TupleKey
   */
  relation: string;
  /**
   *
   * @type {string}
   * @memberof TupleKey
   */
  object: string;
  /**
   *
   * @type {RelationshipCondition}
   * @memberof TupleKey
   */
  condition?: RelationshipCondition;
}

/**
 * No authentication.
 * @public
 */
declare interface UnauthenticatedCredentialConfig {
  /**
   * The type of authentication to use.
   */
  method: "none";
}

/**
 * Resolves AWS credentials with STS AssumeRoleWithWebIdentity using Zuplo's
 * ambient OIDC identity — no AWS keys are stored anywhere. The role's trust
 * policy must trust the Zuplo OIDC identity provider. Resolved credentials are
 * registered on the request context for the AWS Lambda handler and custom code
 * to sign upstream requests with {@link AwsClient.fromContext}. This policy does
 * not itself sign or forward the request.
 *
 * @title Upstream AWS Federated Auth
 * @product api-gateway
 * @beta
 * @enterprise
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare class UpstreamAwsFederatedAuthInboundPolicy extends InboundPolicy<UpstreamAwsFederatedAuthInboundPolicyOptions> {
  #private;
  static readonly policyType = "upstream-aws-federated-auth";
  constructor(
    options: UpstreamAwsFederatedAuthInboundPolicyOptions,
    policyName: string
  );
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
}

/**
 * The options for this policy.
 * @public
 */
export declare interface UpstreamAwsFederatedAuthInboundPolicyOptions {
  /**
   * The IAM role to assume with STS AssumeRoleWithWebIdentity. The role's trust policy must trust the Zuplo OIDC identity provider.
   */
  roleArn: string;
  /**
   * The AWS region used for the STS endpoint and as the default signing region for consumers of the resolved credentials.
   */
  region: string;
  /**
   * The audience ('aud' claim) of the Zuplo-issued OIDC token. Must match a client ID configured on the IAM OIDC identity provider.
   */
  audience?: string;
  /**
   * The STS role session name recorded in AWS CloudTrail. Must match the pattern [\w+=,.@-]{2,64}.
   */
  roleSessionName?: string;
  /**
   * The lifetime in seconds of the temporary credentials requested from STS (900-43200). The assumed role's maximum session duration may further limit this value.
   */
  durationSeconds?: number;
  /**
   * Overrides the STS endpoint URL. Only needed for non-standard partitions such as AWS GovCloud or AWS China.
   */
  stsEndpoint?: string;
  /**
   * The number of times to retry fetching temporary credentials in the event of a failure.
   */
  tokenRetries?: number;
  /**
   * The number of seconds before credential expiration at which cached credentials are discarded and refreshed.
   */
  expirationOffsetSeconds?: number;
}

/**
 * Resolves AWS credentials from static access keys (optionally exchanged for an
 * IAM role's temporary credentials via STS AssumeRole) and registers them on
 * the request context. The AWS Lambda handler and custom code read them with
 * {@link AwsClient.fromContext} to sign upstream requests. This policy does not
 * itself sign or forward the request.
 *
 * @title Upstream AWS Service Auth
 * @product api-gateway
 * @beta
 * @enterprise
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare class UpstreamAwsServiceAuthInboundPolicy extends InboundPolicy<UpstreamAwsServiceAuthInboundPolicyOptions> {
  #private;
  static readonly policyType = "upstream-aws-service-auth";
  constructor(
    options: UpstreamAwsServiceAuthInboundPolicyOptions,
    policyName: string
  );
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
}

/**
 * The options for this policy.
 * @public
 */
export declare interface UpstreamAwsServiceAuthInboundPolicyOptions {
  /**
   * The AWS access key ID. Store the value in an environment variable rather than in source.
   */
  accessKeyId: string;
  /**
   * The AWS secret access key. Always store this in an environment variable.
   */
  secretAccessKey: string;
  /**
   * The AWS region. Used for the STS endpoint when 'roleArn' is set, and as the default signing region for consumers of the resolved credentials.
   */
  region: string;
  /**
   * The AWS session token, required only when the configured access key pair is itself a temporary credential.
   */
  sessionToken?: string;
  /**
   * An IAM role to assume using STS AssumeRole with the configured access keys. When set, the resolved credentials are the role's temporary credentials instead of the static keys.
   */
  roleArn?: string;
  /**
   * The external ID to pass to STS AssumeRole when the role's trust policy requires one.
   */
  externalId?: string;
  /**
   * The STS role session name recorded in AWS CloudTrail. Must match the pattern [\w+=,.@-]{2,64}.
   */
  roleSessionName?: string;
  /**
   * The lifetime in seconds of the temporary credentials requested from STS (900-43200). The assumed role's maximum session duration may further limit this value.
   */
  durationSeconds?: number;
  /**
   * Overrides the STS endpoint URL. Only needed for non-standard partitions such as AWS GovCloud or AWS China.
   */
  stsEndpoint?: string;
  /**
   * The number of times to retry fetching temporary credentials in the event of a failure.
   */
  tokenRetries?: number;
  /**
   * The number of seconds before credential expiration at which cached credentials are discarded and refreshed.
   */
  expirationOffsetSeconds?: number;
}

/**
 * Uses Azure Active Directory to add an Authorization header to the request
 * in order to authenticate requests using Azure identity.
 *
 * @title Upstream Azure AD Service Auth
 * @product api-gateway
 * @public
 * @enterprise
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const UpstreamAzureAdServiceAuthInboundPolicy: InboundPolicyHandler<UpstreamAzureAdServiceAuthInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface UpstreamAzureAdServiceAuthInboundPolicyOptions {
  /**
   * Azure Active Directory Tenant ID.
   */
  activeDirectoryTenantId: string;
  /**
   * The Application (client) ID of the Azure AD App Registration.
   */
  activeDirectoryClientId: string;
  /**
   * The client secret of the Azure AD App Registration.
   */
  activeDirectoryClientSecret: string;
  /**
   * The number of times to retry fetching the token in the event of a failure.
   */
  tokenRetries?: number;
  /**
   * The number of seconds less than the token expiration to cache the token.
   */
  expirationOffsetSeconds?: number;
}

/**
 * Creates a Firebase Admin token and attaches it to the outgoing request.
 * Useful when calling Firebase services as an administrator.
 *
 * @title Upstream Firebase Admin Auth
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const UpstreamFirebaseAdminAuthInboundPolicy: InboundPolicyHandler<UpstreamFirebaseAdminAuthInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface UpstreamFirebaseAdminAuthInboundPolicyOptions {
  /**
   * The Google Service Account key in JSON format. Note you can load this from environment variables using the $env(ENV_VAR) syntax.
   */
  serviceAccountJson: string;
  /**
   * The number of times to retry fetching the token in the event of a failure.
   */
  tokenRetries?: number;
  /**
   * The number of seconds less than the token expiration to cache the token.
   */
  expirationOffsetSeconds?: number;
}

/**
 * Creates a Firebase custom user token and attaches it to the outgoing
 * request. Useful when calling Firebase services as user.
 *
 * @title Upstream Firebase User Auth
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const UpstreamFirebaseUserAuthInboundPolicy: InboundPolicyHandler<UpstreamFirebaseUserAuthInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface UpstreamFirebaseUserAuthInboundPolicyOptions {
  /**
   * The Google Service Account key in JSON format. Note you can load this from environment variables using the $env(ENV_VAR) syntax.
   */
  serviceAccountJson: string;
  /**
   * The userId to use as the custom token's subject.
   */
  userId?: string;
  /**
   * The property on the incoming request.user object to retrieve the value of the userId.
   */
  userIdPropertyPath?: string;
  /**
   * The Firebase Web API Key (found in project settings)
   * @see {@link https://firebase.google.com/docs/projects/api-keys|Firebase API Keys}.
   */
  webApiKey: string;
  /**
   * Additional claims to include in the custom token's payload.
   */
  developerClaims?: Record<string, string | number | boolean | null>;
  /**
   * The number of times to retry fetching the token in the event of a failure.
   */
  tokenRetries?: number;
  /**
   * The number of seconds less than the token expiration to cache the token.
   */
  expirationOffsetSeconds?: number;
}

/**
 * Authenticates with GCP resources or Google services using Workload Identity
 * Federation allowing secure access to these resources without requiring the
 * use of a service account private key.
 *
 * @title Upstream GCP Federated Auth
 * @product api-gateway
 * @public
 * @enterprise
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare class UpstreamGcpFederatedAuthInboundPolicy extends InboundPolicy<UpstreamGcpFederatedAuthInboundPolicyOptions> {
  static readonly policyType = "upstream-gcp-federated-auth";
  private cacheName;
  private normalizedWorkloadIdentityProvider;
  constructor(
    options: UpstreamGcpFederatedAuthInboundPolicyOptions,
    policyName: string
  );
  /**
   * The handler that is called each time this policy is invoked
   *
   * @param request - The incoming Request
   * @param context - The current context of the Request
   * @returns A Response or Request object
   */
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
}

/**
 * The options for this policy.
 * @public
 */
export declare interface UpstreamGcpFederatedAuthInboundPolicyOptions {
  /**
   * The audience for the minted JWT. This is typically the URL of your service. See the document {@link https://cloud.google.com/endpoints/docs/grpc-service-config/reference/rpc/google.api#google.api.AuthRequirement|AuthRequirement} for details.
   */
  audience: string;
  /**
   * The Google Service Account email address.
   */
  serviceAccountEmail: string;
  workloadIdentityProvider: string;
  /**
   * The lifetime in seconds of the issued token.
   */
  tokenLifetime?: number;
  /**
   * The number of times to retry fetching the token in the event of a failure.
   */
  tokenRetries?: number;
  /**
   * The number of seconds less than the token expiration to cache the token.
   */
  expirationOffsetSeconds?: number;
  /**
   * This is an advanced option that should only be used if you do not want to persist information in ZoneCache.
   */
  useMemoryCacheOnly?: boolean;
}

/**
 * Creates a self-signed JWT token (generated using a Google Service Account
 * JSON) and attaches it to the outgoing request. Useful when calling GCP
 * services like Cloud Endpoints / ESPv2
 *
 * @title Upstream GCP Self-Signed JWT
 * @product api-gateway
 * @public
 * @enterprise
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const UpstreamGcpJwtInboundPolicy: InboundPolicyHandler<UpstreamGcpJwtInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface UpstreamGcpJwtInboundPolicyOptions {
  /**
   * The audience for the minted JWT. See the document {@link https://cloud.google.com/endpoints/docs/grpc-service-config/reference/rpc/google.api#google.api.AuthRequirement|AuthRequirement} for details.
   */
  audience: string;
  /**
   * The Google Service Account key in JSON format. Note you can load this from environment variables using the $env(ENV_VAR) syntax.
   */
  serviceAccountJson: string;
}

/**
 * Creates an ID Token from Google's OAuth service and attaches it to the
 * outgoing request. Useful when calling GCP services or Google APIs that are
 * secured with GCP IAM.
 *
 * @title Upstream GCP Service Auth
 * @product api-gateway
 * @public
 * @enterprise
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const UpstreamGcpServiceAuthInboundPolicy: InboundPolicyHandler<UpstreamGcpServiceAuthInboundPolicyOptions>;

/**
 * The options for this policy.
 * @public
 */
export declare interface UpstreamGcpServiceAuthInboundPolicyOptions {
  /**
   * The audience for the service to be called. This is typically the URL of your service endpoint like 'https://my-backend-api-a1b2c3d4e5-uc.a.run.app'. If calling a Google API, leave this empty.
   */
  audience?: string;
  /**
   * The scopes to grant the access token. See {@link https://developers.google.com/identity/protocols/oauth2/scopes|documentation} for details. This is only set with calling a Google API. If calling a service like Cloud Run, etc. leave this empty.
   */
  scopes?: string[];
  /**
   * The Google Service Account key in JSON format. Note you can load this from environment variables using the `$env(ENV_VAR)` syntax.
   * @see {@link https://developers.google.com/workspace/guides/create-credentials|Create access credentials}.
   */
  serviceAccountJson: string;
  /**
   * The number of times to retry fetching the token in the event of a failure.
   */
  tokenRetries?: number;
  /**
   * The number of seconds less than the token expiration to cache the token.
   */
  expirationOffsetSeconds?: number;
  /**
   * This is an advanced option that should only be used if you do not want to persist information in ZoneCache.
   */
  useMemoryCacheOnly?: boolean;
  /**
   * The version of the policy.
   */
  version?: 1 | 2;
  /**
   * When `true` (the default), emits a warning if the inbound request carries headers like `X-Serverless-Authorization` or `X-Goog-IAP-JWT-Assertion`. Forwarding those to a downstream Cloud Run typically causes a `the access token could not be verified` 401 because Cloud Run prefers `X-Serverless-Authorization` over `Authorization` for IAM checks. Set this to `false` only if you have intentionally chosen to forward those headers (e.g. the upstream service is also IAP-fronted and expects them) — the warning is otherwise a useful diagnostic signal.
   */
  enableSuspiciousHeaderWarning?: boolean;
}

/**
 * Fetches an access token from any OAuth 2.0 token endpoint using the client
 * credentials grant and adds it to a header (`Authorization` by default) on
 * the upstream request. Tokens are cached until shortly before they expire.
 *
 * @title Upstream OAuth 2.0 Client Credentials Auth
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare class UpstreamOAuthClientCredentialsInboundPolicy extends InboundPolicy<UpstreamOAuthClientCredentialsInboundPolicyOptions> {
  #private;
  static readonly policyType = "upstream-oauth-client-credentials";
  constructor(
    options: UpstreamOAuthClientCredentialsInboundPolicyOptions,
    policyName: string
  );
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
}

/**
 * The options for this policy.
 * @public
 */
export declare interface UpstreamOAuthClientCredentialsInboundPolicyOptions {
  /**
   * The URL of the OAuth 2.0 token endpoint that issues the access token.
   */
  tokenUrl: string;
  /**
   * The client ID used to authenticate with the token endpoint.
   */
  clientId: string;
  /**
   * The client secret used to authenticate with the token endpoint.
   */
  clientSecret: string;
  /**
   * Space-delimited list of scopes to request. When not set, the `scope` parameter is omitted from the token request.
   */
  scope?: string;
  /**
   * The value of the `audience` form parameter sent to the token endpoint. Required by some identity providers such as Auth0. When not set, the parameter is omitted from the token request.
   */
  audience?: string;
  credentialsIn?: OAuthClientCredentialsLocation;
  /**
   * Additional form parameters to include in the token request, for example `resource` for identity providers that require it.
   */
  additionalParameters?: {
    [k: string]: string;
  };
  /**
   * The name of the header on the upstream request that the access token is set on.
   */
  headerName?: string;
  /**
   * The scheme that prefixes the access token in the header. When the token response includes a `token_type`, that value is used instead.
   */
  headerScheme?: string;
  /**
   * The number of times to retry fetching the token in the event of a failure.
   */
  tokenRetries?: number;
  /**
   * The number of seconds less than the token expiration to cache the token.
   */
  expirationOffsetSeconds?: number;
}

/**
 * Generates a Zuplo JWT token and attaches it to the outgoing request. This
 * policy creates a self-signed JWT using the Zuplo JWT plugin and adds it
 * to the specified header for upstream authentication.
 *
 * @title Upstream Zuplo JWT
 * @product api-gateway
 * @enterprise
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A ZuploRequest
 */
export declare class UpstreamZuploJwtAuthInboundPolicy extends InboundPolicy<UpstreamZuploJwtAuthInboundPolicyOptions> {
  static readonly policyType = "upstream-zuplo-jwt";
  constructor(
    options: UpstreamZuploJwtAuthInboundPolicyOptions,
    policyName: string
  );
  /**
   * The handler that is called each time this policy is invoked
   *
   * @param request - The incoming Request
   * @param context - The current context of the Request
   * @returns A Response or Request object
   */
  handler(
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<ZuploRequest | Response>;
}

/**
 * The options for the Upstream Zuplo JWT Auth Inbound policy.
 * @public
 */
export declare interface UpstreamZuploJwtAuthInboundPolicyOptions {
  /**
   * The audience claim for the JWT.
   */
  audience?: string;
  /**
   * JWT expiration time. Can be a number (seconds) or a string with units (e.g., '5m' for 5 minutes, '1h' for 1 hour, '7d' for 7 days). Defaults to 300 seconds (5 minutes).
   */
  expiresIn?: number | string;
  /**
   * The subject ('sub') claim for the minted JWT. Identifies the acting subject of the token (typically the gateway itself).
   */
  subject?: string;
  /**
   * Maps claims in the minted JWT to values from the authenticated user (request.user). Each key is the claim name to set; each value is a light JSON-path selector into request.user using dot or bracket notation (e.g. 'sub', 'data.role', or 'data["https://example.com/claim"]' for keys containing dots or slashes). When set, the policy requires an authenticated user and returns 401 if request.user is absent — it never mints a token with missing identity.
   */
  claimsFromUser?: {
    [k: string]: string;
  };
  /**
   * The header name where the JWT will be attached. Defaults to 'Authorization'.
   */
  headerName?: string;
  /**
   * The prefix to use before the JWT token. Defaults to 'Bearer'. Set to an empty string to send the token without a prefix.
   */
  tokenPrefix?: string;
  /**
   * Additional claims to include in the JWT. These will be merged with the default claims.
   */
  additionalClaims?: {
    [k: string]: unknown;
  };
}

declare interface UrlConfig {
  defaultUrl: string;
  urls: string[];
}

/**
 * Handler that forwards requests to a different base URL while preserving the path.
 * Ideal for proxying requests to backend services or creating API gateways.
 *
 * @param request - The incoming ZuploRequest
 * @param context - The ZuploContext
 * @returns A Response from the forwarded URL
 *
 * @public
 * @example
 * ```json
 * // routes.oas.json - Forward all /api/* requests to backend
 * {
 *   "paths": {
 *     "/api/{path}*": {
 *       "x-zuplo-route": {
 *         "handler": {
 *           "export": "urlForwardHandler",
 *           "module": "$import(@zuplo/runtime)",
 *           "options": {
 *             "baseUrl": "https://backend.example.com",
 *             "forwardSearch": true
 *           }
 *         }
 *       }
 *     }
 *   }
 * }
 * ```
 *
 * @example
 * ```json
 * // Forward with dynamic base URL based on environment
 * {
 *   "handler": {
 *     "export": "urlForwardHandler",
 *     "module": "$import(@zuplo/runtime)",
 *     "options": {
 *       "baseUrl": "$env(BACKEND_URL)",
 *       "forwardSearch": false,
 *       "followRedirects": true
 *     }
 *   }
 * }
 * ```
 *
 * @example
 * ```json
 * // Forward with mTLS client certificate
 * {
 *   "handler": {
 *     "export": "urlForwardHandler",
 *     "module": "$import(@zuplo/runtime)",
 *     "options": {
 *       "baseUrl": "https://secure-backend.example.com",
 *       "mtlsCertificate": "my-client-cert"
 *     }
 *   }
 * }
 * ```
 *
 * @example
 * ```json
 * // Abort the request with a 504 if the upstream takes longer than 30 seconds
 * {
 *   "handler": {
 *     "export": "urlForwardHandler",
 *     "module": "$import(@zuplo/runtime)",
 *     "options": {
 *       "baseUrl": "https://backend.example.com",
 *       "requestTimeoutSeconds": 30
 *     }
 *   }
 * }
 * ```
 */
export declare function urlForwardHandler(
  request: ZuploRequest,
  context: ZuploContext
): Promise<Response>;

/**
 * Handler that rewrites the request URL based on a pattern.
 * Useful for routing requests to different backends based on path parameters,
 * query strings, or other request properties.
 *
 * @param request - The incoming ZuploRequest
 * @param context - The ZuploContext
 * @returns A Response from the rewritten URL
 *
 * @public
 * @example
 * ```json
 * // routes.oas.json - Route to different API versions
 * {
 *   "paths": {
 *     "/api/{version}/users/{id}": {
 *       "x-zuplo-route": {
 *         "handler": {
 *           "export": "urlRewriteHandler",
 *           "module": "$import(@zuplo/runtime)",
 *           "options": {
 *             "rewritePattern": "https://api-${params.version}.example.com/users/${params.id}",
 *             "forwardSearch": true
 *           }
 *         }
 *       }
 *     }
 *   }
 * }
 * ```
 *
 * @example
 * ```json
 * // Route to backend service with custom headers
 * {
 *   "handler": {
 *     "export": "urlRewriteHandler",
 *     "module": "$import(@zuplo/runtime)",
 *     "options": {
 *       "rewritePattern": "https://backend.internal/api${url.pathname}",
 *       "forwardSearch": false,
 *       "followRedirects": true
 *     }
 *   }
 * }
 * ```
 *
 * @example
 * ```json
 * // Route with mTLS client certificate
 * {
 *   "handler": {
 *     "export": "urlRewriteHandler",
 *     "module": "$import(@zuplo/runtime)",
 *     "options": {
 *       "rewritePattern": "https://secure-api.example.com/api/${params.version}",
 *       "mtlsCertificate": "my-client-cert"
 *     }
 *   }
 * }
 * ```
 *
 * @example
 * ```json
 * // Abort the request with a 504 if the upstream takes longer than 30 seconds
 * {
 *   "handler": {
 *     "export": "urlRewriteHandler",
 *     "module": "$import(@zuplo/runtime)",
 *     "options": {
 *       "rewritePattern": "https://backend.internal/api${url.pathname}",
 *       "requestTimeoutSeconds": 30
 *     }
 *   }
 * }
 * ```
 */
export declare function urlRewriteHandler(
  request: ZuploRequest,
  context: ZuploContext
): Promise<Response>;

declare interface Usage {
  prompt_tokens: number;
  completion_tokens: number;
  total_tokens: number;
  prompt_tokens_details?: {
    cached_tokens?: number;
    cache_write_tokens?: number;
    audio_tokens?: number;
  };
  completion_tokens_details?: {
    reasoning_tokens?: number;
    audio_tokens?: number;
    accepted_prediction_tokens?: number;
    rejected_prediction_tokens?: number;
  };
  /**
   * A cost in USD the upstream reported for this request, exactly as it
   * reported it.
   *
   * Not an OpenAI field. It is present because aggregators that price requests
   * themselves — OpenRouter is the case it exists for — report it here, and
   * metering reads it as the authoritative cost. First-party providers never
   * set it.
   *
   * Declared on this type so a TRANSLATED response can carry it: the Anthropic
   * path rebuilds `usage` from token counts, which silently dropped a reported
   * cost and billed the request from the rate card instead.
   *
   * `unknown` because it is untrusted upstream input that translation carries
   * without validating. Metering validates it with `readProviderReportedCost`,
   * which logs a malformed value as rejected and bills from the rate card.
   */
  cost?: unknown;
}

declare type UserDataDefault = any;

/**
 * Validates the body of an incoming request based on a JSON schema.
 *
 * @title JSON Body Validation
 * @product api-gateway
 * @public
 * @deprecated Use the new {@link https://zuplo.com/docs/policies/request-validation-inbound|Request Validation Policy}.
 * The new policy validates JSON bodies like this policy, but also supports validation of parameters, query strings, etc.
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const ValidateJsonSchemaInbound: InboundPolicyHandler<ValidateJsonSchemaInboundInternalOptions>;

/**
 * @beta
 */
declare interface ValidateJsonSchemaInboundInternalOptions extends Omit<
  ValidateJsonSchemaInboundOptions,
  "validator"
> {
  /* Excluded from this release type: validator */
}

/**
 * The options for this policy.
 * @public
 */
export declare interface ValidateJsonSchemaInboundOptions {
  /**
   * The JSON schema to validate against.
   */
  validator: string;
}

/**
 * The action to perform when validation fails.
 * @public
 */
declare type ValidationOptions =
  | "none"
  | "log-only"
  | "reject-and-log"
  | "reject-only";

/**
 * The action to perform when validation fails.
 * @public
 */
declare type ValidationOptions1 =
  | "none"
  | "log-only"
  | "reject-and-log"
  | "reject-only";

/**
 * The action to perform when validation fails.
 * @public
 */
declare type ValidationOptions2 =
  | "none"
  | "log-only"
  | "reject-and-log"
  | "reject-only";

/**
 * The action to perform when validation fails.
 * @public
 */
declare type ValidationOptions3 =
  | "none"
  | "log-only"
  | "reject-and-log"
  | "reject-only";

declare interface VMWareLogInsightLoggingOptions {
  url: string;
  /**
   * An array of string tuples to replace within the text field of a log entry.
   * @example
   * ```
   * [
   *  ["'", ""],
   *  ['"', ""],
   *  ["\\n", ""],
   *  ["\\", ""],
   *  ["*", ""],
   *  ["&", ""],
   *  [":", "="],
   * ]
   * ```
   */
  textReplacements?: [string, string][];
  /**
   * The unique agent identifier of the logger.
   */
  agentId?: string;
  /**
   * Any custom log fields to include in each log entry.
   */
  fields?: CustomLogFields;
  onMessageSending?: (event: LogInsightLogEntry) => LogInsightLogEntry;
}

/**
 * VMware Log Insight logging plugin
 * @public
 */
export declare class VMWareLogInsightLoggingPlugin extends LogPlugin {
  private options;
  constructor(options: VMWareLogInsightLoggingOptions);
  /* Excluded from this release type: getTransport */
}

/**
 * @public
 */
declare interface WaitUntilFunc {
  (promise: Promise<any>): void;
}

declare interface WarningSettings {
  enabled: boolean;
  /**
   * Percentage of the limit at which to emit a warning event.
   */
  threshold?: number;
}

/**
 * Authenticate bots using web-bot-auth HTTP Message Signatures.
 *
 * @title Web Bot Auth
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare const WebBotAuthInboundPolicy: InboundPolicyHandler<WebBotAuthInboundPolicyOptions>;

/**
 * Options for the Web Bot Auth Inbound Policy.
 * @public
 */
export declare interface WebBotAuthInboundPolicyOptions {
  /**
   * List of bot identifiers that are allowed to access the API.
   */
  allowedBots: string[];
  /**
   * Whether to block bots that aren't in the allowed list.
   */
  blockUnknownBots: boolean;
  /**
   * Allow requests without bot signatures to proceed. This is useful if you want to use multiple authentication policies or if you want to allow both authenticated and non-authenticated traffic.
   */
  allowUnauthenticatedRequests?: boolean;
  /**
   * Optional URL to a directory of known bots (for verification).
   */
  directoryUrl?: string;
}

/**
 * Web search tool (preview version)
 */
declare interface WebSearchPreviewTool {
  type: "web_search_preview" | "web_search_preview_2025_03_11";
  search_context_size?: "low" | "medium" | "high";
  user_location?: {
    type: "approximate";
    city?: string | null;
    country?: string | null;
    region?: string | null;
    timezone?: string | null;
  } | null;
}

/**
 * Web search tool (stable version)
 */
declare interface WebSearchTool {
  type: "web_search" | "web_search_2025_08_26";
  filters?: {
    allowed_domains?: string[] | null;
  } | null;
  search_context_size?: "low" | "medium" | "high";
  user_location?: {
    city?: string | null;
    country?: string | null;
    region?: string | null;
    timezone?: string | null;
  } | null;
}

/**
 * Proxies WebSocket connections to an upstream URL.
 *
 * @deprecated Use {@link webSocketPipelineHandler} instead. `webSocketHandler`
 * is retained as a backwards-compatible alias and resolves to the exact same
 * handler — with no inbound/outbound message policies configured it is a
 * transparent passthrough, so existing routes keep working unchanged. Because
 * it is the same function, routes using this name report
 * `zuplo.handler.type = "websocket-pipeline"`.
 * @public
 */
export declare const webSocketHandler: typeof webSocketPipelineHandler;

/**
 * A WebSocket connection-level hook, invoked once when the connection opens.
 *
 * Mirrors {@link WebSocketPolicyFunction} without the per-message `data`
 * argument. It runs after both the client and upstream legs are established and
 * before any frame is relayed. Throwing (or returning a rejected promise)
 * aborts the connection: both sockets are closed and no `101 Switching
 * Protocols` response is returned to the caller.
 *
 * @param target - The upstream socket (gateway to origin).
 * @param source - The client-facing socket (gateway to caller).
 * @param request - The {@link ZuploRequest} that initiated the upgrade.
 * @param context - The {@link ZuploContext}.
 *
 * @remarks
 * Configuring `onOpen` opts the connection out of the zero-overhead Cloudflare
 * passthrough splice: the worker stays in the data path so the hook has both
 * live sockets to act on. If you need connection-level `close`/`error`/`message`
 * handling, attach your own listeners to either socket from within the hook.
 *
 * @public
 */
export declare type WebSocketOnOpenHook = (
  target: WebSocket,
  source: WebSocket,
  request: ZuploRequest,
  context: ZuploContext
) => void | Promise<void>;

/**
 * Handle WebSocket requests by proxying them to a different URL, optionally
 * running inbound/outbound message policies and/or a connection-level `onOpen`
 * hook.
 *
 * When no intercept policies are configured the handler behaves like the plain
 * `webSocketHandler`: messages are forwarded verbatim and, on Cloudflare,
 * the upstream socket is spliced directly to the client so the worker stays out
 * of the per-message data path. The worker only sits in the message path (and
 * policies are only wired up) when at least one inbound or outbound policy is
 * configured.
 *
 * The optional `onOpen` hook (see {@link WebSocketOnOpenHook}) runs once after
 * both legs are established and before any frame is relayed. Because it needs
 * both live sockets, configuring it keeps the worker in the data path (the
 * Cloudflare splice is skipped). Throwing from the hook aborts the connection.
 *
 * @example
 * A route that runs an `onOpen` hook and an inbound message policy. `onOpen`
 * is declared at the `options` level, a sibling of `policies`:
 * ```json
 * {
 *   "handler": {
 *     "export": "webSocketPipelineHandler",
 *     "module": "$import(@zuplo/runtime)",
 *     "options": {
 *       "rewritePattern": "https://example.com/socket",
 *       "onOpen": {
 *         "export": "onWebSocketOpen",
 *         "module": "$import(./modules/ws-onopen)"
 *       },
 *       "policies": {
 *         "inbound": [
 *           { "export": "authFrame", "module": "$import(./modules/ws-auth)" }
 *         ]
 *       }
 *     }
 *   }
 * }
 * ```
 *
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @returns A WebSocket upgrade Response (101 Switching Protocols)
 * @public
 */
export declare function webSocketPipelineHandler(
  request: ZuploRequest,
  context: ZuploContext
): Promise<Response>;

/**
 * The request to the PDP
 */
declare interface XacmlRequest {
  Request: {
    ReturnPolicyIdList?: boolean;
    CombinedDecision?: boolean;
    XPathVersion?: string;
    Category?: Omit<Category, "CategoryId"> &
      {
        CategoryId: string;
      }[];
    Resource?: Category[];
    Action?: Category[];
    Environment?: Category[];
    AccessSubject?: Category[];
    RecipientSubject?: Category[];
    IntermediarySubject?: Category[];
    RequestingMachine?: Category[];
    CodeBase?: Category[];
    MultiRequests?: MultiRequests;
  };
}

/**
 * Parses XML and converts it to JSON.
 *
 * @title XML to JSON
 * @product api-gateway
 * @public
 * @param request - The ZuploRequest
 * @param context - The ZuploContext
 * @param options - The policy options set in policies.json
 * @param policyName - The name of the policy as set in policies.json
 * @returns A Request or a Response
 */
export declare class XmlToJsonOutboundPolicy extends OutboundPolicy<XmlToJsonPolicyOptions> {
  static readonly policyType = "xml-to-json";
  private parser;
  private parseOnStatusCodes;
  constructor(options: XmlToJsonPolicyOptions, policyName: string);
  handler(
    response: Response,
    request: ZuploRequest,
    context: ZuploContext
  ): Promise<Response>;
}

/**
 * The options for this policy.
 * @public
 */
export declare interface XmlToJsonPolicyOptions {
  /**
   * Remove namespace string from tag and attribute names.
   */
  removeNSPrefix?: boolean;
  /**
   * Ignore processing instruction tags. i.e. `<?elementnames <fred>, <bert>, <harry> ?>`.
   */
  ignoreProcessingInstructions?: boolean;
  /**
   * Ignore declarations. i.e. `<?xml version="1.0"?>`.
   */
  ignoreDeclarations?: boolean;
  /**
   * Ignore tag attributes.
   */
  ignoreAttributes?: boolean;
  /**
   * Remove surrounding whitespace from tag or attribute value.
   */
  trimValues?: boolean;
  /**
   * At particular point, if you don't want to parse a tag and it's nested tags then you can set their path in stopNodes. You can also set tags which should not be processed irrespective of their path using * as the wildcard.
   */
  stopNodes?: string[];
  /**
   * The prefix of attribute names in the resulting JS object.
   */
  attributeNamePrefix?: string;
  /**
   * Text value of a tag is parsed to #text property by default.
   */
  textNodeName?: string;
  /**
   * A list of status codes and ranges "200-299, 304" that should the XML parser should run on. If not set, the parser will run on all status codes.
   */
  parseOnStatusCodes?: string | number[];
}

/**
 * A high-performance cache that stores data in the same data center (zone).
 * Uses the underlying HTTP cache API to store JSON-serializable objects by string keys.
 * Data is not replicated across zones, making it ideal for zone-local caching scenarios.
 *
 * @public
 * @example
 * ```typescript
 * import { ZoneCache, ZuploContext } from "@zuplo/runtime";
 *
 * export async function myHandler(request: ZuploRequest, context: ZuploContext) {
 *   const cache = new ZoneCache<ProductData>("product-cache", context);
 *
 *   // Store product data for 10 minutes
 *   await cache.put("product-123", {
 *     id: "123",
 *     name: "Widget",
 *     price: 99.99
 *   }, 600);
 *
 *   // Retrieve cached data
 *   const product = await cache.get("product-123");
 *   if (product) {
 *     return Response.json(product);
 *   }
 *
 *   return new Response("Product not found", { status: 404 });
 * }
 * ```
 */
export declare class ZoneCache<T = any> {
  #private;
  /**
   * Creates a new ZoneCache instance.
   * @param name - A unique name for this cache instance
   * @param context - The ZuploContext from the current request
   */
  constructor(name: string, context: ZuploContext);
  /* Excluded from this release type: __constructor */
  /**
   * Retrieves a value from the zone cache by key.
   * @param key - The cache key to retrieve
   * @returns The cached value or undefined if not found, expired, or on error
   */
  get(key: string): Promise<T | undefined>;
  /**
   * Stores a value in the zone cache with the specified TTL.
   * @param key - The cache key
   * @param data - The value to cache (must be JSON-serializable)
   * @param ttlSeconds - Time to live in seconds
   */
  put(key: string, data: T, ttlSeconds: number): Promise<void>;
  /**
   * Removes a key from the zone cache.
   * @param key - The cache key to delete
   */
  delete(key: string): Promise<void>;
  deleteFallback(key: string): Promise<void>;
  logDebug(...messages: unknown[]): void;
}

declare interface ZuploAnalyticsContext {
  addAnalyticsEvent(
    value: number,
    eventType: EventType,
    metadata: JsonObject,
    unit?: string,
    eventId?: string
  ): void;
  flushAnalyticsEvents(): ZuploAnalyticsEvent[];
  getAnalyticsEvents(): ZuploAnalyticsEvent[];
}

declare interface ZuploAnalyticsEvent<T extends JsonObject = JsonObject> {
  eventId: string;
  requestId: string;
  timestamp: Date;
  accountName: string;
  projectName: string;
  deploymentName: string;
  eventType: EventType;
  metadata: T;
  unit?: string;
  value: number;
}

/**
 * The ZuploContext provides information about the current request and helper methods.
 * @public
 */
export declare interface ZuploContext extends EventTarget {
  /**
   * The unique identifier of this context
   */
  readonly contextId: Readonly<string>;
  /**
   * The unique identifier of the incoming request
   */
  readonly requestId: Readonly<string>;
  /**
   * Request based logger
   */
  readonly log: Readonly<Logger>;
  /**
   * The route that is being processed
   */
  readonly route: Readonly<RouteConfiguration>;
  /**
   * Custom data stored on the ZuploContext
   */
  readonly custom: Record<string, any>;
  readonly incomingRequestProperties: IncomingRequestProperties;
  /**
   * The parent context that spawned this context
   * @beta
   */
  readonly parentContext: ZuploContext | undefined;
  /* Excluded from this release type: analyticsContext */
  readonly invokeInboundPolicy: (
    policyName: string,
    request: ZuploRequest
  ) => Promise<Response | ZuploRequest>;
  readonly invokeOutboundPolicy: (
    policyName: string,
    response: Response,
    request: ZuploRequest
  ) => Promise<Response>;
  /**
   * Invokes a route based on a Request without going back out to HTTP.
   * Can take a relative route path to invoke on the Gateway
   * Example: "/my/route" will invoke http://localhost/my/route on the Gateway
   * without having to rebuild the Request's protocol and host.
   * @beta
   */
  readonly invokeRoute: <TOptions extends RequestGeneric = RequestGeneric>(
    input: string | URL | Request,
    init?: ZuploRequestInit<TOptions>
  ) => Promise<Response>;
  readonly waitUntil: WaitUntilFunc;
  /**
   * Fires just before the response is sent. Response can be modified.
   */
  readonly addResponseSendingHook: (hook: OnResponseSendingHook) => void;
  /**
   * Fires immediately after the response is sent. Response cannot be modified.
   */
  readonly addResponseSendingFinalHook: (
    hook: OnResponseSendingFinalHook
  ) => void;
  /**
   * Registers a pre-request handler: work started immediately that runs
   * concurrently with the remaining inbound policy chain.
   *
   * The runtime checks the handler after each subsequent policy completes and
   * serves its `Response` verdict if one has resolved (skipping the remaining
   * policies, the route handler, and outbound policies). All outstanding
   * handlers are awaited at a barrier just before the route handler dispatches
   * upstream — the only point in the pipeline that blocks on a handler. A
   * response produced by the policy chain itself (for example an
   * authentication policy's 401) is served immediately: already-resolved
   * verdicts from earlier-registered handlers still win, but a pending
   * handler never delays it and is aborted instead.
   *
   * Handlers run out of order relative to the policies they overlap, so they
   * must observe and veto, never transform: do not mutate or consume the live
   * request from a handler. A handler that rejects fails the request closed
   * (500); catch inside the handler and resolve `undefined` to fail open.
   *
   * May only be called during the inbound policy phase.
   * @beta
   */
  readonly addPreRequestHandler: (
    handler: PreRequestHandler,
    options?: {
      name?: string;
    }
  ) => void;
  /**
   * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.
   *
   * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.
   *
   * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.
   *
   * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.
   *
   * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.
   *
   * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.
   *
   * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.
   * @deprecated This will be removed in the future. Use hooks instead. See {@link https://zuplo.com/docs/programmable-api/runtime-extensions}
   */
  addEventListener<Type extends keyof Record<string, Event>>(
    type: Type,
    handler: EventListenerOrEventListenerObject,
    options?: AddEventListenerOptions | boolean
  ): void;
  /**
   * @deprecated This will be removed in the future. See {@link https://zuplo.com/docs/programmable-api/runtime-extensions}
   */
  removeEventListener<Type extends keyof Record<string, Event>>(
    type: Type,
    handler: EventListenerOrEventListenerObject,
    options?: AddEventListenerOptions | boolean
  ): void;
}

/* Excluded from this release type: ZuploEventContext */

/**
 * A helper SDK for MCP module authors to interact with the MCP runtime.
 *
 * Allows access to the original MCP request and setting metadata on the response.
 */
export declare class ZuploMcpSdk {
  private context;
  constructor(context: ZuploContext);
  /**
   * Retrieves the MCP request object from the context.
   * Use this to access metadata like `_meta` from the incoming tool call.
   *
   * @returns The MCP call tool request object or null if not found
   */
  getRawCallToolRequest(): CallToolRequest | null;
  /**
   * Overrides fields of the MCP tool result the gateway is about to send.
   *
   * Every field is independently optional; an absent field keeps the value
   * the gateway derives from the downstream response. The most useful
   * combination is `content` alone: the human-readable summary replaces the
   * raw serialized body while `structuredContent` is still auto-derived from
   * it — one call, compact model context, full data preserved.
   *
   * @example A compact summary for the model, full JSON in structuredContent
   * ```ts
   * const response = await context.invokeRoute("/todos");
   * new ZuploMcpSdk(context).setRawCallToolResult({
   *   content: [{ type: "text", text: "Fetched the todo list" }],
   * });
   * return response;
   * ```
   *
   * Notes:
   *
   * - The stored value is *consumed* when the gateway builds the tool result
   *   (asymmetric with {@link getRawCallToolRequest}, which can be read any
   *   number of times).
   * - The value is written to the context that carried the matching
   *   `tools/call` request, which is looked up exactly one `invokeRoute`
   *   generation up. Calling this from a grandchild invocation (a route that
   *   itself invokes another route) silently stores the override where the
   *   gateway never reads it.
   * - `isError` is deliberately not overridable: it follows the status of the
   *   response your handler returns, so upstream failures cannot be masked.
   * - `structuredContent` must be a JSON object. The MCP 2025-11-25 wire
   *   format rejects arrays and scalars here.
   * - Declining the spec's backwards-compatibility SHOULD (mirroring
   *   serialized JSON into a text block) has a concrete cost: clients that
   *   predate `structuredContent` see only your summary in `content`.
   * - MCP reserves `_meta` keys with the `modelcontextprotocol.io/` prefix
   *   for the protocol itself; use your own prefix for application metadata.
   *
   * @param result - The fields to override on the tool result
   */
  setRawCallToolResult(result: ZuploMcpToolResultOverride): void;
}

/**
 * The subset of a `tools/call` result a module author may override via
 * {@link ZuploMcpSdk.setRawCallToolResult}. Every field is independently
 * optional; an absent field keeps the value the gateway derives from the
 * downstream response.
 */
export declare interface ZuploMcpToolResultOverride {
  /**
   * Content blocks for the model to read. Replaces the gateway's default
   * (the serialized downstream body in a single text block).
   */
  content?: CallToolResult["content"];
  /**
   * The structured form of the tool's output. MUST be a JSON object — the
   * MCP 2025-11-25 wire format rejects arrays/strings/numbers here.
   */
  structuredContent?: Record<string, unknown>;
  /**
   * Per-call metadata. Replaces the gateway's default of `{}`.
   */
  _meta?: Record<string, unknown>;
}

/**
 * Enhanced Request class that extends the standard Web Request API with
 * convenient properties for accessing path parameters, query strings, and user data.
 * This is the request type passed to all handlers and policies in Zuplo.
 *
 * @public
 * @example
 * ```typescript
 * import { ZuploRequest, ZuploContext } from "@zuplo/runtime";
 *
 * export function myHandler(request: ZuploRequest, context: ZuploContext) {
 *   // Access query parameters
 *   const page = request.query.page || "1";
 *   const limit = request.query.limit || "10";
 *
 *   // Access path parameters (e.g., from /users/:userId)
 *   const userId = request.params.userId;
 *
 *   // Access authenticated user
 *   const user = request.user;
 *
 *   // Standard Request properties still available
 *   const contentType = request.headers.get("content-type");
 *   const method = request.method;
 *
 *   return Response.json({
 *     userId,
 *     page,
 *     limit,
 *     authenticated: !!user
 *   });
 * }
 * ```
 *
 * @example
 * ```typescript
 * // Strongly typed request parameters
 * interface MyParams {
 *   userId: string;
 *   orderId: string;
 * }
 *
 * interface MyQuery {
 *   include?: string;
 *   format?: "json" | "xml";
 * }
 *
 * interface MyUserData {
 *   role: "admin" | "user";
 *   tenantId: string;
 * }
 *
 * type MyRequest = ZuploRequest<{
 *   Params: MyParams;
 *   Query: MyQuery;
 *   UserData: MyUserData;
 * }>;
 *
 * export function typedHandler(request: MyRequest, context: ZuploContext) {
 *   // All properties are now strongly typed
 *   const userId = request.params.userId; // string
 *   const format = request.query.format; // "json" | "xml" | undefined
 *   const role = request.user?.data.role; // "admin" | "user" | undefined
 * }
 * ```
 */
export declare class ZuploRequest<
  TOptions extends RequestGeneric = RequestGeneric,
> extends Request {
  #private;
  constructor(
    input: string | URL | Request,
    init?: ZuploRequestInit<TOptions>,
    originalRequest?: Request
  );
  /* Excluded from this release type: originalRequest */
  /**
   * A dictionary of query-string values
   *
   * @example
   * The url `https://example.com?foo=bar` would return
   * the following query object:
   *
   * ```
   * const foo = request.query.foo;
   * ```
   *
   * @readonly
   */
  get query(): Readonly<ResolveRequestQuery<TOptions["Query"]>>;
  /**
   * If you use tokens in your route’s URL, they are
   * automatically parsed into properties on the params
   * property of your request.
   *
   * @example
   * The route `/products/:productId/vendors/:vendorId`
   * would include two params:
   *
   * ```
   * const productId = request.params.productId;
   * const vendorId = request.params.vendorId;
   * ```
   * @readonly
   */
  get params(): Readonly<ResolveRequestParams<TOptions["Params"]>>;
  /**
   * An optional object identifying a ‘user’.
   *
   * @remarks
   * If undefined this typically means the request is
   * anonymous. If present, the user object will have
   * a sub property that is a unique identifier for
   * that user. There is also an optional data property
   * that is of any type that typically contains other
   * information about the user. When using JWT tokens
   * you’ll usually find all the claims here.
   *
   * @readonly
   */
  user?: RequestUser<ResolveUserData<TOptions["UserData"]>>;
}

/**
 * Options for creating a new ZuploRequest.
 * Extends the standard RequestInit with Zuplo-specific properties.
 * @public
 */
export declare interface ZuploRequestInit<
  TOptions extends RequestInitGeneric = RequestInitGeneric,
> extends RequestInit {
  params?: ResolveRequestParams<TOptions["Params"]>;
  user?: ResolveUserData<TOptions["UserData"]>;
}

/* Excluded from this release type: zuploServiceProxy */

/**
 * Functions for interacting with Zuplo services
 * @beta
 */
export declare class ZuploServices {
  /**
   * Get a JWT access token that can be used to call Zuplo services or
   * for other purposes such as federated identity.
   */
  static getIDToken(
    context: ZuploContext,
    options?: {
      audience?: string;
    }
  ): Promise<string>;
}

export {};
