/** In-memory session — always has masterKeyExportedB64 populated. */ interface OpenMatesSession { apiUrl: string; sessionId: string; wsToken: string | null; cookies: Record; masterKeyExportedB64: string; emailEncryptionKeyB64?: string | null; hashedEmail: string; userEmailSalt: string; createdAt: number; authorizerDeviceName: string | null; autoLogoutMinutes: number | null; activeTeamId?: string | null; } /** * Raw chat record from the WS phase3 payload. * All encrypted_* fields are stored as-is (base64 ciphertext). * Plaintext metadata (id, timestamps, versions) is stored for indexing. */ interface CachedChat { /** chat_details object as received from the WS — all encrypted fields preserved */ details: Record; /** Stringified message JSON objects — stored encrypted */ messages: string[]; } interface CachedEmbed { [key: string]: unknown; } interface CachedEmbedKey { [key: string]: unknown; } interface CachedChatKeyWrapper { [key: string]: unknown; } interface CachedNewChatSuggestion { [key: string]: unknown; } interface SyncCache { /** Timestamp of last successful sync */ syncedAt: number; /** Total chat count as reported by the server */ totalChatCount: number; /** Number of chats loaded (may be less than total if paginated) */ loadedChatCount: number; /** Chats with encrypted fields preserved */ chats: CachedChat[]; /** Embeds with encrypted fields preserved */ embeds: CachedEmbed[]; /** Embed keys for embed decryption */ embedKeys: CachedEmbedKey[]; /** Chat key wrappers for wrapper-first chat decryption */ chatKeyWrappers?: CachedChatKeyWrapper[]; /** * New chat suggestions from the last sync. * Each entry has id, chat_id, encrypted_suggestion, created_at. * Decrypted on-demand with the master key. */ newChatSuggestions?: CachedNewChatSuggestion[]; } interface WsEnvelope { type: string; payload: T; } interface ForceLogoutPayload { reason?: string; revoked_session_id?: string | null; } interface ProjectRemoteAccessRequestFrame { request_id: string; project_id: string; source_id: string; source_session_id: string; requesting_client_id: string; operation: "list" | "search" | "read_text"; key_epoch: number; encrypted_envelope: string; routing_identity?: { context_type: string; context_id_hash: string; host_member_hash: string; host_device_fingerprint_hash: string; requester_member_hash: string; requester_device_fingerprint_hash: string; }; } /** Streaming event dispatched for each chunk or lifecycle event. */ interface StreamEvent { /** Event type. */ kind: "typing" | "chunk" | "done"; /** Cumulative content so far (only on chunk/done). */ content: string; /** AI category (e.g. "general_knowledge"). */ category: string | null; /** Human-readable model name. */ modelName: string | null; } type AiResponseTokenUsage = { promptTokens?: number; completionTokens?: number; userInputTokens?: number; systemPromptTokens?: number; totalCredits?: number; }; type AiResponsePromptBudget = { systemPromptTokens?: number; }; interface ChatCompressionCheckpointEvent { chatId: string; taskId: string | null; checkpointId: string; summaryContent: string; compressedUpToTimestamp: number; compressedMessageCount: number; summaryTokenEstimate: number | null; } interface SendEmbedDataFrame { embed_id: string; type?: string; content?: string; status?: string; text_preview?: string; chat_id?: string; message_id?: string; user_id?: string; embed_ids?: string[]; parent_embed_id?: string | null; task_id?: string; version_number?: number; file_path?: string; content_hash?: string; text_length_chars?: number; is_private?: boolean; is_shared?: boolean; createdAt?: number; updatedAt?: number; version_history_rows?: Array<{ embed_id: string; version_number: number; snapshot?: string; patch?: string; created_at?: number; }>; } type SubChatEventType = "spawn_sub_chats" | "sub_chat_progress" | "sub_chat_confirmation_required" | "sub_chat_confirmation_resolved" | "awaiting_sub_chats_completion" | "sub_chat_completed" | "awaiting_user_input"; interface SubChatEvent { type: SubChatEventType; payload: Record; } interface AppSettingsMemoriesRequestEvent { requestId: string | null; chatId: string; requestedKeys: string[]; payload: Record; } interface TaskProposalEvent { title: string; description?: string | null; status?: "backlog" | "todo" | "in_progress" | "blocked" | "done"; assignee_type?: "ai" | "user"; } interface TaskUpdateProposalEvent { task_id: string; title?: string | null; description?: string | null; status?: "backlog" | "todo" | "in_progress" | "blocked" | "done" | null; assignee_type?: "ai" | "user" | null; } interface TaskEventFrame { event_id: string; chat_id: string; task_id: string; short_id?: string | null; event_type: string; title?: string | null; status?: string | null; reason?: string | null; created_at?: number | null; task_update_job_id?: string | null; } interface PendingTaskUpdateJobFrame { job_id: string; task_id: string; chat_id?: string | null; revision: number; task_key_version: number; expires_at: number; } interface LocalConnectorRequestFrame { type: "local_connector_request"; connector_session_id: string; connected_account_id: string; request_id: string; action: string; arguments?: Record; } declare class OpenMatesWsClient { private readonly socket; private readonly passiveTaskUpdateJobs; private activeResponseCollectors; constructor(options: { apiUrl: string; sessionId: string; wsToken: string | null; refreshToken: string | null; userAgent?: string; cookies?: Record; taskUpdateJobs?: boolean; onForceLogout?: (payload: ForceLogoutPayload) => void | Promise; }); open(timeoutMs?: number): Promise; close(): void; send(type: string, payload: unknown): void; sendAsync(type: string, payload: unknown): Promise; onLocalConnectorRequest(handler: (payload: LocalConnectorRequestFrame) => void | Promise): () => void; onProjectRemoteAccessRequest(handler: (payload: ProjectRemoteAccessRequestFrame) => void | Promise): () => void; waitForClose(): Promise<{ code: number; reason: string; }>; private bufferPassiveTaskUpdateJobs; private handleForceLogout; drainPassiveTaskUpdateJobs(): PendingTaskUpdateJobFrame[]; waitForMessage(expectedType: string, predicate?: (payload: unknown) => boolean, timeoutMs?: number): Promise; /** * Collect all frames until `terminatorType` arrives (or timeout). * Returns every frame received before the terminator, in order. * Used by ensureSynced to consume the full phased-sync event stream. */ collectMessages(terminatorType: string, timeoutMs?: number): Promise; /** * Collect the AI response for a sent message. * * The server has two delivery paths: * * 1. Active-chat path (chat is set as active on this device via set_active_chat): * Sends incremental `ai_message_update` frames with `full_content_so_far`. * The final frame has `is_final_chunk: true`. * * 2. Background path (chat is not marked active — the CLI default unless we * explicitly call set_active_chat first): * Sends a single `ai_background_response_completed` frame with `full_content` * and the user_message_id. No incremental chunks. * * We listen for both simultaneously and resolve on whichever arrives first. */ /** Result from collectAiResponse including metadata from the stream. */ collectAiResponse(userMessageId: string, chatId: string, options?: { timeoutMs?: number; asyncEmbedWaitMs?: number; onStream?: (event: StreamEvent) => void; onSubChatEvent?: (event: SubChatEvent) => void | Promise; onAppSettingsMemoriesRequest?: (event: AppSettingsMemoriesRequestEvent) => void | Promise; recoveryTurnId?: string | null; }): Promise<{ status: "completed" | "waiting_for_user"; messageId: string | null; taskId: string | null; content: string; category: string | null; modelName: string | null; followUpSuggestions: string[]; newChatSuggestions: string[]; chatSummary: string | null; chatTags: string[]; updatedChatTitle: string | null; taskProposals: TaskProposalEvent[]; taskUpdateProposals: TaskUpdateProposalEvent[]; taskEvents: TaskEventFrame[]; pendingTaskUpdateJobs: PendingTaskUpdateJobFrame[]; embeds: SendEmbedDataFrame[]; subChatEvents: SubChatEvent[]; recoveryJobId: string | null; compressionCheckpoints: ChatCompressionCheckpointEvent[]; tokenUsage: AiResponseTokenUsage | null; promptBudget: AiResponsePromptBudget | null; }>; } interface SignupCryptoMaterial { hashedEmail: string; encryptedEmail: string; encryptedEmailWithMasterKey: string; userEmailSaltB64: string; emailEncryptionKeyB64: string; masterKeyB64: string; encryptedMasterKey: string; keyIv: string; saltB64: string; lookupHash: string; } interface RecoveryKeyMaterial { recoveryKey: string; lookupHash: string; wrappedMasterKey: string; keyIv: string; saltB64: string; } interface ApiKeyCryptoMaterial { apiKey: string; apiKeyHash: string; encryptedName: string; encryptedKeyPrefix: string; encryptedMasterKey: string; keyIv: string; saltB64: string; } /** Minimal model info needed for mention resolution */ interface ModelInfo { id: string; name: string; providerId?: string; } /** Minimal app info from /v1/apps */ interface AppInfo { id: string; name: string; skills?: Array<{ id: string; name: string; }>; focus_modes?: Array<{ id: string; name: string; }>; settings_and_memories?: Array<{ id: string; name: string; type?: string; }>; } /** Minimal memory entry info */ interface MemoryEntryInfo { id: string; app_id: string; item_type: string; title?: string; } /** All data needed to resolve mentions */ interface MentionContext { models: ModelInfo[]; mates: Record; apps: AppInfo[]; memoryEntries: MemoryEntryInfo[]; } /** * @file Embed creation pipeline for the CLI — generates encrypted embeds * with proper key wrapping, matching the web app's zero-knowledge architecture. * * For each embed: * 1. Content is TOON-encoded (or JSON-fallback) * 2. A random AES-256 embed key is generated * 3. Content, type, and text_preview are encrypted with the embed key * 4. The embed key is wrapped with both master key and chat key * 5. SHA-256 hashes are computed for all IDs * 6. The encrypted embed + wrapped keys are attached to chat_message_added * * Mirrors: cryptoService.ts (encryptWithEmbedKey, wrapEmbedKeyWithMasterKey, * wrapEmbedKeyWithChatKey, generateEmbedKey) * chatSyncServiceSenders.ts (encrypted_embeds construction) * * Architecture: docs/architecture/embeds.md */ /** A prepared embed ready for encryption and sending */ interface PreparedEmbed { embedId: string; embedRef?: string; type: string; content: string; textPreview: string; status: string; filePath?: string; contentHash?: string; textLengthChars?: number; } /** A fully encrypted embed ready for the WebSocket payload */ interface EncryptedEmbed { embed_id: string; encrypted_type: string; encrypted_content: string; encrypted_text_preview: string; status: string; hashed_chat_id: string; hashed_message_id: string; hashed_user_id: string; embed_ids?: string[]; file_path?: string; content_hash?: string; text_length_chars?: number; created_at: number; updated_at: number; embed_keys: EmbedKeyWrapper[]; } /** A wrapped embed key for storage */ interface EmbedKeyWrapper { hashed_embed_id: string; key_type: "master" | "chat"; hashed_chat_id: string | null; encrypted_embed_key: string; hashed_user_id: string; created_at: number; } /** * @file Share encryption for chat and embed share links. * * Direct Node.js port of: * - frontend/packages/ui/src/services/shareEncryption.ts (chat) * - frontend/packages/ui/src/services/embedShareEncryption.ts (embed) * * The algorithm is identical — same PBKDF2 parameters, same AES-GCM IV * format, same URL-encoded blob serialization, same base64url encoding. * Any divergence here would produce share links that the web app cannot * decrypt. * * URL format: * Chat: {origin}/share/chat/{chatId}#key={encryptedBlob} * Embed: {origin}/share/embed/{embedId}#key={encryptedBlob} * * Architecture: docs/architecture/share_chat.md */ type ShareDuration = 0 | 60 | 3600 | 86400 | 604800 | 1209600 | 2592000 | 7776000; interface ConnectedAccountCliTransferPayload { version: 1; provider_id: string; app_id: string; label: string; account_ref?: string; capabilities: string[]; runtime_modes: Record; refresh_token_bundle: Record; created_at: string; } declare const PROTON_BRIDGE_PROVIDER_ID = "protonmail_bridge"; declare const PROTON_BRIDGE_APP_ID = "mail"; interface ProtonLocalConnectorRegistration { provider_id: typeof PROTON_BRIDGE_PROVIDER_ID; app_id: typeof PROTON_BRIDGE_APP_ID; connector_instance_id: string; label: string; capabilities: string[]; execution_mode: "local_connector"; status: "online"; metadata: { bridge_host: "localhost"; bridge_transport: "imap_smtp"; capabilities: string[]; write_delay_seconds?: number; }; } interface CliSubChatRequest { id?: string; chat_id?: string; user_message_id?: string; message_id?: string; prompt?: string; wait_for_completion?: boolean; } interface SubChatApprovalRequest { chatId: string; taskId: string; subChats: CliSubChatRequest[]; maxAutoSubChats: number | null; maxDirectSubChats: number | null; existingSubChats: number | null; remainingSubChats: number | null; } interface ConnectedAccountDirectoryEntry { connected_account_id: string; app_id: string; provider_id?: string; account_ref: string; label: string; capabilities: string[]; runtime_modes?: Record; } interface ConnectedAccountTurnTokenRefInput { connected_account_id: string; app_id: string; provider_id?: string; allowed_actions: string[]; refresh_token_envelope: Record; action_scope?: Record; } interface ConnectedAccountTurnTokenRef { connected_account_id: string; app_id: string; provider_id?: string; turn_token_ref: string; allowed_actions: string[]; action_scope?: Record; expires_at: number; } interface ConnectedAccountImportValidationResult { valid: boolean; provider_id: string; app_id: string; checked_at: number; } interface ConnectedAccountImportResult { id: string; providerId: string; appId: string; label: string; validation: ConnectedAccountImportValidationResult; } interface DecryptedConnectedAccountForSkill { id: string; providerId: string; appId: string; label: string; accountRef: string; capabilities: string[]; runtimeModes: Record; refreshTokenBundle: Record; } interface RevolutBusinessSetupExchangeResult { provider_id: "revolut_business"; app_id: "finance"; environment: "sandbox" | "production"; refresh_token_bundle: Record; account_hint: { label?: string; account_ref?: string; account_count?: number; [key: string]: unknown; }; } type TeamRole = "owner" | "admin" | "member" | "viewer"; interface TeamRecord { team_id?: string; slug?: string | null; encrypted_name?: string; encrypted_description?: string | null; role?: TeamRole; status?: string; [key: string]: unknown; } interface TeamBillingSummary { balance_credits?: number; encrypted_balance?: string | null; [key: string]: unknown; } type WorkspaceMoveType = "chat" | "project" | "task" | "plan" | "workflow"; interface TeamContextOptions { teamId?: string | null; personal?: boolean; } interface AccountExportStartOptions { domains?: string[]; filters?: Record; format?: "zip" | "directory"; includeAdvancedMetadata?: boolean; } interface AccountExportResponse { export: Record; } interface AccountExportManifestResponse { manifest: Record; } interface AccountExportChunksResponse { chunks: Array>; } interface AccountImportPreviewRequest { source: "openmates" | "chatgpt" | "claude" | "gemini" | "opencode" | "other"; parserFormat?: "claude" | "chatgpt" | "openmates" | "opencode" | "generic"; chatCount: number; sourceFingerprints: string[]; estimatedTokens?: number; estimatedTokensByChat?: number[]; estimatedBytes?: number; } interface AccountImportScanRequest { batchId: string; sequence: number; finalBatch: boolean; chats: Array>; } interface AccountImportCompressRequest { batchId: string; sequence: number; finalBatch: boolean; scanSequence: number; sourceFingerprint: string; sanitizedMessages: Array>; priorSummary?: string; } interface AccountImportPreviewResponse extends Record { free_remaining?: number; chat_limit?: number; default_selection_count?: number; max_batch_count?: number; duplicate_fingerprints?: string[]; estimated_credits?: number; can_import?: boolean; reason?: string; } interface AccountImportScanResponse extends Record { chats?: Array>; credits_reserved?: number; messages_blocked?: Array>; failures?: Array>; } interface AccountImportCompleteRequest { importedChatIds: string[]; sourceFingerprints: string[]; encryptedRecordCounts: Record; clientFailures?: Array>; } interface AccountImportCompleteResponse extends Record { status?: "complete" | "partial" | "failed"; credits_charged?: number; credits_released?: number; imported_count?: number; failures?: Array>; } interface AccountImportEncryptedPersistResponse extends Record { status?: "complete" | "partial" | "failed"; imported_chat_ids?: string[]; failures?: Array>; encrypted_record_counts?: Record; } interface ParsedImportChat { selected_source?: string; title?: string | null; created_at?: string | null; updated_at?: string | null; source_fingerprint?: string; messages: Array<{ role: "user" | "assistant" | "system"; content: string; created_at?: string | null; imported_assistant_identity?: { category: string; sender_name: string; model_name: string; avatar_key: string; } | null; provider_metadata?: Record; }>; } interface TeamCreateInput { name?: string; description?: string | null; slug?: string | null; teamId?: string; encryptedName?: string; encryptedDescription?: string | null; encryptedProfileImageMetadata?: string; profileImageMetadata?: Record; encryptedTeamKey?: string; encryptedZeroBalance?: string; createdAt?: number; } interface TeamGeneratedProfileImageInput { iconName?: string; backgroundColor?: string; } interface TeamUploadedProfileImageResult { status: string; url: string; team: TeamRecord; } interface TeamInviteCreateInput extends Record { role?: Exclude; recipient_email?: string; invite_id?: string; invite_secret?: string; } interface TeamInviteAcceptInput { inviteSecret?: string | null; recipientEmail?: string | null; } type LearningModeAgeGroup = "under_10" | "10_12" | "13_15" | "16_18" | "adult"; interface LearningModeStatus { enabled: boolean; age_group: LearningModeAgeGroup | null; failed_attempts: number; deactivation_blocked_until: number | null; } interface LearningModeContext { enabled: boolean; ageGroup?: LearningModeAgeGroup | null; source?: "anonymous_session"; } type WorkflowNodeType = "schedule_trigger" | "manual_trigger" | "webhook_trigger" | "app_skill_action" | "decision" | "repeat" | "create_chat_report" | "send_notification" | "send_email_notification" | "ask_user" | "custom_code" | "end"; interface WorkflowNode { id: string; type: WorkflowNodeType; title?: string | null; config?: Record; input_mapping?: Record; ui?: Record; } interface WorkflowEdge { from: string; to: string; branch?: string | null; } interface WorkflowGraph { version: number; trigger_node_id: string; nodes: WorkflowNode[]; edges?: WorkflowEdge[]; variables?: Record; limits?: Record; ui_layout?: Record; } type WorkflowRunContentRetention = "last_5" | "none"; type WorkflowRunContentStorage = "durable" | "ephemeral" | "deleted"; type WorkflowLifecycle = "persisted" | "temporary"; interface WorkflowSummary { id: string; slug?: string | null; encrypted_slug?: string | null; slug_lookup_hash?: string | null; title: string; description?: string | null; status: "draft" | "active" | "disabled" | "error" | "deleted"; enabled: boolean; lifecycle?: WorkflowLifecycle; source?: string; source_chat_id?: string | null; created_by_assistant?: boolean; auto_delete_at?: number | null; kept_at?: number | null; trigger_summary?: string | null; next_run_at?: number | null; last_run_status?: "queued" | "running" | "waiting" | "completed" | "failed" | "cancelled" | null; run_content_retention?: WorkflowRunContentRetention; current_version_id: string; created_at: number; updated_at: number; } interface WorkflowDetail extends WorkflowSummary { graph: WorkflowGraph; } interface WorkflowNodeRun { id: string; run_id: string; workflow_id: string; node_id: string; node_type: WorkflowNodeType; status: "queued" | "running" | "completed" | "skipped" | "failed"; started_at?: number | null; finished_at?: number | null; skipped_reason?: string | null; error_code?: string | null; error_summary?: string | null; input_summary?: Record; output_summary?: Record; credit_cost?: number; } type UserTaskStatus = "backlog" | "todo" | "in_progress" | "blocked" | "done"; type UserTaskAssigneeType = "ai" | "user"; type ProjectSourceType = "local_folder" | "local_git_repository" | "remote_folder" | "remote_git_repository"; type ProjectSourceCapability = "read" | "search" | "import" | "write_request"; type ProjectSourceStatus = "connected" | "offline" | "permission_required" | "revoked"; interface ProjectRecord { project_id: string; encrypted_project_key?: string | null; encrypted_slug?: string | null; slug_lookup_hash?: string | null; encrypted_name?: string | null; encrypted_description?: string | null; encrypted_icon?: string | null; encrypted_color?: string | null; pinned?: boolean; archived?: boolean; version?: number; created_at?: number; updated_at?: number; last_opened_at?: number; key_wrappers?: ProjectKeyWrapperRecord[]; mutation_permissions?: ProjectMutationPermissions; [key: string]: unknown; } interface ProjectKeyWrapperRecord { key_type: "master" | "chat" | "project" | "plan" | "team"; encrypted_project_key: string; hashed_team_id?: string | null; team_key_epoch?: number | null; [key: string]: unknown; } interface ProjectMutationPermissions { create: boolean; update: boolean; archive: boolean; delete: boolean; settings: boolean; manage_any_items: boolean; manage_any_sources: boolean; manage_own_items: boolean; manage_own_sources: boolean; } interface ProjectDetail { project: ProjectRecord; folders: Array>; items: ProjectItemRecord[]; } interface ProjectRemoteAccessRequestInput { request_id: string; requesting_client_id: string; operation: "list" | "search" | "read_text"; key_epoch: number; encrypted_envelope: string; } interface ProjectRemoteAccessRequestResult { request_id: string; status: "queued" | "delivered"; source_session_id: string; key_epoch: number; routing_identity?: Record; } interface ProjectSourceRecord { source_id: string; source_type: ProjectSourceType; encrypted_display_name: string; encrypted_metadata: string; capabilities?: ProjectSourceCapability[]; status?: ProjectSourceStatus; created_at?: number; updated_at?: number; last_indexed_at?: number | null; [key: string]: unknown; } type ProjectSourceCreateInput = ProjectSourceRecord; type ProjectItemType = "embed" | "chat" | "upload" | "workflow"; interface ProjectItemRecord { project_item_id: string; item_type: ProjectItemType; target_id_hash?: string; target_id_encrypted: string; encrypted_display_name?: string | null; encrypted_note?: string | null; encrypted_metadata?: string | null; created_at?: number; updated_at?: number; position?: number; [key: string]: unknown; } interface ProjectItemCreateInput { project_item_id: string; folder_id?: string | null; item_type: ProjectItemType; target_id: string; target_id_encrypted: string; encrypted_display_name?: string | null; encrypted_note?: string | null; encrypted_metadata?: string | null; created_at: number; updated_at: number; position?: number; } interface UserTaskRecord { task_id: string; source?: string | null; projection_kind?: "last_run" | "current_run" | "next_run" | null; title?: string | null; read_only?: boolean | null; workflow_id?: string | null; workflow_run_id?: string | null; trigger_id?: string | null; run_status?: string | null; can_cancel?: boolean | null; can_delete?: boolean | null; scheduled_at?: number | null; blocked_reason?: string | null; blocked_message?: string | null; short_id?: string | null; short_id_prefix?: string | null; encrypted_task_key?: string | null; encrypted_slug?: string | null; slug_lookup_hash?: string | null; encrypted_title: string; encrypted_description?: string | null; encrypted_labels?: string | null; encrypted_tags?: string | null; label_hashes?: string[] | null; encrypted_linked_project_ids?: string | null; encrypted_activity_summary?: string | null; encrypted_latest_instruction?: string | null; status: UserTaskStatus; assignee_type: UserTaskAssigneeType; assignee_hash?: string | null; primary_chat_id?: string | null; linked_project_ids?: string[] | null; parent_task_id?: string | null; plan_id?: string | null; plan_step_id?: string | null; task_type?: "work" | "verification" | null; verification_id?: string | null; source_plan_id?: string | null; source_learning_id?: string | null; due_at?: number | null; priority?: number; position?: number; queue_state?: "none" | "waiting" | "active" | "skipped" | "waiting_for_user" | string | null; version?: number; created_at?: number; updated_at?: number; started_at?: number | null; completed_at?: number | null; blocked_reason_code?: string | null; ai_execution_state?: string | null; history?: WorkspaceHistoryResult | null; } interface WorkspaceHistoryResult { change_set?: Record; entries?: Array>; undo_all_command?: string; undo_entry_commands?: string[]; } interface UserTaskProposalRecord { title: string; description?: string | null; status?: UserTaskStatus; assignee_type?: UserTaskAssigneeType; } type UserTaskCreateInput = Omit & { version: number; plaintext_title?: string; plaintext_description?: string; plaintext_latest_instruction?: string; plaintext_chat_title?: string; plaintext_project_context?: string; }; type UserTaskUpdateInput = Partial> & { version: number; }; type UserTaskStartAIInput = UserTaskUpdateInput & { team_id?: string | null; plaintext_title?: string; plaintext_description?: string; plaintext_latest_instruction?: string; plaintext_chat_title?: string; }; type UserTaskActionInput = { version: number; blocked_reason_code?: string | null; team_id?: string | null; }; type UserTaskReorderInput = { moves: Array<{ task_id: string; version: number; before_task_id?: string | null; after_task_id?: string | null; status?: UserTaskStatus | null; position?: number | null; }>; }; type UserPlanStatus = "draft" | "checking_assumptions" | "awaiting_confirmation" | "active" | "executing" | "running_checks" | "blocked" | "completed" | "archived"; type UserPlanCriterionStatus = "pending" | "satisfied" | "failed" | "waived"; type UserPlanVerificationStatus = "proposed" | "pending" | "passed" | "failed" | "passed_unexpectedly" | "skipped" | "skipped_with_reason" | "not_applicable" | "waived"; type UserPlanLearningType = "workflow_improvement" | "agent_instruction_improvement"; type UserPlanLearningTargetKind = "workflow" | "project_agent_instructions"; type UserPlanLearningStatus = "draft" | "proposed" | "accepted" | "applied" | "rejected" | "duplicate" | "merged"; type UserPlanLearningLevel = "low" | "medium" | "high"; interface UserPlanRecord { plan_id: string; encrypted_plan_key?: string | null; encrypted_slug?: string | null; slug_lookup_hash?: string | null; encrypted_title: string; encrypted_summary?: string | null; encrypted_goal?: string | null; encrypted_scope_in?: string | null; encrypted_scope_out?: string | null; encrypted_user_flows?: string | null; encrypted_current_focus?: string | null; encrypted_assumptions?: string | null; encrypted_open_questions?: string | null; encrypted_constraints?: string | null; encrypted_decisions?: string | null; encrypted_risks?: string | null; encrypted_reference_patterns?: string | null; encrypted_context?: string | null; encrypted_linked_project_ids?: string | null; status: UserPlanStatus; primary_chat_id?: string | null; linked_project_ids?: string[] | null; key_wrappers?: Array> | null; current_phase_id?: string | null; current_step_id?: string | null; current_task_id?: string | null; planner_focus_id?: string | null; version?: number; created_at?: number; updated_at?: number; completed_at?: number | null; history?: WorkspaceHistoryResult | null; } type UserPlanCreateInput = Omit & { version?: number; }; type UserPlanUpdateInput = Partial> & { version?: number; }; interface UserPlanCriterionRecord { criterion_id: string; encrypted_text: string; type?: string; status?: UserPlanCriterionStatus; required?: boolean; linked_step_ids?: string[]; linked_task_ids?: string[]; verification_ids?: string[]; created_at?: number; updated_at?: number; } interface UserPlanAssumptionRecord { assumption_id: string; encrypted_text: string; category?: string; status?: string; required_before?: string; linked_sub_chat_id?: string | null; linked_task_id?: string | null; linked_step_ids?: string[]; linked_criterion_ids?: string[]; source_count?: number; encrypted_corrected_text?: string | null; encrypted_evidence_summary?: string | null; encrypted_blocker_reason?: string | null; encrypted_waiver_reason?: string | null; encrypted_sources?: string | null; created_at?: number; updated_at?: number; } interface UserPlanReferencePatternRecord { pattern_id: string; encrypted_title: string; encrypted_description?: string | null; category?: string; status?: string; required_before?: string; source_count?: number; linked_task_ids?: string[]; linked_check_ids?: string[]; encrypted_sources?: string | null; encrypted_match_rules?: string | null; encrypted_anti_patterns?: string | null; encrypted_evidence_summary?: string | null; encrypted_waiver_reason?: string | null; created_at?: number; updated_at?: number; } interface UserPlanLearningRecord { learning_id: string; type: UserPlanLearningType; target_kind: UserPlanLearningTargetKind; status?: UserPlanLearningStatus; severity?: UserPlanLearningLevel | null; confidence?: UserPlanLearningLevel | null; linked_task_ids?: string[]; linked_check_ids?: string[]; applied_task_id?: string | null; encrypted_title: string; encrypted_observation?: string | null; encrypted_root_cause?: string | null; encrypted_suggested_change?: string | null; encrypted_evidence_summary?: string | null; encrypted_task_draft?: string | null; encrypted_rejection_reason?: string | null; version?: number; created_at?: number; updated_at?: number; } interface UserPlanLearningCreateTasksInput { learning_ids?: string[]; all?: boolean; created_at?: number; updated_at?: number; } interface UserPlanLearningCreateTasksResult { tasks: UserTaskRecord[]; skipped: Array>; } interface UserPlanVerificationRecord { verification_id: string; kind: string; phase?: string; status?: UserPlanVerificationStatus; required_for_done?: boolean; covers?: string[]; source_hash?: string | null; threshold?: number | null; score?: number | null; confidence?: string | null; linked_task_id?: string | null; run_id?: string | null; created_at?: number; updated_at?: number; lifecycle_status?: string | null; linked_sub_chat_id?: string | null; source_embed_id?: string | null; runner_kind?: string | null; encrypted_description?: string | null; encrypted_command?: string | null; encrypted_evaluation_prompt?: string | null; encrypted_evaluator_instructions?: string | null; encrypted_expected_result?: string | null; encrypted_source_path?: string | null; encrypted_red_phase_reason?: string | null; encrypted_result_summary?: string | null; encrypted_required_fixes?: string | null; } interface WorkflowRunDetail { id: string; workflow_id: string; version_id: string; trigger_type: string; status: "queued" | "running" | "waiting" | "cancellation_requested" | "completed" | "failed" | "cancelled"; started_at?: number | null; finished_at?: number | null; error_summary?: string | null; cost_summary?: Record; content_retention_mode?: WorkflowRunContentRetention; content_available?: boolean; content_storage?: WorkflowRunContentStorage | null; content_expires_at?: number | null; encrypted_content_ref?: string | null; encrypted_content_checksum?: string | null; node_runs?: WorkflowNodeRun[]; output_summary?: Record; } interface WorkflowRunCancellationResult { run_id: string; status: "cancellation_requested" | "cancelled"; } type WorkflowInputType = "text" | "audio"; interface WorkflowInputStartParams { text?: string | null; inputType?: WorkflowInputType; audioRef?: Record | null; selectedWorkflowId?: string | null; selectedProjectId?: string | null; } interface WorkflowInputEvent { id: string; session_id: string; event_id: number; type: string; status: string; redacted_summary: string; payload?: Record; created_at: number; } interface WorkflowInputSessionResult { session_id: string; status: string; event_cursor: number; message?: string | null; error?: string | null; workflow?: WorkflowDetail | null; project_item?: Record | null; undo_available: boolean; } interface WorkflowInputSessionDetail extends WorkflowInputSessionResult { events: WorkflowInputEvent[]; draft_graph?: Record | null; mutations?: Array>; } interface WorkflowCapability { type: "node" | "app_skill" | "workflow"; id: string; title: string; enabled: boolean; reason?: string | null; metadata?: Record; } interface WorkflowTemplateProjectionUpsertParams { templateId: string; sourceVersion: number; ciphertext: string; ciphertextChecksum: string; ownerWrappedKey: string; projectionSchemaVersion: number; } interface WorkflowTemplateProjectionResult { template_id: string; source_version: number; updated_at: number; } interface PublicWorkflowTemplateProjection { template_id: string; ciphertext: string; ciphertext_checksum: string; projection_schema_version: number; } interface WorkflowTemplateProjectionRevocationResult { template_id: string; revoked_at: number | null; } interface WorkflowTemplateBindingCompletionParams { type: string; nodeId: string; } interface WorkflowTemplateBindingCompletionResult { workflow_id: string; binding_requirement: Record; completed: boolean; } interface WorkflowTemplateImportPayload { template_version: number; title: string; description?: string | null; trigger_template: Record; node_templates?: Array>; edge_templates?: Array>; variables_schema?: Record; required_capabilities?: string[]; binding_requirements?: Array>; } interface ImportedWorkflowTemplate extends WorkflowDetail { binding_requirements: Array>; } interface WorkflowTemplateShortUrlParams { token: string; encryptedUrl: string; templateId: string; ttlSeconds?: number | null; passwordProtected?: boolean; } interface WorkflowTemplateShortUrlResult { success: boolean; expires_at?: number | null; } interface ShortUrlRevokeResult { success: boolean; revoked_at?: number | null; } type InterestTagId = "marketing" | "software_development" | "finance_bookkeeping" | "ui_ux_design" | "business_planning" | "content_creation" | "project_management" | "admin_operations" | "find_local_events" | "plan_trips" | "writing_editing" | "sales" | "customer_support" | "research_analysis" | "data_spreadsheets" | "legal_compliance" | "events_networking" | "websites_online_shops" | "automation_workflows" | "client_work_proposals" | "branding_images" | "video_social_media" | "productivity_organization" | "learning_new_skills" | "health_wellbeing" | "find_doctor_appointments" | "find_apartments" | "find_trains_flights" | "find_restaurants_cafes" | "personal_finances" | "cooking_meal_planning" | "news_current_events" | "diy_electronics" | "privacy_personal_data"; interface TopicPreferencesPayload { version: 1; selectedTagIds: InterestTagId[]; updatedAt: string; } declare const INTEREST_TAG_IDS: InterestTagId[]; declare function normalizeInterestTagIds(values: readonly string[]): InterestTagId[]; /** A single field definition within a memory type schema. */ interface MemoryFieldDef { type: string; description?: string; enum?: string[]; auto_generated?: boolean; } /** Schema definition for one memory type. */ interface MemoryTypeDef { appId: string; itemType: string; entryType: "single" | "list"; required: string[]; properties: Record; } /** * Registry of all production-stage memory types across all apps. * Keys are `${appId}/${itemType}`. * * Keep in sync with backend/apps/{app}/app.yml memory sections. * Auto-generated fields (added_date etc.) are excluded from user-visible fields. */ declare const MEMORY_TYPE_REGISTRY: Record; interface ChatListItem { id: string; shortId: string; slug?: string | null; title: string | null; summary: string | null; updatedAt: number | null; category: string | null; mateName: string | null; source?: "example"; } /** A single parameter extracted from the OpenAPI skill schema. */ interface SkillParam { name: string; type: string; description: string; required: boolean; default?: unknown; inputShape?: "requests" | "flat"; } interface ChatListPage { chats: ChatListItem[]; total: number; page: number; limit: number; hasMore: boolean; } interface EncryptedDraft { chatId: string; encryptedDraftMd: string; encryptedDraftPreview: string | null; draftV: number; } interface DecryptedDraft extends EncryptedDraft { markdown: string; preview: string | null; } interface IdeaBucketAddResult { chatId: string; bucketId: string; processingWindowId: string; scheduledSendAt: number; draftV: number; processingPayloadSynced: boolean; payloadHash: string; markdown: string; preview: string; } interface IdeaBucketSettingsInput { processingPrompt?: string; processingTimes?: string[] | string; } interface IdeaBucketSettings { processingPrompt: string; processingTimes: string[]; entryId?: string; itemVersion?: number; source: "account" | "default"; } interface IdeaBucketStatusResult { processingWindowId?: string; status: string; buckets?: Array>; [key: string]: unknown; } interface IdeaBucketProcessResult { processingWindowId: string; status: string; chatId?: string; userMessageId?: string; systemEventId?: string; aiTaskId?: string | null; errorCode?: string; } interface AuthoritativeChatReconciliation { authoritative: boolean; authoritative_chat_ids?: string[]; deleted_chat_ids?: string[]; } declare function reconcileAuthoritativeChats(chats: CachedChat[], evidence: AuthoritativeChatReconciliation): CachedChat[]; interface BenchmarkMetadata { source: "benchmark"; benchmark_run_id: string; benchmark_suite: string; benchmark_case: string; benchmark_target_model: string; benchmark_judge_model?: string; } interface BenchmarkHistoryMessage { message_id: string; role: "user" | "assistant" | "system"; sender_name: string; content: string; created_at: number; chat_id?: string; category?: string | null; } /** Decrypted message for display */ interface DecryptedMessage { id: string; chatId: string; role: string; content: string; senderName: string | null; category: string | null; modelName: string | null; createdAt: number; embedIds: string[]; } interface ChatMessageSummary extends DecryptedMessage { preview: string; } type ChatMessageWindowDirection = "latest" | "before" | "after" | "around"; interface ChatMessageWindowCursor { created_at: number; message_id: string; } interface ChatMessageWindowOptions extends TeamContextOptions { direction?: ChatMessageWindowDirection; limit?: number; beforeTimestamp?: number; beforeMessageId?: string; afterTimestamp?: number; afterMessageId?: string; anchorMessageId?: string; respectCompressionBoundary?: boolean; } interface ChatMessageWindowResult { chat: ChatListItem; messages: DecryptedMessage[]; hasMoreBefore: boolean; hasMoreAfter: boolean; startCursor: ChatMessageWindowCursor | null; endCursor: ChatMessageWindowCursor | null; anchorFound: boolean; serverMessageCount: number | null; } interface ChatForkResult { success: boolean; source_chat_id: string; chat_id: string; copied_message_count: number; messages_v: number; } interface ChatRewindResult { success: boolean; dry_run: boolean; chat_id: string; to_message_id: string; deleted_message_ids?: string[]; deleted_message_count?: number; planned_deleted_message_ids?: string[]; planned_deleted_message_count?: number; messages_v: number; resulting_messages_v?: number; response?: Awaited>; } /** Decrypted embed summary for display */ interface DecryptedEmbed { id: string; embedId: string; type: string | null; textPreview: string | null; content: Record | null; appId: string | null; skillId: string | null; createdAt: number | null; } interface EmbedVersionMeta { version_number: number; created_at: number; has_snapshot: boolean; has_patch: boolean; encrypted_snapshot?: string | null; encrypted_patch?: string | null; } interface EmbedVersionsResponse { embed_id: string; current_version: number; versions: EmbedVersionMeta[]; readonly: boolean; } interface EmbedVersionContentResponse { embed_id: string; version_number: number; current_version: number; content?: string; rows?: EmbedVersionMeta[]; readonly: boolean; } interface EmbedVersionRestoreResponse { embed_id: string; restored_from_version: number; version_number: number; content: string; content_hash: string; } interface ApplicationPreviewStartParams { embedId: string; chatId: string; sharedContext?: string; requestedRuntime?: string; sourceMessageId?: string; } interface ApplicationPreviewStartResponse { session_id: string; preview_url: string; status: string; credits_per_minute: number; } interface ApplicationPreviewEvent { kind: string; text: string; timestamp: number; } interface ApplicationPreviewStatusResponse { session_id: string; status: string; events: ApplicationPreviewEvent[]; error?: string | null; charged_credits?: number | null; latest_screenshot_url?: string | null; latest_screenshot?: Record | null; auto_started: boolean; auto_opened_at?: number | null; } interface ApplicationPreviewStopResponse { session_id: string; status: string; charged_credits?: number | null; } /** Video metadata attached to a daily inspiration. */ interface DailyInspirationVideo { youtube_id: string; title: string; thumbnail_url: string; channel_name: string | null; view_count: number | null; duration_seconds: number | null; published_at: string | null; } /** * A daily inspiration as returned by the CLI. * * Public inspirations (unauthenticated) come cleartext from * GET /v1/default-inspirations. * * Authenticated inspirations come encrypted from * GET /v1/daily-inspirations and are decrypted with the master key. */ interface DailyInspiration { id: string; phrase: string; title: string; assistant_response: string; category: string; content_type: string; video: DailyInspirationVideo | null; generated_at: number; follow_up_suggestions: string[]; /** Whether the user has already opened this inspiration into a chat. */ is_opened?: boolean; } /** * English mate names by category — matches the web app's i18n mates.* keys. * The CLI ships without the full i18n system, so we hardcode English names. */ declare const MATE_NAMES: Record; /** * A decrypted new-chat suggestion as returned to CLI callers. * * Mirrors the format used by NewChatSuggestions.svelte in the web app. * The `body` text is the plain text to insert into the message input. */ interface DecryptedNewChatSuggestion { id: string; chatId: string | null; body: string; createdAt: number; } /** A decrypted memory entry as returned to CLI callers. */ interface DecryptedMemoryEntry { id: string; app_id: string; item_type: string; item_key_hash: string; item_version: number; created_at: number; updated_at: number; /** Decrypted item_value fields including _original_item_key. */ data: Record; } interface OpenMatesClientOptions { apiUrl?: string; session?: OpenMatesSession; } interface InvoiceListItem { id: string; order_id?: string | null; date: string; amount: string; credits_purchased: number; filename: string; is_gift_card?: boolean; refunded_at?: string | null; refund_status?: string | null; currency?: string | null; provider?: string | null; bank_transfer_reference?: string | null; transaction_status?: string | null; document_status?: string | null; } interface UsageOverviewOptions { granularity?: "daily" | "weekly" | "monthly"; days?: number; weeks?: number; months?: number; } interface DownloadedDocument { filename: string; data: Uint8Array; } interface BankTransferOrderDetails { order_id: string; reference: string; iban: string; bic: string; bank_name: string; account_holder_name: string; account_holder_address_line1?: string; account_holder_address_line2?: string; account_holder_postal_code?: string; account_holder_city?: string; account_holder_country?: string; amount_eur: string; credits_amount: number; expires_at: string; } interface BankTransferStatus { order_id: string; status: string; credits_amount: number; amount_eur: string; reference: string; expires_at: string; created_at?: string; } interface GiftCardBankTransferStatus extends BankTransferStatus { gift_card_code?: string | null; } interface ApiKeyCreateOptions { name: string; fullAccess?: boolean; scopes?: Record; creditLimit?: Record | null; expiresAt?: string | null; } interface CreatedApiKeyResult { api_key: string; key: unknown; crypto: ApiKeyCryptoMaterial; } interface ApiKeyRecord { id: string; name: string; key_prefix: string; created_at?: string | null; expires_at?: string | null; last_used_at?: string | null; full_access?: boolean; scopes?: Record; credit_limit?: Record | null; pending_device_count?: number; encrypted_name?: string | null; encrypted_key_prefix?: string | null; } interface ApiKeyListResult { api_keys: ApiKeyRecord[]; } interface AuthMethodsStatus { has_passkey?: boolean; has_2fa?: boolean; has_password?: boolean; has_recovery_key?: boolean; } interface CliSignupResult { success: boolean; message: string; user?: Record; crypto: SignupCryptoMaterial; } interface TotpSetupStartResult { success: boolean; message: string; secret?: string | null; otpauth_url?: string | null; } interface BackupCodesResult { success: boolean; message: string; backup_codes: string[]; } interface AnonymousFreeUsageStatus { active: boolean; reason: string | null; resetAt: string | null; cta: string | null; } /** * Derive the web app URL from the API URL so the pair token is always looked * up on the same backend the CLI created it on. * Override with OPENMATES_APP_URL when using a custom setup. */ declare function deriveAppUrl(apiUrl: string): string; declare class OpenMatesClient { readonly apiUrl: string; private session; private readonly http; constructor(options?: OpenMatesClientOptions); static load(options?: OpenMatesClientOptions): OpenMatesClient; hasSession(): boolean; getActiveTeamId(): string | null; setActiveTeamId(teamId: string | null): void; resolveTeamContext(options?: TeamContextOptions): string | null; startAccountExport(options?: AccountExportStartOptions): Promise; getAccountExport(exportId: string): Promise; getAccountExportManifest(exportId: string): Promise; listAccountExportChunks(exportId: string): Promise; getAccountExportChunk(exportId: string, chunkId: string): Promise>; completeAccountExport(exportId: string): Promise; acceptPartialAccountExport(exportId: string): Promise; cancelAccountExport(exportId: string): Promise; previewAccountImport(request: AccountImportPreviewRequest): Promise; confirmAccountImport(importId: string, selectedFingerprints: string[]): Promise>; scanAccountImport(importId: string, batch: AccountImportScanRequest): Promise; getAccountImportStatus(importId: string): Promise>; compressAccountImport(importId: string, batch: AccountImportCompressRequest): Promise>; completeAccountImport(importId: string, request: AccountImportCompleteRequest): Promise; persistEncryptedAccountImport(importId: string, chats: ParsedImportChat[]): Promise; private appendTeamQuery; listTeams(): Promise; createTeam(input: TeamCreateInput): Promise; getTeam(teamId: string): Promise; private cacheTeamKeyFromRecord; updateTeam(teamId: string, input: Record): Promise; updateTeamGeneratedProfileImage(teamId: string, input?: TeamGeneratedProfileImageInput): Promise; updateTeamProfileImage(teamId: string, filePath: string): Promise; getTeamProfileImage(teamId: string): Promise<{ contentType: string; data: Uint8Array; }>; deleteTeam(teamId: string): Promise<{ success: boolean; }>; private loadTeamKeyBytes; createTeamInvite(teamId: string, input: TeamInviteCreateInput): Promise>; getTeamInvite(inviteId: string): Promise>; acceptTeamInvite(inviteId: string, input?: TeamInviteAcceptInput): Promise>; declineTeamInvite(inviteId: string): Promise<{ success: boolean; }>; listTeamAccessRequests(teamId: string, status?: string | null): Promise[]>; approveTeamAccessRequest(teamId: string, accessRequestId: string, encryptedTeamKey?: string | null): Promise>; rejectTeamAccessRequest(teamId: string, accessRequestId: string): Promise<{ success: boolean; }>; exportTeamData(teamId: string, input?: Record): Promise>; getTeamExport(teamId: string, exportId: string): Promise>; importTeamData(destinationTeamId: string, artifact: Record): Promise>; updateTeamMemberRole(teamId: string, memberUserId: string, role: Exclude): Promise>; removeTeamMember(teamId: string, memberUserId: string): Promise<{ success: boolean; }>; getTeamBilling(teamId: string): Promise; addTeamCredits(_teamId: string, _input: { credits: number; }): Promise; listTeamUsage(teamId: string, memberUserId?: string): Promise[]>; createTeamBankTransferOrder(teamId: string, creditsAmount: number): Promise; getTeamBankTransferStatus(teamId: string, orderId: string): Promise; listTeamBankTransferOrders(teamId: string): Promise; moveWorkspaceToTeam(workspaceType: WorkspaceMoveType, objectId: string, teamId: string): Promise>; private buildWorkspaceMovePayload; private resolveRequiredPersonalProject; private personalWorkspaceMoveMetadata; getAnonymousFreeUsageStatus(): Promise; sendAnonymousMessage(params: { message: string; learningMode?: LearningModeContext; messageHistory?: BenchmarkHistoryMessage[]; }): Promise<{ status: "completed"; chatId: string; messageId: string; assistant: string; category: string | null; modelName: string | null; mateName: string | null; followUpSuggestions: string[]; taskProposals: TaskProposalEvent[]; taskUpdateProposals: TaskUpdateProposalEvent[]; subChatEvents: SubChatEvent[]; appSettingsMemoryRequests: Array<{ requestId: string | null; requestedKeys: string[]; approvedKeys: string[]; entryCount: number; }>; /** Final-frame token usage surfaced by the backend when provider usage metadata is available. */ tokenUsage: AiResponseTokenUsage | null; /** Prompt-budget metrics surfaced by the backend when available. */ promptBudget: AiResponsePromptBudget | null; }>; createTurnTokenRefs(params: { chatId: string; messageId: string; refs: ConnectedAccountTurnTokenRefInput[]; teamId?: string | null; }): Promise; listConnectedAccounts(): Promise>>; decryptConnectedAccountForSkill(params: { accountId?: string; appId: string; providerId: string; }): Promise; runConnectedAccountSkill(params: { appId: string; skillId: string; input: Record; connectedAccountTokenRefInputs: ConnectedAccountTurnTokenRefInput[]; chatId?: string; messageId?: string; apiKey?: string; promptInjectionProtection?: boolean; }): Promise>; importConnectedAccountFromCliPayload(params: { encryptedPayload: string; passcode: string; }): Promise; importConnectedAccountPayload(payload: ConnectedAccountCliTransferPayload, options?: { skipValidation?: boolean; }): Promise; exchangeRevolutBusinessSetupCode(params: { clientId: string; code: string; privateKeyPem: string; environment: "sandbox" | "production"; redirectUri?: string; }): Promise; validateConnectedAccountImportPayload(payload: ConnectedAccountCliTransferPayload): Promise; private createConnectedAccountImportRow; registerLocalConnectedAccountConnector(input: ProtonLocalConnectorRegistration): Promise<{ connected_account_id: string; connector_session_id: string; heartbeat_interval_ms?: number; }>; sendLocalConnectedAccountConnectorHeartbeat(input: { connector_session_id: string; connected_account_id: string; status: "online" | "offline"; capabilities: string[]; health_summary?: Record; }): Promise>; completeLocalConnectedAccountConnectorRequest(input: { connector_session_id: string; connected_account_id: string; request_id: string; status: "ok" | "error" | "cancelled"; result?: Record; error_code?: string; error_message?: string; }): Promise>; openLocalConnectorWebSocket(): Promise; cancelConnectedAccountAction(params: { actionId: string; chatId: string; messageId: string; }): Promise>; undoConnectedAccountAction(params: { actionId: string; chatId: string; messageId: string; turnTokenRef: string; }): Promise>; loginWithPairAuth(): Promise; whoAmI(): Promise>; getTopicPreferences(): Promise; setTopicPreferences(selectedTagIds: readonly string[]): Promise; clearTopicPreferences(): Promise; getLearningModeStatus(): Promise; activateLearningMode(params: { ageGroup: LearningModeAgeGroup; passcode: string; }): Promise; deactivateLearningMode(passcode: string): Promise; logout(): Promise; requestSignupEmailCode(params: { email: string; inviteCode?: string; language?: string; darkmode?: boolean; }): Promise; verifySignupEmailCode(params: { email: string; username: string; inviteCode?: string; code: string; language?: string; darkmode?: boolean; }): Promise; setupPasswordAccount(params: { email: string; username: string; password: string; inviteCode?: string; language?: string; darkmode?: boolean; }): Promise; startTotpSetup(): Promise; renderTotpQrCode(otpauthUrl: string): void; verifyTotpSetup(code: string): Promise; verifyTotpForCurrentSession(code: string): Promise; setTotpProvider(provider: string): Promise; requestBackupCodes(): Promise; confirmBackupCodesStored(): Promise; createAndConfirmRecoveryKey(): Promise; /** * Decrypt a single chat's key using the master key. * Returns raw Uint8Array (32 bytes) — the AES-256 key used to * encrypt/decrypt the chat's title, category, messages, etc. */ private decryptChatKey; private getContextWrapperEncryptedChatKey; private getChatWrappingKey; private resolveChatKey; /** * Decrypt a single chat record from the sync cache into a ChatListItem. */ private decryptChatListItem; listChats(limit?: number, page?: number, options?: TeamContextOptions): Promise; saveDraft(params: { markdown: string; preview?: string | null; chatId?: string; }): Promise; saveEncryptedDraft(params: { chatId: string; encryptedDraftMd: string; encryptedDraftPreview?: string | null; extraPayload?: Record; }): Promise; getIdeaBucketSettings(): Promise; saveIdeaBucketSettings(input: IdeaBucketSettingsInput): Promise; private normalizeIdeaBucketSettings; private ideaBucketSettingsToMemoryValue; addIdeaBucketText(params: { text: string; chatId?: string; bucketId?: string; scheduledSendAt?: number; prompt?: string; version?: number; }): Promise; addIdeaBucketAudio(params: { filePath: string; chatId?: string; bucketId?: string; scheduledSendAt?: number; prompt?: string; version?: number; }): Promise; private addIdeaBucketPreparedIdeas; private storeDraftEmbeds; getIdeaBucketStatus(bucketId?: string): Promise; processIdeaBucketBucket(bucketId: string, options?: { now?: boolean; }): Promise; listDrafts(forceRefresh?: boolean): Promise; getDraft(chatId: string, forceRefresh?: boolean): Promise; private refreshDraftFromTargetedSync; clearDraft(chatId: string): Promise; reconcileDraftVersions(chatIds?: string[]): Promise>; private storeEncryptedDraft; private decryptCachedDraft; searchChats(query: string, options?: TeamContextOptions): Promise; resolveChatKeyForContext(query: string, options?: TeamContextOptions): Promise<{ chatId: string; chatKey: Uint8Array; }>; private decryptRawChatMessages; private resolveCachedChatForQuery; /** * Get the decrypted messages for a specific chat. * * Lookup order (most-recent-first for all title matches): * 1. Exact full UUID match * 2. Short 8-char prefix match * 3. Exact title match (case-insensitive, most recent first) * 4. Partial title match (case-insensitive, most recent first) * * @param query Full UUID, 8-char short ID, or chat title. */ getChatMessages(query: string, options?: TeamContextOptions): Promise<{ chat: ChatListItem; messages: DecryptedMessage[]; }>; getChatMessagesWindow(query: string, options?: ChatMessageWindowOptions): Promise; getChatMessageSummaries(query: string, options?: TeamContextOptions): Promise<{ chat: ChatListItem; messages: ChatMessageSummary[]; }>; forkChat(params: { chatId: string; fromMessageId: string; title?: string; } & TeamContextOptions): Promise; rewindChat(params: { chatId: string; toMessageId: string; send?: string; dryRun?: boolean; confirmDestructive?: boolean; responseTimeoutMs?: number; } & TeamContextOptions): Promise; retryChat(params: { chatId: string; dryRun?: boolean; confirmDestructive?: boolean; responseTimeoutMs?: number; } & TeamContextOptions): Promise; private loadPersonalChatMutationState; /** * Get a decrypted embed by embed_id (full UUID or short 8-char prefix). * * Key unwrapping strategy (in priority order): * 1. Find embed key with key_type="master" for this embed → * unwrap with master key directly (simplest, no chat needed). * 2. Find embed key with key_type="chat" for this embed → * find the chat, decrypt chat key with master key, unwrap embed key. * * hashed_embed_id in the key table = SHA-256(embed.embed_id). */ getEmbed(embedIdOrShort: string): Promise; private refreshRemotionVideoCreateContent; /** * Build a slug → DecryptedEmbed index for child embeds of specific parents. * * Child embeds store an `embed_ref` slug in their encrypted content (e.g. * "youtube.com-p3f", "marineinsight.com-wrP"). This method only decrypts * child embeds whose parent_embed_id is in the provided set, keeping it * fast even when the cache has thousands of embeds. * * @param parentEmbedIds - Set of parent embed IDs to resolve children for. * Pass the embed IDs extracted from the chat's message JSON blocks. * * Mirrors the web app's embedStore.embedRefToIdIndex (in-memory only). */ buildEmbedRefIndex(parentEmbedIds: Set): Promise>; /** * Resolve the embed decryption key for a given embed. * * Strategy: * 1. Master key type — decrypt embed key with master key directly * 2. Chat key type — unwrap via chat key → then decrypt embed key * 3. Parent key fallback — child embeds inherit the parent's embed key. * If the embed has a parent_embed_id, resolve the parent's key and * reuse it (matching the web app's embedStore.getEmbedKey pattern). */ private resolveEmbedKey; /** * Resolve a short chat ID (first 8 chars) or partial title to a full UUID. * Accepts full UUIDs unchanged. Returns undefined if no match found. */ resolveFullChatId(idOrShort: string, options?: TeamContextOptions): Promise; private resolveChatIdFromCacheSlug; /** * List new-chat suggestions from the local sync cache, decrypted. * * These are the same suggestions shown in the "What would you like to do?" row * on the web app's home screen. They are generated by the AI post-processor * after each conversation and stored encrypted in Directus. * * Mirrors: NewChatSuggestions.svelte + newChatSuggestions.ts (web app) * * @param limit Maximum number of suggestions to return (default: 10) */ listNewChatSuggestions(limit?: number, options?: TeamContextOptions): Promise; /** * Decrypt the follow-up request suggestions for a chat. * Reads encrypted_follow_up_request_suggestions from the sync cache details. * Returns an empty array if not present or decryption fails. * * Mirrors: chat_actions_store.ts / FollowUpSuggestions.svelte (web app) */ getChatFollowUpSuggestions(chatId: string, options?: TeamContextOptions): Promise; sendMessage(params: { message: string; chatId?: string; /** Client-generated ID for a new chat, allowing cleanup after an uncertain send outcome. */ newChatId?: string; slug?: string; teamId?: string | null; personal?: boolean; incognito?: boolean; /** Streaming callback — fires for typing, chunk, and done events. */ onStream?: (event: StreamEvent) => void; /** Sub-chat lifecycle callback for progress/status output. */ onSubChatEvent?: (event: SubChatEvent) => void; /** Approval callback used when the server asks before starting a large sub-chat batch. */ onSubChatApprovalRequest?: (request: SubChatApprovalRequest) => boolean | Promise; /** Explicit opt-in for automatic sub-chat approval in non-interactive runs. */ autoApproveSubChats?: boolean; /** Explicit opt-in to approve server-requested memory categories in non-interactive runs. */ autoApproveMemories?: boolean; /** Encrypted file embeds to attach to the message (code, images, PDFs). */ encryptedEmbeds?: EncryptedEmbed[]; /** Prepared embeds to encrypt after the real chat/message IDs are known. */ preparedEmbeds?: PreparedEmbed[]; /** Placeholder-to-original PII mappings created before sending the user message. */ piiMappings?: Array<{ placeholder: string; original: string; type: string; }>; /** Redacted connected-account directory for AI-visible account selection. */ connectedAccountDirectory?: ConnectedAccountDirectoryEntry[]; /** Refresh-token envelopes to convert into short-lived token refs before send. */ connectedAccountTokenRefInputs?: ConnectedAccountTurnTokenRefInput[]; /** Non-sensitive CLI benchmark labels for usage-source grouping. */ benchmarkMetadata?: BenchmarkMetadata; /** Full plaintext history for incognito benchmark turns. */ messageHistory?: BenchmarkHistoryMessage[]; /** Account-wide Learning Mode context when already known by the caller. */ learningMode?: LearningModeContext; /** Start collecting before send for latency-sensitive benchmark turns. */ precollectResponse?: boolean; /** Disable chat-side encrypted task update jobs for flows that must only clarify. */ taskUpdateJobs?: boolean; /** Override WebSocket turn waits for long-running sends and responses. */ responseTimeoutMs?: number; }): Promise<{ status: "completed" | "waiting_for_user"; chatId: string; messageId: string | null; assistant: string; category: string | null; modelName: string | null; mateName: string | null; /** Follow-up suggestions from post-processing (may be empty for incognito chats). */ followUpSuggestions: string[]; /** Review-only task proposals from post-processing. */ taskProposals: TaskProposalEvent[]; /** Review-only task update proposals from post-processing. */ taskUpdateProposals: TaskUpdateProposalEvent[]; /** Main-processor task tool events observed during the turn. */ taskEvents: TaskEventFrame[]; /** Pending task update jobs awaiting client encryption/persistence. */ pendingTaskUpdateJobs: PendingTaskUpdateJobFrame[]; /** Sub-chat lifecycle frames observed while collecting the parent response. */ subChatEvents: SubChatEvent[]; /** Memory permission requests observed and optionally approved while collecting the response. */ appSettingsMemoryRequests: Array<{ requestId: string | null; requestedKeys: string[]; approvedKeys: string[]; entryCount: number; }>; /** Final-frame token usage surfaced by the backend when provider usage metadata is available. */ tokenUsage: AiResponseTokenUsage | null; /** Prompt-budget metrics surfaced by the backend when available. */ promptBudget: AiResponsePromptBudget | null; }>; private persistEncryptedSystemMessage; private persistPendingTaskUpdateJobs; private persistStreamedEmbeds; private persistPostProcessingMetadata; /** * Delete a chat by ID. * * Mirrors the web app's sendDeleteChatImpl in chatSyncServiceSenders.ts. * Sends a delete_chat WebSocket message and waits for the server ack. */ deleteChat(chatIdInput: string, options?: TeamContextOptions): Promise; listApps(apiKey?: string): Promise; private resolveAsyncSkillResponse; private pollTaskUntilComplete; private wrapResolvedSkillResult; private mergeTaskResults; getApp(appId: string): Promise; getSkillInfo(appId: string, skillId: string, apiKey?: string): Promise; /** A single parameter entry from the skill schema. */ getSkillSchema(appId: string, skillId: string): Promise; runSkill(params: { app: string; skill: string; inputData: Record; apiKey?: string; promptInjectionProtection?: boolean; }): Promise; private appSkillFailureMessage; getCodeRunStreamAuth(): Promise<{ sessionId: string; token: string; fallbackToken?: string; } | null>; getCodeRunStatus(path: string, apiKey?: string): Promise>; getRaw(path: string, apiKey?: string): Promise<{ contentType: string; data: Uint8Array; }>; /** * Look up a booking URL for a flight using its booking_token. * * Calls POST /v1/apps/travel/booking-link which resolves the SerpAPI * booking_token to a direct airline/OTA booking URL. Costs 25 credits. * * @see TravelConnectionEmbedFullscreen.svelte — handleLoadBookingLink() */ getBookingLink(params: { bookingToken: string; bookingContext?: Record; apiKey?: string; }): Promise<{ success: boolean; booking_url?: string; booking_provider?: string; credits_charged?: number; error?: string; }>; listWorkflows(options?: TeamContextOptions): Promise; listTemporaryWorkflows(): Promise; createWorkflow(params: { title: string; slug?: string; graph: WorkflowGraph; enabled?: boolean; runContentRetention?: WorkflowRunContentRetention; lifecycle?: WorkflowLifecycle; source?: string; sourceChatId?: string | null; createdByAssistant?: boolean; autoDeleteAt?: number | null; }): Promise; askWorkflow(input: { instruction: string; create?: Record; exactUpdate?: Record; exactAction?: Record; selectedObjectId?: string | null; }): Promise>; planWorkflowAsk(input: { instruction: string; }): Promise>; validateWorkflowYaml(source: string): Promise<{ draft_valid: boolean; enable_ready: boolean; diagnostics: Array>; }>; createWorkflowYaml(source: string): Promise<{ workflow: WorkflowDetail; validation: { draft_valid: boolean; enable_ready: boolean; diagnostics: Array>; }; }>; updateWorkflowYaml(workflowId: string, source: string): Promise<{ workflow: WorkflowDetail; validation: { draft_valid: boolean; enable_ready: boolean; diagnostics: Array>; }; }>; getWorkflow(workflowId: string, options?: TeamContextOptions): Promise; updateWorkflow(workflowId: string, params: { title?: string; slug?: string; graph?: WorkflowGraph; enabled?: boolean; runContentRetention?: WorkflowRunContentRetention; }): Promise; resolveWorkflowId(query: string, options?: TeamContextOptions): Promise; private resolveRequiredWorkflowId; private resolveRequiredChatId; private resolveRequiredProjectId; private decryptWorkflowSlugs; private toPublicWorkflow; private decryptWorkflowSlug; deleteWorkflow(workflowId: string): Promise<{ deleted: boolean; }>; keepWorkflow(workflowId: string): Promise; enableWorkflow(workflowId: string): Promise; disableWorkflow(workflowId: string): Promise; runWorkflow(workflowId: string, params: { idempotencyKey: string; mode?: "manual" | "test"; input?: Record; }): Promise; listWorkflowRuns(workflowId: string): Promise; getWorkflowRun(workflowId: string, runId: string): Promise; cancelWorkflowRun(workflowId: string, runId: string): Promise; testWorkflowStep(workflowId: string, stepId: string, params?: { input?: Record; confirmed?: boolean; }): Promise; respondToWorkflowRun(workflowId: string, runId: string, stepId: string, input: Record): Promise; listWorkflowCapabilities(): Promise; upsertWorkflowTemplateProjection(workflowId: string, params: WorkflowTemplateProjectionUpsertParams): Promise; getPublicWorkflowTemplateProjection(templateId: string): Promise; revokeWorkflowTemplateProjection(workflowId: string): Promise; unrevokeWorkflowTemplateProjection(workflowId: string): Promise; completeImportedWorkflowBinding(workflowId: string, params: WorkflowTemplateBindingCompletionParams): Promise; createWorkflowTemplateShortUrl(params: WorkflowTemplateShortUrlParams): Promise; revokeShortUrl(token: string): Promise; importWorkflowTemplate(payload: WorkflowTemplateImportPayload): Promise; startWorkflowInput(params: WorkflowInputStartParams): Promise; getWorkflowInputSession(sessionId: string): Promise; listWorkflowInputEvents(sessionId: string, afterEventId?: number): Promise; followUpWorkflowInput(sessionId: string, text: string): Promise; stopWorkflowInput(sessionId: string): Promise; undoWorkflowInput(sessionId: string): Promise; private setWorkflowEnabled; listProjects(options?: { includeArchived?: boolean; teamId?: string | null; personal?: boolean; }): Promise; getProject(projectId: string, options?: TeamContextOptions): Promise; createProject(input: Record, options?: TeamContextOptions): Promise>; updateProject(projectId: string, patch: Record, options?: TeamContextOptions): Promise; deleteProject(projectId: string, confirmationProjectId: string, options?: TeamContextOptions): Promise<{ deleted: boolean; }>; askProject(input: { instruction: string; encryptedCreate?: Record; encryptedUpdate?: Record; encryptedUpdates?: Record[]; exactDelete?: Record; exactDeletes?: Record[]; }): Promise>; planProjectAsk(input: { instruction: string; }): Promise>; listProjectItems(projectId: string, options?: TeamContextOptions): Promise<{ folders: Array>; items: ProjectItemRecord[]; }>; listProjectSources(projectId: string, options?: TeamContextOptions): Promise; createProjectSource(projectId: string, input: ProjectSourceCreateInput, options?: TeamContextOptions): Promise; deleteProjectSource(projectId: string, sourceId: string, confirmationSourceId: string, options?: TeamContextOptions): Promise<{ deleted: boolean; }>; createProjectRemoteAccessRequest(projectId: string, sourceId: string, input: ProjectRemoteAccessRequestInput, options?: TeamContextOptions): Promise; getProjectRemoteAccessResult(projectId: string, sourceId: string, requestId: string, requestingClientId: string, options?: TeamContextOptions): Promise<{ status: string; encrypted_envelope: string; }>; decryptProjectKey(record: ProjectRecord, options?: TeamContextOptions): Promise; projectWrappingKey(options?: TeamContextOptions): Promise<{ key: Uint8Array; teamId: string | null; }>; private projectRequestError; openProjectRemoteAccessWebSocket(): Promise<{ ws: OpenMatesWsClient; ownerId: string; }>; createProjectItem(projectId: string, input: ProjectItemCreateInput): Promise; deleteProjectItemByTarget(projectId: string, itemType: "embed" | "chat" | "workflow", targetId: string, options?: TeamContextOptions): Promise<{ deleted: boolean; deleted_count: number; }>; listWorkspaceHistory(filters?: { objectType?: string; objectId?: string; limit?: number; }): Promise[]>; getWorkspaceHistory(changeSetId: string): Promise>; undoWorkspaceHistory(changeSetId: string): Promise>; listObjectHistory(objectType: "task" | "plan" | "project" | "workflow", objectId: string, limit?: number): Promise[]>; restoreObjectHistory(objectType: "task" | "plan" | "project" | "workflow", objectId: string, entryId: string, state?: "before" | "after"): Promise>; listUserTasks(filters?: { status?: UserTaskStatus; chatId?: string; projectId?: string; labelHashes?: string[]; priority?: number; limit?: number; teamId?: string | null; personal?: boolean; }): Promise; createUserTask(input: UserTaskCreateInput): Promise; askUserTasks(input: { instruction: string; encryptedCreate?: UserTaskCreateInput; encryptedCreates?: UserTaskCreateInput[]; encryptedUpdate?: Record; encryptedUpdates?: Record[]; exactDelete?: Record; exactDeletes?: Record[]; }): Promise>; planUserTaskAsk(input: { instruction: string; contextChatId?: string | null; projectIds?: string[]; }): Promise; extractUserTaskProposals(input: { correctedText: string; mode?: "create" | "update"; contextChatId?: string | null; projectIds?: string[]; }): Promise; updateUserTask(taskId: string, input: UserTaskUpdateInput): Promise; startUserTaskWithAI(taskId: string, input: UserTaskStartAIInput): Promise; deleteUserTask(taskId: string, version: number): Promise<{ deleted?: boolean; task_id?: string; history?: WorkspaceHistoryResult; }>; completeUserTask(taskId: string, input: UserTaskActionInput): Promise; blockUserTask(taskId: string, input: UserTaskActionInput): Promise; unblockUserTask(taskId: string, input: UserTaskActionInput): Promise; skipUserTask(taskId: string, input: UserTaskActionInput): Promise; reorderUserTasks(input: UserTaskReorderInput): Promise; postUserTaskAction(taskId: string, action: string, input: UserTaskActionInput): Promise; listUserPlans(filters?: { status?: UserPlanStatus; chatId?: string; projectId?: string; activeOnly?: boolean; teamId?: string | null; personal?: boolean; }): Promise; createUserPlan(input: UserPlanCreateInput): Promise; askUserPlans(input: { instruction: string; encryptedCreate?: UserPlanCreateInput; encryptedUpdate?: Record; encryptedUpdates?: Record[]; }): Promise>; planUserPlanAsk(input: { instruction: string; }): Promise>; updateUserPlan(planId: string, input: UserPlanUpdateInput): Promise; activateUserPlan(planId: string, input?: Record): Promise; attachUserPlan(planId: string, input?: Record): Promise; startUserPlan(planId: string, input?: Record): Promise; resumeUserPlan(planId: string, input?: Record): Promise; completeUserPlan(planId: string, input?: Record): Promise; createPlanCriterion(planId: string, input: UserPlanCriterionRecord): Promise; listPlanCriteria(planId: string): Promise; updatePlanCriterion(planId: string, criterionId: string, input: Partial): Promise; deletePlanCriterion(planId: string, criterionId: string): Promise>; createPlanVerification(planId: string, input: UserPlanVerificationRecord & Record): Promise; listPlanVerifications(planId: string): Promise; updatePlanVerification(planId: string, verificationId: string, input: Partial): Promise; deletePlanVerification(planId: string, verificationId: string): Promise>; createPlanAssumption(planId: string, input: UserPlanAssumptionRecord): Promise; listPlanAssumptions(planId: string): Promise; updatePlanAssumption(planId: string, assumptionId: string, input: Partial): Promise; deletePlanAssumption(planId: string, assumptionId: string): Promise>; createPlanReferencePattern(planId: string, input: UserPlanReferencePatternRecord): Promise; updatePlanReferencePattern(planId: string, patternId: string, input: Partial): Promise; deletePlanReferencePattern(planId: string, patternId: string): Promise>; createPlanLearning(planId: string, input: UserPlanLearningRecord): Promise; listPlanLearnings(planId: string): Promise; updatePlanLearning(planId: string, learningId: string, input: Partial): Promise; deletePlanLearning(planId: string, learningId: string): Promise>; createPlanLearningTasks(planId: string, input: UserPlanLearningCreateTasksInput): Promise; listPlanReferencePatterns(planId: string): Promise; addPlanVerificationEvidence(planId: string, verificationId: string, input: Partial): Promise; settingsGet(path: string, apiKey?: string): Promise; getUsageOverview(options?: UsageOverviewOptions): Promise; createApiKey(options: ApiKeyCreateOptions): Promise; listApiKeys(): Promise; revokeApiKey(id: string): Promise; private decryptApiKeyList; settingsPost(path: string, body: Record, apiKey?: string): Promise; settingsDelete(path: string, body?: Record, apiKey?: string): Promise; settingsPatch(path: string, body: Record, apiKey?: string): Promise; redeemGiftCard(code: string): Promise<{ success: boolean; credits_added: number; current_credits: number; message: string; }>; listRedeemedGiftCards(): Promise; listPurchasedGiftCards(): Promise; createBankTransferOrder(creditsAmount: number): Promise; createGiftCardBankTransferOrder(creditsAmount: number): Promise; getBankTransferStatus(orderId: string): Promise; listBankTransferOrders(): Promise; getGiftCardPurchaseStatus(orderId: string): Promise; listInvoices(): Promise<{ invoices: InvoiceListItem[]; }>; downloadInvoice(invoiceId: string): Promise; downloadCreditNote(invoiceId: string): Promise; requestRefund(invoiceId: string): Promise; getAuthMethodsStatus(): Promise; requestActionEmailCode(action: "delete_account" | "delete_team"): Promise; requestDeleteAccountEmailCode(): Promise; verifyActionEmailCode(action: "delete_account" | "delete_team", code: string): Promise; verifyDeleteAccountEmailCode(code: string): Promise; deleteAccountWithCliVerification(totpCode?: string): Promise; updateUsername(username: string): Promise; updateProfileImage(filePath: string): Promise; getNewsletterCategories(): Promise; updateNewsletterCategories(categories: Record): Promise; subscribeNewsletter(email: string, language?: string, darkmode?: boolean): Promise; confirmNewsletter(token: string): Promise; unsubscribeNewsletter(token: string): Promise; updateEmailNotificationSettings(payload: { enabled: boolean; email?: string | null; preferences: Record; backup_reminder_interval_days?: number; }): Promise; listNotifications(limit?: number): Promise; streamNotifications(): AsyncGenerator; /** * Fetch today's daily inspirations. * * When the user is logged in, fetches their personalized (encrypted) * inspirations from GET /v1/daily-inspirations and decrypts each field * with their master key. Falls back to the public defaults endpoint if * no personalized inspirations exist for the user yet. * * When not logged in, fetches the public defaults from * GET /v1/default-inspirations?lang= — no decryption needed. * * Mirrors: frontend/packages/ui/src/services/dailyInspirationDB.ts * frontend/packages/ui/src/demo_chats/loadDefaultInspirations.ts */ getDailyInspirations(lang?: string): Promise; /** * Fetch and decrypt the authenticated user's persisted inspirations. * Falls back to public defaults when none are stored yet. */ private _getPersonalizedInspirations; /** * Fetch the public (unauthenticated) default inspirations for the day. * These come cleartext — no decryption needed. * Mirrors loadDefaultInspirations.ts fetchServerDefaultInspirations() */ private _getPublicInspirations; /** * List all memories for the current user, decrypted. * Fetches from the GDPR export endpoint and decrypts each entry with the master key. */ private sdkGetMemories; listMemories(options?: TeamContextOptions): Promise; /** * Create a new memory entry with schema validation. * * Encrypts the full item_value (including _original_item_key and settings_group) * before sending over WebSocket, matching the browser's exact payload format. * * @param appId - App identifier (e.g. "code") * @param itemType - Memory type ID (e.g. "preferred_tech") * @param itemValue - Field values (must satisfy the schema's required fields) */ createMemory(params: { appId: string; itemType: string; itemValue: Record; teamId?: string | null; personal?: boolean; }): Promise<{ success: boolean; id: string; }>; /** * Update an existing memory entry. * Uses the same `store_app_settings_memories_entry` WS event with an * incremented version so the server's conflict-resolution logic accepts it. * * @param entryId - UUID of the entry to update (from listMemories()) * @param appId - App identifier * @param itemType - Memory type ID * @param itemValue - Updated field values (partial — merged with required fields check) * @param currentVersion - The entry's current item_version from listMemories() */ updateMemory(params: { entryId: string; appId: string; itemType: string; itemValue: Record; currentVersion: number; teamId?: string | null; personal?: boolean; }): Promise<{ success: boolean; id: string; }>; /** * Delete a memory entry. Sends `delete_app_settings_memories_entry` over * WebSocket. The server deletes from Directus and broadcasts to all devices. */ deleteMemory(entryId: string, options?: TeamContextOptions): Promise<{ success: boolean; }>; /** * Validate memory item_value against the registered schema and * encrypt + send over WebSocket. */ private upsertMemory; /** * Get the master key bytes for embed encryption. * Requires active session. */ getEmbedEncryptionKeys(): { masterKey: Uint8Array; userId: string; }; /** * Get the session for file upload authentication. */ getSession(): OpenMatesSession; /** * Create a shareable link for a chat. * * Mirrors: SettingsShare.svelte generateShareLink() + shareEncryption.ts generateShareKeyBlob() * * The chat key is decrypted from encrypted_chat_key in the sync cache, * then used to generate the encrypted blob. The chat key bytes never leave * the process — only the blob (which the recipient needs to access the chat) * is placed in the URL fragment (never sent to the server). * * @param chatId UUID or short ID of the chat to share * @param durationSeconds Expiry (0 = no expiry, default) * @param password Optional password protection (max 10 chars) * @returns Full share URL, e.g. https://openmates.org/share/chat/{id}#key={blob} */ createChatShareLink(chatId: string, durationSeconds?: ShareDuration, password?: string): Promise; /** * Create a shareable link for an embed. * * Mirrors: SettingsShare.svelte (embed path) + embedShareEncryption.ts generateEmbedShareKeyBlob() * * Resolves the embed's AES-256 key using the same 3-strategy key resolution * as resolveEmbedKey(), then generates the encrypted blob. * * @param embedIdOrShort UUID or short prefix of the embed to share * @param durationSeconds Expiry (0 = no expiry, default) * @param password Optional password protection (max 10 chars) * @returns Full share URL, e.g. https://openmates.org/share/embed/{id}#key={blob} */ createEmbedShareLink(embedIdOrShort: string, durationSeconds?: ShareDuration, password?: string): Promise; listEmbedVersions(embedIdOrShort: string): Promise; startApplicationPreview(params: ApplicationPreviewStartParams): Promise; getApplicationPreviewStatus(sessionId: string): Promise; openApplicationPreview(sessionId: string): Promise; stopApplicationPreview(sessionId: string): Promise; getEmbedVersion(embedIdOrShort: string, version: number): Promise; restoreEmbedVersion(embedIdOrShort: string, version: number): Promise; private reconstructEncryptedEmbedVersion; private formatEmbedVersionError; private formatApplicationPreviewError; private resolveEmbedId; /** * Build the context needed for CLI mention resolution. * Fetches apps (with skills, focus modes, memory categories) and * memory entries from the server, combines with static model/mate data. * * Mirrors: mentionSearchService.ts data sources */ buildMentionContext(): Promise; private normalizePath; private downloadPaymentPdf; private ensureEmailEncryptionKey; private hydrateEmailEncryptionKey; private requireSession; getMasterKeyBytes(): Uint8Array; private decryptTopicPreferences; private decryptSettingsRecord; private getValidSessionFromDisk; private makeWsClient; /** * Refresh ws_token, then create and open a WebSocket client. * Combines refreshWsToken() + makeWsClient() + ws.open() into one call * so every WebSocket usage gets a fresh HMAC token automatically. */ private openWsClient; /** * Refresh the ws_token by calling /auth/session. * The HMAC ws_token has a 5-minute TTL — the web app refreshes it on every * /auth/session call, but the CLI stores it from login and never updates it. * This method fetches a fresh ws_token and captures any rotated cookies. */ private refreshWsToken; /** * Ensure the local sync cache is up to date. If the cache is fresh, * return it directly. Otherwise, do a full WS sync and save to disk. * * The sync cache stores encrypted data — decryption is always on-demand. * SECURITY: decrypted user content is NEVER written to disk. */ ensureSynced(forceRefresh?: boolean, refreshChatIds?: string[], options?: TeamContextOptions, includeMessageContentRefresh?: boolean): Promise; private persistPendingAIResponsesFromSync; private prompt; private waitForPairAuthorization; private installPairExitListener; private renderPairQrCode; private getCliRequestHeaders; private getCliUserAgent; private getLocalDeviceName; private getCliApiKeyDeviceIdentity; /** Fetch the full documentation tree structure. */ listDocs(): Promise; /** Fetch a single document's raw markdown by slug. */ getDoc(slug: string): Promise; /** Search docs by query string. Returns matching docs with snippets. */ searchDocs(query: string): Promise; } interface DocsTree { folders: DocsFolder[]; files: DocsFile[]; } interface DocsFolder { path: string; title: string; folders: DocsFolder[]; files: DocsFile[]; } interface DocsFile { slug: string; title: string; filename: string; wordCount: number; } interface DocsSearchResult { slug: string; title: string; snippet: string; } /** * @file File upload service for the CLI — uploads images and PDFs to * the OpenMates upload server (S3-backed, encrypted, malware-scanned). * * Uses multipart/form-data POST to upload.openmates.org, authenticated * via the auth_refresh_token cookie from pair-auth login. * * Mirrors: uploadService.ts (web app) — same endpoint, same auth, same response format. * Architecture: docs/architecture/embeds.md */ interface FileVariantMetadata { s3_key: string; width: number; height: number; size_bytes: number; format: string; } interface AIDetectionMetadata { ai_generated: number; provider: string; status?: "success" | "failed" | string; error?: string | null; } interface UploadFileResponse { embed_id: string; filename: string; content_type: string; content_hash: string; files: Record; s3_base_url: string; aes_key: string; aes_nonce: string; vault_wrapped_aes_key: string; malware_scan: string; ai_detection: AIDetectionMetadata | null; deduplicated: boolean; page_count?: number; } declare function resolveProjectContext(client: OpenMatesClient, flags: Record, requireExplicit: boolean): Promise<{ teamId?: string; personal?: boolean; }>; declare function requireExactConfirmation(label: string, exactValue: string, flags: Record): Promise; type ImagesAiDetectionClassification = "likely_ai_generated" | "possibly_ai_generated" | "likely_not_ai_generated" | "unavailable"; interface ImagesAiDetectionSummary { file: string; filename: string; content_type: string; embed_id: string; deduplicated: boolean; stored: true; status: string; provider: string | null; ai_generated: number | null; classification: ImagesAiDetectionClassification; label: string; error: string | null; } declare function classifyImagesAiDetection(score: number | null | undefined): ImagesAiDetectionClassification; declare function formatImagesAiDetectionLabel(classification: ImagesAiDetectionClassification): string; declare function buildImagesAiDetectionSummary(uploadResult: UploadFileResponse, filePath: string): ImagesAiDetectionSummary; declare function buildTravelConnectionsRequest(positionals: string[], flags: Record): Record; /** Format a share duration for display */ /** * Simple YAML serializer for chat export (no external dependency). * Handles nested objects, arrays, and multiline strings. * Mirrors chatExportService.convertToYamlString for compatibility. */ declare function serializeToYaml(data: Record, indent?: number): string; /** Map language identifier to file extension for code embed downloads. */ declare function getExtForLang(language: string): string; export { type DecryptedMessage as $, type WorkflowRunCancellationResult as A, type WorkflowTemplateProjectionUpsertParams as B, type WorkflowTemplateProjectionResult as C, type PublicWorkflowTemplateProjection as D, type WorkflowTemplateProjectionRevocationResult as E, type WorkflowTemplateBindingCompletionParams as F, type WorkflowTemplateBindingCompletionResult as G, type WorkflowTemplateShortUrlParams as H, type WorkflowTemplateShortUrlResult as I, type WorkflowTemplateImportPayload as J, type ImportedWorkflowTemplate as K, type AuthMethodsStatus as L, type AuthoritativeChatReconciliation as M, type BackupCodesResult as N, type BankTransferOrderDetails as O, type ProjectItemRecord as P, type BankTransferStatus as Q, type CachedChat as R, type ShortUrlRevokeResult as S, type CachedNewChatSuggestion as T, type UserTaskStatus as U, type ChatListPage as V, type WorkflowSummary as W, type CliSignupResult as X, type DecryptedDraft as Y, type DecryptedEmbed as Z, type DecryptedMemoryEntry as _, type UserTaskAssigneeType as a, type DecryptedNewChatSuggestion as a0, type DocsFile as a1, type DocsFolder as a2, type DocsSearchResult as a3, type DocsTree as a4, type EncryptedDraft as a5, type GiftCardBankTransferStatus as a6, INTEREST_TAG_IDS as a7, type ImagesAiDetectionClassification as a8, type ImagesAiDetectionSummary as a9, resolveProjectContext as aA, type InterestTagId as aa, MATE_NAMES as ab, MEMORY_TYPE_REGISTRY as ac, type MemoryFieldDef as ad, type MemoryTypeDef as ae, OpenMatesClient as af, type OpenMatesClientOptions as ag, type OpenMatesSession as ah, type SyncCache as ai, type TopicPreferencesPayload as aj, type TotpSetupStartResult as ak, type WorkflowEdge as al, type WorkflowNode as am, type WorkflowNodeRun as an, type WorkflowNodeType as ao, type WorkflowRunContentStorage as ap, buildImagesAiDetectionSummary as aq, classifyImagesAiDetection as ar, deriveAppUrl as as, formatImagesAiDetectionLabel as at, getExtForLang as au, normalizeInterestTagIds as av, reconcileAuthoritativeChats as aw, serializeToYaml as ax, buildTravelConnectionsRequest as ay, requireExactConfirmation as az, type UserTaskRecord as b, type UserPlanStatus as c, type UserPlanRecord as d, type UserPlanVerificationStatus as e, type UserPlanLearningType as f, type UserPlanLearningTargetKind as g, type UserPlanLearningStatus as h, type UserPlanLearningLevel as i, type UserPlanLearningRecord as j, type UserPlanCriterionRecord as k, type UserPlanVerificationRecord as l, type UserPlanCreateInput as m, type UserPlanUpdateInput as n, type UserPlanLearningCreateTasksInput as o, type UserPlanLearningCreateTasksResult as p, type UserTaskReorderInput as q, type WorkflowCapability as r, type WorkflowDetail as s, type WorkflowInputStartParams as t, type WorkflowInputSessionResult as u, type WorkflowInputSessionDetail as v, type WorkflowInputEvent as w, type WorkflowGraph as x, type WorkflowRunContentRetention as y, type WorkflowRunDetail as z };