import { C as ConfigStore, a as CliConfig, b as CliCredentials, c as ChatSession, S as SkippedFile, U as UploadResult, A as AuthHeaders, d as UploadBatchResult, e as UploadOptions, f as UploadDirectOptions, g as UploadDirectResult, h as SUPPORTED_EXTENSIONS, D as DmCryptoContext } from './browser-Bs2joT0Y.js';
export { i as AgentStepEvent, j as Arbi, k as ArbiApiError, l as ArbiError, m as ArbiOptions, n as ArtifactEvent, o as AuthContext, p as AuthenticatedClient, q as CitationSummary, r as ConnectOptions, s as DOC_TERMINAL_STATUSES, t as DocumentListFields, u as DocumentListOrder, v as DocumentWaiter, w as DocumentWaiterOptions, F as FormattedWsMessage, L as ListAllOptions, x as ListPaginatedOptions, M as MessageLevel, y as MessageMetadataPayload, z as MessageQueuedEvent, O as OutputTokensDetails, Q as QueryOptions, R as ReconnectOptions, B as ReconnectableWsConnection, E as ResolvedCitation, G as ResponseCompletedEvent, H as ResponseContentPartAddedEvent, I as ResponseCreatedEvent, J as ResponseFailedEvent, K as ResponseOutputItemAddedEvent, N as ResponseOutputItemDoneEvent, P as ResponseOutputTextDeltaEvent, T as ResponseOutputTextDoneEvent, V as ResponseUsage, W as SSEEvent, X as SSEStreamCallbacks, Y as SSEStreamResult, Z as SSEStreamStartData, _ as UserInfo, $ as UserInputRequestEvent, a0 as UserMessageEvent, a1 as WorkspaceContext, a2 as WsConnection, a3 as agentconfig, a4 as assistant, a5 as authenticatedFetch, a6 as buildRetrievalChunkTool, a7 as buildRetrievalFullContextTool, a8 as buildRetrievalTocTool, a9 as connectWebSocket, aa as connectWithReconnect, ab as consumeSSEStream, ac as contacts, ad as conversations, ae as countCitations, af as createAuthenticatedClient, ag as createDocumentWaiter, ah as dm, ai as doctags, aj as documents, ak as files, al as formatAgentStepLabel, am as formatFileSize, an as formatStreamSummary, ao as formatUserName, ap as formatWorkspaceChoices, aq as formatWsMessage, ar as generateEncryptedWorkspaceKey, as as generateNewWorkspaceKey, at as getErrorCode, au as getErrorMessage, av as getRawWorkspaceKey, aw as health, ax as parseSSEEvents, ay as performPasswordLogin, az as performSigningKeyLogin, aA as performSsoDeviceFlowLogin, aB as requireData, aC as requireOk, aD as resolveAuth, aE as resolveCitations, aF as resolveWorkspace, aG as responses, aH as selectWorkspace, aI as selectWorkspaceById, aJ as settings, aK as streamSSE, aL as stripCitationMarkdown, aM as summarizeCitations, aN as tags, aO as workspaces } from './browser-Bs2joT0Y.js';
import { SessionStorageProvider, ArbiClient, components } from '@arbidocs/client';

/**
 * Configuration persistence — file-based implementation for Node.js environments.
 *
 * Browser consumers should import from './config-types.ts' directly.
 */

