/**
 * Replicate / Llama Governance Adapter
 *
 * Maps Meta Llama function calling (via Replicate hosting) to the
 * GovernanceAdapter interface. Replicate exposes Llama models as managed
 * predictions with an async lifecycle: create -> poll -> succeeded/failed.
 *
 * Endpoint (create):  https://api.replicate.com/v1/predictions
 * Endpoint (poll):    https://api.replicate.com/v1/predictions/{id}
 * Auth:               Authorization: Token <REPLICATE_API_TOKEN>
 *                     NOTE: "Token" prefix, not "Bearer"
 *
 * Supported models:
 *   meta/meta-llama-3.1-8b-instruct
 *   meta/meta-llama-3.1-70b-instruct
 *   meta/meta-llama-3.1-405b-instruct
 *   meta/meta-llama-3.2-3b-instruct
 *   meta/meta-llama-3.3-70b-instruct
 *
 * Prediction lifecycle:
 *   Replicate predictions are async. The adapter does NOT block on polling
 *   inside wrapFunctionCall -- the predictionId is carried in the audit entry
 *   so callers can correlate polls externally. Streaming (SSE) is the
 *   preferred path; polling is provided for compatibility only.
 *
 * Tool calling:
 *   Llama 3.1+ supports tool calls via the `tools` input field on Replicate.
 *   Tool definitions are JSON Schema objects passed in `input.tools`.
 *   The model responds with a `tool_call` field in the output; this adapter
 *   extracts that and routes through governance.
 *
 * 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.
 *
 * Security constraints:
 *   - HTTPS only. HTTP endpoints are rejected at construction.
 *   - REPLICATE_API_TOKEN is NEVER written to audit entries, logs, or errors.
 *   - predictionId is opaque (no prompt content leakage).
 *   - versionSha is truncated to 12 chars in audit entries for readability.
 *
 * No Replicate 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';
/** Primary Replicate predictions endpoint (HTTPS only). */
export declare const REPLICATE_DEFAULT_ENDPOINT = "https://api.replicate.com/v1/predictions";
/** Replicate poll endpoint template (fill in prediction id). */
export declare const REPLICATE_POLL_ENDPOINT_TEMPLATE = "https://api.replicate.com/v1/predictions/{id}";
/** Supported Llama model identifiers on Replicate as of 2026-04-30. */
export declare const REPLICATE_LLAMA_MODELS: readonly ["meta/meta-llama-3.1-8b-instruct", "meta/meta-llama-3.1-70b-instruct", "meta/meta-llama-3.1-405b-instruct", "meta/meta-llama-3.2-3b-instruct", "meta/meta-llama-3.3-70b-instruct"];
export type ReplicateLlamaModelId = (typeof REPLICATE_LLAMA_MODELS)[number];
/**
 * Llama tool call format as returned by the model in Replicate output.
 * Llama 3.1+ encodes tool calls in the response content as a JSON object.
 */
export interface ReplicateLlamaToolCall {
    /** Tool call identifier (opaque string, Llama-generated) */
    id: string;
    type: 'function';
    function: {
        name: string;
        /** JSON-encoded arguments */
        arguments: string;
    };
}
/**
 * Llama legacy function_call format (single tool invocation without id field).
 * Used by some Llama 3.1 fine-tunes that follow the OpenAI function_call shape.
 */
export interface ReplicateLlamaFunctionCall {
    name: string;
    /** JSON-encoded arguments */
    arguments: string;
}
/** Union of both supported Llama call formats on Replicate. */
export type ReplicateLlamaCallFormat = ReplicateLlamaFunctionCall | ReplicateLlamaToolCall;
/** Result from wrapFunctionCall(). Mirrors DeepSeekAdapter's shape. */
export interface ReplicateLlamaWrappedCallResult {
    /** 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: ReplicateLlamaCallFormat;
    /**
     * Provider metadata written to the audit entry.
     * NEVER contains the API token or secrets.
     * predictionId is opaque -- no prompt content is embedded.
     */
    auditEntry: ReplicateLlamaAuditEntry;
}
/**
 * Audit entry shape for governance post-action records.
 *
 * Fields:
 *   - provider: always 'replicate-llama'
 *   - modelOwner: e.g. 'meta'
 *   - modelName: e.g. 'meta-llama-3.1-70b-instruct'
 *   - versionSha: first 12 chars of the Replicate version SHA (readability)
 *   - predictionId: opaque async lifecycle ID (no prompt content)
 *   - toolName: the function/tool being governed
 *   - format: 'function_call' | 'tool_calls'
 *   - decisionType: ALLOW | DENY | REQUIRE_APPROVAL
 *   - timestamp: ISO-8601
 *   - durationMs: populated after execution
 */
