import { A as AxioRankOptions, a as ToolCallParams, T as ToolCallResult, b as ToolResultParams, c as AxioTrace, V as VerifyCardParams, C as CardVerifyResult, d as ToolCallSignal, e as AxioGuardOptions, f as VerifyRequestResult, g as VerifySurfaceParams } from './types-C6RfE7pX.js';
export { h as CardDecision, i as ChallengeInstruction, D as Decision, I as InboundDecision, j as InboundSurfaceKind, P as ProtocolId, S as SignalCategory, k as VerificationMethod, l as VerificationStatus } from './types-C6RfE7pX.js';
import { LocalDecision } from '@axiorank/detectors';

/**
 * AxioRank SDK client.
 *
 * @example
 * ```ts
 * const axio = new AxioRank({ apiKey: process.env.AXIORANK_KEY! });
 * const { decision } = await axio.toolCall({ tool: "github.push", arguments: {} });
 * ```
 */
declare class AxioRank {
    private readonly apiKey?;
    private readonly baseUrl;
    private readonly timeoutMs;
    private readonly approvalTimeoutMs;
    private readonly fetchImpl;
    private readonly defaultTraceId?;
    private readonly defaultSessionId?;
    private readonly onUnavailableOverride?;
    private readonly onDegraded?;
    private lastKnownBehavior?;
    private readonly useTokens;
    private readonly subjectToken?;
    private readonly subjectTokenProvider?;
    private readonly tokenScopes?;
    private readonly tokenTtlSeconds?;
    private cachedToken?;
    private inflightToken?;
    constructor(options: AxioRankOptions);
    /**
     * The bearer credential to send. In token mode, returns a cached short-lived
     * token (minting / refreshing as needed, with concurrent refreshes coalesced);
     * otherwise the static api key. If a token exchange fails but a static key is
     * available, falls back to it so an older gateway (no `/token` endpoint) keeps
     * working unchanged.
     */
    private authHeader;
    private invalidateToken;
    /**
     * Exchange the api key (or a federated OIDC token) for a short-lived token at
     * `/api/gateway/token`. Returns the token, or null on any failure (so callers
     * can fall back to the static key).
     */
    private exchangeToken;
    /**
     * Send a tool call to the gateway and resolve with the policy decision.
     * Throws {@link AxioRankAuthError} / {@link AxioRankRequestError} on errors,
     * but resolves normally for an explicit `deny` decision.
     */
    toolCall(params: ToolCallParams): Promise<ToolCallResult>;
    /**
     * POST a tool-call payload (request or result phase) and resolve with the
     * decision, transparently waiting out a `require_approval` hold so callers only
     * ever see the final `allow` / `deny`. Shared by {@link toolCall} and
     * {@link inspectResult}.
     */
    private submitToolCall;
    /**
     * Resolve a call locally when the gateway is unreachable. Precedence: the
     * constructor `onUnavailable` override > the last posture the gateway reported >
     * `fail_open` (the safe, non-blocking default). `fail_closed` yields a `deny` (so
     * {@link enforce} throws and no ungoverned call proceeds); `fail_open` yields an
     * `allow`. Marked `degraded` so callers and telemetry can tell it apart from a
     * real verdict.
     */
    private degraded;
    /**
     * Inspect a tool's RESULT (phase="result") and resolve with the decision -
     * the enforce-capable counterpart to {@link reportResult}. Use it to catch
     * indirect prompt injection (or a leaked secret / PII) in what a tool returned
     * BEFORE the agent ingests it: a `deny` means block or redact the output.
     *
     * Inspection is opt-in per workspace (`inspect_tool_results`); when it's off,
     * the gateway scores + audits the result but always resolves `allow`
     * (monitor-first). The framework adapters call this automatically for
     * untrusted-source tools when you pass `inspectResults: true`.
     *
     * @example
     * ```ts
     * const page = await fetchUrl(url);
     * const { decision } = await axio.inspectResult({ tool: "web.fetch", resultText: page });
     * if (decision === "deny") page = "[blocked: untrusted content removed]";
     * ```
     */
    inspectResult(params: ToolResultParams): Promise<ToolCallResult>;
    /**
     * Poll the approvals endpoint until a held call is resolved (the gateway
     * long-polls, so this is cheap), resolving to the final allow/deny. After
     * {@link AxioRankOptions.approvalTimeoutMs} it gives up and returns `deny`.
     */
    private waitForApproval;
    /**
     * Like {@link toolCall}, but throws {@link AxioRankDeniedError} when the
     * decision is `deny` - convenient for guarding a tool call in one line.
     */
    enforce(params: ToolCallParams): Promise<ToolCallResult>;
    /**
     * Report a tool's RESULT to the gateway for information-flow-control taint
     * tracking (phase="result"). Best-effort telemetry: never throws and never
     * blocks your agent. The guard wrappers call this automatically for
     * untrusted-source tools when the workspace enforces IFC; you rarely call it
     * directly.
     */
    reportResult(params: ToolResultParams): Promise<void>;
    /**
     * Begin a correlated trace (one agent run). Every call made through the
     * returned handle shares a trace id and gets an auto-incrementing step index,
     * so the gateway can correlate them into a multi-step kill chain (e.g. read a
     * secret → exfiltrate it). Pass your own id to join an existing trace.
     *
     * Pass `{ intent }` to declare the user task this run serves: the handle sends
     * it on its first request-phase call, the gateway stores it once per trace
     * (redacted), and the AI flow judge uses it to release data-flow holds that
     * clearly serve the task.
     *
     * @example
     * ```ts
     * const t = axio.trace();                          // generated uuid
     * await t.enforce({ tool: "vault.read" });         // step 0
     * await t.toolCall({ tool: "http.post", ... });    // step 1
     *
     * const t2 = axio.trace({ intent: "Reply to Bob's email about the offsite" });
     * ```
     */
    trace(traceIdOrOptions?: string | {
        id?: string;
        intent?: string;
        /** Session grouping this run with its sibling runs (one conversation). */
        sessionId?: string;
        /** Metadata tags sent on every call made through this handle (a
         *  per-call `metadata` wins on key conflicts). */
        metadata?: Record<string, string | number | boolean>;
    }): AxioTrace;
    /**
     * Preflight an external MCP server or A2A agent BEFORE your agent trusts it:
     * AxioRank fetches its card, verifies the signature / auth hygiene, scores the
     * declared capabilities, and returns `allow | review | deny`. Pass either a
     * `url` to fetch from or an inline `document` you already hold.
     *
     * @example
     * ```ts
     * const { decision, risk } = await axio.verifyCard({ url: "https://mcp.acme.com" });
     * ```
     */
    verifyCard(params: VerifyCardParams): Promise<CardVerifyResult>;
    /**
     * Like {@link verifyCard}, but throws {@link AxioRankCardDeniedError} when the
     * verdict is `deny` - guard a connection to an untrusted target in one line.
     */
    enforceCard(params: VerifyCardParams): Promise<CardVerifyResult>;
    /**
     * Fetch with a per-attempt timeout, retrying on 429 with backoff (honoring
     * Retry-After). Throws {@link AxioRankRateLimitError} once retries are spent.
     */
    private fetchWithRetry;
    /** Shared POST helper: bearer auth, timeout, 429 backoff, uniform errors. */
    private request;
}