declare class FileConfigStore implements ConfigStore {
    private readonly configDir;
    private readonly configFile;
    private readonly credentialsFile;
    private readonly sessionFile;
    private readonly metadataFile;
    constructor(configDir?: string);
    private ensureConfigDir;
    private writeSecureFile;
    private readJsonFile;
    getConfig(): CliConfig | null;
    saveConfig(config: CliConfig): void;
    updateConfig(updates: Partial<CliConfig>): void;
    requireConfig(): CliConfig;
    getCredentials(): CliCredentials | null;
    saveCredentials(creds: CliCredentials): void;
    deleteCredentials(): void;
    requireCredentials(): CliCredentials;
    /**
     * Returns a SessionStorageProvider backed by this store's
     * credentials file. Used to wire the auto-relogin middleware in
     * `@arbidocs/client` to the Node-side file store — without this, the
     * middleware falls back to IndexedDB which does not exist in Node
     * and re-login on 401 silently gives up.
     *
     * `getSession` reads the stored signing/server-session keys and
     * decodes them to the raw byte form the relogin handler expects.
     * `saveSession` writes a refreshed server session key back to the
     * credentials file on successful re-login so the next CLI
     * invocation picks it up.
     */
    getSessionStorageProvider(): SessionStorageProvider;
    getChatSession(): ChatSession;
    saveChatSession(session: ChatSession): void;
    updateChatSession(updates: Partial<ChatSession>): void;
    clearChatSession(): void;
    saveLastMetadata(metadata: unknown): void;
    loadLastMetadata(): unknown | null;
    /**
     * Try to resolve config from multiple sources, in priority order:
     *
     * 1. Existing `~/.arbi/config.json` (highest priority)
     * 2. `ARBI_SERVER_URL` environment variable
     * 3. `.env` file in `searchDir` → read `VITE_DEPLOYMENT_DOMAIN`
     * 4. `public/config.json` in `searchDir` → read `deployment.domain`
     * 5. Default to `https://localhost`
     *
     * Returns `{ config, source }` where source describes where the config came from.
     * Saves auto-detected config to disk so subsequent calls use the fast path.
     */
    resolveConfigWithFallbacks(searchDir?: string): {
        config: CliConfig;
        source: string;
    };
    /**
     * Read VITE_DEPLOYMENT_DOMAIN from a .env file.
     */
    private readDotEnvDomain;
    /**
     * Read deployment.domain from a public/config.json file.
     */
    private readPublicConfigDomain;
}

/**
 * OAuth 2.0 Device Authorization Grant (RFC 8628) for Auth0.
 *
 * Enables headless CLI login: the user authorizes in a browser while the CLI polls for a token.
 */
interface SsoConfig {
    ssoEnabled: boolean;
    domain: string;
    clientId: string;
    audience: string;
}
interface DeviceCodeResponse {
    device_code: string;
    user_code: string;
    verification_uri: string;
    verification_uri_complete: string;
    expires_in: number;
    interval: number;
}
declare class DeviceFlowError extends Error {
    constructor(message: string);
}
declare class DeviceFlowExpired extends DeviceFlowError {
    constructor();
}
declare class DeviceFlowAccessDenied extends DeviceFlowError {
    constructor();
}
/**
 * Fetch SSO configuration from the ARBI deployment.
 */
declare function fetchSsoConfig(baseUrl: string): Promise<SsoConfig>;
/**
 * Request a device code from Auth0.
 *
 * POST https://{domain}/oauth/device/code
 */
declare function requestDeviceCode(domain: string, clientId: string, audience?: string, scope?: string): Promise<DeviceCodeResponse>;
/**
 * Poll Auth0 token endpoint until the user authorizes (or the code expires).
 *
 * Returns the Auth0 access_token (JWT).
 */
declare function pollForToken(domain: string, clientId: string, deviceCode: string, interval: number, expiresIn: number, onPoll?: (elapsedMs: number) => void): Promise<string>;

type deviceFlow_DeviceCodeResponse = DeviceCodeResponse;
type deviceFlow_DeviceFlowAccessDenied = DeviceFlowAccessDenied;
declare const deviceFlow_DeviceFlowAccessDenied: typeof DeviceFlowAccessDenied;
type deviceFlow_DeviceFlowError = DeviceFlowError;
declare const deviceFlow_DeviceFlowError: typeof DeviceFlowError;
type deviceFlow_DeviceFlowExpired = DeviceFlowExpired;
declare const deviceFlow_DeviceFlowExpired: typeof DeviceFlowExpired;
type deviceFlow_SsoConfig = SsoConfig;
declare const deviceFlow_fetchSsoConfig: typeof fetchSsoConfig;
declare const deviceFlow_pollForToken: typeof pollForToken;
declare const deviceFlow_requestDeviceCode: typeof requestDeviceCode;
declare namespace deviceFlow {
  export { type deviceFlow_DeviceCodeResponse as DeviceCodeResponse, deviceFlow_DeviceFlowAccessDenied as DeviceFlowAccessDenied, deviceFlow_DeviceFlowError as DeviceFlowError, deviceFlow_DeviceFlowExpired as DeviceFlowExpired, type deviceFlow_SsoConfig as SsoConfig, deviceFlow_fetchSsoConfig as fetchSsoConfig, deviceFlow_pollForToken as pollForToken, deviceFlow_requestDeviceCode as requestDeviceCode };
}

