flowstack-sdk 0.2.1 → 0.2.3

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.
package/dist/index.mjs CHANGED
@@ -269,7 +269,25 @@ async function executeQueryWithConfig(credentials, query, workspaceId, options,
269
269
  })
270
270
  });
271
271
  if (!response.ok) {
272
- throw new Error(`Query failed: ${response.statusText}`);
272
+ let message = response.statusText || "request failed";
273
+ let code;
274
+ let body;
275
+ try {
276
+ body = await response.clone().json();
277
+ const payload = body && typeof body === "object" && "detail" in body && typeof body.detail === "object" ? body.detail : body;
278
+ if (payload && typeof payload === "object") {
279
+ code = payload.code;
280
+ message = payload.error || payload.message || payload.detail || message;
281
+ } else if (typeof payload === "string") {
282
+ message = payload;
283
+ }
284
+ } catch {
285
+ }
286
+ const err = new Error(`Query failed: ${message}`);
287
+ err.status = response.status;
288
+ err.code = code;
289
+ err.body = body;
290
+ throw err;
273
291
  }
274
292
  return response;
275
293
  }
@@ -337,6 +355,63 @@ async function deleteDocuments(credentials, collection, filter, config, layer) {
337
355
  config
338
356
  );
339
357
  }
358
+ function dmPairKey(a, b) {
359
+ return [a, b].sort().join("::");
360
+ }
361
+ function requireAppScope(config) {
362
+ const scope = config?.appScope;
363
+ if (!scope) {
364
+ throw new Error("Private messaging requires an app scope (built-app context).");
365
+ }
366
+ return scope;
367
+ }
368
+ async function listThreads(credentials, config) {
369
+ const scope = requireAppScope(config);
370
+ return flowstackFetch(
371
+ `/apps/${encodeURIComponent(scope)}/threads`,
372
+ { credentials },
373
+ config
374
+ );
375
+ }
376
+ async function listMessages(credentials, withUserKey, options, config) {
377
+ const scope = requireAppScope(config);
378
+ const params = new URLSearchParams();
379
+ params.set("with", withUserKey);
380
+ if (options?.limit) params.set("limit", String(options.limit));
381
+ if (options?.before) params.set("before", options.before);
382
+ return flowstackFetch(
383
+ `/apps/${encodeURIComponent(scope)}/messages?${params.toString()}`,
384
+ { credentials },
385
+ config
386
+ );
387
+ }
388
+ async function sendMessage(credentials, toUserKey, body, config) {
389
+ const scope = requireAppScope(config);
390
+ return flowstackFetch(
391
+ `/apps/${encodeURIComponent(scope)}/messages`,
392
+ { method: "POST", credentials, body: { to_user_key: toUserKey, body } },
393
+ config
394
+ );
395
+ }
396
+ async function openThread(credentials, withUserKey, config) {
397
+ const scope = requireAppScope(config);
398
+ const me = credentials.userId;
399
+ if (!me) throw new Error("openThread requires an authenticated user.");
400
+ const pk = dmPairKey(me, withUserKey);
401
+ return flowstackFetch(
402
+ `/apps/${encodeURIComponent(scope)}/threads/${encodeURIComponent(pk)}/consent`,
403
+ { method: "POST", credentials },
404
+ config
405
+ );
406
+ }
407
+ async function markMessageRead(credentials, messageId, config) {
408
+ const scope = requireAppScope(config);
409
+ return flowstackFetch(
410
+ `/apps/${encodeURIComponent(scope)}/messages/${encodeURIComponent(messageId)}/read`,
411
+ { method: "POST", credentials },
412
+ config
413
+ );
414
+ }
340
415
  async function invokeTool(credentials, agentName, toolName, kwargs = {}, config) {
341
416
  return flowstackFetch(
342
417
  "/tool/invoke",
@@ -6171,6 +6246,124 @@ function useConnections() {
6171
6246
  }, [credentials, config.baseUrl, config.tenantId, refresh]);
6172
6247
  return { connections, isLoading, error, connect, disconnect, refresh };
6173
6248
  }