/**
 * Result of a LOCAL inspection - the same detectors and risk scoring the hosted
 * gateway runs, evaluated in-process against the default policy. No API key, no
 * network, no signup.
 */
interface InspectResult {
    /**
     * Advisory verdict under the default posture (deny on a live secret, a
     * destructive op, or risk >= 75). The hosted gateway applies YOUR workspace's
     * real policy (custom rules, approvals/holds, budgets, information-flow
     * control, the ML flow judge, kill-chain correlation) and may decide
     * differently - route the call through `new AxioRank(...).enforce()` to enforce.
     */
    decision: LocalDecision;
    /** Risk score (0-100) the engine assigned. */
    risk: number;
    /** Human-readable explanation for the decision. */
    reason: string;
    /** The content-inspection findings that drove the score. */
    signals: ToolCallSignal[];
    /** A structural copy of the input with secret spans masked in place. */
    redactedPayload: Record<string, unknown>;
}
/**
 * Inspect a tool call locally - in-process, with no API key and no network.
 *
 * Runs the exact AxioRank detectors (leaked secrets, prompt injection,
 * destructive operations, PII, risky egress) and risk scoring the hosted
 * gateway runs, then resolves an advisory `allow` / `deny` under the default
 * policy. Use it to see what AxioRank catches in seconds, then route real
 * traffic through {@link AxioRank.enforce} to enforce centrally with your own
 * policy, an audit trail, approvals, and multi-step kill-chain correlation.
 *
 * Pure and synchronous; safe in Node, edge, and the browser. Plain payloads are
 * scored identically to the gateway; the gateway additionally decodes deeply
 * nested base64/hex/gzip wrappers and writes a salted-SHA-256 audit fingerprint.
 *
 * @example
 * ```ts
 * import { inspect } from "@axiorank/sdk";
 *
 * const r = inspect("aws.s3.putObject", {
 *   body: "AKIAIOSFODNN7EXAMPLE",
 *   webhook: "http://attacker.example/exfil",
 * });
 * console.log(r.decision, r.risk, r.signals.map((s) => s.detector));
 * // → "deny" 96 ["secret.aws_access_key", ...]
 * ```
 */