/**
 * Document operations — Node.js file system operations.
 *
 * These functions require Node.js built-ins (fs, path) and are not browser-safe.
 * Browser consumers should use the Blob-based uploadFile/uploadFiles from './documents.js'.
 */

/** Archive extensions that can be extracted via the system `7z` command. */
declare const ARCHIVE_EXTENSIONS: Set<string>;
interface UploadProgress {
    /** Current batch number (1-based). */
    batch: number;
    /** Total number of batches. */
    totalBatches: number;
    /** Folder being uploaded. */
    folder: string;
    /** Number of files in this batch. */
    filesInBatch: number;
    /** Cumulative files uploaded so far (including this batch). */
    filesUploaded: number;
    /** Total files to upload. */
    totalFiles: number;
}
interface UploadDirectoryOptions {
    /** Called before each batch is sent. */
    onBatchStart?: (progress: UploadProgress) => void;
    /** Called after each batch completes. */
    onBatchComplete?: (progress: UploadProgress & {
        result: UploadResult;
    }) => void;
    /** Config ext_id to pass to each upload batch (e.g. for SKIP_DUPLICATES). */
    configExtId?: string;
}
/**
 * Upload a local file by path. Handles readFileSync + basename + Blob + uploadFile.
 * Convenience wrapper for CLI/TUI consumers that work with file system paths.
 *
 * Workspace context is derived server-side from the open session (the caller's
 * JWT + most recent ``/workspace/{id}/open`` call), so no workspace id is sent.
 */
declare function uploadLocalFile(auth: AuthHeaders, filePath: string, options?: UploadOptions): Promise<UploadResult & {
    fileName: string;
}>;
/**
 * Upload a flat list of local files via the direct-to-MinIO flow.
 *
 * This is the Node-side convenience wrapper around ``uploadDocumentsDirect``
 * for CLI/TUI consumers that work with filesystem paths. It reads each file
 * fully into memory and delegates to the browser-safe helper for hashing,
 * encryption, and transport.
 *
 * Callers are responsible for supplying the raw 32-byte workspace key. In
 * the CLI this is unwrapped lazily from the stored signing key + workspace
 * ``wrapped_key``; see ``getRawWorkspaceKey`` in ``auth.ts``.
 */
declare function uploadLocalFilesDirect(arbi: ArbiClient, workspaceKey: Uint8Array, filePaths: string[], options?: UploadDirectOptions): Promise<UploadDirectResult>;
/**
 * Options for the direct-upload directory/zip/archive helpers. Mirrors the
 * legacy ``UploadDirectoryOptions`` so CLI consumers can switch between the
 * two flows without rewiring their progress callbacks. ``configExtId`` is
 * forwarded to ``uploadDocumentsDirect`` for SKIP_DUPLICATES support.
 */
interface UploadDirectoryDirectOptions {
    onBatchStart?: (progress: UploadProgress) => void;
    onBatchComplete?: (progress: UploadProgress & {
        result: {
            doc_ext_ids?: string[];
            skipped?: SkippedFile[];
        };
    }) => void;
    configExtId?: string;
}
/**
 * Walk a directory, group supported files by their relative subfolder (with
 * the directory basename as the root), and upload each group via the
 * direct-to-MinIO flow.
 */
declare function uploadLocalDirectoryDirect(arbi: ArbiClient, workspaceKey: Uint8Array, dirPath: string, options?: UploadDirectoryDirectOptions): Promise<UploadBatchResult>;
/**
 * Extract a zip archive in memory, group supported entries by their internal
 * folder structure, and upload each group via the direct-to-MinIO flow. Uses
 * jszip via dynamic import so the dep is optional at load time. Mirrors the
 * single-root detection behavior of ``uploadZip``.
 */
