flowstack-sdk 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2325 @@
1
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2
+ import React, { ReactNode } from 'react';
3
+ import { F as FlowstackConfig, a as FlowstackContextValue, U as UseAuthReturn, b as UseWorkspaceReturn, c as UseDatasetsReturn, d as UseVisualizationsReturn, e as UseReportsReturn, f as UseModelsReturn, g as UseDataSourcesReturn, A as AgentTemplate, h as UseAgentOptions, i as UseAgentReturn, j as UseQueryReturn, C as ChatMessage, T as ToolCall, k as UseUserManagementReturn, l as UseSitesReturn, m as UseAgentsReturn, n as CollectionLayer, o as UseSiteVersionsReturn, P as ProviderCredential, p as PurposeInfo, L as LLMProvider, q as ProviderModelSettings, O as OllamaLocalModel, r as OllamaStatus, s as UserDataOverview, t as UserCollectionInfo, u as CollectionSchemaInfo, v as FlowstackCredentials, w as User, W as WorkspaceInfo, D as DatasetInfo, V as VisualizationData, x as DataSource, M as ManagedUser, y as UserStats, z as UserActivityLog, B as DataSourceBadgeInfo, S as StreamEvent, E as AgentConfig, G as ModelPreferenceState, H as ModelOption, I as AdminProviderCredential, J as ExistingProviderCredential, K as CreateAdminProviderCredentialInput, N as FlowstackClientConfig } from './index-BkACA2ls.mjs';
4
+ export { aq as AgentInfo, aD as ApiResponse, _ as AuthConfig, bM as CACHE_TTL, Z as COLLECTION_LAYERS, R as CREDENTIAL_PURPOSES, a9 as ColumnSchema, ah as ConnectionTestResult, as as CreateSiteParams, a7 as CreateWorkspaceRequest, ax as CredentialPurpose, ap as CreditStatus, X as DEFAULT_PROVIDER_MODEL_SETTINGS, ag as DataSourceConfig, af as DataSourceType, a0 as DatabaseConfig, a8 as DatasetPreview, aa as DatasetRow, ab as DatasetStreamOptions, az as GitHubRepo, a5 as GoogleAuthResponse, al as InterruptInfo, Q as LLM_PROVIDERS, aE as ListResponse, a1 as LoginRequest, a2 as LoginResponse, ad as ModelInfo, aB as PiiEntitySettings, aC as PiiRedactedEntity, aA as PiiSettings, av as PublishToGitHubParams, aw as PublishToGitHubResult, ar as PublishedSiteInfo, am as QueryOptions, $ as RedisConfig, a3 as RegisterRequest, a4 as RegisterResponse, ac as ReportInfo, bL as RequestOptions, ae as ScriptInfo, ai as SearchResult, aj as SearchResultsData, a6 as SessionState, at as SiteVersion, au as SiteVersionManifest, ak as StreamEventType, aI as UpdateUserRequest, ao as UsagePeriod, an as UsageStats, aH as UserActivityType, ay as UserDataOverviewWorkspace, aJ as UserListParams, aK as UserListResponse, aF as UserRole, aG as UserStatus, bD as addPiiAllowlistTerm, bk as addSiteFile, be as checkAdminPermissions, aZ as createDataSource, bj as createSite, aN as createWorkspace, c4 as deleteCached, a$ as deleteDataSource, aS as deleteDataset, bv as deleteDocuments, bm as deleteSite, bp as deleteSiteVersion, b9 as deleteUser, bJ as deleteUserCollection, b0 as executeQuery, b1 as executeQueryWithConfig, bK as exportUserCollection, aL as flowstackFetch, c2 as getCached, bQ as getCachedDatasets, bW as getCachedReports, b$ as getCachedSites, bT as getCachedVisualizations, bN as getCachedWorkspaces, bf as getConversationHistory, aQ as getDataset, aR as getDatasetPreview, aX as getModel, bC as getPiiAllowlist, bz as getPiiSettings, bi as getSite, bn as getSiteVersions, b7 as getUser, bc as getUserActivity, bH as getUserCollectionDocuments, bI as getUserCollectionSchema, bG as getUserCollections, bF as getUserDataOverview, bd as getUserStats, aO as getWorkspace, b5 as googleLogin, by as importFromGitHub, bt as insertDocuments, b_ as invalidateAllUserCache, bS as invalidateDatasetsCache, bY as invalidateReportsCache, c1 as invalidateSitesCache, bV as invalidateVisualizationsCache, bZ as invalidateWorkspaceArtifacts, bP as invalidateWorkspacesCache, bw as invokeTool, Y as isProviderCredential, bg as listAgents, aY as listDataSources, aP as listDatasets, bx as listGitHubRepos, aV as listModels, aU as listReports, aW as listScripts, bh as listSites, b6 as listUsers, aT as listVisualizations, aM as listWorkspaces, b3 as login, bB as previewPiiMasking, bo as promoteSiteVersion, bl as publishStagedSite, bs as publishToGitHub, bb as reactivateUser, b4 as register, bE as removePiiAllowlistTerm, br as removeSiteAlias, c3 as setCached, bR as setCachedDatasets, bX as setCachedReports, c0 as setCachedSites, bU as setCachedVisualizations, bO as setCachedWorkspaces, bq as setSiteAlias, ba as suspendUser, a_ as testDataSource, bu as updateDocuments, bA as updatePiiSettings, b8 as updateUser, b2 as uploadFile } from './index-BkACA2ls.mjs';
5
+ export { h as AppAccessStatus, A as AppPaywallProps, e as UseAppAccessReturn } from './types-BmCPwbGH.mjs';
6
+
7
+ /**
8
+ * FlowstackProvider Props
9
+ */
10
+ interface FlowstackProviderProps {
11
+ children: ReactNode;
12
+ config: FlowstackConfig;
13
+ /**
14
+ * P0-72: Optional Privy auth state passed from the parent. When provided,
15
+ * FlowstackProvider cross-validates stored credentials against Privy on
16
+ * mount — if Privy says "not authenticated", stale Flowstack creds are
17
+ * cleared instead of blindly hydrated. This eliminates the 4-minute 401
18
+ * request storm on cold load when Privy's session is absent but
19
+ * sessionStorage still has `flowstack_credentials`.
20
+ *
21
+ * When omitted (e.g., SIWE-only mode, tests), the provider falls back
22
+ * to the legacy behavior of trusting sessionStorage.
23
+ */
24
+ privyAuthState?: {
25
+ ready: boolean;
26
+ authenticated: boolean;
27
+ };
28
+ }
29
+ /**
30
+ * Flowstack Provider Component
31
+ *
32
+ * Wrap your app with this provider to enable all Flowstack SDK features.
33
+ *
34
+ * @example
35
+ * ```tsx
36
+ * <FlowstackProvider config={{ jwtSecret: process.env.JWT_SECRET! }}>
37
+ * <App />
38
+ * </FlowstackProvider>
39
+ * ```
40
+ */
41
+ declare function FlowstackProvider({ children, config, privyAuthState, }: FlowstackProviderProps): react_jsx_runtime.JSX.Element;
42
+ /**
43
+ * Hook to access Flowstack context
44
+ *
45
+ * @example
46
+ * ```tsx
47
+ * function MyComponent() {
48
+ * const { isAuthenticated, credentials } = useFlowstack();
49
+ * // ...
50
+ * }
51
+ * ```
52
+ */
53
+ declare function useFlowstack(): FlowstackContextValue;
54
+ /**
55
+ * Optional hook - returns null if not in provider (for conditional usage)
56
+ */
57
+ declare function useFlowstackOptional(): FlowstackContextValue | null;
58
+
59
+ /**
60
+ * Flowstack SDK Error Codes
61
+ *
62
+ * Standardized error codes for programmatic error handling.
63
+ */
64
+ declare const ErrorCodes: {
65
+ readonly CONFIG_INVALID: "CONFIG_INVALID";
66
+ readonly CONFIG_MISSING_JWT_SECRET: "CONFIG_MISSING_JWT_SECRET";
67
+ readonly CONFIG_MISSING_PASSWORD_SECRET: "CONFIG_MISSING_PASSWORD_SECRET";
68
+ readonly NETWORK_ERROR: "NETWORK_ERROR";
69
+ readonly NETWORK_TIMEOUT: "NETWORK_TIMEOUT";
70
+ readonly NETWORK_OFFLINE: "NETWORK_OFFLINE";
71
+ readonly AUTHENTICATION_FAILED: "AUTHENTICATION_FAILED";
72
+ readonly AUTHENTICATION_EXPIRED: "AUTHENTICATION_EXPIRED";
73
+ readonly INVALID_CREDENTIALS: "INVALID_CREDENTIALS";
74
+ readonly ACCOUNT_NOT_ACTIVE: "ACCOUNT_NOT_ACTIVE";
75
+ readonly ACCOUNT_LOCKED: "ACCOUNT_LOCKED";
76
+ readonly EMAIL_NOT_VERIFIED: "EMAIL_NOT_VERIFIED";
77
+ readonly UNAUTHORIZED: "UNAUTHORIZED";
78
+ readonly FORBIDDEN: "FORBIDDEN";
79
+ readonly INSUFFICIENT_PERMISSIONS: "INSUFFICIENT_PERMISSIONS";
80
+ readonly WORKSPACE_NOT_FOUND: "WORKSPACE_NOT_FOUND";
81
+ readonly WORKSPACE_REQUIRED: "WORKSPACE_REQUIRED";
82
+ readonly WORKSPACE_CREATE_FAILED: "WORKSPACE_CREATE_FAILED";
83
+ readonly DATASET_NOT_FOUND: "DATASET_NOT_FOUND";
84
+ readonly DATASET_UPLOAD_FAILED: "DATASET_UPLOAD_FAILED";
85
+ readonly DATASET_DOWNLOAD_FAILED: "DATASET_DOWNLOAD_FAILED";
86
+ readonly DATASET_DELETE_FAILED: "DATASET_DELETE_FAILED";
87
+ readonly DATASET_TOO_LARGE: "DATASET_TOO_LARGE";
88
+ readonly INVALID_FILE_TYPE: "INVALID_FILE_TYPE";
89
+ readonly QUERY_FAILED: "QUERY_FAILED";
90
+ readonly QUERY_TIMEOUT: "QUERY_TIMEOUT";
91
+ readonly QUERY_CANCELLED: "QUERY_CANCELLED";
92
+ readonly AGENT_ERROR: "AGENT_ERROR";
93
+ readonly STREAMING_ERROR: "STREAMING_ERROR";
94
+ readonly DATA_SOURCE_NOT_FOUND: "DATA_SOURCE_NOT_FOUND";
95
+ readonly DATA_SOURCE_CONNECTION_FAILED: "DATA_SOURCE_CONNECTION_FAILED";
96
+ readonly DATA_SOURCE_AUTH_FAILED: "DATA_SOURCE_AUTH_FAILED";
97
+ readonly RATE_LIMITED: "RATE_LIMITED";
98
+ readonly CREDITS_EXHAUSTED: "CREDITS_EXHAUSTED";
99
+ readonly SERVER_ERROR: "SERVER_ERROR";
100
+ readonly SERVICE_UNAVAILABLE: "SERVICE_UNAVAILABLE";
101
+ readonly MAINTENANCE_MODE: "MAINTENANCE_MODE";
102
+ readonly VALIDATION_ERROR: "VALIDATION_ERROR";
103
+ readonly INVALID_EMAIL: "INVALID_EMAIL";
104
+ readonly PASSWORD_TOO_SHORT: "PASSWORD_TOO_SHORT";
105
+ readonly MISSING_REQUIRED_FIELD: "MISSING_REQUIRED_FIELD";
106
+ readonly UNKNOWN_ERROR: "UNKNOWN_ERROR";
107
+ };
108
+ type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];
109
+ /**
110
+ * User-friendly messages for each error code
111
+ */
112
+ declare const ErrorMessages: Record<ErrorCode, string>;
113
+ /**
114
+ * Recovery actions for each error code
115
+ */
116
+ declare const RecoveryActions: Partial<Record<ErrorCode, string>>;
117
+
118
+ /**
119
+ * Flowstack SDK Error Handling
120
+ *
121
+ * Provides structured error handling with error codes, user-friendly messages,
122
+ * and recovery actions.
123
+ *
124
+ * @example
125
+ * ```tsx
126
+ * import { FlowstackError, ErrorCodes } from 'flowstack-sdk';
127
+ *
128
+ * try {
129
+ * await login(email, password);
130
+ * } catch (error) {
131
+ * if (error instanceof FlowstackError) {
132
+ * if (error.code === ErrorCodes.ACCOUNT_NOT_ACTIVE) {
133
+ * showActivationPrompt();
134
+ * }
135
+ * showError(error.userMessage);
136
+ * }
137
+ * }
138
+ * ```
139
+ */
140
+
141
+ interface FlowstackErrorOptions {
142
+ /** User-friendly error message */
143
+ userMessage?: string;
144
+ /** Suggested recovery action */
145
+ recoveryAction?: string;
146
+ /** Additional error details */
147
+ details?: Record<string, unknown>;
148
+ /** HTTP status code if from API */
149
+ status?: number;
150
+ /** Original error that caused this error */
151
+ cause?: Error;
152
+ }
153
+ /**
154
+ * Structured error class for Flowstack SDK
155
+ *
156
+ * Provides:
157
+ * - Error code for programmatic handling
158
+ * - User-friendly message for display
159
+ * - Recovery action suggestions
160
+ * - Additional details for debugging
161
+ */
162
+ declare class FlowstackError extends Error {
163
+ /** Error code for programmatic handling */
164
+ readonly code: ErrorCode;
165
+ /** User-friendly message safe to display */
166
+ readonly userMessage: string;
167
+ /** Suggested action to recover from the error */
168
+ readonly recoveryAction?: string;
169
+ /** Additional error details */
170
+ details?: Record<string, unknown>;
171
+ /** HTTP status code if from API response */
172
+ readonly status?: number;
173
+ /** Original error that caused this error */
174
+ readonly originalCause?: Error;
175
+ constructor(code: ErrorCode, message?: string, options?: FlowstackErrorOptions);
176
+ /**
177
+ * Create a FlowstackError from an API response
178
+ */
179
+ static fromApiError(status: number, body: string | Record<string, unknown>): FlowstackError;
180
+ /**
181
+ * Create a FlowstackError from a network error
182
+ */
183
+ static fromNetworkError(error: Error): FlowstackError;
184
+ /**
185
+ * Create a FlowstackError from any error
186
+ */
187
+ static from(error: unknown): FlowstackError;
188
+ /**
189
+ * Check if this error is retryable
190
+ */
191
+ isRetryable(): boolean;
192
+ /**
193
+ * Check if this error requires re-authentication
194
+ */
195
+ requiresReauth(): boolean;
196
+ /**
197
+ * Get a serializable representation of the error
198
+ */
199
+ toJSON(): Record<string, unknown>;
200
+ }
201
+ /**
202
+ * Type guard to check if an error is a FlowstackError
203
+ */
204
+ declare function isFlowstackError(error: unknown): error is FlowstackError;
205
+ /**
206
+ * Utility to wrap async functions with error handling
207
+ */
208
+ declare function withErrorHandling<T>(fn: () => Promise<T>, context?: string): Promise<T>;
209
+
210
+ /**
211
+ * Configuration Validator
212
+ *
213
+ * Validates FlowstackConfig on startup and provides helpful error messages.
214
+ */
215
+
216
+ interface ValidationResult {
217
+ valid: boolean;
218
+ errors: string[];
219
+ warnings: string[];
220
+ }
221
+ /**
222
+ * Validate the SDK configuration
223
+ *
224
+ * @param config - FlowstackConfig to validate
225
+ * @returns ValidationResult with errors and warnings
226
+ *
227
+ * @example
228
+ * ```ts
229
+ * const result = validateConfig(config);
230
+ * if (!result.valid) {
231
+ * console.error('Config errors:', result.errors);
232
+ * }
233
+ * result.warnings.forEach(w => console.warn(w));
234
+ * ```
235
+ */
236
+ declare function validateConfig(config: FlowstackConfig): ValidationResult;
237
+ /**
238
+ * Validate config and throw FlowstackError if invalid
239
+ *
240
+ * @param config - FlowstackConfig to validate
241
+ * @throws FlowstackError if configuration is invalid
242
+ */
243
+ declare function validateConfigOrThrow(config: FlowstackConfig): void;
244
+ /**
245
+ * Check if config is for development/testing (relaxed validation)
246
+ */
247
+ declare function isDevelopmentConfig(config: FlowstackConfig): boolean;
248
+ /**
249
+ * Get a summary of the config for debugging
250
+ */
251
+ declare function getConfigSummary(config: FlowstackConfig): Record<string, unknown>;
252
+
253
+ /**
254
+ * Hook for authentication operations
255
+ */
256
+ declare function useAuth(): UseAuthReturn;
257
+
258
+ /**
259
+ * Hook for workspace management
260
+ */
261
+ declare function useWorkspace(): UseWorkspaceReturn;
262
+
263
+ /**
264
+ * Hook for dataset operations
265
+ */
266
+ declare function useDatasets(): UseDatasetsReturn;
267
+
268
+ /**
269
+ * Hook for visualization operations
270
+ */
271
+ declare function useVisualizations(): UseVisualizationsReturn;
272
+
273
+ /**
274
+ * Hook for report operations
275
+ */
276
+ declare function useReports(): UseReportsReturn;
277
+
278
+ /**
279
+ * Hook for ML model operations
280
+ */
281
+ declare function useModels(): UseModelsReturn;
282
+
283
+ /**
284
+ * Hook options for {@link useDataSources}.
285
+ */
286
+ interface UseDataSourcesOptions {
287
+ /**
288
+ * P0-69: when true, appends `include_provenance=true` to the list
289
+ * request so each data source comes back with a `_flowstack`
290
+ * workspace attribution envelope. Useful for built apps that need to
291
+ * know which workspace a shared data source belongs to.
292
+ */
293
+ includeProvenance?: boolean;
294
+ }
295
+ /**
296
+ * Hook for data source management
297
+ */
298
+ declare function useDataSources(options?: UseDataSourcesOptions): UseDataSourcesReturn;
299
+
300
+ /**
301
+ * Hook for AI agent interactions
302
+ * @param template - Agent template to use (default: 'data-science'). NOTE
303
+ * (P0-132 / G6): for apps whose brain is a registered persona, this template
304
+ * only sets a fallback agent_name + default instructions that the persona
305
+ * overrides — it does NOT mean the app runs on a "data-science parent agent".
306
+ * Pass a persona via `options.persona` (G4) to target it explicitly, or
307
+ * `options.systemPrompt` (G5) for an inline prompt. The default is fine for
308
+ * persona-backed apps; 'custom' is the honest label when no template applies.
309
+ */
310
+ declare function useAgent(template?: AgentTemplate, options?: UseAgentOptions): UseAgentReturn;
311
+
312
+ /**
313
+ * Hook for direct query execution
314
+ */
315
+ declare function useQuery(): UseQueryReturn;
316
+
317
+ /**
318
+ * Agent Factory Type Definitions
319
+ *
320
+ * Types for the intent-based agent factory system.
321
+ */
322
+
323
+ /**
324
+ * Extended agent configuration with dynamic properties
325
+ */
326
+ interface DynamicAgentConfig {
327
+ /** Base template for defaults */
328
+ template: AgentTemplate;
329
+ /** Custom system prompt - overrides template default */
330
+ systemPrompt?: string;
331
+ /** Tool whitelist - limits available tools */
332
+ tools?: string[];
333
+ /** Enable streaming responses */
334
+ streaming?: boolean;
335
+ /** Network mode for code execution */
336
+ networkMode?: 'SANDBOX' | 'PUBLIC';
337
+ /** Agent display name */
338
+ name?: string;
339
+ /** Agent description for debugging */
340
+ description?: string;
341
+ /** Additional metadata */
342
+ metadata?: Record<string, unknown>;
343
+ /** Created timestamp */
344
+ createdAt?: Date;
345
+ /** Last used timestamp */
346
+ lastUsedAt?: Date;
347
+ }
348
+ /**
349
+ * Intent categories for matching
350
+ */
351
+ type IntentCategory = 'data_analysis' | 'visualization' | 'data_transformation' | 'machine_learning' | 'content_creation' | 'research' | 'customer_support' | 'code_generation' | 'general_assistant' | 'custom';
352
+ /**
353
+ * Extracted entity from intent string
354
+ */
355
+ interface IntentEntity {
356
+ /** Entity type */
357
+ type: 'data_source' | 'output_format' | 'domain' | 'constraint' | 'action';
358
+ /** Extracted value */
359
+ value: string;
360
+ /** Position in original string */
361
+ position: number;
362
+ }
363
+ /**
364
+ * Result of intent analysis
365
+ */
366
+ interface IntentAnalysis {
367
+ /** Detected primary intent category */
368
+ category: IntentCategory;
369
+ /** Confidence score 0-1 */
370
+ confidence: number;
371
+ /** Extracted entities from intent */
372
+ entities: IntentEntity[];
373
+ /** Suggested agent configuration */
374
+ suggestedConfig: Partial<DynamicAgentConfig>;
375
+ /** Original intent string */
376
+ originalIntent: string;
377
+ /** Analysis method used */
378
+ method: 'rule' | 'llm' | 'hybrid';
379
+ }
380
+ /**
381
+ * Intent pattern for rule-based matching
382
+ */
383
+ interface IntentPattern {
384
+ /** Unique pattern identifier */
385
+ id: string;
386
+ /** Category this pattern maps to */
387
+ category: IntentCategory;
388
+ /** Regex patterns to match */
389
+ patterns: RegExp[];
390
+ /** Keywords to look for */
391
+ keywords: string[];
392
+ /** Suggested config when matched */
393
+ suggestedConfig: Partial<DynamicAgentConfig>;
394
+ /** Priority for pattern matching (higher = checked first) */
395
+ priority?: number;
396
+ }
397
+ /**
398
+ * Registered agent entry
399
+ */
400
+ interface RegisteredAgent {
401
+ /** Unique agent identifier */
402
+ id: string;
403
+ /** Human-readable agent name */
404
+ name: string;
405
+ /** Agent configuration */
406
+ config: DynamicAgentConfig;
407
+ /** Original intent that created this agent */
408
+ intent: string;
409
+ /** Analysis result */
410
+ analysis: IntentAnalysis;
411
+ /** Creation timestamp */
412
+ createdAt: Date;
413
+ /** Last used timestamp */
414
+ lastUsedAt: Date;
415
+ /** Number of times this agent was used */
416
+ usageCount: number;
417
+ }
418
+ /**
419
+ * Agent factory configuration options
420
+ */
421
+ interface AgentFactoryOptions {
422
+ /** Use LLM for ambiguous intents (default: true) */
423
+ useLLMFallback?: boolean;
424
+ /** Minimum confidence for rule-based matching (default: 0.7) */
425
+ ruleConfidenceThreshold?: number;
426
+ /** Cache created agents (default: true) */
427
+ enableCache?: boolean;
428
+ /** Cache TTL in milliseconds (default: 30 minutes) */
429
+ cacheTTL?: number;
430
+ /** Custom intent patterns to add */
431
+ customPatterns?: IntentPattern[];
432
+ }
433
+ /**
434
+ * Intent analyzer configuration options
435
+ */
436
+ interface IntentAnalyzerOptions {
437
+ /** Custom patterns to add to default patterns */
438
+ customPatterns?: IntentPattern[];
439
+ /** Minimum confidence threshold for rule-based (default: 0.7) */
440
+ confidenceThreshold?: number;
441
+ /** Enable LLM fallback for low-confidence matches (default: true) */
442
+ useLLMFallback?: boolean;
443
+ }
444
+ /**
445
+ * Agent registry configuration options
446
+ */
447
+ interface AgentRegistryOptions {
448
+ /** Enable caching (default: true) */
449
+ enableCache?: boolean;
450
+ /** Cache TTL in milliseconds (default: 30 minutes) */
451
+ cacheTTL?: number;
452
+ }
453
+ /**
454
+ * Options for useIntentAgent hook
455
+ */
456
+ interface UseIntentAgentOptions extends AgentFactoryOptions {
457
+ /** Initial intent to create agent with */
458
+ initialIntent?: string;
459
+ }
460
+ /**
461
+ * Return type for useIntentAgent hook
462
+ */
463
+ interface UseIntentAgentReturn {
464
+ /** Create agent from intent */
465
+ createAgent: (intent: string) => Promise<RegisteredAgent>;
466
+ /** Execute query with current agent */
467
+ query: (prompt: string) => Promise<void>;
468
+ /** Current agent (if created) */
469
+ agent: RegisteredAgent | null;
470
+ /** Chat messages */
471
+ messages: ChatMessage[];
472
+ /** Streaming state */
473
+ isStreaming: boolean;
474
+ /** Loading state during agent creation */
475
+ isCreating: boolean;
476
+ /** Tool calls from current session */
477
+ toolCalls: ToolCall[];
478
+ /** Error state */
479
+ error: string | null;
480
+ /** Clear current agent and messages */
481
+ reset: () => void;
482
+ /** List all registered agents */
483
+ listAgents: () => RegisteredAgent[];
484
+ /** Switch to a registered agent by ID */
485
+ useAgent: (agentId: string) => void;
486
+ /** Remove an agent by ID */
487
+ removeAgent: (agentId: string) => boolean;
488
+ }
489
+ /**
490
+ * Function type for executing LLM queries (used for fallback analysis)
491
+ */
492
+ type LLMExecutor = (prompt: string) => Promise<string>;
493
+
494
+ /**
495
+ * Hook for intent-based AI agent interactions
496
+ *
497
+ * @param options - Factory configuration options
498
+ */
499
+ declare function useIntentAgent(options?: UseIntentAgentOptions): UseIntentAgentReturn;
500
+
501
+ interface AuthGuardOptions {
502
+ /** Require authentication (default: true) */
503
+ requireAuth?: boolean;
504
+ /** Require a workspace to be selected */
505
+ requireWorkspace?: boolean;
506
+ /** URL to redirect to when not authenticated */
507
+ redirectTo?: string;
508
+ }
509
+ interface UseAuthGuardReturn {
510
+ /** Whether the user is allowed to access the protected content */
511
+ isAllowed: boolean;
512
+ /** Whether auth state is still being determined */
513
+ isLoading: boolean;
514
+ /** Whether a redirect should occur */
515
+ shouldRedirect: boolean;
516
+ /** The URL to redirect to (if shouldRedirect is true) */
517
+ redirectTo?: string;
518
+ /** Whether the user is authenticated */
519
+ isAuthenticated: boolean;
520
+ /** Whether a workspace is selected */
521
+ hasWorkspace: boolean;
522
+ }
523
+ /**
524
+ * Hook for programmatic auth guard logic
525
+ */
526
+ declare function useAuthGuard(options?: AuthGuardOptions): UseAuthGuardReturn;
527
+
528
+ type ConnectionStatus = 'unknown' | 'connecting' | 'connected' | 'disconnected' | 'error';
529
+ interface UseFlowstackStatusReturn {
530
+ /** Current connection status */
531
+ status: ConnectionStatus;
532
+ /** Whether connected to backend */
533
+ isConnected: boolean;
534
+ /** Whether currently checking connection */
535
+ isChecking: boolean;
536
+ /** Last measured latency in milliseconds */
537
+ latency: number | null;
538
+ /** Last successful connection time */
539
+ lastConnected: Date | null;
540
+ /** Last error message if any */
541
+ error: string | null;
542
+ /** Manually trigger a connection check */
543
+ checkConnection: () => Promise<void>;
544
+ }
545
+ interface UseFlowstackStatusOptions {
546
+ /** Polling interval in milliseconds (default: 30000) */
547
+ pollInterval?: number;
548
+ /** Whether to poll automatically (default: true) */
549
+ autoPoll?: boolean;
550
+ /** Whether to check on mount (default: true) */
551
+ checkOnMount?: boolean;
552
+ }
553
+ /**
554
+ * Hook for monitoring Flowstack backend status
555
+ */
556
+ declare function useFlowstackStatus(options?: UseFlowstackStatusOptions): UseFlowstackStatusReturn;
557
+
558
+ /**
559
+ * Hook for user management operations
560
+ */
561
+ declare function useUserManagement(): UseUserManagementReturn;
562
+
563
+ /**
564
+ * Hook for published site management
565
+ */
566
+ declare function useSites(): UseSitesReturn;
567
+
568
+ declare function useAgents(): UseAgentsReturn;
569
+
570
+ /**
571
+ * useCollection — Direct MongoDB access for built-app components.
572
+ *
573
+ * Provides reactive read access and direct write mutations (insert, update, remove)
574
+ * to MongoDB collections. The agent is NOT involved in data operations.
575
+ *
576
+ * Collection names are auto-prefixed with app_scope by the backend —
577
+ * just pass the short name (e.g. 'transactions', not 'site_abc__transactions').
578
+ *
579
+ * Usage:
580
+ * const { documents, isLoading, insert, update, remove } = useCollection<Transaction>('transactions', {
581
+ * sort: { date: -1 },
582
+ * limit: 50,
583
+ * refreshOnAgentComplete: true,
584
+ * });
585
+ *
586
+ * // Insert a document — auto-refetches all useCollection('transactions') instances
587
+ * await insert({ date: '2026-04-02', amount: 42.50, category: 'Groceries' });
588
+ *
589
+ * // Update a document
590
+ * await update({ _id: docId }, { $set: { category: 'Dining' } });
591
+ *
592
+ * // Delete a document
593
+ * await remove({ _id: docId });
594
+ */
595
+
596
+ interface UseCollectionOptions {
597
+ /** MongoDB query filter (e.g. { status: 'pending' }) */
598
+ filter?: Record<string, any>;
599
+ /** Max documents to return (default 50, max 500) */
600
+ limit?: number;
601
+ /** Skip N documents for pagination */
602
+ skip?: number;
603
+ /** Sort spec (e.g. { date: -1 } for newest first) */
604
+ sort?: Record<string, 1 | -1>;
605
+ /** Field projection (e.g. { _id: 0, amount: 1 }) */
606
+ projection?: Record<string, 0 | 1>;
607
+ /** Auto-poll interval in ms (optional — no polling by default) */
608
+ refreshInterval?: number;
609
+ /** Auto-refresh when agent completes a MongoDB write (default false) */
610
+ refreshOnAgentComplete?: boolean;
611
+ /** Skip initial fetch (useful for conditional rendering) */
612
+ enabled?: boolean;
613
+ /** Data layer override: 'shared' | 'user' | 'auto' (default: backend decides via app_config) */
614
+ layer?: CollectionLayer;
615
+ /**
616
+ * P0-69: include workspace provenance envelope (`_flowstack`) on every
617
+ * document in the response. Sends `include_provenance=true` on the
618
+ * query string. When true, each document will have a `_flowstack`
619
+ * field with workspace attribution metadata. Default false.
620
+ */
621
+ includeProvenance?: boolean;
622
+ }
623
+ interface UseCollectionReturn<T> {
624
+ /** Array of documents from the collection */
625
+ documents: T[];
626
+ /** Number of documents returned (≤ limit) */
627
+ count: number;
628
+ /** Total documents matching the filter (for pagination) */
629
+ total: number;
630
+ /** Loading state */
631
+ isLoading: boolean;
632
+ /** Error message if query failed */
633
+ error: string | null;
634
+ /** Manual refresh — re-fetches with current options */
635
+ refresh: () => Promise<void>;
636
+ /** Insert one or more documents. Auto-refetches after success. */
637
+ insert: (doc: Partial<T> | Partial<T>[]) => Promise<{
638
+ inserted_ids: string[];
639
+ }>;
640
+ /** Update documents matching filter. Auto-refetches after success. */
641
+ update: (filter: Record<string, any>, update: Record<string, any>, opts?: {
642
+ upsert?: boolean;
643
+ }) => Promise<{
644
+ modified_count: number;
645
+ }>;
646
+ /** Delete documents matching filter. Auto-refetches after success. */
647
+ remove: (filter: Record<string, any>) => Promise<{
648
+ deleted_count: number;
649
+ }>;
650
+ }
651
+ declare const COLLECTION_CHANGED_EVENT = "flowstack:collection-changed";
652
+ declare function useCollection<T = Record<string, any>>(collection: string, options?: UseCollectionOptions): UseCollectionReturn<T>;
653
+
654
+ interface UseToolInvocationOptions {
655
+ /** Target agent name (e.g. "finance_agent") */
656
+ agentName: string;
657
+ /** Tool to invoke (e.g. "mongodb_query") */
658
+ toolName: string;
659
+ }
660
+ interface UseToolInvocationReturn<T = any> {
661
+ /** Call the tool with keyword arguments */
662
+ invoke: (kwargs?: Record<string, any>) => Promise<T | null>;
663
+ /** Last successful result */
664
+ result: T | null;
665
+ /** True while the tool call is in flight */
666
+ isLoading: boolean;
667
+ /** Error message from the last failed call */
668
+ error: string | null;
669
+ /** Reset result and error state */
670
+ reset: () => void;
671
+ }
672
+ declare function useToolInvocation<T = any>(options: UseToolInvocationOptions): UseToolInvocationReturn<T>;
673
+
674
+ /**
675
+ * useConnections — Manage external service connections (Google, Reddit, Strava, Twitter, GitHub).
676
+ *
677
+ * Provides status, connect, and disconnect for all supported OAuth integrations.
678
+ * Built apps should include a Settings page that renders connection cards
679
+ * so users can link their accounts to enable agent capabilities.
680
+ *
681
+ * Usage:
682
+ * const { connections, connect, disconnect, refresh, isLoading } = useConnections();
683
+ *
684
+ * // Check if Google Analytics is connected
685
+ * connections.google?.analytics // true | false
686
+ *
687
+ * // Connect Google services
688
+ * connect('google', ['analytics', 'drive']);
689
+ *
690
+ * // Disconnect Reddit
691
+ * disconnect('reddit');
692
+ */
693
+ interface GoogleConnectionStatus {
694
+ connected: boolean;
695
+ email?: string;
696
+ analytics?: boolean;
697
+ ads?: boolean;
698
+ drive?: boolean;
699
+ youtube?: boolean;
700
+ scopes?: string[];
701
+ }
702
+ interface ServiceConnectionStatus {
703
+ connected: boolean;
704
+ username?: string;
705
+ }
706
+ interface GitHubConnectionStatus {
707
+ connected: boolean;
708
+ username?: string;
709
+ avatarUrl?: string;
710
+ }
711
+ interface ConnectionsState {
712
+ google: GoogleConnectionStatus;
713
+ reddit: ServiceConnectionStatus;
714
+ strava: ServiceConnectionStatus;
715
+ twitter: ServiceConnectionStatus;
716
+ github: GitHubConnectionStatus;
717
+ }
718
+ type GoogleService = 'analytics' | 'ads' | 'drive' | 'youtube' | 'all';
719
+ type ServiceProvider = 'google' | 'reddit' | 'strava' | 'twitter' | 'github';
720
+ interface UseConnectionsReturn {
721
+ /** Current connection status for all services */
722
+ connections: ConnectionsState;
723
+ /** Loading state */
724
+ isLoading: boolean;
725
+ /** Error message */
726
+ error: string | null;
727
+ /** Connect a service — opens OAuth popup/redirect */
728
+ connect: (provider: ServiceProvider, services?: GoogleService[]) => Promise<void>;
729
+ /** Disconnect a service */
730
+ disconnect: (provider: ServiceProvider) => Promise<void>;
731
+ /** Refresh connection status */
732
+ refresh: () => Promise<void>;
733
+ }
734
+ declare function useConnections(): UseConnectionsReturn;
735
+
736
+ declare function useSiteVersions(siteId: string | null): UseSiteVersionsReturn;
737
+
738
+ /**
739
+ * useProviderCredentials — Manage LLM provider credentials (BYOK + Ollama).
740
+ *
741
+ * Wraps the /api/v1/user/provider-credentials backend endpoints.
742
+ * Used by the Casino "Models" settings tab to list, create, and delete
743
+ * provider credentials including Ollama local inference.
744
+ *
745
+ * Usage:
746
+ * const { credentials, purposes, createCredential, deleteCredential, isLoading } = useProviderCredentials();
747
+ */
748
+
749
+ interface CreateCredentialParams {
750
+ provider: LLMProvider;
751
+ api_key?: string;
752
+ host?: string;
753
+ model_id?: string;
754
+ purpose?: string;
755
+ is_default?: boolean;
756
+ model_settings?: ProviderModelSettings;
757
+ }
758
+ interface UseProviderCredentialsReturn {
759
+ credentials: ProviderCredential[];
760
+ purposes: PurposeInfo[];
761
+ createCredential: (params: CreateCredentialParams) => Promise<ProviderCredential>;
762
+ deleteCredential: (credentialId: string) => Promise<void>;
763
+ refresh: () => Promise<void>;
764
+ isLoading: boolean;
765
+ error: string | null;
766
+ }
767
+ declare function useProviderCredentials(): UseProviderCredentialsReturn;
768
+
769
+ /**
770
+ * useOllamaDetection — Detect a local Ollama instance and list available models.
771
+ *
772
+ * Probes the Ollama API at the given host (default: http://localhost:11434)
773
+ * via GET /api/tags. If Ollama is running and CORS is enabled, returns the
774
+ * list of locally available models.
775
+ *
776
+ * Note: Users must set OLLAMA_ORIGINS=* (or include the Casino origin) when
777
+ * starting Ollama for browser-side detection to work.
778
+ *
779
+ * Usage:
780
+ * const { available, models, error, detect } = useOllamaDetection();
781
+ */
782
+
783
+ interface UseOllamaDetectionReturn {
784
+ available: boolean;
785
+ models: OllamaLocalModel[];
786
+ host: string;
787
+ error: string | null;
788
+ isDetecting: boolean;
789
+ detect: (host?: string) => Promise<OllamaStatus>;
790
+ }
791
+ declare function useOllamaDetection(initialHost?: string): UseOllamaDetectionReturn;
792
+
793
+ /**
794
+ * useDataOverview — Unified summary of all user-owned data.
795
+ *
796
+ * Fetches workspace artifact counts, site metadata, and MongoDB collection stats.
797
+ * Used by the Casino "My Data" view for the top-level summary cards.
798
+ */
799
+
800
+ interface UseDataOverviewReturn {
801
+ overview: UserDataOverview | null;
802
+ isLoading: boolean;
803
+ error: string | null;
804
+ refresh: () => Promise<void>;
805
+ }
806
+ declare function useDataOverview(): UseDataOverviewReturn;
807
+
808
+ /**
809
+ * useUserCollections — List all MongoDB collections the user owns.
810
+ *
811
+ * Returns collections across all sites, grouped by site ID.
812
+ * Supports optional site_id filtering and schema inclusion.
813
+ */
814
+
815
+ interface UseUserCollectionsOptions {
816
+ siteId?: string;
817
+ includeSchema?: boolean;
818
+ }
819
+ interface UseUserCollectionsReturn {
820
+ collections: UserCollectionInfo[];
821
+ groupedBySite: Record<string, UserCollectionInfo[]>;
822
+ isLoading: boolean;
823
+ error: string | null;
824
+ refresh: () => Promise<void>;
825
+ deleteCollection: (fullName: string) => Promise<boolean>;
826
+ }
827
+ declare function useUserCollections(options?: UseUserCollectionsOptions): UseUserCollectionsReturn;
828
+
829
+ /**
830
+ * useCollectionExplorer — Browse, query, export, and delete a specific MongoDB collection.
831
+ *
832
+ * Provides paginated document browsing, schema inference, CSV/JSON export,
833
+ * and collection deletion for the Casino data explorer.
834
+ */
835
+
836
+ interface UseCollectionExplorerOptions {
837
+ filter?: Record<string, any>;
838
+ limit?: number;
839
+ skip?: number;
840
+ sort?: Record<string, 1 | -1>;
841
+ database?: string;
842
+ }
843
+ interface UseCollectionExplorerReturn<T> {
844
+ documents: T[];
845
+ total: number;
846
+ schema: CollectionSchemaInfo | null;
847
+ isLoading: boolean;
848
+ error: string | null;
849
+ page: number;
850
+ pageSize: number;
851
+ setPage: (page: number) => void;
852
+ refresh: () => Promise<void>;
853
+ exportAs: (format: 'json' | 'csv') => Promise<void>;
854
+ deleteCollection: () => Promise<boolean>;
855
+ }
856
+ declare function useCollectionExplorer<T = Record<string, any>>(collection: string, options?: UseCollectionExplorerOptions): UseCollectionExplorerReturn<T>;
857
+
858
+ /**
859
+ * usePublicCollection — anonymous public submissions for built apps.
860
+ *
861
+ * Provides read and insert access to a public collection that requires
862
+ * NO user authentication. Any visitor can read and write documents.
863
+ * The collection must be declared in the app's publicCollections config.
864
+ *
865
+ * Designed for: leaderboards, guestbooks, comment threads, voting, polls.
866
+ *
867
+ * Usage:
868
+ * const { documents, isLoading, insert } = usePublicCollection<HighScore>('high_scores', {
869
+ * sort: { score: -1 },
870
+ * limit: 25,
871
+ * filter: { album: 'yeezus' },
872
+ * });
873
+ *
874
+ * await insert({ album: 'yeezus', name: 'KEON', score: 12500 });
875
+ *
876
+ * No credentials required — the hook reads appScope from FlowstackProvider config.
877
+ * Rate limiting and spam protection are enforced server-side.
878
+ */
879
+ interface UsePublicCollectionOptions {
880
+ /** MongoDB query filter (e.g. { album: 'yeezus' }) */
881
+ filter?: Record<string, any>;
882
+ /** Max documents to return (default 25, max 200) */
883
+ limit?: number;
884
+ /** Skip N documents for pagination */
885
+ skip?: number;
886
+ /** Sort spec (e.g. { score: -1 } for highest first) */
887
+ sort?: Record<string, 1 | -1>;
888
+ /** Auto-refresh interval in ms (optional) */
889
+ refreshInterval?: number;
890
+ /** Skip initial fetch (useful for conditional rendering) */
891
+ enabled?: boolean;
892
+ }
893
+ interface UsePublicCollectionReturn<T> {
894
+ /** Array of documents (submitter_ip_hash stripped server-side) */
895
+ documents: T[];
896
+ /** Count of documents returned (≤ limit) */
897
+ count: number;
898
+ /** Total documents in collection matching the filter */
899
+ total: number;
900
+ /** Loading state */
901
+ isLoading: boolean;
902
+ /** Error message if query failed */
903
+ error: string | null;
904
+ /** Insert a single document — no auth required */
905
+ insert: (doc: Partial<T>) => Promise<{
906
+ inserted_id: string;
907
+ }>;
908
+ /** Manual refresh */
909
+ refresh: () => Promise<void>;
910
+ }
911
+ declare function usePublicCollection<T = Record<string, any>>(collection: string, options?: UsePublicCollectionOptions): UsePublicCollectionReturn<T>;
912
+
913
+ /**
914
+ * useConversations — fetches the user's past Casino builder conversations
915
+ * from GET /library/conversations. Powers the Sessions sidebar in ChatView.
916
+ */
917
+ interface ConversationSummary {
918
+ id: string;
919
+ title: string;
920
+ preview?: string;
921
+ last_message_at?: string | number;
922
+ message_count?: number;
923
+ starred?: boolean;
924
+ }
925
+ interface UseConversationsOptions {
926
+ limit?: number;
927
+ includeDeleted?: boolean;
928
+ refreshIntervalMs?: number;
929
+ }
930
+ interface UseConversationsReturn {
931
+ conversations: ConversationSummary[];
932
+ isLoading: boolean;
933
+ error: string | null;
934
+ refresh: () => Promise<void>;
935
+ deleteConversation: (sessionId: string) => Promise<boolean>;
936
+ renameConversation: (sessionId: string, title: string) => Promise<boolean>;
937
+ }
938
+ declare function useConversations(options?: UseConversationsOptions): UseConversationsReturn;
939
+
940
+ type IntegrationAuthType = 'bearer' | 'api_key_header' | 'api_key_query' | 'basic' | 'none';
941
+ interface IntegrationEndpoint {
942
+ name: string;
943
+ method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
944
+ path: string;
945
+ description?: string;
946
+ parameters?: Record<string, unknown>;
947
+ }
948
+ interface Integration {
949
+ integration_id: string;
950
+ name: string;
951
+ description: string;
952
+ base_url: string;
953
+ auth_type: IntegrationAuthType;
954
+ /** Redacted preview — raw secrets are never returned after creation */
955
+ auth_preview?: Record<string, unknown>;
956
+ endpoint_count: number;
957
+ endpoints?: IntegrationEndpoint[];
958
+ workspace_id?: string;
959
+ created_at: number;
960
+ updated_at?: number;
961
+ }
962
+ interface CreateIntegrationInput {
963
+ name: string;
964
+ /** 20–300 chars */
965
+ description: string;
966
+ /** HTTPS base URL, e.g. "https://api.stripe.com/v1" */
967
+ base_url: string;
968
+ auth_type?: IntegrationAuthType;
969
+ /** Credentials — encrypted at rest, never returned after save */
970
+ auth_config?: Record<string, unknown>;
971
+ endpoints?: IntegrationEndpoint[];
972
+ workspace_id?: string;
973
+ }
974
+ interface UpdateIntegrationInput {
975
+ name?: string;
976
+ description?: string;
977
+ base_url?: string;
978
+ auth_config?: Record<string, unknown>;
979
+ endpoints?: IntegrationEndpoint[];
980
+ }
981
+ interface UseIntegrationsReturn {
982
+ integrations: Integration[];
983
+ isLoading: boolean;
984
+ error: string | null;
985
+ /** Create and register a new HTTP API integration */
986
+ create: (input: CreateIntegrationInput) => Promise<Integration | null>;
987
+ /** Update an existing integration */
988
+ update: (id: string, input: UpdateIntegrationInput) => Promise<boolean>;
989
+ /** Delete an integration */
990
+ remove: (id: string) => Promise<boolean>;
991
+ /** Get a single integration with full endpoint details */
992
+ get: (id: string) => Promise<Integration | null>;
993
+ /** Refresh the list */
994
+ refresh: () => Promise<void>;
995
+ }
996
+ declare function useIntegrations(): UseIntegrationsReturn;
997
+
998
+ type AutomationOutputType = 'silent' | 'email' | 'webhook' | 'file';
999
+ type AutomationStatus = 'active' | 'paused' | 'error';
1000
+ type AutomationRunStatus = 'success' | 'failure' | 'running' | 'timeout';
1001
+ interface AutomationOutputConfig {
1002
+ /** Where to send results (default: "silent" — stored only) */
1003
+ type: AutomationOutputType;
1004
+ /** Email address — required when type="email" */
1005
+ to?: string;
1006
+ /** Webhook URL — required when type="webhook" */
1007
+ url?: string;
1008
+ /** Custom headers for webhook delivery */
1009
+ headers?: Record<string, string>;
1010
+ /** Output format for file/email: "csv" | "json" | "pdf" */
1011
+ format?: string;
1012
+ /** Subject line template for emails */
1013
+ subject_template?: string;
1014
+ }
1015
+ interface Automation {
1016
+ automation_id: string;
1017
+ name: string;
1018
+ description: string;
1019
+ prompt: string;
1020
+ /** 5-field Unix cron expression */
1021
+ schedule: string;
1022
+ timezone: string;
1023
+ /** Agent persona names to route this job to */
1024
+ target_agents: string[];
1025
+ status: AutomationStatus;
1026
+ output_config: AutomationOutputConfig;
1027
+ max_runtime_seconds: number;
1028
+ retry_on_failure: boolean;
1029
+ max_retries: number;
1030
+ created_at: number;
1031
+ updated_at: number;
1032
+ last_run_at: number;
1033
+ last_run_status: string;
1034
+ run_count: number;
1035
+ failure_count: number;
1036
+ }
1037
+ interface AutomationRun {
1038
+ automation_id: string;
1039
+ run_id: string;
1040
+ status: AutomationRunStatus;
1041
+ started_at: number;
1042
+ completed_at?: number;
1043
+ duration_ms: number;
1044
+ credits_used: number;
1045
+ output_summary: string;
1046
+ output_url?: string;
1047
+ error_msg?: string;
1048
+ }
1049
+ interface CreateAutomationInput {
1050
+ name: string;
1051
+ /** What the agent should do each run */
1052
+ prompt: string;
1053
+ /** 5-field Unix cron, e.g. "0 9 * * 1-5" */
1054
+ schedule: string;
1055
+ timezone?: string;
1056
+ target_agents?: string[];
1057
+ output_config?: Partial<AutomationOutputConfig>;
1058
+ max_runtime_seconds?: number;
1059
+ retry_on_failure?: boolean;
1060
+ max_retries?: number;
1061
+ description?: string;
1062
+ }
1063
+ interface UpdateAutomationInput {
1064
+ name?: string;
1065
+ prompt?: string;
1066
+ schedule?: string;
1067
+ timezone?: string;
1068
+ target_agents?: string[];
1069
+ output_config?: Partial<AutomationOutputConfig>;
1070
+ max_runtime_seconds?: number;
1071
+ retry_on_failure?: boolean;
1072
+ max_retries?: number;
1073
+ description?: string;
1074
+ }
1075
+ interface UseAutomationsReturn {
1076
+ automations: Automation[];
1077
+ isLoading: boolean;
1078
+ error: string | null;
1079
+ /** Create a new scheduled automation */
1080
+ create: (input: CreateAutomationInput) => Promise<Automation | null>;
1081
+ /** Update an existing automation */
1082
+ update: (id: string, input: UpdateAutomationInput) => Promise<boolean>;
1083
+ /** Delete an automation and its EventBridge rule */
1084
+ remove: (id: string) => Promise<boolean>;
1085
+ /** Pause scheduling without deleting */
1086
+ pause: (id: string) => Promise<boolean>;
1087
+ /** Resume a paused automation */
1088
+ resume: (id: string) => Promise<boolean>;
1089
+ /** Trigger an immediate run (ignores schedule) */
1090
+ runNow: (id: string) => Promise<{
1091
+ invoked: boolean;
1092
+ status_code?: number;
1093
+ } | null>;
1094
+ /** Get run history for an automation */
1095
+ getRuns: (id: string, limit?: number) => Promise<AutomationRun[]>;
1096
+ /** Refresh the list */
1097
+ refresh: () => Promise<void>;
1098
+ }
1099
+ declare function useAutomations(): UseAutomationsReturn;
1100
+
1101
+ /**
1102
+ * Mock Fixtures for Development Mode
1103
+ *
1104
+ * Provides realistic test data for development without a backend.
1105
+ */
1106
+
1107
+ /**
1108
+ * Mock user credentials
1109
+ */
1110
+ declare const mockCredentials: FlowstackCredentials;
1111
+ /**
1112
+ * Mock user derived from credentials
1113
+ */
1114
+ declare const mockUser: User;
1115
+ /**
1116
+ * Mock workspaces
1117
+ */
1118
+ declare const mockWorkspaces: WorkspaceInfo[];
1119
+ /**
1120
+ * Mock datasets
1121
+ */
1122
+ declare const mockDatasets: DatasetInfo[];
1123
+ /**
1124
+ * Mock visualizations
1125
+ */
1126
+ declare const mockVisualizations: VisualizationData[];
1127
+ /**
1128
+ * Mock data sources
1129
+ */
1130
+ declare const mockDataSources: DataSource[];
1131
+ /**
1132
+ * Mock chat messages (for demo)
1133
+ */
1134
+ declare const mockChatHistory: ChatMessage[];
1135
+ /**
1136
+ * Generate a unique ID for mock data
1137
+ */
1138
+ declare function generateMockId(prefix?: string): string;
1139
+ /**
1140
+ * Simulate network delay for realistic mock responses
1141
+ */
1142
+ declare function mockDelay(minMs?: number, maxMs?: number): Promise<void>;
1143
+ /**
1144
+ * Mock managed users for admin dashboard
1145
+ */
1146
+ declare const mockManagedUsers: ManagedUser[];
1147
+ /**
1148
+ * Mock user statistics
1149
+ */
1150
+ declare const mockUserStats: UserStats;
1151
+ /**
1152
+ * Mock user activity logs
1153
+ */
1154
+ declare const mockUserActivity: UserActivityLog[];
1155
+
1156
+ interface LoginFormProps {
1157
+ /** Callback on successful login */
1158
+ onSuccess?: () => void;
1159
+ /** Callback on login error */
1160
+ onError?: (error: string) => void;
1161
+ /** Show "Register" link */
1162
+ showRegisterLink?: boolean;
1163
+ /** Register page href */
1164
+ registerHref?: string;
1165
+ /** Custom className for form container */
1166
+ className?: string;
1167
+ /** Custom className for inputs */
1168
+ inputClassName?: string;
1169
+ /** Custom className for button */
1170
+ buttonClassName?: string;
1171
+ /** Custom labels */
1172
+ labels?: {
1173
+ title?: string;
1174
+ email?: string;
1175
+ password?: string;
1176
+ submit?: string;
1177
+ register?: string;
1178
+ loading?: string;
1179
+ };
1180
+ }
1181
+ /**
1182
+ * Login form component
1183
+ */
1184
+ declare function LoginForm({ onSuccess, onError, showRegisterLink, registerHref, className, inputClassName, buttonClassName, labels, }: LoginFormProps): react_jsx_runtime.JSX.Element;
1185
+
1186
+ interface RegisterFormProps {
1187
+ /** Callback on successful registration */
1188
+ onSuccess?: () => void;
1189
+ /** Callback on registration error */
1190
+ onError?: (error: string) => void;
1191
+ /** Show "Login" link */
1192
+ showLoginLink?: boolean;
1193
+ /** Login page href */
1194
+ loginHref?: string;
1195
+ /** Minimum password length */
1196
+ minPasswordLength?: number;
1197
+ /** Custom className for form container */
1198
+ className?: string;
1199
+ /** Custom className for inputs */
1200
+ inputClassName?: string;
1201
+ /** Custom className for button */
1202
+ buttonClassName?: string;
1203
+ /** Custom labels */
1204
+ labels?: {
1205
+ title?: string;
1206
+ email?: string;
1207
+ password?: string;
1208
+ confirmPassword?: string;
1209
+ submit?: string;
1210
+ login?: string;
1211
+ loading?: string;
1212
+ };
1213
+ }
1214
+ /**
1215
+ * Registration form component
1216
+ */
1217
+ declare function RegisterForm({ onSuccess, onError, showLoginLink, loginHref, minPasswordLength, className, inputClassName, buttonClassName, labels, }: RegisterFormProps): react_jsx_runtime.JSX.Element;
1218
+
1219
+ interface GoogleSignInProps {
1220
+ /** Callback on successful sign-in */
1221
+ onSuccess?: () => void;
1222
+ /** Callback on error */
1223
+ onError?: (error: string) => void;
1224
+ /** Custom className */
1225
+ className?: string;
1226
+ /** Button text */
1227
+ label?: string;
1228
+ }
1229
+ /**
1230
+ * Google OAuth sign-in button
1231
+ */
1232
+ declare function GoogleSignIn({ onSuccess, onError, className, label, }: GoogleSignInProps): react_jsx_runtime.JSX.Element;
1233
+
1234
+ interface AuthGuardProps {
1235
+ /** Protected content */
1236
+ children: ReactNode;
1237
+ /** Content to show when not authenticated */
1238
+ fallback?: ReactNode;
1239
+ /** Redirect URL when not authenticated (alternative to fallback) */
1240
+ redirectTo?: string;
1241
+ /** Show loading state while checking auth */
1242
+ loadingComponent?: ReactNode;
1243
+ /** Require a specific workspace to be selected */
1244
+ requireWorkspace?: boolean;
1245
+ /**
1246
+ * Opt-in guest chat for built apps (U1). When the app has an `appScope` and
1247
+ * the site enabled guest chat server-side (`app_config.allowGuestChat`), an
1248
+ * unauthenticated visitor is transparently issued a short-lived guest session
1249
+ * (`POST /auth/guest`) instead of being shown the login gate — removing the
1250
+ * "sign up to the desk" friction. Per-site control lives entirely in the
1251
+ * backend flag: if the site hasn't opted in, `/auth/guest` returns 403 and we
1252
+ * fall back to the normal login UI. Default true, but it's a no-op unless the
1253
+ * app is built with an `appScope` (the Casino dashboard has none, so it is
1254
+ * unaffected and always requires real login).
1255
+ */
1256
+ allowGuest?: boolean;
1257
+ }
1258
+ /**
1259
+ * Auth guard component
1260
+ */
1261
+ declare function AuthGuard({ children, fallback, redirectTo, loadingComponent, requireWorkspace, allowGuest, }: AuthGuardProps): react_jsx_runtime.JSX.Element;
1262
+
1263
+ interface AdminGateProps {
1264
+ children: ReactNode;
1265
+ /** SHA-256 hex hash of the admin password. If omitted, accepts any non-empty password (dev mode). */
1266
+ passwordHash?: string;
1267
+ /** Fallback content shown when not authenticated as admin */
1268
+ fallback?: ReactNode;
1269
+ /** localStorage key for session persistence (default: 'flowstack_admin') */
1270
+ storageKey?: string;
1271
+ }
1272
+ /**
1273
+ * Password-based gate for admin routes in Casino-built apps.
1274
+ * Persists admin access in localStorage for session duration.
1275
+ *
1276
+ * Usage:
1277
+ * <AdminGate passwordHash="a1b2c3...">
1278
+ * <AdminPanel />
1279
+ * </AdminGate>
1280
+ */
1281
+ declare function AdminGate({ children, passwordHash, fallback, storageKey, }: AdminGateProps): react_jsx_runtime.JSX.Element;
1282
+
1283
+ interface BrokeredLoginButtonProps {
1284
+ /** Override broker URL (default https://openinferencefoundation.org/auth/broker). */
1285
+ brokerUrl?: string;
1286
+ /** Button label (default "Continue with Flowstack"). */
1287
+ label?: string;
1288
+ /** Optional wrapper className. */
1289
+ className?: string;
1290
+ /** Fired after credentials are successfully injected. */
1291
+ onSuccess?: (credentials: FlowstackCredentials) => void;
1292
+ }
1293
+ declare function BrokeredLoginButton({ brokerUrl, label, className, onSuccess, }: BrokeredLoginButtonProps): react_jsx_runtime.JSX.Element;
1294
+
1295
+ interface WorkspaceSelectorProps {
1296
+ /** List of workspaces */
1297
+ workspaces: WorkspaceInfo[];
1298
+ /** Currently selected workspace */
1299
+ selected: WorkspaceInfo | null;
1300
+ /** Callback when workspace is selected */
1301
+ onSelect: (workspace: WorkspaceInfo) => void;
1302
+ /** Callback to create new workspace */
1303
+ onCreateNew?: () => void;
1304
+ /** Loading state */
1305
+ isLoading?: boolean;
1306
+ /** Custom className */
1307
+ className?: string;
1308
+ /** Placeholder text */
1309
+ placeholder?: string;
1310
+ }
1311
+ /**
1312
+ * Workspace selector dropdown
1313
+ */
1314
+ declare function WorkspaceSelector({ workspaces, selected, onSelect, onCreateNew, isLoading, className, placeholder, }: WorkspaceSelectorProps): react_jsx_runtime.JSX.Element;
1315
+
1316
+ interface CreateWorkspaceModalProps {
1317
+ /** Whether modal is open */
1318
+ isOpen: boolean;
1319
+ /** Close callback */
1320
+ onClose: () => void;
1321
+ /** Callback after workspace is created */
1322
+ onCreated?: (workspace: WorkspaceInfo) => void;
1323
+ /** Custom className */
1324
+ className?: string;
1325
+ }
1326
+ /**
1327
+ * Create workspace modal
1328
+ */
1329
+ declare function CreateWorkspaceModal({ isOpen, onClose, onCreated, className, }: CreateWorkspaceModalProps): react_jsx_runtime.JSX.Element | null;
1330
+
1331
+ interface DatasetUploaderProps {
1332
+ /** Upload handler */
1333
+ onUpload: (file: File, name?: string) => Promise<DatasetInfo | null>;
1334
+ /** Callback after successful upload */
1335
+ onUploadComplete?: (dataset: DatasetInfo) => void;
1336
+ /** Callback on error */
1337
+ onError?: (error: string) => void;
1338
+ /** Accepted file types */
1339
+ accept?: string;
1340
+ /** Max file size in MB */
1341
+ maxSizeMB?: number;
1342
+ /** Custom className */
1343
+ className?: string;
1344
+ }
1345
+ /**
1346
+ * Dataset uploader component
1347
+ */
1348
+ declare function DatasetUploader({ onUpload, onUploadComplete, onError, accept, maxSizeMB, className, }: DatasetUploaderProps): react_jsx_runtime.JSX.Element;
1349
+
1350
+ interface ChatInterfaceProps {
1351
+ /** Chat messages */
1352
+ messages: ChatMessage[];
1353
+ /** Whether agent is streaming a response */
1354
+ isStreaming?: boolean;
1355
+ /** Send message callback */
1356
+ onSend: (message: string) => void;
1357
+ /** Clear messages callback */
1358
+ onClear?: () => void;
1359
+ /** Cancel current query */
1360
+ onCancel?: () => void;
1361
+ /** Connected data sources to display as badges */
1362
+ dataSources?: DataSourceBadgeInfo[];
1363
+ /** Placeholder text */
1364
+ placeholder?: string;
1365
+ /** Custom className */
1366
+ className?: string;
1367
+ /** Show clear button */
1368
+ showClearButton?: boolean;
1369
+ /** Disable input */
1370
+ disabled?: boolean;
1371
+ }
1372
+ /**
1373
+ * Chat interface component
1374
+ */
1375
+ declare function ChatInterface({ messages, isStreaming, onSend, onClear, onCancel, dataSources, placeholder, className, showClearButton, disabled, }: ChatInterfaceProps): react_jsx_runtime.JSX.Element;
1376
+
1377
+ interface MessageListProps {
1378
+ /** Chat messages */
1379
+ messages: ChatMessage[];
1380
+ /** Whether agent is streaming */
1381
+ isStreaming?: boolean;
1382
+ /** Custom className */
1383
+ className?: string;
1384
+ /** Custom message renderer */
1385
+ renderMessage?: (message: ChatMessage) => React.ReactNode;
1386
+ /** Custom tool call renderer */
1387
+ renderToolCall?: (toolCall: ToolCall) => React.ReactNode;
1388
+ /** Custom visualization renderer */
1389
+ renderVisualization?: (viz: VisualizationData) => React.ReactNode;
1390
+ }
1391
+ /**
1392
+ * Message list component
1393
+ */
1394
+ declare function MessageList({ messages, isStreaming, className, renderMessage, renderToolCall, renderVisualization, }: MessageListProps): react_jsx_runtime.JSX.Element;
1395
+
1396
+ interface MarkdownRendererProps {
1397
+ content: string;
1398
+ isStreaming?: boolean;
1399
+ className?: string;
1400
+ }
1401
+ declare function MarkdownRenderer({ content, className }: MarkdownRendererProps): react_jsx_runtime.JSX.Element;
1402
+
1403
+ interface AuthPageProps {
1404
+ /** Default tab to show */
1405
+ defaultTab?: 'login' | 'register';
1406
+ /** Callback when authentication succeeds */
1407
+ onSuccess?: () => void;
1408
+ /** Callback when authentication fails */
1409
+ onError?: (error: string) => void;
1410
+ /** Custom logo component */
1411
+ logo?: ReactNode;
1412
+ /** Page title */
1413
+ title?: string;
1414
+ /** Show Google Sign In button */
1415
+ showGoogle?: boolean;
1416
+ /**
1417
+ * Show the "Continue with Flowstack" brokered-login button as the primary
1418
+ * CTA (P0-60). Defaults to true — this is the unified-login path for built
1419
+ * apps. Casino itself should pass `false` to avoid opening a broker popup
1420
+ * from the same origin that hosts the broker.
1421
+ */
1422
+ showFlowstackBroker?: boolean;
1423
+ /**
1424
+ * Override the broker URL (default https://openinferencefoundation.org/auth/broker).
1425
+ * Useful for staging or local development.
1426
+ */
1427
+ brokerUrl?: string;
1428
+ /** Custom footer content */
1429
+ footer?: ReactNode;
1430
+ /** Additional CSS class */
1431
+ className?: string;
1432
+ /** Custom styles for the container */
1433
+ containerClassName?: string;
1434
+ /** Custom styles for the card */
1435
+ cardClassName?: string;
1436
+ }
1437
+ /**
1438
+ * Complete authentication page component
1439
+ */
1440
+ declare function AuthPage({ defaultTab, onSuccess, onError, logo, title, showGoogle, showFlowstackBroker, brokerUrl, footer, className, containerClassName, cardClassName, }: AuthPageProps): react_jsx_runtime.JSX.Element;
1441
+
1442
+ interface DashboardLayoutProps {
1443
+ /** Main content */
1444
+ children: ReactNode;
1445
+ /** Sidebar content */
1446
+ sidebar?: ReactNode;
1447
+ /** Header content */
1448
+ header?: ReactNode;
1449
+ /** Footer content */
1450
+ footer?: ReactNode;
1451
+ /** Show workspace selector in header */
1452
+ showWorkspaceSelector?: boolean;
1453
+ /** Show user menu in header */
1454
+ showUserMenu?: boolean;
1455
+ /** Sidebar collapsed by default */
1456
+ sidebarCollapsed?: boolean;
1457
+ /** Sidebar width in pixels */
1458
+ sidebarWidth?: number;
1459
+ /** Header height in pixels */
1460
+ headerHeight?: number;
1461
+ /** Additional CSS class */
1462
+ className?: string;
1463
+ }
1464
+ /**
1465
+ * Dashboard layout component with responsive sidebar
1466
+ */
1467
+ declare function DashboardLayout({ children, sidebar, header, footer, showWorkspaceSelector, showUserMenu, sidebarCollapsed, sidebarWidth, headerHeight, className, }: DashboardLayoutProps): react_jsx_runtime.JSX.Element;
1468
+
1469
+ interface ChatPageProps {
1470
+ /** Page title */
1471
+ title?: string;
1472
+ /** Chat input placeholder */
1473
+ placeholder?: string;
1474
+ /** Welcome message when no messages */
1475
+ welcomeMessage?: ReactNode;
1476
+ /** Header content */
1477
+ header?: ReactNode;
1478
+ /** Sidebar content */
1479
+ sidebar?: ReactNode;
1480
+ /** Show clear button */
1481
+ showClearButton?: boolean;
1482
+ /** Show cancel button during streaming */
1483
+ showCancelButton?: boolean;
1484
+ /** Additional CSS class */
1485
+ className?: string;
1486
+ /** Callback when a message is sent */
1487
+ onMessageSent?: (message: string) => void;
1488
+ /** Callback when an error occurs */
1489
+ onError?: (error: string) => void;
1490
+ }
1491
+ /**
1492
+ * Complete chat page component
1493
+ */
1494
+ declare function ChatPage({ title, placeholder, welcomeMessage, header, sidebar, showClearButton, showCancelButton, className, onMessageSent, onError, }: ChatPageProps): react_jsx_runtime.JSX.Element;
1495
+
1496
+ /**
1497
+ * Server-Sent Events (SSE) parser for streaming responses.
1498
+ *
1499
+ * ─── ARCHITECTURE ───────────────────────────────────────────────────────
1500
+ *
1501
+ * The backend (streaming_v2.py) emits SSE in standard two-line format:
1502
+ *
1503
+ * event: delta
1504
+ * data: {"delta": {"text": "Hello"}}
1505
+ *
1506
+ * event: tool_call
1507
+ * data: {"name": "execute_python", "id": "toolu_01...", "args": {...}}
1508
+ *
1509
+ * event: tool_result
1510
+ * data: {"tool_use_id": "toolu_01...", "content": "...", "status": "success"}
1511
+ *
1512
+ * event: complete
1513
+ * data: {"event_count": 483, "execution_ms": 12340}
1514
+ *
1515
+ * This parser:
1516
+ * 1. Pairs `event:` lines with the next `data:` line (pendingEventType)
1517
+ * 2. Normalizes the JSON payload into a consistent StreamEvent shape
1518
+ * 3. Yields events for consumption by useAgent() hook
1519
+ *
1520
+ * ─── V2 BACKEND EVENT FORMATS ──────────────────────────────────────────
1521
+ *
1522
+ * Text deltas: event: delta → data: {"delta": {"text": "token"}}
1523
+ * Tool calls: event: tool_call → data: {"name": "...", "id": "...", "args": {...}}
1524
+ * Tool results: event: tool_result → data: {"tool_use_id": "...", "content": "..."}
1525
+ * Final text: event: text → data: {"content": "full response", "accumulated": true}
1526
+ * Stream end: event: complete → data: {"event_count": N, "execution_ms": N}
1527
+ * Errors: event: error → data: {"error": "message"}
1528
+ *
1529
+ * ────────────────────────────────────────────────────────────────────────
1530
+ */
1531
+
1532
+ /**
1533
+ * Parse a single SSE line into a StreamEvent.
1534
+ *
1535
+ * Handles three line types:
1536
+ * - "data: {...}" → Parse JSON, normalize to StreamEvent
1537
+ * - "data: [DONE]" → Return done event
1538
+ * - "event: type" → Return bare type (used by parseSSEStream for pairing)
1539
+ *
1540
+ * @param line - Raw SSE line (e.g., "data: {...}")
1541
+ * @returns Parsed StreamEvent or null
1542
+ */
1543
+ declare function parseSSELine(line: string): StreamEvent | null;
1544
+ /**
1545
+ * Async generator that reads a ReadableStream and yields parsed StreamEvents.
1546
+ *
1547
+ * ─── SSE WIRE FORMAT ────────────────────────────────────────────────────
1548
+ *
1549
+ * The backend sends events as two-line pairs separated by blank lines:
1550
+ *
1551
+ * event: delta\n ← event type (optional but v2 always sends it)
1552
+ * data: {"delta":...}\n ← JSON payload
1553
+ * \n ← blank line = end of event
1554
+ *
1555
+ * This generator:
1556
+ * 1. Buffers incoming bytes and splits on newlines
1557
+ * 2. When it sees "event: X", stores X as pendingEventType
1558
+ * 3. When it sees "data: {...}", parses the JSON via normalizeEvent()
1559
+ * 4. Applies the pending event type (overrides whatever normalizeEvent guessed)
1560
+ * 5. Yields the final StreamEvent
1561
+ *
1562
+ * This pairing is critical because normalizeEvent may guess wrong
1563
+ * (e.g., a tool_call payload with "name" field could be mistaken for
1564
+ * tool_use), but the explicit "event: tool_call" line corrects it.
1565
+ *
1566
+ * ────────────────────────────────────────────────────────────────────────
1567
+ *
1568
+ * @param reader - ReadableStreamDefaultReader from fetch response
1569
+ * @returns AsyncGenerator yielding StreamEvents
1570
+ */
1571
+ declare function parseSSEStream(reader: ReadableStreamDefaultReader<Uint8Array>): AsyncGenerator<StreamEvent, void, unknown>;
1572
+ /**
1573
+ * Convenience wrapper: process an SSE stream with callbacks instead of async iteration.
1574
+ * Used when you prefer callback-style over for-await-of.
1575
+ *
1576
+ * @param response - Fetch Response with SSE body
1577
+ * @param onEvent - Called for each parsed StreamEvent
1578
+ * @param onError - Called if the stream throws (optional)
1579
+ */
1580
+ declare function processSSEStream(response: Response, onEvent: (event: StreamEvent) => void, onError?: (error: Error) => void): Promise<void>;
1581
+
1582
+ /**
1583
+ * Storage utilities for credential and state persistence
1584
+ * Supports both localStorage and sessionStorage with user-scoped isolation
1585
+ */
1586
+
1587
+ /**
1588
+ * Save credentials to storage
1589
+ * @param credentials - Credentials to save
1590
+ * @param storageType - Storage type ('local' or 'session')
1591
+ */
1592
+ declare function saveCredentials(credentials: FlowstackCredentials, storageType?: 'local' | 'session'): void;
1593
+ /**
1594
+ * Load credentials from storage
1595
+ * @param storageType - Storage type ('local' or 'session')
1596
+ * @returns Stored credentials or null
1597
+ */
1598
+ declare function loadCredentials(storageType?: 'local' | 'session'): FlowstackCredentials | null;
1599
+ /**
1600
+ * Clear credentials from storage
1601
+ * @param storageType - Storage type ('local' or 'session')
1602
+ */
1603
+ declare function clearCredentials(storageType?: 'local' | 'session'): void;
1604
+ /**
1605
+ * Save selected workspace ID to storage
1606
+ * @param workspaceId - Workspace ID to save
1607
+ * @param credentials - User credentials for scoping
1608
+ * @param storageType - Storage type
1609
+ */
1610
+ declare function saveSelectedWorkspace(workspaceId: string, credentials: FlowstackCredentials | null, storageType?: 'local' | 'session'): void;
1611
+ /**
1612
+ * Load selected workspace ID from storage
1613
+ * @param credentials - User credentials for scoping
1614
+ * @param storageType - Storage type
1615
+ * @returns Workspace ID or null
1616
+ */
1617
+ declare function loadSelectedWorkspace(credentials: FlowstackCredentials | null, storageType?: 'local' | 'session'): string | null;
1618
+ /**
1619
+ * Clear selected workspace from storage
1620
+ * @param credentials - User credentials for scoping
1621
+ * @param storageType - Storage type
1622
+ */
1623
+ declare function clearSelectedWorkspace(credentials: FlowstackCredentials | null, storageType?: 'local' | 'session'): void;
1624
+ /**
1625
+ * Save chat messages to storage
1626
+ * @param messages - Messages to save
1627
+ * @param workspaceId - Workspace ID for scoping
1628
+ * @param credentials - User credentials for scoping
1629
+ * @param storageType - Storage type
1630
+ */
1631
+ declare function saveMessages<T>(messages: T[], workspaceId: string, credentials: FlowstackCredentials | null, storageType?: 'local' | 'session'): void;
1632
+ /**
1633
+ * Load chat messages from storage
1634
+ * @param workspaceId - Workspace ID for scoping
1635
+ * @param credentials - User credentials for scoping
1636
+ * @param storageType - Storage type
1637
+ * @returns Messages array or empty array
1638
+ */
1639
+ declare function loadMessages<T>(workspaceId: string, credentials: FlowstackCredentials | null, storageType?: 'local' | 'session'): T[];
1640
+ /**
1641
+ * Clear chat messages from storage
1642
+ * @param workspaceId - Workspace ID for scoping
1643
+ * @param credentials - User credentials for scoping
1644
+ * @param storageType - Storage type
1645
+ */
1646
+ declare function clearMessages(workspaceId: string, credentials: FlowstackCredentials | null, storageType?: 'local' | 'session'): void;
1647
+ /**
1648
+ * Set an item in storage with optional expiry
1649
+ * @param key - Storage key
1650
+ * @param value - Value to store
1651
+ * @param ttlMs - Time to live in milliseconds (optional)
1652
+ * @param storageType - Storage type
1653
+ */
1654
+ declare function setItem<T>(key: string, value: T, ttlMs?: number, storageType?: 'local' | 'session'): void;
1655
+ /**
1656
+ * Get an item from storage
1657
+ * @param key - Storage key
1658
+ * @param storageType - Storage type
1659
+ * @returns Stored value or null
1660
+ */
1661
+ declare function getItem<T>(key: string, storageType?: 'local' | 'session'): T | null;
1662
+ /**
1663
+ * Remove an item from storage
1664
+ * @param key - Storage key
1665
+ * @param storageType - Storage type
1666
+ */
1667
+ declare function removeItem(key: string, storageType?: 'local' | 'session'): void;
1668
+ /**
1669
+ * Clear all Flowstack-related items from storage. P0-72: also clears
1670
+ * `privy:*` keys as a belt-and-suspenders sweep so a logout always leaves
1671
+ * a clean slate for the next login attempt — even if Privy's own
1672
+ * `logout()` call missed a key. Without this, a Flowstack-only clear
1673
+ * left Privy's sticky session in place and silently re-authed the
1674
+ * same wallet on the next click.
1675
+ * @param storageType - Storage type
1676
+ */
1677
+ declare function clearAllFlowstackData(storageType?: 'local' | 'session'): void;
1678
+
1679
+ /**
1680
+ * Mermaid diagram utilities — sanitization and content parsing.
1681
+ *
1682
+ * Used by both the SDK's MessageList (built apps) and Casino's ChatMessage
1683
+ * to safely render LLM-generated Mermaid code.
1684
+ */
1685
+ /**
1686
+ * Sanitize LLM-generated Mermaid code before passing to the renderer.
1687
+ * Strips HTML tags, replaces special characters in labels, and fixes
1688
+ * common structural issues that break the Mermaid parser.
1689
+ */
1690
+ declare function sanitizeMermaidCode(code: string): string;
1691
+ interface ContentSegment {
1692
+ type: 'text' | 'mermaid';
1693
+ content: string;
1694
+ }
1695
+ /**
1696
+ * Split message content into alternating text and mermaid segments.
1697
+ * Text segments preserve everything outside fenced mermaid blocks.
1698
+ * Mermaid segments contain only the code inside the fences (trimmed).
1699
+ */
1700
+ declare function splitContentSegments(text: string): ContentSegment[];
1701
+
1702
+ /**
1703
+ * Agent Templates
1704
+ *
1705
+ * Pre-configured agent templates for different use cases.
1706
+ */
1707
+
1708
+ /**
1709
+ * Data Science agent template
1710
+ * Optimized for data analysis, ML, and visualization
1711
+ */
1712
+ declare const dataScienceTemplate: AgentConfig;
1713
+ /**
1714
+ * Marketing agent template
1715
+ * Optimized for content, campaigns, and analytics
1716
+ */
1717
+ declare const marketingTemplate: AgentConfig;
1718
+ /**
1719
+ * Support agent template
1720
+ * Optimized for customer support and knowledge base
1721
+ */
1722
+ declare const supportTemplate: AgentConfig;
1723
+ /**
1724
+ * Custom agent template factory
1725
+ */
1726
+ declare function createCustomTemplate(config: Partial<AgentConfig>): AgentConfig;
1727
+ /**
1728
+ * Get agent template by name
1729
+ */
1730
+ declare function getAgentTemplate(name: AgentTemplate): AgentConfig;
1731
+
1732
+ /**
1733
+ * Intent Analyzer
1734
+ *
1735
+ * Analyzes user intent and returns structured analysis with suggested config.
1736
+ * Uses rule-based matching first, falls back to LLM for ambiguous cases.
1737
+ */
1738
+
1739
+ /**
1740
+ * Pre-configured patterns for common intent categories
1741
+ */
1742
+ declare const DEFAULT_PATTERNS: IntentPattern[];
1743
+ /**
1744
+ * Extract entities from intent string
1745
+ */
1746
+ declare function extractEntities(intent: string): IntentEntity[];
1747
+ /**
1748
+ * Analyze intent using rule-based matching
1749
+ */
1750
+ declare function analyzeWithRules(intent: string, customPatterns?: IntentPattern[]): IntentAnalysis | null;
1751
+ /**
1752
+ * Intent Analyzer
1753
+ *
1754
+ * Analyzes user intent strings and produces structured analysis
1755
+ * with suggested agent configurations.
1756
+ */
1757
+ declare class IntentAnalyzer {
1758
+ private customPatterns;
1759
+ private confidenceThreshold;
1760
+ private useLLMFallback;
1761
+ constructor(options?: IntentAnalyzerOptions);
1762
+ /**
1763
+ * Analyze intent and return structured analysis
1764
+ */
1765
+ analyze(intent: string, llmExecutor?: LLMExecutor): Promise<IntentAnalysis>;
1766
+ /**
1767
+ * Register a custom intent pattern
1768
+ */
1769
+ addPattern(pattern: IntentPattern): void;
1770
+ /**
1771
+ * Remove a custom pattern by ID
1772
+ */
1773
+ removePattern(patternId: string): boolean;
1774
+ /**
1775
+ * Get all registered patterns (custom + defaults)
1776
+ */
1777
+ getPatterns(): IntentPattern[];
1778
+ /**
1779
+ * Get only custom patterns
1780
+ */
1781
+ getCustomPatterns(): IntentPattern[];
1782
+ /**
1783
+ * Update confidence threshold
1784
+ */
1785
+ setConfidenceThreshold(threshold: number): void;
1786
+ /**
1787
+ * Enable or disable LLM fallback
1788
+ */
1789
+ setLLMFallback(enabled: boolean): void;
1790
+ }
1791
+
1792
+ /**
1793
+ * Agent Registry
1794
+ *
1795
+ * Stores and manages registered agents with caching support.
1796
+ * Supports fuzzy intent matching to reuse similar agent configurations.
1797
+ */
1798
+
1799
+ /**
1800
+ * Agent Registry
1801
+ *
1802
+ * Manages registration, retrieval, and caching of dynamically created agents.
1803
+ */
1804
+ declare class AgentRegistry {
1805
+ private agents;
1806
+ private intentIndex;
1807
+ private options;
1808
+ constructor(options?: AgentRegistryOptions);
1809
+ /**
1810
+ * Register a new agent
1811
+ */
1812
+ register(agent: RegisteredAgent): void;
1813
+ /**
1814
+ * Get agent by ID
1815
+ */
1816
+ get(id: string): RegisteredAgent | undefined;
1817
+ /**
1818
+ * Find agent by exact intent match
1819
+ */
1820
+ findByExactIntent(intent: string): RegisteredAgent | undefined;
1821
+ /**
1822
+ * Find agent by similar intent (fuzzy matching)
1823
+ */
1824
+ findByIntent(intent: string, threshold?: number): RegisteredAgent | undefined;
1825
+ /**
1826
+ * Record agent usage (updates lastUsedAt and usageCount)
1827
+ */
1828
+ recordUsage(id: string): void;
1829
+ /**
1830
+ * List all registered agents
1831
+ */
1832
+ listAll(): RegisteredAgent[];
1833
+ /**
1834
+ * List agents sorted by usage count (most used first)
1835
+ */
1836
+ listByUsage(): RegisteredAgent[];
1837
+ /**
1838
+ * List agents sorted by last used (most recent first)
1839
+ */
1840
+ listByRecent(): RegisteredAgent[];
1841
+ /**
1842
+ * Remove agent by ID
1843
+ */
1844
+ remove(id: string): boolean;
1845
+ /**
1846
+ * Clear all registered agents
1847
+ */
1848
+ clear(): void;
1849
+ /**
1850
+ * Get registry size
1851
+ */
1852
+ size(): number;
1853
+ /**
1854
+ * Check if agent exists
1855
+ */
1856
+ has(id: string): boolean;
1857
+ /**
1858
+ * Clean expired agents
1859
+ */
1860
+ private cleanExpired;
1861
+ /**
1862
+ * Update cache TTL
1863
+ */
1864
+ setCacheTTL(ttl: number): void;
1865
+ /**
1866
+ * Enable or disable caching
1867
+ */
1868
+ setCacheEnabled(enabled: boolean): void;
1869
+ /**
1870
+ * Export registry state (for persistence)
1871
+ */
1872
+ export(): RegisteredAgent[];
1873
+ /**
1874
+ * Import registry state (for restoration)
1875
+ */
1876
+ import(agents: RegisteredAgent[]): void;
1877
+ }
1878
+
1879
+ /**
1880
+ * Agent Factory
1881
+ *
1882
+ * Creates and manages dynamic agent configurations based on user intent.
1883
+ * Combines IntentAnalyzer for intent parsing and AgentRegistry for storage.
1884
+ */
1885
+
1886
+ /**
1887
+ * Agent Factory
1888
+ *
1889
+ * Creates agents dynamically based on user intent.
1890
+ * Uses rule-based analysis with optional LLM fallback.
1891
+ */
1892
+ declare class AgentFactory {
1893
+ private analyzer;
1894
+ private registry;
1895
+ private options;
1896
+ constructor(options?: AgentFactoryOptions);
1897
+ /**
1898
+ * Create agent from user intent
1899
+ *
1900
+ * @param intent - Natural language description of what the user wants
1901
+ * @param llmExecutor - Optional function to execute LLM queries for fallback analysis
1902
+ * @returns Created or cached RegisteredAgent
1903
+ */
1904
+ createFromIntent(intent: string, llmExecutor?: LLMExecutor): Promise<RegisteredAgent>;
1905
+ /**
1906
+ * Create agent from explicit configuration (bypass intent analysis)
1907
+ *
1908
+ * @param name - Human-readable agent name
1909
+ * @param config - Partial agent configuration
1910
+ * @returns Created RegisteredAgent
1911
+ */
1912
+ createFromConfig(name: string, config: Partial<DynamicAgentConfig>): RegisteredAgent;
1913
+ /**
1914
+ * Build full config from intent analysis
1915
+ */
1916
+ private buildConfig;
1917
+ /**
1918
+ * Generate human-readable agent name from analysis
1919
+ */
1920
+ private generateAgentName;
1921
+ /**
1922
+ * Get agent by ID
1923
+ */
1924
+ getAgent(id: string): RegisteredAgent | undefined;
1925
+ /**
1926
+ * List all registered agents
1927
+ */
1928
+ listAgents(): RegisteredAgent[];
1929
+ /**
1930
+ * List agents by usage (most used first)
1931
+ */
1932
+ listAgentsByUsage(): RegisteredAgent[];
1933
+ /**
1934
+ * List agents by recency (most recent first)
1935
+ */
1936
+ listAgentsByRecent(): RegisteredAgent[];
1937
+ /**
1938
+ * Remove an agent by ID
1939
+ */
1940
+ removeAgent(id: string): boolean;
1941
+ /**
1942
+ * Clear all agents
1943
+ */
1944
+ clearAll(): void;
1945
+ /**
1946
+ * Get number of registered agents
1947
+ */
1948
+ getAgentCount(): number;
1949
+ /**
1950
+ * Record usage of an agent
1951
+ */
1952
+ recordAgentUsage(id: string): void;
1953
+ /**
1954
+ * Get the analyzer instance for direct access
1955
+ */
1956
+ getAnalyzer(): IntentAnalyzer;
1957
+ /**
1958
+ * Get the registry instance for direct access
1959
+ */
1960
+ getRegistry(): AgentRegistry;
1961
+ /**
1962
+ * Export factory state for persistence
1963
+ */
1964
+ exportState(): {
1965
+ agents: RegisteredAgent[];
1966
+ options: AgentFactoryOptions;
1967
+ };
1968
+ /**
1969
+ * Import factory state from persistence
1970
+ */
1971
+ importState(state: {
1972
+ agents: RegisteredAgent[];
1973
+ }): void;
1974
+ }
1975
+
1976
+ /**
1977
+ * Login Route Generator
1978
+ *
1979
+ * Creates a Next.js API route handler for user login.
1980
+ *
1981
+ * @example
1982
+ * ```ts
1983
+ * // app/api/auth/login/route.ts
1984
+ * import { createLoginRoute } from 'flowstack-sdk/api/routes';
1985
+ *
1986
+ * export const POST = createLoginRoute({
1987
+ * jwtSecret: process.env.JWT_SECRET!,
1988
+ * passwordSecret: process.env.PASSWORD_SECRET!,
1989
+ * });
1990
+ * ```
1991
+ */
1992
+
1993
+ interface LoginRouteConfig {
1994
+ /** JWT secret for token signing */
1995
+ jwtSecret: string;
1996
+ /** Token expiration in seconds (default: 86400 = 24 hours) */
1997
+ tokenExpiry?: number;
1998
+ /** Tenant ID (default: shared tenant) */
1999
+ tenantId?: string;
2000
+ /** Sage API base URL */
2001
+ baseUrl?: string;
2002
+ /** Custom user lookup function */
2003
+ getUserByEmail?: (email: string) => Promise<{
2004
+ id: string;
2005
+ email: string;
2006
+ passwordHash: string;
2007
+ } | null>;
2008
+ }
2009
+
2010
+ /**
2011
+ * Register Route Generator
2012
+ *
2013
+ * Creates a Next.js API route handler for user registration.
2014
+ *
2015
+ * @example
2016
+ * ```ts
2017
+ * // app/api/auth/register/route.ts
2018
+ * import { createRegisterRoute } from 'flowstack-sdk/api/routes';
2019
+ *
2020
+ * export const POST = createRegisterRoute({
2021
+ * jwtSecret: process.env.JWT_SECRET!,
2022
+ * passwordSecret: process.env.PASSWORD_SECRET!,
2023
+ * });
2024
+ * ```
2025
+ */
2026
+
2027
+ interface RegisterRouteConfig {
2028
+ /** JWT secret for token signing */
2029
+ jwtSecret: string;
2030
+ /** Token expiration in seconds (default: 86400 = 24 hours) */
2031
+ tokenExpiry?: number;
2032
+ /** Minimum password length (default: 8) */
2033
+ minPasswordLength?: number;
2034
+ /** Tenant ID (default: shared tenant) */
2035
+ tenantId?: string;
2036
+ /** Sage API base URL */
2037
+ baseUrl?: string;
2038
+ /** Custom user creation function */
2039
+ createUser?: (data: {
2040
+ email: string;
2041
+ passwordHash: string;
2042
+ }) => Promise<{
2043
+ id: string;
2044
+ email: string;
2045
+ }>;
2046
+ /** Check if email already exists */
2047
+ userExists?: (email: string) => Promise<boolean>;
2048
+ }
2049
+
2050
+ /**
2051
+ * useModelPreference — User-pinned LLM credential resolution.
2052
+ *
2053
+ * Wraps the backend `/user/model-preference` routes (P0-95 finale):
2054
+ * GET /user/model-preference → current resolved state
2055
+ * PUT /user/model-preference → set or clear pinned credential_id
2056
+ * GET /user/model-preference/options → platform creds available in tenant pool
2057
+ *
2058
+ * The Casino Settings → Model tab (`ModelSettingsView`) drives off this hook;
2059
+ * the previous SDK shim returned the wrong shape and the page error-boundaried
2060
+ * to blank.
2061
+ */
2062
+
2063
+ interface UseModelPreferenceReturn {
2064
+ preference: ModelPreferenceState | null;
2065
+ options: ModelOption[];
2066
+ isLoading: boolean;
2067
+ error: string | null;
2068
+ setPreference: (credentialId: string | null) => Promise<boolean>;
2069
+ refresh: () => Promise<void>;
2070
+ }
2071
+ declare function useModelPreference(): UseModelPreferenceReturn;
2072
+
2073
+ /**
2074
+ * useAdminProviderCredentials — Tenant-admin LLM credential pool management.
2075
+ *
2076
+ * Wraps the backend `/admin/provider-credentials` routes (P0-95 multi-tenant):
2077
+ * GET /admin/provider-credentials/am-i-admin → non-throwing isAdmin gate
2078
+ * GET /admin/provider-credentials → list tenant's platform pool
2079
+ * GET /admin/provider-credentials/existing → non-platform creds (promote candidates)
2080
+ * POST /admin/provider-credentials → create new platform credential
2081
+ * POST /admin/provider-credentials/promote → clone existing into platform pool
2082
+ *
2083
+ * Drives the admin-only sections of the Casino Settings → Model tab.
2084
+ * For non-admins, am-i-admin returns false and the rest of the requests are
2085
+ * skipped — the hook degrades to an empty/no-op state without errors so
2086
+ * non-admin users still see their own model picker.
2087
+ */
2088
+
2089
+ interface UseAdminProviderCredentialsReturn {
2090
+ isAdmin: boolean;
2091
+ isLoading: boolean;
2092
+ error: string | null;
2093
+ credentials: AdminProviderCredential[];
2094
+ existing: ExistingProviderCredential[];
2095
+ create: (input: CreateAdminProviderCredentialInput) => Promise<boolean>;
2096
+ promote: (sourceTenantId: string, credentialId: string) => Promise<boolean>;
2097
+ refresh: () => Promise<void>;
2098
+ }
2099
+ declare function useAdminProviderCredentials(): UseAdminProviderCredentialsReturn;
2100
+
2101
+ type LibraryItemType$1 = string;
2102
+ interface UseLibraryReturn {
2103
+ items: any[];
2104
+ isLoading: boolean;
2105
+ error: string | null;
2106
+ hasMore: boolean;
2107
+ total: number | null;
2108
+ loadMore: () => void;
2109
+ refresh: (search?: string) => void;
2110
+ deleteItem: (name: string) => Promise<boolean>;
2111
+ getDetail: (name: string) => Promise<Record<string, any> | null>;
2112
+ }
2113
+ declare function useLibrary(type: LibraryItemType$1): UseLibraryReturn;
2114
+
2115
+ interface SubagentSummary$1 {
2116
+ id: string;
2117
+ name: string;
2118
+ description: string;
2119
+ source?: string;
2120
+ /** kept for legacy compat (AgentsTab checks this) */
2121
+ created_by?: string;
2122
+ created_at?: string;
2123
+ site_id?: string;
2124
+ }
2125
+ interface SubagentDefinition$1 extends SubagentSummary$1 {
2126
+ system_prompt?: string;
2127
+ /** @deprecated use system_prompt — kept for compat */
2128
+ systemPrompt?: string;
2129
+ tools?: string[];
2130
+ model?: string;
2131
+ max_turns?: number;
2132
+ max_cost_usd?: number;
2133
+ }
2134
+ interface UseSubagentsReturn {
2135
+ subagents: SubagentSummary$1[];
2136
+ builtin: SubagentSummary$1[];
2137
+ userDefined: SubagentSummary$1[];
2138
+ isLoading: boolean;
2139
+ error: string | null;
2140
+ refresh: () => void;
2141
+ uploadSubagent: (file: File) => Promise<SubagentDefinition$1 | null>;
2142
+ deleteSubagent: (name: string) => Promise<boolean>;
2143
+ }
2144
+ declare function useSubagents(): UseSubagentsReturn;
2145
+ /** Fetch full agent definition from GET /library/agents/{name} */
2146
+ declare function getSubagent(credentials: any, name: string, config?: FlowstackClientConfig): Promise<{
2147
+ ok: boolean;
2148
+ data?: SubagentDefinition$1;
2149
+ error?: string;
2150
+ }>;
2151
+
2152
+ /**
2153
+ * useConversation — fetch the full message history for a specific session.
2154
+ *
2155
+ * Used by the built-app sidebar when the user clicks a past conversation —
2156
+ * we hydrate the chat panel by fetching the S3-backed history via
2157
+ * /conversations/{id}/messages and calling restoreConversation on the
2158
+ * shared provider so useAgent renders it.
2159
+ */
2160
+ interface ConversationMessage {
2161
+ id?: string;
2162
+ role: string;
2163
+ content: string | unknown;
2164
+ timestamp?: string;
2165
+ [key: string]: unknown;
2166
+ }
2167
+ interface UseConversationReturn {
2168
+ messages: ConversationMessage[];
2169
+ /** The sessionId these messages belong to — used by ChatView to guard
2170
+ * against painting stale messages from a previous session. */
2171
+ forSessionId: string | null | undefined;
2172
+ isLoading: boolean;
2173
+ error: string | null;
2174
+ refresh: () => Promise<void>;
2175
+ }
2176
+ declare function useConversation(sessionId: string | null | undefined): UseConversationReturn;
2177
+
2178
+ /**
2179
+ * Flowstack SDK
2180
+ *
2181
+ * Complete Backend-as-a-Service for AI-powered apps.
2182
+ *
2183
+ * @example
2184
+ * ```tsx
2185
+ * import { FlowstackProvider, useAuth, useAgent, LoginForm } from 'flowstack-sdk';
2186
+ *
2187
+ * function App() {
2188
+ * return (
2189
+ * <FlowstackProvider config={{ jwtSecret: process.env.JWT_SECRET! }}>
2190
+ * <MyApp />
2191
+ * </FlowstackProvider>
2192
+ * );
2193
+ * }
2194
+ * ```
2195
+ *
2196
+ * @packageDocumentation
2197
+ */
2198
+
2199
+ declare function useCurrentSession(): {
2200
+ currentSession: {
2201
+ sessionId: string;
2202
+ } | null;
2203
+ lockStatus: "available" | "elsewhere" | "claimed";
2204
+ claim: () => Promise<void>;
2205
+ release: () => Promise<void>;
2206
+ };
2207
+
2208
+ declare function useLibraryConversations(): {
2209
+ conversations: LibraryConversationSummary[];
2210
+ isLoading: boolean;
2211
+ error: string | null;
2212
+ refresh: () => void;
2213
+ star: (_id: string) => Promise<void>;
2214
+ unstar: (_id: string) => Promise<void>;
2215
+ deleteConversation: (_id: string) => Promise<void>;
2216
+ };
2217
+ declare function useRecentLibraryConversations(_limit?: number): {
2218
+ items: LibraryConversationSummary[];
2219
+ conversations: LibraryConversationSummary[];
2220
+ isLoading: boolean;
2221
+ error: string | null;
2222
+ refresh: () => void;
2223
+ };
2224
+ declare function useLibrarySearch(_options?: string | {
2225
+ limit?: number;
2226
+ }): {
2227
+ results: LibraryItem[];
2228
+ isLoading: boolean;
2229
+ query: string;
2230
+ setQuery: (_q: string) => void;
2231
+ error: string | null;
2232
+ clear: () => void;
2233
+ };
2234
+ declare function useLibraryTrash(): {
2235
+ items: TrashedItem[];
2236
+ isLoading: boolean;
2237
+ restore: (_id: string) => Promise<void>;
2238
+ deletePermanently: (_id: string) => Promise<void>;
2239
+ refresh: () => void;
2240
+ };
2241
+
2242
+ declare function useSubagentInvoke(): {
2243
+ invoke: (_id: string, _input: Record<string, unknown>) => Promise<SubagentInvokeRun>;
2244
+ isRunning: boolean;
2245
+ error: string | null;
2246
+ };
2247
+
2248
+ declare function listLibraryItems(credentials: {
2249
+ apiKey: string;
2250
+ tenantId: string;
2251
+ userId: string;
2252
+ }, type: string, _options?: {
2253
+ limit?: number;
2254
+ }, config?: {
2255
+ baseUrl?: string;
2256
+ }): Promise<{
2257
+ ok: boolean;
2258
+ data?: {
2259
+ total: number | null;
2260
+ items: unknown[];
2261
+ };
2262
+ error?: string;
2263
+ }>;
2264
+ type LibraryItemType = 'dataset' | 'visualization' | 'code' | 'document' | 'report' | 'model' | 'conversation' | 'script';
2265
+ interface LibraryItem {
2266
+ /** Primary display name (from backend "name" field) */
2267
+ name: string;
2268
+ type?: string;
2269
+ /** ISO string or Unix epoch (number) */
2270
+ created_at?: string | number;
2271
+ updated_at?: string | number;
2272
+ size_bytes?: number;
2273
+ format?: string;
2274
+ source_conversation_title_snapshot?: string;
2275
+ source?: string;
2276
+ id?: string;
2277
+ title?: string;
2278
+ createdAt?: string;
2279
+ [key: string]: unknown;
2280
+ }
2281
+ type LibraryItemDetail = LibraryItem & {
2282
+ content: string;
2283
+ };
2284
+ type LibraryConversationSummary = {
2285
+ id: string;
2286
+ conversation_id?: string;
2287
+ title: string;
2288
+ lastMessageAt?: string;
2289
+ last_activity_at?: string;
2290
+ first_message_preview?: string;
2291
+ last_snippet?: string;
2292
+ message_count?: number;
2293
+ starred?: boolean;
2294
+ };
2295
+ type TrashedItem = {
2296
+ id: string;
2297
+ type: LibraryItemType;
2298
+ title: string;
2299
+ trashedAt: string;
2300
+ };
2301
+ type SubagentSummary = {
2302
+ id: string;
2303
+ name: string;
2304
+ description: string;
2305
+ source?: string;
2306
+ site_id?: string;
2307
+ };
2308
+ type SubagentDefinition = SubagentSummary & {
2309
+ /** snake_case from backend — preferred */
2310
+ system_prompt?: string;
2311
+ /** camelCase alias — kept for compat */
2312
+ systemPrompt?: string;
2313
+ tools?: string[];
2314
+ model?: string;
2315
+ max_turns?: number;
2316
+ max_cost_usd?: number;
2317
+ created_at?: string;
2318
+ };
2319
+ type SubagentInvokeRun = {
2320
+ runId: string;
2321
+ status: 'pending' | 'running' | 'done' | 'error';
2322
+ output: string | null;
2323
+ };
2324
+
2325
+ export { AdminGate, type AdminGateProps, AdminProviderCredential, AgentConfig, AgentFactory, type AgentFactoryOptions, AgentRegistry, type AgentRegistryOptions, AgentTemplate, AuthGuard, type AuthGuardOptions, type AuthGuardProps, AuthPage, type AuthPageProps, type Automation, type AutomationOutputConfig, type AutomationOutputType, type AutomationRun, type AutomationStatus, BrokeredLoginButton, type BrokeredLoginButtonProps, COLLECTION_CHANGED_EVENT, ChatInterface, type ChatInterfaceProps, ChatMessage, ChatPage, type ChatPageProps, CollectionLayer, CollectionSchemaInfo, type ConnectionStatus, type ConnectionsState, type ContentSegment, CreateAdminProviderCredentialInput, type CreateAutomationInput, type CreateCredentialParams, type CreateIntegrationInput, CreateWorkspaceModal, type CreateWorkspaceModalProps, DEFAULT_PATTERNS, DashboardLayout, type DashboardLayoutProps, DataSource, DataSourceBadgeInfo, DatasetInfo, DatasetUploader, type DatasetUploaderProps, type DynamicAgentConfig, type ErrorCode, ErrorCodes, ErrorMessages, ExistingProviderCredential, FlowstackClientConfig, FlowstackConfig, FlowstackContextValue, FlowstackCredentials, FlowstackError, type FlowstackErrorOptions, FlowstackProvider, type GitHubConnectionStatus, type GoogleService, GoogleSignIn, type GoogleSignInProps, type Integration, type IntegrationAuthType, type IntegrationEndpoint, type IntentAnalysis, IntentAnalyzer, type IntentAnalyzerOptions, type IntentCategory, type IntentEntity, type IntentPattern, type LLMExecutor, LLMProvider, type LibraryConversationSummary, type LibraryItem, type LibraryItemDetail, type LibraryItemType, LoginForm, type LoginFormProps, type LoginRouteConfig, ManagedUser, MarkdownRenderer, type MarkdownRendererProps, MessageList, type MessageListProps, ModelOption, ModelPreferenceState, OllamaLocalModel, OllamaStatus, ProviderCredential, ProviderModelSettings, PurposeInfo, RecoveryActions, RegisterForm, type RegisterFormProps, type RegisterRouteConfig, type RegisteredAgent, type ServiceProvider, StreamEvent, type SubagentDefinition, type SubagentInvokeRun, type SubagentSummary, ToolCall, type TrashedItem, type UpdateAutomationInput, type UpdateIntegrationInput, type UseAdminProviderCredentialsReturn, UseAgentOptions, UseAgentReturn, UseAgentsReturn, type UseAuthGuardReturn, UseAuthReturn, type UseAutomationsReturn, type UseCollectionExplorerOptions, type UseCollectionExplorerReturn, type UseCollectionOptions, type UseCollectionReturn, type UseConnectionsReturn, type UseConversationReturn, type UseDataOverviewReturn, UseDataSourcesReturn, UseDatasetsReturn, type UseFlowstackStatusOptions, type UseFlowstackStatusReturn, type UseIntegrationsReturn, type UseIntentAgentOptions, type UseIntentAgentReturn, type UseLibraryReturn, type UseModelPreferenceReturn, UseModelsReturn, type UseProviderCredentialsReturn, type UsePublicCollectionOptions, type UsePublicCollectionReturn, UseQueryReturn, UseReportsReturn, UseSiteVersionsReturn, UseSitesReturn, type UseToolInvocationOptions, type UseToolInvocationReturn, type UseUserCollectionsOptions, type UseUserCollectionsReturn, UseUserManagementReturn, UseVisualizationsReturn, UseWorkspaceReturn, User, UserActivityLog, UserCollectionInfo, UserDataOverview, UserStats, type ValidationResult, VisualizationData, WorkspaceInfo, WorkspaceSelector, type WorkspaceSelectorProps, analyzeWithRules, clearAllFlowstackData, clearCredentials, clearMessages, clearSelectedWorkspace, createCustomTemplate, dataScienceTemplate, extractEntities, generateMockId, getAgentTemplate, getConfigSummary, getItem, getSubagent, isDevelopmentConfig, isFlowstackError, listLibraryItems, loadCredentials, loadMessages, loadSelectedWorkspace, marketingTemplate, mockChatHistory, mockCredentials, mockDataSources, mockDatasets, mockDelay, mockManagedUsers, mockUser, mockUserActivity, mockUserStats, mockVisualizations, mockWorkspaces, parseSSELine, parseSSEStream, processSSEStream, removeItem, sanitizeMermaidCode, saveCredentials, saveMessages, saveSelectedWorkspace, setItem, splitContentSegments, supportTemplate, useAdminProviderCredentials, useAgent, useAgents, useAuth, useAuthGuard, useAutomations, useCollection, useCollectionExplorer, useConnections, useConversation, useConversations, useCurrentSession, useDataOverview, useDataSources, useDatasets, useFlowstack, useFlowstackOptional, useFlowstackStatus, useIntegrations, useIntentAgent, useLibrary, useLibraryConversations, useLibrarySearch, useLibraryTrash, useModelPreference, useModels, useOllamaDetection, useProviderCredentials, usePublicCollection, useQuery, useRecentLibraryConversations, useReports, useSiteVersions, useSites, useSubagentInvoke, useSubagents, useToolInvocation, useUserCollections, useUserManagement, useVisualizations, useWorkspace, validateConfig, validateConfigOrThrow, withErrorHandling };