/**
 * LlamaIndexAdapter -- Orchestrator adapter for LlamaIndex Agents.
 *
 * Hook surface: LlamaIndex exposes FunctionAgent, ReActAgent, and CodeActAgent
 * as primary agent entry points. Our adapter is the TypeScript governance-side
 * consumer of normalised event payloads produced at each stage of the LlamaIndex
 * pipeline. Customers wire the adapter at the governance boundary:
 *
 *   const adapter = new LlamaIndexAdapter(cfg);
 *   adapter.initialize(orchCfg);
 *
 *   // At agent spawn:
 *   await adapter.agentStart(sessionId, agentType, contextSnapshot);
 *
 *   // Before a tool/function call:
 *   await adapter.toolCall(sessionId, toolName, args);
 *
 *   // After a tool result returns:
 *   await adapter.toolResult(sessionId, toolName, result);
 *
 *   // Before an LLM call:
 *   await adapter.llmCall(sessionId, model, messages);
 *
 *   // After a retrieved document chunk is classified:
 *   await adapter.documentRetrieval(sessionId, chunks);
 *
 *   // After the response synthesis stage:
 *   await adapter.responseSynthesis(sessionId, synthesizedText, sourceChunkIds);
 *
 *   // When the agent terminates:
 *   await adapter.agentEnd(sessionId, outcome);
 *
 * LlamaIndex-specific considerations:
 *   - Primary runtime is Python; our adapter is the TypeScript governance-side
 *     consumer of normalised event payloads (same pattern as ADK).
 *   - DocumentStore and VectorStore retrieval is a first-class ingress surface.
 *     Every retrieved chunk is classified for PHI before the agent sees it.
 *     Common healthcare document classes: medical records, lab PDFs, clinical notes.
 *   - ReAct trace format (Thought -> Action -> Observation) is surfaced in canonical
 *     audit events as a structured reactTrace field.
 *   - Response synthesis stage (where LlamaIndex assembles the final answer from
 *     retrieved chunks) is a post-retrieval ingress stage: the synthesised response
 *     is classified before return to the caller.
 *
 * Healthcare document classes handled at ingress:
 *   MedicalRecord, LabReport, ClinicalNote, PatientChart, PathologyReport,
 *   RadiologyReport, PrescriptionRecord, InsuranceClaim
 *
 * No live LlamaIndex Python SDK installed. All framework surfaces are shims.
 * DEFERRED-LLAMAINDEX-V1-API: Verify exact hook surface when LlamaIndex
 * stabilises its TypeScript / event-bus API.
 *
 * Pentest gate:
 *   PT-ADAPT-LLAMAINDEX-1: retrieved chunk with PHI and no HIPAA binding is refused.
 *   PT-ADAPT-LLAMAINDEX-2: response synthesis reveals distilled PHI that was not
 *     present in any single chunk.
 *   PT-ADAPT-LLAMAINDEX-3: ReAct Observation leaking to external tool call is caught
 *     by egress guard.
 *
 * Spec: P3-SUB-ADAPT-04
 * @connexum/ai-governance
 */
import { BaseOrchestratorAdapter } from './base';
import { OrchestratorCapabilities, WorkflowContext, WorkflowDecision, WorkflowStepContext, WorkflowStepDecision, WorkflowResult, RoleEdgeContext, RoleEdgeDecision, OrchestratorError } from './index';
import { LlamaIndexUnboundDataError } from '../errors/index';
import type { TaskContext, TaskDecision, PlanContext, PlanDecision, DelegationContext, DelegationDecision } from './orchestrator-adapter';
/**
 * Thrown when a LlamaIndex session acts without a pack binding.
 * Re-exports canonical UnboundDataError as LlamaIndexUnboundDataError so
 * a single `instanceof UnboundDataError` at the server boundary matches
 * all adapter origins. (C2 fix, 2026-04-24)
 */
export { LlamaIndexUnboundDataError };
/**
 * Thrown when a retrieved document chunk contains PHI and HIPAA enforcement
 * is active with no BAA-covered provider on file.
 */
export declare class LlamaIndexPhiRetrievalError extends Error {
    readonly sessionId: string;
    readonly chunkId: string;
    readonly documentClass: string;
    constructor(sessionId: string, chunkId: string, documentClass: string);
}
/**
 * Thrown when the response synthesis stage produces output containing PHI
 * that was not detectable in any single source chunk (distillation risk).
 */
export declare class LlamaIndexSynthesisPhiError extends Error {
    readonly sessionId: string;
    constructor(sessionId: string);
}
/**
 * Thrown when a ReAct Observation contains sensitive data that is about to
 * be passed to an external tool call (observation egress leak).
 */
export declare class LlamaIndexReactObservationLeakError extends Error {
    readonly sessionId: string;
    readonly toolName: string;
    constructor(sessionId: string, toolName: string);
}
/**
 * Healthcare document classes LlamaIndex commonly ingests.
 * Used to classify retrieved chunks at ingress.
 */