declare function uploadLocalZipDirect(arbi: ArbiClient, workspaceKey: Uint8Array, zipPath: string, options?: UploadDirectoryDirectOptions): Promise<UploadBatchResult>;
/**
 * Upload a 7z/rar archive via the direct-to-MinIO flow. Shells out to the
 * system ``7z`` binary to extract to a temporary directory, then delegates
 * to ``uploadLocalDirectoryDirect``. The temp directory is removed on exit.
 */
declare function uploadLocalArchiveDirect(arbi: ArbiClient, workspaceKey: Uint8Array, archivePath: string, options?: UploadDirectoryDirectOptions): Promise<UploadBatchResult>;
/**
 * Upload all supported files from a directory, preserving folder structure.
 * Files are grouped by their relative folder path, then each group is split
 * into batches of UPLOAD_BATCH_SIZE to avoid overwhelming the backend.
 */
declare function uploadDirectory(auth: AuthHeaders, dirPath: string, options?: UploadDirectoryOptions): Promise<UploadBatchResult>;
/**
 * Upload files from a zip archive, preserving internal folder structure.
 * Uses jszip via dynamic import so the dependency is optional at load time.
 * Files are uploaded in batches of UPLOAD_BATCH_SIZE per folder.
 */
declare function uploadZip(auth: AuthHeaders, zipPath: string, options?: UploadDirectoryOptions): Promise<UploadBatchResult>;
/**
 * Terminal status for a single file after `uploadManifest` processes it.
 *
 * - `uploaded`  — new document created on the backend
 * - `duplicate` — server reported it as a duplicate of an existing doc
 * - `rejected`  — server refused (unsupported on server, too large, etc.)
 *                 or caller-side validation failed (file missing, wrong type,
 *                 oversized, read error)
 * - `error`     — transport / unexpected failure, safe to retry
 * - `skipped`   — caller-side skip without an attempt (unsupported extension,
 *                 already completed in a previous run, etc.)
 */
type FileStatus = 'uploaded' | 'duplicate' | 'rejected' | 'error' | 'skipped';
/** Per-file outcome emitted by `uploadManifest`. */
interface FileOutcome {
    /** The caller-supplied path (as passed into `uploadManifest`). */
    path: string;
    /** The sanitized folder used for the backend `folder` query param. */
    folder: string;
    /** File size at resolution time, in bytes. */
    sizeBytes: number;
    /** Terminal status for this file. */
    status: FileStatus;
    /** Backend doc ext id, populated on `uploaded` and `duplicate`. */
    docId?: string;
    /** Free-form reason, populated on any non-`uploaded` status. */
    reason?: string;
    /** 1-indexed upload attempt that produced this outcome. 0 for caller-side. */
    attempt: number;
    /** Backend batch id, when known. */
    batchId?: string | null;
}
interface UploadManifestProgress {
    done: number;
    total: number;
    bytesDone: number;
    bytesTotal: number;
}
interface UploadManifestOptions {
    /**
     * Root directory used to derive the `folder` query param for each file.
     * If omitted, the longest common parent directory of all inputs is used.
     */
    rootDir?: string;
    /** Config ext id to pass with each batch (e.g. SKIP_DUPLICATES config). */
    configExtId?: string;
    /** Max upload attempts for transient errors. Default 3. */
    maxRetries?: number;
    /**
     * Called once for every input path with its terminal outcome, in input
     * order. Awaited, so callers can flush audit logs synchronously before
     * the next file is processed.
     */
    onFile?: (outcome: FileOutcome) => void | Promise<void>;
    /** Called after each batch completes (or aborts). */
    onProgress?: (progress: UploadManifestProgress) => void;
    /** Stop processing further files on first `error` outcome. */
    failFast?: boolean;
    /** Abort signal. Remaining files are emitted as `error` with reason `aborted`. */
    signal?: AbortSignal;
}
interface UploadManifestSummary {
    total: number;
    uploaded: number;
    duplicate: number;
    rejected: number;
    error: number;
    skipped: number;
}
interface UploadManifestResult {
    outcomes: FileOutcome[];
    summary: UploadManifestSummary;
}
/**
 * Upload an explicit list of file paths with a per-file audit trail.
 *
 * This is the eDiscovery-grade primitive: every caller-supplied path produces
 * exactly one `FileOutcome`, emitted via `onFile` in input order, so the
 * caller can stream the outcomes to a JSONL log / CSV / state file with no
 * ambiguity about which input got which doc id.
 *
 * Per-file mapping is recovered from the backend's lumped
 * `{doc_ext_ids[], skipped[]}` response as follows:
 *
 *   1. Files are grouped by their parent folder (relative to `rootDir` or
 *      the longest common parent of all inputs). Within one filesystem
 *      folder, basenames are guaranteed unique, which is what makes the
 *      reconciliation below safe.
 *   2. Each folder is chunked into batches of UPLOAD_BATCH_SIZE.
 *   3. After each batch request: any basename in `skipped[]` maps back to
 *      its input path by basename lookup; the remaining survivors are
 *      matched positionally against `doc_ext_ids[]`.
 *
 * If the backend's response length disagrees with the survivor count, all
 * survivors are emitted as `error` so the caller can retry.
 */