declare function inspect(tool: string, args?: Record<string, unknown>): InspectResult;
/**
 * Inspect a tool's RESULT (or any freeform text) locally - the result-phase
 * counterpart to {@link inspect}. Catches indirect prompt injection, a leaked
 * secret, or PII in what a tool returned BEFORE your agent ingests it. No API
 * key, no network.
 *
 * @example
 * ```ts
 * const page = await fetchUrl(url);
 * const r = inspectText("web.fetch", page);
 * if (r.decision === "deny") {
 *   // strip or quarantine untrusted content before the model sees it
 * }
 * ```
 */
declare function inspectText(tool: string, text: string): InspectResult;
/**
 * Inspect an LLM PROMPT locally - the model-input guardrail. Catches prompt
 * injection, jailbreak attempts, and a secret or PII leaking INTO the prompt,
 * before you send it to the model. No API key, no network.
 *
 * @example
 * ```ts
 * const r = inspectPrompt(userMessage);
 * if (r.decision === "deny") throw new Error("blocked prompt: " + r.reason);
 * ```
 */
declare function inspectPrompt(text: string): InspectResult;
/**
 * Inspect an LLM COMPLETION locally - the model-output guardrail. Catches
 * injected instructions in the output, PII egress, and a leaked secret in what
 * the model returned, before it reaches a user or a downstream tool. No API key,
 * no network.
 *
 * @example
 * ```ts
 * const out = await model.generate(prompt);
 * const r = inspectCompletion(out.text);
 * if (r.decision === "deny") out.text = "[response withheld]";
 * ```
 */
declare function inspectCompletion(text: string): InspectResult;

/** Base class for all errors thrown by the SDK. */
declare class AxioRankError extends Error {
    constructor(message: string);
}
/** Thrown when the API key is missing, invalid, or revoked (HTTP 401). */
declare class AxioRankAuthError extends AxioRankError {
    constructor(message?: string);
}
/** Thrown for malformed requests, timeouts, and other non-2xx responses. */
declare class AxioRankRequestError extends AxioRankError {
    status?: number;
    constructor(message: string, status?: number);
}
/** Thrown by {@link AxioRank.enforce} when the gateway denies the call. */
declare class AxioRankDeniedError extends AxioRankError {
    result: ToolCallResult;
    constructor(result: ToolCallResult);
}
/** Thrown by the chat guards when a prompt or completion is blocked locally. */
declare class AxioRankGuardError extends AxioRankError {
    /** Which side of the model call was blocked. */
    phase: "prompt" | "completion";
    risk: number;
    reason: string;
    constructor(phase: "prompt" | "completion", reason: string, risk: number);
}
/** Thrown by {@link AxioRank.enforceCard} when the preflight verdict is `deny`. */
declare class AxioRankCardDeniedError extends AxioRankError {
    result: CardVerifyResult;
    constructor(result: CardVerifyResult);
}
/** Thrown when the workspace is rate-limited (HTTP 429) after retries are exhausted. */
declare class AxioRankRateLimitError extends AxioRankError {
    retryAfterSec?: number;
    constructor(message?: string, retryAfterSec?: number);
}
/** Thrown by {@link constructEvent} when a webhook signature is missing, stale, or invalid. */
declare class AxioRankWebhookSignatureError extends AxioRankError {
    constructor(message?: string);
}

