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

/**
 * Upload a local file by path. Handles readFileSync + basename + Blob + uploadFile.
 * Convenience wrapper for CLI/TUI consumers that work with file system paths.
 */
declare function uploadLocalFile(auth: AuthHeaders, workspaceId: string, filePath: string, options?: UploadOptions): Promise<UploadResult & {
    fileName: string;
}>;
/**
 * Upload all supported files from a directory, preserving folder structure.
 * Files are grouped by their relative folder path and uploaded per group.
 */
declare function uploadDirectory(auth: AuthHeaders, workspaceId: string, dirPath: string): 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.
 */
declare function uploadZip(auth: AuthHeaders, workspaceId: string, zipPath: string): Promise<UploadBatchResult>;

declare const documentsNode_uploadDirectory: typeof uploadDirectory;
declare const documentsNode_uploadLocalFile: typeof uploadLocalFile;
declare const documentsNode_uploadZip: typeof uploadZip;
declare namespace documentsNode {
  export { documentsNode_uploadDirectory as uploadDirectory, documentsNode_uploadLocalFile as uploadLocalFile, documentsNode_uploadZip as uploadZip };
}

/**
 * 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 };
}

/**
 * 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, _context?: PromptContext): 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;
}
declare class OpenClawOrchestrator implements Orchestrator {
    readonly name = "openclaw";
    private readonly binaryPath;
    private readonly agentId;
    private readonly sessionKey;
    private readonly timeoutMs;
    constructor(options: OpenClawOrchestratorOptions);
    prompt(prompt: string, _context?: PromptContext): 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, sessions, startDmListener };