declare function uploadManifest(auth: AuthHeaders, paths: string[], options?: UploadManifestOptions): Promise<UploadManifestResult>;
/**
 * Recursively walk a directory and return all absolute paths of files whose
 * extension is in SUPPORTED_EXTENSIONS. Useful for turning a directory input
 * into a flat manifest before calling `uploadManifest`.
 */
declare function walkSupportedFiles(dirPath: string): string[];
/**
 * Upload files from a 7z/rar archive, preserving internal folder structure.
 * Uses the system `7z` command to extract to a temp directory, then delegates
 * to `uploadDirectory`. Requires p7zip / 7z to be installed on the system.
 * Supports: .7z, .rar (anything `7z x` can handle).
 */
declare function uploadArchive(auth: AuthHeaders, archivePath: string, options?: UploadDirectoryOptions): Promise<UploadBatchResult>;

declare const documentsNode_ARCHIVE_EXTENSIONS: typeof ARCHIVE_EXTENSIONS;
type documentsNode_FileOutcome = FileOutcome;
type documentsNode_FileStatus = FileStatus;
declare const documentsNode_SUPPORTED_EXTENSIONS: typeof SUPPORTED_EXTENSIONS;
type documentsNode_UploadDirectoryDirectOptions = UploadDirectoryDirectOptions;
type documentsNode_UploadDirectoryOptions = UploadDirectoryOptions;
type documentsNode_UploadManifestOptions = UploadManifestOptions;
type documentsNode_UploadManifestProgress = UploadManifestProgress;
type documentsNode_UploadManifestResult = UploadManifestResult;
type documentsNode_UploadManifestSummary = UploadManifestSummary;
type documentsNode_UploadProgress = UploadProgress;
declare const documentsNode_uploadArchive: typeof uploadArchive;
declare const documentsNode_uploadDirectory: typeof uploadDirectory;
declare const documentsNode_uploadLocalArchiveDirect: typeof uploadLocalArchiveDirect;
declare const documentsNode_uploadLocalDirectoryDirect: typeof uploadLocalDirectoryDirect;
declare const documentsNode_uploadLocalFile: typeof uploadLocalFile;
declare const documentsNode_uploadLocalFilesDirect: typeof uploadLocalFilesDirect;
declare const documentsNode_uploadLocalZipDirect: typeof uploadLocalZipDirect;
declare const documentsNode_uploadManifest: typeof uploadManifest;
declare const documentsNode_uploadZip: typeof uploadZip;
declare const documentsNode_walkSupportedFiles: typeof walkSupportedFiles;
declare namespace documentsNode {
  export { documentsNode_ARCHIVE_EXTENSIONS as ARCHIVE_EXTENSIONS, type documentsNode_FileOutcome as FileOutcome, type documentsNode_FileStatus as FileStatus, documentsNode_SUPPORTED_EXTENSIONS as SUPPORTED_EXTENSIONS, type documentsNode_UploadDirectoryDirectOptions as UploadDirectoryDirectOptions, type documentsNode_UploadDirectoryOptions as UploadDirectoryOptions, type documentsNode_UploadManifestOptions as UploadManifestOptions, type documentsNode_UploadManifestProgress as UploadManifestProgress, type documentsNode_UploadManifestResult as UploadManifestResult, type documentsNode_UploadManifestSummary as UploadManifestSummary, type documentsNode_UploadProgress as UploadProgress, documentsNode_uploadArchive as uploadArchive, documentsNode_uploadDirectory as uploadDirectory, documentsNode_uploadLocalArchiveDirect as uploadLocalArchiveDirect, documentsNode_uploadLocalDirectoryDirect as uploadLocalDirectoryDirect, documentsNode_uploadLocalFile as uploadLocalFile, documentsNode_uploadLocalFilesDirect as uploadLocalFilesDirect, documentsNode_uploadLocalZipDirect as uploadLocalZipDirect, documentsNode_uploadManifest as uploadManifest, documentsNode_uploadZip as uploadZip, documentsNode_walkSupportedFiles as walkSupportedFiles };
}