/**
 * Verify an inbound request against AxioRank: collect the request metadata
 * (method, path, the Web Bot Auth signature headers, a bounded body sample),
 * POST it to the verify endpoint, and resolve with the verdict.
 *
 * Framework-agnostic - takes a standard `Request`, so it works in Next.js
 * middleware, Hono, Express (via a Request shim), or Workers. Throws only on a
 * misconfigured site key (401); any transport failure resolves to a synthetic
 * `onError` verdict so a verification outage never breaks the caller's site.
 */
declare function verifyRequest(req: Request, options: AxioGuardOptions): Promise<VerifyRequestResult>;

/**
 * Verify the agent reaching into a NON-website surface you operate - an MCP
 * server, an A2A agent, an HTTP API, or a webhook - where there is no standard
 * `Request` to hand to {@link verifyRequest}. You supply the caller's identity
 * material directly (a signed card for mcp/a2a, an OAuth token or mTLS/SPIFFE id
 * for http_api), AxioRank verifies it, and the result carries the verdict plus a
 * per-kind `challenge` instruction to enforce a non-allow decision.
 *
 * Throws only on a misconfigured site key (401); any transport failure resolves
 * to a synthetic `onError` verdict so a verification outage never breaks you.
 *
 * @example MCP server you expose
 * const result = await verifySurface(
 *   { surfaceKind: "mcp_server", operation: "tools/call", agentCard: incomingCard },
 *   { apiKey: process.env.AXIORANK_SITE_KEY! },
 * );
 * if (result.decision !== "allow") throw rpcError(result.challenge);
 */
declare function verifySurface(params: VerifySurfaceParams, options: AxioGuardOptions): Promise<VerifyRequestResult>;

/**
 * Drop-in guard for a site's edge/middleware. Returns a `Response` to short
 * the request (403 block / 401 or custom challenge) or `undefined` to let it
 * continue - exactly the contract a Next.js middleware expects, with no
 * `next/server` dependency (a standard `Request`/`Response` works everywhere).
 *
 * @example
 * ```ts
 * // middleware.ts
 * import { axioGuard } from "@axiorank/sdk";
 * export const middleware = axioGuard({
 *   apiKey: process.env.AXIORANK_SITE_KEY!,
 *   onChallenge: (req) =>
 *     Response.redirect(new URL("/verify-human", req.url), 302),
 * });
 * export const config = { matcher: ["/api/:path*", "/admin/:path*"] };
 * ```
 */
declare function axioGuard(options: AxioGuardOptions): (req: Request) => Promise<Response | undefined>;

interface WebhookEvent {
    /** Stable idempotency id - dedupe on this. */
    id: string;
    /** Public event type, e.g. "tool_call.evaluated". */
    type: string;
    data: Record<string, unknown>;
    /** Present on a replayed delivery - the original event id. */
    replayOf?: string;
}
interface VerifyWebhookOptions {
    /** Max clock skew (seconds) before a delivery is rejected as a replay. Default 300. */
    toleranceSec?: number;
    /** Injectable clock (unix seconds) for testing. */
    nowSec?: number;
}
/**
 * Verify the `Axiorank-Signature` header against the raw body. Returns false on a missing,
 * malformed, stale, or mismatched signature - never throws.
 */
