@personaai/react 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -97,6 +97,18 @@ function parsePresentedFile(content) {
97
97
  return null;
98
98
  }
99
99
  }
100
+ function normalizeWorkspaceFiles(raw) {
101
+ const normalized = {};
102
+ for (const [path, file] of Object.entries(raw || {})) {
103
+ normalized[path] = {
104
+ content: file.content,
105
+ size: file.size,
106
+ createdAt: file.created_at,
107
+ modifiedAt: file.modified_at
108
+ };
109
+ }
110
+ return normalized;
111
+ }
100
112
  function normalizePendingInterrupt(pending) {
101
113
  if (!pending || typeof pending !== "object") return null;
102
114
  const p = pending;
@@ -165,7 +177,7 @@ function useChat(options = {}) {
165
177
  }));
166
178
  setMessages(loaded);
167
179
  setInterrupt(normalizePendingInterrupt(data?.pendingInterrupt));
168
- setFiles(data?.state?.files ?? {});
180
+ setFiles(normalizeWorkspaceFiles(data?.state?.files ?? {}));
169
181
  setTodos(data?.state?.todos ?? []);
170
182
  return loaded;
171
183
  } catch (err) {
@@ -298,7 +310,7 @@ function useChat(options = {}) {
298
310
  patchAssistant({});
299
311
  }
300
312
  } else if (event.type === "STATE_SNAPSHOT") {
301
- setFiles(event.snapshot.files);
313
+ setFiles(normalizeWorkspaceFiles(event.snapshot.files));
302
314
  setTodos(event.snapshot.todos);
303
315
  } else if (event.type === "REASONING_MESSAGE_CONTENT") {
304
316
  accumulatedReasoning += event.delta;
@@ -404,6 +416,10 @@ function useChat(options = {}) {
404
416
  [sendMessage]
405
417
  );
406
418
  const dismissPresentedFile = (0, import_react2.useCallback)(() => setPresentedFile(null), []);
419
+ const openWorkspaceFile = (0, import_react2.useCallback)(
420
+ (path) => setPresentedFile({ path, title: path.split("/").pop() || path, description: "" }),
421
+ []
422
+ );
407
423
  return {
408
424
  messages,
409
425
  input,
@@ -421,6 +437,7 @@ function useChat(options = {}) {
421
437
  todos,
422
438
  presentedFile,
423
439
  dismissPresentedFile,
440
+ openWorkspaceFile,
424
441
  stop,
425
442
  reload,
426
443
  clear,
@@ -811,7 +828,7 @@ function useConnection(autoCheck = true) {
811
828
  }
812
829
 
813
830
  // src/index.ts
814
- var VERSION = "0.2.0";
831
+ var VERSION = "0.3.2";
815
832
  // Annotate the CommonJS export names for ESM import in node:
816
833
  0 && (module.exports = {
817
834
  PersonaProvider,
@@ -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.2.0';\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// 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((data?.state?.files ?? {}) as Record<string, PersonaWorkspaceFile>);\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(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 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 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;A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AAElB,+BAAU,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,SAAS;AAAA,EACX;AACF;;;ACpDA,IAAAC,gBAAiD;AAS1C,SAAS,cAAc,YAAY,MAAM;AAC9C,QAAM,EAAE,cAAc,IAAI,kBAAkB;AAC5C,QAAM,CAAC,QAAQ,SAAS,QAAI,wBAAmC,IAAI;AACnE,QAAM,CAAC,aAAa,cAAc,QAAI,wBAAS,KAAK;AACpD,QAAM,CAAC,WAAW,YAAY,QAAI,wBAAS,KAAK;AAEhD,QAAM,kBAAc,2BAAY,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,+BAAU,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;;;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"],"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,KAA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;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,+BAAU,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;;;APxCO,IAAM,UAAU;","names":["import_react","value","import_react","import_react","import_react","import_react","import_react"]}
package/dist/index.d.cts CHANGED
@@ -172,8 +172,14 @@ type PersonaStreamingEvent = {
172
172
  type: 'REASONING_END';
173
173
  } | {
174
174
  type: 'STATE_SNAPSHOT';
175
+ /** Raw wire shape (snake_case timestamps) — useChat normalizes this into `files`/`todos`. */
175
176
  snapshot: {
176
- files: Record<string, PersonaWorkspaceFile>;
177
+ files: Record<string, {
178
+ content: string;
179
+ size: number;
180
+ created_at: string | null;
181
+ modified_at: string | null;
182
+ }>;
177
183
  todos: PersonaTodo[];
178
184
  };
179
185
  } | {
@@ -257,6 +263,7 @@ declare function useChat(options?: UseChatOptions): {
257
263
  todos: PersonaTodo[];
258
264
  presentedFile: PersonaPresentedFile | null;
259
265
  dismissPresentedFile: () => void;
266
+ openWorkspaceFile: (path: string) => void;
260
267
  stop: () => void;
261
268
  reload: () => void;
262
269
  clear: () => void;
@@ -359,6 +366,6 @@ declare function useConnection(autoCheck?: boolean): {
359
366
  checkHealth: () => Promise<PersonaHealthInfo | null>;
360
367
  };
361
368
 
362
- declare const VERSION = "0.2.0";
369
+ declare const VERSION = "0.3.2";
363
370
 
364
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 };
package/dist/index.d.ts CHANGED
@@ -172,8 +172,14 @@ type PersonaStreamingEvent = {
172
172
  type: 'REASONING_END';
173
173
  } | {
174
174
  type: 'STATE_SNAPSHOT';
175
+ /** Raw wire shape (snake_case timestamps) — useChat normalizes this into `files`/`todos`. */
175
176
  snapshot: {
176
- files: Record<string, PersonaWorkspaceFile>;
177
+ files: Record<string, {
178
+ content: string;
179
+ size: number;
180
+ created_at: string | null;
181
+ modified_at: string | null;
182
+ }>;
177
183
  todos: PersonaTodo[];
178
184
  };
179
185
  } | {
@@ -257,6 +263,7 @@ declare function useChat(options?: UseChatOptions): {
257
263
  todos: PersonaTodo[];
258
264
  presentedFile: PersonaPresentedFile | null;
259
265
  dismissPresentedFile: () => void;
266
+ openWorkspaceFile: (path: string) => void;
260
267
  stop: () => void;
261
268
  reload: () => void;
262
269
  clear: () => void;
@@ -359,6 +366,6 @@ declare function useConnection(autoCheck?: boolean): {
359
366
  checkHealth: () => Promise<PersonaHealthInfo | null>;
360
367
  };
361
368
 
362
- declare const VERSION = "0.2.0";
369
+ declare const VERSION = "0.3.2";
363
370
 
364
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 };
package/dist/index.js CHANGED
@@ -63,6 +63,18 @@ function parsePresentedFile(content) {
63
63
  return null;
64
64
  }
65
65
  }
66
+ function normalizeWorkspaceFiles(raw) {
67
+ const normalized = {};
68
+ for (const [path, file] of Object.entries(raw || {})) {
69
+ normalized[path] = {
70
+ content: file.content,
71
+ size: file.size,
72
+ createdAt: file.created_at,
73
+ modifiedAt: file.modified_at
74
+ };
75
+ }
76
+ return normalized;
77
+ }
66
78
  function normalizePendingInterrupt(pending) {
67
79
  if (!pending || typeof pending !== "object") return null;
68
80
  const p = pending;
@@ -131,7 +143,7 @@ function useChat(options = {}) {
131
143
  }));
132
144
  setMessages(loaded);
133
145
  setInterrupt(normalizePendingInterrupt(data?.pendingInterrupt));
134
- setFiles(data?.state?.files ?? {});
146
+ setFiles(normalizeWorkspaceFiles(data?.state?.files ?? {}));
135
147
  setTodos(data?.state?.todos ?? []);
136
148
  return loaded;
137
149
  } catch (err) {
@@ -264,7 +276,7 @@ function useChat(options = {}) {
264
276
  patchAssistant({});
265
277
  }
266
278
  } else if (event.type === "STATE_SNAPSHOT") {
267
- setFiles(event.snapshot.files);
279
+ setFiles(normalizeWorkspaceFiles(event.snapshot.files));
268
280
  setTodos(event.snapshot.todos);
269
281
  } else if (event.type === "REASONING_MESSAGE_CONTENT") {
270
282
  accumulatedReasoning += event.delta;
@@ -370,6 +382,10 @@ function useChat(options = {}) {
370
382
  [sendMessage]
371
383
  );
372
384
  const dismissPresentedFile = useCallback(() => setPresentedFile(null), []);
385
+ const openWorkspaceFile = useCallback(
386
+ (path) => setPresentedFile({ path, title: path.split("/").pop() || path, description: "" }),
387
+ []
388
+ );
373
389
  return {
374
390
  messages,
375
391
  input,
@@ -387,6 +403,7 @@ function useChat(options = {}) {
387
403
  todos,
388
404
  presentedFile,
389
405
  dismissPresentedFile,
406
+ openWorkspaceFile,
390
407
  stop,
391
408
  reload,
392
409
  clear,
@@ -777,7 +794,7 @@ function useConnection(autoCheck = true) {
777
794
  }
778
795
 
779
796
  // src/index.ts
780
- var VERSION = "0.2.0";
797
+ var VERSION = "0.3.2";
781
798
  export {
782
799
  PersonaProvider,
783
800
  VERSION,
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// 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((data?.state?.files ?? {}) as Record<string, PersonaWorkspaceFile>);\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(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 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 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.2.0';\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,QAAM,QAAQ,QAA6B,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,oBAAC,eAAe,UAAf,EAAwB,OAAe,UAAS;AAC1D;AAEO,SAAS,oBAAyC;AACvD,QAAM,UAAU,WAAW,cAA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;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,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/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,QAAM,QAAQ,QAA6B,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,YAA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M,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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@personaai/react",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "React hooks and state management library for the Persona AI agent runtime. Client-side only.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",