/**
 * Agent operations — list, delete persistent agents.
 */

type UserResponse = components['schemas']['UserResponse'];
declare function listAgents(arbi: ArbiClient): Promise<UserResponse[]>;
declare function deleteAgents(arbi: ArbiClient, agentExtIds: string[]): Promise<{
    [x: string]: unknown;
}>;

declare const agents_deleteAgents: typeof deleteAgents;
declare const agents_listAgents: typeof listAgents;
declare namespace agents {
  export { agents_deleteAgents as deleteAgents, agents_listAgents as listAgents };
}

/**
 * Session operations — list active sessions.
 */

type SessionInfoResponse = components['schemas']['SessionInfoResponse'];
/**
 * List all active sessions for the current user.
 * Agents see only their own session.
 */
declare function listSessions(arbi: ArbiClient): Promise<SessionInfoResponse[]>;

declare const sessions_listSessions: typeof listSessions;
declare namespace sessions {
  export { sessions_listSessions as listSessions };
}

/**
 * Project operations — list, create, update, delete, checkout, refresh.
 */

declare function listProjects(arbi: ArbiClient): Promise<{
    external_id: string;
    name: string;
    created_by: string;
    packs: number;
    subscription: string;
    created_at: string;
    quotas: {
        storage_gb: {
            used: number;
            limit: number;
        };
        ai_credits: {
            used: number;
            limit: number;
        };
        collaborators: {
            used: number;
            limit: number;
        };
        budget_reset_at?: number | null | undefined;
    };
    daily_cap_per_user?: number | null | undefined;
    price_id?: string | null | undefined;
    plan?: string | null | undefined;
    amount?: number | null | undefined;
    currency?: string | null | undefined;
    current_period_end?: number | null | undefined;
    cancel_at_period_end?: boolean | null | undefined;
    portal_url?: string | null | undefined;
}[]>;
declare function createProject(arbi: ArbiClient, name: string): Promise<{
    external_id: string;
    name: string;
    created_by: string;
    packs: number;
    subscription: string;
    created_at: string;
    quotas: {
        storage_gb: {
            used: number;
            limit: number;
        };
        ai_credits: {
            used: number;
            limit: number;
        };
        collaborators: {
            used: number;
            limit: number;
        };
        budget_reset_at?: number | null | undefined;
    };
    daily_cap_per_user?: number | null | undefined;
    price_id?: string | null | undefined;
    plan?: string | null | undefined;
    amount?: number | null | undefined;
    currency?: string | null | undefined;
    current_period_end?: number | null | undefined;
    cancel_at_period_end?: boolean | null | undefined;
    portal_url?: string | null | undefined;
}>;
declare function refreshProject(arbi: ArbiClient, projectExtId: string): Promise<{
    external_id: string;
    name: string;
    created_by: string;
    packs: number;
    subscription: string;
    created_at: string;
    quotas: {
        storage_gb: {
            used: number;
            limit: number;
        };
        ai_credits: {
            used: number;
            limit: number;
        };
        collaborators: {
            used: number;
            limit: number;
        };
        budget_reset_at?: number | null | undefined;
    };
    daily_cap_per_user?: number | null | undefined;
    price_id?: string | null | undefined;
    plan?: string | null | undefined;
    amount?: number | null | undefined;
    currency?: string | null | undefined;
    current_period_end?: number | null | undefined;
    cancel_at_period_end?: boolean | null | undefined;
    portal_url?: string | null | undefined;
}>;

