{"version":3,"file":"useRenderTool-CKEPq7MQ.cjs","names":["CopilotKitCoreReact","CopilotKitContext","LicenseContext"],"sources":["../src/CopilotKitProvider.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\";\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        {children}\n      </LicenseContext.Provider>\n    </CopilotKitContext.Provider>\n  );\n};\n","import { useFrontendTool } from \"@copilotkit/react-core/v2/headless\";\nimport type { StandardSchemaV1 } from \"@copilotkit/shared\";\nimport type { RenderToolFunction } from \"./render-tool-types\";\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  /** Schema describing the tool's parameters (any StandardSchemaV1 library). */\n  parameters: StandardSchemaV1<unknown, T>;\n  /**\n   * Render function returning a React Native element for the tool call.\n   * Rendered by `CopilotChat` inline, and by `useRenderToolCall()` anywhere else.\n   *\n   * Arguments STREAM: on `status: \"inProgress\"` the props are partial, because\n   * the model has not finished writing the JSON. Write renderers that tolerate\n   * missing fields — that is what makes UI build progressively.\n   */\n  render: RenderToolFunction<T>;\n  /** Optional handler. Omit for render-only (display IS the effect). */\n  handler?: (args: T) => Promise<unknown>;\n  /** Scope this tool to a single agent. */\n  agentId?: string;\n}\n\n/**\n * Registers a frontend tool AND its renderer.\n *\n * Registration goes through react-core's `useFrontendTool`, which writes the\n * renderer into `CopilotKitCoreReact.renderToolCalls` — the canonical registry\n * that RN's provider already instantiates. There is deliberately NO React\n * Native-local registry: this package previously kept its own Map, which meant\n * `useComponent` (registering into core's) rendered nowhere on RN, and renderers\n * were dropped from chat history on unmount.\n */\n/**\n * @param deps Optional dependency array. The `render` function is captured at\n * registration and only refreshed when `deps` change — it does NOT re-read the\n * latest closure on every render. If your `render` closes over component state\n * or props that change over time, you MUST pass those values in `deps`, or the\n * chat will keep painting with the stale closure.\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\n  useFrontendTool<T>(\n    {\n      name,\n      description,\n      parameters,\n      handler,\n      agentId,\n      // No cast needed: ReactFrontendTool.render is ReactToolCallRenderer<T>[\"render\"],\n      // and RenderToolFunction is derived from exactly that props type, returning\n      // ReactElement | null (assignable to ComponentType's ReactNode).\n      render,\n    },\n    deps,\n  );\n}\n\nexport type { RenderToolProps, RenderToolFunction } from \"./render-tool-types\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2EA,MAAa,sBAA+D,EAC1E,UACA,YACA,SAAS,aACT,aACA,mBACA,YACA,SACA,OACA,wBACI;CAEJ,MAAM,kBACJ,OAAO,gBAAgB,aAAa,aAAa,GAAG;CAKtD,MAAM,yCACE,mBAAmB,EAAE,EAC3B,CAAC,KAAK,UAAU,gBAAgB,CAAC,CAClC;CAED,MAAM,4CACE,cAAc,EAAE,EACtB,CAAC,KAAK,UAAU,WAAW,CAAC,CAC7B;CAED,MAAM,kCAA2D,KAAK;AAEtE,KAAI,cAAc,YAAY,MAAM;EAClC,MAAM,WAAwC,IAAIA,uDAAoB;GACpE;GACA,kBACE,sBAAsB,OAClB,WACA,sBAAsB,QACpB,SAC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