/**
 * HuggingFace Governance Adapter
 *
 * Maps HuggingFace Inference API and Inference Endpoints function calling to
 * the GovernanceAdapter interface.
 *
 * TWO API variants are supported, selected by the REQUIRED `apiVariant` field:
 *
 * 1. 'inference-api' (shared/free):
 *    POST https://api-inference.huggingface.co/models/<modelId>
 *    Auth: Authorization: Bearer <HF_TOKEN>
 *    Body: { inputs: '<prompt>', parameters: { ... } }
 *    Response: [{ generated_text: '...' }]
 *    Rate-limited on the free tier. `modelId` is required.
 *
 * 2. 'inference-endpoints' (managed/paid):
 *    POST <endpointUrl>  (custom HTTPS URL per endpoint)
 *    Auth: same Bearer token
 *    Body shape depends on endpoint task; text-generation and chat-completion
 *    endpoints mirror the OpenAI chat-completions shape (messages, tools, etc.)
 *    `endpointUrl` is required. `modelId` is optional (used for audit metadata).
 *
 * Variant discriminator: `apiVariant: 'inference-api' | 'inference-endpoints'`
 *   - Cross-contamination (e.g. providing endpointUrl in 'inference-api' variant)
 *     is rejected at construction.
 *   - Missing required fields per variant are rejected at construction.
 *
 * Tool calling:
 *   Mistral, Llama 3.1+, Qwen, and Zephyr models support tool calls via their
 *   respective prompt templates. This adapter passes tool definitions through
 *   to the model and parses tool_call output from the response, consistent with
 *   the OpenAI/DeepSeek tool_calls format.
 *
 * Commonly supported models on HuggingFace:
 *   mistralai/Mistral-7B-Instruct-v0.3
 *   mistralai/Mixtral-8x7B-Instruct-v0.1
 *   meta-llama/Meta-Llama-3-8B-Instruct
 *   meta-llama/Meta-Llama-3.1-70B-Instruct
 *   Qwen/Qwen2.5-72B-Instruct
 *   tiiuae/falcon-7b-instruct
 *   HuggingFaceH4/zephyr-7b-beta
 *
 * Security constraints:
 *   - HTTPS only. HTTP endpointUrl values are rejected at construction.
 *   - HF token (hf_*) is NEVER written to audit entries, logs, or errors.
 *   - endpointUrl is recorded in audit entries as-is (HF never puts tokens in URLs).
 *
 * Pack-binding primacy (Thomas Directive, 2026-04-22):
 *   Every record governed by this adapter MUST carry a non-empty
 *   packBinding[]. Callers passing an empty array will receive an
 *   UnboundDataError before any action is dispatched.
 *
 * No HuggingFace Hub SDK dependency -- pure wire format mapping.
 *
 * @connexum/ai-governance
 */
import { BaseGovernanceAdapter, type ActionContext, type ActionDecision, type ActionResult, type AdapterCapabilities, type AdapterConfig, type AgentIdentity } from '../adapters/index';
import { type InjectionDetectorConfig } from '../security/prompt-injection-detector';
/** Base URL for the shared HuggingFace Inference API (HTTPS only). */
export declare const HUGGINGFACE_INFERENCE_API_BASE = "https://api-inference.huggingface.co/models";
/**
 * API variant discriminator.
 *
 * 'inference-api'       -- shared/free hosted inference (model-id routed)
 * 'inference-endpoints' -- managed/paid endpoint (custom URL per deployment)
 */
export type HuggingFaceApiVariant = 'inference-api' | 'inference-endpoints';
/**
 * Common HuggingFace model identifiers as of 2026-04-30.
 * Non-exhaustive; any HF model path is valid for 'inference-api'.
 */