declare const projects_createProject: typeof createProject;
declare const projects_listProjects: typeof listProjects;
declare const projects_refreshProject: typeof refreshProject;
declare namespace projects {
  export { projects_createProject as createProject, projects_listProjects as listProjects, projects_refreshProject as refreshProject };
}

/**
 * Orchestrator interface for `arbi listen`.
 *
 * An orchestrator is an external agent that receives prompts and returns responses.
 * ARBI acts as the transport layer (encrypted DMs); the orchestrator does the thinking.
 */
interface Orchestrator {
    /** Human-readable name (e.g. "claude", "openclaw") */
    readonly name: string;
    /**
     * Send a prompt to the orchestrator and collect the response.
     *
     * @param prompt - The decrypted DM content to process
     * @param context - Optional metadata about the message
     * @returns The orchestrator's text response
     */
    prompt(prompt: string, context?: PromptContext): Promise<string>;
    /** Clean up resources (kill child processes, close connections, etc.) */
    close?(): Promise<void>;
}
interface PromptContext {
    /** Sender's external_id */
    senderExtId?: string;
    /** Sender's email */
    senderEmail?: string;
    /** Workspace context (if any) */
    workspaceId?: string;
}

/**
 * Claude Code integration.
 *
 * Spawns `claude -p <prompt> --output-format text` as a child process for each prompt.
 * The prompt is passed as a CLI argument (not stdin).
 *
 * Conversation continuity: first prompt uses --session-id to create a session,
 * subsequent prompts use --resume to continue it. The session ID is derived
 * from the agent's ext_id so it's stable across restarts.
 *
 * The ARBI SKILL.md is injected via --append-system-prompt so Claude knows
 * which CLI commands are available.
 */

interface ClaudeOrchestratorOptions {
    /** Path to the claude CLI binary (defaults to "claude") */
    binaryPath?: string;
    /** ARBI session identifier — used to maintain Claude conversation continuity */
    sessionId: string;
    /** Additional CLI flags (e.g. ["--model", "opus"]) */
    extraArgs?: string[];
    /** Timeout in ms per prompt (defaults to 300_000 = 5 min) */
    timeoutMs?: number;
    /** Override SKILL.md content (defaults to loading from arbi-cli package) */
    skillPrompt?: string;
}
declare class ClaudeOrchestrator implements Orchestrator {
    readonly name = "claude";
    private readonly binaryPath;
    private readonly extraArgs;
    private readonly timeoutMs;
    private readonly claudeSessionId;
    private readonly skillPrompt;
    private sessionStarted;
    constructor(options: ClaudeOrchestratorOptions);
    prompt(prompt: string): Promise<string>;
    private spawnClaude;
    close(): Promise<void>;
}

/**
 * OpenClaw integration.
 *
 * Spawns `openclaw agent --agent <id> --message <prompt> --json` as a child
 * process for each prompt. The gateway handles routing, model selection, and
 * session memory.
 *
 * Session isolation: uses `--session-id` to keep conversations separate per
 * ARBI user. The OpenClaw agent id (e.g. "arbi") is created once during
 * `arbi connect --agent openclaw` via `openclaw agents add`.
 *
 * The ARBI SKILL.md is installed as BOOTSTRAP.md in the agent's workspace
 * during setup, so the agent always has context about arbi commands.
 */