declare function verifyWebhookSignature(rawBody: string, signatureHeader: string | null | undefined, secret: string, options?: VerifyWebhookOptions): Promise<boolean>;
/**
 * Verify the signature and parse the body in one call. Throws
 * {@link AxioRankWebhookSignatureError} on a bad/stale/missing signature or non-JSON body;
 * otherwise returns the typed event. Dedupe on `event.id` (delivery is at-least-once).
 */
declare function constructEvent(rawBody: string, signatureHeader: string | null | undefined, secret: string, options?: VerifyWebhookOptions): Promise<WebhookEvent>;

interface ChatGuardOptions {
    /**
     * On a denied prompt or completion: `"throw"` (default) raises
     * {@link AxioRankGuardError}; `"return"` lets the call proceed and surfaces the
     * verdict via {@link ChatGuardOptions.onDecision} instead of throwing, so the
     * caller decides what to do.
     * @default "throw"
     */
    onDeny?: "throw" | "return";
    /** Observe every verdict (prompt and completion). Errors here are swallowed. */
    onDecision?: (phase: "prompt" | "completion", result: InspectResult) => void;
    /** Skip scoring the prompt (guard the output only). @default false */
    skipPrompt?: boolean;
    /** Skip scoring the completion (guard the input only). @default false */
    skipCompletion?: boolean;
}

/**
 * Drop-in model-I/O guardrails for the OpenAI and Anthropic chat APIs. Each wraps
 * the client's `create` so the PROMPT is scored before the model runs and the
 * COMPLETION is scored after, blocking prompt injection, jailbreaks, and a secret
 * or PII leaking in or out. Detection is local and in-process (no key, no
 * network), the same engine the hosted gateway runs.
 *
 * The clients are typed structurally, so these add no dependency on the openai or
 * @anthropic-ai/sdk packages.
 *
 * @example OpenAI
 * ```ts
 * import OpenAI from "openai";
 * import { guardOpenAIChat } from "@axiorank/sdk";
 *
 * const openai = new OpenAI();
 * const chat = guardOpenAIChat(openai.chat.completions, { onDeny: "throw" });
 * const res = await chat.create({ model: "gpt-4.1", messages });
 * ```
 *
 * @example Anthropic
 * ```ts
 * import Anthropic from "@anthropic-ai/sdk";
 * import { guardAnthropicMessages } from "@axiorank/sdk";
 *
 * const anthropic = new Anthropic();
 * const messages = guardAnthropicMessages(anthropic.messages);
 * const msg = await messages.create({ model: "claude-opus-4-8", max_tokens: 1024, messages: msgs });
 * ```
 */

interface OpenAIMessage {
    role: string;
    content: unknown;
}
/** Wrap `openai.chat.completions` so every create() is guarded on both sides. */
declare function guardOpenAIChat<B extends {
    messages: OpenAIMessage[];
}, R>(completions: {
    create: (body: B) => Promise<R>;
}, opts?: ChatGuardOptions): {
    create: (body: B) => Promise<R>;
};
interface AnthropicMessage {
    role: string;
    content: unknown;
}
/** Wrap `anthropic.messages` so every create() is guarded on both sides. */
declare function guardAnthropicMessages<B extends {
    messages: AnthropicMessage[];
}, R>(messages: {
    create: (body: B) => Promise<R>;
}, opts?: ChatGuardOptions): {
    create: (body: B) => Promise<R>;
};

export { AxioGuardOptions, AxioRank, AxioRankAuthError, AxioRankCardDeniedError, AxioRankDeniedError, AxioRankError, AxioRankGuardError, AxioRankOptions, AxioRankRateLimitError, AxioRankRequestError, AxioRankWebhookSignatureError, AxioTrace, CardVerifyResult, type ChatGuardOptions, type InspectResult, ToolCallParams, ToolCallResult, ToolCallSignal, VerifyCardParams, VerifyRequestResult, VerifySurfaceParams, type VerifyWebhookOptions, type WebhookEvent, axioGuard, constructEvent, guardAnthropicMessages, guardOpenAIChat, inspect, inspectCompletion, inspectPrompt, inspectText, verifyRequest, verifySurface, verifyWebhookSignature };