export declare const HUGGINGFACE_KNOWN_MODELS: readonly ["mistralai/Mistral-7B-Instruct-v0.3", "mistralai/Mixtral-8x7B-Instruct-v0.1", "meta-llama/Meta-Llama-3-8B-Instruct", "meta-llama/Meta-Llama-3.1-70B-Instruct", "Qwen/Qwen2.5-72B-Instruct", "tiiuae/falcon-7b-instruct", "HuggingFaceH4/zephyr-7b-beta"];
/**
 * HuggingFace tool call format.
 * Mistral, Llama 3.1+, and Qwen return OpenAI-compatible tool_calls arrays.
 */
export interface HuggingFaceToolCall {
    id: string;
    type: 'function';
    function: {
        name: string;
        /** JSON-encoded arguments */
        arguments: string;
    };
}
/**
 * HuggingFace legacy function_call format (single function invocation).
 * Returned by some models before tool_calls support was standardised.
 */
export interface HuggingFaceFunctionCall {
    name: string;
    /** JSON-encoded arguments */
    arguments: string;
}
/** Union of both supported HuggingFace call formats. */
export type HuggingFaceCallFormat = HuggingFaceFunctionCall | HuggingFaceToolCall;
/** Result from wrapFunctionCall(). Mirrors DeepSeek/Replicate shape. */
export interface HuggingFaceWrappedCallResult {
    /** The governance decision that was applied */
    decision: ActionDecision;
    /** The action result, if the call was allowed and executed */
    result?: ActionResult;
    /** The original call object, preserved for chaining */
    originalCall: HuggingFaceCallFormat;
    /**
     * Provider metadata written to the audit entry.
     * NEVER contains the HF token or any secret.
     */
    auditEntry: HuggingFaceAuditEntry;
}
/**
 * Audit entry shape for governance post-action records.
 *
 * Fields:
 *   provider     -- always 'huggingface'
 *   apiVariant   -- 'inference-api' | 'inference-endpoints'
 *   modelId      -- present for 'inference-api'; optional for 'inference-endpoints'
 *   endpointUrl  -- present for 'inference-endpoints'; sanitised (no token in URL)
 *   toolName     -- the function/tool being governed
 *   format       -- 'function_call' | 'tool_calls'
 *   decisionType -- ALLOW | DENY | REQUIRE_APPROVAL
 *   timestamp    -- ISO-8601
 *   durationMs   -- populated after execution
 *
 * The HF token (hf_*) is NEVER included in any of these fields.
 */
export interface HuggingFaceAuditEntry {
    provider: 'huggingface';
    apiVariant: HuggingFaceApiVariant;
    /** Present for 'inference-api'; optional for 'inference-endpoints' */
    modelId?: string;
    /** Present for 'inference-endpoints'; sanitised URL (HF never puts tokens in URLs) */
    endpointUrl?: string;
    toolName: string;
    format: 'function_call' | 'tool_calls';
    decisionType: string;
    timestamp: string;
    durationMs?: number;
}
/** Block/approval rule: function name pattern with reason. */
export interface HuggingFaceFunctionRule {
    /** Exact function name or regex pattern */
    pattern: string | RegExp;
    /** Reason for the rule */
    reason: string;
}
/**
 * Extended config for the HuggingFace adapter.
 *
 * REQUIRED:
 *   apiVariant -- selects which HuggingFace API surface to target.
 *
 * For 'inference-api':
 *   modelId (required) -- e.g. 'mistralai/Mistral-7B-Instruct-v0.3'
 *   Providing endpointUrl with this variant is a cross-contamination error.
 *
 * For 'inference-endpoints':
 *   endpointUrl (required) -- HTTPS custom endpoint URL
 *   modelId (optional) -- recorded in audit metadata; endpoint IS the model
 *   Providing modelId alone (without endpointUrl) with this variant is rejected.
 */