interface OpenClawOrchestratorOptions {
    /** Path to the openclaw CLI binary (defaults to "openclaw") */
    binaryPath?: string;
    /** ARBI session identifier — used for OpenClaw session isolation */
    sessionId: string;
    /** OpenClaw agent id (defaults to "arbi") */
    agentId?: string;
    /** Timeout in ms per prompt (defaults to 300_000 = 5 min) */
    timeoutMs?: number;
    /**
     * Override the HOME env for the spawned openclaw subprocess. Set this in
     * multi-tenant deployments where ``arbi listen`` runs with a per-agent
     * HOME (for its own .arbi config) but openclaw should still resolve its
     * gateway config from the shared real ``/home/<user>`` — symlinks back
     * to the global ``.openclaw`` are rejected by openclaw's exec sandbox,
     * so a direct env override is the right escape hatch.
     */
    spawnHome?: string;
}
declare class OpenClawOrchestrator implements Orchestrator {
    readonly name = "openclaw";
    private readonly binaryPath;
    private readonly agentId;
    private readonly sessionKey;
    private readonly timeoutMs;
    private readonly spawnHome?;
    constructor(options: OpenClawOrchestratorOptions);
    prompt(prompt: string): Promise<string>;
    close(): Promise<void>;
    private spawnOpenClaw;
}

/**
 * DM Listener Loop.
 *
 * Connects to the WebSocket, listens for incoming DMs, decrypts them,
 * routes to an orchestrator, encrypts the reply, and sends it back.
 *
 * Only processes messages from the agent's parent user (owner).
 */

interface DmListenerOptions {
    /** Authenticated ArbiClient instance */
    arbi: ArbiClient;
    /** Access token for WebSocket auth */
    accessToken: string;
    /** Base URL of the ARBI server */
    baseUrl: string;
    /** DM crypto context for encrypt/decrypt */
    crypto: DmCryptoContext;
    /** Orchestrator to route prompts to */
    orchestrator: Orchestrator;
    /** Parent user ext_id — only process messages from this sender */
    parentExtId: string;
    /** Called when a log-worthy event happens (verbose output) */
    onLog?: (message: string) => void;
    /** Called when an error occurs during processing */
    onError?: (message: string, error?: unknown) => void;
}
interface DmListener {
    /** Stop listening and clean up */
    close(): void;
}
/**
 * Start listening for DMs and routing them to the orchestrator.
 *
 * Connects via WebSocket with auto-reconnect. For each incoming DM:
 * 1. Filters to parent user only
 * 2. Decrypts the message
 * 3. Sends plaintext to orchestrator.prompt()
 * 4. Encrypts the response
 * 5. Sends encrypted reply via DM
 */
declare function startDmListener(options: DmListenerOptions): Promise<DmListener>;

/**
 * Listen module — integration interface, implementations, and DM listener loop.
 */

type index_ClaudeOrchestrator = ClaudeOrchestrator;
declare const index_ClaudeOrchestrator: typeof ClaudeOrchestrator;
type index_ClaudeOrchestratorOptions = ClaudeOrchestratorOptions;
type index_DmListener = DmListener;
type index_DmListenerOptions = DmListenerOptions;
type index_OpenClawOrchestrator = OpenClawOrchestrator;
declare const index_OpenClawOrchestrator: typeof OpenClawOrchestrator;
type index_OpenClawOrchestratorOptions = OpenClawOrchestratorOptions;
type index_Orchestrator = Orchestrator;
type index_PromptContext = PromptContext;
declare const index_startDmListener: typeof startDmListener;
declare namespace index {
  export { index_ClaudeOrchestrator as ClaudeOrchestrator, type index_ClaudeOrchestratorOptions as ClaudeOrchestratorOptions, type index_DmListener as DmListener, type index_DmListenerOptions as DmListenerOptions, index_OpenClawOrchestrator as OpenClawOrchestrator, type index_OpenClawOrchestratorOptions as OpenClawOrchestratorOptions, type index_Orchestrator as Orchestrator, type index_PromptContext as PromptContext, index_startDmListener as startDmListener };
}

export { AuthHeaders, ChatSession, ClaudeOrchestrator, type ClaudeOrchestratorOptions, CliConfig, CliCredentials, ConfigStore, DmCryptoContext, type DmListener, type DmListenerOptions, FileConfigStore, OpenClawOrchestrator, type OpenClawOrchestratorOptions, type Orchestrator, type PromptContext, agents, deviceFlow, documentsNode, index as listen, projects, sessions, startDmListener };