export interface ReplicateLlamaAuditEntry {
    provider: 'replicate-llama';
    modelOwner?: string;
    modelName?: string;
    /** Truncated to first 12 chars for readability. Never the full SHA. */
    versionSha?: string;
    /** Opaque Replicate prediction ID. Never contains prompt content. */
    predictionId?: string;
    toolName: string;
    format: 'function_call' | 'tool_calls';
    decisionType: string;
    timestamp: string;
    durationMs?: number;
}
/** Block/approval rule: function name pattern with reason. */
export interface ReplicateLlamaFunctionRule {
    /** Exact function name or regex pattern */
    pattern: string | RegExp;
    /** Reason for the rule */
    reason: string;
}
/** Extended config for the Replicate/Llama adapter. */
export interface ReplicateLlamaAdapterConfig extends AdapterConfig {
    /**
     * Replicate API token (REPLICATE_API_TOKEN).
     * Authorization header format: "Token <value>", NOT "Bearer".
     * NEVER logged, NEVER included in audit entries.
     * Stored in memory only; validated at construction.
     */
    apiToken?: string;
    /**
     * Endpoint override. Defaults to REPLICATE_DEFAULT_ENDPOINT.
     * Must be HTTPS. HTTP endpoints are rejected at construction.
     */
    endpoint?: string;
    /**
     * Replicate model identifier in <owner>/<name> format.
     * Must be one of REPLICATE_LLAMA_MODELS or a custom Llama deployment.
     * Required: validation at construction.
     */
    modelId?: string;
    /**
     * Replicate version SHA for the model (long opaque hash).
     * Required for deterministic prediction routing.
     * Stored in full; truncated to 12 chars only in audit entries.
     */
    versionSha?: string;
    /** Functions explicitly blocked from execution */
    blockedFunctions?: ReplicateLlamaFunctionRule[];
    /** Functions requiring human approval before execution */
    approvalRequiredFunctions?: ReplicateLlamaFunctionRule[];
    /** 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 ReplicateLlamaAdapter extends BaseGovernanceAdapter {
    private blockedFunctions;
    private approvalRequiredFunctions;
    private agentIdentity;
    private preActionLog;
    private postActionLog;
    private injectionDetector;
    private injectionConfig;
    /** Effective endpoint after config validation. */
    private endpoint;
    /** Model <owner>/<name> from config. */
    private configuredModelId;
    /** Full version SHA from config (truncated in audit entries). */
    private configuredVersionSha;
    /**
     * Initialize with Replicate/Llama-specific configuration.
     *
     * Throws synchronously if:
     *   - endpoint is provided but uses HTTP (not HTTPS)
     *   - modelId is provided but does not match <owner>/<name> format
     *   - apiToken contains only whitespace
     */
    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 Replicate.
     *
     * 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.
     * Replicate has no native post-action hook; callers invoke this after execution.
     */
    postAction(context: ActionContext, result: ActionResult): void;
    /**
     * Report adapter capabilities.
     * Replicate (like OpenAI/DeepSeek) lacks native hooks -- middleware wrapper.
     */
    getCapabilities(): AdapterCapabilities;
    /**
     * Parse a Llama function_call (legacy format) into ActionContext.
     */
    parseFunctionCall(call: ReplicateLlamaFunctionCall): ActionContext;
    /**
     * Parse a Llama tool call (tool_calls array element) into ActionContext.
     */
    parseToolCall(call: ReplicateLlamaToolCall): ActionContext;
    /**
     * Parse either format into ActionContext (auto-detects).
     */
    parseCall(call: ReplicateLlamaCallFormat): ActionContext;
    /**
     * Wrap a Llama function/tool call with governance enforcement.
     *
     * Primary integration point. Callers pass the Llama tool call extracted from
     * the Replicate prediction output. Governance is applied before execution.
     *
     * Replicate-specific audit fields:
     *   - modelOwner / modelName: split from configured modelId
     *   - versionSha: truncated to 12 chars for readability
     *   - predictionId: opaque async lifecycle ID (no prompt content)
     *
     * Streaming preferred over polling. This wrapper does NOT block on polling.
     * If the caller has a predictionId from an async prediction, pass it here
     * so it appears in the audit entry for correlation.
     *
     * @param call          - The Llama function/tool call object
     * @param executor      - Optional executor invoked if governance allows
     * @param modelId       - Optional model identifier for audit entry
     * @param predictionId  - Optional Replicate prediction ID for audit correlation
     * @returns ReplicateLlamaWrappedCallResult
     */
    wrapFunctionCall(call: ReplicateLlamaCallFormat, executor?: (context: ActionContext) => Promise<unknown>, modelId?: string, predictionId?: string): Promise<ReplicateLlamaWrappedCallResult>;
    /**
     * Synchronous version of wrapFunctionCall for non-async executors.
     */
    wrapFunctionCallSync(call: ReplicateLlamaCallFormat, executor?: (context: ActionContext) => unknown, modelId?: string, predictionId?: string): ReplicateLlamaWrappedCallResult;
    /**
     * Extract a ReplicateLlamaToolCall from a Replicate prediction output string.
     *
     * Replicate returns the prediction output as a streamed string (SSE) or a
     * single string. When Llama uses tool calling, the output contains a JSON
     * object with a `tool_call` key. This helper parses that out.
     *
     * Returns null if the output does not contain a tool call.
     * Callers should check for null before passing to wrapFunctionCall.
     *
     * NOTE: streaming is the preferred path; use SSE events and reconstruct
     * the tool call from the delta stream. This synchronous helper is for
     * completed (non-streaming) prediction outputs only.
     */
    extractToolCallFromOutput(output: string): ReplicateLlamaToolCall | null;
    /**
     * Build a Llama-format tool response message from an ActionResult.
     * Compatible with OpenAI/DeepSeek tool response shape for interoperability.
     */
    buildToolResponse(callId: string, result: ActionResult): {
        role: 'tool';
        tool_call_id: string;
        content: string;
    };
    /**
     * Build a governance-denied response in Llama/OpenAI tool response format.
     */
    buildDeniedResponse(callId: string, decision: ActionDecision): {
        role: 'tool';
        tool_call_id: string;
        content: string;
    };
    /** Returns the effective endpoint URL configured for this adapter instance. */
    getEndpoint(): string;
    /** Returns the configured model identifier, if any. */
    getModelId(): string | undefined;
    /** Returns the configured version SHA, if any. */
    getVersionSha(): 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;
    /**
     * Split a Replicate model identifier into owner and name components.
     * Returns empty strings if the model ID is absent or malformed.
     * No exception is thrown here -- validation happens at construction.
     */
    private splitModelId;
}
//# sourceMappingURL=replicate-llama.d.ts.map