export interface HuggingFaceAdapterConfig extends AdapterConfig {
    /**
     * API variant discriminator (REQUIRED).
     * Determines which HuggingFace API surface is used and which fields are required.
     */
    apiVariant: HuggingFaceApiVariant;
    /**
     * HuggingFace API token (HF_TOKEN / HUGGINGFACE_TOKEN).
     * Format: 'hf_...' (read/write tokens) or 'api_...' (legacy API keys).
     * NEVER logged, NEVER included in audit entries.
     */
    apiToken?: string;
    /**
     * Model identifier for the Inference API variant (required for 'inference-api').
     * Example: 'mistralai/Mistral-7B-Instruct-v0.3'
     * Leading/trailing whitespace is rejected at construction.
     *
     * For 'inference-endpoints', this is optional (audit metadata only).
     */
    modelId?: string;
    /**
     * Custom endpoint URL for the Inference Endpoints variant (required for 'inference-endpoints').
     * Must be HTTPS. HTTP endpoints are rejected at construction.
     * Example: 'https://my-endpoint.us-east-1.aws.endpoints.huggingface.cloud'
     *
     * Providing this field when apiVariant is 'inference-api' is a cross-contamination
     * error and is rejected at construction.
     */
    endpointUrl?: string;
    /** Functions explicitly blocked from execution */
    blockedFunctions?: HuggingFaceFunctionRule[];
    /** Functions requiring human approval before execution */
    approvalRequiredFunctions?: HuggingFaceFunctionRule[];
    /** Agent identity (name + optional role/sessionId) */
    agentIdentity?: AgentIdentity;
    /**
     * Prompt injection detection for LLM messages.
     * Enabled by default with HIGH severity triggering DENY.
     */
    promptInjection?: {
        enabled?: boolean;
        detectorConfig?: InjectionDetectorConfig;
        denyThreshold?: 'high' | 'medium';
    };
}
export declare class HuggingFaceAdapter extends BaseGovernanceAdapter {
    private blockedFunctions;
    private approvalRequiredFunctions;
    private agentIdentity;
    private preActionLog;
    private postActionLog;
    private injectionDetector;
    private injectionConfig;
    /** Effective API variant. Set during initialize(). */
    private configuredVariant;
    /** Effective model ID (for 'inference-api' required; for 'inference-endpoints' optional). */
    private configuredModelId;
    /** Effective endpoint URL (for 'inference-endpoints' required). */
    private configuredEndpointUrl;
    /**
     * Initialize with HuggingFace-specific configuration.
     *
     * Throws synchronously if:
     *   - apiVariant is absent or not one of the two recognised values
     *   - apiVariant is 'inference-api' and modelId is absent, empty, or contains whitespace
     *   - apiVariant is 'inference-api' and endpointUrl is provided (cross-contamination)
     *   - apiVariant is 'inference-endpoints' and endpointUrl is absent
     *   - apiVariant is 'inference-endpoints' and endpointUrl does not start with 'https://'
     */
    initialize(config: AdapterConfig): void;
    /**
     * Assert that packBinding is non-empty.
     * Throws UnboundDataError immediately if the binding is empty or absent.
     * Every caller that writes a governed record must pass their pack bindings.
     *
     * @param packBinding - Array of compliance pack IDs governing this record.
     * @param writeSite   - Identifier of the call site (for error reporting).
     * @param tenantId    - Tenant/org identifier (for error reporting).
     */
    assertPackBinding(packBinding: string[], writeSite: string, tenantId: string): void;
    /**
     * Scan an array of LLM messages for prompt injection BEFORE sending to HuggingFace.
     *
     * Returns ActionDecision DENY if injection detected at denyThreshold severity,
     * ALLOW otherwise. Audit event written to stderr (privacy-safe, no full content).
     */
    scanMessagesForInjection(messages: Array<{
        role: string;
        content: string;
    }>): ActionDecision;
    /**
     * Pre-action governance check.
     * Evaluates blocked and approval-required rules against the tool name.
     */
    preAction(context: ActionContext): ActionDecision;
    /**
     * Post-action audit logging.
     * HuggingFace has no native post-action hook; callers invoke this after execution.
     */
    postAction(context: ActionContext, result: ActionResult): void;
    /**
     * Report adapter capabilities.
     * HuggingFace lacks native hooks -- this adapter is a middleware wrapper.
     */
    getCapabilities(): AdapterCapabilities;
    /**
     * Parse a HuggingFace function_call (legacy format) into ActionContext.
     */
    parseFunctionCall(call: HuggingFaceFunctionCall): ActionContext;
    /**
     * Parse a HuggingFace tool call (tool_calls array element) into ActionContext.
     */
    parseToolCall(call: HuggingFaceToolCall): ActionContext;
    /**
     * Parse either format into ActionContext (auto-detects).
     */
    parseCall(call: HuggingFaceCallFormat): ActionContext;
    /**
     * Wrap a HuggingFace function/tool call with governance enforcement.
     *
     * Primary integration point. Callers pass the HuggingFace tool call extracted
     * from the inference response. Governance is applied before execution.
     *
     * Audit entry includes:
     *   - provider: 'huggingface'
     *   - apiVariant: which API surface was used
     *   - modelId: present for 'inference-api'; optional for 'inference-endpoints'
     *   - endpointUrl: present for 'inference-endpoints' (sanitised; HF never puts
     *     tokens in URLs but we confirm the field is clean)
     *
     * The HF token (hf_*) is NEVER written to the audit entry or any log output.
     *
     * @param call      - HuggingFace function_call or tool_calls element
     * @param executor  - Optional function that executes the call.
     *                    Only invoked if governance allows.
     * @param modelId   - Optional model ID override for audit entry.
     * @returns HuggingFaceWrappedCallResult
     */
    wrapFunctionCall(call: HuggingFaceCallFormat, executor?: (context: ActionContext) => Promise<unknown>, modelId?: string): Promise<HuggingFaceWrappedCallResult>;
    /**
     * Synchronous version of wrapFunctionCall for non-async executors.
     */
    wrapFunctionCallSync(call: HuggingFaceCallFormat, executor?: (context: ActionContext) => unknown, modelId?: string): HuggingFaceWrappedCallResult;
    /**
     * Extract a HuggingFaceToolCall from an Inference API response string.
     *
     * For models returning tool_calls in the generated_text field (Mistral, Llama 3.1+),
     * the output is a JSON object with a `tool_calls` array or a `tool_call` field.
     *
     * Returns the first extracted tool call, or null if none found.
     * Callers should check for null before passing to wrapFunctionCall.
     */
    extractToolCallFromOutput(output: string): HuggingFaceToolCall | null;
    /**
     * Build a HuggingFace/OpenAI-compatible tool response message from an ActionResult.
     */
    buildToolResponse(callId: string, result: ActionResult): {
        role: 'tool';
        tool_call_id: string;
        content: string;
    };
    /**
     * Build a governance-denied response in HuggingFace/OpenAI tool response format.
     */
    buildDeniedResponse(callId: string, decision: ActionDecision): {
        role: 'tool';
        tool_call_id: string;
        content: string;
    };
    /** Returns the configured API variant. */
    getApiVariant(): HuggingFaceApiVariant;
    /**
     * Returns the effective endpoint URL.
     * For 'inference-api': the constructed URL for the configured model.
     * For 'inference-endpoints': the configured endpointUrl.
     */
    getEffectiveEndpointUrl(): string;
    /** Returns the configured model ID, if any. */
    getModelId(): string | undefined;
    /** Get the pre-action decision log. */
    getPreActionLog(): Array<{
        context: ActionContext;
        decision: ActionDecision;
    }>;
    /** Get the post-action result log. */
    getPostActionLog(): Array<{
        context: ActionContext;
        result: ActionResult;
    }>;
    private isToolCall;
    private matchesRule;
}
//# sourceMappingURL=huggingface.d.ts.map