@copilotkit/react-native 1.61.0 → 1.61.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 +10 -10
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -5
- package/dist/index.d.mts +8 -6
- package/dist/index.mjs +10 -10
- package/dist/index.mjs.map +1 -1
- package/dist/polyfills.cjs +1 -1
- package/dist/polyfills.cjs.map +1 -1
- package/dist/polyfills.mjs +1 -1
- package/dist/polyfills.mjs.map +1 -1
- package/package.json +4 -4
- package/src/CopilotChat.tsx +3 -1
- package/src/CopilotKitProvider.tsx +20 -12
- package/src/CopilotSidebar.tsx +3 -3
- package/src/__tests__/copilot-sidebar.test.tsx +1 -1
- package/src/__tests__/headless-integration.test.tsx +2 -5
- package/src/components/__tests__/CopilotChat-edge-cases.test.tsx +1 -1
- package/src/components/__tests__/CopilotChat.test.tsx +1 -1
- package/src/index.ts +3 -0
- package/src/streaming-fetch.ts +2 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["CopilotKitContext","useAgent","useCopilotKit","styles"],"sources":["../src/CopilotKitProvider.tsx","../src/hooks/use-attachments.ts","../src/CopilotChat.tsx","../src/CopilotModal.tsx","../src/CopilotSidebar.tsx","../src/CopilotPopup.tsx","../src/hooks/useRenderTool.ts"],"sourcesContent":["import React, { useEffect, useMemo, useRef, useState } from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n CopilotKitContext,\n LicenseContext,\n} from \"@copilotkit/react-core/v2/context\";\nimport type { CopilotKitContextValue } from \"@copilotkit/react-core/v2/context\";\nimport { CopilotKitCoreReact } from \"@copilotkit/react-core/v2/headless\";\nimport type { CopilotKitCoreErrorCode } from \"@copilotkit/core\";\nimport type { DebugConfig } from \"@copilotkit/shared\";\nimport { RenderToolProvider } from \"./hooks/RenderToolContext\";\n\nexport interface CopilotKitNativeProviderProps {\n children: ReactNode;\n /** URL of the CopilotKit runtime endpoint */\n runtimeUrl: string;\n /** Custom headers sent with every request */\n headers?: Record<string, string> | (() => Record<string, string>);\n /**\n * Credentials mode for fetch requests (e.g., \"include\" for HTTP-only cookies in cross-origin requests).\n */\n credentials?: RequestCredentials;\n /** Whether the runtime uses a single-route endpoint */\n useSingleEndpoint?: boolean;\n /** Custom properties forwarded to agents */\n properties?: Record<string, unknown>;\n /**\n * Error handler called when CopilotKit encounters an error.\n * Fires for all error types (runtime connection failures, agent errors, tool errors).\n * If not provided, errors are logged to console.error.\n */\n onError?: (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => void | Promise<void>;\n /**\n * Enable debug logging for the client-side event pipeline.\n * When `true`, enables verbose logging from the core instance.\n */\n debug?: DebugConfig;\n /**\n * Default throttle interval (ms) for `onMessagesChanged` / `onStateChanged`\n * subscriptions. Individual subscriptions can override with their own `throttleMs`.\n */\n defaultThrottleMs?: number;\n // Cloud features (publicApiKey, licenseToken) — not yet supported on React Native\n}\n\n/**\n * CopilotKit provider for React Native.\n *\n * A lightweight alternative to the web CopilotKitProvider that avoids\n * web-only dependencies (DOM, CSS, Radix UI, Lit, etc).\n *\n * Polyfills are auto-imported when `@copilotkit/react-native` is loaded,\n * so a separate `import \"@copilotkit/react-native/polyfills\"` is no longer\n * required (though it remains available for advanced use).\n *\n * Usage:\n * ```tsx\n * import { CopilotKitProvider } from \"@copilotkit/react-native\";\n *\n * function App() {\n * return (\n * <CopilotKitProvider runtimeUrl=\"https://your-runtime/api/copilotkit\">\n * <ChatScreen />\n * </CopilotKitProvider>\n * );\n * }\n * ```\n */\nexport const CopilotKitProvider: React.FC<CopilotKitNativeProviderProps> = ({\n children,\n runtimeUrl,\n headers: headersProp,\n credentials,\n useSingleEndpoint,\n properties,\n onError,\n debug,\n defaultThrottleMs,\n}) => {\n // Resolve headers from function or static object (matches web provider pattern)\n const resolvedHeaders =\n typeof headersProp === \"function\" ? headersProp() : headersProp;\n\n // Stabilize headers/properties references to avoid effect churn when callers\n // pass inline object literals (e.g. headers={{}} or the undefined default).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const stableHeaders = useMemo(\n () => resolvedHeaders ?? {},\n [JSON.stringify(resolvedHeaders)],\n );\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const stableProperties = useMemo(\n () => properties ?? {},\n [JSON.stringify(properties)],\n );\n\n const copilotkitRef = useRef<CopilotKitCoreReact | null>(null);\n\n if (copilotkitRef.current === null) {\n copilotkitRef.current = new CopilotKitCoreReact({\n runtimeUrl,\n runtimeTransport:\n useSingleEndpoint === true\n ? \"single\"\n : useSingleEndpoint === false\n ? \"rest\"\n : \"auto\",\n headers: stableHeaders,\n credentials,\n properties: stableProperties,\n debug,\n });\n // Set initial defaultThrottleMs synchronously so child hooks see the\n // correct value on their first render (before useEffect fires).\n if (defaultThrottleMs !== undefined) {\n copilotkitRef.current.setDefaultThrottleMs(defaultThrottleMs);\n }\n }\n\n const copilotkit = copilotkitRef.current;\n\n // Sync props to core instance\n useEffect(() => {\n copilotkit.setRuntimeUrl(runtimeUrl);\n copilotkit.setRuntimeTransport(\n useSingleEndpoint === true\n ? \"single\"\n : useSingleEndpoint === false\n ? \"rest\"\n : \"auto\",\n );\n copilotkit.setHeaders(stableHeaders);\n copilotkit.setCredentials(credentials);\n copilotkit.setProperties(stableProperties);\n copilotkit.setDebug(debug);\n }, [\n runtimeUrl,\n useSingleEndpoint,\n stableHeaders,\n credentials,\n stableProperties,\n debug,\n copilotkit,\n ]);\n\n // Sync defaultThrottleMs to the core instance on prop changes.\n // Initial value is set synchronously during instance creation (inside the\n // ref guard above), so this only handles subsequent updates.\n useEffect(() => {\n copilotkit.setDefaultThrottleMs(defaultThrottleMs);\n }, [copilotkit, defaultThrottleMs]);\n\n // Track executing tool call IDs at the provider level.\n // Critical for HITL reconnection: onToolExecutionStart fires before child\n // components mount, so we must capture the state here.\n const [executingToolCallIds, setExecutingToolCallIds] = useState<\n ReadonlySet<string>\n >(() => new Set());\n\n // Use ref to avoid subscription churn when onError changes\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n // Single subscription for tool execution tracking and error handling.\n // Tool call IDs are tracked at the provider level because onToolExecutionStart\n // fires before child components mount — critical for HITL reconnection.\n useEffect(() => {\n const subscription = copilotkit.subscribe({\n onToolExecutionStart: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.add(toolCallId);\n return next;\n });\n },\n onToolExecutionEnd: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (!prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.delete(toolCallId);\n return next;\n });\n },\n onError: (event) => {\n if (onErrorRef.current) {\n onErrorRef.current(event);\n } else {\n console.error(\n `[CopilotKit] Error (${event.code}):`,\n event.error,\n event.context ?? {},\n );\n }\n },\n });\n return () => subscription.unsubscribe();\n }, [copilotkit]);\n\n const contextValue: CopilotKitContextValue = useMemo(\n () => ({\n copilotkit,\n executingToolCallIds,\n }),\n [copilotkit, executingToolCallIds],\n );\n\n const licenseContextValue = useMemo(\n () => ({\n status: null as null,\n license: null as null,\n checkFeature: () => true,\n getLimit: () => null,\n }),\n [],\n );\n\n return (\n <CopilotKitContext.Provider value={contextValue}>\n <LicenseContext.Provider value={licenseContextValue}>\n <RenderToolProvider>{children}</RenderToolProvider>\n </LicenseContext.Provider>\n </CopilotKitContext.Provider>\n );\n};\n","// packages/react-native/src/hooks/use-attachments.ts\nimport { useCallback, useRef, useState } from \"react\";\nimport {\n randomUUID,\n getModalityFromMimeType,\n formatFileSize,\n} from \"@copilotkit/shared\";\nimport type {\n Attachment,\n AttachmentUploadResult,\n AttachmentUploadErrorReason,\n} from \"@copilotkit/shared\";\nimport * as DocumentPicker from \"expo-document-picker\";\nimport * as FileSystem from \"expo-file-system\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Platform-neutral file descriptor for React Native.\n * Replaces the web `File` object in all attachment APIs.\n */\nexport interface NativeFileInput {\n /** Local file URI (e.g. `file:///path/to/file`). */\n uri: string;\n /** Filename with extension. */\n name: string;\n /** File size in bytes. */\n size: number;\n /** MIME type (e.g. `\"image/jpeg\"`). */\n mimeType: string;\n}\n\n/**\n * React Native variant of AttachmentsConfig.\n * Identical to the shared AttachmentsConfig except `onUpload` receives\n * a `NativeFileInput` instead of a web `File`.\n */\nexport interface NativeAttachmentsConfig {\n /** Enable file attachments in the chat input. */\n enabled: boolean;\n /** MIME type filter for the file picker, default all files. */\n accept?: string;\n /** Maximum file size in bytes, default 20MB (20 * 1024 * 1024). */\n maxSize?: number;\n /** Custom upload handler. Receives the native file descriptor. */\n onUpload?: (\n file: NativeFileInput,\n ) => AttachmentUploadResult | Promise<AttachmentUploadResult>;\n /** Called when an attachment fails validation or upload. */\n onUploadFailed?: (error: {\n reason: AttachmentUploadErrorReason;\n file: NativeFileInput;\n message: string;\n }) => void;\n}\n\nexport interface UseNativeAttachmentsProps {\n config?: NativeAttachmentsConfig;\n}\n\nexport interface UseNativeAttachmentsReturn {\n /** Currently selected attachments (uploading + ready). */\n attachments: Attachment[];\n /** Whether attachments are enabled. */\n enabled: boolean;\n /** Open the native document picker. */\n openPicker: () => Promise<void>;\n /** Process an array of NativeFileInput objects (validate, read, add to state). */\n processFiles: (files: NativeFileInput[]) => Promise<void>;\n /** Remove an attachment by ID. */\n removeAttachment: (id: string) => void;\n /** Consume ready attachments and clear the queue. Returns the consumed attachments. */\n consumeAttachments: () => Attachment[];\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_MAX_SIZE = 20 * 1024 * 1024; // 20 MB\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\n/**\n * React Native hook that manages file attachment state -- picking, uploading,\n * and lifecycle. All returned callbacks are referentially stable via useCallback.\n *\n * This is the RN counterpart of the web `useAttachments` hook from\n * `@copilotkit/react-core`. It replaces web APIs (FileReader, DragEvent,\n * HTMLInputElement) with Expo modules (expo-document-picker, expo-file-system).\n */\nexport function useAttachments({\n config,\n}: UseNativeAttachmentsProps): UseNativeAttachmentsReturn {\n const enabled = config?.enabled ?? false;\n\n const [attachments, setAttachments] = useState<Attachment[]>([]);\n\n // Refs for stable callbacks to read latest values\n const configRef = useRef(config);\n configRef.current = config;\n const attachmentsRef = useRef<Attachment[]>([]);\n attachmentsRef.current = attachments;\n\n /**\n * Simple MIME accept filter for NativeFileInput.\n * Handles wildcards like \"image/*\" and exact types like \"application/pdf\".\n * Comma-separated lists are supported.\n */\n const matchesAccept = useCallback(\n (file: NativeFileInput, accept: string): boolean => {\n if (!accept || accept === \"*/*\") return true;\n const filters = accept.split(\",\").map((f) => f.trim());\n return filters.some((filter) => {\n if (filter.startsWith(\".\")) {\n return file.name.toLowerCase().endsWith(filter.toLowerCase());\n }\n if (filter.endsWith(\"/*\")) {\n const prefix = filter.slice(0, -2);\n return file.mimeType.startsWith(prefix + \"/\");\n }\n return file.mimeType === filter;\n });\n },\n [],\n );\n\n const processFiles = useCallback(\n async (files: NativeFileInput[]) => {\n const cfg = configRef.current;\n const accept = cfg?.accept ?? \"*/*\";\n const maxSize = cfg?.maxSize ?? DEFAULT_MAX_SIZE;\n\n // Filter by accept type\n const rejectedFiles = files.filter((f) => !matchesAccept(f, accept));\n for (const file of rejectedFiles) {\n cfg?.onUploadFailed?.({\n reason: \"invalid-type\",\n file,\n message: `File \"${file.name}\" is not accepted. Supported types: ${accept}`,\n });\n }\n\n const validFiles = files.filter((f) => matchesAccept(f, accept));\n\n for (const file of validFiles) {\n // Size check\n if (file.size > maxSize) {\n cfg?.onUploadFailed?.({\n reason: \"file-too-large\",\n file,\n message: `File \"${file.name}\" exceeds the maximum size of ${formatFileSize(maxSize)}`,\n });\n continue;\n }\n\n const modality = getModalityFromMimeType(file.mimeType);\n const placeholderId = randomUUID();\n const placeholder: Attachment = {\n id: placeholderId,\n type: modality,\n source: { type: \"data\", value: \"\", mimeType: file.mimeType },\n filename: file.name,\n size: file.size,\n status: \"uploading\",\n };\n\n setAttachments((prev) => [...prev, placeholder]);\n\n try {\n let source: Attachment[\"source\"];\n let uploadMetadata: Record<string, unknown> | undefined;\n\n if (cfg?.onUpload) {\n const { metadata: meta, ...uploadSource } =\n await cfg.onUpload(file);\n source = uploadSource;\n uploadMetadata = meta;\n } else {\n // Default: read file as base64 via expo-file-system\n const base64 = await FileSystem.readAsStringAsync(file.uri, {\n encoding: FileSystem.EncodingType.Base64,\n });\n source = { type: \"data\", value: base64, mimeType: file.mimeType };\n }\n\n setAttachments((prev) =>\n prev.map((att) =>\n att.id === placeholderId\n ? {\n ...att,\n source,\n status: \"ready\" as const,\n metadata: uploadMetadata,\n }\n : att,\n ),\n );\n } catch (error) {\n // Remove placeholder on failure\n setAttachments((prev) =>\n prev.filter((att) => att.id !== placeholderId),\n );\n console.error(`[CopilotKit] Failed to upload \"${file.name}\":`, error);\n cfg?.onUploadFailed?.({\n reason: \"upload-failed\",\n file,\n message:\n error instanceof Error\n ? error.message\n : `Failed to upload \"${file.name}\"`,\n });\n }\n }\n },\n [matchesAccept],\n );\n\n const openPicker = useCallback(async () => {\n const cfg = configRef.current;\n const accept = cfg?.accept ?? \"*/*\";\n\n // Convert accept string to array for DocumentPicker\n const typeArray = accept\n .split(\",\")\n .map((t) => t.trim())\n .filter(Boolean);\n\n try {\n const result = await DocumentPicker.getDocumentAsync({\n type: typeArray.length > 0 ? typeArray : [\"*/*\"],\n copyToCacheDirectory: true,\n multiple: true,\n });\n\n if (result.canceled || !result.assets?.length) return;\n\n const nativeFiles: NativeFileInput[] = result.assets.map((asset) => ({\n uri: asset.uri,\n name: asset.name ?? \"unknown\",\n size: asset.size ?? 0,\n mimeType: asset.mimeType ?? \"application/octet-stream\",\n }));\n\n await processFiles(nativeFiles);\n } catch (error) {\n console.error(\"[CopilotKit] Document picker error:\", error);\n }\n }, [processFiles]);\n\n const removeAttachment = useCallback((id: string) => {\n setAttachments((prev) => prev.filter((a) => a.id !== id));\n }, []);\n\n const consumeAttachments = useCallback(() => {\n const ready = attachmentsRef.current.filter((a) => a.status === \"ready\");\n if (ready.length === 0) return ready;\n setAttachments((prev) => prev.filter((a) => a.status !== \"ready\"));\n return ready;\n }, []);\n\n return {\n attachments,\n enabled,\n openPicker,\n processFiles,\n removeAttachment,\n consumeAttachments,\n };\n}\n","import React, {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useRef,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport { useAgent } from \"@copilotkit/react-core/v2/headless\";\nimport { useCopilotKit } from \"@copilotkit/react-core/v2/context\";\nimport { DEFAULT_AGENT_ID, randomUUID } from \"@copilotkit/shared\";\nimport type { InputContent } from \"@copilotkit/shared\";\nimport type { CopilotKitCoreErrorCode } from \"@copilotkit/core\";\nimport { useAttachments } from \"./hooks/use-attachments\";\nimport type { NativeAttachmentsConfig } from \"./hooks/use-attachments\";\nimport type { Attachment } from \"@copilotkit/shared\";\n\n// ---------------------------------------------------------------------------\n// Context\n// ---------------------------------------------------------------------------\n\nexport interface CopilotChatContextValue {\n /** The resolved agent instance. */\n agent: any;\n /** Whether the agent is currently running. */\n isRunning: boolean;\n /** Current messages in the conversation. */\n messages: any[];\n /** Currently selected attachments (uploading + ready). */\n attachments: Attachment[];\n /** Whether attachments are enabled. */\n attachmentsEnabled: boolean;\n /** Open the native document picker to add files. */\n openPicker: () => Promise<void>;\n /** Remove an attachment by ID. */\n removeAttachment: (id: string) => void;\n /**\n * Submit a message with optional attachments.\n * Handles consuming ready attachments, building InputContent[],\n * calling agent.addMessage, and running the agent.\n */\n submitMessage: (text: string) => Promise<void>;\n}\n\nconst CopilotChatCtx = createContext<CopilotChatContextValue | null>(null);\n\n/**\n * Hook to access the CopilotChat context from child components.\n * Must be called inside a `<CopilotChat>` component tree.\n */\nexport function useCopilotChatContext(): CopilotChatContextValue {\n const ctx = useContext(CopilotChatCtx);\n if (!ctx) {\n throw new Error(\n \"useCopilotChatContext must be used within a <CopilotChat> component\",\n );\n }\n return ctx;\n}\n\n// ---------------------------------------------------------------------------\n// Props\n// ---------------------------------------------------------------------------\n\nexport interface CopilotChatProps {\n /**\n * The agent ID to use for this chat session.\n * Matches the web SDK's CopilotChat `agentId` prop.\n *\n * Resolution order: `agentId` > `agentName` > `\"default\"`\n */\n agentId?: string;\n\n /**\n * @deprecated Use `agentId` instead. `agentName` is kept for backwards\n * compatibility and will be removed in a future release.\n */\n agentName?: string;\n\n /**\n * Thread ID for this chat session. When provided, the chat will resume\n * the specified thread. Matches the web SDK's CopilotChat `threadId` prop.\n */\n threadId?: string;\n\n /**\n * Error handler scoped to this chat's agent. Fires in addition to the\n * provider-level onError (does not suppress it). Receives only errors\n * whose context.agentId matches this chat's agent.\n */\n onError?: (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => void | Promise<void>;\n\n /**\n * Throttle interval (in milliseconds) for re-renders triggered by message\n * change notifications. Overrides the provider-level `defaultThrottleMs`\n * for this chat instance. Forwarded to the internal `useAgent()` hook.\n *\n * @default undefined -- inherits from provider `defaultThrottleMs`;\n * if that is also unset, re-renders are unthrottled.\n */\n throttleMs?: number;\n\n /**\n * Enable multimodal file attachments (images, audio, video, documents).\n * Pass a NativeAttachmentsConfig object to configure file picking behavior.\n */\n attachments?: NativeAttachmentsConfig;\n\n /**\n * Optional children rendered inside the chat context.\n */\n children?: ReactNode;\n\n /** Passthrough props are forwarded to consumers via the agent context. */\n [key: string]: unknown;\n}\n\n/**\n * Headless CopilotChat component for React Native.\n *\n * Wires up the `useAgent` hook with `agentId` resolution and renders children.\n * Unlike the web SDK's CopilotChat, this component does not render any UI\n * elements -- consumers provide their own React Native views.\n *\n * Children can access chat state via `useCopilotChatContext()`.\n *\n * ```tsx\n * import { CopilotChat, useCopilotChatContext } from \"@copilotkit/react-native\";\n *\n * function MyChatUI() {\n * const { messages, submitMessage, attachments, openPicker } = useCopilotChatContext();\n * // ... render your UI\n * }\n *\n * <CopilotChat agentId=\"my-agent\" attachments={{ enabled: true }}>\n * <MyChatUI />\n * </CopilotChat>\n * ```\n */\nexport function CopilotChat({\n agentId,\n agentName,\n threadId,\n onError,\n throttleMs,\n attachments: attachmentsConfig,\n children,\n ..._rest\n}: CopilotChatProps) {\n const resolvedAgentId = agentId ?? agentName ?? DEFAULT_AGENT_ID;\n\n // Deprecation warning (dev only, fires once per mount)\n const warnedRef = useRef(false);\n useEffect(() => {\n if (\n agentName !== undefined &&\n agentId === undefined &&\n !warnedRef.current\n ) {\n warnedRef.current = true;\n if (typeof __DEV__ === \"undefined\" || __DEV__) {\n console.warn(\n \"[CopilotKit] agentName is deprecated, use agentId instead\",\n );\n }\n }\n }, [agentName, agentId]);\n\n const { agent } = useAgent({ agentId: resolvedAgentId, throttleMs });\n\n // Set threadId on the agent when provided\n useEffect(() => {\n if (threadId) {\n agent.threadId = threadId;\n }\n }, [agent, threadId]);\n\n // onError subscription -- forward core errors scoped to this chat's agent\n const { copilotkit } = useCopilotKit();\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n useEffect(() => {\n if (!onErrorRef.current) return;\n\n const subscription = copilotkit.subscribe({\n onError: (event) => {\n // Only forward errors that match this chat's agent\n if (\n event.context?.agentId === resolvedAgentId ||\n !event.context?.agentId\n ) {\n onErrorRef.current?.({\n error: event.error,\n code: event.code,\n context: event.context,\n });\n }\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit, resolvedAgentId]);\n\n // Attachments\n const {\n attachments: selectedAttachments,\n enabled: attachmentsEnabled,\n openPicker,\n removeAttachment,\n consumeAttachments,\n } = useAttachments({ config: attachmentsConfig });\n\n // Submit handler -- mirrors web CopilotChat.tsx lines 234-288\n const submitMessage = useCallback(\n async (value: string) => {\n // Block if uploads in progress\n const hasUploading = selectedAttachments.some(\n (a) => a.status === \"uploading\",\n );\n if (hasUploading) {\n console.error(\n \"[CopilotKit] Cannot send while attachments are uploading\",\n );\n return;\n }\n\n const readyAttachments = consumeAttachments();\n\n if (readyAttachments.length > 0) {\n const contentParts: InputContent[] = [];\n if (value.trim()) {\n contentParts.push({ type: \"text\", text: value });\n }\n for (const att of readyAttachments) {\n contentParts.push({\n type: att.type,\n source: att.source,\n metadata: {\n ...(att.filename ? { filename: att.filename } : {}),\n ...att.metadata,\n },\n } as InputContent);\n }\n agent.addMessage({\n id: randomUUID(),\n role: \"user\",\n content: contentParts,\n });\n } else {\n agent.addMessage({\n id: randomUUID(),\n role: \"user\",\n content: value,\n });\n }\n\n try {\n await copilotkit.runAgent({ agent });\n } catch (error) {\n console.error(\"CopilotChat: runAgent failed\", error);\n }\n },\n // copilotkit is intentionally excluded -- it is a stable ref that never changes.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [agent, selectedAttachments, consumeAttachments],\n );\n\n const contextValue: CopilotChatContextValue = {\n agent,\n isRunning: agent.isRunning,\n messages: agent.messages,\n attachments: selectedAttachments,\n attachmentsEnabled,\n openPicker,\n removeAttachment,\n submitMessage,\n };\n\n return (\n <CopilotChatCtx.Provider value={contextValue}>\n {children}\n </CopilotChatCtx.Provider>\n );\n}\n","import React, { type ReactNode } from \"react\";\nimport { CopilotChat, type CopilotChatProps } from \"./CopilotChat\";\n\nexport interface CopilotModalProps extends CopilotChatProps {\n /**\n * Optional children rendered inside the modal context.\n */\n children?: ReactNode;\n}\n\n/**\n * Headless CopilotModal component for React Native.\n *\n * A thin wrapper around CopilotChat that mirrors the web SDK's CopilotModal\n * API surface. On React Native, modal presentation is handled by the consumer\n * (e.g. React Native's `Modal` component) -- this component only provides\n * the agent wiring and prop resolution.\n *\n * ```tsx\n * import { CopilotModal } from \"@copilotkit/react-native\";\n * import { Modal } from \"react-native\";\n *\n * <Modal visible={isOpen}>\n * <CopilotModal agentId=\"my-agent\">\n * <MyChatUI />\n * </CopilotModal>\n * </Modal>\n * ```\n */\nexport function CopilotModal({ children, ...props }: CopilotModalProps) {\n return <CopilotChat {...props}>{children}</CopilotChat>;\n}\n","import React, {\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n Animated,\n Dimensions,\n Pressable,\n StyleSheet,\n Text,\n useWindowDimensions,\n View,\n} from \"react-native\";\nimport type { ViewStyle } from \"react-native\";\nimport { CopilotChat } from \"./CopilotChat\";\nimport type { CopilotChatProps } from \"./CopilotChat\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface CopilotSidebarHandle {\n /** Slide the drawer open. */\n open(): void;\n /** Slide the drawer closed. */\n close(): void;\n /** Toggle the drawer open/closed. */\n toggle(): void;\n}\n\nexport interface CopilotSidebarProps extends Omit<\n CopilotChatProps,\n \"children\"\n> {\n /**\n * Start the drawer in the open position.\n * @default false\n */\n defaultOpen?: boolean;\n\n /**\n * Width of the drawer panel. Accepts a number (points) or a percentage\n * string (e.g. `\"85%\"`). Defaults to 85% of the screen width.\n */\n width?: number | string;\n\n /**\n * Title displayed in the drawer header bar.\n * @default \"Copilot\"\n */\n headerTitle?: string;\n\n /**\n * Show a floating action button to toggle the drawer.\n * @default true\n */\n showToggleButton?: boolean;\n\n /** Called after the drawer finishes opening. */\n onOpen?: () => void;\n\n /** Called after the drawer finishes closing. */\n onClose?: () => void;\n\n /** Custom style applied to the drawer container. */\n style?: ViewStyle;\n\n /** Content rendered inside the drawer below the chat area. */\n children?: ReactNode;\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst ANIMATION_DURATION_MS = 300;\nconst DEFAULT_HEADER_TITLE = \"Copilot\";\nconst BACKDROP_OPACITY = 0.4;\nconst FAB_SIZE = 56;\n\n// ---------------------------------------------------------------------------\n// Component\n// ---------------------------------------------------------------------------\n\n/**\n * CopilotSidebar -- a slide-in drawer from the right edge of the screen\n * that wraps CopilotChat for React Native.\n *\n * ```tsx\n * import { CopilotSidebar } from \"@copilotkit/react-native\";\n *\n * const ref = useRef<CopilotSidebarHandle>(null);\n *\n * <CopilotSidebar\n * ref={ref}\n * agentId=\"my-agent\"\n * headerTitle=\"Assistant\"\n * defaultOpen={false}\n * />\n * ```\n */\nexport const CopilotSidebar = forwardRef<\n CopilotSidebarHandle,\n CopilotSidebarProps\n>(function CopilotSidebar(\n {\n agentId,\n agentName,\n threadId,\n onError,\n throttleMs,\n defaultOpen = false,\n width: widthProp,\n headerTitle = DEFAULT_HEADER_TITLE,\n showToggleButton = true,\n onOpen,\n onClose,\n style,\n children,\n ...rest\n },\n ref,\n) {\n const { width: screenWidth } = useWindowDimensions();\n\n // Resolve drawer width ---------------------------------------------------\n const drawerWidth = resolveWidth(widthProp, screenWidth);\n\n // Animation & open state -------------------------------------------------\n const [isOpen, setIsOpen] = useState(defaultOpen);\n const slideAnim = useRef(\n new Animated.Value(defaultOpen ? 0 : drawerWidth),\n ).current;\n\n // Keep the animated value in sync when drawerWidth changes while closed\n useEffect(() => {\n if (!isOpen) {\n slideAnim.setValue(drawerWidth);\n }\n }, [drawerWidth, isOpen, slideAnim]);\n\n const animateTo = useCallback(\n (toValue: number, cb?: () => void) => {\n Animated.timing(slideAnim, {\n toValue,\n duration: ANIMATION_DURATION_MS,\n useNativeDriver: true,\n }).start(({ finished }) => {\n if (finished) cb?.();\n });\n },\n [slideAnim],\n );\n\n const open = useCallback(() => {\n setIsOpen(true);\n animateTo(0, onOpen);\n }, [animateTo, onOpen]);\n\n const close = useCallback(() => {\n animateTo(drawerWidth, () => {\n setIsOpen(false);\n onClose?.();\n });\n }, [animateTo, drawerWidth, onClose]);\n\n const toggle = useCallback(() => {\n if (isOpen) {\n close();\n } else {\n open();\n }\n }, [isOpen, open, close]);\n\n useImperativeHandle(ref, () => ({ open, close, toggle }), [\n open,\n close,\n toggle,\n ]);\n\n // Callbacks stored in refs for stable animation closures -----------------\n const onOpenRef = useRef(onOpen);\n const onCloseRef = useRef(onClose);\n useEffect(() => {\n onOpenRef.current = onOpen;\n }, [onOpen]);\n useEffect(() => {\n onCloseRef.current = onClose;\n }, [onClose]);\n\n // -----------------------------------------------------------------------\n // Render\n // -----------------------------------------------------------------------\n return (\n <>\n {/* Backdrop */}\n {isOpen && (\n <Pressable\n style={styles.backdrop}\n onPress={close}\n accessibilityRole=\"button\"\n accessibilityLabel=\"Close sidebar\"\n testID=\"copilot-sidebar-backdrop\"\n />\n )}\n\n {/* Drawer */}\n {isOpen && (\n <Animated.View\n style={[\n styles.drawer,\n { width: drawerWidth, transform: [{ translateX: slideAnim }] },\n style,\n ]}\n testID=\"copilot-sidebar-drawer\"\n >\n {/* Header */}\n <View style={styles.header}>\n <Text style={styles.headerTitle}>{headerTitle}</Text>\n <Pressable\n onPress={close}\n accessibilityRole=\"button\"\n accessibilityLabel=\"Close\"\n hitSlop={8}\n testID=\"copilot-sidebar-close\"\n >\n <Text style={styles.closeButton}>{\"✕\"}</Text>\n </Pressable>\n </View>\n\n {/* Chat area */}\n <View style={styles.chatContainer}>\n <CopilotChat\n agentId={agentId}\n agentName={agentName}\n threadId={threadId}\n onError={onError}\n throttleMs={throttleMs}\n {...rest}\n >\n {children}\n </CopilotChat>\n </View>\n </Animated.View>\n )}\n\n {/* Floating action button */}\n {showToggleButton && !isOpen && (\n <Pressable\n style={styles.fab}\n onPress={open}\n accessibilityRole=\"button\"\n accessibilityLabel=\"Open sidebar\"\n testID=\"copilot-sidebar-fab\"\n >\n <Text style={styles.fabIcon}>{\"💬\"}</Text>\n </Pressable>\n )}\n </>\n );\n});\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction resolveWidth(\n widthProp: number | string | undefined,\n screenWidth: number,\n): number {\n if (widthProp === undefined) {\n return Math.round(screenWidth * 0.85);\n }\n if (typeof widthProp === \"number\") {\n return widthProp;\n }\n // Percentage string, e.g. \"85%\"\n const pctMatch = String(widthProp).match(/^(\\d+(?:\\.\\d+)?)%$/);\n if (pctMatch) {\n return Math.round(screenWidth * (parseFloat(pctMatch[1]) / 100));\n }\n // Fallback: try parsing as number\n const parsed = parseFloat(widthProp);\n return isNaN(parsed) ? Math.round(screenWidth * 0.85) : parsed;\n}\n\n// ---------------------------------------------------------------------------\n// Styles\n// ---------------------------------------------------------------------------\n\nconst styles = StyleSheet.create({\n backdrop: {\n ...StyleSheet.absoluteFillObject,\n backgroundColor: `rgba(0, 0, 0, ${BACKDROP_OPACITY})`,\n zIndex: 999,\n },\n drawer: {\n position: \"absolute\",\n top: 0,\n right: 0,\n bottom: 0,\n backgroundColor: \"#ffffff\",\n zIndex: 1000,\n shadowColor: \"#000\",\n shadowOffset: { width: -2, height: 0 },\n shadowOpacity: 0.25,\n shadowRadius: 8,\n elevation: 16,\n },\n header: {\n flexDirection: \"row\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n paddingHorizontal: 16,\n paddingVertical: 12,\n borderBottomWidth: StyleSheet.hairlineWidth,\n borderBottomColor: \"#e0e0e0\",\n },\n headerTitle: {\n fontSize: 18,\n fontWeight: \"600\",\n color: \"#1a1a1a\",\n },\n closeButton: {\n fontSize: 20,\n color: \"#666\",\n padding: 4,\n },\n chatContainer: {\n flex: 1,\n },\n fab: {\n position: \"absolute\",\n bottom: 24,\n right: 24,\n width: FAB_SIZE,\n height: FAB_SIZE,\n borderRadius: FAB_SIZE / 2,\n backgroundColor: \"#007AFF\",\n alignItems: \"center\",\n justifyContent: \"center\",\n shadowColor: \"#000\",\n shadowOffset: { width: 0, height: 2 },\n shadowOpacity: 0.3,\n shadowRadius: 4,\n elevation: 8,\n zIndex: 998,\n },\n fabIcon: {\n fontSize: 24,\n },\n});\n","// NOTE: This component needs to be exported from index.ts\n// e.g. export { CopilotPopup } from \"./CopilotPopup\";\n// export type { CopilotPopupProps, CopilotPopupHandle } from \"./CopilotPopup\";\n\nimport React, {\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n Modal,\n Pressable,\n StyleSheet,\n Text,\n TouchableOpacity,\n View,\n useWindowDimensions,\n} from \"react-native\";\nimport type { ViewStyle } from \"react-native\";\nimport { CopilotChat } from \"./CopilotChat\";\nimport type { NativeAttachmentsConfig } from \"./hooks/use-attachments\";\nimport type { CopilotKitCoreErrorCode } from \"@copilotkit/core\";\n\nexport interface CopilotPopupProps {\n /**\n * The agent ID to use for this chat session.\n * Passed through to CopilotChat.\n */\n agentId?: string;\n\n /**\n * @deprecated Use `agentId` instead.\n */\n agentName?: string;\n\n /**\n * Thread ID for this chat session.\n */\n threadId?: string;\n\n /**\n * Throttle interval (ms) for re-renders.\n */\n throttleMs?: number;\n\n /**\n * Whether the popup starts in the open state.\n * @default false\n */\n defaultOpen?: boolean;\n\n /**\n * Height of the popup card. Accepts a number (points) or a percentage\n * string (e.g. \"60%\") relative to the screen height.\n * @default \"60%\"\n */\n height?: number | string;\n\n /**\n * Error handler scoped to this popup's chat agent.\n */\n onError?: (error: Error) => void;\n\n /**\n * Title displayed in the popup header bar.\n * @default \"CopilotKit\"\n */\n headerTitle?: string;\n\n /**\n * Enable multimodal file attachments. Forwarded to the internal CopilotChat.\n * Children access attachment state via `useCopilotChatContext()`.\n */\n attachments?: NativeAttachmentsConfig;\n\n /**\n * Optional children rendered below the CopilotChat content\n * inside the popup card.\n */\n children?: ReactNode;\n\n /**\n * Callback fired when the popup opens.\n */\n onOpen?: () => void;\n\n /**\n * Callback fired when the popup closes.\n */\n onClose?: () => void;\n\n /**\n * Whether tapping the semi-transparent backdrop dismisses the popup.\n * Equivalent to web SDK's `clickOutsideToClose`.\n * @default true\n */\n dismissOnBackdropPress?: boolean;\n\n /**\n * Whether to show the floating action button (FAB) that toggles the popup.\n * @default true\n */\n showToggleButton?: boolean;\n\n /**\n * Custom styles applied to the popup card container.\n */\n style?: ViewStyle;\n}\n\n/**\n * Imperative handle exposed via ref for controlling the popup programmatically.\n */\nexport interface CopilotPopupHandle {\n open: () => void;\n close: () => void;\n toggle: () => void;\n}\n\n/**\n * CopilotPopup for React Native.\n *\n * A floating action button (FAB) that opens a modal chat overlay.\n * The popup appears as a card floating above content with rounded corners,\n * a shadow, and a semi-transparent backdrop.\n *\n * ```tsx\n * import { CopilotPopup } from \"@copilotkit/react-native\";\n *\n * const popupRef = useRef<CopilotPopupHandle>(null);\n *\n * <CopilotPopup\n * ref={popupRef}\n * agentId=\"my-agent\"\n * headerTitle=\"Chat\"\n * defaultOpen={false}\n * />\n * ```\n */\nexport const CopilotPopup = forwardRef<CopilotPopupHandle, CopilotPopupProps>(\n function CopilotPopup(\n {\n agentId,\n agentName,\n threadId,\n throttleMs,\n defaultOpen = false,\n height = \"60%\",\n onError,\n headerTitle = \"CopilotKit\",\n attachments: attachmentsConfig,\n children,\n onOpen,\n onClose,\n dismissOnBackdropPress = true,\n showToggleButton = true,\n style,\n }: CopilotPopupProps,\n ref: React.Ref<CopilotPopupHandle>,\n ) {\n const [visible, setVisible] = useState(defaultOpen);\n const { height: screenHeight } = useWindowDimensions();\n\n // Stable refs for callbacks to avoid effect churn\n const onOpenRef = useRef(onOpen);\n const onCloseRef = useRef(onClose);\n useEffect(() => {\n onOpenRef.current = onOpen;\n }, [onOpen]);\n useEffect(() => {\n onCloseRef.current = onClose;\n }, [onClose]);\n\n const handleOpen = useCallback(() => {\n setVisible(true);\n onOpenRef.current?.();\n }, []);\n\n const handleClose = useCallback(() => {\n setVisible(false);\n onCloseRef.current?.();\n }, []);\n\n const handleToggle = useCallback(() => {\n setVisible((prev) => {\n const next = !prev;\n if (next) {\n onOpenRef.current?.();\n } else {\n onCloseRef.current?.();\n }\n return next;\n });\n }, []);\n\n // Expose imperative methods\n useImperativeHandle(\n ref,\n () => ({\n open: handleOpen,\n close: handleClose,\n toggle: handleToggle,\n }),\n [handleOpen, handleClose, handleToggle],\n );\n\n // Resolve popup height\n const resolvedHeight =\n typeof height === \"string\" && height.endsWith(\"%\")\n ? (parseFloat(height) / 100) * screenHeight\n : typeof height === \"number\"\n ? height\n : 0.6 * screenHeight;\n\n // Wrap onError to match CopilotChat's expected signature\n const chatOnError = onError\n ? (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => onError(event.error)\n : undefined;\n\n return (\n <>\n {/* Floating Action Button */}\n {showToggleButton && !visible && (\n <TouchableOpacity\n testID=\"copilot-popup-fab\"\n style={styles.fab}\n onPress={handleToggle}\n activeOpacity={0.8}\n accessibilityLabel=\"Open chat\"\n accessibilityRole=\"button\"\n >\n <Text style={styles.fabIcon}>💬</Text>\n </TouchableOpacity>\n )}\n\n {/* Modal Overlay */}\n <Modal\n testID=\"copilot-popup-modal\"\n visible={visible}\n transparent\n animationType=\"slide\"\n onRequestClose={handleClose}\n >\n {/* Backdrop */}\n <Pressable\n testID=\"copilot-popup-backdrop\"\n style={styles.backdrop}\n onPress={dismissOnBackdropPress ? handleClose : undefined}\n >\n {/* Card — stop propagation so tapping the card doesn't dismiss */}\n <Pressable\n testID=\"copilot-popup-card\"\n style={[styles.card, { height: resolvedHeight }, style]}\n onPress={() => {\n // Prevent backdrop press from firing\n }}\n >\n {/* Header */}\n <View style={styles.header}>\n <Text style={styles.headerTitle}>{headerTitle}</Text>\n <TouchableOpacity\n testID=\"copilot-popup-close\"\n onPress={handleClose}\n hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}\n accessibilityLabel=\"Close chat\"\n accessibilityRole=\"button\"\n >\n <Text style={styles.closeButton}>✕</Text>\n </TouchableOpacity>\n </View>\n\n {/* Chat Content */}\n <View style={styles.chatContainer}>\n <CopilotChat\n agentId={agentId}\n agentName={agentName}\n threadId={threadId}\n throttleMs={throttleMs}\n onError={chatOnError}\n attachments={attachmentsConfig}\n >\n {children}\n </CopilotChat>\n </View>\n </Pressable>\n </Pressable>\n </Modal>\n </>\n );\n },\n);\n\nconst styles = StyleSheet.create({\n fab: {\n position: \"absolute\",\n bottom: 24,\n right: 24,\n width: 56,\n height: 56,\n borderRadius: 28,\n backgroundColor: \"#6366f1\",\n alignItems: \"center\",\n justifyContent: \"center\",\n elevation: 6,\n shadowColor: \"#000\",\n shadowOffset: { width: 0, height: 3 },\n shadowOpacity: 0.27,\n shadowRadius: 4.65,\n },\n fabIcon: {\n fontSize: 24,\n },\n backdrop: {\n flex: 1,\n backgroundColor: \"rgba(0, 0, 0, 0.4)\",\n justifyContent: \"flex-end\",\n },\n card: {\n backgroundColor: \"#ffffff\",\n borderTopLeftRadius: 16,\n borderTopRightRadius: 16,\n overflow: \"hidden\",\n elevation: 10,\n shadowColor: \"#000\",\n shadowOffset: { width: 0, height: -3 },\n shadowOpacity: 0.25,\n shadowRadius: 8,\n },\n header: {\n flexDirection: \"row\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n paddingHorizontal: 16,\n paddingVertical: 12,\n borderBottomWidth: StyleSheet.hairlineWidth,\n borderBottomColor: \"#e5e7eb\",\n },\n headerTitle: {\n fontSize: 17,\n fontWeight: \"600\",\n color: \"#111827\",\n },\n closeButton: {\n fontSize: 18,\n color: \"#6b7280\",\n fontWeight: \"500\",\n },\n chatContainer: {\n flex: 1,\n },\n});\n","import { useEffect, useRef } from \"react\";\nimport { useFrontendTool } from \"@copilotkit/react-core/v2/headless\";\nimport type { StandardSchemaV1 } from \"@copilotkit/shared\";\nimport type { RenderToolFunction } from \"./RenderToolContext\";\nimport { useRenderToolContext } from \"./RenderToolContext\";\n\n/**\n * Options for the useRenderTool hook.\n */\nexport interface UseRenderToolOptions<T extends Record<string, unknown>> {\n /** Unique name for the tool. Must match what the agent calls. */\n name: string;\n /** Human-readable description shown to the agent. */\n description: string;\n /**\n * Schema describing the tool's parameters.\n * Accepts any StandardSchemaV1-compatible schema (Zod, Valibot, ArkType, etc.).\n */\n parameters: StandardSchemaV1<unknown, T>;\n /**\n * Render function that returns a React Native element for the tool call.\n * Called by CopilotChat when it encounters a tool call message for this tool.\n *\n * Returns ReactElement | null (not ReactNode) because React Native's\n * FlatList cannot render strings or portals.\n */\n render: RenderToolFunction<T>;\n /**\n * Optional handler executed when the tool is called.\n * If omitted, the tool is render-only (the render function shows UI\n * but the tool returns no result to the agent).\n */\n handler?: (args: T) => Promise<unknown>;\n /**\n * Optional agent ID to scope this tool to a specific agent.\n */\n agentId?: string;\n}\n\n/**\n * Hook that registers a frontend tool AND a render function for it.\n *\n * This bridges `useFrontendTool` (which handles tool registration and\n * handler execution) with a render registry so that CopilotChat can\n * render React Native elements inline when it encounters tool call messages.\n *\n * @example\n * ```tsx\n * useRenderTool({\n * name: \"showWeather\",\n * description: \"Display weather information\",\n * parameters: z.object({ city: z.string(), temp: z.number() }),\n * render: ({ args, status }) => (\n * <View>\n * <Text>{args.city}: {args.temp}</Text>\n * {status === \"executing\" && <ActivityIndicator />}\n * </View>\n * ),\n * handler: async ({ city }) => {\n * return { forecast: \"sunny\" };\n * },\n * });\n * ```\n */\nexport function useRenderTool<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(options: UseRenderToolOptions<T>, deps?: ReadonlyArray<unknown>): void {\n const { name, description, parameters, render, handler, agentId } = options;\n const { register } = useRenderToolContext();\n\n // Register the tool with the core system via useFrontendTool\n useFrontendTool<T>(\n {\n name,\n description,\n parameters,\n handler,\n agentId,\n },\n deps,\n );\n\n // Use a ref so the effect cleanup always has the latest render function\n const renderRef = useRef(render);\n renderRef.current = render;\n\n // Register the render function in the RenderToolContext\n useEffect(() => {\n // Wrap in a stable function that delegates to the ref\n const stableRender: RenderToolFunction<T> = (props) =>\n renderRef.current(props);\n\n const unregister = register(name, stableRender as RenderToolFunction);\n return unregister;\n }, [name, register]);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwEA,MAAa,sBAA+D,EAC1E,UACA,YACA,SAAS,aACT,aACA,mBACA,YACA,SACA,OACA,wBACI;CAEJ,MAAM,kBACJ,OAAO,gBAAgB,aAAa,aAAa,GAAG;CAKtD,MAAM,gBAAgB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AM;EACN,iBAAiB;EACjB,gBAAgB;EACjB;CACD,MAAM;EACJ,iBAAiB;EACjB,qBAAqB;EACrB,sBAAsB;EACtB,UAAU;EACV,WAAW;EACX,aAAa;EACb,cAAc;GAAE,OAAO;GAAG,QAAQ;GAAI;EACtC,eAAe;EACf,cAAc;EACf;CACD,QAAQ;EACN,eAAe;EACf,YAAY;EACZ,gBAAgB;EAChB,mBAAmB;EACnB,iBAAiB;EACjB,mBAAmB,WAAW;EAC9B,mBAAmB;EACpB;CACD,aAAa;EACX,UAAU;EACV,YAAY;EACZ,OAAO;EACR;CACD,aAAa;EACX,UAAU;EACV,OAAO;EACP,YAAY;EACb;CACD,eAAe,EACb,MAAM,GACP;CACF,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACtSF,SAAgB,cAEd,SAAkC,MAAqC;CACvE,MAAM,EAAE,MAAM,aAAa,YAAY,QAAQ,SAAS,YAAY;CACpE,MAAM,EAAE,aAAa,sBAAsB;AAG3C,mBACE;EACE;EACA;EACA;EACA;EACA;EACD,EACD,KACD;CAGD,MAAM,YAAY,OAAO,OAAO;AAChC,WAAU,UAAU;AAGpB,iBAAgB;EAEd,MAAM,gBAAuC,UAC3C,UAAU,QAAQ,MAAM;AAG1B,SADmB,SAAS,MAAM,aAAmC;IAEpE,CAAC,MAAM,SAAS,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["CopilotKitContext","useAgent","useCopilotKit","styles"],"sources":["../src/CopilotKitProvider.tsx","../src/hooks/use-attachments.ts","../src/CopilotChat.tsx","../src/CopilotModal.tsx","../src/CopilotSidebar.tsx","../src/CopilotPopup.tsx","../src/hooks/useRenderTool.ts"],"sourcesContent":["import React, { useEffect, useMemo, useRef, useState } from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n CopilotKitContext,\n LicenseContext,\n} from \"@copilotkit/react-core/v2/context\";\nimport type {\n CopilotKitContextValue,\n CopilotKitCoreReact as CopilotKitCoreReactInstance,\n} from \"@copilotkit/react-core/v2/context\";\nimport { CopilotKitCoreReact } from \"@copilotkit/react-core/v2/headless\";\nimport type { CopilotKitCoreErrorCode } from \"@copilotkit/core\";\nimport type { DebugConfig, RuntimeLicenseStatus } from \"@copilotkit/shared\";\nimport { createLicenseContextValue } from \"@copilotkit/shared\";\nimport { RenderToolProvider } from \"./hooks/RenderToolContext\";\n\nexport interface CopilotKitNativeProviderProps {\n children: ReactNode;\n /** URL of the CopilotKit runtime endpoint */\n runtimeUrl: string;\n /** Custom headers sent with every request */\n headers?: Record<string, string> | (() => Record<string, string>);\n /**\n * Credentials mode for fetch requests (e.g., \"include\" for HTTP-only cookies in cross-origin requests).\n */\n credentials?: RequestCredentials;\n /** Whether the runtime uses a single-route endpoint */\n useSingleEndpoint?: boolean;\n /** Custom properties forwarded to agents */\n properties?: Record<string, unknown>;\n /**\n * Error handler called when CopilotKit encounters an error.\n * Fires for all error types (runtime connection failures, agent errors, tool errors).\n * If not provided, errors are logged to console.error.\n */\n onError?: (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => void | Promise<void>;\n /**\n * Enable debug logging for the client-side event pipeline.\n * When `true`, enables verbose logging from the core instance.\n */\n debug?: DebugConfig;\n /**\n * Default throttle interval (ms) for `onMessagesChanged` / `onStateChanged`\n * subscriptions. Individual subscriptions can override with their own `throttleMs`.\n */\n defaultThrottleMs?: number;\n // Cloud features (publicApiKey, licenseToken) — not yet supported on React Native\n}\n\n/**\n * CopilotKit provider for React Native.\n *\n * A lightweight alternative to the web CopilotKitProvider that avoids\n * web-only dependencies (DOM, CSS, Radix UI, Lit, etc).\n *\n * Polyfills are auto-imported when `@copilotkit/react-native` is loaded,\n * so a separate `import \"@copilotkit/react-native/polyfills\"` is no longer\n * required (though it remains available for advanced use).\n *\n * Usage:\n * ```tsx\n * import { CopilotKitProvider } from \"@copilotkit/react-native\";\n *\n * function App() {\n * return (\n * <CopilotKitProvider runtimeUrl=\"https://your-runtime/api/copilotkit\">\n * <ChatScreen />\n * </CopilotKitProvider>\n * );\n * }\n * ```\n */\nexport const CopilotKitProvider: React.FC<CopilotKitNativeProviderProps> = ({\n children,\n runtimeUrl,\n headers: headersProp,\n credentials,\n useSingleEndpoint,\n properties,\n onError,\n debug,\n defaultThrottleMs,\n}) => {\n // Resolve headers from function or static object (matches web provider pattern)\n const resolvedHeaders =\n typeof headersProp === \"function\" ? headersProp() : headersProp;\n\n // Stabilize headers/properties references to avoid effect churn when callers\n // pass inline object literals (e.g. headers={{}} or the undefined default).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const stableHeaders = useMemo(\n () => resolvedHeaders ?? {},\n [JSON.stringify(resolvedHeaders)],\n );\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const stableProperties = useMemo(\n () => properties ?? {},\n [JSON.stringify(properties)],\n );\n\n const copilotkitRef = useRef<CopilotKitCoreReactInstance | null>(null);\n\n if (copilotkitRef.current === null) {\n const instance: CopilotKitCoreReactInstance = new CopilotKitCoreReact({\n runtimeUrl,\n runtimeTransport:\n useSingleEndpoint === true\n ? \"single\"\n : useSingleEndpoint === false\n ? \"rest\"\n : \"auto\",\n headers: stableHeaders,\n credentials,\n properties: stableProperties,\n debug,\n });\n // Set initial defaultThrottleMs synchronously so child hooks see the\n // correct value on their first render (before useEffect fires).\n if (defaultThrottleMs !== undefined) {\n instance.setDefaultThrottleMs(defaultThrottleMs);\n }\n copilotkitRef.current = instance;\n }\n\n const copilotkit = copilotkitRef.current;\n\n // Sync props to core instance\n useEffect(() => {\n copilotkit.setRuntimeUrl(runtimeUrl);\n copilotkit.setRuntimeTransport(\n useSingleEndpoint === true\n ? \"single\"\n : useSingleEndpoint === false\n ? \"rest\"\n : \"auto\",\n );\n copilotkit.setHeaders(stableHeaders);\n copilotkit.setCredentials(credentials);\n copilotkit.setProperties(stableProperties);\n copilotkit.setDebug(debug);\n }, [\n runtimeUrl,\n useSingleEndpoint,\n stableHeaders,\n credentials,\n stableProperties,\n debug,\n copilotkit,\n ]);\n\n // Sync defaultThrottleMs to the core instance on prop changes.\n // Initial value is set synchronously during instance creation (inside the\n // ref guard above), so this only handles subsequent updates.\n useEffect(() => {\n copilotkit.setDefaultThrottleMs(defaultThrottleMs);\n }, [copilotkit, defaultThrottleMs]);\n\n // Track executing tool call IDs at the provider level.\n // Critical for HITL reconnection: onToolExecutionStart fires before child\n // components mount, so we must capture the state here.\n const [executingToolCallIds, setExecutingToolCallIds] = useState<\n ReadonlySet<string>\n >(() => new Set());\n\n const [runtimeLicenseStatus, setRuntimeLicenseStatus] = useState<\n RuntimeLicenseStatus | undefined\n >(undefined);\n\n // Use ref to avoid subscription churn when onError changes\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n // Single subscription for tool execution tracking and error handling.\n // Tool call IDs are tracked at the provider level because onToolExecutionStart\n // fires before child components mount — critical for HITL reconnection.\n useEffect(() => {\n const subscription = copilotkit.subscribe({\n onToolExecutionStart: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.add(toolCallId);\n return next;\n });\n },\n onToolExecutionEnd: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (!prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.delete(toolCallId);\n return next;\n });\n },\n onError: (event) => {\n if (onErrorRef.current) {\n onErrorRef.current(event);\n } else {\n console.error(\n `[CopilotKit] Error (${event.code}):`,\n event.error,\n event.context ?? {},\n );\n }\n },\n onRuntimeConnectionStatusChanged: () => {\n setRuntimeLicenseStatus(copilotkit.licenseStatus);\n },\n });\n return () => subscription.unsubscribe();\n }, [copilotkit]);\n\n const contextValue: CopilotKitContextValue = useMemo(\n () => ({\n copilotkit,\n executingToolCallIds,\n }),\n [copilotkit, executingToolCallIds],\n );\n\n // License context — driven by server-reported status via /info endpoint\n const licenseContextValue = useMemo(\n () => createLicenseContextValue(runtimeLicenseStatus),\n [runtimeLicenseStatus],\n );\n\n return (\n <CopilotKitContext.Provider value={contextValue}>\n <LicenseContext.Provider value={licenseContextValue}>\n <RenderToolProvider>{children}</RenderToolProvider>\n </LicenseContext.Provider>\n </CopilotKitContext.Provider>\n );\n};\n","// packages/react-native/src/hooks/use-attachments.ts\nimport { useCallback, useRef, useState } from \"react\";\nimport {\n randomUUID,\n getModalityFromMimeType,\n formatFileSize,\n} from \"@copilotkit/shared\";\nimport type {\n Attachment,\n AttachmentUploadResult,\n AttachmentUploadErrorReason,\n} from \"@copilotkit/shared\";\nimport * as DocumentPicker from \"expo-document-picker\";\nimport * as FileSystem from \"expo-file-system\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Platform-neutral file descriptor for React Native.\n * Replaces the web `File` object in all attachment APIs.\n */\nexport interface NativeFileInput {\n /** Local file URI (e.g. `file:///path/to/file`). */\n uri: string;\n /** Filename with extension. */\n name: string;\n /** File size in bytes. */\n size: number;\n /** MIME type (e.g. `\"image/jpeg\"`). */\n mimeType: string;\n}\n\n/**\n * React Native variant of AttachmentsConfig.\n * Identical to the shared AttachmentsConfig except `onUpload` receives\n * a `NativeFileInput` instead of a web `File`.\n */\nexport interface NativeAttachmentsConfig {\n /** Enable file attachments in the chat input. */\n enabled: boolean;\n /** MIME type filter for the file picker, default all files. */\n accept?: string;\n /** Maximum file size in bytes, default 20MB (20 * 1024 * 1024). */\n maxSize?: number;\n /** Custom upload handler. Receives the native file descriptor. */\n onUpload?: (\n file: NativeFileInput,\n ) => AttachmentUploadResult | Promise<AttachmentUploadResult>;\n /** Called when an attachment fails validation or upload. */\n onUploadFailed?: (error: {\n reason: AttachmentUploadErrorReason;\n file: NativeFileInput;\n message: string;\n }) => void;\n}\n\nexport interface UseNativeAttachmentsProps {\n config?: NativeAttachmentsConfig;\n}\n\nexport interface UseNativeAttachmentsReturn {\n /** Currently selected attachments (uploading + ready). */\n attachments: Attachment[];\n /** Whether attachments are enabled. */\n enabled: boolean;\n /** Open the native document picker. */\n openPicker: () => Promise<void>;\n /** Process an array of NativeFileInput objects (validate, read, add to state). */\n processFiles: (files: NativeFileInput[]) => Promise<void>;\n /** Remove an attachment by ID. */\n removeAttachment: (id: string) => void;\n /** Consume ready attachments and clear the queue. Returns the consumed attachments. */\n consumeAttachments: () => Attachment[];\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_MAX_SIZE = 20 * 1024 * 1024; // 20 MB\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\n/**\n * React Native hook that manages file attachment state -- picking, uploading,\n * and lifecycle. All returned callbacks are referentially stable via useCallback.\n *\n * This is the RN counterpart of the web `useAttachments` hook from\n * `@copilotkit/react-core`. It replaces web APIs (FileReader, DragEvent,\n * HTMLInputElement) with Expo modules (expo-document-picker, expo-file-system).\n */\nexport function useAttachments({\n config,\n}: UseNativeAttachmentsProps): UseNativeAttachmentsReturn {\n const enabled = config?.enabled ?? false;\n\n const [attachments, setAttachments] = useState<Attachment[]>([]);\n\n // Refs for stable callbacks to read latest values\n const configRef = useRef(config);\n configRef.current = config;\n const attachmentsRef = useRef<Attachment[]>([]);\n attachmentsRef.current = attachments;\n\n /**\n * Simple MIME accept filter for NativeFileInput.\n * Handles wildcards like \"image/*\" and exact types like \"application/pdf\".\n * Comma-separated lists are supported.\n */\n const matchesAccept = useCallback(\n (file: NativeFileInput, accept: string): boolean => {\n if (!accept || accept === \"*/*\") return true;\n const filters = accept.split(\",\").map((f) => f.trim());\n return filters.some((filter) => {\n if (filter.startsWith(\".\")) {\n return file.name.toLowerCase().endsWith(filter.toLowerCase());\n }\n if (filter.endsWith(\"/*\")) {\n const prefix = filter.slice(0, -2);\n return file.mimeType.startsWith(prefix + \"/\");\n }\n return file.mimeType === filter;\n });\n },\n [],\n );\n\n const processFiles = useCallback(\n async (files: NativeFileInput[]) => {\n const cfg = configRef.current;\n const accept = cfg?.accept ?? \"*/*\";\n const maxSize = cfg?.maxSize ?? DEFAULT_MAX_SIZE;\n\n // Filter by accept type\n const rejectedFiles = files.filter((f) => !matchesAccept(f, accept));\n for (const file of rejectedFiles) {\n cfg?.onUploadFailed?.({\n reason: \"invalid-type\",\n file,\n message: `File \"${file.name}\" is not accepted. Supported types: ${accept}`,\n });\n }\n\n const validFiles = files.filter((f) => matchesAccept(f, accept));\n\n for (const file of validFiles) {\n // Size check\n if (file.size > maxSize) {\n cfg?.onUploadFailed?.({\n reason: \"file-too-large\",\n file,\n message: `File \"${file.name}\" exceeds the maximum size of ${formatFileSize(maxSize)}`,\n });\n continue;\n }\n\n const modality = getModalityFromMimeType(file.mimeType);\n const placeholderId = randomUUID();\n const placeholder: Attachment = {\n id: placeholderId,\n type: modality,\n source: { type: \"data\", value: \"\", mimeType: file.mimeType },\n filename: file.name,\n size: file.size,\n status: \"uploading\",\n };\n\n setAttachments((prev) => [...prev, placeholder]);\n\n try {\n let source: Attachment[\"source\"];\n let uploadMetadata: Record<string, unknown> | undefined;\n\n if (cfg?.onUpload) {\n const { metadata: meta, ...uploadSource } =\n await cfg.onUpload(file);\n source = uploadSource;\n uploadMetadata = meta;\n } else {\n // Default: read file as base64 via expo-file-system\n const base64 = await FileSystem.readAsStringAsync(file.uri, {\n encoding: FileSystem.EncodingType.Base64,\n });\n source = { type: \"data\", value: base64, mimeType: file.mimeType };\n }\n\n setAttachments((prev) =>\n prev.map((att) =>\n att.id === placeholderId\n ? {\n ...att,\n source,\n status: \"ready\" as const,\n metadata: uploadMetadata,\n }\n : att,\n ),\n );\n } catch (error) {\n // Remove placeholder on failure\n setAttachments((prev) =>\n prev.filter((att) => att.id !== placeholderId),\n );\n console.error(`[CopilotKit] Failed to upload \"${file.name}\":`, error);\n cfg?.onUploadFailed?.({\n reason: \"upload-failed\",\n file,\n message:\n error instanceof Error\n ? error.message\n : `Failed to upload \"${file.name}\"`,\n });\n }\n }\n },\n [matchesAccept],\n );\n\n const openPicker = useCallback(async () => {\n const cfg = configRef.current;\n const accept = cfg?.accept ?? \"*/*\";\n\n // Convert accept string to array for DocumentPicker\n const typeArray = accept\n .split(\",\")\n .map((t) => t.trim())\n .filter(Boolean);\n\n try {\n const result = await DocumentPicker.getDocumentAsync({\n type: typeArray.length > 0 ? typeArray : [\"*/*\"],\n copyToCacheDirectory: true,\n multiple: true,\n });\n\n if (result.canceled || !result.assets?.length) return;\n\n const nativeFiles: NativeFileInput[] = result.assets.map((asset) => ({\n uri: asset.uri,\n name: asset.name ?? \"unknown\",\n size: asset.size ?? 0,\n mimeType: asset.mimeType ?? \"application/octet-stream\",\n }));\n\n await processFiles(nativeFiles);\n } catch (error) {\n console.error(\"[CopilotKit] Document picker error:\", error);\n }\n }, [processFiles]);\n\n const removeAttachment = useCallback((id: string) => {\n setAttachments((prev) => prev.filter((a) => a.id !== id));\n }, []);\n\n const consumeAttachments = useCallback(() => {\n const ready = attachmentsRef.current.filter((a) => a.status === \"ready\");\n if (ready.length === 0) return ready;\n setAttachments((prev) => prev.filter((a) => a.status !== \"ready\"));\n return ready;\n }, []);\n\n return {\n attachments,\n enabled,\n openPicker,\n processFiles,\n removeAttachment,\n consumeAttachments,\n };\n}\n","import React, {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useRef,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport { useAgent } from \"@copilotkit/react-core/v2/headless\";\nimport { useCopilotKit } from \"@copilotkit/react-core/v2/context\";\nimport { DEFAULT_AGENT_ID, randomUUID } from \"@copilotkit/shared\";\nimport type { InputContent } from \"@copilotkit/shared\";\nimport type { CopilotKitCoreErrorCode } from \"@copilotkit/core\";\nimport { useAttachments } from \"./hooks/use-attachments\";\nimport type { NativeAttachmentsConfig } from \"./hooks/use-attachments\";\nimport type { Attachment } from \"@copilotkit/shared\";\n\n// ---------------------------------------------------------------------------\n// Context\n// ---------------------------------------------------------------------------\n\nexport interface CopilotChatContextValue {\n /** The resolved agent instance. */\n agent: any;\n /** Whether the agent is currently running. */\n isRunning: boolean;\n /** Current messages in the conversation. */\n messages: any[];\n /** Currently selected attachments (uploading + ready). */\n attachments: Attachment[];\n /** Whether attachments are enabled. */\n attachmentsEnabled: boolean;\n /** Open the native document picker to add files. */\n openPicker: () => Promise<void>;\n /** Remove an attachment by ID. */\n removeAttachment: (id: string) => void;\n /**\n * Submit a message with optional attachments.\n * Handles consuming ready attachments, building InputContent[],\n * calling agent.addMessage, and running the agent.\n */\n submitMessage: (text: string) => Promise<void>;\n}\n\nconst CopilotChatCtx = createContext<CopilotChatContextValue | null>(null);\n\n/**\n * Hook to access the CopilotChat context from child components.\n * Must be called inside a `<CopilotChat>` component tree.\n */\nexport function useCopilotChatContext(): CopilotChatContextValue {\n const ctx = useContext(CopilotChatCtx);\n if (!ctx) {\n throw new Error(\n \"useCopilotChatContext must be used within a <CopilotChat> component\",\n );\n }\n return ctx;\n}\n\n// ---------------------------------------------------------------------------\n// Props\n// ---------------------------------------------------------------------------\n\nexport interface CopilotChatBaseProps {\n /**\n * The agent ID to use for this chat session.\n * Matches the web SDK's CopilotChat `agentId` prop.\n *\n * Resolution order: `agentId` > `agentName` > `\"default\"`\n */\n agentId?: string;\n\n /**\n * @deprecated Use `agentId` instead. `agentName` is kept for backwards\n * compatibility and will be removed in a future release.\n */\n agentName?: string;\n\n /**\n * Thread ID for this chat session. When provided, the chat will resume\n * the specified thread. Matches the web SDK's CopilotChat `threadId` prop.\n */\n threadId?: string;\n\n /**\n * Error handler scoped to this chat's agent. Fires in addition to the\n * provider-level onError (does not suppress it). Receives only errors\n * whose context.agentId matches this chat's agent.\n */\n onError?: (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => void | Promise<void>;\n\n /**\n * Throttle interval (in milliseconds) for re-renders triggered by message\n * change notifications. Overrides the provider-level `defaultThrottleMs`\n * for this chat instance. Forwarded to the internal `useAgent()` hook.\n *\n * @default undefined -- inherits from provider `defaultThrottleMs`;\n * if that is also unset, re-renders are unthrottled.\n */\n throttleMs?: number;\n\n /**\n * Enable multimodal file attachments (images, audio, video, documents).\n * Pass a NativeAttachmentsConfig object to configure file picking behavior.\n */\n attachments?: NativeAttachmentsConfig;\n\n /**\n * Optional children rendered inside the chat context.\n */\n children?: ReactNode;\n}\n\nexport interface CopilotChatProps extends CopilotChatBaseProps {\n /** Passthrough props are forwarded to consumers via the agent context. */\n [key: string]: unknown;\n}\n\n/**\n * Headless CopilotChat component for React Native.\n *\n * Wires up the `useAgent` hook with `agentId` resolution and renders children.\n * Unlike the web SDK's CopilotChat, this component does not render any UI\n * elements -- consumers provide their own React Native views.\n *\n * Children can access chat state via `useCopilotChatContext()`.\n *\n * ```tsx\n * import { CopilotChat, useCopilotChatContext } from \"@copilotkit/react-native\";\n *\n * function MyChatUI() {\n * const { messages, submitMessage, attachments, openPicker } = useCopilotChatContext();\n * // ... render your UI\n * }\n *\n * <CopilotChat agentId=\"my-agent\" attachments={{ enabled: true }}>\n * <MyChatUI />\n * </CopilotChat>\n * ```\n */\nexport function CopilotChat({\n agentId,\n agentName,\n threadId,\n onError,\n throttleMs,\n attachments: attachmentsConfig,\n children,\n ..._rest\n}: CopilotChatProps) {\n const resolvedAgentId = agentId ?? agentName ?? DEFAULT_AGENT_ID;\n\n // Deprecation warning (dev only, fires once per mount)\n const warnedRef = useRef(false);\n useEffect(() => {\n if (\n agentName !== undefined &&\n agentId === undefined &&\n !warnedRef.current\n ) {\n warnedRef.current = true;\n if (typeof __DEV__ === \"undefined\" || __DEV__) {\n console.warn(\n \"[CopilotKit] agentName is deprecated, use agentId instead\",\n );\n }\n }\n }, [agentName, agentId]);\n\n const { agent } = useAgent({ agentId: resolvedAgentId, throttleMs });\n\n // Set threadId on the agent when provided\n useEffect(() => {\n if (threadId) {\n agent.threadId = threadId;\n }\n }, [agent, threadId]);\n\n // onError subscription -- forward core errors scoped to this chat's agent\n const { copilotkit } = useCopilotKit();\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n useEffect(() => {\n if (!onErrorRef.current) return;\n\n const subscription = copilotkit.subscribe({\n onError: (event) => {\n // Only forward errors that match this chat's agent\n if (\n event.context?.agentId === resolvedAgentId ||\n !event.context?.agentId\n ) {\n onErrorRef.current?.({\n error: event.error,\n code: event.code,\n context: event.context,\n });\n }\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit, resolvedAgentId]);\n\n // Attachments\n const {\n attachments: selectedAttachments,\n enabled: attachmentsEnabled,\n openPicker,\n removeAttachment,\n consumeAttachments,\n } = useAttachments({ config: attachmentsConfig });\n\n // Submit handler -- mirrors web CopilotChat.tsx lines 234-288\n const submitMessage = useCallback(\n async (value: string) => {\n // Block if uploads in progress\n const hasUploading = selectedAttachments.some(\n (a) => a.status === \"uploading\",\n );\n if (hasUploading) {\n console.error(\n \"[CopilotKit] Cannot send while attachments are uploading\",\n );\n return;\n }\n\n const readyAttachments = consumeAttachments();\n\n if (readyAttachments.length > 0) {\n const contentParts: InputContent[] = [];\n if (value.trim()) {\n contentParts.push({ type: \"text\", text: value });\n }\n for (const att of readyAttachments) {\n contentParts.push({\n type: att.type,\n source: att.source,\n metadata: {\n ...(att.filename ? { filename: att.filename } : {}),\n ...att.metadata,\n },\n } as InputContent);\n }\n agent.addMessage({\n id: randomUUID(),\n role: \"user\",\n content: contentParts,\n });\n } else {\n agent.addMessage({\n id: randomUUID(),\n role: \"user\",\n content: value,\n });\n }\n\n try {\n await copilotkit.runAgent({ agent });\n } catch (error) {\n console.error(\"CopilotChat: runAgent failed\", error);\n }\n },\n // copilotkit is intentionally excluded -- it is a stable ref that never changes.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [agent, selectedAttachments, consumeAttachments],\n );\n\n const contextValue: CopilotChatContextValue = {\n agent,\n isRunning: agent.isRunning,\n messages: agent.messages,\n attachments: selectedAttachments,\n attachmentsEnabled,\n openPicker,\n removeAttachment,\n submitMessage,\n };\n\n return (\n <CopilotChatCtx.Provider value={contextValue}>\n {children}\n </CopilotChatCtx.Provider>\n );\n}\n","import React, { type ReactNode } from \"react\";\nimport { CopilotChat, type CopilotChatProps } from \"./CopilotChat\";\n\nexport interface CopilotModalProps extends CopilotChatProps {\n /**\n * Optional children rendered inside the modal context.\n */\n children?: ReactNode;\n}\n\n/**\n * Headless CopilotModal component for React Native.\n *\n * A thin wrapper around CopilotChat that mirrors the web SDK's CopilotModal\n * API surface. On React Native, modal presentation is handled by the consumer\n * (e.g. React Native's `Modal` component) -- this component only provides\n * the agent wiring and prop resolution.\n *\n * ```tsx\n * import { CopilotModal } from \"@copilotkit/react-native\";\n * import { Modal } from \"react-native\";\n *\n * <Modal visible={isOpen}>\n * <CopilotModal agentId=\"my-agent\">\n * <MyChatUI />\n * </CopilotModal>\n * </Modal>\n * ```\n */\nexport function CopilotModal({ children, ...props }: CopilotModalProps) {\n return <CopilotChat {...props}>{children}</CopilotChat>;\n}\n","import React, {\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n Animated,\n Dimensions,\n Pressable,\n StyleSheet,\n Text,\n useWindowDimensions,\n View,\n} from \"react-native\";\nimport type { ViewStyle } from \"react-native\";\nimport { CopilotChat } from \"./CopilotChat\";\nimport type { CopilotChatBaseProps } from \"./CopilotChat\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface CopilotSidebarHandle {\n /** Slide the drawer open. */\n open(): void;\n /** Slide the drawer closed. */\n close(): void;\n /** Toggle the drawer open/closed. */\n toggle(): void;\n}\n\nexport interface CopilotSidebarProps extends Omit<\n CopilotChatBaseProps,\n \"children\"\n> {\n /**\n * Start the drawer in the open position.\n * @default false\n */\n defaultOpen?: boolean;\n\n /**\n * Width of the drawer panel. Accepts a number (points) or a percentage\n * string (e.g. `\"85%\"`). Defaults to 85% of the screen width.\n */\n width?: number | string;\n\n /**\n * Title displayed in the drawer header bar.\n * @default \"Copilot\"\n */\n headerTitle?: string;\n\n /**\n * Show a floating action button to toggle the drawer.\n * @default true\n */\n showToggleButton?: boolean;\n\n /** Called after the drawer finishes opening. */\n onOpen?: () => void;\n\n /** Called after the drawer finishes closing. */\n onClose?: () => void;\n\n /** Custom style applied to the drawer container. */\n style?: ViewStyle;\n\n /** Content rendered inside the drawer below the chat area. */\n children?: ReactNode;\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst ANIMATION_DURATION_MS = 300;\nconst DEFAULT_HEADER_TITLE = \"Copilot\";\nconst BACKDROP_OPACITY = 0.4;\nconst FAB_SIZE = 56;\n\n// ---------------------------------------------------------------------------\n// Component\n// ---------------------------------------------------------------------------\n\n/**\n * CopilotSidebar -- a slide-in drawer from the right edge of the screen\n * that wraps CopilotChat for React Native.\n *\n * ```tsx\n * import { CopilotSidebar } from \"@copilotkit/react-native\";\n *\n * const ref = useRef<CopilotSidebarHandle>(null);\n *\n * <CopilotSidebar\n * ref={ref}\n * agentId=\"my-agent\"\n * headerTitle=\"Assistant\"\n * defaultOpen={false}\n * />\n * ```\n */\nexport const CopilotSidebar = forwardRef<\n CopilotSidebarHandle,\n CopilotSidebarProps\n>(function CopilotSidebar(\n {\n agentId,\n agentName,\n threadId,\n onError,\n throttleMs,\n defaultOpen = false,\n width: widthProp,\n headerTitle = DEFAULT_HEADER_TITLE,\n showToggleButton = true,\n onOpen,\n onClose,\n style,\n children,\n ...rest\n },\n ref,\n) {\n const { width: screenWidth } = useWindowDimensions();\n\n // Resolve drawer width ---------------------------------------------------\n const drawerWidth = resolveWidth(widthProp, screenWidth);\n\n // Animation & open state -------------------------------------------------\n const [isOpen, setIsOpen] = useState(defaultOpen);\n const slideAnim = useRef(\n new Animated.Value(defaultOpen ? 0 : drawerWidth),\n ).current;\n\n // Keep the animated value in sync when drawerWidth changes while closed\n useEffect(() => {\n if (!isOpen) {\n slideAnim.setValue(drawerWidth);\n }\n }, [drawerWidth, isOpen, slideAnim]);\n\n const animateTo = useCallback(\n (toValue: number, cb?: () => void) => {\n Animated.timing(slideAnim, {\n toValue,\n duration: ANIMATION_DURATION_MS,\n useNativeDriver: true,\n }).start(({ finished }) => {\n if (finished) cb?.();\n });\n },\n [slideAnim],\n );\n\n const open = useCallback(() => {\n setIsOpen(true);\n animateTo(0, onOpen);\n }, [animateTo, onOpen]);\n\n const close = useCallback(() => {\n animateTo(drawerWidth, () => {\n setIsOpen(false);\n onClose?.();\n });\n }, [animateTo, drawerWidth, onClose]);\n\n const toggle = useCallback(() => {\n if (isOpen) {\n close();\n } else {\n open();\n }\n }, [isOpen, open, close]);\n\n useImperativeHandle(ref, () => ({ open, close, toggle }), [\n open,\n close,\n toggle,\n ]);\n\n // Callbacks stored in refs for stable animation closures -----------------\n const onOpenRef = useRef(onOpen);\n const onCloseRef = useRef(onClose);\n useEffect(() => {\n onOpenRef.current = onOpen;\n }, [onOpen]);\n useEffect(() => {\n onCloseRef.current = onClose;\n }, [onClose]);\n\n // -----------------------------------------------------------------------\n // Render\n // -----------------------------------------------------------------------\n return (\n <>\n {/* Backdrop */}\n {isOpen && (\n <Pressable\n style={styles.backdrop}\n onPress={close}\n accessibilityRole=\"button\"\n accessibilityLabel=\"Close sidebar\"\n testID=\"copilot-sidebar-backdrop\"\n />\n )}\n\n {/* Drawer */}\n {isOpen && (\n <Animated.View\n style={[\n styles.drawer,\n { width: drawerWidth, transform: [{ translateX: slideAnim }] },\n style,\n ]}\n testID=\"copilot-sidebar-drawer\"\n >\n {/* Header */}\n <View style={styles.header}>\n <Text style={styles.headerTitle}>{headerTitle}</Text>\n <Pressable\n onPress={close}\n accessibilityRole=\"button\"\n accessibilityLabel=\"Close\"\n hitSlop={8}\n testID=\"copilot-sidebar-close\"\n >\n <Text style={styles.closeButton}>{\"✕\"}</Text>\n </Pressable>\n </View>\n\n {/* Chat area */}\n <View style={styles.chatContainer}>\n <CopilotChat\n agentId={agentId}\n agentName={agentName}\n threadId={threadId}\n onError={onError}\n throttleMs={throttleMs}\n {...rest}\n >\n {children}\n </CopilotChat>\n </View>\n </Animated.View>\n )}\n\n {/* Floating action button */}\n {showToggleButton && !isOpen && (\n <Pressable\n style={styles.fab}\n onPress={open}\n accessibilityRole=\"button\"\n accessibilityLabel=\"Open sidebar\"\n testID=\"copilot-sidebar-fab\"\n >\n <Text style={styles.fabIcon}>{\"💬\"}</Text>\n </Pressable>\n )}\n </>\n );\n});\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction resolveWidth(\n widthProp: number | string | undefined,\n screenWidth: number,\n): number {\n if (widthProp === undefined) {\n return Math.round(screenWidth * 0.85);\n }\n if (typeof widthProp === \"number\") {\n return widthProp;\n }\n // Percentage string, e.g. \"85%\"\n const pctMatch = String(widthProp).match(/^(\\d+(?:\\.\\d+)?)%$/);\n if (pctMatch) {\n return Math.round(screenWidth * (parseFloat(pctMatch[1]) / 100));\n }\n // Fallback: try parsing as number\n const parsed = parseFloat(widthProp);\n return isNaN(parsed) ? Math.round(screenWidth * 0.85) : parsed;\n}\n\n// ---------------------------------------------------------------------------\n// Styles\n// ---------------------------------------------------------------------------\n\nconst styles = StyleSheet.create({\n backdrop: {\n ...StyleSheet.absoluteFill,\n backgroundColor: `rgba(0, 0, 0, ${BACKDROP_OPACITY})`,\n zIndex: 999,\n },\n drawer: {\n position: \"absolute\",\n top: 0,\n right: 0,\n bottom: 0,\n backgroundColor: \"#ffffff\",\n zIndex: 1000,\n shadowColor: \"#000\",\n shadowOffset: { width: -2, height: 0 },\n shadowOpacity: 0.25,\n shadowRadius: 8,\n elevation: 16,\n },\n header: {\n flexDirection: \"row\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n paddingHorizontal: 16,\n paddingVertical: 12,\n borderBottomWidth: StyleSheet.hairlineWidth,\n borderBottomColor: \"#e0e0e0\",\n },\n headerTitle: {\n fontSize: 18,\n fontWeight: \"600\",\n color: \"#1a1a1a\",\n },\n closeButton: {\n fontSize: 20,\n color: \"#666\",\n padding: 4,\n },\n chatContainer: {\n flex: 1,\n },\n fab: {\n position: \"absolute\",\n bottom: 24,\n right: 24,\n width: FAB_SIZE,\n height: FAB_SIZE,\n borderRadius: FAB_SIZE / 2,\n backgroundColor: \"#007AFF\",\n alignItems: \"center\",\n justifyContent: \"center\",\n shadowColor: \"#000\",\n shadowOffset: { width: 0, height: 2 },\n shadowOpacity: 0.3,\n shadowRadius: 4,\n elevation: 8,\n zIndex: 998,\n },\n fabIcon: {\n fontSize: 24,\n },\n});\n","// NOTE: This component needs to be exported from index.ts\n// e.g. export { CopilotPopup } from \"./CopilotPopup\";\n// export type { CopilotPopupProps, CopilotPopupHandle } from \"./CopilotPopup\";\n\nimport React, {\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n Modal,\n Pressable,\n StyleSheet,\n Text,\n TouchableOpacity,\n View,\n useWindowDimensions,\n} from \"react-native\";\nimport type { ViewStyle } from \"react-native\";\nimport { CopilotChat } from \"./CopilotChat\";\nimport type { NativeAttachmentsConfig } from \"./hooks/use-attachments\";\nimport type { CopilotKitCoreErrorCode } from \"@copilotkit/core\";\n\nexport interface CopilotPopupProps {\n /**\n * The agent ID to use for this chat session.\n * Passed through to CopilotChat.\n */\n agentId?: string;\n\n /**\n * @deprecated Use `agentId` instead.\n */\n agentName?: string;\n\n /**\n * Thread ID for this chat session.\n */\n threadId?: string;\n\n /**\n * Throttle interval (ms) for re-renders.\n */\n throttleMs?: number;\n\n /**\n * Whether the popup starts in the open state.\n * @default false\n */\n defaultOpen?: boolean;\n\n /**\n * Height of the popup card. Accepts a number (points) or a percentage\n * string (e.g. \"60%\") relative to the screen height.\n * @default \"60%\"\n */\n height?: number | string;\n\n /**\n * Error handler scoped to this popup's chat agent.\n */\n onError?: (error: Error) => void;\n\n /**\n * Title displayed in the popup header bar.\n * @default \"CopilotKit\"\n */\n headerTitle?: string;\n\n /**\n * Enable multimodal file attachments. Forwarded to the internal CopilotChat.\n * Children access attachment state via `useCopilotChatContext()`.\n */\n attachments?: NativeAttachmentsConfig;\n\n /**\n * Optional children rendered below the CopilotChat content\n * inside the popup card.\n */\n children?: ReactNode;\n\n /**\n * Callback fired when the popup opens.\n */\n onOpen?: () => void;\n\n /**\n * Callback fired when the popup closes.\n */\n onClose?: () => void;\n\n /**\n * Whether tapping the semi-transparent backdrop dismisses the popup.\n * Equivalent to web SDK's `clickOutsideToClose`.\n * @default true\n */\n dismissOnBackdropPress?: boolean;\n\n /**\n * Whether to show the floating action button (FAB) that toggles the popup.\n * @default true\n */\n showToggleButton?: boolean;\n\n /**\n * Custom styles applied to the popup card container.\n */\n style?: ViewStyle;\n}\n\n/**\n * Imperative handle exposed via ref for controlling the popup programmatically.\n */\nexport interface CopilotPopupHandle {\n open: () => void;\n close: () => void;\n toggle: () => void;\n}\n\n/**\n * CopilotPopup for React Native.\n *\n * A floating action button (FAB) that opens a modal chat overlay.\n * The popup appears as a card floating above content with rounded corners,\n * a shadow, and a semi-transparent backdrop.\n *\n * ```tsx\n * import { CopilotPopup } from \"@copilotkit/react-native\";\n *\n * const popupRef = useRef<CopilotPopupHandle>(null);\n *\n * <CopilotPopup\n * ref={popupRef}\n * agentId=\"my-agent\"\n * headerTitle=\"Chat\"\n * defaultOpen={false}\n * />\n * ```\n */\nexport const CopilotPopup = forwardRef<CopilotPopupHandle, CopilotPopupProps>(\n function CopilotPopup(\n {\n agentId,\n agentName,\n threadId,\n throttleMs,\n defaultOpen = false,\n height = \"60%\",\n onError,\n headerTitle = \"CopilotKit\",\n attachments: attachmentsConfig,\n children,\n onOpen,\n onClose,\n dismissOnBackdropPress = true,\n showToggleButton = true,\n style,\n }: CopilotPopupProps,\n ref: React.Ref<CopilotPopupHandle>,\n ) {\n const [visible, setVisible] = useState(defaultOpen);\n const { height: screenHeight } = useWindowDimensions();\n\n // Stable refs for callbacks to avoid effect churn\n const onOpenRef = useRef(onOpen);\n const onCloseRef = useRef(onClose);\n useEffect(() => {\n onOpenRef.current = onOpen;\n }, [onOpen]);\n useEffect(() => {\n onCloseRef.current = onClose;\n }, [onClose]);\n\n const handleOpen = useCallback(() => {\n setVisible(true);\n onOpenRef.current?.();\n }, []);\n\n const handleClose = useCallback(() => {\n setVisible(false);\n onCloseRef.current?.();\n }, []);\n\n const handleToggle = useCallback(() => {\n setVisible((prev) => {\n const next = !prev;\n if (next) {\n onOpenRef.current?.();\n } else {\n onCloseRef.current?.();\n }\n return next;\n });\n }, []);\n\n // Expose imperative methods\n useImperativeHandle(\n ref,\n () => ({\n open: handleOpen,\n close: handleClose,\n toggle: handleToggle,\n }),\n [handleOpen, handleClose, handleToggle],\n );\n\n // Resolve popup height\n const resolvedHeight =\n typeof height === \"string\" && height.endsWith(\"%\")\n ? (parseFloat(height) / 100) * screenHeight\n : typeof height === \"number\"\n ? height\n : 0.6 * screenHeight;\n\n // Wrap onError to match CopilotChat's expected signature\n const chatOnError = onError\n ? (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => onError(event.error)\n : undefined;\n\n return (\n <>\n {/* Floating Action Button */}\n {showToggleButton && !visible && (\n <TouchableOpacity\n testID=\"copilot-popup-fab\"\n style={styles.fab}\n onPress={handleToggle}\n activeOpacity={0.8}\n accessibilityLabel=\"Open chat\"\n accessibilityRole=\"button\"\n >\n <Text style={styles.fabIcon}>💬</Text>\n </TouchableOpacity>\n )}\n\n {/* Modal Overlay */}\n <Modal\n testID=\"copilot-popup-modal\"\n visible={visible}\n transparent\n animationType=\"slide\"\n onRequestClose={handleClose}\n >\n {/* Backdrop */}\n <Pressable\n testID=\"copilot-popup-backdrop\"\n style={styles.backdrop}\n onPress={dismissOnBackdropPress ? handleClose : undefined}\n >\n {/* Card — stop propagation so tapping the card doesn't dismiss */}\n <Pressable\n testID=\"copilot-popup-card\"\n style={[styles.card, { height: resolvedHeight }, style]}\n onPress={() => {\n // Prevent backdrop press from firing\n }}\n >\n {/* Header */}\n <View style={styles.header}>\n <Text style={styles.headerTitle}>{headerTitle}</Text>\n <TouchableOpacity\n testID=\"copilot-popup-close\"\n onPress={handleClose}\n hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}\n accessibilityLabel=\"Close chat\"\n accessibilityRole=\"button\"\n >\n <Text style={styles.closeButton}>✕</Text>\n </TouchableOpacity>\n </View>\n\n {/* Chat Content */}\n <View style={styles.chatContainer}>\n <CopilotChat\n agentId={agentId}\n agentName={agentName}\n threadId={threadId}\n throttleMs={throttleMs}\n onError={chatOnError}\n attachments={attachmentsConfig}\n >\n {children}\n </CopilotChat>\n </View>\n </Pressable>\n </Pressable>\n </Modal>\n </>\n );\n },\n);\n\nconst styles = StyleSheet.create({\n fab: {\n position: \"absolute\",\n bottom: 24,\n right: 24,\n width: 56,\n height: 56,\n borderRadius: 28,\n backgroundColor: \"#6366f1\",\n alignItems: \"center\",\n justifyContent: \"center\",\n elevation: 6,\n shadowColor: \"#000\",\n shadowOffset: { width: 0, height: 3 },\n shadowOpacity: 0.27,\n shadowRadius: 4.65,\n },\n fabIcon: {\n fontSize: 24,\n },\n backdrop: {\n flex: 1,\n backgroundColor: \"rgba(0, 0, 0, 0.4)\",\n justifyContent: \"flex-end\",\n },\n card: {\n backgroundColor: \"#ffffff\",\n borderTopLeftRadius: 16,\n borderTopRightRadius: 16,\n overflow: \"hidden\",\n elevation: 10,\n shadowColor: \"#000\",\n shadowOffset: { width: 0, height: -3 },\n shadowOpacity: 0.25,\n shadowRadius: 8,\n },\n header: {\n flexDirection: \"row\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n paddingHorizontal: 16,\n paddingVertical: 12,\n borderBottomWidth: StyleSheet.hairlineWidth,\n borderBottomColor: \"#e5e7eb\",\n },\n headerTitle: {\n fontSize: 17,\n fontWeight: \"600\",\n color: \"#111827\",\n },\n closeButton: {\n fontSize: 18,\n color: \"#6b7280\",\n fontWeight: \"500\",\n },\n chatContainer: {\n flex: 1,\n },\n});\n","import { useEffect, useRef } from \"react\";\nimport { useFrontendTool } from \"@copilotkit/react-core/v2/headless\";\nimport type { StandardSchemaV1 } from \"@copilotkit/shared\";\nimport type { RenderToolFunction } from \"./RenderToolContext\";\nimport { useRenderToolContext } from \"./RenderToolContext\";\n\n/**\n * Options for the useRenderTool hook.\n */\nexport interface UseRenderToolOptions<T extends Record<string, unknown>> {\n /** Unique name for the tool. Must match what the agent calls. */\n name: string;\n /** Human-readable description shown to the agent. */\n description: string;\n /**\n * Schema describing the tool's parameters.\n * Accepts any StandardSchemaV1-compatible schema (Zod, Valibot, ArkType, etc.).\n */\n parameters: StandardSchemaV1<unknown, T>;\n /**\n * Render function that returns a React Native element for the tool call.\n * Called by CopilotChat when it encounters a tool call message for this tool.\n *\n * Returns ReactElement | null (not ReactNode) because React Native's\n * FlatList cannot render strings or portals.\n */\n render: RenderToolFunction<T>;\n /**\n * Optional handler executed when the tool is called.\n * If omitted, the tool is render-only (the render function shows UI\n * but the tool returns no result to the agent).\n */\n handler?: (args: T) => Promise<unknown>;\n /**\n * Optional agent ID to scope this tool to a specific agent.\n */\n agentId?: string;\n}\n\n/**\n * Hook that registers a frontend tool AND a render function for it.\n *\n * This bridges `useFrontendTool` (which handles tool registration and\n * handler execution) with a render registry so that CopilotChat can\n * render React Native elements inline when it encounters tool call messages.\n *\n * @example\n * ```tsx\n * useRenderTool({\n * name: \"showWeather\",\n * description: \"Display weather information\",\n * parameters: z.object({ city: z.string(), temp: z.number() }),\n * render: ({ args, status }) => (\n * <View>\n * <Text>{args.city}: {args.temp}</Text>\n * {status === \"executing\" && <ActivityIndicator />}\n * </View>\n * ),\n * handler: async ({ city }) => {\n * return { forecast: \"sunny\" };\n * },\n * });\n * ```\n */\nexport function useRenderTool<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(options: UseRenderToolOptions<T>, deps?: ReadonlyArray<unknown>): void {\n const { name, description, parameters, render, handler, agentId } = options;\n const { register } = useRenderToolContext();\n\n // Register the tool with the core system via useFrontendTool\n useFrontendTool<T>(\n {\n name,\n description,\n parameters,\n handler,\n agentId,\n },\n deps,\n );\n\n // Use a ref so the effect cleanup always has the latest render function\n const renderRef = useRef(render);\n renderRef.current = render;\n\n // Register the render function in the RenderToolContext\n useEffect(() => {\n // Wrap in a stable function that delegates to the ref\n const stableRender: RenderToolFunction<T> = (props) =>\n renderRef.current(props);\n\n const unregister = register(name, stableRender as RenderToolFunction);\n return unregister;\n }, [name, register]);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4EA,MAAa,sBAA+D,EAC1E,UACA,YACA,SAAS,aACT,aACA,mBACA,YACA,SACA,OACA,wBACI;CAEJ,MAAM,kBACJ,OAAO,gBAAgB,aAAa,aAAa,GAAG;CAKtD,MAAM,gBAAgB,cACd,mBAAmB,EAAE,EAC3B,CAAC,KAAK,UAAU,gBAAgB,CAAC,CAClC;CAED,MAAM,mBAAmB,cACjB,cAAc,EAAE,EACtB,CAAC,KAAK,UAAU,WAAW,CAAC,CAC7B;CAED,MAAM,gBAAgB,OAA2C,KAAK;AAEtE,KAAI,cAAc,YAAY,MAAM;EAClC,MAAM,WAAwC,IAAI,oBAAoB;GACpE;GACA,kBACE,sBAAsB,OAClB,WACA,sBAAsB,QACpB,SACA;GACR,SAAS;GACT;GACA,YAAY;GACZ;GACD,CAAC;AAGF,MAAI,sBAAsB,OACxB,UAAS,qBAAqB,kBAAkB;AAElD,gBAAc,UAAU;;CAG1B,MAAM,aAAa,cAAc;AAGjC,iBAAgB;AACd,aAAW,cAAc,WAAW;AACpC,aAAW,oBACT,sBAAsB,OAClB,WACA,sBAAsB,QACpB,SACA,OACP;AACD,aAAW,WAAW,cAAc;AACpC,aAAW,eAAe,YAAY;AACtC,aAAW,cAAc,iBAAiB;AAC1C,aAAW,SAAS,MAAM;IACzB;EACD;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;AAKF,iBAAgB;AACd,aAAW,qBAAqB,kBAAkB;IACjD,CAAC,YAAY,kBAAkB,CAAC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;AAChC,WAAU,UAAU;AAGpB,iBAAgB;EAEd,MAAM,gBAAuC,UAC3C,UAAU,QAAQ,MAAM;AAG1B,SADmB,SAAS,MAAM,aAAmC;IAEpE,CAAC,MAAM,SAAS,CAAC"}
|
package/dist/polyfills.cjs
CHANGED
|
@@ -165,7 +165,7 @@ function installStreamingFetch() {
|
|
|
165
165
|
try {
|
|
166
166
|
return JSON.parse(text);
|
|
167
167
|
} catch (e) {
|
|
168
|
-
throw new TypeError(`Failed to parse JSON from ${method} ${url} (status ${xhrStatus}): ${text.length > 200 ? text.slice(0, 200) + "..." : text}
|
|
168
|
+
throw new TypeError(`Failed to parse JSON from ${method} ${url} (status ${xhrStatus}): ${text.length > 200 ? text.slice(0, 200) + "..." : text}`, { cause: e });
|
|
169
169
|
}
|
|
170
170
|
},
|
|
171
171
|
text: async () => {
|
package/dist/polyfills.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"polyfills.cjs","names":[],"sources":["../src/streaming-fetch.ts","../src/polyfills.ts"],"sourcesContent":["/**\n * Streaming fetch implementation for React Native.\n *\n * React Native's built-in fetch doesn't support response.body.getReader()\n * (ReadableStream). This replaces global.fetch with an XHR-based\n * implementation that streams chunks via ReadableStream, enabling\n * CopilotKit's SSE-based agent communication.\n *\n * If native fetch already supports ReadableStream bodies (newer RN / Hermes),\n * the replacement is skipped entirely.\n *\n * THREADING NOTE: In React Native, XHR callbacks (onprogress, onload, etc.)\n * may fire on a native networking thread. Pushing data into the ReadableStream\n * from that thread can trigger downstream React setState calls on the wrong\n * thread, causing iOS to kill the process with \"deleted thread with uncommitted\n * CATransaction\". All stream-mutating operations are therefore deferred via\n * setTimeout(fn, 0) to bounce back to the JS thread (main thread in Hermes).\n *\n * Call `installStreamingFetch()` once at app startup after polyfills.\n */\n\ndeclare const global: typeof globalThis;\n\n/** Subset of the Response interface implemented by the streaming fetch polyfill. */\ninterface StreamingFetchResponse {\n readonly ok: boolean;\n readonly status: number;\n readonly statusText: string;\n readonly url: string;\n readonly type: string;\n readonly redirected: boolean;\n readonly bodyUsed: boolean;\n readonly headers: Headers;\n readonly body: ReadableStream<Uint8Array>;\n json(): Promise<unknown>;\n text(): Promise<string>;\n arrayBuffer(): Promise<ArrayBuffer>;\n blob(): Promise<Blob>;\n clone(): never;\n formData(): Promise<never>;\n}\n\nfunction createAbortError(): DOMException {\n return new (global as any).DOMException(\n \"The operation was aborted.\",\n \"AbortError\",\n );\n}\n\nexport function installStreamingFetch(): void {\n // Skip if native fetch already supports ReadableStream body.\n // Newer React Native versions (Hermes) may support this natively.\n try {\n const testResponse = new Response(\"\");\n if (\n testResponse.body != null &&\n typeof testResponse.body.getReader === \"function\"\n ) {\n return;\n }\n } catch (e) {\n // Response constructor unavailable — expected in older RN environments.\n if (\n __DEV__ &&\n e instanceof Error &&\n !(e instanceof ReferenceError) &&\n !(e instanceof TypeError)\n ) {\n console.warn(\n \"[CopilotKit] Unexpected error during streaming fetch feature detection, \" +\n \"installing XHR-based polyfill:\",\n e,\n );\n }\n }\n\n const originalFetch = global.fetch;\n const TextEncoder = global.TextEncoder;\n\n const streamingFetch = function streamingFetch(\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> {\n // Extract defaults from Request object when input is a Request\n const request =\n typeof input !== \"string\" && !(input instanceof URL) ? input : null;\n let url: string;\n if (typeof input === \"string\") {\n url = input;\n } else if (input instanceof URL) {\n url = input.href;\n } else {\n url = (input as Request).url;\n }\n const method = init?.method || request?.method || \"GET\";\n const headers = init?.headers || (request ? request.headers : {});\n const body = (init?.body ?? request?.body) as string | null | undefined;\n const signal = init?.signal || request?.signal;\n\n return new Promise((resolve, reject) => {\n // Reject immediately if signal is already aborted (per fetch spec)\n if (signal?.aborted) {\n reject(createAbortError());\n return;\n }\n\n const xhr = new XMLHttpRequest();\n xhr.open(method, url);\n\n // Default 60s timeout to prevent hanging on stalled mobile connections\n // (WiFi→cellular transitions, tunnels, serverless cold starts).\n // Callers can still use AbortSignal.timeout() for finer control.\n xhr.timeout = 60_000;\n\n let headerEntries: [string, string][];\n if (headers instanceof Headers) {\n headerEntries = Array.from(headers.entries());\n } else if (Array.isArray(headers)) {\n headerEntries = headers as [string, string][];\n } else {\n headerEntries = Object.entries(headers as Record<string, string>);\n }\n for (const [key, value] of headerEntries) {\n xhr.setRequestHeader(key, value as string);\n }\n\n xhr.responseType = \"text\";\n\n let streamController: ReadableStreamDefaultController<Uint8Array> | null =\n null;\n let lastIndex = 0;\n let streamClosed = false;\n let settled = false;\n const encoder = new TextEncoder();\n\n // Promise that resolves/rejects when XHR completes or fails\n let resolveFullText: (text: string) => void;\n let rejectFullText: (error: Error) => void;\n const fullTextPromise = new Promise<string>((res, rej) => {\n resolveFullText = res;\n rejectFullText = rej;\n });\n // Prevent unhandled rejection when error occurs but .text()/.json() is never called\n fullTextPromise.catch(() => {});\n\n function closeStream() {\n if (streamController && !streamClosed) {\n streamClosed = true;\n streamController.close();\n }\n }\n\n function errorStream(err: Error) {\n if (streamController && !streamClosed) {\n streamClosed = true;\n streamController.error(err);\n }\n }\n\n function flushChunks() {\n if (\n streamController &&\n !streamClosed &&\n xhr.responseText.length > lastIndex\n ) {\n const newData = xhr.responseText.slice(lastIndex);\n lastIndex = xhr.responseText.length;\n streamController.enqueue(encoder.encode(newData));\n }\n }\n\n /** Centralized error handler — errors the stream, rejects fullTextPromise,\n * and rejects the outer fetch promise if not yet settled. */\n function fail(err: Error) {\n cleanupAbortListener();\n errorStream(err);\n rejectFullText(err);\n if (!settled) {\n settled = true;\n reject(err);\n }\n }\n\n const onAbort = () => {\n fail(createAbortError());\n xhr.abort();\n };\n\n if (signal) {\n signal.addEventListener(\"abort\", onAbort);\n }\n\n function cleanupAbortListener() {\n if (signal) {\n signal.removeEventListener(\"abort\", onAbort);\n }\n }\n\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n streamController = controller;\n },\n cancel() {\n xhr.abort();\n rejectFullText(createAbortError());\n },\n });\n\n // All XHR callbacks are wrapped with setTimeout(fn, 0) to ensure they\n // run on the JS thread. In React Native, XHR callbacks may fire on a\n // native networking thread; calling streamController.enqueue() there\n // triggers downstream React setState on the wrong thread, which causes\n // iOS to kill the process (\"deleted thread with uncommitted CATransaction\").\n // setTimeout(fn, 0) defers execution to the JS event loop (main thread\n // in Hermes) with negligible latency — streaming still feels real-time.\n\n xhr.onprogress = function () {\n setTimeout(() => {\n try {\n flushChunks();\n } catch (err) {\n fail(err instanceof Error ? err : new Error(String(err)));\n xhr.abort();\n }\n }, 0);\n };\n\n xhr.onload = function () {\n setTimeout(() => {\n cleanupAbortListener();\n try {\n flushChunks();\n } catch (err) {\n fail(err instanceof Error ? err : new Error(String(err)));\n return;\n }\n closeStream();\n resolveFullText(xhr.responseText);\n }, 0);\n };\n\n xhr.onerror = function () {\n setTimeout(() => {\n fail(new TypeError(\"Network request failed\"));\n }, 0);\n };\n\n xhr.ontimeout = function () {\n setTimeout(() => {\n fail(new TypeError(\"Network request timed out\"));\n }, 0);\n };\n\n // Resolve with Response once headers arrive.\n // Guard against status === 0 which XHR produces for CORS failures,\n // DNS errors, and mixed-content blocks — let onerror handle those.\n let resp: StreamingFetchResponse | null = null;\n xhr.onreadystatechange = function () {\n // Capture XHR state synchronously before deferring — XHR properties\n // may change between now and when setTimeout fires.\n const readyState = xhr.readyState;\n const xhrStatus = xhr.status;\n const xhrStatusText = xhr.statusText;\n const rawHeaders = xhr.getAllResponseHeaders() || \"\";\n\n setTimeout(() => {\n // Safety net: if XHR completed but we never resolved/rejected, fail explicitly.\n // This can happen when status === 0 and onerror doesn't fire (some RN networking impls).\n if (readyState === 4 && !settled && !resp) {\n fail(\n new TypeError(\n `Network request to ${url} completed with status ${xhrStatus} but no response was produced. ` +\n `This may indicate a CORS failure, DNS error, or React Native networking issue.`,\n ),\n );\n return;\n }\n\n if (readyState >= 2 && !resp && xhrStatus !== 0) {\n const respHeaders: Record<string, string> = {};\n for (const line of rawHeaders.trim().split(\"\\r\\n\")) {\n const idx = line.indexOf(\": \");\n if (idx > 0) {\n respHeaders[line.slice(0, idx).toLowerCase()] = line.slice(\n idx + 2,\n );\n }\n }\n\n const responseHeaders = new Headers(respHeaders);\n\n let bodyUsed = false;\n\n resp = {\n // Duck-typed Response object (not a native Response instance)\n ok: xhrStatus >= 200 && xhrStatus < 300,\n status: xhrStatus,\n statusText: xhrStatusText,\n url: url,\n type: \"basic\",\n redirected: false,\n get bodyUsed() {\n return bodyUsed;\n },\n headers: responseHeaders,\n body: stream,\n json: async () => {\n bodyUsed = true;\n const text = await fullTextPromise;\n try {\n return JSON.parse(text);\n } catch (e) {\n throw new TypeError(\n `Failed to parse JSON from ${method} ${url} (status ${xhrStatus}): ${\n text.length > 200 ? text.slice(0, 200) + \"...\" : text\n }`,\n );\n }\n },\n text: async () => {\n bodyUsed = true;\n return fullTextPromise;\n },\n arrayBuffer: async () => {\n bodyUsed = true;\n return encoder.encode(await fullTextPromise).buffer;\n },\n blob: async () => {\n bodyUsed = true;\n const buf = encoder.encode(await fullTextPromise);\n if (typeof Blob !== \"undefined\") {\n return new Blob([buf], {\n type: responseHeaders.get(\"content-type\") || \"\",\n });\n }\n throw new Error(\n \"Blob is not available in this React Native environment.\",\n );\n },\n clone: () => {\n throw new Error(\n \"Response.clone() is not supported by the React Native streaming fetch polyfill.\",\n );\n },\n formData: async () => {\n throw new Error(\n \"Response.formData() is not supported by the React Native streaming fetch polyfill.\",\n );\n },\n };\n settled = true;\n // NOTE: abort listener is NOT removed here — the signal must remain\n // wired to xhr.abort() for mid-stream cancellation. Cleanup happens\n // in terminal handlers (onload, onerror, ontimeout) or onAbort itself.\n resolve(resp as unknown as Response);\n }\n }, 0);\n };\n\n xhr.send(body ?? null);\n });\n };\n\n // Expose original fetch for opt-out (e.g., third-party libs that need native behavior)\n (streamingFetch as any).__originalFetch = originalFetch;\n global.fetch = streamingFetch;\n}\n","/**\n * All polyfills required for CopilotKit to work in React Native.\n *\n * These are auto-imported when `@copilotkit/react-native` is loaded.\n * A manual `import \"@copilotkit/react-native/polyfills\"` is no longer\n * required but still works for advanced / selective bootstrap scenarios.\n *\n * For granular control, import individual polyfills instead:\n * import \"@copilotkit/react-native/polyfills/streams\";\n * import \"@copilotkit/react-native/polyfills/encoding\";\n * import \"@copilotkit/react-native/polyfills/crypto\";\n * import \"@copilotkit/react-native/polyfills/dom\";\n * import \"@copilotkit/react-native/polyfills/location\";\n */\n\nimport \"./polyfills/streams\";\nimport \"./polyfills/encoding\";\nimport \"./polyfills/crypto\";\nimport \"./polyfills/dom\";\nimport \"./polyfills/location\";\n\nimport { installStreamingFetch } from \"./streaming-fetch\";\ninstallStreamingFetch();\n"],"mappings":";;AA0CA,SAAS,mBAAiC;AACxC,QAAO,IAAK,OAAe,aACzB,8BACA,aACD;;AAGH,SAAgB,wBAA8B;AAG5C,KAAI;EACF,MAAM,eAAe,IAAI,SAAS,GAAG;AACrC,MACE,aAAa,QAAQ,QACrB,OAAO,aAAa,KAAK,cAAc,WAEvC;UAEK,GAAG;AAEV,MACE,WACA,aAAa,SACb,EAAE,aAAa,mBACf,EAAE,aAAa,WAEf,SAAQ,KACN,0GAEA,EACD;;CAIL,MAAM,gBAAgB,OAAO;CAC7B,MAAM,cAAc,OAAO;CAE3B,MAAM,iBAAiB,SAAS,eAC9B,OACA,MACmB;EAEnB,MAAM,UACJ,OAAO,UAAU,YAAY,EAAE,iBAAiB,OAAO,QAAQ;EACjE,IAAI;AACJ,MAAI,OAAO,UAAU,SACnB,OAAM;WACG,iBAAiB,IAC1B,OAAM,MAAM;MAEZ,OAAO,MAAkB;EAE3B,MAAM,SAAS,MAAM,UAAU,SAAS,UAAU;EAClD,MAAM,UAAU,MAAM,YAAY,UAAU,QAAQ,UAAU,EAAE;EAChE,MAAM,OAAQ,MAAM,QAAQ,SAAS;EACrC,MAAM,SAAS,MAAM,UAAU,SAAS;AAExC,SAAO,IAAI,SAAS,SAAS,WAAW;AAEtC,OAAI,QAAQ,SAAS;AACnB,WAAO,kBAAkB,CAA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M,EACR,aAAY,KAAK,MAAM,GAAG,IAAI,CAAC,aAAa,IAAI,KAAK,MACnD,MAAM,EACP;;MAIL,MAAM,kBAAkB,IAAI,QAAQ,YAAY;MAEhD,IAAI,WAAW;AAEf,aAAO;OAEL,IAAI,aAAa,OAAO,YAAY;OACpC,QAAQ;OACR,YAAY;OACP;OACL,MAAM;OACN,YAAY;OACZ,IAAI,WAAW;AACb,eAAO;;OAET,SAAS;OACT,MAAM;OACN,MAAM,YAAY;AAChB,mBAAW;QACX,MAAM,OAAO,MAAM;AACnB,YAAI;AACF,gBAAO,KAAK,MAAM,KAAK;iBAChB,GAAG;AACV,eAAM,IAAI,UACR,6BAA6B,OAAO,GAAG,IAAI,WAAW,UAAU,KAC9D,KAAK,SAAS,MAAM,KAAK,MAAM,GAAG,IAAI,GAAG,QAAQ,OAEpD;;;OAGL,MAAM,YAAY;AAChB,mBAAW;AACX,eAAO;;OAET,aAAa,YAAY;AACvB,mBAAW;AACX,eAAO,QAAQ,OAAO,MAAM,gBAAgB,CAAC;;OAE/C,MAAM,YAAY;AAChB,mBAAW;QACX,MAAM,MAAM,QAAQ,OAAO,MAAM,gBAAgB;AACjD,YAAI,OAAO,SAAS,YAClB,QAAO,IAAI,KAAK,CAAC,IAAI,EAAE,EACrB,MAAM,gBAAgB,IAAI,eAAe,IAAI,IAC9C,CAAC;AAEJ,cAAM,IAAI,MACR,0DACD;;OAEH,aAAa;AACX,cAAM,IAAI,MACR,kFACD;;OAEH,UAAU,YAAY;AACpB,cAAM,IAAI,MACR,qFACD;;OAEJ;AACD,gBAAU;AAIV,cAAQ,KAA4B;;OAErC,EAAE;;AAGP,OAAI,KAAK,QAAQ,KAAK;IACtB;;AAIJ,CAAC,eAAuB,kBAAkB;AAC1C,QAAO,QAAQ;;;;;ACvVjB,uBAAuB"}
|
|
1
|
+
{"version":3,"file":"polyfills.cjs","names":[],"sources":["../src/streaming-fetch.ts","../src/polyfills.ts"],"sourcesContent":["/**\n * Streaming fetch implementation for React Native.\n *\n * React Native's built-in fetch doesn't support response.body.getReader()\n * (ReadableStream). This replaces global.fetch with an XHR-based\n * implementation that streams chunks via ReadableStream, enabling\n * CopilotKit's SSE-based agent communication.\n *\n * If native fetch already supports ReadableStream bodies (newer RN / Hermes),\n * the replacement is skipped entirely.\n *\n * THREADING NOTE: In React Native, XHR callbacks (onprogress, onload, etc.)\n * may fire on a native networking thread. Pushing data into the ReadableStream\n * from that thread can trigger downstream React setState calls on the wrong\n * thread, causing iOS to kill the process with \"deleted thread with uncommitted\n * CATransaction\". All stream-mutating operations are therefore deferred via\n * setTimeout(fn, 0) to bounce back to the JS thread (main thread in Hermes).\n *\n * Call `installStreamingFetch()` once at app startup after polyfills.\n */\n\ndeclare const global: typeof globalThis;\n\n/** Subset of the Response interface implemented by the streaming fetch polyfill. */\ninterface StreamingFetchResponse {\n readonly ok: boolean;\n readonly status: number;\n readonly statusText: string;\n readonly url: string;\n readonly type: string;\n readonly redirected: boolean;\n readonly bodyUsed: boolean;\n readonly headers: Headers;\n readonly body: ReadableStream<Uint8Array>;\n json(): Promise<unknown>;\n text(): Promise<string>;\n arrayBuffer(): Promise<ArrayBuffer>;\n blob(): Promise<Blob>;\n clone(): never;\n formData(): Promise<never>;\n}\n\nfunction createAbortError(): DOMException {\n return new (global as any).DOMException(\n \"The operation was aborted.\",\n \"AbortError\",\n );\n}\n\nexport function installStreamingFetch(): void {\n // Skip if native fetch already supports ReadableStream body.\n // Newer React Native versions (Hermes) may support this natively.\n try {\n const testResponse = new Response(\"\");\n if (\n testResponse.body != null &&\n typeof testResponse.body.getReader === \"function\"\n ) {\n return;\n }\n } catch (e) {\n // Response constructor unavailable — expected in older RN environments.\n if (\n __DEV__ &&\n e instanceof Error &&\n !(e instanceof ReferenceError) &&\n !(e instanceof TypeError)\n ) {\n console.warn(\n \"[CopilotKit] Unexpected error during streaming fetch feature detection, \" +\n \"installing XHR-based polyfill:\",\n e,\n );\n }\n }\n\n const originalFetch = global.fetch;\n const TextEncoder = global.TextEncoder;\n\n const streamingFetch = function streamingFetch(\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> {\n // Extract defaults from Request object when input is a Request\n const request =\n typeof input !== \"string\" && !(input instanceof URL) ? input : null;\n let url: string;\n if (typeof input === \"string\") {\n url = input;\n } else if (input instanceof URL) {\n url = input.href;\n } else {\n url = (input as Request).url;\n }\n const method = init?.method || request?.method || \"GET\";\n const headers = init?.headers || (request ? request.headers : {});\n const body = (init?.body ?? request?.body) as string | null | undefined;\n const signal = init?.signal || request?.signal;\n\n return new Promise((resolve, reject) => {\n // Reject immediately if signal is already aborted (per fetch spec)\n if (signal?.aborted) {\n reject(createAbortError());\n return;\n }\n\n const xhr = new XMLHttpRequest();\n xhr.open(method, url);\n\n // Default 60s timeout to prevent hanging on stalled mobile connections\n // (WiFi→cellular transitions, tunnels, serverless cold starts).\n // Callers can still use AbortSignal.timeout() for finer control.\n xhr.timeout = 60_000;\n\n let headerEntries: [string, string][];\n if (headers instanceof Headers) {\n headerEntries = Array.from(headers.entries());\n } else if (Array.isArray(headers)) {\n headerEntries = headers as [string, string][];\n } else {\n headerEntries = Object.entries(headers as Record<string, string>);\n }\n for (const [key, value] of headerEntries) {\n xhr.setRequestHeader(key, value as string);\n }\n\n xhr.responseType = \"text\";\n\n let streamController: ReadableStreamDefaultController<Uint8Array> | null =\n null;\n let lastIndex = 0;\n let streamClosed = false;\n let settled = false;\n const encoder = new TextEncoder();\n\n // Promise that resolves/rejects when XHR completes or fails\n let resolveFullText: (text: string) => void;\n let rejectFullText: (error: Error) => void;\n const fullTextPromise = new Promise<string>((res, rej) => {\n resolveFullText = res;\n rejectFullText = rej;\n });\n // Prevent unhandled rejection when error occurs but .text()/.json() is never called\n fullTextPromise.catch(() => {});\n\n function closeStream() {\n if (streamController && !streamClosed) {\n streamClosed = true;\n streamController.close();\n }\n }\n\n function errorStream(err: Error) {\n if (streamController && !streamClosed) {\n streamClosed = true;\n streamController.error(err);\n }\n }\n\n function flushChunks() {\n if (\n streamController &&\n !streamClosed &&\n xhr.responseText.length > lastIndex\n ) {\n const newData = xhr.responseText.slice(lastIndex);\n lastIndex = xhr.responseText.length;\n streamController.enqueue(encoder.encode(newData));\n }\n }\n\n /** Centralized error handler — errors the stream, rejects fullTextPromise,\n * and rejects the outer fetch promise if not yet settled. */\n function fail(err: Error) {\n cleanupAbortListener();\n errorStream(err);\n rejectFullText(err);\n if (!settled) {\n settled = true;\n reject(err);\n }\n }\n\n const onAbort = () => {\n fail(createAbortError());\n xhr.abort();\n };\n\n if (signal) {\n signal.addEventListener(\"abort\", onAbort);\n }\n\n function cleanupAbortListener() {\n if (signal) {\n signal.removeEventListener(\"abort\", onAbort);\n }\n }\n\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n streamController = controller;\n },\n cancel() {\n xhr.abort();\n rejectFullText(createAbortError());\n },\n });\n\n // All XHR callbacks are wrapped with setTimeout(fn, 0) to ensure they\n // run on the JS thread. In React Native, XHR callbacks may fire on a\n // native networking thread; calling streamController.enqueue() there\n // triggers downstream React setState on the wrong thread, which causes\n // iOS to kill the process (\"deleted thread with uncommitted CATransaction\").\n // setTimeout(fn, 0) defers execution to the JS event loop (main thread\n // in Hermes) with negligible latency — streaming still feels real-time.\n\n xhr.onprogress = function () {\n setTimeout(() => {\n try {\n flushChunks();\n } catch (err) {\n fail(err instanceof Error ? err : new Error(String(err)));\n xhr.abort();\n }\n }, 0);\n };\n\n xhr.onload = function () {\n setTimeout(() => {\n cleanupAbortListener();\n try {\n flushChunks();\n } catch (err) {\n fail(err instanceof Error ? err : new Error(String(err)));\n return;\n }\n closeStream();\n resolveFullText(xhr.responseText);\n }, 0);\n };\n\n xhr.onerror = function () {\n setTimeout(() => {\n fail(new TypeError(\"Network request failed\"));\n }, 0);\n };\n\n xhr.ontimeout = function () {\n setTimeout(() => {\n fail(new TypeError(\"Network request timed out\"));\n }, 0);\n };\n\n // Resolve with Response once headers arrive.\n // Guard against status === 0 which XHR produces for CORS failures,\n // DNS errors, and mixed-content blocks — let onerror handle those.\n let resp: StreamingFetchResponse | null = null;\n xhr.onreadystatechange = function () {\n // Capture XHR state synchronously before deferring — XHR properties\n // may change between now and when setTimeout fires.\n const readyState = xhr.readyState;\n const xhrStatus = xhr.status;\n const xhrStatusText = xhr.statusText;\n const rawHeaders = xhr.getAllResponseHeaders() || \"\";\n\n setTimeout(() => {\n // Safety net: if XHR completed but we never resolved/rejected, fail explicitly.\n // This can happen when status === 0 and onerror doesn't fire (some RN networking impls).\n if (readyState === 4 && !settled && !resp) {\n fail(\n new TypeError(\n `Network request to ${url} completed with status ${xhrStatus} but no response was produced. ` +\n `This may indicate a CORS failure, DNS error, or React Native networking issue.`,\n ),\n );\n return;\n }\n\n if (readyState >= 2 && !resp && xhrStatus !== 0) {\n const respHeaders: Record<string, string> = {};\n for (const line of rawHeaders.trim().split(\"\\r\\n\")) {\n const idx = line.indexOf(\": \");\n if (idx > 0) {\n respHeaders[line.slice(0, idx).toLowerCase()] = line.slice(\n idx + 2,\n );\n }\n }\n\n const responseHeaders = new Headers(respHeaders);\n\n let bodyUsed = false;\n\n resp = {\n // Duck-typed Response object (not a native Response instance)\n ok: xhrStatus >= 200 && xhrStatus < 300,\n status: xhrStatus,\n statusText: xhrStatusText,\n url: url,\n type: \"basic\",\n redirected: false,\n get bodyUsed() {\n return bodyUsed;\n },\n headers: responseHeaders,\n body: stream,\n json: async () => {\n bodyUsed = true;\n const text = await fullTextPromise;\n try {\n return JSON.parse(text);\n } catch (e) {\n throw new TypeError(\n `Failed to parse JSON from ${method} ${url} (status ${xhrStatus}): ${\n text.length > 200 ? text.slice(0, 200) + \"...\" : text\n }`,\n { cause: e },\n );\n }\n },\n text: async () => {\n bodyUsed = true;\n return fullTextPromise;\n },\n arrayBuffer: async () => {\n bodyUsed = true;\n return encoder.encode(await fullTextPromise).buffer;\n },\n blob: async () => {\n bodyUsed = true;\n const buf = encoder.encode(await fullTextPromise);\n if (typeof Blob !== \"undefined\") {\n return new Blob([buf], {\n type: responseHeaders.get(\"content-type\") || \"\",\n });\n }\n throw new Error(\n \"Blob is not available in this React Native environment.\",\n );\n },\n clone: () => {\n throw new Error(\n \"Response.clone() is not supported by the React Native streaming fetch polyfill.\",\n );\n },\n formData: async () => {\n throw new Error(\n \"Response.formData() is not supported by the React Native streaming fetch polyfill.\",\n );\n },\n };\n settled = true;\n // NOTE: abort listener is NOT removed here — the signal must remain\n // wired to xhr.abort() for mid-stream cancellation. Cleanup happens\n // in terminal handlers (onload, onerror, ontimeout) or onAbort itself.\n resolve(resp as unknown as Response);\n }\n }, 0);\n };\n\n xhr.send(body ?? null);\n });\n };\n\n // Expose original fetch for opt-out (e.g., third-party libs that need native behavior)\n (streamingFetch as any).__originalFetch = originalFetch;\n global.fetch = streamingFetch as typeof fetch;\n}\n","/**\n * All polyfills required for CopilotKit to work in React Native.\n *\n * These are auto-imported when `@copilotkit/react-native` is loaded.\n * A manual `import \"@copilotkit/react-native/polyfills\"` is no longer\n * required but still works for advanced / selective bootstrap scenarios.\n *\n * For granular control, import individual polyfills instead:\n * import \"@copilotkit/react-native/polyfills/streams\";\n * import \"@copilotkit/react-native/polyfills/encoding\";\n * import \"@copilotkit/react-native/polyfills/crypto\";\n * import \"@copilotkit/react-native/polyfills/dom\";\n * import \"@copilotkit/react-native/polyfills/location\";\n */\n\nimport \"./polyfills/streams\";\nimport \"./polyfills/encoding\";\nimport \"./polyfills/crypto\";\nimport \"./polyfills/dom\";\nimport \"./polyfills/location\";\n\nimport { installStreamingFetch } from \"./streaming-fetch\";\ninstallStreamingFetch();\n"],"mappings":";;AA0CA,SAAS,mBAAiC;AACxC,QAAO,IAAK,OAAe,aACzB,8BACA,aACD;;AAGH,SAAgB,wBAA8B;AAG5C,KAAI;EACF,MAAM,eAAe,IAAI,SAAS,GAAG;AACrC,MACE,aAAa,QAAQ,QACrB,OAAO,aAAa,KAAK,cAAc,WAEvC;UAEK,GAAG;AAEV,MACE,WACA,aAAa,SACb,EAAE,aAAa,m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AC;;OAE/C,MAAM,YAAY;AAChB,mBAAW;QACX,MAAM,MAAM,QAAQ,OAAO,MAAM,gBAAgB;AACjD,YAAI,OAAO,SAAS,YAClB,QAAO,IAAI,KAAK,CAAC,IAAI,EAAE,EACrB,MAAM,gBAAgB,IAAI,eAAe,IAAI,IAC9C,CAAC;AAEJ,cAAM,IAAI,MACR,0DACD;;OAEH,aAAa;AACX,cAAM,IAAI,MACR,kFACD;;OAEH,UAAU,YAAY;AACpB,cAAM,IAAI,MACR,qFACD;;OAEJ;AACD,gBAAU;AAIV,cAAQ,KAA4B;;OAErC,EAAE;;AAGP,OAAI,KAAK,QAAQ,KAAK;IACtB;;AAIJ,CAAC,eAAuB,kBAAkB;AAC1C,QAAO,QAAQ;;;;;ACxVjB,uBAAuB"}
|
package/dist/polyfills.mjs
CHANGED
|
@@ -164,7 +164,7 @@ function installStreamingFetch() {
|
|
|
164
164
|
try {
|
|
165
165
|
return JSON.parse(text);
|
|
166
166
|
} catch (e) {
|
|
167
|
-
throw new TypeError(`Failed to parse JSON from ${method} ${url} (status ${xhrStatus}): ${text.length > 200 ? text.slice(0, 200) + "..." : text}
|
|
167
|
+
throw new TypeError(`Failed to parse JSON from ${method} ${url} (status ${xhrStatus}): ${text.length > 200 ? text.slice(0, 200) + "..." : text}`, { cause: e });
|
|
168
168
|
}
|
|
169
169
|
},
|
|
170
170
|
text: async () => {
|
package/dist/polyfills.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"polyfills.mjs","names":[],"sources":["../src/streaming-fetch.ts","../src/polyfills.ts"],"sourcesContent":["/**\n * Streaming fetch implementation for React Native.\n *\n * React Native's built-in fetch doesn't support response.body.getReader()\n * (ReadableStream). This replaces global.fetch with an XHR-based\n * implementation that streams chunks via ReadableStream, enabling\n * CopilotKit's SSE-based agent communication.\n *\n * If native fetch already supports ReadableStream bodies (newer RN / Hermes),\n * the replacement is skipped entirely.\n *\n * THREADING NOTE: In React Native, XHR callbacks (onprogress, onload, etc.)\n * may fire on a native networking thread. Pushing data into the ReadableStream\n * from that thread can trigger downstream React setState calls on the wrong\n * thread, causing iOS to kill the process with \"deleted thread with uncommitted\n * CATransaction\". All stream-mutating operations are therefore deferred via\n * setTimeout(fn, 0) to bounce back to the JS thread (main thread in Hermes).\n *\n * Call `installStreamingFetch()` once at app startup after polyfills.\n */\n\ndeclare const global: typeof globalThis;\n\n/** Subset of the Response interface implemented by the streaming fetch polyfill. */\ninterface StreamingFetchResponse {\n readonly ok: boolean;\n readonly status: number;\n readonly statusText: string;\n readonly url: string;\n readonly type: string;\n readonly redirected: boolean;\n readonly bodyUsed: boolean;\n readonly headers: Headers;\n readonly body: ReadableStream<Uint8Array>;\n json(): Promise<unknown>;\n text(): Promise<string>;\n arrayBuffer(): Promise<ArrayBuffer>;\n blob(): Promise<Blob>;\n clone(): never;\n formData(): Promise<never>;\n}\n\nfunction createAbortError(): DOMException {\n return new (global as any).DOMException(\n \"The operation was aborted.\",\n \"AbortError\",\n );\n}\n\nexport function installStreamingFetch(): void {\n // Skip if native fetch already supports ReadableStream body.\n // Newer React Native versions (Hermes) may support this natively.\n try {\n const testResponse = new Response(\"\");\n if (\n testResponse.body != null &&\n typeof testResponse.body.getReader === \"function\"\n ) {\n return;\n }\n } catch (e) {\n // Response constructor unavailable — expected in older RN environments.\n if (\n __DEV__ &&\n e instanceof Error &&\n !(e instanceof ReferenceError) &&\n !(e instanceof TypeError)\n ) {\n console.warn(\n \"[CopilotKit] Unexpected error during streaming fetch feature detection, \" +\n \"installing XHR-based polyfill:\",\n e,\n );\n }\n }\n\n const originalFetch = global.fetch;\n const TextEncoder = global.TextEncoder;\n\n const streamingFetch = function streamingFetch(\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> {\n // Extract defaults from Request object when input is a Request\n const request =\n typeof input !== \"string\" && !(input instanceof URL) ? input : null;\n let url: string;\n if (typeof input === \"string\") {\n url = input;\n } else if (input instanceof URL) {\n url = input.href;\n } else {\n url = (input as Request).url;\n }\n const method = init?.method || request?.method || \"GET\";\n const headers = init?.headers || (request ? request.headers : {});\n const body = (init?.body ?? request?.body) as string | null | undefined;\n const signal = init?.signal || request?.signal;\n\n return new Promise((resolve, reject) => {\n // Reject immediately if signal is already aborted (per fetch spec)\n if (signal?.aborted) {\n reject(createAbortError());\n return;\n }\n\n const xhr = new XMLHttpRequest();\n xhr.open(method, url);\n\n // Default 60s timeout to prevent hanging on stalled mobile connections\n // (WiFi→cellular transitions, tunnels, serverless cold starts).\n // Callers can still use AbortSignal.timeout() for finer control.\n xhr.timeout = 60_000;\n\n let headerEntries: [string, string][];\n if (headers instanceof Headers) {\n headerEntries = Array.from(headers.entries());\n } else if (Array.isArray(headers)) {\n headerEntries = headers as [string, string][];\n } else {\n headerEntries = Object.entries(headers as Record<string, string>);\n }\n for (const [key, value] of headerEntries) {\n xhr.setRequestHeader(key, value as string);\n }\n\n xhr.responseType = \"text\";\n\n let streamController: ReadableStreamDefaultController<Uint8Array> | null =\n null;\n let lastIndex = 0;\n let streamClosed = false;\n let settled = false;\n const encoder = new TextEncoder();\n\n // Promise that resolves/rejects when XHR completes or fails\n let resolveFullText: (text: string) => void;\n let rejectFullText: (error: Error) => void;\n const fullTextPromise = new Promise<string>((res, rej) => {\n resolveFullText = res;\n rejectFullText = rej;\n });\n // Prevent unhandled rejection when error occurs but .text()/.json() is never called\n fullTextPromise.catch(() => {});\n\n function closeStream() {\n if (streamController && !streamClosed) {\n streamClosed = true;\n streamController.close();\n }\n }\n\n function errorStream(err: Error) {\n if (streamController && !streamClosed) {\n streamClosed = true;\n streamController.error(err);\n }\n }\n\n function flushChunks() {\n if (\n streamController &&\n !streamClosed &&\n xhr.responseText.length > lastIndex\n ) {\n const newData = xhr.responseText.slice(lastIndex);\n lastIndex = xhr.responseText.length;\n streamController.enqueue(encoder.encode(newData));\n }\n }\n\n /** Centralized error handler — errors the stream, rejects fullTextPromise,\n * and rejects the outer fetch promise if not yet settled. */\n function fail(err: Error) {\n cleanupAbortListener();\n errorStream(err);\n rejectFullText(err);\n if (!settled) {\n settled = true;\n reject(err);\n }\n }\n\n const onAbort = () => {\n fail(createAbortError());\n xhr.abort();\n };\n\n if (signal) {\n signal.addEventListener(\"abort\", onAbort);\n }\n\n function cleanupAbortListener() {\n if (signal) {\n signal.removeEventListener(\"abort\", onAbort);\n }\n }\n\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n streamController = controller;\n },\n cancel() {\n xhr.abort();\n rejectFullText(createAbortError());\n },\n });\n\n // All XHR callbacks are wrapped with setTimeout(fn, 0) to ensure they\n // run on the JS thread. In React Native, XHR callbacks may fire on a\n // native networking thread; calling streamController.enqueue() there\n // triggers downstream React setState on the wrong thread, which causes\n // iOS to kill the process (\"deleted thread with uncommitted CATransaction\").\n // setTimeout(fn, 0) defers execution to the JS event loop (main thread\n // in Hermes) with negligible latency — streaming still feels real-time.\n\n xhr.onprogress = function () {\n setTimeout(() => {\n try {\n flushChunks();\n } catch (err) {\n fail(err instanceof Error ? err : new Error(String(err)));\n xhr.abort();\n }\n }, 0);\n };\n\n xhr.onload = function () {\n setTimeout(() => {\n cleanupAbortListener();\n try {\n flushChunks();\n } catch (err) {\n fail(err instanceof Error ? err : new Error(String(err)));\n return;\n }\n closeStream();\n resolveFullText(xhr.responseText);\n }, 0);\n };\n\n xhr.onerror = function () {\n setTimeout(() => {\n fail(new TypeError(\"Network request failed\"));\n }, 0);\n };\n\n xhr.ontimeout = function () {\n setTimeout(() => {\n fail(new TypeError(\"Network request timed out\"));\n }, 0);\n };\n\n // Resolve with Response once headers arrive.\n // Guard against status === 0 which XHR produces for CORS failures,\n // DNS errors, and mixed-content blocks — let onerror handle those.\n let resp: StreamingFetchResponse | null = null;\n xhr.onreadystatechange = function () {\n // Capture XHR state synchronously before deferring — XHR properties\n // may change between now and when setTimeout fires.\n const readyState = xhr.readyState;\n const xhrStatus = xhr.status;\n const xhrStatusText = xhr.statusText;\n const rawHeaders = xhr.getAllResponseHeaders() || \"\";\n\n setTimeout(() => {\n // Safety net: if XHR completed but we never resolved/rejected, fail explicitly.\n // This can happen when status === 0 and onerror doesn't fire (some RN networking impls).\n if (readyState === 4 && !settled && !resp) {\n fail(\n new TypeError(\n `Network request to ${url} completed with status ${xhrStatus} but no response was produced. ` +\n `This may indicate a CORS failure, DNS error, or React Native networking issue.`,\n ),\n );\n return;\n }\n\n if (readyState >= 2 && !resp && xhrStatus !== 0) {\n const respHeaders: Record<string, string> = {};\n for (const line of rawHeaders.trim().split(\"\\r\\n\")) {\n const idx = line.indexOf(\": \");\n if (idx > 0) {\n respHeaders[line.slice(0, idx).toLowerCase()] = line.slice(\n idx + 2,\n );\n }\n }\n\n const responseHeaders = new Headers(respHeaders);\n\n let bodyUsed = false;\n\n resp = {\n // Duck-typed Response object (not a native Response instance)\n ok: xhrStatus >= 200 && xhrStatus < 300,\n status: xhrStatus,\n statusText: xhrStatusText,\n url: url,\n type: \"basic\",\n redirected: false,\n get bodyUsed() {\n return bodyUsed;\n },\n headers: responseHeaders,\n body: stream,\n json: async () => {\n bodyUsed = true;\n const text = await fullTextPromise;\n try {\n return JSON.parse(text);\n } catch (e) {\n throw new TypeError(\n `Failed to parse JSON from ${method} ${url} (status ${xhrStatus}): ${\n text.length > 200 ? text.slice(0, 200) + \"...\" : text\n }`,\n );\n }\n },\n text: async () => {\n bodyUsed = true;\n return fullTextPromise;\n },\n arrayBuffer: async () => {\n bodyUsed = true;\n return encoder.encode(await fullTextPromise).buffer;\n },\n blob: async () => {\n bodyUsed = true;\n const buf = encoder.encode(await fullTextPromise);\n if (typeof Blob !== \"undefined\") {\n return new Blob([buf], {\n type: responseHeaders.get(\"content-type\") || \"\",\n });\n }\n throw new Error(\n \"Blob is not available in this React Native environment.\",\n );\n },\n clone: () => {\n throw new Error(\n \"Response.clone() is not supported by the React Native streaming fetch polyfill.\",\n );\n },\n formData: async () => {\n throw new Error(\n \"Response.formData() is not supported by the React Native streaming fetch polyfill.\",\n );\n },\n };\n settled = true;\n // NOTE: abort listener is NOT removed here — the signal must remain\n // wired to xhr.abort() for mid-stream cancellation. Cleanup happens\n // in terminal handlers (onload, onerror, ontimeout) or onAbort itself.\n resolve(resp as unknown as Response);\n }\n }, 0);\n };\n\n xhr.send(body ?? null);\n });\n };\n\n // Expose original fetch for opt-out (e.g., third-party libs that need native behavior)\n (streamingFetch as any).__originalFetch = originalFetch;\n global.fetch = streamingFetch;\n}\n","/**\n * All polyfills required for CopilotKit to work in React Native.\n *\n * These are auto-imported when `@copilotkit/react-native` is loaded.\n * A manual `import \"@copilotkit/react-native/polyfills\"` is no longer\n * required but still works for advanced / selective bootstrap scenarios.\n *\n * For granular control, import individual polyfills instead:\n * import \"@copilotkit/react-native/polyfills/streams\";\n * import \"@copilotkit/react-native/polyfills/encoding\";\n * import \"@copilotkit/react-native/polyfills/crypto\";\n * import \"@copilotkit/react-native/polyfills/dom\";\n * import \"@copilotkit/react-native/polyfills/location\";\n */\n\nimport \"./polyfills/streams\";\nimport \"./polyfills/encoding\";\nimport \"./polyfills/crypto\";\nimport \"./polyfills/dom\";\nimport \"./polyfills/location\";\n\nimport { installStreamingFetch } from \"./streaming-fetch\";\ninstallStreamingFetch();\n"],"mappings":";AA0CA,SAAS,mBAAiC;AACxC,QAAO,IAAK,OAAe,aACzB,8BACA,aACD;;AAGH,SAAgB,wBAA8B;AAG5C,KAAI;EACF,MAAM,eAAe,IAAI,SAAS,GAAG;AACrC,MACE,aAAa,QAAQ,QACrB,OAAO,aAAa,KAAK,cAAc,WAEvC;UAEK,GAAG;AAEV,MACE,WACA,aAAa,SACb,EAAE,aAAa,mBACf,EAAE,aAAa,WAEf,SAAQ,KACN,0GAEA,EACD;;CAIL,MAAM,gBAAgB,OAAO;CAC7B,MAAM,cAAc,OAAO;CAE3B,MAAM,iBAAiB,SAAS,eAC9B,OACA,MACmB;EAEnB,MAAM,UACJ,OAAO,UAAU,YAAY,EAAE,iBAAiB,OAAO,QAAQ;EACjE,IAAI;AACJ,MAAI,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I,MACR,kFACD;;OAEH,UAAU,YAAY;AACpB,cAAM,IAAI,MACR,qFACD;;OAEJ;AACD,gBAAU;AAIV,cAAQ,KAA4B;;OAErC,EAAE;;AAGP,OAAI,KAAK,QAAQ,KAAK;IACtB;;AAIJ,CAAC,eAAuB,kBAAkB;AAC1C,QAAO,QAAQ;;;;;ACvVjB,uBAAuB"}
|
|
1
|
+
{"version":3,"file":"polyfills.mjs","names":[],"sources":["../src/streaming-fetch.ts","../src/polyfills.ts"],"sourcesContent":["/**\n * Streaming fetch implementation for React Native.\n *\n * React Native's built-in fetch doesn't support response.body.getReader()\n * (ReadableStream). This replaces global.fetch with an XHR-based\n * implementation that streams chunks via ReadableStream, enabling\n * CopilotKit's SSE-based agent communication.\n *\n * If native fetch already supports ReadableStream bodies (newer RN / Hermes),\n * the replacement is skipped entirely.\n *\n * THREADING NOTE: In React Native, XHR callbacks (onprogress, onload, etc.)\n * may fire on a native networking thread. Pushing data into the ReadableStream\n * from that thread can trigger downstream React setState calls on the wrong\n * thread, causing iOS to kill the process with \"deleted thread with uncommitted\n * CATransaction\". All stream-mutating operations are therefore deferred via\n * setTimeout(fn, 0) to bounce back to the JS thread (main thread in Hermes).\n *\n * Call `installStreamingFetch()` once at app startup after polyfills.\n */\n\ndeclare const global: typeof globalThis;\n\n/** Subset of the Response interface implemented by the streaming fetch polyfill. */\ninterface StreamingFetchResponse {\n readonly ok: boolean;\n readonly status: number;\n readonly statusText: string;\n readonly url: string;\n readonly type: string;\n readonly redirected: boolean;\n readonly bodyUsed: boolean;\n readonly headers: Headers;\n readonly body: ReadableStream<Uint8Array>;\n json(): Promise<unknown>;\n text(): Promise<string>;\n arrayBuffer(): Promise<ArrayBuffer>;\n blob(): Promise<Blob>;\n clone(): never;\n formData(): Promise<never>;\n}\n\nfunction createAbortError(): DOMException {\n return new (global as any).DOMException(\n \"The operation was aborted.\",\n \"AbortError\",\n );\n}\n\nexport function installStreamingFetch(): void {\n // Skip if native fetch already supports ReadableStream body.\n // Newer React Native versions (Hermes) may support this natively.\n try {\n const testResponse = new Response(\"\");\n if (\n testResponse.body != null &&\n typeof testResponse.body.getReader === \"function\"\n ) {\n return;\n }\n } catch (e) {\n // Response constructor unavailable — expected in older RN environments.\n if (\n __DEV__ &&\n e instanceof Error &&\n !(e instanceof ReferenceError) &&\n !(e instanceof TypeError)\n ) {\n console.warn(\n \"[CopilotKit] Unexpected error during streaming fetch feature detection, \" +\n \"installing XHR-based polyfill:\",\n e,\n );\n }\n }\n\n const originalFetch = global.fetch;\n const TextEncoder = global.TextEncoder;\n\n const streamingFetch = function streamingFetch(\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> {\n // Extract defaults from Request object when input is a Request\n const request =\n typeof input !== \"string\" && !(input instanceof URL) ? input : null;\n let url: string;\n if (typeof input === \"string\") {\n url = input;\n } else if (input instanceof URL) {\n url = input.href;\n } else {\n url = (input as Request).url;\n }\n const method = init?.method || request?.method || \"GET\";\n const headers = init?.headers || (request ? request.headers : {});\n const body = (init?.body ?? request?.body) as string | null | undefined;\n const signal = init?.signal || request?.signal;\n\n return new Promise((resolve, reject) => {\n // Reject immediately if signal is already aborted (per fetch spec)\n if (signal?.aborted) {\n reject(createAbortError());\n return;\n }\n\n const xhr = new XMLHttpRequest();\n xhr.open(method, url);\n\n // Default 60s timeout to prevent hanging on stalled mobile connections\n // (WiFi→cellular transitions, tunnels, serverless cold starts).\n // Callers can still use AbortSignal.timeout() for finer control.\n xhr.timeout = 60_000;\n\n let headerEntries: [string, string][];\n if (headers instanceof Headers) {\n headerEntries = Array.from(headers.entries());\n } else if (Array.isArray(headers)) {\n headerEntries = headers as [string, string][];\n } else {\n headerEntries = Object.entries(headers as Record<string, string>);\n }\n for (const [key, value] of headerEntries) {\n xhr.setRequestHeader(key, value as string);\n }\n\n xhr.responseType = \"text\";\n\n let streamController: ReadableStreamDefaultController<Uint8Array> | null =\n null;\n let lastIndex = 0;\n let streamClosed = false;\n let settled = false;\n const encoder = new TextEncoder();\n\n // Promise that resolves/rejects when XHR completes or fails\n let resolveFullText: (text: string) => void;\n let rejectFullText: (error: Error) => void;\n const fullTextPromise = new Promise<string>((res, rej) => {\n resolveFullText = res;\n rejectFullText = rej;\n });\n // Prevent unhandled rejection when error occurs but .text()/.json() is never called\n fullTextPromise.catch(() => {});\n\n function closeStream() {\n if (streamController && !streamClosed) {\n streamClosed = true;\n streamController.close();\n }\n }\n\n function errorStream(err: Error) {\n if (streamController && !streamClosed) {\n streamClosed = true;\n streamController.error(err);\n }\n }\n\n function flushChunks() {\n if (\n streamController &&\n !streamClosed &&\n xhr.responseText.length > lastIndex\n ) {\n const newData = xhr.responseText.slice(lastIndex);\n lastIndex = xhr.responseText.length;\n streamController.enqueue(encoder.encode(newData));\n }\n }\n\n /** Centralized error handler — errors the stream, rejects fullTextPromise,\n * and rejects the outer fetch promise if not yet settled. */\n function fail(err: Error) {\n cleanupAbortListener();\n errorStream(err);\n rejectFullText(err);\n if (!settled) {\n settled = true;\n reject(err);\n }\n }\n\n const onAbort = () => {\n fail(createAbortError());\n xhr.abort();\n };\n\n if (signal) {\n signal.addEventListener(\"abort\", onAbort);\n }\n\n function cleanupAbortListener() {\n if (signal) {\n signal.removeEventListener(\"abort\", onAbort);\n }\n }\n\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n streamController = controller;\n },\n cancel() {\n xhr.abort();\n rejectFullText(createAbortError());\n },\n });\n\n // All XHR callbacks are wrapped with setTimeout(fn, 0) to ensure they\n // run on the JS thread. In React Native, XHR callbacks may fire on a\n // native networking thread; calling streamController.enqueue() there\n // triggers downstream React setState on the wrong thread, which causes\n // iOS to kill the process (\"deleted thread with uncommitted CATransaction\").\n // setTimeout(fn, 0) defers execution to the JS event loop (main thread\n // in Hermes) with negligible latency — streaming still feels real-time.\n\n xhr.onprogress = function () {\n setTimeout(() => {\n try {\n flushChunks();\n } catch (err) {\n fail(err instanceof Error ? err : new Error(String(err)));\n xhr.abort();\n }\n }, 0);\n };\n\n xhr.onload = function () {\n setTimeout(() => {\n cleanupAbortListener();\n try {\n flushChunks();\n } catch (err) {\n fail(err instanceof Error ? err : new Error(String(err)));\n return;\n }\n closeStream();\n resolveFullText(xhr.responseText);\n }, 0);\n };\n\n xhr.onerror = function () {\n setTimeout(() => {\n fail(new TypeError(\"Network request failed\"));\n }, 0);\n };\n\n xhr.ontimeout = function () {\n setTimeout(() => {\n fail(new TypeError(\"Network request timed out\"));\n }, 0);\n };\n\n // Resolve with Response once headers arrive.\n // Guard against status === 0 which XHR produces for CORS failures,\n // DNS errors, and mixed-content blocks — let onerror handle those.\n let resp: StreamingFetchResponse | null = null;\n xhr.onreadystatechange = function () {\n // Capture XHR state synchronously before deferring — XHR properties\n // may change between now and when setTimeout fires.\n const readyState = xhr.readyState;\n const xhrStatus = xhr.status;\n const xhrStatusText = xhr.statusText;\n const rawHeaders = xhr.getAllResponseHeaders() || \"\";\n\n setTimeout(() => {\n // Safety net: if XHR completed but we never resolved/rejected, fail explicitly.\n // This can happen when status === 0 and onerror doesn't fire (some RN networking impls).\n if (readyState === 4 && !settled && !resp) {\n fail(\n new TypeError(\n `Network request to ${url} completed with status ${xhrStatus} but no response was produced. ` +\n `This may indicate a CORS failure, DNS error, or React Native networking issue.`,\n ),\n );\n return;\n }\n\n if (readyState >= 2 && !resp && xhrStatus !== 0) {\n const respHeaders: Record<string, string> = {};\n for (const line of rawHeaders.trim().split(\"\\r\\n\")) {\n const idx = line.indexOf(\": \");\n if (idx > 0) {\n respHeaders[line.slice(0, idx).toLowerCase()] = line.slice(\n idx + 2,\n );\n }\n }\n\n const responseHeaders = new Headers(respHeaders);\n\n let bodyUsed = false;\n\n resp = {\n // Duck-typed Response object (not a native Response instance)\n ok: xhrStatus >= 200 && xhrStatus < 300,\n status: xhrStatus,\n statusText: xhrStatusText,\n url: url,\n type: \"basic\",\n redirected: false,\n get bodyUsed() {\n return bodyUsed;\n },\n headers: responseHeaders,\n body: stream,\n json: async () => {\n bodyUsed = true;\n const text = await fullTextPromise;\n try {\n return JSON.parse(text);\n } catch (e) {\n throw new TypeError(\n `Failed to parse JSON from ${method} ${url} (status ${xhrStatus}): ${\n text.length > 200 ? text.slice(0, 200) + \"...\" : text\n }`,\n { cause: e },\n );\n }\n },\n text: async () => {\n bodyUsed = true;\n return fullTextPromise;\n },\n arrayBuffer: async () => {\n bodyUsed = true;\n return encoder.encode(await fullTextPromise).buffer;\n },\n blob: async () => {\n bodyUsed = true;\n const buf = encoder.encode(await fullTextPromise);\n if (typeof Blob !== \"undefined\") {\n return new Blob([buf], {\n type: responseHeaders.get(\"content-type\") || \"\",\n });\n }\n throw new Error(\n \"Blob is not available in this React Native environment.\",\n );\n },\n clone: () => {\n throw new Error(\n \"Response.clone() is not supported by the React Native streaming fetch polyfill.\",\n );\n },\n formData: async () => {\n throw new Error(\n \"Response.formData() is not supported by the React Native streaming fetch polyfill.\",\n );\n },\n };\n settled = true;\n // NOTE: abort listener is NOT removed here — the signal must remain\n // wired to xhr.abort() for mid-stream cancellation. Cleanup happens\n // in terminal handlers (onload, onerror, ontimeout) or onAbort itself.\n resolve(resp as unknown as Response);\n }\n }, 0);\n };\n\n xhr.send(body ?? null);\n });\n };\n\n // Expose original fetch for opt-out (e.g., third-party libs that need native behavior)\n (streamingFetch as any).__originalFetch = originalFetch;\n global.fetch = streamingFetch as typeof fetch;\n}\n","/**\n * All polyfills required for CopilotKit to work in React Native.\n *\n * These are auto-imported when `@copilotkit/react-native` is loaded.\n * A manual `import \"@copilotkit/react-native/polyfills\"` is no longer\n * required but still works for advanced / selective bootstrap scenarios.\n *\n * For granular control, import individual polyfills instead:\n * import \"@copilotkit/react-native/polyfills/streams\";\n * import \"@copilotkit/react-native/polyfills/encoding\";\n * import \"@copilotkit/react-native/polyfills/crypto\";\n * import \"@copilotkit/react-native/polyfills/dom\";\n * import \"@copilotkit/react-native/polyfills/location\";\n */\n\nimport \"./polyfills/streams\";\nimport \"./polyfills/encoding\";\nimport \"./polyfills/crypto\";\nimport \"./poly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AAO,MAAM;AACnB,YAAI;AACF,gBAAO,KAAK,MAAM,KAAK;iBAChB,GAAG;AACV,eAAM,IAAI,UACR,6BAA6B,OAAO,GAAG,IAAI,WAAW,UAAU,KAC9D,KAAK,SAAS,MAAM,KAAK,MAAM,GAAG,IAAI,GAAG,QAAQ,QAEnD,EAAE,OAAO,GAAG,CACb;;;OAGL,MAAM,YAAY;AAChB,mBAAW;AACX,eAAO;;OAET,aAAa,YAAY;AACvB,mBAAW;AACX,eAAO,QAAQ,OAAO,MAAM,gBAAgB,CAAC;;OAE/C,MAAM,YAAY;AAChB,mBAAW;QACX,MAAM,MAAM,QAAQ,OAAO,MAAM,gBAAgB;AACjD,YAAI,OAAO,SAAS,YAClB,QAAO,IAAI,KAAK,CAAC,IAAI,EAAE,EACrB,MAAM,gBAAgB,IAAI,eAAe,IAAI,IAC9C,CAAC;AAEJ,cAAM,IAAI,MACR,0DACD;;OAEH,aAAa;AACX,cAAM,IAAI,MACR,kFACD;;OAEH,UAAU,YAAY;AACpB,cAAM,IAAI,MACR,qFACD;;OAEJ;AACD,gBAAU;AAIV,cAAQ,KAA4B;;OAErC,EAAE;;AAGP,OAAI,KAAK,QAAQ,KAAK;IACtB;;AAIJ,CAAC,eAAuB,kBAAkB;AAC1C,QAAO,QAAQ;;;;;ACxVjB,uBAAuB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@copilotkit/react-native",
|
|
3
|
-
"version": "1.61.
|
|
3
|
+
"version": "1.61.2",
|
|
4
4
|
"private": false,
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
@@ -67,9 +67,9 @@
|
|
|
67
67
|
"@ag-ui/client": "0.0.57",
|
|
68
68
|
"text-encoding": "^0.7.0",
|
|
69
69
|
"web-streams-polyfill": "^4.2.0",
|
|
70
|
-
"@copilotkit/core": "1.61.
|
|
71
|
-
"@copilotkit/
|
|
72
|
-
"@copilotkit/
|
|
70
|
+
"@copilotkit/core": "1.61.2",
|
|
71
|
+
"@copilotkit/react-core": "1.61.2",
|
|
72
|
+
"@copilotkit/shared": "1.61.2"
|
|
73
73
|
},
|
|
74
74
|
"devDependencies": {
|
|
75
75
|
"@testing-library/react": "^16.3.0",
|
package/src/CopilotChat.tsx
CHANGED
|
@@ -62,7 +62,7 @@ export function useCopilotChatContext(): CopilotChatContextValue {
|
|
|
62
62
|
// Props
|
|
63
63
|
// ---------------------------------------------------------------------------
|
|
64
64
|
|
|
65
|
-
export interface
|
|
65
|
+
export interface CopilotChatBaseProps {
|
|
66
66
|
/**
|
|
67
67
|
* The agent ID to use for this chat session.
|
|
68
68
|
* Matches the web SDK's CopilotChat `agentId` prop.
|
|
@@ -114,7 +114,9 @@ export interface CopilotChatProps {
|
|
|
114
114
|
* Optional children rendered inside the chat context.
|
|
115
115
|
*/
|
|
116
116
|
children?: ReactNode;
|
|
117
|
+
}
|
|
117
118
|
|
|
119
|
+
export interface CopilotChatProps extends CopilotChatBaseProps {
|
|
118
120
|
/** Passthrough props are forwarded to consumers via the agent context. */
|
|
119
121
|
[key: string]: unknown;
|
|
120
122
|
}
|