@sinas/sdk 0.5.0 → 0.7.0
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/{chunk-IABVF56L.js → chunk-QDIOYYBA.js} +125 -1
- package/dist/chunk-QDIOYYBA.js.map +1 -0
- package/dist/client.cjs +130 -0
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +103 -1
- package/dist/client.d.ts +103 -1
- package/dist/client.js +13 -1
- package/dist/index.cjs +130 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +13 -1
- package/dist/index.js.map +1 -1
- package/dist/sinas-sdk.umd.js +124 -0
- package/dist/sinas-sdk.umd.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-IABVF56L.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -7,14 +7,18 @@ import {
|
|
|
7
7
|
SinasPermissionError,
|
|
8
8
|
SinasTimeoutError,
|
|
9
9
|
approveToolCall,
|
|
10
|
+
cancelBatch,
|
|
10
11
|
checkPermissions,
|
|
11
12
|
createChat,
|
|
13
|
+
enqueueFunction,
|
|
12
14
|
executeFunction,
|
|
13
15
|
executeQuery,
|
|
14
16
|
generateFileUrl,
|
|
17
|
+
getBatch,
|
|
15
18
|
getChat,
|
|
16
19
|
getInfo,
|
|
17
20
|
getMe,
|
|
21
|
+
listBatchExecutions,
|
|
18
22
|
listCollections,
|
|
19
23
|
listFiles,
|
|
20
24
|
login,
|
|
@@ -27,9 +31,11 @@ import {
|
|
|
27
31
|
stateSet,
|
|
28
32
|
streamFromChannel,
|
|
29
33
|
streamMessage,
|
|
34
|
+
submitAgentBatch,
|
|
35
|
+
submitFunctionBatch,
|
|
30
36
|
uploadFile,
|
|
31
37
|
verifyOTP
|
|
32
|
-
} from "./chunk-
|
|
38
|
+
} from "./chunk-QDIOYYBA.js";
|
|
33
39
|
|
|
34
40
|
// src/hooks/useQuery.ts
|
|
35
41
|
import React2 from "react";
|
|
@@ -604,14 +610,18 @@ export {
|
|
|
604
610
|
SinasProvider,
|
|
605
611
|
SinasTimeoutError,
|
|
606
612
|
approveToolCall,
|
|
613
|
+
cancelBatch,
|
|
607
614
|
checkPermissions,
|
|
608
615
|
createChat,
|
|
616
|
+
enqueueFunction,
|
|
609
617
|
executeFunction,
|
|
610
618
|
executeQuery,
|
|
611
619
|
generateFileUrl,
|
|
620
|
+
getBatch,
|
|
612
621
|
getChat,
|
|
613
622
|
getInfo,
|
|
614
623
|
getMe,
|
|
624
|
+
listBatchExecutions,
|
|
615
625
|
listCollections,
|
|
616
626
|
listFiles,
|
|
617
627
|
login,
|
|
@@ -624,6 +634,8 @@ export {
|
|
|
624
634
|
stateSet,
|
|
625
635
|
streamFromChannel,
|
|
626
636
|
streamMessage,
|
|
637
|
+
submitAgentBatch,
|
|
638
|
+
submitFunctionBatch,
|
|
627
639
|
uploadFile,
|
|
628
640
|
useAuth,
|
|
629
641
|
useChat,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks/useQuery.ts","../src/hooks/context.ts","../src/hooks/useExecute.ts","../src/hooks/useStateStore.ts","../src/hooks/useChat.ts","../src/hooks/useSinas.ts","../src/hooks/useAuth.ts"],"sourcesContent":["import React from 'react';\nimport { executeQuery } from '../client/queries';\nimport { useClient } from './context';\nimport type { QueryResult } from '../client/types';\n\nexport interface UseQueryOptions {\n enabled?: boolean;\n refetchInterval?: number | null;\n}\n\nexport interface UseQueryResult {\n data: Record<string, unknown>[] | null;\n loading: boolean;\n error: string | null;\n rowCount: number | null;\n refetch: (overrideInput?: Record<string, unknown>) => Promise<QueryResult | undefined>;\n}\n\nexport function useQuery(\n ref: string,\n input: Record<string, unknown> = {},\n options: UseQueryOptions = {}\n): UseQueryResult {\n const client = useClient();\n const { enabled = true, refetchInterval = null } = options;\n\n const [data, setData] = React.useState<Record<string, unknown>[] | null>(null);\n const [loading, setLoading] = React.useState(false);\n const [error, setError] = React.useState<string | null>(null);\n const [rowCount, setRowCount] = React.useState<number | null>(null);\n\n const abortRef = React.useRef<AbortController | null>(null);\n const inputJson = JSON.stringify(input);\n\n const execute = React.useCallback(\n async (overrideInput?: Record<string, unknown>) => {\n abortRef.current?.abort();\n const controller = new AbortController();\n abortRef.current = controller;\n\n setLoading(true);\n setError(null);\n try {\n const result = await executeQuery(\n client,\n ref,\n overrideInput || JSON.parse(inputJson)\n );\n if (!controller.signal.aborted) {\n setData(result.data || null);\n setRowCount(result.rowCount ?? result.affectedRows ?? null);\n }\n return result;\n } catch (e) {\n if (!controller.signal.aborted) {\n setError((e as Error).message);\n }\n } finally {\n if (!controller.signal.aborted) {\n setLoading(false);\n }\n }\n },\n [client, ref, inputJson]\n );\n\n React.useEffect(() => {\n if (enabled) {\n execute();\n }\n return () => {\n abortRef.current?.abort();\n };\n }, [enabled, execute]);\n\n React.useEffect(() => {\n if (refetchInterval && enabled) {\n const id = setInterval(execute, refetchInterval);\n return () => clearInterval(id);\n }\n }, [refetchInterval, enabled, execute]);\n\n return { data, loading, error, rowCount, refetch: execute };\n}\n","import React from 'react';\nimport { SinasClient, type SinasClientOptions } from '../client/SinasClient';\n\nconst SinasContext = React.createContext<SinasClient | null>(null);\n\nexport interface SinasProviderProps {\n /** Pre-built client. If provided, options below are ignored. */\n client?: SinasClient;\n /** Standalone-mode options (baseUrl, token callbacks, etc.). */\n options?: SinasClientOptions;\n children: React.ReactNode;\n}\n\nexport function SinasProvider({ client, options, children }: SinasProviderProps) {\n const value = React.useMemo(\n () => client || new SinasClient(options),\n // We intentionally only re-create when `client` reference changes; `options`\n // is expected to be a stable object (callbacks reading from localStorage).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [client],\n );\n return React.createElement(SinasContext.Provider, { value }, children);\n}\n\nexport function useClient(): SinasClient {\n const client = React.useContext(SinasContext);\n if (client) return client;\n return defaultClient;\n}\n\nconst defaultClient = new SinasClient();\n","import React from 'react';\nimport { executeFunction } from '../client/functions';\nimport { useClient } from './context';\nimport type { FunctionResult } from '../client/types';\n\nexport interface UseExecuteResult {\n execute: (input?: Record<string, unknown>, timeout?: number) => Promise<FunctionResult | undefined>;\n result: unknown;\n loading: boolean;\n error: string | null;\n executionId: string | null;\n}\n\nexport function useExecute(ref: string): UseExecuteResult {\n const client = useClient();\n\n const [result, setResult] = React.useState<unknown>(null);\n const [loading, setLoading] = React.useState(false);\n const [error, setError] = React.useState<string | null>(null);\n const [executionId, setExecutionId] = React.useState<string | null>(null);\n\n const execute = React.useCallback(\n async (input: Record<string, unknown> = {}, timeout?: number) => {\n setLoading(true);\n setError(null);\n try {\n const data = await executeFunction(client, ref, input, timeout);\n setResult(data.result);\n setExecutionId(data.executionId);\n if (data.status === 'error') {\n setError(data.error || 'Function execution failed');\n } else if (data.status === 'timeout') {\n setError('Function execution timed out');\n }\n return data;\n } catch (e) {\n setError((e as Error).message);\n } finally {\n setLoading(false);\n }\n },\n [client, ref]\n );\n\n return { execute, result, loading, error, executionId };\n}\n","import React from 'react';\nimport { stateGet, stateSet, stateDelete, stateList } from '../client/states';\nimport { useClient } from './context';\nimport type { StateListResult } from '../client/types';\n\nexport interface UseStateStoreOptions {\n visibility?: 'private' | 'shared';\n}\n\nexport interface UseStateStoreResult {\n value: unknown;\n loading: boolean;\n error: string | null;\n save: (value: unknown, opts?: UseStateStoreOptions) => Promise<void>;\n remove: () => Promise<void>;\n refetch: () => Promise<void>;\n list: () => Promise<StateListResult | undefined>;\n}\n\nexport function useStateStore(ns: string, key?: string): UseStateStoreResult {\n const client = useClient();\n\n const [value, setValue] = React.useState<unknown>(null);\n const [loading, setLoading] = React.useState(true);\n const [error, setError] = React.useState<string | null>(null);\n\n const load = React.useCallback(async () => {\n if (!key) {\n setLoading(false);\n return;\n }\n setLoading(true);\n setError(null);\n try {\n const result = await stateGet(client, ns, key);\n if (result.found) {\n setValue(result.value);\n } else {\n setValue(null);\n }\n } catch (e) {\n setError((e as Error).message);\n } finally {\n setLoading(false);\n }\n }, [client, ns, key]);\n\n const save = React.useCallback(\n async (newValue: unknown, opts?: UseStateStoreOptions) => {\n if (!key) throw new Error('Cannot save without a key');\n setValue(newValue);\n setError(null);\n try {\n await stateSet(client, ns, key, newValue, opts?.visibility);\n } catch (e) {\n setError((e as Error).message);\n throw e;\n }\n },\n [client, ns, key]\n );\n\n const remove = React.useCallback(async () => {\n if (!key) throw new Error('Cannot delete without a key');\n setValue(null);\n setError(null);\n try {\n await stateDelete(client, ns, key);\n } catch (e) {\n setError((e as Error).message);\n throw e;\n }\n }, [client, ns, key]);\n\n const list = React.useCallback(async () => {\n setError(null);\n try {\n return await stateList(client, ns);\n } catch (e) {\n setError((e as Error).message);\n }\n }, [client, ns]);\n\n React.useEffect(() => {\n load();\n }, [load]);\n\n return { value, loading, error, save, remove, refetch: load, list };\n}\n","import React from 'react';\nimport { createChat, getChat, streamMessage, approveToolCall, streamFromChannel } from '../client/chat';\nimport { useClient } from './context';\nimport type { ChatMessageFull, ApprovalRequest, SSEChunk, MessageContent } from '../client/types';\n\nexport interface ToolResult {\n content: string;\n name: string;\n}\n\nexport interface ChatSessionMessage extends ChatMessageFull {\n /** True while streaming content is being appended */\n streaming?: boolean;\n /** Inline tool results keyed by tool_call_id (merged from tool_end events) */\n toolResults?: Record<string, ToolResult>;\n}\n\nexport interface ToolStatus {\n toolCallId: string;\n name: string;\n description: string;\n status: 'running' | 'complete';\n}\n\nexport interface UseChatResult {\n chatId: string | null;\n messages: ChatSessionMessage[];\n loading: boolean;\n streaming: boolean;\n error: string | null;\n pendingApprovals: ApprovalRequest[];\n toolStatus: ToolStatus[];\n send: (content: MessageContent) => void;\n approve: (toolCallId: string) => void;\n reject: (toolCallId: string) => void;\n stop: () => void;\n clearError: () => void;\n}\n\nexport interface UseChatOptions {\n chatId?: string;\n input?: Record<string, unknown>;\n}\n\nexport function useChat(\n agentRef: string,\n options?: UseChatOptions,\n): UseChatResult {\n const client = useClient();\n\n const [chatId, setChatId] = React.useState<string | null>(options?.chatId ?? null);\n const [messages, setMessages] = React.useState<ChatSessionMessage[]>([]);\n const [loading, setLoading] = React.useState(false);\n const [streaming, setStreaming] = React.useState(false);\n const [error, setError] = React.useState<string | null>(null);\n const [pendingApprovals, setPendingApprovals] = React.useState<ApprovalRequest[]>([]);\n const [toolStatus, setToolStatus] = React.useState<ToolStatus[]>([]);\n\n const abortRef = React.useRef<AbortController | null>(null);\n const chatIdRef = React.useRef<string | null>(chatId);\n chatIdRef.current = chatId;\n\n // Load existing chat on mount if chatId provided\n React.useEffect(() => {\n if (!options?.chatId) return;\n let cancelled = false;\n\n setLoading(true);\n getChat(client, options.chatId)\n .then((detail) => {\n if (cancelled) return;\n setChatId(detail.id);\n setMessages(detail.messages);\n if (detail.pendingApprovals?.length) {\n setPendingApprovals(detail.pendingApprovals);\n }\n })\n .catch((e) => {\n if (cancelled) return;\n setError((e as Error).message);\n })\n .finally(() => {\n if (!cancelled) setLoading(false);\n });\n\n return () => { cancelled = true; };\n }, [client, options?.chatId]);\n\n // Cleanup on unmount\n React.useEffect(() => {\n return () => {\n abortRef.current?.abort();\n };\n }, []);\n\n const handleStreamChunks = React.useCallback(\n (chunk: SSEChunk) => {\n if (chunk.event === 'message') {\n // Append text to the last assistant text message, or create a new one.\n const newContent = (() => {\n try {\n const parsed = JSON.parse(chunk.data);\n return parsed.content || '';\n } catch {\n return chunk.data;\n }\n })();\n if (!newContent) return;\n setMessages((prev) => {\n const last = prev[prev.length - 1];\n if (last && last.role === 'assistant' && !last.toolCalls && last.streaming) {\n // Append to existing text message\n const next = [...prev];\n next[next.length - 1] = { ...last, content: (last.content || '') + newContent };\n return next;\n }\n // Create a new text message\n return [...prev, {\n id: `tmp-text-${Date.now()}`,\n chatId: chatIdRef.current || '',\n role: 'assistant' as const,\n content: newContent,\n toolCalls: null,\n toolCallId: null,\n name: null,\n createdAt: new Date().toISOString(),\n streaming: true,\n }];\n });\n } else if (chunk.event === 'tool_start') {\n try {\n const parsed = JSON.parse(chunk.data);\n setToolStatus((prev) => [\n ...prev,\n { toolCallId: parsed.tool_call_id, name: parsed.name, description: parsed.description, status: 'running' },\n ]);\n setMessages((prev) => {\n if (prev.some((m) => m.toolCalls?.some((tc) => tc.id === parsed.tool_call_id))) {\n return prev;\n }\n // Stop streaming on previous text message (freeze it in place)\n const next = prev.map((m, i) =>\n i === prev.length - 1 && m.streaming && m.role === 'assistant' && !m.toolCalls\n ? { ...m, streaming: false }\n : m,\n );\n return [...next, {\n id: `tmp-tc-${parsed.tool_call_id}`,\n chatId: chatIdRef.current || '',\n role: 'assistant' as const,\n content: null,\n toolCalls: [{\n id: parsed.tool_call_id,\n type: 'function' as const,\n function: { name: parsed.name, arguments: parsed.arguments || '{}' },\n description: parsed.description,\n }],\n toolCallId: null,\n name: null,\n createdAt: new Date().toISOString(),\n streaming: true,\n }];\n });\n } catch {\n // ignore malformed tool_start events\n }\n } else if (chunk.event === 'tool_end') {\n try {\n const parsed = JSON.parse(chunk.data);\n setToolStatus((prev) =>\n prev.map((t) => t.toolCallId === parsed.tool_call_id ? { ...t, status: 'complete' } : t),\n );\n // Merge result into the existing tool call message (same bubble)\n if (parsed.result !== undefined) {\n const resultContent = typeof parsed.result === 'string' ? parsed.result : JSON.stringify(parsed.result);\n setMessages((prev) =>\n prev.map((m) => {\n if (m.toolCalls?.some((tc) => tc.id === parsed.tool_call_id)) {\n return {\n ...m,\n toolResults: {\n ...m.toolResults,\n [parsed.tool_call_id]: { content: resultContent, name: parsed.name },\n },\n };\n }\n return m;\n }),\n );\n }\n } catch {\n // ignore malformed tool_end events\n }\n } else if (chunk.event === 'approval_required') {\n try {\n const raw = JSON.parse(chunk.data);\n const parsed: ApprovalRequest = {\n type: raw.type,\n toolCallId: raw.tool_call_id,\n functionNamespace: raw.function_namespace,\n functionName: raw.function_name,\n arguments: raw.arguments,\n };\n setPendingApprovals((prev) => [...prev, parsed]);\n } catch {\n // ignore malformed approval events\n }\n } else if (chunk.event === 'error') {\n try {\n const parsed = JSON.parse(chunk.data);\n setError(parsed.error || 'Stream error');\n } catch {\n setError(chunk.data || 'Stream error');\n }\n }\n },\n [],\n );\n\n const refreshMessages = React.useCallback(\n async (id: string) => {\n try {\n const detail = await getChat(client, id);\n setMessages(detail.messages);\n if (detail.pendingApprovals?.length) {\n setPendingApprovals(detail.pendingApprovals);\n }\n } catch {\n // Refresh is best-effort — streaming content already visible\n }\n },\n [client],\n );\n\n const send = React.useCallback(\n (content: MessageContent) => {\n const doSend = async () => {\n let activeChatId = chatIdRef.current;\n\n // Auto-create chat on first send\n if (!activeChatId) {\n setLoading(true);\n setError(null);\n try {\n const result = await createChat(client, agentRef, options?.input);\n activeChatId = result.id;\n setChatId(result.id);\n chatIdRef.current = result.id;\n } catch (e) {\n setError((e as Error).message);\n setLoading(false);\n return;\n }\n setLoading(false);\n }\n\n abortRef.current?.abort();\n setStreaming(true);\n setError(null);\n setPendingApprovals([]);\n setToolStatus([]);\n\n // Add user message optimistically\n const displayContent = typeof content === 'string' ? content : JSON.stringify(content);\n const userMsg: ChatSessionMessage = {\n id: `tmp-user-${Date.now()}`,\n chatId: activeChatId,\n role: 'user',\n content: displayContent,\n toolCalls: null,\n toolCallId: null,\n name: null,\n createdAt: new Date().toISOString(),\n };\n setMessages((prev) => [...prev, userMsg]);\n\n const controller = streamMessage(\n client,\n activeChatId,\n content,\n handleStreamChunks,\n () => {\n setStreaming(false);\n setToolStatus([]);\n // Refresh to get authoritative server state\n refreshMessages(activeChatId!);\n },\n (err: Error) => {\n setError(err.message);\n setStreaming(false);\n setToolStatus([]);\n },\n );\n\n abortRef.current = controller;\n };\n\n doSend();\n },\n [client, agentRef, options?.input, handleStreamChunks, refreshMessages],\n );\n\n const handleApproval = React.useCallback(\n (toolCallId: string, approved: boolean) => {\n const currentChatId = chatIdRef.current;\n if (!currentChatId) return;\n\n setPendingApprovals((prev) => prev.filter((a) => a.toolCallId !== toolCallId));\n setStreaming(true);\n setError(null);\n\n // No placeholder needed — handleStreamChunks creates messages on demand\n\n (async () => {\n try {\n const result = await approveToolCall(client, currentChatId, toolCallId, approved);\n\n if (!approved) {\n setStreaming(false);\n refreshMessages(currentChatId);\n return;\n }\n\n // Connect to resume stream\n const controller = streamFromChannel(\n client,\n currentChatId,\n result.channelId,\n handleStreamChunks,\n () => {\n setStreaming(false);\n setToolStatus([]);\n refreshMessages(currentChatId);\n },\n (err: Error) => {\n setError(err.message);\n setStreaming(false);\n setToolStatus([]);\n },\n );\n\n abortRef.current = controller;\n } catch (e) {\n setError((e as Error).message);\n setStreaming(false);\n }\n })();\n },\n [client, handleStreamChunks, refreshMessages],\n );\n\n const approve = React.useCallback(\n (toolCallId: string) => handleApproval(toolCallId, true),\n [handleApproval],\n );\n\n const reject = React.useCallback(\n (toolCallId: string) => handleApproval(toolCallId, false),\n [handleApproval],\n );\n\n const stop = React.useCallback(() => {\n abortRef.current?.abort();\n abortRef.current = null;\n setStreaming(false);\n }, []);\n\n const clearError = React.useCallback(() => {\n setError(null);\n }, []);\n\n return {\n chatId,\n messages,\n loading,\n streaming,\n error,\n pendingApprovals,\n toolStatus,\n send,\n approve,\n reject,\n stop,\n clearError,\n };\n}\n","import { useClient } from './context';\nimport { useQuery } from './useQuery';\nimport { useExecute } from './useExecute';\nimport { useStateStore } from './useStateStore';\nimport { useChat } from './useChat';\nimport type { SinasConfig } from '../client/types';\nimport type { SinasClient } from '../client/SinasClient';\n\nexport interface UseSinasResult {\n config: SinasConfig;\n input: Record<string, unknown>;\n client: SinasClient;\n useQuery: typeof useQuery;\n useExecute: typeof useExecute;\n useStateStore: typeof useStateStore;\n useChat: typeof useChat;\n}\n\nexport function useSinas(): UseSinasResult {\n const client = useClient();\n\n return {\n config: client.getConfig(),\n input: client.getInput(),\n client,\n useQuery,\n useExecute,\n useStateStore,\n useChat,\n };\n}\n","import React from 'react';\nimport { useClient } from './context';\nimport { SinasAuthError } from '../client/errors';\nimport type {\n AuthUser,\n InfoResponse,\n LoginResponse,\n OTPVerifyResponse,\n} from '../client/types';\n\nexport type AuthStatus = 'loading' | 'authenticated' | 'unauthenticated';\n\nexport interface UseAuthResult {\n status: AuthStatus;\n user: AuthUser | null;\n info: InfoResponse | null;\n error: string | null;\n\n /**\n * Refresh the session by calling /auth/me with the current access token.\n * Call this on app boot and after token changes.\n */\n refresh: () => Promise<void>;\n\n /**\n * Start a login. In password-only mode this completes the login and\n * returns access/refresh tokens. In OTP / password+OTP mode the response\n * carries a `session_id` to feed into `verifyOTP`.\n */\n login: (email: string, password?: string) => Promise<LoginResponse>;\n\n /** Second step for OTP / password+OTP. Returns the final tokens. */\n verifyOTP: (sessionId: string, otpCode: string) => Promise<OTPVerifyResponse>;\n\n /** Revoke the refresh token and clear local auth state. */\n logout: (refreshToken?: string) => Promise<void>;\n}\n\nexport interface UseAuthOptions {\n /** Refresh on mount. Default true. */\n autoRefresh?: boolean;\n}\n\n/**\n * React hook for the standalone Sinas login flow. The hosting app is\n * responsible for storing the tokens it receives (typically in localStorage)\n * and wiring `getAccessToken` / `getRefreshToken` / `onTokenRefresh` on the\n * SinasProvider so this hook can read the current session.\n */\nexport function useAuth(options: UseAuthOptions = {}): UseAuthResult {\n const { autoRefresh = true } = options;\n const client = useClient();\n\n const [status, setStatus] = React.useState<AuthStatus>('loading');\n const [user, setUser] = React.useState<AuthUser | null>(null);\n const [info, setInfo] = React.useState<InfoResponse | null>(null);\n const [error, setError] = React.useState<string | null>(null);\n\n const refresh = React.useCallback(async () => {\n setError(null);\n try {\n // Fetch /info in parallel with /me (info is unauthenticated and cheap).\n const [infoResp, meResp] = await Promise.all([\n client.auth.getInfo().catch(() => null),\n client.getAccessToken() ? client.auth.getMe().catch(() => null) : Promise.resolve(null),\n ]);\n if (infoResp) setInfo(infoResp);\n if (meResp) {\n setUser(meResp);\n setStatus('authenticated');\n } else {\n setUser(null);\n setStatus('unauthenticated');\n }\n } catch (e) {\n setError(e instanceof Error ? e.message : String(e));\n setStatus('unauthenticated');\n }\n }, [client]);\n\n React.useEffect(() => {\n if (autoRefresh) void refresh();\n }, [autoRefresh, refresh]);\n\n const login = React.useCallback(\n async (email: string, password?: string) => {\n setError(null);\n try {\n return await client.auth.login({ email, password });\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n setError(msg);\n throw e;\n }\n },\n [client],\n );\n\n const verifyOTP = React.useCallback(\n async (sessionId: string, otpCode: string) => {\n setError(null);\n try {\n return await client.auth.verifyOTP({ session_id: sessionId, otp_code: otpCode });\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n setError(msg);\n throw e;\n }\n },\n [client],\n );\n\n const logout = React.useCallback(\n async (refreshToken?: string) => {\n if (refreshToken) {\n try {\n await client.auth.logout(refreshToken);\n } catch (e) {\n if (!(e instanceof SinasAuthError)) throw e;\n }\n }\n setUser(null);\n setStatus('unauthenticated');\n },\n [client],\n );\n\n return { status, user, info, error, refresh, login, verifyOTP, logout };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAOA,YAAW;;;ACAlB,OAAO,WAAW;AAGlB,IAAM,eAAe,MAAM,cAAkC,IAAI;AAU1D,SAAS,cAAc,EAAE,QAAQ,SAAS,SAAS,GAAuB;AAC/E,QAAM,QAAQ,MAAM;AAAA,IAClB,MAAM,UAAU,IAAI,YAAY,OAAO;AAAA;AAAA;AAAA;AAAA,IAIvC,CAAC,MAAM;AAAA,EACT;AACA,SAAO,MAAM,cAAc,aAAa,UAAU,EAAE,MAAM,GAAG,QAAQ;AACvE;AAEO,SAAS,YAAyB;AACvC,QAAM,SAAS,MAAM,WAAW,YAAY;AAC5C,MAAI,OAAQ,QAAO;AACnB,SAAO;AACT;AAEA,IAAM,gBAAgB,IAAI,YAAY;;;ADZ/B,SAAS,SACd,KACA,QAAiC,CAAC,GAClC,UAA2B,CAAC,GACZ;AAChB,QAAM,SAAS,UAAU;AACzB,QAAM,EAAE,UAAU,MAAM,kBAAkB,KAAK,IAAI;AAEnD,QAAM,CAAC,MAAM,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,EAAE,QAAQ,MAAM,MAAM,OAAO,SAAAC,UAAS,OAAAC,QAAO,WAAAC,YAAW,QAAAC,QAAO;AACxE;","names":["React","React","React","React","React","React","React","React","React","React","refresh","login","verifyOTP","logout"]}
|
|
1
|
+
{"version":3,"sources":["../src/hooks/useQuery.ts","../src/hooks/context.ts","../src/hooks/useExecute.ts","../src/hooks/useStateStore.ts","../src/hooks/useChat.ts","../src/hooks/useSinas.ts","../src/hooks/useAuth.ts"],"sourcesContent":["import React from 'react';\nimport { executeQuery } from '../client/queries';\nimport { useClient } from './context';\nimport type { QueryResult } from '../client/types';\n\nexport interface UseQueryOptions {\n enabled?: boolean;\n refetchInterval?: number | null;\n}\n\nexport interface UseQueryResult {\n data: Record<string, unknown>[] | null;\n loading: boolean;\n error: string | null;\n rowCount: number | null;\n refetch: (overrideInput?: Record<string, unknown>) => Promise<QueryResult | undefined>;\n}\n\nexport function useQuery(\n ref: string,\n input: Record<string, unknown> = {},\n options: UseQueryOptions = {}\n): UseQueryResult {\n const client = useClient();\n const { enabled = true, refetchInterval = null } = options;\n\n const [data, setData] = React.useState<Record<string, unknown>[] | null>(null);\n const [loading, setLoading] = React.useState(false);\n const [error, setError] = React.useState<string | null>(null);\n const [rowCount, setRowCount] = React.useState<number | null>(null);\n\n const abortRef = React.useRef<AbortController | null>(null);\n const inputJson = JSON.stringify(input);\n\n const execute = React.useCallback(\n async (overrideInput?: Record<string, unknown>) => {\n abortRef.current?.abort();\n const controller = new AbortController();\n abortRef.current = controller;\n\n setLoading(true);\n setError(null);\n try {\n const result = await executeQuery(\n client,\n ref,\n overrideInput || JSON.parse(inputJson)\n );\n if (!controller.signal.aborted) {\n setData(result.data || null);\n setRowCount(result.rowCount ?? result.affectedRows ?? null);\n }\n return result;\n } catch (e) {\n if (!controller.signal.aborted) {\n setError((e as Error).message);\n }\n } finally {\n if (!controller.signal.aborted) {\n setLoading(false);\n }\n }\n },\n [client, ref, inputJson]\n );\n\n React.useEffect(() => {\n if (enabled) {\n execute();\n }\n return () => {\n abortRef.current?.abort();\n };\n }, [enabled, execute]);\n\n React.useEffect(() => {\n if (refetchInterval && enabled) {\n const id = setInterval(execute, refetchInterval);\n return () => clearInterval(id);\n }\n }, [refetchInterval, enabled, execute]);\n\n return { data, loading, error, rowCount, refetch: execute };\n}\n","import React from 'react';\nimport { SinasClient, type SinasClientOptions } from '../client/SinasClient';\n\nconst SinasContext = React.createContext<SinasClient | null>(null);\n\nexport interface SinasProviderProps {\n /** Pre-built client. If provided, options below are ignored. */\n client?: SinasClient;\n /** Standalone-mode options (baseUrl, token callbacks, etc.). */\n options?: SinasClientOptions;\n children: React.ReactNode;\n}\n\nexport function SinasProvider({ client, options, children }: SinasProviderProps) {\n const value = React.useMemo(\n () => client || new SinasClient(options),\n // We intentionally only re-create when `client` reference changes; `options`\n // is expected to be a stable object (callbacks reading from localStorage).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [client],\n );\n return React.createElement(SinasContext.Provider, { value }, children);\n}\n\nexport function useClient(): SinasClient {\n const client = React.useContext(SinasContext);\n if (client) return client;\n return defaultClient;\n}\n\nconst defaultClient = new SinasClient();\n","import React from 'react';\nimport { executeFunction } from '../client/functions';\nimport { useClient } from './context';\nimport type { FunctionResult } from '../client/types';\n\nexport interface UseExecuteResult {\n execute: (input?: Record<string, unknown>, timeout?: number) => Promise<FunctionResult | undefined>;\n result: unknown;\n loading: boolean;\n error: string | null;\n executionId: string | null;\n}\n\nexport function useExecute(ref: string): UseExecuteResult {\n const client = useClient();\n\n const [result, setResult] = React.useState<unknown>(null);\n const [loading, setLoading] = React.useState(false);\n const [error, setError] = React.useState<string | null>(null);\n const [executionId, setExecutionId] = React.useState<string | null>(null);\n\n const execute = React.useCallback(\n async (input: Record<string, unknown> = {}, timeout?: number) => {\n setLoading(true);\n setError(null);\n try {\n const data = await executeFunction(client, ref, input, timeout);\n setResult(data.result);\n setExecutionId(data.executionId);\n if (data.status === 'error') {\n setError(data.error || 'Function execution failed');\n } else if (data.status === 'timeout') {\n setError('Function execution timed out');\n }\n return data;\n } catch (e) {\n setError((e as Error).message);\n } finally {\n setLoading(false);\n }\n },\n [client, ref]\n );\n\n return { execute, result, loading, error, executionId };\n}\n","import React from 'react';\nimport { stateGet, stateSet, stateDelete, stateList } from '../client/states';\nimport { useClient } from './context';\nimport type { StateListResult } from '../client/types';\n\nexport interface UseStateStoreOptions {\n visibility?: 'private' | 'shared';\n}\n\nexport interface UseStateStoreResult {\n value: unknown;\n loading: boolean;\n error: string | null;\n save: (value: unknown, opts?: UseStateStoreOptions) => Promise<void>;\n remove: () => Promise<void>;\n refetch: () => Promise<void>;\n list: () => Promise<StateListResult | undefined>;\n}\n\nexport function useStateStore(ns: string, key?: string): UseStateStoreResult {\n const client = useClient();\n\n const [value, setValue] = React.useState<unknown>(null);\n const [loading, setLoading] = React.useState(true);\n const [error, setError] = React.useState<string | null>(null);\n\n const load = React.useCallback(async () => {\n if (!key) {\n setLoading(false);\n return;\n }\n setLoading(true);\n setError(null);\n try {\n const result = await stateGet(client, ns, key);\n if (result.found) {\n setValue(result.value);\n } else {\n setValue(null);\n }\n } catch (e) {\n setError((e as Error).message);\n } finally {\n setLoading(false);\n }\n }, [client, ns, key]);\n\n const save = React.useCallback(\n async (newValue: unknown, opts?: UseStateStoreOptions) => {\n if (!key) throw new Error('Cannot save without a key');\n setValue(newValue);\n setError(null);\n try {\n await stateSet(client, ns, key, newValue, opts?.visibility);\n } catch (e) {\n setError((e as Error).message);\n throw e;\n }\n },\n [client, ns, key]\n );\n\n const remove = React.useCallback(async () => {\n if (!key) throw new Error('Cannot delete without a key');\n setValue(null);\n setError(null);\n try {\n await stateDelete(client, ns, key);\n } catch (e) {\n setError((e as Error).message);\n throw e;\n }\n }, [client, ns, key]);\n\n const list = React.useCallback(async () => {\n setError(null);\n try {\n return await stateList(client, ns);\n } catch (e) {\n setError((e as Error).message);\n }\n }, [client, ns]);\n\n React.useEffect(() => {\n load();\n }, [load]);\n\n return { value, loading, error, save, remove, refetch: load, list };\n}\n","import React from 'react';\nimport { createChat, getChat, streamMessage, approveToolCall, streamFromChannel } from '../client/chat';\nimport { useClient } from './context';\nimport type { ChatMessageFull, ApprovalRequest, SSEChunk, MessageContent } from '../client/types';\n\nexport interface ToolResult {\n content: string;\n name: string;\n}\n\nexport interface ChatSessionMessage extends ChatMessageFull {\n /** True while streaming content is being appended */\n streaming?: boolean;\n /** Inline tool results keyed by tool_call_id (merged from tool_end events) */\n toolResults?: Record<string, ToolResult>;\n}\n\nexport interface ToolStatus {\n toolCallId: string;\n name: string;\n description: string;\n status: 'running' | 'complete';\n}\n\nexport interface UseChatResult {\n chatId: string | null;\n messages: ChatSessionMessage[];\n loading: boolean;\n streaming: boolean;\n error: string | null;\n pendingApprovals: ApprovalRequest[];\n toolStatus: ToolStatus[];\n send: (content: MessageContent) => void;\n approve: (toolCallId: string) => void;\n reject: (toolCallId: string) => void;\n stop: () => void;\n clearError: () => void;\n}\n\nexport interface UseChatOptions {\n chatId?: string;\n input?: Record<string, unknown>;\n}\n\nexport function useChat(\n agentRef: string,\n options?: UseChatOptions,\n): UseChatResult {\n const client = useClient();\n\n const [chatId, setChatId] = React.useState<string | null>(options?.chatId ?? null);\n const [messages, setMessages] = React.useState<ChatSessionMessage[]>([]);\n const [loading, setLoading] = React.useState(false);\n const [streaming, setStreaming] = React.useState(false);\n const [error, setError] = React.useState<string | null>(null);\n const [pendingApprovals, setPendingApprovals] = React.useState<ApprovalRequest[]>([]);\n const [toolStatus, setToolStatus] = React.useState<ToolStatus[]>([]);\n\n const abortRef = React.useRef<AbortController | null>(null);\n const chatIdRef = React.useRef<string | null>(chatId);\n chatIdRef.current = chatId;\n\n // Load existing chat on mount if chatId provided\n React.useEffect(() => {\n if (!options?.chatId) return;\n let cancelled = false;\n\n setLoading(true);\n getChat(client, options.chatId)\n .then((detail) => {\n if (cancelled) return;\n setChatId(detail.id);\n setMessages(detail.messages);\n if (detail.pendingApprovals?.length) {\n setPendingApprovals(detail.pendingApprovals);\n }\n })\n .catch((e) => {\n if (cancelled) return;\n setError((e as Error).message);\n })\n .finally(() => {\n if (!cancelled) setLoading(false);\n });\n\n return () => { cancelled = true; };\n }, [client, options?.chatId]);\n\n // Cleanup on unmount\n React.useEffect(() => {\n return () => {\n abortRef.current?.abort();\n };\n }, []);\n\n const handleStreamChunks = React.useCallback(\n (chunk: SSEChunk) => {\n if (chunk.event === 'message') {\n // Append text to the last assistant text message, or create a new one.\n const newContent = (() => {\n try {\n const parsed = JSON.parse(chunk.data);\n return parsed.content || '';\n } catch {\n return chunk.data;\n }\n })();\n if (!newContent) return;\n setMessages((prev) => {\n const last = prev[prev.length - 1];\n if (last && last.role === 'assistant' && !last.toolCalls && last.streaming) {\n // Append to existing text message\n const next = [...prev];\n next[next.length - 1] = { ...last, content: (last.content || '') + newContent };\n return next;\n }\n // Create a new text message\n return [...prev, {\n id: `tmp-text-${Date.now()}`,\n chatId: chatIdRef.current || '',\n role: 'assistant' as const,\n content: newContent,\n toolCalls: null,\n toolCallId: null,\n name: null,\n createdAt: new Date().toISOString(),\n streaming: true,\n }];\n });\n } else if (chunk.event === 'tool_start') {\n try {\n const parsed = JSON.parse(chunk.data);\n setToolStatus((prev) => [\n ...prev,\n { toolCallId: parsed.tool_call_id, name: parsed.name, description: parsed.description, status: 'running' },\n ]);\n setMessages((prev) => {\n if (prev.some((m) => m.toolCalls?.some((tc) => tc.id === parsed.tool_call_id))) {\n return prev;\n }\n // Stop streaming on previous text message (freeze it in place)\n const next = prev.map((m, i) =>\n i === prev.length - 1 && m.streaming && m.role === 'assistant' && !m.toolCalls\n ? { ...m, streaming: false }\n : m,\n );\n return [...next, {\n id: `tmp-tc-${parsed.tool_call_id}`,\n chatId: chatIdRef.current || '',\n role: 'assistant' as const,\n content: null,\n toolCalls: [{\n id: parsed.tool_call_id,\n type: 'function' as const,\n function: { name: parsed.name, arguments: parsed.arguments || '{}' },\n description: parsed.description,\n }],\n toolCallId: null,\n name: null,\n createdAt: new Date().toISOString(),\n streaming: true,\n }];\n });\n } catch {\n // ignore malformed tool_start events\n }\n } else if (chunk.event === 'tool_end') {\n try {\n const parsed = JSON.parse(chunk.data);\n setToolStatus((prev) =>\n prev.map((t) => t.toolCallId === parsed.tool_call_id ? { ...t, status: 'complete' } : t),\n );\n // Merge result into the existing tool call message (same bubble)\n if (parsed.result !== undefined) {\n const resultContent = typeof parsed.result === 'string' ? parsed.result : JSON.stringify(parsed.result);\n setMessages((prev) =>\n prev.map((m) => {\n if (m.toolCalls?.some((tc) => tc.id === parsed.tool_call_id)) {\n return {\n ...m,\n toolResults: {\n ...m.toolResults,\n [parsed.tool_call_id]: { content: resultContent, name: parsed.name },\n },\n };\n }\n return m;\n }),\n );\n }\n } catch {\n // ignore malformed tool_end events\n }\n } else if (chunk.event === 'approval_required') {\n try {\n const raw = JSON.parse(chunk.data);\n const parsed: ApprovalRequest = {\n type: raw.type,\n toolCallId: raw.tool_call_id,\n functionNamespace: raw.function_namespace,\n functionName: raw.function_name,\n arguments: raw.arguments,\n };\n setPendingApprovals((prev) => [...prev, parsed]);\n } catch {\n // ignore malformed approval events\n }\n } else if (chunk.event === 'error') {\n try {\n const parsed = JSON.parse(chunk.data);\n setError(parsed.error || 'Stream error');\n } catch {\n setError(chunk.data || 'Stream error');\n }\n }\n },\n [],\n );\n\n const refreshMessages = React.useCallback(\n async (id: string) => {\n try {\n const detail = await getChat(client, id);\n setMessages(detail.messages);\n if (detail.pendingApprovals?.length) {\n setPendingApprovals(detail.pendingApprovals);\n }\n } catch {\n // Refresh is best-effort — streaming content already visible\n }\n },\n [client],\n );\n\n const send = React.useCallback(\n (content: MessageContent) => {\n const doSend = async () => {\n let activeChatId = chatIdRef.current;\n\n // Auto-create chat on first send\n if (!activeChatId) {\n setLoading(true);\n setError(null);\n try {\n const result = await createChat(client, agentRef, options?.input);\n activeChatId = result.id;\n setChatId(result.id);\n chatIdRef.current = result.id;\n } catch (e) {\n setError((e as Error).message);\n setLoading(false);\n return;\n }\n setLoading(false);\n }\n\n abortRef.current?.abort();\n setStreaming(true);\n setError(null);\n setPendingApprovals([]);\n setToolStatus([]);\n\n // Add user message optimistically\n const displayContent = typeof content === 'string' ? content : JSON.stringify(content);\n const userMsg: ChatSessionMessage = {\n id: `tmp-user-${Date.now()}`,\n chatId: activeChatId,\n role: 'user',\n content: displayContent,\n toolCalls: null,\n toolCallId: null,\n name: null,\n createdAt: new Date().toISOString(),\n };\n setMessages((prev) => [...prev, userMsg]);\n\n const controller = streamMessage(\n client,\n activeChatId,\n content,\n handleStreamChunks,\n () => {\n setStreaming(false);\n setToolStatus([]);\n // Refresh to get authoritative server state\n refreshMessages(activeChatId!);\n },\n (err: Error) => {\n setError(err.message);\n setStreaming(false);\n setToolStatus([]);\n },\n );\n\n abortRef.current = controller;\n };\n\n doSend();\n },\n [client, agentRef, options?.input, handleStreamChunks, refreshMessages],\n );\n\n const handleApproval = React.useCallback(\n (toolCallId: string, approved: boolean) => {\n const currentChatId = chatIdRef.current;\n if (!currentChatId) return;\n\n setPendingApprovals((prev) => prev.filter((a) => a.toolCallId !== toolCallId));\n setStreaming(true);\n setError(null);\n\n // No placeholder needed — handleStreamChunks creates messages on demand\n\n (async () => {\n try {\n const result = await approveToolCall(client, currentChatId, toolCallId, approved);\n\n if (!approved) {\n setStreaming(false);\n refreshMessages(currentChatId);\n return;\n }\n\n // Connect to resume stream\n const controller = streamFromChannel(\n client,\n currentChatId,\n result.channelId,\n handleStreamChunks,\n () => {\n setStreaming(false);\n setToolStatus([]);\n refreshMessages(currentChatId);\n },\n (err: Error) => {\n setError(err.message);\n setStreaming(false);\n setToolStatus([]);\n },\n );\n\n abortRef.current = controller;\n } catch (e) {\n setError((e as Error).message);\n setStreaming(false);\n }\n })();\n },\n [client, handleStreamChunks, refreshMessages],\n );\n\n const approve = React.useCallback(\n (toolCallId: string) => handleApproval(toolCallId, true),\n [handleApproval],\n );\n\n const reject = React.useCallback(\n (toolCallId: string) => handleApproval(toolCallId, false),\n [handleApproval],\n );\n\n const stop = React.useCallback(() => {\n abortRef.current?.abort();\n abortRef.current = null;\n setStreaming(false);\n }, []);\n\n const clearError = React.useCallback(() => {\n setError(null);\n }, []);\n\n return {\n chatId,\n messages,\n loading,\n streaming,\n error,\n pendingApprovals,\n toolStatus,\n send,\n approve,\n reject,\n stop,\n clearError,\n };\n}\n","import { useClient } from './context';\nimport { useQuery } from './useQuery';\nimport { useExecute } from './useExecute';\nimport { useStateStore } from './useStateStore';\nimport { useChat } from './useChat';\nimport type { SinasConfig } from '../client/types';\nimport type { SinasClient } from '../client/SinasClient';\n\nexport interface UseSinasResult {\n config: SinasConfig;\n input: Record<string, unknown>;\n client: SinasClient;\n useQuery: typeof useQuery;\n useExecute: typeof useExecute;\n useStateStore: typeof useStateStore;\n useChat: typeof useChat;\n}\n\nexport function useSinas(): UseSinasResult {\n const client = useClient();\n\n return {\n config: client.getConfig(),\n input: client.getInput(),\n client,\n useQuery,\n useExecute,\n useStateStore,\n useChat,\n };\n}\n","import React from 'react';\nimport { useClient } from './context';\nimport { SinasAuthError } from '../client/errors';\nimport type {\n AuthUser,\n InfoResponse,\n LoginResponse,\n OTPVerifyResponse,\n} from '../client/types';\n\nexport type AuthStatus = 'loading' | 'authenticated' | 'unauthenticated';\n\nexport interface UseAuthResult {\n status: AuthStatus;\n user: AuthUser | null;\n info: InfoResponse | null;\n error: string | null;\n\n /**\n * Refresh the session by calling /auth/me with the current access token.\n * Call this on app boot and after token changes.\n */\n refresh: () => Promise<void>;\n\n /**\n * Start a login. In password-only mode this completes the login and\n * returns access/refresh tokens. In OTP / password+OTP mode the response\n * carries a `session_id` to feed into `verifyOTP`.\n */\n login: (email: string, password?: string) => Promise<LoginResponse>;\n\n /** Second step for OTP / password+OTP. Returns the final tokens. */\n verifyOTP: (sessionId: string, otpCode: string) => Promise<OTPVerifyResponse>;\n\n /** Revoke the refresh token and clear local auth state. */\n logout: (refreshToken?: string) => Promise<void>;\n}\n\nexport interface UseAuthOptions {\n /** Refresh on mount. Default true. */\n autoRefresh?: boolean;\n}\n\n/**\n * React hook for the standalone Sinas login flow. The hosting app is\n * responsible for storing the tokens it receives (typically in localStorage)\n * and wiring `getAccessToken` / `getRefreshToken` / `onTokenRefresh` on the\n * SinasProvider so this hook can read the current session.\n */\nexport function useAuth(options: UseAuthOptions = {}): UseAuthResult {\n const { autoRefresh = true } = options;\n const client = useClient();\n\n const [status, setStatus] = React.useState<AuthStatus>('loading');\n const [user, setUser] = React.useState<AuthUser | null>(null);\n const [info, setInfo] = React.useState<InfoResponse | null>(null);\n const [error, setError] = React.useState<string | null>(null);\n\n const refresh = React.useCallback(async () => {\n setError(null);\n try {\n // Fetch /info in parallel with /me (info is unauthenticated and cheap).\n const [infoResp, meResp] = await Promise.all([\n client.auth.getInfo().catch(() => null),\n client.getAccessToken() ? client.auth.getMe().catch(() => null) : Promise.resolve(null),\n ]);\n if (infoResp) setInfo(infoResp);\n if (meResp) {\n setUser(meResp);\n setStatus('authenticated');\n } else {\n setUser(null);\n setStatus('unauthenticated');\n }\n } catch (e) {\n setError(e instanceof Error ? e.message : String(e));\n setStatus('unauthenticated');\n }\n }, [client]);\n\n React.useEffect(() => {\n if (autoRefresh) void refresh();\n }, [autoRefresh, refresh]);\n\n const login = React.useCallback(\n async (email: string, password?: string) => {\n setError(null);\n try {\n return await client.auth.login({ email, password });\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n setError(msg);\n throw e;\n }\n },\n [client],\n );\n\n const verifyOTP = React.useCallback(\n async (sessionId: string, otpCode: string) => {\n setError(null);\n try {\n return await client.auth.verifyOTP({ session_id: sessionId, otp_code: otpCode });\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n setError(msg);\n throw e;\n }\n },\n [client],\n );\n\n const logout = React.useCallback(\n async (refreshToken?: string) => {\n if (refreshToken) {\n try {\n await client.auth.logout(refreshToken);\n } catch (e) {\n if (!(e instanceof SinasAuthError)) throw e;\n }\n }\n setUser(null);\n setStatus('unauthenticated');\n },\n [client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AC;AACrD,iBAAS,GAAG;AACZ,cAAM;AAAA,MACR;AAAA,IACF;AAAA,IACA,CAAC,MAAM;AAAA,EACT;AAEA,QAAMG,aAAYH,OAAM;AAAA,IACtB,OAAO,WAAmB,YAAoB;AAC5C,eAAS,IAAI;AACb,UAAI;AACF,eAAO,MAAM,OAAO,KAAK,UAAU,EAAE,YAAY,WAAW,UAAU,QAAQ,CAAC;AAAA,MACjF,SAAS,GAAG;AACV,cAAM,MAAM,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC;AACrD,iBAAS,GAAG;AACZ,cAAM;AAAA,MACR;AAAA,IACF;AAAA,IACA,CAAC,MAAM;AAAA,EACT;AAEA,QAAMI,UAASJ,OAAM;AAAA,IACnB,OAAO,iBAA0B;AAC/B,UAAI,cAAc;AAChB,YAAI;AACF,gBAAM,OAAO,KAAK,OAAO,YAAY;AAAA,QACvC,SAAS,GAAG;AACV,cAAI,EAAE,aAAa,gBAAiB,OAAM;AAAA,QAC5C;AAAA,MACF;AACA,cAAQ,IAAI;AACZ,gBAAU,iBAAiB;AAAA,IAC7B;AAAA,IACA,CAAC,MAAM;AAAA,EACT;AAEA,SAAO,EAAE,QAAQ,MAAM,MAAM,OAAO,SAAAC,UAAS,OAAAC,QAAO,WAAAC,YAAW,QAAAC,QAAO;AACxE;","names":["React","React","React","React","React","React","React","React","React","React","refresh","login","verifyOTP","logout"]}
|
package/dist/sinas-sdk.umd.js
CHANGED
|
@@ -51,14 +51,18 @@ var SinasSDK = (() => {
|
|
|
51
51
|
SinasProvider: () => SinasProvider,
|
|
52
52
|
SinasTimeoutError: () => SinasTimeoutError,
|
|
53
53
|
approveToolCall: () => approveToolCall,
|
|
54
|
+
cancelBatch: () => cancelBatch,
|
|
54
55
|
checkPermissions: () => checkPermissions,
|
|
55
56
|
createChat: () => createChat,
|
|
57
|
+
enqueueFunction: () => enqueueFunction,
|
|
56
58
|
executeFunction: () => executeFunction,
|
|
57
59
|
executeQuery: () => executeQuery,
|
|
58
60
|
generateFileUrl: () => generateFileUrl,
|
|
61
|
+
getBatch: () => getBatch,
|
|
59
62
|
getChat: () => getChat,
|
|
60
63
|
getInfo: () => getInfo,
|
|
61
64
|
getMe: () => getMe,
|
|
65
|
+
listBatchExecutions: () => listBatchExecutions,
|
|
62
66
|
listCollections: () => listCollections,
|
|
63
67
|
listFiles: () => listFiles,
|
|
64
68
|
login: () => login,
|
|
@@ -71,6 +75,8 @@ var SinasSDK = (() => {
|
|
|
71
75
|
stateSet: () => stateSet,
|
|
72
76
|
streamFromChannel: () => streamFromChannel,
|
|
73
77
|
streamMessage: () => streamMessage,
|
|
78
|
+
submitAgentBatch: () => submitAgentBatch,
|
|
79
|
+
submitFunctionBatch: () => submitFunctionBatch,
|
|
74
80
|
uploadFile: () => uploadFile,
|
|
75
81
|
useAuth: () => useAuth,
|
|
76
82
|
useChat: () => useChat,
|
|
@@ -391,6 +397,124 @@ var SinasSDK = (() => {
|
|
|
391
397
|
error: data.error
|
|
392
398
|
};
|
|
393
399
|
}
|
|
400
|
+
async function enqueueFunction(client, ref, input = {}, options = {}) {
|
|
401
|
+
const [ns, name] = parseRef2(ref);
|
|
402
|
+
const baseUrl = client.requireBaseUrl();
|
|
403
|
+
const body = { input };
|
|
404
|
+
if (options.triggerId !== void 0) body.trigger_id = options.triggerId;
|
|
405
|
+
if (options.delaySeconds !== void 0) body.delay_seconds = options.delaySeconds;
|
|
406
|
+
if (options.callbackUrl !== void 0) body.callback_url = options.callbackUrl;
|
|
407
|
+
const res = await client.fetch(`${baseUrl}/functions/${ns}/${name}/execute/async`, {
|
|
408
|
+
method: "POST",
|
|
409
|
+
body: JSON.stringify(body)
|
|
410
|
+
});
|
|
411
|
+
const data = await res.json();
|
|
412
|
+
return {
|
|
413
|
+
executionId: data.execution_id,
|
|
414
|
+
status: data.status
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
async function submitFunctionBatch(client, ref, inputs, options = {}) {
|
|
418
|
+
const [ns, name] = parseRef2(ref);
|
|
419
|
+
const baseUrl = client.requireBaseUrl();
|
|
420
|
+
const body = { inputs };
|
|
421
|
+
if (options.triggerIdPrefix !== void 0) body.trigger_id_prefix = options.triggerIdPrefix;
|
|
422
|
+
if (options.delaySeconds !== void 0) body.delay_seconds = options.delaySeconds;
|
|
423
|
+
if (options.callbackUrl !== void 0) body.callback_url = options.callbackUrl;
|
|
424
|
+
if (options.batchCallbackUrl !== void 0) body.batch_callback_url = options.batchCallbackUrl;
|
|
425
|
+
const res = await client.fetch(`${baseUrl}/functions/${ns}/${name}/execute/batch`, {
|
|
426
|
+
method: "POST",
|
|
427
|
+
body: JSON.stringify(body)
|
|
428
|
+
});
|
|
429
|
+
const data = await res.json();
|
|
430
|
+
return {
|
|
431
|
+
batchId: data.batch_id,
|
|
432
|
+
executionIds: data.execution_ids,
|
|
433
|
+
total: data.total,
|
|
434
|
+
status: data.status
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
async function submitAgentBatch(client, ref, inputs, options = {}) {
|
|
438
|
+
const [ns, name] = parseRef2(ref);
|
|
439
|
+
const baseUrl = client.requireBaseUrl();
|
|
440
|
+
const body = {
|
|
441
|
+
inputs: inputs.map((item) => ({
|
|
442
|
+
input_variables: item.inputVariables || {},
|
|
443
|
+
message: item.message
|
|
444
|
+
}))
|
|
445
|
+
};
|
|
446
|
+
if (options.triggerIdPrefix !== void 0) body.trigger_id_prefix = options.triggerIdPrefix;
|
|
447
|
+
if (options.callbackUrl !== void 0) body.callback_url = options.callbackUrl;
|
|
448
|
+
if (options.batchCallbackUrl !== void 0) body.batch_callback_url = options.batchCallbackUrl;
|
|
449
|
+
const res = await client.fetch(`${baseUrl}/agents/${ns}/${name}/chats/batch`, {
|
|
450
|
+
method: "POST",
|
|
451
|
+
body: JSON.stringify(body)
|
|
452
|
+
});
|
|
453
|
+
const data = await res.json();
|
|
454
|
+
return {
|
|
455
|
+
batchId: data.batch_id,
|
|
456
|
+
executionIds: data.execution_ids,
|
|
457
|
+
chatIds: data.chat_ids,
|
|
458
|
+
total: data.total,
|
|
459
|
+
status: data.status
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
async function getBatch(client, batchId) {
|
|
463
|
+
const baseUrl = client.requireBaseUrl();
|
|
464
|
+
const res = await client.fetch(`${baseUrl}/batches/${batchId}`);
|
|
465
|
+
const data = await res.json();
|
|
466
|
+
return {
|
|
467
|
+
batchId: data.batch_id,
|
|
468
|
+
kind: data.kind,
|
|
469
|
+
target: data.target,
|
|
470
|
+
userId: data.user_id,
|
|
471
|
+
total: data.total,
|
|
472
|
+
completed: data.completed,
|
|
473
|
+
failed: data.failed,
|
|
474
|
+
cancelled: data.cancelled,
|
|
475
|
+
running: data.running,
|
|
476
|
+
queued: data.queued,
|
|
477
|
+
status: data.status,
|
|
478
|
+
startedAt: data.started_at,
|
|
479
|
+
finishedAt: data.finished_at,
|
|
480
|
+
triggerIdPrefix: data.trigger_id_prefix
|
|
481
|
+
};
|
|
482
|
+
}
|
|
483
|
+
async function listBatchExecutions(client, batchId, options = {}) {
|
|
484
|
+
const baseUrl = client.requireBaseUrl();
|
|
485
|
+
const params = new URLSearchParams();
|
|
486
|
+
if (options.status) params.set("status", options.status);
|
|
487
|
+
if (options.limit !== void 0) params.set("limit", String(options.limit));
|
|
488
|
+
if (options.offset !== void 0) params.set("offset", String(options.offset));
|
|
489
|
+
const q = params.toString();
|
|
490
|
+
const res = await client.fetch(
|
|
491
|
+
`${baseUrl}/batches/${batchId}/executions${q ? "?" + q : ""}`
|
|
492
|
+
);
|
|
493
|
+
const data = await res.json();
|
|
494
|
+
return (data.executions || []).map((row) => ({
|
|
495
|
+
executionId: row.execution_id,
|
|
496
|
+
status: row.status,
|
|
497
|
+
functionName: row.function_name,
|
|
498
|
+
chatId: row.chat_id ?? null,
|
|
499
|
+
triggerId: row.trigger_id,
|
|
500
|
+
startedAt: row.started_at ?? null,
|
|
501
|
+
completedAt: row.completed_at ?? null,
|
|
502
|
+
durationMs: row.duration_ms ?? null,
|
|
503
|
+
error: row.error ?? null
|
|
504
|
+
}));
|
|
505
|
+
}
|
|
506
|
+
async function cancelBatch(client, batchId) {
|
|
507
|
+
const baseUrl = client.requireBaseUrl();
|
|
508
|
+
const res = await client.fetch(`${baseUrl}/batches/${batchId}/cancel`, {
|
|
509
|
+
method: "POST"
|
|
510
|
+
});
|
|
511
|
+
const data = await res.json();
|
|
512
|
+
return {
|
|
513
|
+
batchId: data.batch_id,
|
|
514
|
+
status: data.status,
|
|
515
|
+
cancelledChildren: data.cancelled_children
|
|
516
|
+
};
|
|
517
|
+
}
|
|
394
518
|
|
|
395
519
|
// src/client/states.ts
|
|
396
520
|
async function stateGet(client, ns, key) {
|