6249
+ function useThreads(options) {
6250
+ const { credentials, config } = useFlowstack();
6251
+ const [threads, setThreads] = useState([]);
6252
+ const [isLoading, setIsLoading] = useState(false);
6253
+ const [error, setError] = useState(null);
6254
+ const enabled = options?.enabled !== false;
6255
+ const clientConfig = {
6256
+ baseUrl: config.baseUrl,
6257
+ tenantId: config.tenantId,
6258
+ appScope: config.appScope
6259
+ };
6260
+ const refresh = useCallback(async () => {
6261
+ if (!credentials || !enabled) return;
6262
+ setIsLoading(true);
6263
+ setError(null);
6264
+ try {
6265
+ const res = await listThreads(credentials, clientConfig);
6266
+ if (res.ok && res.data) {
6267
+ setThreads(res.data.threads);
6268
+ } else {
6269
+ setError(res.error || "Failed to load threads");
6270
+ }
6271
+ } catch (err) {
6272
+ setError(err?.message || "Failed to load threads");
6273
+ } finally {
6274
+ setIsLoading(false);
6275
+ }
6276
+ }, [credentials, config.baseUrl, config.tenantId, config.appScope, enabled]);
6277
+ useEffect(() => {
6278
+ refresh();
6279
+ }, [refresh]);
6280
+ const intervalRef = useRef(null);
6281
+ useEffect(() => {
6282
+ if (!options?.refreshInterval || !enabled) return;
6283
+ intervalRef.current = setInterval(refresh, options.refreshInterval);
6284
+ return () => {
6285
+ if (intervalRef.current) clearInterval(intervalRef.current);
6286
+ };
6287
+ }, [options?.refreshInterval, enabled, refresh]);
6288
+ const openThread2 = useCallback(
6289
+ async (withUserKey) => {
6290
+ if (!credentials || !withUserKey) return null;
6291
+ const res = await openThread(credentials, withUserKey, clientConfig);
6292
+ if (res.ok && res.data) {
6293
+ await refresh();
6294
+ return res.data.status;
6295
+ }
6296
+ setError(res.error || "Failed to open thread");
6297
+ return null;
6298
+ },
6299
+ // eslint-disable-next-line react-hooks/exhaustive-deps
6300
+ [credentials, config.baseUrl, config.tenantId, config.appScope, refresh]
6301
+ );
6302
+ return { threads, isLoading, error, refresh, openThread: openThread2 };
6303
+ }
6304
+ function useMessages(withUserKey, options) {
6305
+ const { credentials, config } = useFlowstack();
6306
+ const [messages, setMessages] = useState([]);
6307
+ const [isLoading, setIsLoading] = useState(false);
6308
+ const [error, setError] = useState(null);
6309
+ const enabled = options?.enabled !== false && !!withUserKey;
6310
+ const clientConfig = {
6311
+ baseUrl: config.baseUrl,
6312
+ tenantId: config.tenantId,
6313
+ appScope: config.appScope
6314
+ };
6315
+ const refresh = useCallback(async () => {
6316
+ if (!credentials || !withUserKey || !enabled) return;
6317
+ setIsLoading(true);
6318
+ setError(null);
6319
+ try {
6320
+ const res = await listMessages(
6321
+ credentials,
6322
+ withUserKey,
6323
+ { limit: options?.limit },
6324
+ clientConfig
6325
+ );
6326
+ if (res.ok && res.data) {
6327
+ setMessages(res.data.messages);
6328
+ } else {
6329
+ setError(res.error || "Failed to load messages");
6330
+ }
6331
+ } catch (err) {
6332
+ setError(err?.message || "Failed to load messages");
6333
+ } finally {
6334
+ setIsLoading(false);
6335
+ }
6336
+ }, [credentials, withUserKey, config.baseUrl, config.tenantId, config.appScope, enabled, options?.limit]);
6337
+ useEffect(() => {
6338
+ refresh();
6339
+ }, [refresh]);
6340
+ const intervalRef = useRef(null);
6341
+ useEffect(() => {
6342
+ if (!options?.refreshInterval || !enabled) return;
6343
+ intervalRef.current = setInterval(refresh, options.refreshInterval);
6344
+ return () => {
6345
+ if (intervalRef.current) clearInterval(intervalRef.current);
6346
+ };
6347
+ }, [options?.refreshInterval, enabled, refresh]);
6348
+ const send = useCallback(
6349
+ async (body) => {
6350
+ if (!credentials) throw new Error("Not authenticated");
6351
+ if (!withUserKey) throw new Error("No counterpart selected");
6352
+ if (!body || !body.trim()) return;
6353
+ setError(null);
6354
+ const res = await sendMessage(credentials, withUserKey, body, clientConfig);
6355
+ if (!res.ok) {
6356
+ const msg = res.error || "Failed to send message";
6357
+ setError(msg);
6358
+ throw new Error(msg);
6359
+ }
6360
+ await refresh();
6361
+ },
6362
+ // eslint-disable-next-line react-hooks/exhaustive-deps
6363
+ [credentials, withUserKey, config.baseUrl, config.tenantId, config.appScope, refresh]
6364
+ );
6365
+ return { messages, isLoading, error, send, refresh };
6366
+ }
6174
6367
  function normalizeVersion(raw) {
6175
6368
  return {
6176
6369
  version: raw.version || 0,
@@ -6915,7 +7108,7 @@ function useAutomations() {
6915
7108
  return;
6916
7109
  }
6917
7110
  const data = await res.json();
6918
- setAutomations(data.automations ?? []);
7111
+ setAutomations(Array.isArray(data) ? data : data.automations ?? []);
6919
7112
  } catch (e) {
6920
7113
  setError(e.message || "Failed to load automations");
6921
7114
  } finally {
@@ -7014,7 +7207,7 @@ function useAutomations() {
7014
7207
  const res = await fetch(url, { headers: headers() });
7015
7208
  if (!res.ok) return [];
7016
7209
  const data = await res.json();
7017
- return data.runs ?? [];
7210
+ return Array.isArray(data) ? data : data.runs ?? [];
7018
7211
  } catch {
7019
7212
  return [];
7020
7213
  }
@@ -8560,7 +8753,11 @@ function MermaidDiagram({ code }) {
8560
8753
  let cancelled = false;
8561
8754
  async function render() {
8562
8755
  try {
8563
- const mermaid = (await import('mermaid')).default;
8756
+ const mermaidPkg = "mermaid";
8757
+ const mermaid = (await import(
8758
+ /* @vite-ignore */
8759
+ mermaidPkg
8760
+ )).default;
8564
8761
  if (!mermaidInitialized) {
8565
8762
  mermaid.initialize({
8566
8763
  startOnLoad: false,
@@ -10605,6 +10802,6 @@ async function listLibraryItems(credentials, type, _options, config) {
10605
10802
  }
10606
10803
  }
10607
10804
 
10608
- export { AdminGate, AgentFactory, AgentRegistry, AuthGuard, AuthPage, BrokeredLoginButton, CACHE_TTL, COLLECTION_CHANGED_EVENT, COLLECTION_LAYERS, CREDENTIAL_PURPOSES, ChatInterface, ChatPage, CreateWorkspaceModal, DEFAULT_PATTERNS, DEFAULT_PROVIDER_MODEL_SETTINGS, DashboardLayout, DatasetUploader, ErrorCodes, ErrorMessages, FlowstackError, FlowstackProvider, GoogleSignIn, IntentAnalyzer, LLM_PROVIDERS, LoginForm, MarkdownRenderer, MessageList, RecoveryActions, RegisterForm, WorkspaceSelector, addPiiAllowlistTerm, addSiteFile, analyzeWithRules, checkAdminPermissions, clearAllFlowstackData, clearCredentials, clearMessages, clearSelectedWorkspace, createCustomTemplate, createDataSource, createSite, createWorkspace, dataScienceTemplate, deleteCached, deleteDataSource, deleteDataset, deleteDocuments, deleteSite, deleteSiteVersion, deleteUser, deleteUserCollection, executeQuery, executeQueryWithConfig, exportUserCollection, extractEntities, flowstackFetch, generateMockId, getAgentTemplate, getCached, getCachedDatasets, getCachedReports, getCachedSites, getCachedVisualizations, getCachedWorkspaces, getConfigSummary, getConversationHistory, getDataset, getDatasetPreview, getItem, getModel, getPiiAllowlist, getPiiSettings, getSite, getSiteVersions, getSubagent, getUser, getUserActivity, getUserCollectionDocuments, getUserCollectionSchema, getUserCollections, getUserDataOverview, getUserStats, getWorkspace, googleLogin, importFromGitHub, insertDocuments, invalidateAllUserCache, invalidateDatasetsCache, invalidateReportsCache, invalidateSitesCache, invalidateVisualizationsCache, invalidateWorkspaceArtifacts, invalidateWorkspacesCache, invokeTool, isDevelopmentConfig, isFlowstackError, isProviderCredential, listAgents, listDataSources, listDatasets, listGitHubRepos, listLibraryItems, listModels, listReports, listScripts, listSites, listUsers, listVisualizations, listWorkspaces, loadCredentials, loadMessages, loadSelectedWorkspace, login, marketingTemplate, mockChatHistory, mockCredentials, mockDataSources, mockDatasets, mockDelay, mockManagedUsers, mockUser, mockUserActivity, mockUserStats, mockVisualizations, mockWorkspaces, parseSSELine, parseSSEStream, previewPiiMasking, processSSEStream, promoteSiteVersion, publishStagedSite, publishToGitHub, reactivateUser, register, removeItem, removePiiAllowlistTerm, removeSiteAlias, sanitizeMermaidCode, saveCredentials, saveMessages, saveSelectedWorkspace, setCached, setCachedDatasets, setCachedReports, setCachedSites, setCachedVisualizations, setCachedWorkspaces, setItem, setSiteAlias, splitContentSegments, supportTemplate, suspendUser, testDataSource, updateDocuments, updatePiiSettings, updateUser, uploadFile, 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 };
10805
+ export { AdminGate, AgentFactory, AgentRegistry, AuthGuard, AuthPage, BrokeredLoginButton, CACHE_TTL, COLLECTION_CHANGED_EVENT, COLLECTION_LAYERS, CREDENTIAL_PURPOSES, ChatInterface, ChatPage, CreateWorkspaceModal, DEFAULT_PATTERNS, DEFAULT_PROVIDER_MODEL_SETTINGS, DashboardLayout, DatasetUploader, ErrorCodes, ErrorMessages, FlowstackError, FlowstackProvider, GoogleSignIn, IntentAnalyzer, LLM_PROVIDERS, LoginForm, MarkdownRenderer, MessageList, RecoveryActions, RegisterForm, WorkspaceSelector, addPiiAllowlistTerm, addSiteFile, analyzeWithRules, checkAdminPermissions, clearAllFlowstackData, clearCredentials, clearMessages, clearSelectedWorkspace, createCustomTemplate, createDataSource, createSite, createWorkspace, dataScienceTemplate, deleteCached, deleteDataSource, deleteDataset, deleteDocuments, deleteSite, deleteSiteVersion, deleteUser, deleteUserCollection, dmPairKey, executeQuery, executeQueryWithConfig, exportUserCollection, extractEntities, flowstackFetch, generateMockId, getAgentTemplate, getCached, getCachedDatasets, getCachedReports, getCachedSites, getCachedVisualizations, getCachedWorkspaces, getConfigSummary, getConversationHistory, getDataset, getDatasetPreview, getItem, getModel, getPiiAllowlist, getPiiSettings, getSite, getSiteVersions, getSubagent, getUser, getUserActivity, getUserCollectionDocuments, getUserCollectionSchema, getUserCollections, getUserDataOverview, getUserStats, getWorkspace, googleLogin, importFromGitHub, insertDocuments, invalidateAllUserCache, invalidateDatasetsCache, invalidateReportsCache, invalidateSitesCache, invalidateVisualizationsCache, invalidateWorkspaceArtifacts, invalidateWorkspacesCache, invokeTool, isDevelopmentConfig, isFlowstackError, isProviderCredential, listAgents, listDataSources, listDatasets, listGitHubRepos, listLibraryItems, listMessages, listModels, listReports, listScripts, listSites, listThreads, listUsers, listVisualizations, listWorkspaces, loadCredentials, loadMessages, loadSelectedWorkspace, login, markMessageRead, marketingTemplate, mockChatHistory, mockCredentials, mockDataSources, mockDatasets, mockDelay, mockManagedUsers, mockUser, mockUserActivity, mockUserStats, mockVisualizations, mockWorkspaces, openThread, parseSSELine, parseSSEStream, previewPiiMasking, processSSEStream, promoteSiteVersion, publishStagedSite, publishToGitHub, reactivateUser, register, removeItem, removePiiAllowlistTerm, removeSiteAlias, sanitizeMermaidCode, saveCredentials, saveMessages, saveSelectedWorkspace, sendMessage, setCached, setCachedDatasets, setCachedReports, setCachedSites, setCachedVisualizations, setCachedWorkspaces, setItem, setSiteAlias, splitContentSegments, supportTemplate, suspendUser, testDataSource, updateDocuments, updatePiiSettings, updateUser, uploadFile, useAdminProviderCredentials, useAgent, useAgents, useAuth, useAuthGuard, useAutomations, useCollection, useCollectionExplorer, useConnections, useConversation, useConversations, useCurrentSession, useDataOverview, useDataSources, useDatasets, useFlowstack, useFlowstackOptional, useFlowstackStatus, useIntegrations, useIntentAgent, useLibrary, useLibraryConversations, useLibrarySearch, useLibraryTrash, useMessages, useModelPreference, useModels, useOllamaDetection, useProviderCredentials, usePublicCollection, useQuery, useRecentLibraryConversations, useReports, useSiteVersions, useSites, useSubagentInvoke, useSubagents, useThreads, useToolInvocation, useUserCollections, useUserManagement, useVisualizations, useWorkspace, validateConfig, validateConfigOrThrow, withErrorHandling };
10609
10806
  //# sourceMappingURL=index.mjs.map
10610
10807
  //# sourceMappingURL=index.mjs.map