export type LlamaIndexDocumentClass = 'MedicalRecord' | 'LabReport' | 'ClinicalNote' | 'PatientChart' | 'PathologyReport' | 'RadiologyReport' | 'PrescriptionRecord' | 'InsuranceClaim' | 'GenericDocument' | 'UNKNOWN';
/** Keywords that signal a document is in a protected healthcare class. */
export declare const HEALTHCARE_DOC_KEYWORDS: ReadonlyMap<LlamaIndexDocumentClass, string[]>;
/** LlamaIndex agent types. */
export type LlamaIndexAgentType = 'FunctionAgent' | 'ReActAgent' | 'CodeActAgent' | 'UNKNOWN';
/** Context snapshot at agent spawn. */
export interface LlamaIndexContextSnapshot {
    /** ISO-8601 timestamp at spawn */
    spawnedAt: string;
    /** Pack binding array -- MUST be non-empty for the session to proceed */
    packBinding: string[];
    /** LLM model identifier */
    model: string;
    /** Agent type (FunctionAgent, ReActAgent, CodeActAgent) */
    agentType: LlamaIndexAgentType;
    /** Whether this agent accesses a document store / vector store */
    hasDocumentStore: boolean;
    /** Whether this agent accesses a vector store for retrieval */
    hasVectorStore: boolean;
    /** Provider identifier (e.g. 'openai', 'anthropic', 'bedrock', 'azure-openai') */
    providerId?: string;
    /** Arbitrary session metadata */
    metadata?: Record<string, unknown>;
}
/** A single retrieved document chunk from LlamaIndex's retrieval pipeline. */
export interface LlamaIndexDocumentChunk {
    /** Unique chunk identifier */
    chunkId: string;
    /** Source document identifier */
    sourceDocId: string;
    /** Plain-text content of the chunk */
    content: string;
    /** Metadata from the document store */
    metadata?: Record<string, unknown>;
    /** Optional pre-classified document class (from caller) */
    documentClass?: LlamaIndexDocumentClass;
}
/** Classified form of a retrieved chunk (with PHI flag added). */
export interface LlamaIndexDocumentChunkClassified extends LlamaIndexDocumentChunk {
    documentClass: LlamaIndexDocumentClass;
    hasPhi: boolean;
}
/**
 * A single step in a ReAct trace (Thought -> Action -> Observation cycle).
 * The adapter surfaces these as a structured reactTrace field in audit events.
 */
