@personaai/react 0.3.2 → 0.3.4
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/README.md +64 -0
- package/dist/index.cjs +48 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +52 -3
- package/dist/index.d.ts +52 -3
- package/dist/index.js +47 -2
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# @personaai/react
|
|
2
|
+
|
|
3
|
+
React SDK for [Persona](https://persona.hasanraiyan.me) — hooks and a context provider for building chat UIs against any Persona backend.
|
|
4
|
+
|
|
5
|
+
> **v0.3.2.** Requires React 18+. Client-side only — never holds a credential.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @personaai/react
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Quickstart
|
|
14
|
+
|
|
15
|
+
```tsx
|
|
16
|
+
import { PersonaProvider, useChat } from '@personaai/react';
|
|
17
|
+
|
|
18
|
+
function App() {
|
|
19
|
+
return (
|
|
20
|
+
<PersonaProvider
|
|
21
|
+
baseUrl="http://localhost:3000/api/persona"
|
|
22
|
+
getAuthToken={async () => getToken()}
|
|
23
|
+
defaultAgentId="my-agent-id"
|
|
24
|
+
>
|
|
25
|
+
<Chat />
|
|
26
|
+
</PersonaProvider>
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function Chat() {
|
|
31
|
+
const { messages, input, setInput, handleSubmit, isStreaming } = useChat();
|
|
32
|
+
|
|
33
|
+
return (
|
|
34
|
+
<div>
|
|
35
|
+
{messages.map((m) => (
|
|
36
|
+
<div key={m.id}>{m.content}</div>
|
|
37
|
+
))}
|
|
38
|
+
<form onSubmit={handleSubmit}>
|
|
39
|
+
<input value={input} onChange={(e) => setInput(e.target.value)} />
|
|
40
|
+
<button disabled={isStreaming}>Send</button>
|
|
41
|
+
</form>
|
|
42
|
+
</div>
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Hooks
|
|
48
|
+
|
|
49
|
+
| Hook | Purpose |
|
|
50
|
+
| --- | --- |
|
|
51
|
+
| `useChat` | Streaming chat — messages, send, stop, reload, interrupts, workspace files |
|
|
52
|
+
| `useThreads` | Thread CRUD — list, create, delete, rename, archive |
|
|
53
|
+
| `useFiles` | Upload management — list, upload, delete |
|
|
54
|
+
| `useMemory` | Persistent memory — read, write, delete |
|
|
55
|
+
| `useAgents` | Agent discovery — list available agents |
|
|
56
|
+
| `useConnection` | Health check — backend connectivity status |
|
|
57
|
+
|
|
58
|
+
## Full documentation
|
|
59
|
+
|
|
60
|
+
**[persona.hasanraiyan.me/guides/react/quickstart](https://persona.hasanraiyan.me/guides/react/quickstart)** — quickstart, hooks reference, streaming events, and types.
|
|
61
|
+
|
|
62
|
+
## Peer dependencies
|
|
63
|
+
|
|
64
|
+
- `react >= 18`
|
package/dist/index.cjs
CHANGED
|
@@ -26,6 +26,7 @@ __export(index_exports, {
|
|
|
26
26
|
useChat: () => useChat,
|
|
27
27
|
useConnection: () => useConnection,
|
|
28
28
|
useFiles: () => useFiles,
|
|
29
|
+
useMcpConnections: () => useMcpConnections,
|
|
29
30
|
useMemory: () => useMemory,
|
|
30
31
|
usePersonaContext: () => usePersonaContext,
|
|
31
32
|
useThreads: () => useThreads
|
|
@@ -236,6 +237,7 @@ function useChat(options = {}) {
|
|
|
236
237
|
role: m.role === "assistant" ? "assistant" : "user",
|
|
237
238
|
content: m.content
|
|
238
239
|
}));
|
|
240
|
+
const resolvedThreadId = await (overrideOptions?.threadId ?? options.threadId);
|
|
239
241
|
const response = await fetchWithAuth("/chat", {
|
|
240
242
|
method: "POST",
|
|
241
243
|
headers: {
|
|
@@ -244,7 +246,7 @@ function useChat(options = {}) {
|
|
|
244
246
|
body: JSON.stringify({
|
|
245
247
|
agentId: targetAgentId,
|
|
246
248
|
messages: payloadMessages,
|
|
247
|
-
threadId:
|
|
249
|
+
threadId: resolvedThreadId,
|
|
248
250
|
resume: overrideOptions?.resume
|
|
249
251
|
}),
|
|
250
252
|
signal: controller.signal
|
|
@@ -827,8 +829,51 @@ function useConnection(autoCheck = true) {
|
|
|
827
829
|
};
|
|
828
830
|
}
|
|
829
831
|
|
|
832
|
+
// src/hooks/useMcpConnections.ts
|
|
833
|
+
var import_react8 = require("react");
|
|
834
|
+
function useMcpConnections(options = {}) {
|
|
835
|
+
const { defaultAgentId, fetchWithAuth } = usePersonaContext();
|
|
836
|
+
const agentId = options.agentId ?? defaultAgentId;
|
|
837
|
+
const autoFetch = options.autoFetch ?? true;
|
|
838
|
+
const [connections, setConnections] = (0, import_react8.useState)([]);
|
|
839
|
+
const [isLoading, setIsLoading] = (0, import_react8.useState)(false);
|
|
840
|
+
const [error, setError] = (0, import_react8.useState)(null);
|
|
841
|
+
const fetchConnections = (0, import_react8.useCallback)(async () => {
|
|
842
|
+
if (!agentId) return [];
|
|
843
|
+
setIsLoading(true);
|
|
844
|
+
setError(null);
|
|
845
|
+
try {
|
|
846
|
+
const returnTo = options.returnTo ?? (typeof window !== "undefined" ? window.location.href : void 0);
|
|
847
|
+
const query = returnTo ? `?returnTo=${encodeURIComponent(returnTo)}` : "";
|
|
848
|
+
const res = await fetchWithAuth(`/agents/${agentId}/mcp-connections${query}`);
|
|
849
|
+
if (!res.ok) throw new Error(`Failed to load MCP connections: ${res.statusText}`);
|
|
850
|
+
const data = await res.json();
|
|
851
|
+
const items = Array.isArray(data) ? data : data?.items || [];
|
|
852
|
+
setConnections(items);
|
|
853
|
+
return items;
|
|
854
|
+
} catch (err) {
|
|
855
|
+
const errorObj = err instanceof Error ? err : new Error(String(err));
|
|
856
|
+
setError(errorObj);
|
|
857
|
+
return [];
|
|
858
|
+
} finally {
|
|
859
|
+
setIsLoading(false);
|
|
860
|
+
}
|
|
861
|
+
}, [agentId, fetchWithAuth, options.returnTo]);
|
|
862
|
+
(0, import_react8.useEffect)(() => {
|
|
863
|
+
if (autoFetch) void fetchConnections();
|
|
864
|
+
}, [autoFetch, fetchConnections]);
|
|
865
|
+
return {
|
|
866
|
+
connections,
|
|
867
|
+
/** Convenience filter for the common "show a banner for what's missing" case. */
|
|
868
|
+
unconnected: connections.filter((c) => !c.connected),
|
|
869
|
+
isLoading,
|
|
870
|
+
error,
|
|
871
|
+
refetch: fetchConnections
|
|
872
|
+
};
|
|
873
|
+
}
|
|
874
|
+
|
|
830
875
|
// src/index.ts
|
|
831
|
-
var VERSION = "0.3.
|
|
876
|
+
var VERSION = "0.3.4";
|
|
832
877
|
// Annotate the CommonJS export names for ESM import in node:
|
|
833
878
|
0 && (module.exports = {
|
|
834
879
|
PersonaProvider,
|
|
@@ -837,6 +882,7 @@ var VERSION = "0.3.2";
|
|
|
837
882
|
useChat,
|
|
838
883
|
useConnection,
|
|
839
884
|
useFiles,
|
|
885
|
+
useMcpConnections,
|
|
840
886
|
useMemory,
|
|
841
887
|
usePersonaContext,
|
|
842
888
|
useThreads
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/context/PersonaContext.tsx","../src/hooks/useChat.ts","../src/hooks/useMemory.ts","../src/hooks/useThreads.ts","../src/hooks/useFiles.ts","../src/hooks/useAgents.ts","../src/hooks/useConnection.ts"],"sourcesContent":["export * from './types.js';\nexport * from './context/PersonaContext.js';\nexport * from './hooks/useChat.js';\nexport * from './hooks/useMemory.js';\nexport * from './hooks/useThreads.js';\nexport * from './hooks/useFiles.js';\nexport * from './hooks/useAgents.js';\nexport * from './hooks/useConnection.js';\n\nexport const VERSION = '0.3.2';\n","'use client';\n\nimport React, { createContext, useContext, useMemo } from 'react';\nimport type { PersonaProviderProps } from '../types.js';\n\ninterface PersonaContextValue {\n baseUrl: string;\n getAuthToken?: () => Promise<string | null | undefined> | string | null | undefined;\n defaultAgentId?: string;\n fetchWithAuth: (path: string, init?: RequestInit) => Promise<Response>;\n}\n\nconst PersonaContext = createContext<PersonaContextValue | null>(null);\n\nexport function PersonaProvider({\n baseUrl,\n getAuthToken,\n defaultAgentId,\n children,\n}: PersonaProviderProps) {\n const normalizedBaseUrl = useMemo(() => baseUrl.replace(/\\/+$/, ''), [baseUrl]);\n\n const value = useMemo<PersonaContextValue>(() => {\n async function fetchWithAuth(path: string, init: RequestInit = {}): Promise<Response> {\n const token = getAuthToken ? await getAuthToken() : null;\n const headers = new Headers(init.headers || {});\n if (token) {\n headers.set('Authorization', `Bearer ${token}`);\n }\n\n const cleanPath = path.startsWith('/') ? path : `/${path}`;\n const url = `${normalizedBaseUrl}${cleanPath}`;\n\n return fetch(url, {\n ...init,\n headers,\n });\n }\n\n return {\n baseUrl: normalizedBaseUrl,\n getAuthToken,\n defaultAgentId,\n fetchWithAuth,\n };\n }, [normalizedBaseUrl, getAuthToken, defaultAgentId]);\n\n return <PersonaContext.Provider value={value}>{children}</PersonaContext.Provider>;\n}\n\nexport function usePersonaContext(): PersonaContextValue {\n const context = useContext(PersonaContext);\n if (!context) {\n throw new Error('usePersonaContext must be used within a <PersonaProvider>');\n }\n return context;\n}\n","'use client';\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { usePersonaContext } from '../context/PersonaContext.js';\nimport type {\n PersonaInterrupt,\n PersonaMessage,\n PersonaPresentedFile,\n PersonaResumeValue,\n PersonaStreamingEvent,\n PersonaSubagentActivityEntry,\n PersonaTodo,\n PersonaToolCall,\n PersonaWorkspaceFile,\n SendMessageOverride,\n UseChatOptions,\n} from '../types.js';\n\n// A failed tool call's TOOL_CALL_RESULT content is a JSON envelope\n// (`{status:'error',message}`, see aguiTranslator.js's buildToolErrorContent)\n// rather than a separate boolean field on the event itself.\nfunction isErrorToolContent(content: string): boolean {\n if (typeof content !== 'string' || !content.trim().startsWith('{')) return false;\n try {\n return JSON.parse(content)?.status === 'error';\n } catch {\n return false;\n }\n}\n\n// present_file's result is `{status:'success', filePath, title, description}`\n// (see present.tool.js) — a signal to highlight that path in the workspace\n// files panel, not something meant to render as a generic tool-result blob.\nfunction parsePresentedFile(content: string): PersonaPresentedFile | null {\n try {\n const parsed = JSON.parse(content);\n if (parsed?.status !== 'success' || typeof parsed.filePath !== 'string') return null;\n return {\n path: parsed.filePath,\n title: typeof parsed.title === 'string' ? parsed.title : parsed.filePath,\n description: typeof parsed.description === 'string' ? parsed.description : '',\n };\n } catch {\n return null;\n }\n}\n\n// buildFilesTodosSnapshot (aguiTranslator.js) emits snake_case\n// created_at/modified_at on the wire — both from the live STATE_SNAPSHOT\n// event and from a reloaded thread's persisted state (checkpoint.service.js\n// runs the same function). Normalize to the SDK's usual camelCase shape.\nfunction normalizeWorkspaceFiles(\n raw: Record<string, { content: string; size: number; created_at: string | null; modified_at: string | null }>\n): Record<string, PersonaWorkspaceFile> {\n const normalized: Record<string, PersonaWorkspaceFile> = {};\n for (const [path, file] of Object.entries(raw || {})) {\n normalized[path] = {\n content: file.content,\n size: file.size,\n createdAt: file.created_at,\n modifiedAt: file.modified_at,\n };\n }\n return normalized;\n}\n\n// checkpointService.getMessages() wraps a paused thread's interrupt as\n// `{ kind, value }` (see checkpoint.service.js) — the same envelope shape\n// the live hitl_request/clarification_request CUSTOM events carry, just\n// nested one level deeper. Flatten both into the same PersonaInterrupt shape.\nfunction normalizePendingInterrupt(pending: unknown): PersonaInterrupt | null {\n if (!pending || typeof pending !== 'object') return null;\n const p = pending as { kind?: string; value?: Record<string, unknown> };\n if (p.kind === 'hitl') {\n return {\n kind: 'hitl',\n actionRequests: (p.value?.actionRequests ?? []) as Extract<\n PersonaInterrupt,\n { kind: 'hitl' }\n >['actionRequests'],\n reviewConfigs: (p.value?.reviewConfigs ?? []) as unknown[],\n };\n }\n if (p.kind === 'clarification') {\n return {\n kind: 'clarification',\n questions: (p.value?.questions ?? []) as Extract<PersonaInterrupt, { kind: 'clarification' }>['questions'],\n };\n }\n return null;\n}\n\nexport function useChat(options: UseChatOptions = {}) {\n const { defaultAgentId, fetchWithAuth } = usePersonaContext();\n const agentId = options.agentId || defaultAgentId;\n const threadId = options.threadId;\n\n const [messages, setMessages] = useState<PersonaMessage[]>(options.initialMessages || []);\n const [input, setInput] = useState('');\n const [isStreaming, setIsStreaming] = useState(false);\n const [isLoadingHistory, setIsLoadingHistory] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const [interrupt, setInterrupt] = useState<PersonaInterrupt | null>(null);\n const [files, setFiles] = useState<Record<string, PersonaWorkspaceFile>>({});\n const [todos, setTodos] = useState<PersonaTodo[]>([]);\n const [presentedFile, setPresentedFile] = useState<PersonaPresentedFile | null>(null);\n\n const abortControllerRef = useRef<AbortController | null>(null);\n const loadedThreadIdRef = useRef<string | undefined>(undefined);\n\n const stop = useCallback(() => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n abortControllerRef.current = null;\n setIsStreaming(false);\n }\n }, []);\n\n const clear = useCallback(() => {\n stop();\n setMessages([]);\n setError(null);\n setInterrupt(null);\n setFiles({});\n setTodos([]);\n setPresentedFile(null);\n }, [stop]);\n\n const loadThreadMessages = useCallback(\n async (id: string) => {\n setIsLoadingHistory(true);\n setError(null);\n try {\n const res = await fetchWithAuth(`/threads/${id}/messages`);\n if (!res.ok) throw new Error(`Failed to load thread history: ${res.statusText}`);\n const body = await res.json();\n const data = body?.data ?? body;\n const raw = (data?.messages ?? []) as Array<{\n id?: string;\n role: PersonaMessage['role'];\n content: string;\n toolCalls?: PersonaToolCall[];\n }>;\n const loaded: PersonaMessage[] = raw.map((m, i) => ({\n id: m.id || `history-${id}-${i}`,\n role: m.role,\n content: m.content,\n createdAt: new Date(),\n toolCalls: m.toolCalls,\n }));\n setMessages(loaded);\n // Re-show the approval/clarification card on reload if this thread\n // is currently paused — otherwise it wouldn't reappear until the\n // next live stream re-surfaces it.\n setInterrupt(normalizePendingInterrupt(data?.pendingInterrupt));\n // Restore the workspace files/todos this thread already had (same\n // cleaned shape checkpoint.service.js now derives via\n // buildFilesTodosSnapshot, matching the live STATE_SNAPSHOT event).\n setFiles(normalizeWorkspaceFiles(data?.state?.files ?? {}));\n setTodos((data?.state?.todos ?? []) as PersonaTodo[]);\n return loaded;\n } catch (err) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n return [];\n } finally {\n setIsLoadingHistory(false);\n }\n },\n [fetchWithAuth]\n );\n\n // Auto-load history the first time a thread with no in-memory messages is\n // selected (switching threads in the sidebar). Skipped for a thread whose\n // messages already live in state — e.g. one just created by handleSend,\n // which sets its placeholder messages in the same render batch as the\n // threadId change, so `messages` there is never empty at effect time.\n useEffect(() => {\n if (!threadId || isStreaming) return;\n if (loadedThreadIdRef.current === threadId) return;\n if (messages.length > 0) return;\n loadedThreadIdRef.current = threadId;\n void loadThreadMessages(threadId);\n }, [threadId, isStreaming, messages.length, loadThreadMessages]);\n\n const sendMessage = useCallback(\n async (contentToSend?: string, overrideOptions?: SendMessageOverride) => {\n const prompt = (contentToSend ?? input).trim();\n if (!prompt || isStreaming) return;\n\n const targetAgentId = overrideOptions?.agentId || agentId;\n if (!targetAgentId) {\n const err = new Error('No Agent ID specified for useChat.');\n setError(err);\n options.onError?.(err);\n return;\n }\n\n const userMessage: PersonaMessage = {\n id: `user-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,\n role: 'user',\n content: prompt,\n createdAt: new Date(),\n };\n\n const assistantMessageId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;\n const placeholderAssistant: PersonaMessage = {\n id: assistantMessageId,\n role: 'assistant',\n content: '',\n createdAt: new Date(),\n isStreaming: true,\n toolCalls: [],\n };\n\n const nextMessages = [...messages, userMessage];\n setMessages([...nextMessages, placeholderAssistant]);\n setInput('');\n setIsStreaming(true);\n setError(null);\n setInterrupt(null);\n\n const controller = new AbortController();\n abortControllerRef.current = controller;\n\n try {\n const payloadMessages = nextMessages.map((m) => ({\n role: m.role === 'assistant' ? ('assistant' as const) : ('user' as const),\n content: m.content,\n }));\n\n const response = await fetchWithAuth('/chat', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n agentId: targetAgentId,\n messages: payloadMessages,\n threadId: overrideOptions?.threadId || options.threadId,\n resume: overrideOptions?.resume,\n }),\n signal: controller.signal,\n });\n\n if (!response.ok) {\n const errText = await response.text().catch(() => 'Stream failed');\n throw new Error(`Chat error (${response.status}): ${errText}`);\n }\n\n if (!response.body) {\n throw new Error('No response body received for streaming.');\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder('utf-8');\n let buffer = '';\n let accumulatedText = '';\n let accumulatedReasoning = '';\n const toolCallsMap = new Map<string, PersonaToolCall>();\n\n const patchAssistant = (patch: Partial<PersonaMessage>) => {\n setMessages((prev) =>\n prev.map((msg) =>\n msg.id === assistantMessageId\n ? { ...msg, toolCalls: Array.from(toolCallsMap.values()), ...patch }\n : msg\n )\n );\n };\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed || !trimmed.startsWith('data:')) continue;\n\n const raw = trimmed.replace(/^data:\\s*/, '');\n if (raw === '[DONE]') break;\n\n try {\n const event = JSON.parse(raw) as PersonaStreamingEvent;\n options.onEvent?.(event);\n\n if (event.type === 'TEXT_MESSAGE_CHUNK' && event.delta) {\n accumulatedText += event.delta;\n patchAssistant({ content: accumulatedText, isStreaming: true });\n } else if (event.type === 'TOOL_CALL_CHUNK' && event.toolCallId) {\n // The backend streams tool calls as accumulating chunks\n // (id/name arrive on the first chunk, args stream in pieces\n // across subsequent ones) rather than separate start/args\n // events.\n const existing = toolCallsMap.get(event.toolCallId);\n if (existing) {\n existing.args = (existing.args || '') + (event.delta || '');\n } else {\n toolCallsMap.set(event.toolCallId, {\n toolCallId: event.toolCallId,\n toolName: event.toolCallName || '',\n args: event.delta || '',\n });\n }\n patchAssistant({});\n } else if (event.type === 'TOOL_CALL_RESULT') {\n const existing = toolCallsMap.get(event.toolCallId);\n if (existing) {\n existing.result = event.content;\n existing.isError = isErrorToolContent(event.content);\n if (existing.toolName === 'present_file' && !existing.isError) {\n const presented = parsePresentedFile(event.content);\n if (presented) setPresentedFile(presented);\n }\n patchAssistant({});\n }\n } else if (event.type === 'STATE_SNAPSHOT') {\n setFiles(normalizeWorkspaceFiles(event.snapshot.files));\n setTodos(event.snapshot.todos);\n } else if (event.type === 'REASONING_MESSAGE_CONTENT') {\n accumulatedReasoning += event.delta;\n patchAssistant({ reasoning: accumulatedReasoning, isReasoning: true });\n } else if (event.type === 'REASONING_END') {\n patchAssistant({ isReasoning: false });\n } else if (event.type === 'CUSTOM') {\n if (event.name === 'hitl_request') {\n const value = event.value as Extract<PersonaInterrupt, { kind: 'hitl' }>;\n setInterrupt({\n kind: 'hitl',\n actionRequests: value.actionRequests,\n reviewConfigs: value.reviewConfigs,\n });\n } else if (event.name === 'clarification_request') {\n const value = event.value as Extract<PersonaInterrupt, { kind: 'clarification' }>;\n setInterrupt({ kind: 'clarification', questions: value.questions });\n } else if (event.name === 'subagent_activity') {\n const { toolCallId, ...entry } = event.value as { toolCallId: string } & PersonaSubagentActivityEntry;\n const existing = toolCallsMap.get(toolCallId);\n if (existing) {\n existing.subagentActivity = [...(existing.subagentActivity || []), entry];\n patchAssistant({});\n }\n }\n // 'mcp_app' custom events carry no chat-transcript UI here —\n // consumers that render MCP widgets read them via onEvent.\n } else if (event.type === 'RUN_ERROR') {\n throw new Error(event.message || 'Stream error from agent');\n }\n } catch (e) {\n if (e instanceof Error && e.message.startsWith('Stream error')) {\n throw e;\n }\n }\n }\n }\n\n const finalMessage: PersonaMessage = {\n id: assistantMessageId,\n role: 'assistant',\n content: accumulatedText,\n createdAt: new Date(),\n isStreaming: false,\n toolCalls: Array.from(toolCallsMap.values()),\n ...(accumulatedReasoning ? { reasoning: accumulatedReasoning, isReasoning: false } : {}),\n };\n\n setMessages((prev) =>\n prev.map((msg) => (msg.id === assistantMessageId ? finalMessage : msg))\n );\n\n options.onFinish?.(finalMessage);\n } catch (err) {\n if (controller.signal.aborted) {\n setMessages((prev) =>\n prev.map((msg) =>\n msg.id === assistantMessageId ? { ...msg, isStreaming: false } : msg\n )\n );\n return;\n }\n\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n options.onError?.(errorObj);\n\n setMessages((prev) =>\n prev.map((msg) =>\n msg.id === assistantMessageId\n ? {\n ...msg,\n content:\n msg.content || `⚠️ Error: ${errorObj.message || 'Failed to get response.'}`,\n isStreaming: false,\n }\n : msg\n )\n );\n } finally {\n setIsStreaming(false);\n abortControllerRef.current = null;\n }\n },\n [agentId, fetchWithAuth, input, isStreaming, messages, options]\n );\n\n const handleInputChange = useCallback((e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {\n setInput(e.target.value);\n }, []);\n\n const handleSubmit = useCallback(\n (e?: React.FormEvent) => {\n if (e) e.preventDefault();\n void sendMessage();\n },\n [sendMessage]\n );\n\n const reload = useCallback(() => {\n if (messages.length === 0 || isStreaming) return;\n let lastUserIndex = -1;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role === 'user') {\n lastUserIndex = i;\n break;\n }\n }\n if (lastUserIndex === -1) return;\n\n const lastUserMessage = messages[lastUserIndex];\n setMessages(messages.slice(0, lastUserIndex));\n void sendMessage(lastUserMessage.content);\n }, [isStreaming, messages, sendMessage]);\n\n // Unpauses a paused HITL/clarification run. `displayContent` becomes the\n // visible user-turn bubble (e.g. \"Approved\", or the typed clarification\n // answer) — the server resolves the actual resume value from `resume`\n // itself, `displayContent` is only ever used for its own transcript text.\n const resumeInterrupt = useCallback(\n (resume: PersonaResumeValue, displayContent: string) => sendMessage(displayContent, { resume }),\n [sendMessage]\n );\n\n const dismissPresentedFile = useCallback(() => setPresentedFile(null), []);\n\n // Manually re-open a workspace file — e.g. a present_file tool card's\n // \"Open\" button, after the auto-opened drawer was closed or a different\n // file was selected since.\n const openWorkspaceFile = useCallback(\n (path: string) => setPresentedFile({ path, title: path.split('/').pop() || path, description: '' }),\n []\n );\n\n return {\n messages,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n sendMessage,\n isStreaming,\n isLoading: isStreaming,\n isLoadingHistory,\n error,\n interrupt,\n resumeInterrupt,\n files,\n todos,\n presentedFile,\n dismissPresentedFile,\n openWorkspaceFile,\n stop,\n reload,\n clear,\n setMessages,\n loadThreadMessages,\n };\n}\n","'use client';\n\nimport { useCallback, useEffect, useState } from 'react';\nimport { usePersonaContext } from '../context/PersonaContext.js';\nimport type { PersonaMemoryFile, PersonaMemoryList } from '../types.js';\n\nexport function useMemory(autoFetch = true) {\n const { fetchWithAuth } = usePersonaContext();\n const [memory, setMemory] = useState<PersonaMemoryList>({ userFiles: [], agentMemories: [] });\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n\n const fetchMemory = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n try {\n const res = await fetchWithAuth('/memory');\n if (!res.ok) {\n throw new Error(`Failed to fetch memory: ${res.statusText}`);\n }\n const data = (await res.json()) as PersonaMemoryList;\n setMemory(data);\n return data;\n } catch (err) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n return { userFiles: [], agentMemories: [] };\n } finally {\n setIsLoading(false);\n }\n }, [fetchWithAuth]);\n\n const getFile = useCallback(\n async (params: { path: string; scope?: 'user' | 'agent'; agentId?: string }) => {\n const query = new URLSearchParams({ path: params.path });\n if (params.scope) query.set('scope', params.scope);\n if (params.agentId) query.set('agentId', params.agentId);\n\n const res = await fetchWithAuth(`/memory/file?${query.toString()}`);\n if (!res.ok) throw new Error(`Failed to get memory file: ${res.statusText}`);\n return (await res.json()) as PersonaMemoryFile;\n },\n [fetchWithAuth]\n );\n\n const writeFile = useCallback(\n async (params: { path: string; content: string; scope?: 'user' | 'agent'; agentId?: string }) => {\n const res = await fetchWithAuth('/memory/file', {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(params),\n });\n if (!res.ok) throw new Error(`Failed to write memory file: ${res.statusText}`);\n const updated = (await res.json()) as PersonaMemoryFile;\n void fetchMemory();\n return updated;\n },\n [fetchWithAuth, fetchMemory]\n );\n\n const deleteFile = useCallback(\n async (params: { path: string; scope?: 'user' | 'agent'; agentId?: string }) => {\n const query = new URLSearchParams({ path: params.path });\n if (params.scope) query.set('scope', params.scope);\n if (params.agentId) query.set('agentId', params.agentId);\n\n const res = await fetchWithAuth(`/memory/file?${query.toString()}`, {\n method: 'DELETE',\n });\n if (!res.ok) throw new Error(`Failed to delete memory file: ${res.statusText}`);\n void fetchMemory();\n },\n [fetchWithAuth, fetchMemory]\n );\n\n useEffect(() => {\n if (autoFetch) {\n void fetchMemory();\n }\n }, [autoFetch, fetchMemory]);\n\n return {\n memory,\n isLoading,\n error,\n refetch: fetchMemory,\n getFile,\n writeFile,\n deleteFile,\n };\n}\n","'use client';\n\nimport { useCallback, useEffect, useState } from 'react';\nimport { usePersonaContext } from '../context/PersonaContext.js';\nimport type { PersonaThread } from '../types.js';\n\nexport function useThreads(autoFetch = true) {\n const { fetchWithAuth, defaultAgentId } = usePersonaContext();\n const [threads, setThreads] = useState<PersonaThread[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n\n const fetchThreads = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n try {\n const res = await fetchWithAuth('/threads');\n if (!res.ok) throw new Error(`Failed to list threads: ${res.statusText}`);\n const data = await res.json();\n // Real shape is { items, pagination }. Bare array / `.data` / `.threads`\n // are defensive fallbacks for other deployments, not the actual contract.\n const items: PersonaThread[] = Array.isArray(data)\n ? data\n : data?.items || data?.threads || (Array.isArray(data?.data) ? data.data : undefined) || [];\n setThreads(items);\n return items;\n } catch (err) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n return [];\n } finally {\n setIsLoading(false);\n }\n }, [fetchWithAuth]);\n\n const createThread = useCallback(\n async (agentId?: string) => {\n const targetAgentId = agentId || defaultAgentId;\n const res = await fetchWithAuth('/threads', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ agentId: targetAgentId }),\n });\n if (!res.ok) throw new Error(`Failed to create thread: ${res.statusText}`);\n const data = await res.json();\n const created = (data?.data ?? data) as PersonaThread;\n void fetchThreads();\n return created;\n },\n [fetchWithAuth, defaultAgentId, fetchThreads]\n );\n\n const deleteThread = useCallback(\n async (threadId: string) => {\n const res = await fetchWithAuth(`/threads/${threadId}`, { method: 'DELETE' });\n if (!res.ok) throw new Error(`Failed to delete thread: ${res.statusText}`);\n setThreads((prev) => prev.filter((t) => t._id !== threadId));\n },\n [fetchWithAuth]\n );\n\n // Best-effort batch delete — no not-found id aborts the rest. Up to 100\n // ids per call, matching the server's own limit.\n const bulkDeleteThreads = useCallback(\n async (threadIds: string[]) => {\n const res = await fetchWithAuth('/threads/bulk-delete', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ ids: threadIds }),\n });\n if (!res.ok) throw new Error(`Failed to bulk-delete threads: ${res.statusText}`);\n const data = await res.json();\n const result = (data?.data ?? data) as { deleted: string[]; failed: Array<{ id: string; reason: string }> };\n const deletedSet = new Set(result.deleted);\n setThreads((prev) => prev.filter((t) => !deletedSet.has(t._id)));\n return result;\n },\n [fetchWithAuth]\n );\n\n // Convenience wrapper: there is no server-side \"delete everything\"\n // endpoint, only bulk-delete-by-id — so this bulk-deletes every\n // currently-loaded thread (up to 100 per call, chunked if there are more).\n const deleteAllThreads = useCallback(async () => {\n const ids = threads.map((t) => t._id);\n for (let i = 0; i < ids.length; i += 100) {\n await bulkDeleteThreads(ids.slice(i, i + 100));\n }\n }, [threads, bulkDeleteThreads]);\n\n // General-purpose update — { title?, isArchived? }.\n const updateThread = useCallback(\n async (threadId: string, input: { title?: string; isArchived?: boolean }) => {\n const res = await fetchWithAuth(`/threads/${threadId}`, {\n method: 'PATCH',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(input),\n });\n if (!res.ok) throw new Error(`Failed to update thread: ${res.statusText}`);\n const data = await res.json();\n const updated = (data?.data ?? data) as PersonaThread;\n setThreads((prev) => prev.map((t) => (t._id === threadId ? { ...t, ...updated } : t)));\n return updated;\n },\n [fetchWithAuth]\n );\n\n const renameThread = useCallback(\n (threadId: string, title: string) => updateThread(threadId, { title }),\n [updateThread]\n );\n\n const getThread = useCallback(\n async (threadId: string) => {\n const res = await fetchWithAuth(`/threads/${threadId}`);\n if (!res.ok) throw new Error(`Failed to fetch thread: ${res.statusText}`);\n const data = await res.json();\n return (data?.data ?? data) as PersonaThread;\n },\n [fetchWithAuth]\n );\n\n useEffect(() => {\n if (autoFetch) {\n void fetchThreads();\n }\n }, [autoFetch, fetchThreads]);\n\n return {\n threads,\n isLoading,\n error,\n refetch: fetchThreads,\n createThread,\n deleteThread,\n bulkDeleteThreads,\n deleteAllThreads,\n updateThread,\n renameThread,\n getThread,\n };\n}\n","'use client';\n\nimport { useCallback, useEffect, useState } from 'react';\nimport { usePersonaContext } from '../context/PersonaContext.js';\nimport type { PersonaFileItem } from '../types.js';\n\nexport type { PersonaFileItem };\n\nexport function useFiles(autoFetch = true) {\n const { fetchWithAuth } = usePersonaContext();\n const [files, setFiles] = useState<PersonaFileItem[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [isUploading, setIsUploading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n\n const fetchFiles = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n try {\n const res = await fetchWithAuth('/files');\n if (!res.ok) throw new Error(`Failed to list files: ${res.statusText}`);\n const data = await res.json();\n // Real shape is { items, pagination } — bare array/`.files` are\n // defensive fallbacks, not the actual wire contract.\n const items: PersonaFileItem[] = Array.isArray(data)\n ? data\n : data?.items || data?.files || [];\n setFiles(items);\n return items;\n } catch (err) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n return [];\n } finally {\n setIsLoading(false);\n }\n }, [fetchWithAuth]);\n\n const uploadFile = useCallback(\n async (fileOrFormData: FormData | { name: string; uri: string; type?: string }) => {\n setIsUploading(true);\n setError(null);\n try {\n let body: FormData;\n if (fileOrFormData instanceof FormData) {\n body = fileOrFormData;\n } else {\n // React Native FormData support\n body = new FormData();\n body.append('file', fileOrFormData as unknown as Blob);\n }\n\n const res = await fetchWithAuth('/files', {\n method: 'POST',\n body,\n });\n\n if (!res.ok) {\n const errText = await res.text().catch(() => 'Upload failed');\n throw new Error(`Upload error (${res.status}): ${errText}`);\n }\n\n const uploaded = (await res.json()) as PersonaFileItem;\n void fetchFiles();\n return uploaded;\n } catch (err) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n throw errorObj;\n } finally {\n setIsUploading(false);\n }\n },\n [fetchWithAuth, fetchFiles]\n );\n\n const deleteFile = useCallback(\n async (fileId: string) => {\n const res = await fetchWithAuth(`/files/${fileId}`, { method: 'DELETE' });\n if (!res.ok) throw new Error(`Failed to delete file: ${res.statusText}`);\n setFiles((prev) => prev.filter((f) => f.id !== fileId));\n },\n [fetchWithAuth]\n );\n\n const bulkDeleteFiles = useCallback(\n async (fileIds: string[]) => {\n const res = await fetchWithAuth('/files/bulk-delete', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ ids: fileIds }),\n });\n if (!res.ok) throw new Error(`Failed to bulk-delete files: ${res.statusText}`);\n const idSet = new Set(fileIds);\n setFiles((prev) => prev.filter((f) => !idSet.has(f.id)));\n return (await res.json()) as { deleted: string[]; failed: Array<{ id: string; reason: string }> };\n },\n [fetchWithAuth]\n );\n\n const getDownloadUrl = useCallback(\n (fileId: string) => {\n return `/files/${fileId}`;\n },\n []\n );\n\n useEffect(() => {\n if (autoFetch) {\n void fetchFiles();\n }\n }, [autoFetch, fetchFiles]);\n\n return {\n files,\n isLoading,\n isUploading,\n error,\n refetch: fetchFiles,\n uploadFile,\n deleteFile,\n bulkDeleteFiles,\n getDownloadUrl,\n };\n}\n","'use client';\n\nimport { useCallback, useEffect, useState } from 'react';\nimport { usePersonaContext } from '../context/PersonaContext.js';\n\nexport interface PersonaAgentSummary {\n _id: string;\n name: string;\n slug: string;\n description?: string;\n tagline?: string;\n avatar?: string;\n}\n\nexport function useAgents(autoFetch = true) {\n const { fetchWithAuth } = usePersonaContext();\n const [agents, setAgents] = useState<PersonaAgentSummary[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n\n const fetchAgents = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n try {\n const res = await fetchWithAuth('/agents');\n if (!res.ok) throw new Error(`Failed to list agents: ${res.statusText}`);\n const data = await res.json();\n // Real shape is { items, pagination }.\n const items: PersonaAgentSummary[] = Array.isArray(data)\n ? data\n : data?.items || data?.agents || [];\n setAgents(items);\n return items;\n } catch (err) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n return [];\n } finally {\n setIsLoading(false);\n }\n }, [fetchWithAuth]);\n\n useEffect(() => {\n if (autoFetch) {\n void fetchAgents();\n }\n }, [autoFetch, fetchAgents]);\n\n return {\n agents,\n isLoading,\n error,\n refetch: fetchAgents,\n };\n}\n","'use client';\n\nimport { useCallback, useEffect, useState } from 'react';\nimport { usePersonaContext } from '../context/PersonaContext.js';\n\nexport interface PersonaHealthInfo {\n status: string;\n version?: string;\n capabilities?: Record<string, boolean>;\n}\n\nexport function useConnection(autoCheck = true) {\n const { fetchWithAuth } = usePersonaContext();\n const [health, setHealth] = useState<PersonaHealthInfo | null>(null);\n const [isConnected, setIsConnected] = useState(false);\n const [isLoading, setIsLoading] = useState(false);\n\n const checkHealth = useCallback(async () => {\n setIsLoading(true);\n try {\n const res = await fetchWithAuth('/health');\n if (res.ok) {\n const data = (await res.json()) as PersonaHealthInfo;\n setHealth(data);\n setIsConnected(true);\n return data;\n }\n setIsConnected(false);\n return null;\n } catch {\n setIsConnected(false);\n return null;\n } finally {\n setIsLoading(false);\n }\n }, [fetchWithAuth]);\n\n useEffect(() => {\n if (autoCheck) {\n void checkHealth();\n }\n }, [autoCheck, checkHealth]);\n\n return {\n isConnected,\n health,\n isLoading,\n checkHealth,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEA,mBAA0D;AA6CjD;AAnCT,IAAM,qBAAiB,4BAA0C,IAAI;AAE9D,SAAS,gBAAgB;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAyB;AACvB,QAAM,wBAAoB,sBAAQ,MAAM,QAAQ,QAAQ,QAAQ,EAAE,GAAG,CAAC,OAAO,CAAC;AAE9E,QAAM,YAAQ,sBAA6B,MAAM;AAC/C,mBAAe,cAAc,MAAc,OAAoB,CAAC,GAAsB;AACpF,YAAM,QAAQ,eAAe,MAAM,aAAa,IAAI;AACpD,YAAM,UAAU,IAAI,QAAQ,KAAK,WAAW,CAAC,CAAC;AAC9C,UAAI,OAAO;AACT,gBAAQ,IAAI,iBAAiB,UAAU,KAAK,EAAE;AAAA,MAChD;AAEA,YAAM,YAAY,KAAK,WAAW,GAAG,IAAI,OAAO,IAAI,IAAI;AACxD,YAAM,MAAM,GAAG,iBAAiB,GAAG,SAAS;AAE5C,aAAO,MAAM,KAAK;AAAA,QAChB,GAAG;AAAA,QACH;AAAA,MACF,CAAC;AAAA,IACH;AAEA,WAAO;AAAA,MACL,SAAS;AAAA,MACT;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF,GAAG,CAAC,mBAAmB,cAAc,cAAc,CAAC;AAEpD,SAAO,4CAAC,eAAe,UAAf,EAAwB,OAAe,UAAS;AAC1D;AAEO,SAAS,oBAAyC;AACvD,QAAM,cAAU,yBAAW,cAAc;AACzC,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI,MA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AAAA,IACA;AAAA,EACF;AACF;;;APxCO,IAAM,UAAU;","names":["import_react","value","import_react","import_react","import_react","import_react","import_react"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/context/PersonaContext.tsx","../src/hooks/useChat.ts","../src/hooks/useMemory.ts","../src/hooks/useThreads.ts","../src/hooks/useFiles.ts","../src/hooks/useAgents.ts","../src/hooks/useConnection.ts","../src/hooks/useMcpConnections.ts"],"sourcesContent":["export * from './types.js';\nexport * from './context/PersonaContext.js';\nexport * from './hooks/useChat.js';\nexport * from './hooks/useMemory.js';\nexport * from './hooks/useThreads.js';\nexport * from './hooks/useFiles.js';\nexport * from './hooks/useAgents.js';\nexport * from './hooks/useConnection.js';\nexport * from './hooks/useMcpConnections.js';\n\nexport const VERSION = '0.3.4';\n","'use client';\n\nimport React, { createContext, useContext, useMemo } from 'react';\nimport type { PersonaProviderProps } from '../types.js';\n\ninterface PersonaContextValue {\n baseUrl: string;\n getAuthToken?: () => Promise<string | null | undefined> | string | null | undefined;\n defaultAgentId?: string;\n fetchWithAuth: (path: string, init?: RequestInit) => Promise<Response>;\n}\n\nconst PersonaContext = createContext<PersonaContextValue | null>(null);\n\nexport function PersonaProvider({\n baseUrl,\n getAuthToken,\n defaultAgentId,\n children,\n}: PersonaProviderProps) {\n const normalizedBaseUrl = useMemo(() => baseUrl.replace(/\\/+$/, ''), [baseUrl]);\n\n const value = useMemo<PersonaContextValue>(() => {\n async function fetchWithAuth(path: string, init: RequestInit = {}): Promise<Response> {\n const token = getAuthToken ? await getAuthToken() : null;\n const headers = new Headers(init.headers || {});\n if (token) {\n headers.set('Authorization', `Bearer ${token}`);\n }\n\n const cleanPath = path.startsWith('/') ? path : `/${path}`;\n const url = `${normalizedBaseUrl}${cleanPath}`;\n\n return fetch(url, {\n ...init,\n headers,\n });\n }\n\n return {\n baseUrl: normalizedBaseUrl,\n getAuthToken,\n defaultAgentId,\n fetchWithAuth,\n };\n }, [normalizedBaseUrl, getAuthToken, defaultAgentId]);\n\n return <PersonaContext.Provider value={value}>{children}</PersonaContext.Provider>;\n}\n\nexport function usePersonaContext(): PersonaContextValue {\n const context = useContext(PersonaContext);\n if (!context) {\n throw new Error('usePersonaContext must be used within a <PersonaProvider>');\n }\n return context;\n}\n","'use client';\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { usePersonaContext } from '../context/PersonaContext.js';\nimport type {\n PersonaInterrupt,\n PersonaMessage,\n PersonaPresentedFile,\n PersonaResumeValue,\n PersonaStreamingEvent,\n PersonaSubagentActivityEntry,\n PersonaTodo,\n PersonaToolCall,\n PersonaWorkspaceFile,\n SendMessageOverride,\n UseChatOptions,\n} from '../types.js';\n\n// A failed tool call's TOOL_CALL_RESULT content is a JSON envelope\n// (`{status:'error',message}`, see aguiTranslator.js's buildToolErrorContent)\n// rather than a separate boolean field on the event itself.\nfunction isErrorToolContent(content: string): boolean {\n if (typeof content !== 'string' || !content.trim().startsWith('{')) return false;\n try {\n return JSON.parse(content)?.status === 'error';\n } catch {\n return false;\n }\n}\n\n// present_file's result is `{status:'success', filePath, title, description}`\n// (see present.tool.js) — a signal to highlight that path in the workspace\n// files panel, not something meant to render as a generic tool-result blob.\nfunction parsePresentedFile(content: string): PersonaPresentedFile | null {\n try {\n const parsed = JSON.parse(content);\n if (parsed?.status !== 'success' || typeof parsed.filePath !== 'string') return null;\n return {\n path: parsed.filePath,\n title: typeof parsed.title === 'string' ? parsed.title : parsed.filePath,\n description: typeof parsed.description === 'string' ? parsed.description : '',\n };\n } catch {\n return null;\n }\n}\n\n// buildFilesTodosSnapshot (aguiTranslator.js) emits snake_case\n// created_at/modified_at on the wire — both from the live STATE_SNAPSHOT\n// event and from a reloaded thread's persisted state (checkpoint.service.js\n// runs the same function). Normalize to the SDK's usual camelCase shape.\nfunction normalizeWorkspaceFiles(\n raw: Record<string, { content: string; size: number; created_at: string | null; modified_at: string | null }>\n): Record<string, PersonaWorkspaceFile> {\n const normalized: Record<string, PersonaWorkspaceFile> = {};\n for (const [path, file] of Object.entries(raw || {})) {\n normalized[path] = {\n content: file.content,\n size: file.size,\n createdAt: file.created_at,\n modifiedAt: file.modified_at,\n };\n }\n return normalized;\n}\n\n// checkpointService.getMessages() wraps a paused thread's interrupt as\n// `{ kind, value }` (see checkpoint.service.js) — the same envelope shape\n// the live hitl_request/clarification_request CUSTOM events carry, just\n// nested one level deeper. Flatten both into the same PersonaInterrupt shape.\nfunction normalizePendingInterrupt(pending: unknown): PersonaInterrupt | null {\n if (!pending || typeof pending !== 'object') return null;\n const p = pending as { kind?: string; value?: Record<string, unknown> };\n if (p.kind === 'hitl') {\n return {\n kind: 'hitl',\n actionRequests: (p.value?.actionRequests ?? []) as Extract<\n PersonaInterrupt,\n { kind: 'hitl' }\n >['actionRequests'],\n reviewConfigs: (p.value?.reviewConfigs ?? []) as unknown[],\n };\n }\n if (p.kind === 'clarification') {\n return {\n kind: 'clarification',\n questions: (p.value?.questions ?? []) as Extract<PersonaInterrupt, { kind: 'clarification' }>['questions'],\n };\n }\n return null;\n}\n\nexport function useChat(options: UseChatOptions = {}) {\n const { defaultAgentId, fetchWithAuth } = usePersonaContext();\n const agentId = options.agentId || defaultAgentId;\n const threadId = options.threadId;\n\n const [messages, setMessages] = useState<PersonaMessage[]>(options.initialMessages || []);\n const [input, setInput] = useState('');\n const [isStreaming, setIsStreaming] = useState(false);\n const [isLoadingHistory, setIsLoadingHistory] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const [interrupt, setInterrupt] = useState<PersonaInterrupt | null>(null);\n const [files, setFiles] = useState<Record<string, PersonaWorkspaceFile>>({});\n const [todos, setTodos] = useState<PersonaTodo[]>([]);\n const [presentedFile, setPresentedFile] = useState<PersonaPresentedFile | null>(null);\n\n const abortControllerRef = useRef<AbortController | null>(null);\n const loadedThreadIdRef = useRef<string | undefined>(undefined);\n\n const stop = useCallback(() => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n abortControllerRef.current = null;\n setIsStreaming(false);\n }\n }, []);\n\n const clear = useCallback(() => {\n stop();\n setMessages([]);\n setError(null);\n setInterrupt(null);\n setFiles({});\n setTodos([]);\n setPresentedFile(null);\n }, [stop]);\n\n const loadThreadMessages = useCallback(\n async (id: string) => {\n setIsLoadingHistory(true);\n setError(null);\n try {\n const res = await fetchWithAuth(`/threads/${id}/messages`);\n if (!res.ok) throw new Error(`Failed to load thread history: ${res.statusText}`);\n const body = await res.json();\n const data = body?.data ?? body;\n const raw = (data?.messages ?? []) as Array<{\n id?: string;\n role: PersonaMessage['role'];\n content: string;\n toolCalls?: PersonaToolCall[];\n }>;\n const loaded: PersonaMessage[] = raw.map((m, i) => ({\n id: m.id || `history-${id}-${i}`,\n role: m.role,\n content: m.content,\n createdAt: new Date(),\n toolCalls: m.toolCalls,\n }));\n setMessages(loaded);\n // Re-show the approval/clarification card on reload if this thread\n // is currently paused — otherwise it wouldn't reappear until the\n // next live stream re-surfaces it.\n setInterrupt(normalizePendingInterrupt(data?.pendingInterrupt));\n // Restore the workspace files/todos this thread already had (same\n // cleaned shape checkpoint.service.js now derives via\n // buildFilesTodosSnapshot, matching the live STATE_SNAPSHOT event).\n setFiles(normalizeWorkspaceFiles(data?.state?.files ?? {}));\n setTodos((data?.state?.todos ?? []) as PersonaTodo[]);\n return loaded;\n } catch (err) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n return [];\n } finally {\n setIsLoadingHistory(false);\n }\n },\n [fetchWithAuth]\n );\n\n // Auto-load history the first time a thread with no in-memory messages is\n // selected (switching threads in the sidebar). Skipped for a thread whose\n // messages already live in state — e.g. one just created by handleSend,\n // which sets its placeholder messages in the same render batch as the\n // threadId change, so `messages` there is never empty at effect time.\n useEffect(() => {\n if (!threadId || isStreaming) return;\n if (loadedThreadIdRef.current === threadId) return;\n if (messages.length > 0) return;\n loadedThreadIdRef.current = threadId;\n void loadThreadMessages(threadId);\n }, [threadId, isStreaming, messages.length, loadThreadMessages]);\n\n const sendMessage = useCallback(\n async (contentToSend?: string, overrideOptions?: SendMessageOverride) => {\n const prompt = (contentToSend ?? input).trim();\n if (!prompt || isStreaming) return;\n\n const targetAgentId = overrideOptions?.agentId || agentId;\n if (!targetAgentId) {\n const err = new Error('No Agent ID specified for useChat.');\n setError(err);\n options.onError?.(err);\n return;\n }\n\n const userMessage: PersonaMessage = {\n id: `user-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,\n role: 'user',\n content: prompt,\n createdAt: new Date(),\n };\n\n const assistantMessageId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;\n const placeholderAssistant: PersonaMessage = {\n id: assistantMessageId,\n role: 'assistant',\n content: '',\n createdAt: new Date(),\n isStreaming: true,\n toolCalls: [],\n };\n\n const nextMessages = [...messages, userMessage];\n setMessages([...nextMessages, placeholderAssistant]);\n setInput('');\n setIsStreaming(true);\n setError(null);\n setInterrupt(null);\n\n const controller = new AbortController();\n abortControllerRef.current = controller;\n\n try {\n const payloadMessages = nextMessages.map((m) => ({\n role: m.role === 'assistant' ? ('assistant' as const) : ('user' as const),\n content: m.content,\n }));\n\n // Resolved here, not earlier — everything above this line (the\n // optimistic message + placeholder, clearing input, etc.) already\n // ran synchronously, so a caller passing an in-flight thread-creation\n // promise gets an instant UI update without the message send itself\n // waiting on it any longer than the network call already would.\n const resolvedThreadId = await (overrideOptions?.threadId ?? options.threadId);\n\n const response = await fetchWithAuth('/chat', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n agentId: targetAgentId,\n messages: payloadMessages,\n threadId: resolvedThreadId,\n resume: overrideOptions?.resume,\n }),\n signal: controller.signal,\n });\n\n if (!response.ok) {\n const errText = await response.text().catch(() => 'Stream failed');\n throw new Error(`Chat error (${response.status}): ${errText}`);\n }\n\n if (!response.body) {\n throw new Error('No response body received for streaming.');\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder('utf-8');\n let buffer = '';\n let accumulatedText = '';\n let accumulatedReasoning = '';\n const toolCallsMap = new Map<string, PersonaToolCall>();\n\n const patchAssistant = (patch: Partial<PersonaMessage>) => {\n setMessages((prev) =>\n prev.map((msg) =>\n msg.id === assistantMessageId\n ? { ...msg, toolCalls: Array.from(toolCallsMap.values()), ...patch }\n : msg\n )\n );\n };\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed || !trimmed.startsWith('data:')) continue;\n\n const raw = trimmed.replace(/^data:\\s*/, '');\n if (raw === '[DONE]') break;\n\n try {\n const event = JSON.parse(raw) as PersonaStreamingEvent;\n options.onEvent?.(event);\n\n if (event.type === 'TEXT_MESSAGE_CHUNK' && event.delta) {\n accumulatedText += event.delta;\n patchAssistant({ content: accumulatedText, isStreaming: true });\n } else if (event.type === 'TOOL_CALL_CHUNK' && event.toolCallId) {\n // The backend streams tool calls as accumulating chunks\n // (id/name arrive on the first chunk, args stream in pieces\n // across subsequent ones) rather than separate start/args\n // events.\n const existing = toolCallsMap.get(event.toolCallId);\n if (existing) {\n existing.args = (existing.args || '') + (event.delta || '');\n } else {\n toolCallsMap.set(event.toolCallId, {\n toolCallId: event.toolCallId,\n toolName: event.toolCallName || '',\n args: event.delta || '',\n });\n }\n patchAssistant({});\n } else if (event.type === 'TOOL_CALL_RESULT') {\n const existing = toolCallsMap.get(event.toolCallId);\n if (existing) {\n existing.result = event.content;\n existing.isError = isErrorToolContent(event.content);\n if (existing.toolName === 'present_file' && !existing.isError) {\n const presented = parsePresentedFile(event.content);\n if (presented) setPresentedFile(presented);\n }\n patchAssistant({});\n }\n } else if (event.type === 'STATE_SNAPSHOT') {\n setFiles(normalizeWorkspaceFiles(event.snapshot.files));\n setTodos(event.snapshot.todos);\n } else if (event.type === 'REASONING_MESSAGE_CONTENT') {\n accumulatedReasoning += event.delta;\n patchAssistant({ reasoning: accumulatedReasoning, isReasoning: true });\n } else if (event.type === 'REASONING_END') {\n patchAssistant({ isReasoning: false });\n } else if (event.type === 'CUSTOM') {\n if (event.name === 'hitl_request') {\n const value = event.value as Extract<PersonaInterrupt, { kind: 'hitl' }>;\n setInterrupt({\n kind: 'hitl',\n actionRequests: value.actionRequests,\n reviewConfigs: value.reviewConfigs,\n });\n } else if (event.name === 'clarification_request') {\n const value = event.value as Extract<PersonaInterrupt, { kind: 'clarification' }>;\n setInterrupt({ kind: 'clarification', questions: value.questions });\n } else if (event.name === 'subagent_activity') {\n const { toolCallId, ...entry } = event.value as { toolCallId: string } & PersonaSubagentActivityEntry;\n const existing = toolCallsMap.get(toolCallId);\n if (existing) {\n existing.subagentActivity = [...(existing.subagentActivity || []), entry];\n patchAssistant({});\n }\n }\n // 'mcp_app' custom events carry no chat-transcript UI here —\n // consumers that render MCP widgets read them via onEvent.\n } else if (event.type === 'RUN_ERROR') {\n throw new Error(event.message || 'Stream error from agent');\n }\n } catch (e) {\n if (e instanceof Error && e.message.startsWith('Stream error')) {\n throw e;\n }\n }\n }\n }\n\n const finalMessage: PersonaMessage = {\n id: assistantMessageId,\n role: 'assistant',\n content: accumulatedText,\n createdAt: new Date(),\n isStreaming: false,\n toolCalls: Array.from(toolCallsMap.values()),\n ...(accumulatedReasoning ? { reasoning: accumulatedReasoning, isReasoning: false } : {}),\n };\n\n setMessages((prev) =>\n prev.map((msg) => (msg.id === assistantMessageId ? finalMessage : msg))\n );\n\n options.onFinish?.(finalMessage);\n } catch (err) {\n if (controller.signal.aborted) {\n setMessages((prev) =>\n prev.map((msg) =>\n msg.id === assistantMessageId ? { ...msg, isStreaming: false } : msg\n )\n );\n return;\n }\n\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n options.onError?.(errorObj);\n\n setMessages((prev) =>\n prev.map((msg) =>\n msg.id === assistantMessageId\n ? {\n ...msg,\n content:\n msg.content || `⚠️ Error: ${errorObj.message || 'Failed to get response.'}`,\n isStreaming: false,\n }\n : msg\n )\n );\n } finally {\n setIsStreaming(false);\n abortControllerRef.current = null;\n }\n },\n [agentId, fetchWithAuth, input, isStreaming, messages, options]\n );\n\n const handleInputChange = useCallback((e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {\n setInput(e.target.value);\n }, []);\n\n const handleSubmit = useCallback(\n (e?: React.FormEvent) => {\n if (e) e.preventDefault();\n void sendMessage();\n },\n [sendMessage]\n );\n\n const reload = useCallback(() => {\n if (messages.length === 0 || isStreaming) return;\n let lastUserIndex = -1;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role === 'user') {\n lastUserIndex = i;\n break;\n }\n }\n if (lastUserIndex === -1) return;\n\n const lastUserMessage = messages[lastUserIndex];\n setMessages(messages.slice(0, lastUserIndex));\n void sendMessage(lastUserMessage.content);\n }, [isStreaming, messages, sendMessage]);\n\n // Unpauses a paused HITL/clarification run. `displayContent` becomes the\n // visible user-turn bubble (e.g. \"Approved\", or the typed clarification\n // answer) — the server resolves the actual resume value from `resume`\n // itself, `displayContent` is only ever used for its own transcript text.\n const resumeInterrupt = useCallback(\n (resume: PersonaResumeValue, displayContent: string) => sendMessage(displayContent, { resume }),\n [sendMessage]\n );\n\n const dismissPresentedFile = useCallback(() => setPresentedFile(null), []);\n\n // Manually re-open a workspace file — e.g. a present_file tool card's\n // \"Open\" button, after the auto-opened drawer was closed or a different\n // file was selected since.\n const openWorkspaceFile = useCallback(\n (path: string) => setPresentedFile({ path, title: path.split('/').pop() || path, description: '' }),\n []\n );\n\n return {\n messages,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n sendMessage,\n isStreaming,\n isLoading: isStreaming,\n isLoadingHistory,\n error,\n interrupt,\n resumeInterrupt,\n files,\n todos,\n presentedFile,\n dismissPresentedFile,\n openWorkspaceFile,\n stop,\n reload,\n clear,\n setMessages,\n loadThreadMessages,\n };\n}\n","'use client';\n\nimport { useCallback, useEffect, useState } from 'react';\nimport { usePersonaContext } from '../context/PersonaContext.js';\nimport type { PersonaMemoryFile, PersonaMemoryList } from '../types.js';\n\nexport function useMemory(autoFetch = true) {\n const { fetchWithAuth } = usePersonaContext();\n const [memory, setMemory] = useState<PersonaMemoryList>({ userFiles: [], agentMemories: [] });\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n\n const fetchMemory = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n try {\n const res = await fetchWithAuth('/memory');\n if (!res.ok) {\n throw new Error(`Failed to fetch memory: ${res.statusText}`);\n }\n const data = (await res.json()) as PersonaMemoryList;\n setMemory(data);\n return data;\n } catch (err) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n return { userFiles: [], agentMemories: [] };\n } finally {\n setIsLoading(false);\n }\n }, [fetchWithAuth]);\n\n const getFile = useCallback(\n async (params: { path: string; scope?: 'user' | 'agent'; agentId?: string }) => {\n const query = new URLSearchParams({ path: params.path });\n if (params.scope) query.set('scope', params.scope);\n if (params.agentId) query.set('agentId', params.agentId);\n\n const res = await fetchWithAuth(`/memory/file?${query.toString()}`);\n if (!res.ok) throw new Error(`Failed to get memory file: ${res.statusText}`);\n return (await res.json()) as PersonaMemoryFile;\n },\n [fetchWithAuth]\n );\n\n const writeFile = useCallback(\n async (params: { path: string; content: string; scope?: 'user' | 'agent'; agentId?: string }) => {\n const res = await fetchWithAuth('/memory/file', {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(params),\n });\n if (!res.ok) throw new Error(`Failed to write memory file: ${res.statusText}`);\n const updated = (await res.json()) as PersonaMemoryFile;\n void fetchMemory();\n return updated;\n },\n [fetchWithAuth, fetchMemory]\n );\n\n const deleteFile = useCallback(\n async (params: { path: string; scope?: 'user' | 'agent'; agentId?: string }) => {\n const query = new URLSearchParams({ path: params.path });\n if (params.scope) query.set('scope', params.scope);\n if (params.agentId) query.set('agentId', params.agentId);\n\n const res = await fetchWithAuth(`/memory/file?${query.toString()}`, {\n method: 'DELETE',\n });\n if (!res.ok) throw new Error(`Failed to delete memory file: ${res.statusText}`);\n void fetchMemory();\n },\n [fetchWithAuth, fetchMemory]\n );\n\n useEffect(() => {\n if (autoFetch) {\n void fetchMemory();\n }\n }, [autoFetch, fetchMemory]);\n\n return {\n memory,\n isLoading,\n error,\n refetch: fetchMemory,\n getFile,\n writeFile,\n deleteFile,\n };\n}\n","'use client';\n\nimport { useCallback, useEffect, useState } from 'react';\nimport { usePersonaContext } from '../context/PersonaContext.js';\nimport type { PersonaThread } from '../types.js';\n\nexport function useThreads(autoFetch = true) {\n const { fetchWithAuth, defaultAgentId } = usePersonaContext();\n const [threads, setThreads] = useState<PersonaThread[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n\n const fetchThreads = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n try {\n const res = await fetchWithAuth('/threads');\n if (!res.ok) throw new Error(`Failed to list threads: ${res.statusText}`);\n const data = await res.json();\n // Real shape is { items, pagination }. Bare array / `.data` / `.threads`\n // are defensive fallbacks for other deployments, not the actual contract.\n const items: PersonaThread[] = Array.isArray(data)\n ? data\n : data?.items || data?.threads || (Array.isArray(data?.data) ? data.data : undefined) || [];\n setThreads(items);\n return items;\n } catch (err) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n return [];\n } finally {\n setIsLoading(false);\n }\n }, [fetchWithAuth]);\n\n const createThread = useCallback(\n async (agentId?: string) => {\n const targetAgentId = agentId || defaultAgentId;\n const res = await fetchWithAuth('/threads', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ agentId: targetAgentId }),\n });\n if (!res.ok) throw new Error(`Failed to create thread: ${res.statusText}`);\n const data = await res.json();\n const created = (data?.data ?? data) as PersonaThread;\n void fetchThreads();\n return created;\n },\n [fetchWithAuth, defaultAgentId, fetchThreads]\n );\n\n const deleteThread = useCallback(\n async (threadId: string) => {\n const res = await fetchWithAuth(`/threads/${threadId}`, { method: 'DELETE' });\n if (!res.ok) throw new Error(`Failed to delete thread: ${res.statusText}`);\n setThreads((prev) => prev.filter((t) => t._id !== threadId));\n },\n [fetchWithAuth]\n );\n\n // Best-effort batch delete — no not-found id aborts the rest. Up to 100\n // ids per call, matching the server's own limit.\n const bulkDeleteThreads = useCallback(\n async (threadIds: string[]) => {\n const res = await fetchWithAuth('/threads/bulk-delete', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ ids: threadIds }),\n });\n if (!res.ok) throw new Error(`Failed to bulk-delete threads: ${res.statusText}`);\n const data = await res.json();\n const result = (data?.data ?? data) as { deleted: string[]; failed: Array<{ id: string; reason: string }> };\n const deletedSet = new Set(result.deleted);\n setThreads((prev) => prev.filter((t) => !deletedSet.has(t._id)));\n return result;\n },\n [fetchWithAuth]\n );\n\n // Convenience wrapper: there is no server-side \"delete everything\"\n // endpoint, only bulk-delete-by-id — so this bulk-deletes every\n // currently-loaded thread (up to 100 per call, chunked if there are more).\n const deleteAllThreads = useCallback(async () => {\n const ids = threads.map((t) => t._id);\n for (let i = 0; i < ids.length; i += 100) {\n await bulkDeleteThreads(ids.slice(i, i + 100));\n }\n }, [threads, bulkDeleteThreads]);\n\n // General-purpose update — { title?, isArchived? }.\n const updateThread = useCallback(\n async (threadId: string, input: { title?: string; isArchived?: boolean }) => {\n const res = await fetchWithAuth(`/threads/${threadId}`, {\n method: 'PATCH',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(input),\n });\n if (!res.ok) throw new Error(`Failed to update thread: ${res.statusText}`);\n const data = await res.json();\n const updated = (data?.data ?? data) as PersonaThread;\n setThreads((prev) => prev.map((t) => (t._id === threadId ? { ...t, ...updated } : t)));\n return updated;\n },\n [fetchWithAuth]\n );\n\n const renameThread = useCallback(\n (threadId: string, title: string) => updateThread(threadId, { title }),\n [updateThread]\n );\n\n const getThread = useCallback(\n async (threadId: string) => {\n const res = await fetchWithAuth(`/threads/${threadId}`);\n if (!res.ok) throw new Error(`Failed to fetch thread: ${res.statusText}`);\n const data = await res.json();\n return (data?.data ?? data) as PersonaThread;\n },\n [fetchWithAuth]\n );\n\n useEffect(() => {\n if (autoFetch) {\n void fetchThreads();\n }\n }, [autoFetch, fetchThreads]);\n\n return {\n threads,\n isLoading,\n error,\n refetch: fetchThreads,\n createThread,\n deleteThread,\n bulkDeleteThreads,\n deleteAllThreads,\n updateThread,\n renameThread,\n getThread,\n };\n}\n","'use client';\n\nimport { useCallback, useEffect, useState } from 'react';\nimport { usePersonaContext } from '../context/PersonaContext.js';\nimport type { PersonaFileItem } from '../types.js';\n\nexport type { PersonaFileItem };\n\nexport function useFiles(autoFetch = true) {\n const { fetchWithAuth } = usePersonaContext();\n const [files, setFiles] = useState<PersonaFileItem[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [isUploading, setIsUploading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n\n const fetchFiles = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n try {\n const res = await fetchWithAuth('/files');\n if (!res.ok) throw new Error(`Failed to list files: ${res.statusText}`);\n const data = await res.json();\n // Real shape is { items, pagination } — bare array/`.files` are\n // defensive fallbacks, not the actual wire contract.\n const items: PersonaFileItem[] = Array.isArray(data)\n ? data\n : data?.items || data?.files || [];\n setFiles(items);\n return items;\n } catch (err) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n return [];\n } finally {\n setIsLoading(false);\n }\n }, [fetchWithAuth]);\n\n const uploadFile = useCallback(\n async (fileOrFormData: FormData | { name: string; uri: string; type?: string }) => {\n setIsUploading(true);\n setError(null);\n try {\n let body: FormData;\n if (fileOrFormData instanceof FormData) {\n body = fileOrFormData;\n } else {\n // React Native FormData support\n body = new FormData();\n body.append('file', fileOrFormData as unknown as Blob);\n }\n\n const res = await fetchWithAuth('/files', {\n method: 'POST',\n body,\n });\n\n if (!res.ok) {\n const errText = await res.text().catch(() => 'Upload failed');\n throw new Error(`Upload error (${res.status}): ${errText}`);\n }\n\n const uploaded = (await res.json()) as PersonaFileItem;\n void fetchFiles();\n return uploaded;\n } catch (err) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n throw errorObj;\n } finally {\n setIsUploading(false);\n }\n },\n [fetchWithAuth, fetchFiles]\n );\n\n const deleteFile = useCallback(\n async (fileId: string) => {\n const res = await fetchWithAuth(`/files/${fileId}`, { method: 'DELETE' });\n if (!res.ok) throw new Error(`Failed to delete file: ${res.statusText}`);\n setFiles((prev) => prev.filter((f) => f.id !== fileId));\n },\n [fetchWithAuth]\n );\n\n const bulkDeleteFiles = useCallback(\n async (fileIds: string[]) => {\n const res = await fetchWithAuth('/files/bulk-delete', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ ids: fileIds }),\n });\n if (!res.ok) throw new Error(`Failed to bulk-delete files: ${res.statusText}`);\n const idSet = new Set(fileIds);\n setFiles((prev) => prev.filter((f) => !idSet.has(f.id)));\n return (await res.json()) as { deleted: string[]; failed: Array<{ id: string; reason: string }> };\n },\n [fetchWithAuth]\n );\n\n const getDownloadUrl = useCallback(\n (fileId: string) => {\n return `/files/${fileId}`;\n },\n []\n );\n\n useEffect(() => {\n if (autoFetch) {\n void fetchFiles();\n }\n }, [autoFetch, fetchFiles]);\n\n return {\n files,\n isLoading,\n isUploading,\n error,\n refetch: fetchFiles,\n uploadFile,\n deleteFile,\n bulkDeleteFiles,\n getDownloadUrl,\n };\n}\n","'use client';\n\nimport { useCallback, useEffect, useState } from 'react';\nimport { usePersonaContext } from '../context/PersonaContext.js';\n\nexport interface PersonaAgentSummary {\n _id: string;\n name: string;\n slug: string;\n description?: string;\n tagline?: string;\n avatar?: string;\n}\n\nexport function useAgents(autoFetch = true) {\n const { fetchWithAuth } = usePersonaContext();\n const [agents, setAgents] = useState<PersonaAgentSummary[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n\n const fetchAgents = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n try {\n const res = await fetchWithAuth('/agents');\n if (!res.ok) throw new Error(`Failed to list agents: ${res.statusText}`);\n const data = await res.json();\n // Real shape is { items, pagination }.\n const items: PersonaAgentSummary[] = Array.isArray(data)\n ? data\n : data?.items || data?.agents || [];\n setAgents(items);\n return items;\n } catch (err) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n return [];\n } finally {\n setIsLoading(false);\n }\n }, [fetchWithAuth]);\n\n useEffect(() => {\n if (autoFetch) {\n void fetchAgents();\n }\n }, [autoFetch, fetchAgents]);\n\n return {\n agents,\n isLoading,\n error,\n refetch: fetchAgents,\n };\n}\n","'use client';\n\nimport { useCallback, useEffect, useState } from 'react';\nimport { usePersonaContext } from '../context/PersonaContext.js';\n\nexport interface PersonaHealthInfo {\n status: string;\n version?: string;\n capabilities?: Record<string, boolean>;\n}\n\nexport function useConnection(autoCheck = true) {\n const { fetchWithAuth } = usePersonaContext();\n const [health, setHealth] = useState<PersonaHealthInfo | null>(null);\n const [isConnected, setIsConnected] = useState(false);\n const [isLoading, setIsLoading] = useState(false);\n\n const checkHealth = useCallback(async () => {\n setIsLoading(true);\n try {\n const res = await fetchWithAuth('/health');\n if (res.ok) {\n const data = (await res.json()) as PersonaHealthInfo;\n setHealth(data);\n setIsConnected(true);\n return data;\n }\n setIsConnected(false);\n return null;\n } catch {\n setIsConnected(false);\n return null;\n } finally {\n setIsLoading(false);\n }\n }, [fetchWithAuth]);\n\n useEffect(() => {\n if (autoCheck) {\n void checkHealth();\n }\n }, [autoCheck, checkHealth]);\n\n return {\n isConnected,\n health,\n isLoading,\n checkHealth,\n };\n}\n","'use client';\n\nimport { useCallback, useEffect, useState } from 'react';\nimport { usePersonaContext } from '../context/PersonaContext.js';\n\n/**\n * One `authType: 'oauth', authMode: 'user'` MCP an Agent has attached, and\n * whether the current end user has connected it yet. `authorizeUrl` is only\n * present when `connected` is `false` — navigate the browser there (a\n * same-tab redirect is fine; it's a real OAuth authorization URL) to start\n * the consent flow.\n */\nexport interface PersonaMcpConnection {\n mcpId: string;\n name: string;\n description: string;\n connected: boolean;\n authorizeUrl: string | null;\n}\n\nexport interface UseMcpConnectionsOptions {\n /** @default the PersonaProvider's defaultAgentId */\n agentId?: string;\n /** Where the browser lands after OAuth consent completes. @default window.location.href */\n returnTo?: string;\n /** @default true */\n autoFetch?: boolean;\n}\n\n/**\n * Surfaces the gap that used to be invisible entirely: a user-mode MCP tool\n * call for a user who hasn't connected yet is silently dropped from the\n * Agent's toolset server-side, with no signal in the chat stream at all.\n * Check this before (or alongside) a chat session to show a real \"Connect\n * your account\" affordance instead of a capability that just quietly isn't\n * there.\n */\nexport function useMcpConnections(options: UseMcpConnectionsOptions = {}) {\n const { defaultAgentId, fetchWithAuth } = usePersonaContext();\n const agentId = options.agentId ?? defaultAgentId;\n const autoFetch = options.autoFetch ?? true;\n\n const [connections, setConnections] = useState<PersonaMcpConnection[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n\n const fetchConnections = useCallback(async () => {\n if (!agentId) return [];\n setIsLoading(true);\n setError(null);\n try {\n const returnTo =\n options.returnTo ?? (typeof window !== 'undefined' ? window.location.href : undefined);\n const query = returnTo ? `?returnTo=${encodeURIComponent(returnTo)}` : '';\n const res = await fetchWithAuth(`/agents/${agentId}/mcp-connections${query}`);\n if (!res.ok) throw new Error(`Failed to load MCP connections: ${res.statusText}`);\n const data = await res.json();\n const items: PersonaMcpConnection[] = Array.isArray(data) ? data : data?.items || [];\n setConnections(items);\n return items;\n } catch (err) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n return [];\n } finally {\n setIsLoading(false);\n }\n }, [agentId, fetchWithAuth, options.returnTo]);\n\n useEffect(() => {\n if (autoFetch) void fetchConnections();\n }, [autoFetch, fetchConnections]);\n\n return {\n connections,\n /** Convenience filter for the common \"show a banner for what's missing\" case. */\n unconnected: connections.filter((c) => !c.connected),\n isLoading,\n error,\n refetch: fetchConnections,\n };\n}\n"],"mappings":";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","value","import_react","import_react","import_react","import_react","import_react","import_react"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -232,7 +232,17 @@ interface UseChatOptions {
|
|
|
232
232
|
}
|
|
233
233
|
interface SendMessageOverride {
|
|
234
234
|
agentId?: string;
|
|
235
|
-
|
|
235
|
+
/**
|
|
236
|
+
* A plain id, or a promise/thunk for one still in flight (e.g. a thread
|
|
237
|
+
* being lazily created for the first message of a new conversation).
|
|
238
|
+
* `sendMessage` only awaits this right before building the request body —
|
|
239
|
+
* its own optimistic UI update (adding the user's message + a streaming
|
|
240
|
+
* placeholder) already ran synchronously before that point, so callers
|
|
241
|
+
* don't have to choose between "wait for the thread to exist" and
|
|
242
|
+
* "show the message instantly": passing an in-flight promise here gets
|
|
243
|
+
* both.
|
|
244
|
+
*/
|
|
245
|
+
threadId?: string | Promise<string | undefined>;
|
|
236
246
|
/** Answers/approves a paused interrupt from a previous turn instead of starting a fresh one. */
|
|
237
247
|
resume?: PersonaResumeValue;
|
|
238
248
|
}
|
|
@@ -366,6 +376,45 @@ declare function useConnection(autoCheck?: boolean): {
|
|
|
366
376
|
checkHealth: () => Promise<PersonaHealthInfo | null>;
|
|
367
377
|
};
|
|
368
378
|
|
|
369
|
-
|
|
379
|
+
/**
|
|
380
|
+
* One `authType: 'oauth', authMode: 'user'` MCP an Agent has attached, and
|
|
381
|
+
* whether the current end user has connected it yet. `authorizeUrl` is only
|
|
382
|
+
* present when `connected` is `false` — navigate the browser there (a
|
|
383
|
+
* same-tab redirect is fine; it's a real OAuth authorization URL) to start
|
|
384
|
+
* the consent flow.
|
|
385
|
+
*/
|
|
386
|
+
interface PersonaMcpConnection {
|
|
387
|
+
mcpId: string;
|
|
388
|
+
name: string;
|
|
389
|
+
description: string;
|
|
390
|
+
connected: boolean;
|
|
391
|
+
authorizeUrl: string | null;
|
|
392
|
+
}
|
|
393
|
+
interface UseMcpConnectionsOptions {
|
|
394
|
+
/** @default the PersonaProvider's defaultAgentId */
|
|
395
|
+
agentId?: string;
|
|
396
|
+
/** Where the browser lands after OAuth consent completes. @default window.location.href */
|
|
397
|
+
returnTo?: string;
|
|
398
|
+
/** @default true */
|
|
399
|
+
autoFetch?: boolean;
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* Surfaces the gap that used to be invisible entirely: a user-mode MCP tool
|
|
403
|
+
* call for a user who hasn't connected yet is silently dropped from the
|
|
404
|
+
* Agent's toolset server-side, with no signal in the chat stream at all.
|
|
405
|
+
* Check this before (or alongside) a chat session to show a real "Connect
|
|
406
|
+
* your account" affordance instead of a capability that just quietly isn't
|
|
407
|
+
* there.
|
|
408
|
+
*/
|
|
409
|
+
declare function useMcpConnections(options?: UseMcpConnectionsOptions): {
|
|
410
|
+
connections: PersonaMcpConnection[];
|
|
411
|
+
/** Convenience filter for the common "show a banner for what's missing" case. */
|
|
412
|
+
unconnected: PersonaMcpConnection[];
|
|
413
|
+
isLoading: boolean;
|
|
414
|
+
error: Error | null;
|
|
415
|
+
refetch: () => Promise<PersonaMcpConnection[]>;
|
|
416
|
+
};
|
|
417
|
+
|
|
418
|
+
declare const VERSION = "0.3.4";
|
|
370
419
|
|
|
371
|
-
export { type PersonaAgentSummary, type PersonaClarificationQuestion, type PersonaFileItem, type PersonaHealthInfo, type PersonaHitlActionRequest, type PersonaInterrupt, type PersonaMemoryAgentGroup, type PersonaMemoryFile, type PersonaMemoryList, type PersonaMessage, type PersonaPresentedFile, PersonaProvider, type PersonaProviderProps, type PersonaResumeValue, type PersonaRole, type PersonaStreamingEvent, type PersonaSubagentActivityEntry, type PersonaThread, type PersonaTodo, type PersonaToolCall, type PersonaWorkspaceFile, type SendMessageOverride, type UseChatOptions, VERSION, useAgents, useChat, useConnection, useFiles, useMemory, usePersonaContext, useThreads };
|
|
420
|
+
export { type PersonaAgentSummary, type PersonaClarificationQuestion, type PersonaFileItem, type PersonaHealthInfo, type PersonaHitlActionRequest, type PersonaInterrupt, type PersonaMcpConnection, type PersonaMemoryAgentGroup, type PersonaMemoryFile, type PersonaMemoryList, type PersonaMessage, type PersonaPresentedFile, PersonaProvider, type PersonaProviderProps, type PersonaResumeValue, type PersonaRole, type PersonaStreamingEvent, type PersonaSubagentActivityEntry, type PersonaThread, type PersonaTodo, type PersonaToolCall, type PersonaWorkspaceFile, type SendMessageOverride, type UseChatOptions, type UseMcpConnectionsOptions, VERSION, useAgents, useChat, useConnection, useFiles, useMcpConnections, useMemory, usePersonaContext, useThreads };
|
package/dist/index.d.ts
CHANGED
|
@@ -232,7 +232,17 @@ interface UseChatOptions {
|
|
|
232
232
|
}
|
|
233
233
|
interface SendMessageOverride {
|
|
234
234
|
agentId?: string;
|
|
235
|
-
|
|
235
|
+
/**
|
|
236
|
+
* A plain id, or a promise/thunk for one still in flight (e.g. a thread
|
|
237
|
+
* being lazily created for the first message of a new conversation).
|
|
238
|
+
* `sendMessage` only awaits this right before building the request body —
|
|
239
|
+
* its own optimistic UI update (adding the user's message + a streaming
|
|
240
|
+
* placeholder) already ran synchronously before that point, so callers
|
|
241
|
+
* don't have to choose between "wait for the thread to exist" and
|
|
242
|
+
* "show the message instantly": passing an in-flight promise here gets
|
|
243
|
+
* both.
|
|
244
|
+
*/
|
|
245
|
+
threadId?: string | Promise<string | undefined>;
|
|
236
246
|
/** Answers/approves a paused interrupt from a previous turn instead of starting a fresh one. */
|
|
237
247
|
resume?: PersonaResumeValue;
|
|
238
248
|
}
|
|
@@ -366,6 +376,45 @@ declare function useConnection(autoCheck?: boolean): {
|
|
|
366
376
|
checkHealth: () => Promise<PersonaHealthInfo | null>;
|
|
367
377
|
};
|
|
368
378
|
|
|
369
|
-
|
|
379
|
+
/**
|
|
380
|
+
* One `authType: 'oauth', authMode: 'user'` MCP an Agent has attached, and
|
|
381
|
+
* whether the current end user has connected it yet. `authorizeUrl` is only
|
|
382
|
+
* present when `connected` is `false` — navigate the browser there (a
|
|
383
|
+
* same-tab redirect is fine; it's a real OAuth authorization URL) to start
|
|
384
|
+
* the consent flow.
|
|
385
|
+
*/
|
|
386
|
+
interface PersonaMcpConnection {
|
|
387
|
+
mcpId: string;
|
|
388
|
+
name: string;
|
|
389
|
+
description: string;
|
|
390
|
+
connected: boolean;
|
|
391
|
+
authorizeUrl: string | null;
|
|
392
|
+
}
|
|
393
|
+
interface UseMcpConnectionsOptions {
|
|
394
|
+
/** @default the PersonaProvider's defaultAgentId */
|
|
395
|
+
agentId?: string;
|
|
396
|
+
/** Where the browser lands after OAuth consent completes. @default window.location.href */
|
|
397
|
+
returnTo?: string;
|
|
398
|
+
/** @default true */
|
|
399
|
+
autoFetch?: boolean;
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* Surfaces the gap that used to be invisible entirely: a user-mode MCP tool
|
|
403
|
+
* call for a user who hasn't connected yet is silently dropped from the
|
|
404
|
+
* Agent's toolset server-side, with no signal in the chat stream at all.
|
|
405
|
+
* Check this before (or alongside) a chat session to show a real "Connect
|
|
406
|
+
* your account" affordance instead of a capability that just quietly isn't
|
|
407
|
+
* there.
|
|
408
|
+
*/
|
|
409
|
+
declare function useMcpConnections(options?: UseMcpConnectionsOptions): {
|
|
410
|
+
connections: PersonaMcpConnection[];
|
|
411
|
+
/** Convenience filter for the common "show a banner for what's missing" case. */
|
|
412
|
+
unconnected: PersonaMcpConnection[];
|
|
413
|
+
isLoading: boolean;
|
|
414
|
+
error: Error | null;
|
|
415
|
+
refetch: () => Promise<PersonaMcpConnection[]>;
|
|
416
|
+
};
|
|
417
|
+
|
|
418
|
+
declare const VERSION = "0.3.4";
|
|
370
419
|
|
|
371
|
-
export { type PersonaAgentSummary, type PersonaClarificationQuestion, type PersonaFileItem, type PersonaHealthInfo, type PersonaHitlActionRequest, type PersonaInterrupt, type PersonaMemoryAgentGroup, type PersonaMemoryFile, type PersonaMemoryList, type PersonaMessage, type PersonaPresentedFile, PersonaProvider, type PersonaProviderProps, type PersonaResumeValue, type PersonaRole, type PersonaStreamingEvent, type PersonaSubagentActivityEntry, type PersonaThread, type PersonaTodo, type PersonaToolCall, type PersonaWorkspaceFile, type SendMessageOverride, type UseChatOptions, VERSION, useAgents, useChat, useConnection, useFiles, useMemory, usePersonaContext, useThreads };
|
|
420
|
+
export { type PersonaAgentSummary, type PersonaClarificationQuestion, type PersonaFileItem, type PersonaHealthInfo, type PersonaHitlActionRequest, type PersonaInterrupt, type PersonaMcpConnection, type PersonaMemoryAgentGroup, type PersonaMemoryFile, type PersonaMemoryList, type PersonaMessage, type PersonaPresentedFile, PersonaProvider, type PersonaProviderProps, type PersonaResumeValue, type PersonaRole, type PersonaStreamingEvent, type PersonaSubagentActivityEntry, type PersonaThread, type PersonaTodo, type PersonaToolCall, type PersonaWorkspaceFile, type SendMessageOverride, type UseChatOptions, type UseMcpConnectionsOptions, VERSION, useAgents, useChat, useConnection, useFiles, useMcpConnections, useMemory, usePersonaContext, useThreads };
|
package/dist/index.js
CHANGED
|
@@ -202,6 +202,7 @@ function useChat(options = {}) {
|
|
|
202
202
|
role: m.role === "assistant" ? "assistant" : "user",
|
|
203
203
|
content: m.content
|
|
204
204
|
}));
|
|
205
|
+
const resolvedThreadId = await (overrideOptions?.threadId ?? options.threadId);
|
|
205
206
|
const response = await fetchWithAuth("/chat", {
|
|
206
207
|
method: "POST",
|
|
207
208
|
headers: {
|
|
@@ -210,7 +211,7 @@ function useChat(options = {}) {
|
|
|
210
211
|
body: JSON.stringify({
|
|
211
212
|
agentId: targetAgentId,
|
|
212
213
|
messages: payloadMessages,
|
|
213
|
-
threadId:
|
|
214
|
+
threadId: resolvedThreadId,
|
|
214
215
|
resume: overrideOptions?.resume
|
|
215
216
|
}),
|
|
216
217
|
signal: controller.signal
|
|
@@ -793,8 +794,51 @@ function useConnection(autoCheck = true) {
|
|
|
793
794
|
};
|
|
794
795
|
}
|
|
795
796
|
|
|
797
|
+
// src/hooks/useMcpConnections.ts
|
|
798
|
+
import { useCallback as useCallback7, useEffect as useEffect7, useState as useState7 } from "react";
|
|
799
|
+
function useMcpConnections(options = {}) {
|
|
800
|
+
const { defaultAgentId, fetchWithAuth } = usePersonaContext();
|
|
801
|
+
const agentId = options.agentId ?? defaultAgentId;
|
|
802
|
+
const autoFetch = options.autoFetch ?? true;
|
|
803
|
+
const [connections, setConnections] = useState7([]);
|
|
804
|
+
const [isLoading, setIsLoading] = useState7(false);
|
|
805
|
+
const [error, setError] = useState7(null);
|
|
806
|
+
const fetchConnections = useCallback7(async () => {
|
|
807
|
+
if (!agentId) return [];
|
|
808
|
+
setIsLoading(true);
|
|
809
|
+
setError(null);
|
|
810
|
+
try {
|
|
811
|
+
const returnTo = options.returnTo ?? (typeof window !== "undefined" ? window.location.href : void 0);
|
|
812
|
+
const query = returnTo ? `?returnTo=${encodeURIComponent(returnTo)}` : "";
|
|
813
|
+
const res = await fetchWithAuth(`/agents/${agentId}/mcp-connections${query}`);
|
|
814
|
+
if (!res.ok) throw new Error(`Failed to load MCP connections: ${res.statusText}`);
|
|
815
|
+
const data = await res.json();
|
|
816
|
+
const items = Array.isArray(data) ? data : data?.items || [];
|
|
817
|
+
setConnections(items);
|
|
818
|
+
return items;
|
|
819
|
+
} catch (err) {
|
|
820
|
+
const errorObj = err instanceof Error ? err : new Error(String(err));
|
|
821
|
+
setError(errorObj);
|
|
822
|
+
return [];
|
|
823
|
+
} finally {
|
|
824
|
+
setIsLoading(false);
|
|
825
|
+
}
|
|
826
|
+
}, [agentId, fetchWithAuth, options.returnTo]);
|
|
827
|
+
useEffect7(() => {
|
|
828
|
+
if (autoFetch) void fetchConnections();
|
|
829
|
+
}, [autoFetch, fetchConnections]);
|
|
830
|
+
return {
|
|
831
|
+
connections,
|
|
832
|
+
/** Convenience filter for the common "show a banner for what's missing" case. */
|
|
833
|
+
unconnected: connections.filter((c) => !c.connected),
|
|
834
|
+
isLoading,
|
|
835
|
+
error,
|
|
836
|
+
refetch: fetchConnections
|
|
837
|
+
};
|
|
838
|
+
}
|
|
839
|
+
|
|
796
840
|
// src/index.ts
|
|
797
|
-
var VERSION = "0.3.
|
|
841
|
+
var VERSION = "0.3.4";
|
|
798
842
|
export {
|
|
799
843
|
PersonaProvider,
|
|
800
844
|
VERSION,
|
|
@@ -802,6 +846,7 @@ export {
|
|
|
802
846
|
useChat,
|
|
803
847
|
useConnection,
|
|
804
848
|
useFiles,
|
|
849
|
+
useMcpConnections,
|
|
805
850
|
useMemory,
|
|
806
851
|
usePersonaContext,
|
|
807
852
|
useThreads
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/context/PersonaContext.tsx","../src/hooks/useChat.ts","../src/hooks/useMemory.ts","../src/hooks/useThreads.ts","../src/hooks/useFiles.ts","../src/hooks/useAgents.ts","../src/hooks/useConnection.ts","../src/index.ts"],"sourcesContent":["'use client';\n\nimport React, { createContext, useContext, useMemo } from 'react';\nimport type { PersonaProviderProps } from '../types.js';\n\ninterface PersonaContextValue {\n baseUrl: string;\n getAuthToken?: () => Promise<string | null | undefined> | string | null | undefined;\n defaultAgentId?: string;\n fetchWithAuth: (path: string, init?: RequestInit) => Promise<Response>;\n}\n\nconst PersonaContext = createContext<PersonaContextValue | null>(null);\n\nexport function PersonaProvider({\n baseUrl,\n getAuthToken,\n defaultAgentId,\n children,\n}: PersonaProviderProps) {\n const normalizedBaseUrl = useMemo(() => baseUrl.replace(/\\/+$/, ''), [baseUrl]);\n\n const value = useMemo<PersonaContextValue>(() => {\n async function fetchWithAuth(path: string, init: RequestInit = {}): Promise<Response> {\n const token = getAuthToken ? await getAuthToken() : null;\n const headers = new Headers(init.headers || {});\n if (token) {\n headers.set('Authorization', `Bearer ${token}`);\n }\n\n const cleanPath = path.startsWith('/') ? path : `/${path}`;\n const url = `${normalizedBaseUrl}${cleanPath}`;\n\n return fetch(url, {\n ...init,\n headers,\n });\n }\n\n return {\n baseUrl: normalizedBaseUrl,\n getAuthToken,\n defaultAgentId,\n fetchWithAuth,\n };\n }, [normalizedBaseUrl, getAuthToken, defaultAgentId]);\n\n return <PersonaContext.Provider value={value}>{children}</PersonaContext.Provider>;\n}\n\nexport function usePersonaContext(): PersonaContextValue {\n const context = useContext(PersonaContext);\n if (!context) {\n throw new Error('usePersonaContext must be used within a <PersonaProvider>');\n }\n return context;\n}\n","'use client';\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { usePersonaContext } from '../context/PersonaContext.js';\nimport type {\n PersonaInterrupt,\n PersonaMessage,\n PersonaPresentedFile,\n PersonaResumeValue,\n PersonaStreamingEvent,\n PersonaSubagentActivityEntry,\n PersonaTodo,\n PersonaToolCall,\n PersonaWorkspaceFile,\n SendMessageOverride,\n UseChatOptions,\n} from '../types.js';\n\n// A failed tool call's TOOL_CALL_RESULT content is a JSON envelope\n// (`{status:'error',message}`, see aguiTranslator.js's buildToolErrorContent)\n// rather than a separate boolean field on the event itself.\nfunction isErrorToolContent(content: string): boolean {\n if (typeof content !== 'string' || !content.trim().startsWith('{')) return false;\n try {\n return JSON.parse(content)?.status === 'error';\n } catch {\n return false;\n }\n}\n\n// present_file's result is `{status:'success', filePath, title, description}`\n// (see present.tool.js) — a signal to highlight that path in the workspace\n// files panel, not something meant to render as a generic tool-result blob.\nfunction parsePresentedFile(content: string): PersonaPresentedFile | null {\n try {\n const parsed = JSON.parse(content);\n if (parsed?.status !== 'success' || typeof parsed.filePath !== 'string') return null;\n return {\n path: parsed.filePath,\n title: typeof parsed.title === 'string' ? parsed.title : parsed.filePath,\n description: typeof parsed.description === 'string' ? parsed.description : '',\n };\n } catch {\n return null;\n }\n}\n\n// buildFilesTodosSnapshot (aguiTranslator.js) emits snake_case\n// created_at/modified_at on the wire — both from the live STATE_SNAPSHOT\n// event and from a reloaded thread's persisted state (checkpoint.service.js\n// runs the same function). Normalize to the SDK's usual camelCase shape.\nfunction normalizeWorkspaceFiles(\n raw: Record<string, { content: string; size: number; created_at: string | null; modified_at: string | null }>\n): Record<string, PersonaWorkspaceFile> {\n const normalized: Record<string, PersonaWorkspaceFile> = {};\n for (const [path, file] of Object.entries(raw || {})) {\n normalized[path] = {\n content: file.content,\n size: file.size,\n createdAt: file.created_at,\n modifiedAt: file.modified_at,\n };\n }\n return normalized;\n}\n\n// checkpointService.getMessages() wraps a paused thread's interrupt as\n// `{ kind, value }` (see checkpoint.service.js) — the same envelope shape\n// the live hitl_request/clarification_request CUSTOM events carry, just\n// nested one level deeper. Flatten both into the same PersonaInterrupt shape.\nfunction normalizePendingInterrupt(pending: unknown): PersonaInterrupt | null {\n if (!pending || typeof pending !== 'object') return null;\n const p = pending as { kind?: string; value?: Record<string, unknown> };\n if (p.kind === 'hitl') {\n return {\n kind: 'hitl',\n actionRequests: (p.value?.actionRequests ?? []) as Extract<\n PersonaInterrupt,\n { kind: 'hitl' }\n >['actionRequests'],\n reviewConfigs: (p.value?.reviewConfigs ?? []) as unknown[],\n };\n }\n if (p.kind === 'clarification') {\n return {\n kind: 'clarification',\n questions: (p.value?.questions ?? []) as Extract<PersonaInterrupt, { kind: 'clarification' }>['questions'],\n };\n }\n return null;\n}\n\nexport function useChat(options: UseChatOptions = {}) {\n const { defaultAgentId, fetchWithAuth } = usePersonaContext();\n const agentId = options.agentId || defaultAgentId;\n const threadId = options.threadId;\n\n const [messages, setMessages] = useState<PersonaMessage[]>(options.initialMessages || []);\n const [input, setInput] = useState('');\n const [isStreaming, setIsStreaming] = useState(false);\n const [isLoadingHistory, setIsLoadingHistory] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const [interrupt, setInterrupt] = useState<PersonaInterrupt | null>(null);\n const [files, setFiles] = useState<Record<string, PersonaWorkspaceFile>>({});\n const [todos, setTodos] = useState<PersonaTodo[]>([]);\n const [presentedFile, setPresentedFile] = useState<PersonaPresentedFile | null>(null);\n\n const abortControllerRef = useRef<AbortController | null>(null);\n const loadedThreadIdRef = useRef<string | undefined>(undefined);\n\n const stop = useCallback(() => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n abortControllerRef.current = null;\n setIsStreaming(false);\n }\n }, []);\n\n const clear = useCallback(() => {\n stop();\n setMessages([]);\n setError(null);\n setInterrupt(null);\n setFiles({});\n setTodos([]);\n setPresentedFile(null);\n }, [stop]);\n\n const loadThreadMessages = useCallback(\n async (id: string) => {\n setIsLoadingHistory(true);\n setError(null);\n try {\n const res = await fetchWithAuth(`/threads/${id}/messages`);\n if (!res.ok) throw new Error(`Failed to load thread history: ${res.statusText}`);\n const body = await res.json();\n const data = body?.data ?? body;\n const raw = (data?.messages ?? []) as Array<{\n id?: string;\n role: PersonaMessage['role'];\n content: string;\n toolCalls?: PersonaToolCall[];\n }>;\n const loaded: PersonaMessage[] = raw.map((m, i) => ({\n id: m.id || `history-${id}-${i}`,\n role: m.role,\n content: m.content,\n createdAt: new Date(),\n toolCalls: m.toolCalls,\n }));\n setMessages(loaded);\n // Re-show the approval/clarification card on reload if this thread\n // is currently paused — otherwise it wouldn't reappear until the\n // next live stream re-surfaces it.\n setInterrupt(normalizePendingInterrupt(data?.pendingInterrupt));\n // Restore the workspace files/todos this thread already had (same\n // cleaned shape checkpoint.service.js now derives via\n // buildFilesTodosSnapshot, matching the live STATE_SNAPSHOT event).\n setFiles(normalizeWorkspaceFiles(data?.state?.files ?? {}));\n setTodos((data?.state?.todos ?? []) as PersonaTodo[]);\n return loaded;\n } catch (err) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n return [];\n } finally {\n setIsLoadingHistory(false);\n }\n },\n [fetchWithAuth]\n );\n\n // Auto-load history the first time a thread with no in-memory messages is\n // selected (switching threads in the sidebar). Skipped for a thread whose\n // messages already live in state — e.g. one just created by handleSend,\n // which sets its placeholder messages in the same render batch as the\n // threadId change, so `messages` there is never empty at effect time.\n useEffect(() => {\n if (!threadId || isStreaming) return;\n if (loadedThreadIdRef.current === threadId) return;\n if (messages.length > 0) return;\n loadedThreadIdRef.current = threadId;\n void loadThreadMessages(threadId);\n }, [threadId, isStreaming, messages.length, loadThreadMessages]);\n\n const sendMessage = useCallback(\n async (contentToSend?: string, overrideOptions?: SendMessageOverride) => {\n const prompt = (contentToSend ?? input).trim();\n if (!prompt || isStreaming) return;\n\n const targetAgentId = overrideOptions?.agentId || agentId;\n if (!targetAgentId) {\n const err = new Error('No Agent ID specified for useChat.');\n setError(err);\n options.onError?.(err);\n return;\n }\n\n const userMessage: PersonaMessage = {\n id: `user-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,\n role: 'user',\n content: prompt,\n createdAt: new Date(),\n };\n\n const assistantMessageId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;\n const placeholderAssistant: PersonaMessage = {\n id: assistantMessageId,\n role: 'assistant',\n content: '',\n createdAt: new Date(),\n isStreaming: true,\n toolCalls: [],\n };\n\n const nextMessages = [...messages, userMessage];\n setMessages([...nextMessages, placeholderAssistant]);\n setInput('');\n setIsStreaming(true);\n setError(null);\n setInterrupt(null);\n\n const controller = new AbortController();\n abortControllerRef.current = controller;\n\n try {\n const payloadMessages = nextMessages.map((m) => ({\n role: m.role === 'assistant' ? ('assistant' as const) : ('user' as const),\n content: m.content,\n }));\n\n const response = await fetchWithAuth('/chat', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n agentId: targetAgentId,\n messages: payloadMessages,\n threadId: overrideOptions?.threadId || options.threadId,\n resume: overrideOptions?.resume,\n }),\n signal: controller.signal,\n });\n\n if (!response.ok) {\n const errText = await response.text().catch(() => 'Stream failed');\n throw new Error(`Chat error (${response.status}): ${errText}`);\n }\n\n if (!response.body) {\n throw new Error('No response body received for streaming.');\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder('utf-8');\n let buffer = '';\n let accumulatedText = '';\n let accumulatedReasoning = '';\n const toolCallsMap = new Map<string, PersonaToolCall>();\n\n const patchAssistant = (patch: Partial<PersonaMessage>) => {\n setMessages((prev) =>\n prev.map((msg) =>\n msg.id === assistantMessageId\n ? { ...msg, toolCalls: Array.from(toolCallsMap.values()), ...patch }\n : msg\n )\n );\n };\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed || !trimmed.startsWith('data:')) continue;\n\n const raw = trimmed.replace(/^data:\\s*/, '');\n if (raw === '[DONE]') break;\n\n try {\n const event = JSON.parse(raw) as PersonaStreamingEvent;\n options.onEvent?.(event);\n\n if (event.type === 'TEXT_MESSAGE_CHUNK' && event.delta) {\n accumulatedText += event.delta;\n patchAssistant({ content: accumulatedText, isStreaming: true });\n } else if (event.type === 'TOOL_CALL_CHUNK' && event.toolCallId) {\n // The backend streams tool calls as accumulating chunks\n // (id/name arrive on the first chunk, args stream in pieces\n // across subsequent ones) rather than separate start/args\n // events.\n const existing = toolCallsMap.get(event.toolCallId);\n if (existing) {\n existing.args = (existing.args || '') + (event.delta || '');\n } else {\n toolCallsMap.set(event.toolCallId, {\n toolCallId: event.toolCallId,\n toolName: event.toolCallName || '',\n args: event.delta || '',\n });\n }\n patchAssistant({});\n } else if (event.type === 'TOOL_CALL_RESULT') {\n const existing = toolCallsMap.get(event.toolCallId);\n if (existing) {\n existing.result = event.content;\n existing.isError = isErrorToolContent(event.content);\n if (existing.toolName === 'present_file' && !existing.isError) {\n const presented = parsePresentedFile(event.content);\n if (presented) setPresentedFile(presented);\n }\n patchAssistant({});\n }\n } else if (event.type === 'STATE_SNAPSHOT') {\n setFiles(normalizeWorkspaceFiles(event.snapshot.files));\n setTodos(event.snapshot.todos);\n } else if (event.type === 'REASONING_MESSAGE_CONTENT') {\n accumulatedReasoning += event.delta;\n patchAssistant({ reasoning: accumulatedReasoning, isReasoning: true });\n } else if (event.type === 'REASONING_END') {\n patchAssistant({ isReasoning: false });\n } else if (event.type === 'CUSTOM') {\n if (event.name === 'hitl_request') {\n const value = event.value as Extract<PersonaInterrupt, { kind: 'hitl' }>;\n setInterrupt({\n kind: 'hitl',\n actionRequests: value.actionRequests,\n reviewConfigs: value.reviewConfigs,\n });\n } else if (event.name === 'clarification_request') {\n const value = event.value as Extract<PersonaInterrupt, { kind: 'clarification' }>;\n setInterrupt({ kind: 'clarification', questions: value.questions });\n } else if (event.name === 'subagent_activity') {\n const { toolCallId, ...entry } = event.value as { toolCallId: string } & PersonaSubagentActivityEntry;\n const existing = toolCallsMap.get(toolCallId);\n if (existing) {\n existing.subagentActivity = [...(existing.subagentActivity || []), entry];\n patchAssistant({});\n }\n }\n // 'mcp_app' custom events carry no chat-transcript UI here —\n // consumers that render MCP widgets read them via onEvent.\n } else if (event.type === 'RUN_ERROR') {\n throw new Error(event.message || 'Stream error from agent');\n }\n } catch (e) {\n if (e instanceof Error && e.message.startsWith('Stream error')) {\n throw e;\n }\n }\n }\n }\n\n const finalMessage: PersonaMessage = {\n id: assistantMessageId,\n role: 'assistant',\n content: accumulatedText,\n createdAt: new Date(),\n isStreaming: false,\n toolCalls: Array.from(toolCallsMap.values()),\n ...(accumulatedReasoning ? { reasoning: accumulatedReasoning, isReasoning: false } : {}),\n };\n\n setMessages((prev) =>\n prev.map((msg) => (msg.id === assistantMessageId ? finalMessage : msg))\n );\n\n options.onFinish?.(finalMessage);\n } catch (err) {\n if (controller.signal.aborted) {\n setMessages((prev) =>\n prev.map((msg) =>\n msg.id === assistantMessageId ? { ...msg, isStreaming: false } : msg\n )\n );\n return;\n }\n\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n options.onError?.(errorObj);\n\n setMessages((prev) =>\n prev.map((msg) =>\n msg.id === assistantMessageId\n ? {\n ...msg,\n content:\n msg.content || `⚠️ Error: ${errorObj.message || 'Failed to get response.'}`,\n isStreaming: false,\n }\n : msg\n )\n );\n } finally {\n setIsStreaming(false);\n abortControllerRef.current = null;\n }\n },\n [agentId, fetchWithAuth, input, isStreaming, messages, options]\n );\n\n const handleInputChange = useCallback((e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {\n setInput(e.target.value);\n }, []);\n\n const handleSubmit = useCallback(\n (e?: React.FormEvent) => {\n if (e) e.preventDefault();\n void sendMessage();\n },\n [sendMessage]\n );\n\n const reload = useCallback(() => {\n if (messages.length === 0 || isStreaming) return;\n let lastUserIndex = -1;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role === 'user') {\n lastUserIndex = i;\n break;\n }\n }\n if (lastUserIndex === -1) return;\n\n const lastUserMessage = messages[lastUserIndex];\n setMessages(messages.slice(0, lastUserIndex));\n void sendMessage(lastUserMessage.content);\n }, [isStreaming, messages, sendMessage]);\n\n // Unpauses a paused HITL/clarification run. `displayContent` becomes the\n // visible user-turn bubble (e.g. \"Approved\", or the typed clarification\n // answer) — the server resolves the actual resume value from `resume`\n // itself, `displayContent` is only ever used for its own transcript text.\n const resumeInterrupt = useCallback(\n (resume: PersonaResumeValue, displayContent: string) => sendMessage(displayContent, { resume }),\n [sendMessage]\n );\n\n const dismissPresentedFile = useCallback(() => setPresentedFile(null), []);\n\n // Manually re-open a workspace file — e.g. a present_file tool card's\n // \"Open\" button, after the auto-opened drawer was closed or a different\n // file was selected since.\n const openWorkspaceFile = useCallback(\n (path: string) => setPresentedFile({ path, title: path.split('/').pop() || path, description: '' }),\n []\n );\n\n return {\n messages,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n sendMessage,\n isStreaming,\n isLoading: isStreaming,\n isLoadingHistory,\n error,\n interrupt,\n resumeInterrupt,\n files,\n todos,\n presentedFile,\n dismissPresentedFile,\n openWorkspaceFile,\n stop,\n reload,\n clear,\n setMessages,\n loadThreadMessages,\n };\n}\n","'use client';\n\nimport { useCallback, useEffect, useState } from 'react';\nimport { usePersonaContext } from '../context/PersonaContext.js';\nimport type { PersonaMemoryFile, PersonaMemoryList } from '../types.js';\n\nexport function useMemory(autoFetch = true) {\n const { fetchWithAuth } = usePersonaContext();\n const [memory, setMemory] = useState<PersonaMemoryList>({ userFiles: [], agentMemories: [] });\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n\n const fetchMemory = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n try {\n const res = await fetchWithAuth('/memory');\n if (!res.ok) {\n throw new Error(`Failed to fetch memory: ${res.statusText}`);\n }\n const data = (await res.json()) as PersonaMemoryList;\n setMemory(data);\n return data;\n } catch (err) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n return { userFiles: [], agentMemories: [] };\n } finally {\n setIsLoading(false);\n }\n }, [fetchWithAuth]);\n\n const getFile = useCallback(\n async (params: { path: string; scope?: 'user' | 'agent'; agentId?: string }) => {\n const query = new URLSearchParams({ path: params.path });\n if (params.scope) query.set('scope', params.scope);\n if (params.agentId) query.set('agentId', params.agentId);\n\n const res = await fetchWithAuth(`/memory/file?${query.toString()}`);\n if (!res.ok) throw new Error(`Failed to get memory file: ${res.statusText}`);\n return (await res.json()) as PersonaMemoryFile;\n },\n [fetchWithAuth]\n );\n\n const writeFile = useCallback(\n async (params: { path: string; content: string; scope?: 'user' | 'agent'; agentId?: string }) => {\n const res = await fetchWithAuth('/memory/file', {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(params),\n });\n if (!res.ok) throw new Error(`Failed to write memory file: ${res.statusText}`);\n const updated = (await res.json()) as PersonaMemoryFile;\n void fetchMemory();\n return updated;\n },\n [fetchWithAuth, fetchMemory]\n );\n\n const deleteFile = useCallback(\n async (params: { path: string; scope?: 'user' | 'agent'; agentId?: string }) => {\n const query = new URLSearchParams({ path: params.path });\n if (params.scope) query.set('scope', params.scope);\n if (params.agentId) query.set('agentId', params.agentId);\n\n const res = await fetchWithAuth(`/memory/file?${query.toString()}`, {\n method: 'DELETE',\n });\n if (!res.ok) throw new Error(`Failed to delete memory file: ${res.statusText}`);\n void fetchMemory();\n },\n [fetchWithAuth, fetchMemory]\n );\n\n useEffect(() => {\n if (autoFetch) {\n void fetchMemory();\n }\n }, [autoFetch, fetchMemory]);\n\n return {\n memory,\n isLoading,\n error,\n refetch: fetchMemory,\n getFile,\n writeFile,\n deleteFile,\n };\n}\n","'use client';\n\nimport { useCallback, useEffect, useState } from 'react';\nimport { usePersonaContext } from '../context/PersonaContext.js';\nimport type { PersonaThread } from '../types.js';\n\nexport function useThreads(autoFetch = true) {\n const { fetchWithAuth, defaultAgentId } = usePersonaContext();\n const [threads, setThreads] = useState<PersonaThread[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n\n const fetchThreads = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n try {\n const res = await fetchWithAuth('/threads');\n if (!res.ok) throw new Error(`Failed to list threads: ${res.statusText}`);\n const data = await res.json();\n // Real shape is { items, pagination }. Bare array / `.data` / `.threads`\n // are defensive fallbacks for other deployments, not the actual contract.\n const items: PersonaThread[] = Array.isArray(data)\n ? data\n : data?.items || data?.threads || (Array.isArray(data?.data) ? data.data : undefined) || [];\n setThreads(items);\n return items;\n } catch (err) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n return [];\n } finally {\n setIsLoading(false);\n }\n }, [fetchWithAuth]);\n\n const createThread = useCallback(\n async (agentId?: string) => {\n const targetAgentId = agentId || defaultAgentId;\n const res = await fetchWithAuth('/threads', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ agentId: targetAgentId }),\n });\n if (!res.ok) throw new Error(`Failed to create thread: ${res.statusText}`);\n const data = await res.json();\n const created = (data?.data ?? data) as PersonaThread;\n void fetchThreads();\n return created;\n },\n [fetchWithAuth, defaultAgentId, fetchThreads]\n );\n\n const deleteThread = useCallback(\n async (threadId: string) => {\n const res = await fetchWithAuth(`/threads/${threadId}`, { method: 'DELETE' });\n if (!res.ok) throw new Error(`Failed to delete thread: ${res.statusText}`);\n setThreads((prev) => prev.filter((t) => t._id !== threadId));\n },\n [fetchWithAuth]\n );\n\n // Best-effort batch delete — no not-found id aborts the rest. Up to 100\n // ids per call, matching the server's own limit.\n const bulkDeleteThreads = useCallback(\n async (threadIds: string[]) => {\n const res = await fetchWithAuth('/threads/bulk-delete', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ ids: threadIds }),\n });\n if (!res.ok) throw new Error(`Failed to bulk-delete threads: ${res.statusText}`);\n const data = await res.json();\n const result = (data?.data ?? data) as { deleted: string[]; failed: Array<{ id: string; reason: string }> };\n const deletedSet = new Set(result.deleted);\n setThreads((prev) => prev.filter((t) => !deletedSet.has(t._id)));\n return result;\n },\n [fetchWithAuth]\n );\n\n // Convenience wrapper: there is no server-side \"delete everything\"\n // endpoint, only bulk-delete-by-id — so this bulk-deletes every\n // currently-loaded thread (up to 100 per call, chunked if there are more).\n const deleteAllThreads = useCallback(async () => {\n const ids = threads.map((t) => t._id);\n for (let i = 0; i < ids.length; i += 100) {\n await bulkDeleteThreads(ids.slice(i, i + 100));\n }\n }, [threads, bulkDeleteThreads]);\n\n // General-purpose update — { title?, isArchived? }.\n const updateThread = useCallback(\n async (threadId: string, input: { title?: string; isArchived?: boolean }) => {\n const res = await fetchWithAuth(`/threads/${threadId}`, {\n method: 'PATCH',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(input),\n });\n if (!res.ok) throw new Error(`Failed to update thread: ${res.statusText}`);\n const data = await res.json();\n const updated = (data?.data ?? data) as PersonaThread;\n setThreads((prev) => prev.map((t) => (t._id === threadId ? { ...t, ...updated } : t)));\n return updated;\n },\n [fetchWithAuth]\n );\n\n const renameThread = useCallback(\n (threadId: string, title: string) => updateThread(threadId, { title }),\n [updateThread]\n );\n\n const getThread = useCallback(\n async (threadId: string) => {\n const res = await fetchWithAuth(`/threads/${threadId}`);\n if (!res.ok) throw new Error(`Failed to fetch thread: ${res.statusText}`);\n const data = await res.json();\n return (data?.data ?? data) as PersonaThread;\n },\n [fetchWithAuth]\n );\n\n useEffect(() => {\n if (autoFetch) {\n void fetchThreads();\n }\n }, [autoFetch, fetchThreads]);\n\n return {\n threads,\n isLoading,\n error,\n refetch: fetchThreads,\n createThread,\n deleteThread,\n bulkDeleteThreads,\n deleteAllThreads,\n updateThread,\n renameThread,\n getThread,\n };\n}\n","'use client';\n\nimport { useCallback, useEffect, useState } from 'react';\nimport { usePersonaContext } from '../context/PersonaContext.js';\nimport type { PersonaFileItem } from '../types.js';\n\nexport type { PersonaFileItem };\n\nexport function useFiles(autoFetch = true) {\n const { fetchWithAuth } = usePersonaContext();\n const [files, setFiles] = useState<PersonaFileItem[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [isUploading, setIsUploading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n\n const fetchFiles = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n try {\n const res = await fetchWithAuth('/files');\n if (!res.ok) throw new Error(`Failed to list files: ${res.statusText}`);\n const data = await res.json();\n // Real shape is { items, pagination } — bare array/`.files` are\n // defensive fallbacks, not the actual wire contract.\n const items: PersonaFileItem[] = Array.isArray(data)\n ? data\n : data?.items || data?.files || [];\n setFiles(items);\n return items;\n } catch (err) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n return [];\n } finally {\n setIsLoading(false);\n }\n }, [fetchWithAuth]);\n\n const uploadFile = useCallback(\n async (fileOrFormData: FormData | { name: string; uri: string; type?: string }) => {\n setIsUploading(true);\n setError(null);\n try {\n let body: FormData;\n if (fileOrFormData instanceof FormData) {\n body = fileOrFormData;\n } else {\n // React Native FormData support\n body = new FormData();\n body.append('file', fileOrFormData as unknown as Blob);\n }\n\n const res = await fetchWithAuth('/files', {\n method: 'POST',\n body,\n });\n\n if (!res.ok) {\n const errText = await res.text().catch(() => 'Upload failed');\n throw new Error(`Upload error (${res.status}): ${errText}`);\n }\n\n const uploaded = (await res.json()) as PersonaFileItem;\n void fetchFiles();\n return uploaded;\n } catch (err) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n throw errorObj;\n } finally {\n setIsUploading(false);\n }\n },\n [fetchWithAuth, fetchFiles]\n );\n\n const deleteFile = useCallback(\n async (fileId: string) => {\n const res = await fetchWithAuth(`/files/${fileId}`, { method: 'DELETE' });\n if (!res.ok) throw new Error(`Failed to delete file: ${res.statusText}`);\n setFiles((prev) => prev.filter((f) => f.id !== fileId));\n },\n [fetchWithAuth]\n );\n\n const bulkDeleteFiles = useCallback(\n async (fileIds: string[]) => {\n const res = await fetchWithAuth('/files/bulk-delete', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ ids: fileIds }),\n });\n if (!res.ok) throw new Error(`Failed to bulk-delete files: ${res.statusText}`);\n const idSet = new Set(fileIds);\n setFiles((prev) => prev.filter((f) => !idSet.has(f.id)));\n return (await res.json()) as { deleted: string[]; failed: Array<{ id: string; reason: string }> };\n },\n [fetchWithAuth]\n );\n\n const getDownloadUrl = useCallback(\n (fileId: string) => {\n return `/files/${fileId}`;\n },\n []\n );\n\n useEffect(() => {\n if (autoFetch) {\n void fetchFiles();\n }\n }, [autoFetch, fetchFiles]);\n\n return {\n files,\n isLoading,\n isUploading,\n error,\n refetch: fetchFiles,\n uploadFile,\n deleteFile,\n bulkDeleteFiles,\n getDownloadUrl,\n };\n}\n","'use client';\n\nimport { useCallback, useEffect, useState } from 'react';\nimport { usePersonaContext } from '../context/PersonaContext.js';\n\nexport interface PersonaAgentSummary {\n _id: string;\n name: string;\n slug: string;\n description?: string;\n tagline?: string;\n avatar?: string;\n}\n\nexport function useAgents(autoFetch = true) {\n const { fetchWithAuth } = usePersonaContext();\n const [agents, setAgents] = useState<PersonaAgentSummary[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n\n const fetchAgents = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n try {\n const res = await fetchWithAuth('/agents');\n if (!res.ok) throw new Error(`Failed to list agents: ${res.statusText}`);\n const data = await res.json();\n // Real shape is { items, pagination }.\n const items: PersonaAgentSummary[] = Array.isArray(data)\n ? data\n : data?.items || data?.agents || [];\n setAgents(items);\n return items;\n } catch (err) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n return [];\n } finally {\n setIsLoading(false);\n }\n }, [fetchWithAuth]);\n\n useEffect(() => {\n if (autoFetch) {\n void fetchAgents();\n }\n }, [autoFetch, fetchAgents]);\n\n return {\n agents,\n isLoading,\n error,\n refetch: fetchAgents,\n };\n}\n","'use client';\n\nimport { useCallback, useEffect, useState } from 'react';\nimport { usePersonaContext } from '../context/PersonaContext.js';\n\nexport interface PersonaHealthInfo {\n status: string;\n version?: string;\n capabilities?: Record<string, boolean>;\n}\n\nexport function useConnection(autoCheck = true) {\n const { fetchWithAuth } = usePersonaContext();\n const [health, setHealth] = useState<PersonaHealthInfo | null>(null);\n const [isConnected, setIsConnected] = useState(false);\n const [isLoading, setIsLoading] = useState(false);\n\n const checkHealth = useCallback(async () => {\n setIsLoading(true);\n try {\n const res = await fetchWithAuth('/health');\n if (res.ok) {\n const data = (await res.json()) as PersonaHealthInfo;\n setHealth(data);\n setIsConnected(true);\n return data;\n }\n setIsConnected(false);\n return null;\n } catch {\n setIsConnected(false);\n return null;\n } finally {\n setIsLoading(false);\n }\n }, [fetchWithAuth]);\n\n useEffect(() => {\n if (autoCheck) {\n void checkHealth();\n }\n }, [autoCheck, checkHealth]);\n\n return {\n isConnected,\n health,\n isLoading,\n checkHealth,\n };\n}\n","export * from './types.js';\nexport * from './context/PersonaContext.js';\nexport * from './hooks/useChat.js';\nexport * from './hooks/useMemory.js';\nexport * from './hooks/useThreads.js';\nexport * from './hooks/useFiles.js';\nexport * from './hooks/useAgents.js';\nexport * from './hooks/useConnection.js';\n\nexport const VERSION = '0.3.2';\n"],"mappings":";AAEA,SAAgB,eAAe,YAAY,eAAe;AA6CjD;AAnCT,IAAM,iBAAiB,cAA0C,IAAI;AAE9D,SAAS,gBAAgB;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAyB;AACvB,QAAM,oBAAoB,QAAQ,MAAM,QAAQ,QAAQ,QAAQ,EAAE,GAAG,CAAC,OAAO,CAAC;AAE9E,QA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E3B,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA,SAAS;AAAA,EACX;AACF;;;ACpDA,SAAS,eAAAC,cAAa,aAAAC,YAAW,YAAAC,iBAAgB;AAS1C,SAAS,cAAc,YAAY,MAAM;AAC9C,QAAM,EAAE,cAAc,IAAI,kBAAkB;AAC5C,QAAM,CAAC,QAAQ,SAAS,IAAIC,UAAmC,IAAI;AACnE,QAAM,CAAC,aAAa,cAAc,IAAIA,UAAS,KAAK;AACpD,QAAM,CAAC,WAAW,YAAY,IAAIA,UAAS,KAAK;AAEhD,QAAM,cAAcC,aAAY,YAAY;AAC1C,iBAAa,IAAI;AACjB,QAAI;AACF,YAAM,MAAM,MAAM,cAAc,SAAS;AACzC,UAAI,IAAI,IAAI;AACV,cAAM,OAAQ,MAAM,IAAI,KAAK;AAC7B,kBAAU,IAAI;AACd,uBAAe,IAAI;AACnB,eAAO;AAAA,MACT;AACA,qBAAe,KAAK;AACpB,aAAO;AAAA,IACT,QAAQ;AACN,qBAAe,KAAK;AACpB,aAAO;AAAA,IACT,UAAE;AACA,mBAAa,KAAK;AAAA,IACpB;AAAA,EACF,GAAG,CAAC,aAAa,CAAC;AAElB,EAAAC,WAAU,MAAM;AACd,QAAI,WAAW;AACb,WAAK,YAAY;AAAA,IACnB;AAAA,EACF,GAAG,CAAC,WAAW,WAAW,CAAC;AAE3B,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;;;ACxCO,IAAM,UAAU;","names":["value","useCallback","useEffect","useState","useState","useCallback","useEffect","useCallback","useEffect","useState","useState","useCallback","useEffect","useCallback","useEffect","useState","useState","useCallback","useEffect","useCallback","useEffect","useState","useState","useCallback","useEffect","useCallback","useEffect","useState","useState","useCallback","useEffect"]}
|
|
1
|
+
{"version":3,"sources":["../src/context/PersonaContext.tsx","../src/hooks/useChat.ts","../src/hooks/useMemory.ts","../src/hooks/useThreads.ts","../src/hooks/useFiles.ts","../src/hooks/useAgents.ts","../src/hooks/useConnection.ts","../src/hooks/useMcpConnections.ts","../src/index.ts"],"sourcesContent":["'use client';\n\nimport React, { createContext, useContext, useMemo } from 'react';\nimport type { PersonaProviderProps } from '../types.js';\n\ninterface PersonaContextValue {\n baseUrl: string;\n getAuthToken?: () => Promise<string | null | undefined> | string | null | undefined;\n defaultAgentId?: string;\n fetchWithAuth: (path: string, init?: RequestInit) => Promise<Response>;\n}\n\nconst PersonaContext = createContext<PersonaContextValue | null>(null);\n\nexport function PersonaProvider({\n baseUrl,\n getAuthToken,\n defaultAgentId,\n children,\n}: PersonaProviderProps) {\n const normalizedBaseUrl = useMemo(() => baseUrl.replace(/\\/+$/, ''), [baseUrl]);\n\n const value = useMemo<PersonaContextValue>(() => {\n async function fetchWithAuth(path: string, init: RequestInit = {}): Promise<Response> {\n const token = getAuthToken ? await getAuthToken() : null;\n const headers = new Headers(init.headers || {});\n if (token) {\n headers.set('Authorization', `Bearer ${token}`);\n }\n\n const cleanPath = path.startsWith('/') ? path : `/${path}`;\n const url = `${normalizedBaseUrl}${cleanPath}`;\n\n return fetch(url, {\n ...init,\n headers,\n });\n }\n\n return {\n baseUrl: normalizedBaseUrl,\n getAuthToken,\n defaultAgentId,\n fetchWithAuth,\n };\n }, [normalizedBaseUrl, getAuthToken, defaultAgentId]);\n\n return <PersonaContext.Provider value={value}>{children}</PersonaContext.Provider>;\n}\n\nexport function usePersonaContext(): PersonaContextValue {\n const context = useContext(PersonaContext);\n if (!context) {\n throw new Error('usePersonaContext must be used within a <PersonaProvider>');\n }\n return context;\n}\n","'use client';\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { usePersonaContext } from '../context/PersonaContext.js';\nimport type {\n PersonaInterrupt,\n PersonaMessage,\n PersonaPresentedFile,\n PersonaResumeValue,\n PersonaStreamingEvent,\n PersonaSubagentActivityEntry,\n PersonaTodo,\n PersonaToolCall,\n PersonaWorkspaceFile,\n SendMessageOverride,\n UseChatOptions,\n} from '../types.js';\n\n// A failed tool call's TOOL_CALL_RESULT content is a JSON envelope\n// (`{status:'error',message}`, see aguiTranslator.js's buildToolErrorContent)\n// rather than a separate boolean field on the event itself.\nfunction isErrorToolContent(content: string): boolean {\n if (typeof content !== 'string' || !content.trim().startsWith('{')) return false;\n try {\n return JSON.parse(content)?.status === 'error';\n } catch {\n return false;\n }\n}\n\n// present_file's result is `{status:'success', filePath, title, description}`\n// (see present.tool.js) — a signal to highlight that path in the workspace\n// files panel, not something meant to render as a generic tool-result blob.\nfunction parsePresentedFile(content: string): PersonaPresentedFile | null {\n try {\n const parsed = JSON.parse(content);\n if (parsed?.status !== 'success' || typeof parsed.filePath !== 'string') return null;\n return {\n path: parsed.filePath,\n title: typeof parsed.title === 'string' ? parsed.title : parsed.filePath,\n description: typeof parsed.description === 'string' ? parsed.description : '',\n };\n } catch {\n return null;\n }\n}\n\n// buildFilesTodosSnapshot (aguiTranslator.js) emits snake_case\n// created_at/modified_at on the wire — both from the live STATE_SNAPSHOT\n// event and from a reloaded thread's persisted state (checkpoint.service.js\n// runs the same function). Normalize to the SDK's usual camelCase shape.\nfunction normalizeWorkspaceFiles(\n raw: Record<string, { content: string; size: number; created_at: string | null; modified_at: string | null }>\n): Record<string, PersonaWorkspaceFile> {\n const normalized: Record<string, PersonaWorkspaceFile> = {};\n for (const [path, file] of Object.entries(raw || {})) {\n normalized[path] = {\n content: file.content,\n size: file.size,\n createdAt: file.created_at,\n modifiedAt: file.modified_at,\n };\n }\n return normalized;\n}\n\n// checkpointService.getMessages() wraps a paused thread's interrupt as\n// `{ kind, value }` (see checkpoint.service.js) — the same envelope shape\n// the live hitl_request/clarification_request CUSTOM events carry, just\n// nested one level deeper. Flatten both into the same PersonaInterrupt shape.\nfunction normalizePendingInterrupt(pending: unknown): PersonaInterrupt | null {\n if (!pending || typeof pending !== 'object') return null;\n const p = pending as { kind?: string; value?: Record<string, unknown> };\n if (p.kind === 'hitl') {\n return {\n kind: 'hitl',\n actionRequests: (p.value?.actionRequests ?? []) as Extract<\n PersonaInterrupt,\n { kind: 'hitl' }\n >['actionRequests'],\n reviewConfigs: (p.value?.reviewConfigs ?? []) as unknown[],\n };\n }\n if (p.kind === 'clarification') {\n return {\n kind: 'clarification',\n questions: (p.value?.questions ?? []) as Extract<PersonaInterrupt, { kind: 'clarification' }>['questions'],\n };\n }\n return null;\n}\n\nexport function useChat(options: UseChatOptions = {}) {\n const { defaultAgentId, fetchWithAuth } = usePersonaContext();\n const agentId = options.agentId || defaultAgentId;\n const threadId = options.threadId;\n\n const [messages, setMessages] = useState<PersonaMessage[]>(options.initialMessages || []);\n const [input, setInput] = useState('');\n const [isStreaming, setIsStreaming] = useState(false);\n const [isLoadingHistory, setIsLoadingHistory] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n const [interrupt, setInterrupt] = useState<PersonaInterrupt | null>(null);\n const [files, setFiles] = useState<Record<string, PersonaWorkspaceFile>>({});\n const [todos, setTodos] = useState<PersonaTodo[]>([]);\n const [presentedFile, setPresentedFile] = useState<PersonaPresentedFile | null>(null);\n\n const abortControllerRef = useRef<AbortController | null>(null);\n const loadedThreadIdRef = useRef<string | undefined>(undefined);\n\n const stop = useCallback(() => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n abortControllerRef.current = null;\n setIsStreaming(false);\n }\n }, []);\n\n const clear = useCallback(() => {\n stop();\n setMessages([]);\n setError(null);\n setInterrupt(null);\n setFiles({});\n setTodos([]);\n setPresentedFile(null);\n }, [stop]);\n\n const loadThreadMessages = useCallback(\n async (id: string) => {\n setIsLoadingHistory(true);\n setError(null);\n try {\n const res = await fetchWithAuth(`/threads/${id}/messages`);\n if (!res.ok) throw new Error(`Failed to load thread history: ${res.statusText}`);\n const body = await res.json();\n const data = body?.data ?? body;\n const raw = (data?.messages ?? []) as Array<{\n id?: string;\n role: PersonaMessage['role'];\n content: string;\n toolCalls?: PersonaToolCall[];\n }>;\n const loaded: PersonaMessage[] = raw.map((m, i) => ({\n id: m.id || `history-${id}-${i}`,\n role: m.role,\n content: m.content,\n createdAt: new Date(),\n toolCalls: m.toolCalls,\n }));\n setMessages(loaded);\n // Re-show the approval/clarification card on reload if this thread\n // is currently paused — otherwise it wouldn't reappear until the\n // next live stream re-surfaces it.\n setInterrupt(normalizePendingInterrupt(data?.pendingInterrupt));\n // Restore the workspace files/todos this thread already had (same\n // cleaned shape checkpoint.service.js now derives via\n // buildFilesTodosSnapshot, matching the live STATE_SNAPSHOT event).\n setFiles(normalizeWorkspaceFiles(data?.state?.files ?? {}));\n setTodos((data?.state?.todos ?? []) as PersonaTodo[]);\n return loaded;\n } catch (err) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n return [];\n } finally {\n setIsLoadingHistory(false);\n }\n },\n [fetchWithAuth]\n );\n\n // Auto-load history the first time a thread with no in-memory messages is\n // selected (switching threads in the sidebar). Skipped for a thread whose\n // messages already live in state — e.g. one just created by handleSend,\n // which sets its placeholder messages in the same render batch as the\n // threadId change, so `messages` there is never empty at effect time.\n useEffect(() => {\n if (!threadId || isStreaming) return;\n if (loadedThreadIdRef.current === threadId) return;\n if (messages.length > 0) return;\n loadedThreadIdRef.current = threadId;\n void loadThreadMessages(threadId);\n }, [threadId, isStreaming, messages.length, loadThreadMessages]);\n\n const sendMessage = useCallback(\n async (contentToSend?: string, overrideOptions?: SendMessageOverride) => {\n const prompt = (contentToSend ?? input).trim();\n if (!prompt || isStreaming) return;\n\n const targetAgentId = overrideOptions?.agentId || agentId;\n if (!targetAgentId) {\n const err = new Error('No Agent ID specified for useChat.');\n setError(err);\n options.onError?.(err);\n return;\n }\n\n const userMessage: PersonaMessage = {\n id: `user-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,\n role: 'user',\n content: prompt,\n createdAt: new Date(),\n };\n\n const assistantMessageId = `assistant-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;\n const placeholderAssistant: PersonaMessage = {\n id: assistantMessageId,\n role: 'assistant',\n content: '',\n createdAt: new Date(),\n isStreaming: true,\n toolCalls: [],\n };\n\n const nextMessages = [...messages, userMessage];\n setMessages([...nextMessages, placeholderAssistant]);\n setInput('');\n setIsStreaming(true);\n setError(null);\n setInterrupt(null);\n\n const controller = new AbortController();\n abortControllerRef.current = controller;\n\n try {\n const payloadMessages = nextMessages.map((m) => ({\n role: m.role === 'assistant' ? ('assistant' as const) : ('user' as const),\n content: m.content,\n }));\n\n // Resolved here, not earlier — everything above this line (the\n // optimistic message + placeholder, clearing input, etc.) already\n // ran synchronously, so a caller passing an in-flight thread-creation\n // promise gets an instant UI update without the message send itself\n // waiting on it any longer than the network call already would.\n const resolvedThreadId = await (overrideOptions?.threadId ?? options.threadId);\n\n const response = await fetchWithAuth('/chat', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n agentId: targetAgentId,\n messages: payloadMessages,\n threadId: resolvedThreadId,\n resume: overrideOptions?.resume,\n }),\n signal: controller.signal,\n });\n\n if (!response.ok) {\n const errText = await response.text().catch(() => 'Stream failed');\n throw new Error(`Chat error (${response.status}): ${errText}`);\n }\n\n if (!response.body) {\n throw new Error('No response body received for streaming.');\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder('utf-8');\n let buffer = '';\n let accumulatedText = '';\n let accumulatedReasoning = '';\n const toolCallsMap = new Map<string, PersonaToolCall>();\n\n const patchAssistant = (patch: Partial<PersonaMessage>) => {\n setMessages((prev) =>\n prev.map((msg) =>\n msg.id === assistantMessageId\n ? { ...msg, toolCalls: Array.from(toolCallsMap.values()), ...patch }\n : msg\n )\n );\n };\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed || !trimmed.startsWith('data:')) continue;\n\n const raw = trimmed.replace(/^data:\\s*/, '');\n if (raw === '[DONE]') break;\n\n try {\n const event = JSON.parse(raw) as PersonaStreamingEvent;\n options.onEvent?.(event);\n\n if (event.type === 'TEXT_MESSAGE_CHUNK' && event.delta) {\n accumulatedText += event.delta;\n patchAssistant({ content: accumulatedText, isStreaming: true });\n } else if (event.type === 'TOOL_CALL_CHUNK' && event.toolCallId) {\n // The backend streams tool calls as accumulating chunks\n // (id/name arrive on the first chunk, args stream in pieces\n // across subsequent ones) rather than separate start/args\n // events.\n const existing = toolCallsMap.get(event.toolCallId);\n if (existing) {\n existing.args = (existing.args || '') + (event.delta || '');\n } else {\n toolCallsMap.set(event.toolCallId, {\n toolCallId: event.toolCallId,\n toolName: event.toolCallName || '',\n args: event.delta || '',\n });\n }\n patchAssistant({});\n } else if (event.type === 'TOOL_CALL_RESULT') {\n const existing = toolCallsMap.get(event.toolCallId);\n if (existing) {\n existing.result = event.content;\n existing.isError = isErrorToolContent(event.content);\n if (existing.toolName === 'present_file' && !existing.isError) {\n const presented = parsePresentedFile(event.content);\n if (presented) setPresentedFile(presented);\n }\n patchAssistant({});\n }\n } else if (event.type === 'STATE_SNAPSHOT') {\n setFiles(normalizeWorkspaceFiles(event.snapshot.files));\n setTodos(event.snapshot.todos);\n } else if (event.type === 'REASONING_MESSAGE_CONTENT') {\n accumulatedReasoning += event.delta;\n patchAssistant({ reasoning: accumulatedReasoning, isReasoning: true });\n } else if (event.type === 'REASONING_END') {\n patchAssistant({ isReasoning: false });\n } else if (event.type === 'CUSTOM') {\n if (event.name === 'hitl_request') {\n const value = event.value as Extract<PersonaInterrupt, { kind: 'hitl' }>;\n setInterrupt({\n kind: 'hitl',\n actionRequests: value.actionRequests,\n reviewConfigs: value.reviewConfigs,\n });\n } else if (event.name === 'clarification_request') {\n const value = event.value as Extract<PersonaInterrupt, { kind: 'clarification' }>;\n setInterrupt({ kind: 'clarification', questions: value.questions });\n } else if (event.name === 'subagent_activity') {\n const { toolCallId, ...entry } = event.value as { toolCallId: string } & PersonaSubagentActivityEntry;\n const existing = toolCallsMap.get(toolCallId);\n if (existing) {\n existing.subagentActivity = [...(existing.subagentActivity || []), entry];\n patchAssistant({});\n }\n }\n // 'mcp_app' custom events carry no chat-transcript UI here —\n // consumers that render MCP widgets read them via onEvent.\n } else if (event.type === 'RUN_ERROR') {\n throw new Error(event.message || 'Stream error from agent');\n }\n } catch (e) {\n if (e instanceof Error && e.message.startsWith('Stream error')) {\n throw e;\n }\n }\n }\n }\n\n const finalMessage: PersonaMessage = {\n id: assistantMessageId,\n role: 'assistant',\n content: accumulatedText,\n createdAt: new Date(),\n isStreaming: false,\n toolCalls: Array.from(toolCallsMap.values()),\n ...(accumulatedReasoning ? { reasoning: accumulatedReasoning, isReasoning: false } : {}),\n };\n\n setMessages((prev) =>\n prev.map((msg) => (msg.id === assistantMessageId ? finalMessage : msg))\n );\n\n options.onFinish?.(finalMessage);\n } catch (err) {\n if (controller.signal.aborted) {\n setMessages((prev) =>\n prev.map((msg) =>\n msg.id === assistantMessageId ? { ...msg, isStreaming: false } : msg\n )\n );\n return;\n }\n\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n options.onError?.(errorObj);\n\n setMessages((prev) =>\n prev.map((msg) =>\n msg.id === assistantMessageId\n ? {\n ...msg,\n content:\n msg.content || `⚠️ Error: ${errorObj.message || 'Failed to get response.'}`,\n isStreaming: false,\n }\n : msg\n )\n );\n } finally {\n setIsStreaming(false);\n abortControllerRef.current = null;\n }\n },\n [agentId, fetchWithAuth, input, isStreaming, messages, options]\n );\n\n const handleInputChange = useCallback((e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {\n setInput(e.target.value);\n }, []);\n\n const handleSubmit = useCallback(\n (e?: React.FormEvent) => {\n if (e) e.preventDefault();\n void sendMessage();\n },\n [sendMessage]\n );\n\n const reload = useCallback(() => {\n if (messages.length === 0 || isStreaming) return;\n let lastUserIndex = -1;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role === 'user') {\n lastUserIndex = i;\n break;\n }\n }\n if (lastUserIndex === -1) return;\n\n const lastUserMessage = messages[lastUserIndex];\n setMessages(messages.slice(0, lastUserIndex));\n void sendMessage(lastUserMessage.content);\n }, [isStreaming, messages, sendMessage]);\n\n // Unpauses a paused HITL/clarification run. `displayContent` becomes the\n // visible user-turn bubble (e.g. \"Approved\", or the typed clarification\n // answer) — the server resolves the actual resume value from `resume`\n // itself, `displayContent` is only ever used for its own transcript text.\n const resumeInterrupt = useCallback(\n (resume: PersonaResumeValue, displayContent: string) => sendMessage(displayContent, { resume }),\n [sendMessage]\n );\n\n const dismissPresentedFile = useCallback(() => setPresentedFile(null), []);\n\n // Manually re-open a workspace file — e.g. a present_file tool card's\n // \"Open\" button, after the auto-opened drawer was closed or a different\n // file was selected since.\n const openWorkspaceFile = useCallback(\n (path: string) => setPresentedFile({ path, title: path.split('/').pop() || path, description: '' }),\n []\n );\n\n return {\n messages,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n sendMessage,\n isStreaming,\n isLoading: isStreaming,\n isLoadingHistory,\n error,\n interrupt,\n resumeInterrupt,\n files,\n todos,\n presentedFile,\n dismissPresentedFile,\n openWorkspaceFile,\n stop,\n reload,\n clear,\n setMessages,\n loadThreadMessages,\n };\n}\n","'use client';\n\nimport { useCallback, useEffect, useState } from 'react';\nimport { usePersonaContext } from '../context/PersonaContext.js';\nimport type { PersonaMemoryFile, PersonaMemoryList } from '../types.js';\n\nexport function useMemory(autoFetch = true) {\n const { fetchWithAuth } = usePersonaContext();\n const [memory, setMemory] = useState<PersonaMemoryList>({ userFiles: [], agentMemories: [] });\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n\n const fetchMemory = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n try {\n const res = await fetchWithAuth('/memory');\n if (!res.ok) {\n throw new Error(`Failed to fetch memory: ${res.statusText}`);\n }\n const data = (await res.json()) as PersonaMemoryList;\n setMemory(data);\n return data;\n } catch (err) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n return { userFiles: [], agentMemories: [] };\n } finally {\n setIsLoading(false);\n }\n }, [fetchWithAuth]);\n\n const getFile = useCallback(\n async (params: { path: string; scope?: 'user' | 'agent'; agentId?: string }) => {\n const query = new URLSearchParams({ path: params.path });\n if (params.scope) query.set('scope', params.scope);\n if (params.agentId) query.set('agentId', params.agentId);\n\n const res = await fetchWithAuth(`/memory/file?${query.toString()}`);\n if (!res.ok) throw new Error(`Failed to get memory file: ${res.statusText}`);\n return (await res.json()) as PersonaMemoryFile;\n },\n [fetchWithAuth]\n );\n\n const writeFile = useCallback(\n async (params: { path: string; content: string; scope?: 'user' | 'agent'; agentId?: string }) => {\n const res = await fetchWithAuth('/memory/file', {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(params),\n });\n if (!res.ok) throw new Error(`Failed to write memory file: ${res.statusText}`);\n const updated = (await res.json()) as PersonaMemoryFile;\n void fetchMemory();\n return updated;\n },\n [fetchWithAuth, fetchMemory]\n );\n\n const deleteFile = useCallback(\n async (params: { path: string; scope?: 'user' | 'agent'; agentId?: string }) => {\n const query = new URLSearchParams({ path: params.path });\n if (params.scope) query.set('scope', params.scope);\n if (params.agentId) query.set('agentId', params.agentId);\n\n const res = await fetchWithAuth(`/memory/file?${query.toString()}`, {\n method: 'DELETE',\n });\n if (!res.ok) throw new Error(`Failed to delete memory file: ${res.statusText}`);\n void fetchMemory();\n },\n [fetchWithAuth, fetchMemory]\n );\n\n useEffect(() => {\n if (autoFetch) {\n void fetchMemory();\n }\n }, [autoFetch, fetchMemory]);\n\n return {\n memory,\n isLoading,\n error,\n refetch: fetchMemory,\n getFile,\n writeFile,\n deleteFile,\n };\n}\n","'use client';\n\nimport { useCallback, useEffect, useState } from 'react';\nimport { usePersonaContext } from '../context/PersonaContext.js';\nimport type { PersonaThread } from '../types.js';\n\nexport function useThreads(autoFetch = true) {\n const { fetchWithAuth, defaultAgentId } = usePersonaContext();\n const [threads, setThreads] = useState<PersonaThread[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n\n const fetchThreads = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n try {\n const res = await fetchWithAuth('/threads');\n if (!res.ok) throw new Error(`Failed to list threads: ${res.statusText}`);\n const data = await res.json();\n // Real shape is { items, pagination }. Bare array / `.data` / `.threads`\n // are defensive fallbacks for other deployments, not the actual contract.\n const items: PersonaThread[] = Array.isArray(data)\n ? data\n : data?.items || data?.threads || (Array.isArray(data?.data) ? data.data : undefined) || [];\n setThreads(items);\n return items;\n } catch (err) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n return [];\n } finally {\n setIsLoading(false);\n }\n }, [fetchWithAuth]);\n\n const createThread = useCallback(\n async (agentId?: string) => {\n const targetAgentId = agentId || defaultAgentId;\n const res = await fetchWithAuth('/threads', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ agentId: targetAgentId }),\n });\n if (!res.ok) throw new Error(`Failed to create thread: ${res.statusText}`);\n const data = await res.json();\n const created = (data?.data ?? data) as PersonaThread;\n void fetchThreads();\n return created;\n },\n [fetchWithAuth, defaultAgentId, fetchThreads]\n );\n\n const deleteThread = useCallback(\n async (threadId: string) => {\n const res = await fetchWithAuth(`/threads/${threadId}`, { method: 'DELETE' });\n if (!res.ok) throw new Error(`Failed to delete thread: ${res.statusText}`);\n setThreads((prev) => prev.filter((t) => t._id !== threadId));\n },\n [fetchWithAuth]\n );\n\n // Best-effort batch delete — no not-found id aborts the rest. Up to 100\n // ids per call, matching the server's own limit.\n const bulkDeleteThreads = useCallback(\n async (threadIds: string[]) => {\n const res = await fetchWithAuth('/threads/bulk-delete', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ ids: threadIds }),\n });\n if (!res.ok) throw new Error(`Failed to bulk-delete threads: ${res.statusText}`);\n const data = await res.json();\n const result = (data?.data ?? data) as { deleted: string[]; failed: Array<{ id: string; reason: string }> };\n const deletedSet = new Set(result.deleted);\n setThreads((prev) => prev.filter((t) => !deletedSet.has(t._id)));\n return result;\n },\n [fetchWithAuth]\n );\n\n // Convenience wrapper: there is no server-side \"delete everything\"\n // endpoint, only bulk-delete-by-id — so this bulk-deletes every\n // currently-loaded thread (up to 100 per call, chunked if there are more).\n const deleteAllThreads = useCallback(async () => {\n const ids = threads.map((t) => t._id);\n for (let i = 0; i < ids.length; i += 100) {\n await bulkDeleteThreads(ids.slice(i, i + 100));\n }\n }, [threads, bulkDeleteThreads]);\n\n // General-purpose update — { title?, isArchived? }.\n const updateThread = useCallback(\n async (threadId: string, input: { title?: string; isArchived?: boolean }) => {\n const res = await fetchWithAuth(`/threads/${threadId}`, {\n method: 'PATCH',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(input),\n });\n if (!res.ok) throw new Error(`Failed to update thread: ${res.statusText}`);\n const data = await res.json();\n const updated = (data?.data ?? data) as PersonaThread;\n setThreads((prev) => prev.map((t) => (t._id === threadId ? { ...t, ...updated } : t)));\n return updated;\n },\n [fetchWithAuth]\n );\n\n const renameThread = useCallback(\n (threadId: string, title: string) => updateThread(threadId, { title }),\n [updateThread]\n );\n\n const getThread = useCallback(\n async (threadId: string) => {\n const res = await fetchWithAuth(`/threads/${threadId}`);\n if (!res.ok) throw new Error(`Failed to fetch thread: ${res.statusText}`);\n const data = await res.json();\n return (data?.data ?? data) as PersonaThread;\n },\n [fetchWithAuth]\n );\n\n useEffect(() => {\n if (autoFetch) {\n void fetchThreads();\n }\n }, [autoFetch, fetchThreads]);\n\n return {\n threads,\n isLoading,\n error,\n refetch: fetchThreads,\n createThread,\n deleteThread,\n bulkDeleteThreads,\n deleteAllThreads,\n updateThread,\n renameThread,\n getThread,\n };\n}\n","'use client';\n\nimport { useCallback, useEffect, useState } from 'react';\nimport { usePersonaContext } from '../context/PersonaContext.js';\nimport type { PersonaFileItem } from '../types.js';\n\nexport type { PersonaFileItem };\n\nexport function useFiles(autoFetch = true) {\n const { fetchWithAuth } = usePersonaContext();\n const [files, setFiles] = useState<PersonaFileItem[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [isUploading, setIsUploading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n\n const fetchFiles = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n try {\n const res = await fetchWithAuth('/files');\n if (!res.ok) throw new Error(`Failed to list files: ${res.statusText}`);\n const data = await res.json();\n // Real shape is { items, pagination } — bare array/`.files` are\n // defensive fallbacks, not the actual wire contract.\n const items: PersonaFileItem[] = Array.isArray(data)\n ? data\n : data?.items || data?.files || [];\n setFiles(items);\n return items;\n } catch (err) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n return [];\n } finally {\n setIsLoading(false);\n }\n }, [fetchWithAuth]);\n\n const uploadFile = useCallback(\n async (fileOrFormData: FormData | { name: string; uri: string; type?: string }) => {\n setIsUploading(true);\n setError(null);\n try {\n let body: FormData;\n if (fileOrFormData instanceof FormData) {\n body = fileOrFormData;\n } else {\n // React Native FormData support\n body = new FormData();\n body.append('file', fileOrFormData as unknown as Blob);\n }\n\n const res = await fetchWithAuth('/files', {\n method: 'POST',\n body,\n });\n\n if (!res.ok) {\n const errText = await res.text().catch(() => 'Upload failed');\n throw new Error(`Upload error (${res.status}): ${errText}`);\n }\n\n const uploaded = (await res.json()) as PersonaFileItem;\n void fetchFiles();\n return uploaded;\n } catch (err) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n throw errorObj;\n } finally {\n setIsUploading(false);\n }\n },\n [fetchWithAuth, fetchFiles]\n );\n\n const deleteFile = useCallback(\n async (fileId: string) => {\n const res = await fetchWithAuth(`/files/${fileId}`, { method: 'DELETE' });\n if (!res.ok) throw new Error(`Failed to delete file: ${res.statusText}`);\n setFiles((prev) => prev.filter((f) => f.id !== fileId));\n },\n [fetchWithAuth]\n );\n\n const bulkDeleteFiles = useCallback(\n async (fileIds: string[]) => {\n const res = await fetchWithAuth('/files/bulk-delete', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ ids: fileIds }),\n });\n if (!res.ok) throw new Error(`Failed to bulk-delete files: ${res.statusText}`);\n const idSet = new Set(fileIds);\n setFiles((prev) => prev.filter((f) => !idSet.has(f.id)));\n return (await res.json()) as { deleted: string[]; failed: Array<{ id: string; reason: string }> };\n },\n [fetchWithAuth]\n );\n\n const getDownloadUrl = useCallback(\n (fileId: string) => {\n return `/files/${fileId}`;\n },\n []\n );\n\n useEffect(() => {\n if (autoFetch) {\n void fetchFiles();\n }\n }, [autoFetch, fetchFiles]);\n\n return {\n files,\n isLoading,\n isUploading,\n error,\n refetch: fetchFiles,\n uploadFile,\n deleteFile,\n bulkDeleteFiles,\n getDownloadUrl,\n };\n}\n","'use client';\n\nimport { useCallback, useEffect, useState } from 'react';\nimport { usePersonaContext } from '../context/PersonaContext.js';\n\nexport interface PersonaAgentSummary {\n _id: string;\n name: string;\n slug: string;\n description?: string;\n tagline?: string;\n avatar?: string;\n}\n\nexport function useAgents(autoFetch = true) {\n const { fetchWithAuth } = usePersonaContext();\n const [agents, setAgents] = useState<PersonaAgentSummary[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n\n const fetchAgents = useCallback(async () => {\n setIsLoading(true);\n setError(null);\n try {\n const res = await fetchWithAuth('/agents');\n if (!res.ok) throw new Error(`Failed to list agents: ${res.statusText}`);\n const data = await res.json();\n // Real shape is { items, pagination }.\n const items: PersonaAgentSummary[] = Array.isArray(data)\n ? data\n : data?.items || data?.agents || [];\n setAgents(items);\n return items;\n } catch (err) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n return [];\n } finally {\n setIsLoading(false);\n }\n }, [fetchWithAuth]);\n\n useEffect(() => {\n if (autoFetch) {\n void fetchAgents();\n }\n }, [autoFetch, fetchAgents]);\n\n return {\n agents,\n isLoading,\n error,\n refetch: fetchAgents,\n };\n}\n","'use client';\n\nimport { useCallback, useEffect, useState } from 'react';\nimport { usePersonaContext } from '../context/PersonaContext.js';\n\nexport interface PersonaHealthInfo {\n status: string;\n version?: string;\n capabilities?: Record<string, boolean>;\n}\n\nexport function useConnection(autoCheck = true) {\n const { fetchWithAuth } = usePersonaContext();\n const [health, setHealth] = useState<PersonaHealthInfo | null>(null);\n const [isConnected, setIsConnected] = useState(false);\n const [isLoading, setIsLoading] = useState(false);\n\n const checkHealth = useCallback(async () => {\n setIsLoading(true);\n try {\n const res = await fetchWithAuth('/health');\n if (res.ok) {\n const data = (await res.json()) as PersonaHealthInfo;\n setHealth(data);\n setIsConnected(true);\n return data;\n }\n setIsConnected(false);\n return null;\n } catch {\n setIsConnected(false);\n return null;\n } finally {\n setIsLoading(false);\n }\n }, [fetchWithAuth]);\n\n useEffect(() => {\n if (autoCheck) {\n void checkHealth();\n }\n }, [autoCheck, checkHealth]);\n\n return {\n isConnected,\n health,\n isLoading,\n checkHealth,\n };\n}\n","'use client';\n\nimport { useCallback, useEffect, useState } from 'react';\nimport { usePersonaContext } from '../context/PersonaContext.js';\n\n/**\n * One `authType: 'oauth', authMode: 'user'` MCP an Agent has attached, and\n * whether the current end user has connected it yet. `authorizeUrl` is only\n * present when `connected` is `false` — navigate the browser there (a\n * same-tab redirect is fine; it's a real OAuth authorization URL) to start\n * the consent flow.\n */\nexport interface PersonaMcpConnection {\n mcpId: string;\n name: string;\n description: string;\n connected: boolean;\n authorizeUrl: string | null;\n}\n\nexport interface UseMcpConnectionsOptions {\n /** @default the PersonaProvider's defaultAgentId */\n agentId?: string;\n /** Where the browser lands after OAuth consent completes. @default window.location.href */\n returnTo?: string;\n /** @default true */\n autoFetch?: boolean;\n}\n\n/**\n * Surfaces the gap that used to be invisible entirely: a user-mode MCP tool\n * call for a user who hasn't connected yet is silently dropped from the\n * Agent's toolset server-side, with no signal in the chat stream at all.\n * Check this before (or alongside) a chat session to show a real \"Connect\n * your account\" affordance instead of a capability that just quietly isn't\n * there.\n */\nexport function useMcpConnections(options: UseMcpConnectionsOptions = {}) {\n const { defaultAgentId, fetchWithAuth } = usePersonaContext();\n const agentId = options.agentId ?? defaultAgentId;\n const autoFetch = options.autoFetch ?? true;\n\n const [connections, setConnections] = useState<PersonaMcpConnection[]>([]);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n\n const fetchConnections = useCallback(async () => {\n if (!agentId) return [];\n setIsLoading(true);\n setError(null);\n try {\n const returnTo =\n options.returnTo ?? (typeof window !== 'undefined' ? window.location.href : undefined);\n const query = returnTo ? `?returnTo=${encodeURIComponent(returnTo)}` : '';\n const res = await fetchWithAuth(`/agents/${agentId}/mcp-connections${query}`);\n if (!res.ok) throw new Error(`Failed to load MCP connections: ${res.statusText}`);\n const data = await res.json();\n const items: PersonaMcpConnection[] = Array.isArray(data) ? data : data?.items || [];\n setConnections(items);\n return items;\n } catch (err) {\n const errorObj = err instanceof Error ? err : new Error(String(err));\n setError(errorObj);\n return [];\n } finally {\n setIsLoading(false);\n }\n }, [agentId, fetchWithAuth, options.returnTo]);\n\n useEffect(() => {\n if (autoFetch) void fetchConnections();\n }, [autoFetch, fetchConnections]);\n\n return {\n connections,\n /** Convenience filter for the common \"show a banner for what's missing\" case. */\n unconnected: connections.filter((c) => !c.connected),\n isLoading,\n error,\n refetch: fetchConnections,\n };\n}\n","export * from './types.js';\nexport * from './context/PersonaContext.js';\nexport * from './hooks/useChat.js';\nexport * from './hooks/useMemory.js';\nexport * from './hooks/useThreads.js';\nexport * from './hooks/useFiles.js';\nexport * from './hooks/useAgents.js';\nexport * from './hooks/useConnection.js';\nexport * from './hooks/useMcpConnections.js';\n\nexport const VERSION = '0.3.4';\n"],"mappings":";AAEA,SAAgB,eAAe,YAAY,eAAe;AA6CjD;AAnCT,IAAM,iBAAiB,cAA0C,IAAI;AAE9D,SAAS,gBAAgB;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAyB;AACvB,QAAM,oBAAoB,QAAQ,MAAM,QAAQ,QAAQ,QAAQ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C,UAAiC,CAAC,CAAC;AACzE,QAAM,CAAC,WAAW,YAAY,IAAIA,UAAS,KAAK;AAChD,QAAM,CAAC,OAAO,QAAQ,IAAIA,UAAuB,IAAI;AAErD,QAAM,mBAAmBC,aAAY,YAAY;AAC/C,QAAI,CAAC,QAAS,QAAO,CAAC;AACtB,iBAAa,IAAI;AACjB,aAAS,IAAI;AACb,QAAI;AACF,YAAM,WACJ,QAAQ,aAAa,OAAO,WAAW,cAAc,OAAO,SAAS,OAAO;AAC9E,YAAM,QAAQ,WAAW,aAAa,mBAAmB,QAAQ,CAAC,KAAK;AACvE,YAAM,MAAM,MAAM,cAAc,WAAW,OAAO,mBAAmB,KAAK,EAAE;AAC5E,UAAI,CAAC,IAAI,GAAI,OAAM,IAAI,MAAM,mCAAmC,IAAI,UAAU,EAAE;AAChF,YAAM,OAAO,MAAM,IAAI,KAAK;AAC5B,YAAM,QAAgC,MAAM,QAAQ,IAAI,IAAI,OAAO,MAAM,SAAS,CAAC;AACnF,qBAAe,KAAK;AACpB,aAAO;AAAA,IACT,SAAS,KAAK;AACZ,YAAM,WAAW,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC;AACnE,eAAS,QAAQ;AACjB,aAAO,CAAC;AAAA,IACV,UAAE;AACA,mBAAa,KAAK;AAAA,IACpB;AAAA,EACF,GAAG,CAAC,SAAS,eAAe,QAAQ,QAAQ,CAAC;AAE7C,EAAAC,WAAU,MAAM;AACd,QAAI,UAAW,MAAK,iBAAiB;AAAA,EACvC,GAAG,CAAC,WAAW,gBAAgB,CAAC;AAEhC,SAAO;AAAA,IACL;AAAA;AAAA,IAEA,aAAa,YAAY,OAAO,CAAC,MAAM,CAAC,EAAE,SAAS;AAAA,IACnD;AAAA,IACA;AAAA,IACA,SAAS;AAAA,EACX;AACF;;;ACvEO,IAAM,UAAU;","names":["value","useCallback","useEffect","useState","useState","useCallback","useEffect","useCallback","useEffect","useState","useState","useCallback","useEffect","useCallback","useEffect","useState","useState","useCallback","useEffect","useCallback","useEffect","useState","useState","useCallback","useEffect","useCallback","useEffect","useState","useState","useCallback","useEffect","useCallback","useEffect","useState","useState","useCallback","useEffect"]}
|