export interface LlamaIndexReactStep {
    /** Sequential step number within the ReAct cycle */
    stepIndex: number;
    /** Thought text (agent's internal reasoning) */
    thought?: string;
    /** Action invoked (tool name or "finish") */
    action?: string;
    /** Action input arguments */
    actionInput?: Record<string, unknown>;
    /** Observation text returned by the action */
    observation?: string;
    /** Whether this is the terminal step (finish action) */
    isFinal?: boolean;
}
/** Tool call arguments in a LlamaIndex function/tool call. */
export interface LlamaIndexToolCallArgs {
    [key: string]: unknown;
}
/** Result returned by a LlamaIndex tool call. */
export interface LlamaIndexToolResult {
    success: boolean;
    output?: unknown;
    error?: string;
    durationMs?: number;
}
/** A message in a LlamaIndex conversation turn. */
export interface LlamaIndexMessage {
    role: 'user' | 'assistant' | 'system' | 'tool';
    content: string;
}
/** Terminal outcome when a LlamaIndex session ends. */
export interface LlamaIndexAgentOutcome {
    success: boolean;
    summary?: string;
    durationMs?: number;
    error?: string;
    /** Total chunks retrieved during session */
    totalChunksRetrieved?: number;
    /** Number of synthesis calls during session */
    synthesisCalls?: number;
}
export interface LlamaIndexAdapterConfig {
    /**
     * Session ID prefixes that are registered under governance.
     * Empty array denies all sessions (fail closed).
     */
    registeredSessions: string[];
    /**
     * Tool names that require reviewer approval before execution.
     */
    sensitiveTools: string[];
    /**
     * LLM model identifiers approved for use.
     */
    approvedModels: string[];
    /**
     * Tool argument keys to scan for PHI / exfiltration patterns.
     */
    sensitiveArgKeys: string[];
    /**
     * Maximum tool calls per session before automatic suspension.
     */
    maxToolCallsPerSession?: number;
    /**
     * When true (default), block document retrieval when PHI is detected
     * in a chunk and HIPAA binding is active with no BAA-covered provider.
     * Set to false only to log-and-allow (non-blocking mode for staging).
     */
    blockPhiRetrieval?: boolean;
    /**
     * When true (default), block response synthesis output when PHI is detected.
     */
    blockPhiSynthesis?: boolean;
    /**
     * When true (default), enforce pack-binding at every hook surface.
     */
    enforcePackBinding?: boolean;
}
export declare class LlamaIndexAdapter extends BaseOrchestratorAdapter {
    readonly adapterId = "llamaindex";
    readonly orchestratorId = "llamaindex";
    private llamaConfig;
    /** Per-session tool call counters for runaway detection. */
    private toolCallCounters;
    /** Active sessions: sessionId -> contextSnapshot */
    private activeSessions;
    /**
     * Per-session ReAct trace buffer.
     * Surfaces Thought -> Action -> Observation trace in audit events.
     */
    private reactTraces;
    /**
     * Per-session retrieval history (chunk IDs only, not content).
     * Used by the synthesis-stage classifier to detect distillation risk.
     */
    private retrievalHistory;
    constructor(config: LlamaIndexAdapterConfig);
    /**
     * Called when a LlamaIndex agent session starts.
     *   1. Session registration check
     *   2. Pack-binding resolver
     *   3. Provider compliance check on model
     *   4. Document-store / vector-store ingress surface registration
     *
     * Throws LlamaIndexUnboundDataError or OrchestratorError if denied.
     */
    agentStart(sessionId: string, agentType: LlamaIndexAgentType, contextSnapshot: LlamaIndexContextSnapshot): Promise<WorkflowDecision>;
    /**
     * Called when LlamaIndex retrieves document chunks from its store.
     * This is the primary PHI ingress surface for healthcare workflows.
     *
     * Each chunk is:
     *   1. Classified for healthcare document class
     *   2. Scanned for PHI patterns
     *   3. Blocked if HIPAA pack active + PHI present + blockPhiRetrieval=true
     *
     * Returns classified chunks (with hasPhi + documentClass tags).
     *
     * Throws LlamaIndexPhiRetrievalError for the first PHI chunk found
     * when HIPAA is active and blockPhiRetrieval=true.
     */
    documentRetrieval(sessionId: string, chunks: LlamaIndexDocumentChunk[]): Promise<LlamaIndexDocumentChunkClassified[]>;
    /**
     * Called after LlamaIndex assembles the final answer from retrieved chunks.
     * The synthesised response is classified before it is returned to the caller.
     *
     * Risk: LlamaIndex's synthesis process can produce distilled PHI that was not
     * present in any single source chunk (e.g. correlating name + diagnosis across
     * multiple chunks). This hook catches that.
     *
     * Throws LlamaIndexSynthesisPhiError when PHI is detected and blockPhiSynthesis=true.
     */
    responseSynthesis(sessionId: string, synthesizedText: string, sourceChunkIds: string[]): Promise<{
        hasPhi: boolean;
        auditId: string;
    }>;
    /**
     * Called before every LlamaIndex tool invocation.
     *   1. Active-session check
     *   2. Pack-binding check
     *   3. Runaway-session counter
     *   4. ReAct observation egress check (last Observation -> this tool call)
     *   5. Sensitive-tool REQUIRE_APPROVAL routing
     *   6. Exfiltration scan on sensitive argument keys
     */
    toolCall(sessionId: string, toolName: string, args: LlamaIndexToolCallArgs, reactStep?: LlamaIndexReactStep): Promise<TaskDecision>;
    toolResult(sessionId: string, toolName: string, result: LlamaIndexToolResult): Promise<void>;
    llmCall(sessionId: string, model: string, messages: LlamaIndexMessage[]): Promise<TaskDecision>;
    agentEnd(sessionId: string, outcome: LlamaIndexAgentOutcome): Promise<void>;
    /** Check if HIPAA (or HITECH) pack is in the binding. */
    private hasHipaaBinding;
    /**
     * Classify the healthcare document class of a chunk based on content keywords.
     * Returns the first matching class or GenericDocument.
     */
    private classifyDocumentClass;
    /**
     * Heuristic PHI / PAN pattern check.
     * Mirrors the DataClassifier patterns at a lightweight level.
     */
    private containsPhiPattern;
    startWorkflow(ctx: WorkflowContext): Promise<WorkflowDecision>;
    stepWorkflow(ctx: WorkflowStepContext): Promise<WorkflowStepDecision>;
    completeWorkflow(ctx: WorkflowContext, result: WorkflowResult): Promise<void>;
    preTask(task: TaskContext): Promise<TaskDecision>;
    postTask(task: TaskContext, result: Record<string, unknown>): Promise<void>;
    prePlan(plan: PlanContext): Promise<PlanDecision>;
    postPlan(plan: PlanContext, result: Record<string, unknown>): Promise<void>;
    preDelegation(d: DelegationContext): Promise<DelegationDecision>;
    postDelegation(d: DelegationContext, result: Record<string, unknown>): Promise<void>;
    invokeRoleEdge(edge: RoleEdgeContext): Promise<RoleEdgeDecision>;
    translateError(raw: unknown): OrchestratorError;
    getOrchestratorCapabilities(): OrchestratorCapabilities;
}
//# sourceMappingURL=llamaindex.d.ts.map