@copilotkit/react-core 2.0.0-rc.23 → 2.0.0-rc.25
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/{MarkdownRendererContext-Bsl28Gmn.d.mts → MarkdownRendererContext-BX26QLwl.d.cts} +4 -5
- package/dist/{MarkdownRendererContext-Bsl28Gmn.d.mts.map → MarkdownRendererContext-BX26QLwl.d.cts.map} +1 -1
- package/dist/{MarkdownRendererContext-CBppkb5j.d.cts → MarkdownRendererContext-DAOMewji.d.mts} +4 -5
- package/dist/{MarkdownRendererContext-CBppkb5j.d.cts.map → MarkdownRendererContext-DAOMewji.d.mts.map} +1 -1
- package/dist/{MarkdownSurfaces-DveOwhaW.mjs → MarkdownSurfaces-CD0FAiZq.mjs} +2 -2
- package/dist/{MarkdownSurfaces-DveOwhaW.mjs.map → MarkdownSurfaces-CD0FAiZq.mjs.map} +1 -1
- package/dist/{MarkdownSurfaces-CGW92DCL.cjs → MarkdownSurfaces-v9AplTEj.cjs} +2 -2
- package/dist/{MarkdownSurfaces-CGW92DCL.cjs.map → MarkdownSurfaces-v9AplTEj.cjs.map} +1 -1
- package/dist/generative-ui.cjs +1 -1
- package/dist/generative-ui.cjs.map +1 -1
- package/dist/generative-ui.d.cts +1 -1
- package/dist/generative-ui.d.mts +1 -1
- package/dist/generative-ui.mjs +1 -1
- package/dist/generative-ui.mjs.map +1 -1
- package/dist/headless.cjs.map +1 -1
- package/dist/headless.mjs.map +1 -1
- package/dist/index.cjs +4 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +4 -4
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +4 -4
- package/dist/index.umd.js.map +1 -1
- package/package.json +8 -8
package/dist/headless.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"headless.mjs","names":["isPlainObject","CopilotChatDefaultLabels","useCopilotKit","EMPTY_DEPS","useCopilotKit","useCopilotKit","useCopilotKit","useCopilotKit","useCopilotKit","useCopilotKit","useCopilotKit","useCopilotKit","useCopilotKit","useCopilotKit"],"sources":["../src/providers/use-owned-core.ts","../src/lib/shallow-stable-ref.ts","../src/providers/CopilotChatConfigurationProvider.tsx","../src/hooks/use-agent.tsx","../src/hooks/tool-registration.ts","../src/hooks/use-frontend-tool.tsx","../src/hooks/use-frontend-tools.tsx","../src/hooks/use-component.tsx","../src/hooks/use-human-in-the-loop.tsx","../src/hooks/use-interrupt.tsx","../src/hooks/use-suggestions.tsx","../src/hooks/use-configure-suggestions.tsx","../src/hooks/use-agent-context.tsx","../src/hooks/use-threads.tsx","../src/types/defineToolCallRenderer.ts","../src/hooks/use-render-tool.tsx","../src/hooks/use-render-tool-call.tsx","../src/hooks/use-capabilities.tsx"],"sourcesContent":["import { useEffect, useReducer, useRef } from \"react\";\nimport type { MutableRefObject } from \"react\";\n\n/** The part of a core this hook needs: something it can dispose. */\ninterface Disposable {\n dispose(): void;\n}\n\n/**\n * @internal Create a core for the provider's lifetime and dispose it on\n * unmount.\n *\n * The dispose waits one task. StrictMode (and Fast Refresh) unmount and\n * remount effects in the same commit, so the remount cancels the pending\n * dispose and the same core keeps working. When effects mount again after the\n * core was really disposed (for example an `<Activity>` that was hidden and\n * shown), the hook creates a new core and renders again: a disposed core is\n * never reused.\n *\n * `ref` holds the current core. The provider owns it, so code that runs\n * before the core exists can read `ref.current`.\n *\n * @example\n * const coreRef = useRef<CopilotKitCoreReact | null>(null);\n * const core = ɵuseOwnedCore(coreRef, () => new CopilotKitCoreReact(config));\n */\nexport function ɵuseOwnedCore<T extends Disposable>(\n ref: MutableRefObject<T | null>,\n create: () => T,\n) {\n const createRef = useRef(create);\n createRef.current = create;\n const pendingDispose = useRef<ReturnType<typeof setTimeout> | undefined>(\n undefined,\n );\n const disposedRef = useRef(false);\n const [, rerender] = useReducer((count: number) => count + 1, 0);\n\n const current = ref.current ?? create();\n ref.current = current;\n\n useEffect(() => {\n clearTimeout(pendingDispose.current);\n pendingDispose.current = undefined;\n let core = ref.current ?? createRef.current();\n if (disposedRef.current) {\n disposedRef.current = false;\n core = createRef.current();\n rerender();\n }\n ref.current = core;\n return () => {\n pendingDispose.current = setTimeout(() => {\n pendingDispose.current = undefined;\n disposedRef.current = true;\n core.dispose();\n }, 0);\n };\n }, [ref]);\n\n return current;\n}\n","import { useRef } from \"react\";\nimport { ɵshallowEqualRecord } from \"@copilotkit/core\";\n\n// Reference-stability helpers, kept in their own leaf module (not in ./slots)\n// so that DOM-free consumers — e.g. CopilotChatConfigurationProvider, which is\n// re-exported from the lean `@copilotkit/react-core/headless` entry — reach\n// them without pulling in the slot rendering code (issue #4893).\n\n/**\n * Shallow equality comparison for objects: same own keys, each holding the\n * same value (`Object.is`). Core's `ɵshallowEqualRecord` holds the rule.\n */\nexport function shallowEqual<T extends Record<string, unknown>>(\n obj1: T,\n obj2: T,\n) {\n return ɵshallowEqualRecord(obj1, obj2);\n}\n\n/**\n * Returns true only for plain JS objects (`{}`), excluding arrays, Dates,\n * class instances, and other exotic objects that happen to have typeof \"object\".\n */\nfunction isPlainObject(obj: unknown): obj is Record<string, unknown> {\n return (\n obj !== null &&\n typeof obj === \"object\" &&\n Object.prototype.toString.call(obj) === \"[object Object]\"\n );\n}\n\n/**\n * Returns the same reference as long as the value is shallowly equal to the\n * previous render's value.\n *\n * - Identical references bail out immediately (O(1)).\n * - Plain objects ({}) are shallow-compared key-by-key.\n * - Arrays, Dates, class instances, functions, and primitives are compared by\n * reference only — shallowEqual is never called on non-plain objects, which\n * avoids incorrect equality for e.g. [1,2] vs [1,2] (different arrays).\n *\n * Typical use: stabilize inline slot props so MemoizedSlotWrapper's shallow\n * equality check isn't defeated by a new object reference on every render.\n */\nexport function useShallowStableRef<T>(value: T): T {\n const ref = useRef(value);\n\n // 1. Identical reference — bail early, no comparison needed.\n if (ref.current === value) return ref.current;\n\n // 2. Both are plain objects — shallow-compare to detect structural equality.\n if (isPlainObject(ref.current) && isPlainObject(value)) {\n if (shallowEqual(ref.current, value)) return ref.current;\n }\n\n // 3. Different values (or non-comparable types) — update the ref.\n ref.current = value;\n return ref.current;\n}\n","import type { ReactNode } from \"react\";\nimport React, {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport {\n CopilotChatDefaultLabels,\n ɵChatConfigurationStore,\n} from \"@copilotkit/core\";\nimport type { CopilotChatLabels } from \"@copilotkit/core\";\nimport { CopilotKitContext, useDefaultAgentId } from \"../context\";\n// Import from the leaf module (not ../lib/slots) so this provider stays lean in\n// the headless entry (issue #4893).\nimport { useShallowStableRef } from \"../lib/shallow-stable-ref\";\n\nexport interface CopilotChatConfigurationValue {\n labels: CopilotChatLabels;\n agentId: string;\n threadId: string;\n isModalOpen: boolean;\n setModalOpen: (open: boolean) => void;\n /**\n * Whether the thread-list drawer is open. A sibling boolean to `isModalOpen`\n * (deliberately NOT folded into a tri-state enum): on desktop the chat modal\n * and the drawer coexist, so two independent booleans are required.\n */\n drawerOpen: boolean;\n /**\n * Toggles the drawer open state. On mobile viewports (`<768px`) opening the\n * drawer closes the chat modal (mutual exclusion); on desktop there is no\n * constraint.\n */\n setDrawerOpen: (open: boolean) => void;\n /**\n * True once a `<CopilotThreadsDrawer>` wrapper has registered itself with this chat\n * configuration. The header thread-list launcher renders ONLY when this is\n * set, so chats with no drawer stay byte-for-byte unchanged.\n */\n drawerRegistered: boolean;\n /**\n * Called by the drawer wrapper on mount to announce its presence (and flip\n * `drawerRegistered`). Returns a cleanup function that de-registers the\n * drawer on unmount.\n *\n * @returns A cleanup callback that reverses the registration.\n */\n registerDrawer: () => () => void;\n /**\n * Internal: registers the modal-close setter of the provider that actually\n * owns the rendered modal (a descendant that supplied `isModalDefaultOpen`),\n * so the drawer's mobile mutual-exclusion — owned by the top-most provider —\n * closes the modal that is genuinely on screen rather than the top-most\n * provider's own (possibly unrendered) modal state.\n *\n * @param closeModal - A setter the drawer may call to close the rendered modal.\n * @returns A cleanup callback that de-registers the closer.\n */\n ɵregisterModalCloser: (closeModal: (open: boolean) => void) => () => void;\n // True when the current threadId was chosen by the caller rather than\n // silently minted inside the provider chain. Consumers that only make\n // sense against a real backend thread (e.g. /connect, suppressing the\n // welcome screen on switch) gate on this instead of `!!threadId`.\n hasExplicitThreadId: boolean;\n /**\n * Imperatively sets the active thread for this chat configuration.\n *\n * Use this to drive the rendered thread without a host callback — e.g. a\n * `<CopilotThreadsDrawer>` selecting a thread row sets it explicitly so the chat\n * connects to that backend thread.\n *\n * Guarded like the top-level `<CopilotKit>` provider's `setThreadId`: when\n * the consumer controls the threadId via the `threadId` prop on this\n * provider, this is a no-op (a warning is logged) so a prop-controlled\n * threadId is never silently overridden.\n *\n * @param threadId - The thread id to make active.\n * @param options.explicit - Whether the thread is a caller choice. Defaults\n * to `true` (a picked thread). Pass `false` to set a non-explicit thread\n * so the welcome screen shows (see {@link startNewThread}).\n */\n setActiveThreadId: (\n threadId: string,\n options?: { explicit?: boolean },\n ) => void;\n /**\n * Resets the active thread to a fresh, non-explicit client-side thread: a\n * newly minted UUID with `hasExplicitThreadId=false`, so the welcome screen\n * shows. Pairs with the core `startNewThread()` to clear the conversation\n * with no host wiring.\n *\n * Guarded identically to {@link setActiveThreadId}: a no-op when the\n * threadId is prop-controlled.\n */\n startNewThread: () => void;\n /**\n * Internal: the core store behind this value, so a nested provider can link\n * its own store to it.\n */\n ɵstore?: ɵChatConfigurationStore;\n}\n\n// Create the configuration context\nconst CopilotChatConfiguration =\n createContext<CopilotChatConfigurationValue | null>(null);\n\n// Provider props interface\nexport interface CopilotChatConfigurationProviderProps {\n children: ReactNode;\n labels?: Partial<CopilotChatLabels>;\n agentId?: string;\n threadId?: string;\n // Lets internal wrappers (e.g. the v1 CopilotKit bridge, which pipes a\n // ThreadsProvider-minted UUID through as `threadId`) declare that the\n // threadId they are supplying is NOT a caller choice. When omitted, the\n // provider infers explicitness from whether the `threadId` prop itself\n // was supplied.\n hasExplicitThreadId?: boolean;\n isModalDefaultOpen?: boolean;\n}\n\n// Provider component\nexport const CopilotChatConfigurationProvider: React.FC<\n CopilotChatConfigurationProviderProps\n> = ({\n children,\n labels,\n agentId,\n threadId,\n hasExplicitThreadId,\n isModalDefaultOpen,\n}) => {\n const parentConfig = useContext(CopilotChatConfiguration);\n\n // Stabilize labels references so that inline objects (new reference on every\n // parent render) don't invalidate mergedLabels and churn the context value.\n // parentConfig?.labels is already stabilized by the parent provider's own\n // useShallowStableRef, so we only need to stabilize the local labels prop.\n const stableLabels = useShallowStableRef(labels);\n const mergedLabels: CopilotChatLabels = useMemo(\n () => ({\n ...CopilotChatDefaultLabels,\n ...parentConfig?.labels,\n ...stableLabels,\n }),\n [stableLabels, parentConfig?.labels],\n );\n\n // Core owns thread, agent, modal and drawer resolution across the provider\n // chain. This component feeds it props during render (so the value is\n // current on the first pass), reports them after commit (so subscribers such\n // as nested stores and the open-thread registration hear about it), and\n // projects the snapshot into context.\n const providerAgentId = useDefaultAgentId();\n const options = {\n agentId,\n threadId,\n hasExplicitThreadId,\n isModalDefaultOpen,\n providerAgentId,\n };\n const parentStore = parentConfig?.ɵstore ?? null;\n const [store] = useState(\n () => new ɵChatConfigurationStore(options, parentStore),\n );\n store.ɵsetOptions(options);\n const snapshot = useSyncExternalStore(\n store.subscribe,\n store.getSnapshot,\n store.getSnapshot,\n );\n useEffect(() => {\n store.update({\n agentId,\n threadId,\n hasExplicitThreadId,\n isModalDefaultOpen,\n providerAgentId,\n });\n }, [\n store,\n agentId,\n threadId,\n hasExplicitThreadId,\n isModalDefaultOpen,\n providerAgentId,\n ]);\n\n // Tell Core which Thread this view shows, so captured interactions can link\n // to it. Read the context directly: this provider also works without a\n // CopilotKitProvider, and then there is nothing to register with.\n const copilotkit = useContext(CopilotKitContext)?.copilotkit;\n useEffect(() => {\n if (copilotkit === undefined) return;\n return store.bindOpenThread(copilotkit);\n }, [copilotkit, store]);\n\n // A provider without its own modal shows the modal state in context above\n // it, which may be a ControlledModalOpenScope's host-controlled value.\n const ownsModal = isModalDefaultOpen !== undefined;\n const isModalOpen =\n ownsModal || !parentConfig\n ? snapshot.isModalOpen\n : parentConfig.isModalOpen;\n const setModalOpen =\n ownsModal || !parentConfig ? store.setModalOpen : parentConfig.setModalOpen;\n\n // Keyed on the snapshot's fields, not its identity: a drawer that\n // unregisters and re-registers in one commit yields an equal snapshot, and\n // a new context value there would re-run the drawer's effect forever.\n const {\n agentId: resolvedAgentId,\n threadId: resolvedThreadId,\n hasExplicitThreadId: resolvedHasExplicitThreadId,\n drawerOpen,\n drawerRegistered,\n } = snapshot;\n const configurationValue: CopilotChatConfigurationValue = useMemo(\n () => ({\n labels: mergedLabels,\n agentId: resolvedAgentId,\n threadId: resolvedThreadId,\n hasExplicitThreadId: resolvedHasExplicitThreadId,\n isModalOpen,\n setModalOpen,\n drawerOpen,\n setDrawerOpen: store.setDrawerOpen,\n drawerRegistered,\n registerDrawer: store.registerDrawer,\n ɵregisterModalCloser: store.registerModalCloser,\n setActiveThreadId: store.setActiveThreadId,\n startNewThread: store.startNewThread,\n ɵstore: store,\n }),\n [\n mergedLabels,\n resolvedAgentId,\n resolvedThreadId,\n resolvedHasExplicitThreadId,\n isModalOpen,\n setModalOpen,\n drawerOpen,\n drawerRegistered,\n store,\n ],\n );\n\n return (\n <CopilotChatConfiguration.Provider value={configurationValue}>\n {children}\n </CopilotChatConfiguration.Provider>\n );\n};\n\n// Hook to use the full configuration\nexport const useCopilotChatConfiguration =\n (): CopilotChatConfigurationValue | null => {\n const configuration = useContext(CopilotChatConfiguration);\n return configuration;\n };\n\n/**\n * Props for {@link ControlledModalOpenScope}.\n */\nexport interface ControlledModalOpenScopeProps {\n children: ReactNode;\n /**\n * The host-owned open state. When this is a boolean, everything inside the\n * scope reads it as `isModalOpen`, so the host prop is the single source of\n * truth for what is on screen. Leave it `undefined` to keep the underlying\n * state in charge and only report requests through `onOpenChange`.\n */\n open?: boolean;\n /**\n * Called with the requested state whenever something inside the scope asks\n * to open or close the modal (the toggle button, click-outside, a consumer\n * calling `setModalOpen`). Fires whether or not `open` is supplied.\n */\n onOpenChange?: (open: boolean) => void;\n}\n\n/**\n * Reports modal open/close requests to the host, and — when `open` is\n * supplied — makes the modal state of an already-established chat\n * configuration **controlled** for the subtree it wraps.\n *\n * This is deliberately a scope component rather than another mode inside\n * {@link CopilotChatConfigurationProvider}. The provider resolves modal state\n * across a nested chain (own state, parent sync, drawer mutual-exclusion, the\n * modal-closer registry); a controlled branch inside that resolution would add\n * a fourth interacting mode. Overriding the context for the subtree instead\n * leaves every one of those paths untouched:\n *\n * - `isModalOpen` is replaced with the host's `open`, so the rendered surface\n * follows the prop from the very first frame (no open-then-close flash).\n * - `setModalOpen` still calls the underlying setter, so the existing\n * parent-sync and drawer mutual-exclusion side effects continue to run, and\n * *then* reports the request through `onOpenChange`.\n * - The wrapped setter is registered as the modal closer, so the drawer's\n * mobile mutual-exclusion reaches the host instead of silently flipping\n * state that nothing displays.\n *\n * A host that supplies `open` and ignores `onOpenChange` gets a modal pinned\n * to `open`, which is the standard controlled-component contract. A host that\n * supplies only `onOpenChange` is notified while the modal keeps managing\n * itself.\n *\n * Renders `children` unchanged when no chat configuration is in scope.\n */\nexport const ControlledModalOpenScope: React.FC<\n ControlledModalOpenScopeProps\n> = ({ children, open, onOpenChange }) => {\n const parentConfig = useContext(CopilotChatConfiguration);\n const parentSetModalOpen = parentConfig?.setModalOpen;\n const registerModalCloser = parentConfig?.ɵregisterModalCloser;\n\n const setModalOpen = useCallback(\n (next: boolean) => {\n parentSetModalOpen?.(next);\n onOpenChange?.(next);\n },\n [parentSetModalOpen, onOpenChange],\n );\n\n useEffect(() => {\n if (!registerModalCloser) return;\n return registerModalCloser(setModalOpen);\n }, [registerModalCloser, setModalOpen]);\n\n const configurationValue = useMemo(\n () =>\n parentConfig\n ? {\n ...parentConfig,\n isModalOpen: open ?? parentConfig.isModalOpen,\n setModalOpen,\n }\n : null,\n [parentConfig, open, setModalOpen],\n );\n\n if (!configurationValue) {\n return <>{children}</>;\n }\n\n return (\n <CopilotChatConfiguration.Provider value={configurationValue}>\n {children}\n </CopilotChatConfiguration.Provider>\n );\n};\n\nControlledModalOpenScope.displayName = \"ControlledModalOpenScope\";\n","import { useCopilotKit, useDefaultAgentId } from \"../context\";\nimport { useMemo, useEffect, useReducer, useSyncExternalStore } from \"react\";\nimport {\n ɵgetAgentResolver,\n ɵresolveAgentId,\n ɵresolveAgentThreadId,\n ɵsubscribeToAgentUpdates,\n ɵvalidateAgentBinding,\n} from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\n\nexport enum UseAgentUpdate {\n OnMessagesChanged = \"OnMessagesChanged\",\n OnStateChanged = \"OnStateChanged\",\n OnRunStatusChanged = \"OnRunStatusChanged\",\n}\n\nconst ALL_UPDATES: UseAgentUpdate[] = [\n UseAgentUpdate.OnMessagesChanged,\n UseAgentUpdate.OnStateChanged,\n UseAgentUpdate.OnRunStatusChanged,\n];\n\ninterface UseAgentPropsBase {\n updates?: UseAgentUpdate[];\n /**\n * Throttle interval (in milliseconds) for re-renders triggered by\n * `onMessagesChanged` and `onStateChanged` notifications. Useful to reduce\n * re-render frequency during high-frequency streaming updates.\n *\n * Uses a leading+trailing pattern with a shared window — first update\n * fires immediately, subsequent updates within the window are coalesced,\n * and a trailing timer ensures the most recent update fires after the\n * window expires. See `CopilotKitCore.subscribeToAgentWithOptions` in `@copilotkit/core`\n * for details.\n *\n * Resolved as: `throttleMs ?? provider defaultThrottleMs ?? 0`.\n * Passing `throttleMs={0}` explicitly disables throttling even when the\n * provider specifies a non-zero `defaultThrottleMs`.\n *\n * Run lifecycle callbacks (`onRunInitialized`, `onRunFinalized`,\n * `onRunFailed`, `onRunErrorEvent`) always fire immediately.\n *\n * @default undefined\n * When unset, inherits from the provider's `defaultThrottleMs`;\n * if that is also unset, the effective value is `0` (no throttle).\n */\n throttleMs?: number;\n}\n\n/**\n * Thread-scoped variant. `agentId`, `runtimeAgentId`, and `threadId` are a\n * matched set: together they give this hook a *private* agent — registered\n * under the local `agentId`, routing outbound to `runtimeAgentId` — that is\n * safe to pin a thread onto. None of the three is meaningful without the other\n * two, so all are required here.\n */\ninterface UseAgentThreadScopedProps {\n /**\n * The name to register this hook's proxied agent under.\n *\n * Required, and must not already be taken. The usual fallbacks (the chat\n * configuration's agentId, then `DEFAULT_AGENT_ID`) name agents that already\n * exist, and registering over one either throws `already registered` or\n * silently shadows it, depending on whether runtime discovery has landed — so\n * the caller has to name it.\n */\n agentId: string;\n /**\n * Thread to scope the agent's run to. Written onto the underlying agent, so\n * `/agent/run`, `/agent/connect`, and `/agent/stop` address this thread.\n *\n * REQUIRES `runtimeAgentId`. A runtime agent registered under a given id is a\n * singleton, so writing a per-hook threadId directly onto it would let two\n * `useAgent` calls that share an `agentId` clobber each other's thread.\n * Passing a distinct local `agentId` plus the `runtimeAgentId` it routes to\n * gives this hook a private proxied agent to pin the thread onto instead of a\n * shared one.\n */\n threadId: string;\n /**\n * The id of the runtime agent to route outbound requests to, while this hook\n * exposes a distinct local `agentId`. Registers a proxied agent via\n * `CopilotKitCore.registerProxiedAgent`, letting several frontend agents\n * (e.g. one per open thread) mount against a single runtime agent without a\n * shared-singleton collision.\n *\n * When set, `agentId` is the *local* registry id (must not collide with an\n * existing local or runtime-discovered agent) and `runtimeAgentId` is the\n * runtime agent the proxy addresses on `/agent/run` etc.\n *\n * REQUIRES `threadId`. Registering a private agent is only worth doing to\n * scope a thread to it; without a `threadId` the private agent would take its\n * thread from the chat configuration, which is what binding to the shared\n * agent via `agentId` alone already does — just with an extra registration\n * and a local id to keep unique.\n */\n runtimeAgentId: string;\n}\n\n/**\n * Default variant: neither `threadId` nor `runtimeAgentId`. The hook binds to\n * the shared agent registered under `agentId` and leaves its threadId to the\n * chat configuration (or to the agent's own auto-minted UUID).\n *\n * Both props are typed `undefined` here rather than omitted so that supplying\n * either one on its own fails to match *both* branches — that is the\n * type-level enforcement of the all-or-nothing rule.\n */\ninterface UseAgentUnscopedProps {\n /**\n * Agent to bind to. Resolution precedence: this property, then the surrounding\n * chat configuration's agentId, then the global default.\n */\n agentId?: string;\n /** Requires `runtimeAgentId`. See {@link UseAgentThreadScopedProps.threadId}. */\n threadId?: undefined;\n /** Requires `threadId`. See {@link UseAgentThreadScopedProps.runtimeAgentId}. */\n runtimeAgentId?: undefined;\n}\n\n/**\n * Props for {@link useAgent}.\n *\n * There are exactly two valid shapes, and the type admits nothing in between:\n *\n * - **Bind to an agent** — `useAgent()`, `useAgent({ agentId })`. The shared\n * instance from the registry; the thread comes from the chat configuration.\n * - **Bind a private agent to a thread** —\n * `useAgent({ agentId, runtimeAgentId, threadId })`. All three required.\n *\n * So `useAgent({ agentId, threadId })`, `useAgent({ agentId, runtimeAgentId })`,\n * and `useAgent({ runtimeAgentId, threadId })` are all compile errors. Each\n * partial combination is either unsafe (a thread scoped onto a shared singleton)\n * or pointless (a private agent with no thread, or one registered over an id\n * that already belongs to a real agent).\n */\nexport type UseAgentProps = UseAgentPropsBase &\n (UseAgentThreadScopedProps | UseAgentUnscopedProps);\n\nexport function useAgent({\n agentId,\n threadId,\n runtimeAgentId,\n updates,\n throttleMs,\n}: UseAgentProps = {}) {\n // Runtime backstop for the all-or-nothing rule UseAgentProps enforces at\n // compile time (plain JS, `as any`, props widened at a call boundary).\n ɵvalidateAgentBinding({ agentId, threadId, runtimeAgentId });\n\n // Explicit prop, then the surrounding chat configuration (#5533), then the\n // provider default, then DEFAULT_AGENT_ID.\n const chatConfig = useCopilotChatConfiguration();\n const providerAgentId = useDefaultAgentId();\n const resolvedAgentId = ɵresolveAgentId({\n agentId,\n chatAgentId: chatConfig?.agentId,\n providerAgentId,\n });\n\n const { copilotkit } = useCopilotKit();\n const resolver = ɵgetAgentResolver(copilotkit);\n const revision = useSyncExternalStore(\n resolver.subscribe,\n resolver.getSnapshot,\n resolver.getSnapshot,\n );\n // Read the provider-level default so it appears in the effect's dep array.\n // subscribeToAgentWithOptions reads it from the core instance, but React\n // needs the dep to know when to re-subscribe.\n const providerThrottleMs = copilotkit.defaultThrottleMs;\n\n const [, forceUpdate] = useReducer((x) => x + 1, 0);\n\n const updateFlags = useMemo(\n () => updates ?? ALL_UPDATES,\n [JSON.stringify(updates)],\n );\n\n // Thread-scoped path: register a private proxied agent for this hook as one\n // balanced effect (StrictMode-safe: the cleanup unregisters before the\n // remount re-registers). The resolver notifies, so the hook swaps from the\n // provisional stand-in to the real proxy.\n useEffect(() => {\n if (runtimeAgentId == null) return;\n return resolver.bindProxy({ agentId: resolvedAgentId, runtimeAgentId });\n }, [resolver, resolvedAgentId, runtimeAgentId]);\n\n // Keyed on the header generation, not header values: a builder returning a\n // new token on every resolution must not re-resolve (#1937).\n const headersGeneration = copilotkit.ɵheadersGeneration;\n const { agent, isReady } = useMemo(\n () =>\n resolver.resolve({\n agentId: resolvedAgentId,\n runtimeAgentId,\n caller: \"useAgent\",\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n resolver,\n revision,\n resolvedAgentId,\n runtimeAgentId,\n copilotkit.agents,\n copilotkit.runtimeConnectionStatus,\n copilotkit.runtimeUrl,\n copilotkit.runtimeTransport,\n copilotkit.credentials,\n headersGeneration,\n ],\n );\n\n useEffect(\n () =>\n ɵsubscribeToAgentUpdates(copilotkit, agent, {\n updates: updateFlags,\n throttleMs,\n onUpdate: forceUpdate,\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [agent, forceUpdate, throttleMs, providerThrottleMs, updateFlags],\n );\n\n // Keep request settings fresh outside useMemo: mutating inside it is unsafe\n // in concurrent mode.\n useEffect(() => {\n resolver.refreshRequestSettings(agent);\n }, [resolver, agent, headersGeneration, copilotkit.credentials]);\n\n // Pin the thread onto the agent. AbstractAgent auto-mints a UUID, so without\n // this the agent ships its own random id in /agent/run, /agent/connect and\n // /agent/stop.\n const resolvedThreadId = ɵresolveAgentThreadId({\n threadId,\n chatThreadId: chatConfig?.threadId,\n chatHasExplicitThreadId: chatConfig?.hasExplicitThreadId,\n });\n useEffect(() => {\n if (!resolvedThreadId) return;\n agent.threadId = resolvedThreadId;\n }, [agent, resolvedThreadId]);\n\n return {\n agent,\n /**\n * Whether `agent` is the real, runtime-synced (or locally-registered) agent\n * rather than a provisional stand-in returned while the runtime is still\n * connecting (or in an error state).\n *\n * `agent` is always a fully-constructed `AbstractAgent`, so calling\n * `agent.subscribe(...)`, `agent.setState(...)`, etc. is always safe. But\n * while `isReady` is `false` the instance is a placeholder that will be\n * swapped for the real agent once the runtime `/info` sync resolves, at\n * which point `agent` changes reference and dependent effects re-run.\n * Guard on `isReady` when you only want to act against the real agent —\n * e.g. subscribing to run-lifecycle events you don't want to miss during\n * the provisional window (#5000).\n */\n isReady,\n };\n}\n","import { useRef } from \"react\";\n\n/**\n * Deps comparison shared by `useFrontendTool` (and through it\n * `useHumanInTheLoop` and `useComponent`) and `useRenderTool`. Not part of the\n * public API.\n */\n\nconst EMPTY_DEPS: ReadonlyArray<unknown> = [];\n\nfunction isPlainObject(value: object): boolean {\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * Plain data (primitives, plain objects, arrays, dates) compares by value.\n * Functions always compare equal: these hooks used to compare\n * `JSON.stringify(deps)`, which turns every function into `null`, and a\n * function that counted as changed would re-register on every render when it\n * is written inline (and loop in a component that also reads\n * `useRenderToolCall`). Everything else (class instances, maps, sets) compares\n * by identity. A cycle inside plain data is safe: a pair already being\n * compared counts as equal for that branch.\n */\nfunction depEqual(a: unknown, b: unknown, seen: Map<object, object>): boolean {\n if (Object.is(a, b)) return true;\n if (typeof a === \"function\" && typeof b === \"function\") return true;\n if (\n typeof a !== \"object\" ||\n typeof b !== \"object\" ||\n a === null ||\n b === null\n ) {\n return false;\n }\n if (a instanceof Date && b instanceof Date) {\n return Object.is(a.getTime(), b.getTime());\n }\n const aIsArray = Array.isArray(a);\n if (aIsArray !== Array.isArray(b)) return false;\n if (!aIsArray && !(isPlainObject(a) && isPlainObject(b))) return false;\n\n if (seen.get(a) === b) return true;\n seen.set(a, b);\n\n if (aIsArray) {\n const left = a as unknown[];\n const right = b as unknown[];\n if (left.length !== right.length) return false;\n for (let i = 0; i < left.length; i++) {\n if (!depEqual(left[i], right[i], seen)) return false;\n }\n return true;\n }\n\n const left = a as Record<string, unknown>;\n const right = b as Record<string, unknown>;\n const leftKeys = Object.keys(left);\n if (leftKeys.length !== Object.keys(right).length) return false;\n for (const key of leftKeys) {\n if (!Object.prototype.hasOwnProperty.call(right, key)) return false;\n if (!depEqual(left[key], right[key], seen)) return false;\n }\n return true;\n}\n\n/** Whether two deps arrays are equal. A change in length is always a change. */\nexport function depsEqual(\n prev: ReadonlyArray<unknown>,\n next: ReadonlyArray<unknown>,\n): boolean {\n if (prev.length !== next.length) return false;\n const seen = new Map<object, object>();\n for (let i = 0; i < prev.length; i++) {\n if (!depEqual(prev[i], next[i], seen)) return false;\n }\n return true;\n}\n\n/**\n * Turns a caller's `deps` array into a number that changes exactly when the\n * deps change, by the rules of {@link depsEqual}. Put the number, not the\n * array, in the registration effect's dependency list: that keeps the list a\n * constant length and never serializes a value.\n */\nexport function useDepsVersion(deps?: ReadonlyArray<unknown>): number {\n const next = deps ?? EMPTY_DEPS;\n const ref = useRef({ deps: next, version: 0 });\n if (ref.current.deps !== next && !depsEqual(ref.current.deps, next)) {\n ref.current = { deps: next, version: ref.current.version + 1 };\n }\n return ref.current.version;\n}\n","import { useLayoutEffect } from \"react\";\nimport { useCopilotKit } from \"../context\";\nimport type { ReactFrontendTool } from \"../types/frontend-tool\";\nimport { useDepsVersion } from \"./tool-registration\";\n\n/**\n * Register a frontend tool while the component is mounted. The agent can\n * call it, and its `render` component draws the call in the chat.\n *\n * A tool with the same name and agentId as a tool that is already registered\n * (for example one from the provider's `tools`) overrides it while this\n * component is mounted. When the component unmounts, the overridden tool is\n * active again. The renderer stays registered after unmount, so past tool\n * calls still render in the chat history.\n *\n * @param tool - The tool to register.\n * @param deps - Extra values that re-register the tool when they change. Use\n * it when the handler closes over a value that is not part of the tool.\n *\n * @example\n * ```tsx\n * useFrontendTool({\n * name: \"showWeather\",\n * description: \"Show the weather for a city\",\n * parameters: z.object({ city: z.string() }),\n * handler: async ({ city }) => `Sunny in ${city}`,\n * });\n * ```\n */\nexport function useFrontendTool<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(tool: ReactFrontendTool<T>, deps?: ReadonlyArray<unknown>) {\n const { copilotkit } = useCopilotKit();\n // Plain data in `deps` compares by value, everything else by identity; see\n // useDepsVersion. Only the resulting number enters the effect's dependency\n // list, so `deps` is never serialized and may hold a circular value such as\n // the agent from useAgent.\n const depsVersion = useDepsVersion(deps);\n\n useLayoutEffect(() => {\n const name = tool.name;\n\n // This registration hides any tool with the same name and agentId (a\n // provider tool or another hook) until this effect cleans up. Unregistering\n // brings the hidden tool back.\n if (copilotkit.getTool({ toolName: name, agentId: tool.agentId })) {\n console.warn(\n `Tool '${name}' already exists for agent '${tool.agentId || \"global\"}'. Overriding with latest registration.`,\n );\n }\n const unregister = copilotkit.addTool(tool);\n\n // Register/override renderer by name and agentId through core.\n // The render function is registered even when tool.parameters is\n // undefined — tools like HITL confirm dialogs have no parameters\n // but still need their UI rendered in the chat.\n if (tool.render) {\n copilotkit.addHookRenderToolCall({\n name,\n args: tool.parameters,\n agentId: tool.agentId,\n render: tool.render,\n });\n }\n\n return () => {\n unregister();\n // we are intentionally not removing the render here so that the tools can still render in the chat history\n };\n // Depend on stable keys by default and allow callers to opt into\n // additional dependencies for dynamic tool configuration.\n // tool.available is included so toggling availability re-registers the tool.\n // tool.webmcp is compared by value (it is commonly an object literal), so\n // a changed WebMCP config re-registers without churning on identity.\n }, [\n tool.name,\n tool.available,\n copilotkit,\n depsVersion,\n JSON.stringify(tool.webmcp ?? null),\n ]);\n}\n","import { useLayoutEffect } from \"react\";\nimport { useCopilotKit } from \"../context\";\nimport type { ReactFrontendTool } from \"../types/frontend-tool\";\n\nconst EMPTY_DEPS: ReadonlyArray<unknown> = [];\nconst EMPTY_TOOLS: ReadonlyArray<ReactFrontendTool<any>> = [];\n\n/**\n * Register a list of frontend tools whose length can change between renders.\n *\n * `useFrontendTool` registers exactly one tool per call, so it cannot be called\n * in a loop over a runtime-length list without breaking the rules of hooks.\n * This hook runs a single effect over the whole array instead, which makes it\n * safe to build the list from state, props, or a server response.\n *\n * Tools are keyed by `name` plus `agentId`, the same as `useFrontendTool`. A\n * tool that disappears from the array is unregistered on the next render, and\n * every tool is unregistered on unmount. A listed tool hides a tool with the\n * same name and agentId (for example one from the provider's `tools`) until it\n * is unregistered, and then the hidden tool is active again. Renderers stay\n * registered after unmount so past tool calls still render in the chat history.\n *\n * @param tools - The tools to register. May be empty and may change length.\n * @param deps - Extra dependencies that force re-registration, compared by\n * identity like the second argument of `useEffect`. Use this when a handler\n * closes over a value that is not part of the tool definition. Keep the array\n * a constant length across renders.\n *\n * @example\n * Register one tool per item in application state:\n * ```tsx\n * const [reports, setReports] = useState<Report[]>([]);\n *\n * useFrontendTools(\n * reports.map((report) => ({\n * name: `open_${report.id}`,\n * description: `Open the ${report.title} report`,\n * handler: async () => navigate(`/reports/${report.id}`),\n * })),\n * [navigate],\n * );\n * ```\n *\n * @example\n * Register tools described by the backend:\n * ```tsx\n * const { data } = useQuery(fetchToolDescriptors);\n *\n * useFrontendTools(\n * (data ?? []).map((descriptor) => ({\n * name: descriptor.name,\n * description: descriptor.description,\n * parameters: z.object({ query: z.string() }),\n * handler: async ({ query }) => runDescriptor(descriptor.id, query),\n * })),\n * );\n * ```\n */\nexport function useFrontendTools(\n tools: ReadonlyArray<ReactFrontendTool<any>> | undefined,\n deps?: ReadonlyArray<unknown>,\n) {\n const { copilotkit } = useCopilotKit();\n const toolList = tools ?? EMPTY_TOOLS;\n const extraDeps = deps ?? EMPTY_DEPS;\n\n // The array is usually built inline, so its identity changes on every render\n // and cannot be a dependency. Derive a value signature from the fields that\n // decide what the agent sees, so the effect re-runs when the set of tools\n // actually changes and not merely when the caller re-renders.\n //\n // `description` is in the signature even though useFrontendTool does not key\n // on it. A singular caller writes a literal description, so it never changes\n // without the component re-mounting. This hook exists to build tools from\n // data, where the description is usually derived from that data, and a\n // description the agent reads must not go stale while the names stay put.\n const signature = JSON.stringify(\n toolList.map((tool) => [\n tool.name,\n tool.description ?? null,\n tool.agentId ?? null,\n tool.available ?? null,\n tool.webmcp ?? null,\n ]),\n );\n\n useLayoutEffect(() => {\n // Collapse duplicate names so the last entry wins, which matches the\n // override behavior of useFrontendTool, and so the cleanup below removes\n // each (name, agentId) pair exactly once.\n const deduped = new Map<string, ReactFrontendTool<any>>();\n for (const tool of toolList) {\n const key = `${tool.agentId ?? \"\"}:${tool.name}`;\n if (deduped.has(key)) {\n console.warn(\n `Tool '${tool.name}' is listed more than once for agent '${tool.agentId || \"global\"}' in the same useFrontendTools call. Using the last entry.`,\n );\n }\n deduped.set(key, tool);\n }\n\n const registered = [...deduped.values()];\n const unregisters: Array<() => void> = [];\n\n for (const tool of registered) {\n // Each registration hides any tool with the same name and agentId (a\n // provider tool or another hook) until this effect cleans up.\n if (copilotkit.getTool({ toolName: tool.name, agentId: tool.agentId })) {\n console.warn(\n `Tool '${tool.name}' already exists for agent '${tool.agentId || \"global\"}'. Overriding with latest registration.`,\n );\n }\n unregisters.push(copilotkit.addTool(tool));\n\n // Register/override renderer by name and agentId through core.\n // The render function is registered even when tool.parameters is\n // undefined — tools like HITL confirm dialogs have no parameters\n // but still need their UI rendered in the chat.\n if (tool.render) {\n copilotkit.addHookRenderToolCall({\n name: tool.name,\n args: tool.parameters,\n agentId: tool.agentId,\n render: tool.render,\n });\n }\n }\n\n return () => {\n // Remove exactly what this run registered. Reading the current array here\n // would miss a tool that was dropped from it before the effect re-ran.\n // Unregistering brings back any tool these registrations hid.\n for (const unregister of unregisters) {\n unregister();\n }\n // we are intentionally not removing the render here so that the tools can still render in the chat history\n };\n // `signature` is the value-based key for `toolList`, so the array itself is\n // deliberately not a dependency. `available` and `webmcp` are folded into\n // the signature for the same reasons they are dependencies of\n // useFrontendTool: toggling either must re-register the tool.\n //\n // `deps` is spread rather than stringified. JSON.stringify maps a function\n // to null, so a stringified `[navigate]` is the constant \"[null]\", and a\n // changed callback would never re-register. That is exactly the case `deps`\n // exists to cover. Spreading gives the entries React's own identity\n // comparison, the same contract as the second argument of useEffect. Pass a\n // deps array of a constant length, as React requires everywhere else.\n }, [signature, copilotkit, ...extraDeps]);\n}\n","import type { StandardSchemaV1, InferSchemaOutput } from \"@copilotkit/shared\";\nimport { ɵcomponentToolDescription } from \"@copilotkit/core\";\nimport type { ComponentType } from \"react\";\nimport { useFrontendTool } from \"./use-frontend-tool\";\n\ntype InferRenderProps<T> = T extends StandardSchemaV1\n ? InferSchemaOutput<T>\n : any;\n\n/**\n * Registers a React component as a frontend tool renderer in chat.\n *\n * This hook is a convenience wrapper around `useFrontendTool` that:\n * - builds a model-facing tool description,\n * - forwards optional schema parameters (any Standard Schema V1 compatible library),\n * - renders your component with tool call parameters.\n *\n * Use this when you want to display a typed visual component for a tool call\n * without manually wiring a full frontend tool object.\n *\n * When `parameters` is provided, render props are inferred from the schema.\n * When omitted, the render component may accept any props.\n *\n * @typeParam TSchema - Schema describing tool parameters, or `undefined` when no schema is given.\n * @param config - Tool registration config.\n * @param deps - Optional dependencies to refresh registration (same semantics as `useEffect`).\n *\n * @example\n * ```tsx\n * // Without parameters — render accepts any props\n * useComponent({\n * name: \"showGreeting\",\n * render: ({ message }: { message: string }) => <div>{message}</div>,\n * });\n * ```\n *\n * @example\n * ```tsx\n * // With parameters — render props inferred from schema\n * useComponent({\n * name: \"showWeatherCard\",\n * parameters: z.object({ city: z.string() }),\n * render: ({ city }) => <div>{city}</div>,\n * });\n * ```\n *\n * @example\n * ```tsx\n * useComponent(\n * {\n * name: \"renderProfile\",\n * parameters: z.object({ userId: z.string() }),\n * render: ProfileCard,\n * agentId: \"support-agent\",\n * },\n * [selectedAgentId],\n * );\n * ```\n */\nexport function useComponent<\n TSchema extends StandardSchemaV1<any, Record<string, unknown>> | undefined =\n undefined,\n>(\n config: {\n name: string;\n description?: string;\n parameters?: TSchema;\n render: ComponentType<NoInfer<InferRenderProps<TSchema>>>;\n agentId?: string;\n followUp?: boolean;\n },\n deps?: ReadonlyArray<unknown>,\n): void {\n const fullDescription = ɵcomponentToolDescription(\n config.name,\n config.description,\n );\n\n useFrontendTool(\n {\n name: config.name,\n description: fullDescription,\n parameters: config.parameters,\n render: ({ args }: { args: unknown }) => {\n const Component = config.render;\n return <Component {...(args as InferRenderProps<TSchema>)} />;\n },\n agentId: config.agentId,\n followUp: config.followUp,\n },\n deps,\n );\n}\n","import { useCopilotKit } from \"../context\";\nimport type { ReactFrontendTool } from \"../types/frontend-tool\";\nimport type { ReactHumanInTheLoop } from \"../types/human-in-the-loop\";\nimport type { ReactToolCallRenderer } from \"../types/react-tool-call-renderer\";\nimport { ɵbuildHumanInTheLoopTool, ɵhitlRenderProps } from \"@copilotkit/core\";\nimport { useCallback, useLayoutEffect } from \"react\";\nimport React from \"react\";\nimport { useFrontendTool } from \"./use-frontend-tool\";\n\nexport function useHumanInTheLoop<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(tool: ReactHumanInTheLoop<T>, deps?: ReadonlyArray<unknown>) {\n const { copilotkit } = useCopilotKit();\n // Core parks each call by tool call id, so parallel calls of this tool\n // (or of a \"*\" catch-all) each get their own `respond`.\n const registry = copilotkit.ɵhumanInTheLoop;\n\n const RenderComponent: ReactToolCallRenderer<T>[\"render\"] = useCallback(\n (props) =>\n React.createElement(\n tool.render,\n ɵhitlRenderProps<T, typeof props>(props, tool, registry),\n ),\n // eslint-disable-next-line react-hooks/exhaustive-deps -- tool is a fresh object each render; depend on the fields the renderer reads\n [tool.render, tool.name, tool.description, tool.agentId, registry],\n );\n\n const frontendTool: ReactFrontendTool<T> = {\n ...ɵbuildHumanInTheLoopTool<T>(tool, registry),\n render: RenderComponent,\n };\n\n useFrontendTool(frontendTool, deps);\n\n // Human-in-the-loop tools should remove their renderer on unmount\n // since they can't respond to user interactions anymore.\n //\n // This MUST stay a layout effect to match `useFrontendTool`, which registers\n // the renderer in its own layout effect. React runs every cleanup in a phase\n // before any effect of that same phase, but it runs the whole layout phase\n // ahead of the whole passive phase. If this teardown were passive while the\n // registration is layout, a keyed remount would order the outgoing\n // instance's removal *after* the incoming instance's registration and delete\n // the renderer that had just been added, leaving the tool unrenderable.\n useLayoutEffect(() => {\n return () => {\n copilotkit.removeHookRenderToolCall(tool.name, tool.agentId);\n };\n }, [copilotkit, tool.name, tool.agentId]);\n}\n","import React, {\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport type { Interrupt } from \"@ag-ui/client\";\nimport { ɵInterruptController } from \"@copilotkit/core\";\nimport { useCopilotKit } from \"../context\";\nimport { useAgent } from \"./use-agent\";\nimport type {\n InterruptEvent,\n InterruptRenderProps,\n InterruptHandlerProps,\n} from \"../types/interrupt\";\n\nexport type {\n InterruptEvent,\n InterruptRenderProps,\n InterruptHandlerProps,\n Interrupt,\n};\n\ntype InterruptHandlerFn<TValue, TResult> = (\n props: InterruptHandlerProps<TValue>,\n) => TResult | PromiseLike<TResult>;\n\ntype InterruptResultFromHandler<THandler> = THandler extends (\n ...args: never[]\n) => infer TResult\n ? TResult extends PromiseLike<infer TResolved>\n ? TResolved | null\n : TResult | null\n : null;\n\ntype InterruptResult<TValue, TResult> = InterruptResultFromHandler<\n InterruptHandlerFn<TValue, TResult>\n>;\n\ntype InterruptRenderInChat = boolean | undefined;\n\ntype UseInterruptReturn<TRenderInChat extends InterruptRenderInChat> =\n TRenderInChat extends false\n ? React.ReactElement | null\n : TRenderInChat extends true | undefined\n ? void\n : React.ReactElement | null | void;\n\n/**\n * Configuration options for `useInterrupt`.\n */\ninterface UseInterruptConfigBase<TValue = unknown, TResult = never> {\n /**\n * Render function for the interrupt UI.\n *\n * Receives both the standard `interrupt`/`interrupts` and the legacy `event`.\n * Call `resolve(payload)` to resume with user input, or `cancel()` to cancel.\n */\n render: (\n props: InterruptRenderProps<TValue, InterruptResult<TValue, TResult>>,\n ) => React.ReactElement;\n /**\n * Optional pre-render handler invoked when an interrupt is received.\n * Return a sync or async value to expose as `result` in `render`.\n * Rejecting/throwing falls back to `result = null`.\n */\n handler?: InterruptHandlerFn<TValue, TResult>;\n /**\n * Optional predicate to filter which interrupts this hook handles.\n * Receives the legacy-compatible event (for standard interrupts, `value` is\n * the primary `Interrupt`). Return `false` to ignore.\n */\n enabled?: (event: InterruptEvent<TValue>) => boolean;\n /** Optional agent id. Defaults to the current configured chat agent. */\n agentId?: string;\n}\n\nexport interface UseInterruptInChatConfig<\n TValue = unknown,\n TResult = never,\n> extends UseInterruptConfigBase<TValue, TResult> {\n /** When true (default), the interrupt UI renders inside `<CopilotChat>` automatically. */\n renderInChat?: true;\n}\n\nexport interface UseInterruptExternalConfig<\n TValue = unknown,\n TResult = never,\n> extends UseInterruptConfigBase<TValue, TResult> {\n /** When false, the hook returns the interrupt element so you can place it yourself. */\n renderInChat: false;\n}\n\nexport interface UseInterruptDynamicConfig<\n TValue = unknown,\n TResult = never,\n> extends UseInterruptConfigBase<TValue, TResult> {\n /** Dynamic boolean mode. When non-literal, return type is a union. */\n renderInChat: boolean;\n}\n\nexport type UseInterruptConfig<\n TValue = unknown,\n TResult = never,\n TRenderInChat extends InterruptRenderInChat = undefined,\n> = UseInterruptConfigBase<TValue, TResult> & {\n /** When true (default), the interrupt UI renders inside `<CopilotChat>` automatically. */\n renderInChat?: TRenderInChat;\n};\n\n/**\n * Handles agent interrupts with optional filtering, preprocessing, and resume behavior.\n *\n * Supports both the AG-UI standard interrupt flow (`RUN_FINISHED` with\n * `outcome.type === \"interrupt\"`) and the legacy custom-event flow\n * (`on_interrupt`). For standard interrupts, `render` receives `interrupt`\n * (the primary one) and `interrupts` (the full open set); call `resolve(payload)`\n * to resume or `cancel()` to cancel. Resuming addresses the targeted interrupt\n * and, once every open interrupt is addressed, submits a single spec `resume`\n * array via `copilotkit.runAgent`.\n *\n * - `renderInChat: true` (default): the element is published into `<CopilotChat>`; returns `void`.\n * - `renderInChat: false`: the hook returns the interrupt element for manual placement.\n *\n * @example\n * ```tsx\n * useInterrupt({\n * render: ({ interrupt, resolve, cancel }) => (\n * <div>\n * <p>{interrupt?.message}</p>\n * <button onClick={() => resolve({ approved: true })}>Approve</button>\n * <button onClick={() => cancel()}>Cancel</button>\n * </div>\n * ),\n * });\n * ```\n */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport function useInterrupt<\n TResult = never,\n TRenderInChat extends InterruptRenderInChat = undefined,\n>(\n config: UseInterruptConfig<any, TResult, TRenderInChat>,\n): UseInterruptReturn<TRenderInChat> {\n /* eslint-enable @typescript-eslint/no-explicit-any */\n const { copilotkit } = useCopilotKit();\n const { agent } = useAgent({ agentId: config.agentId, updates: [] });\n\n // Read consumer callbacks through refs so inline lambdas neither recreate\n // the controller nor churn the element memo.\n const renderRef = useRef(config.render);\n renderRef.current = config.render;\n const enabledRef = useRef(config.enabled);\n enabledRef.current = config.enabled;\n const handlerRef = useRef(config.handler);\n handlerRef.current = config.handler;\n const copilotkitRef = useRef(copilotkit);\n copilotkitRef.current = copilotkit;\n\n const [controller] = useState(\n () =>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n new ɵInterruptController<any, TResult>(\n { runAgent: (params) => copilotkitRef.current.runAgent(params) },\n {\n enabled: (event) => enabledRef.current?.(event) ?? true,\n handler: (props) =>\n handlerRef.current ? handlerRef.current(props) : (null as TResult),\n },\n ),\n );\n\n useEffect(() => {\n controller.connect(agent);\n return () => controller.disconnect();\n }, [controller, agent]);\n\n const { renderProps } = useSyncExternalStore(\n controller.subscribe,\n controller.getSnapshot,\n controller.getSnapshot,\n );\n\n const element = useMemo(\n () => (renderProps ? renderRef.current(renderProps) : null),\n [renderProps],\n );\n\n // Publish to core for in-chat rendering. Publish-only.\n useEffect(() => {\n if (config.renderInChat === false) return;\n copilotkit.setInterruptElement(element);\n }, [element, config.renderInChat, copilotkit]);\n\n // Nullify on true unmount only.\n useEffect(() => {\n if (config.renderInChat === false) return;\n return () => {\n copilotkit.setInterruptElement(null);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n if (config.renderInChat === false) {\n return element as UseInterruptReturn<TRenderInChat>;\n }\n\n return undefined as UseInterruptReturn<TRenderInChat>;\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { ɵsubscribeToAgentSuggestions } from \"@copilotkit/core\";\nimport type { Suggestion } from \"@copilotkit/core\";\nimport { useCopilotKit, useDefaultAgentId } from \"../context\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\nimport { DEFAULT_AGENT_ID } from \"@copilotkit/shared\";\n\nexport interface UseSuggestionsOptions {\n agentId?: string;\n}\n\nexport interface UseSuggestionsResult {\n suggestions: Suggestion[];\n reloadSuggestions: () => void;\n clearSuggestions: () => void;\n isLoading: boolean;\n}\n\nexport function useSuggestions({\n agentId,\n}: UseSuggestionsOptions = {}): UseSuggestionsResult {\n const { copilotkit } = useCopilotKit();\n const config = useCopilotChatConfiguration();\n const providerAgentId = useDefaultAgentId();\n const resolvedAgentId = useMemo(\n () => agentId ?? config?.agentId ?? providerAgentId ?? DEFAULT_AGENT_ID,\n [agentId, config?.agentId, providerAgentId],\n );\n\n const [result, setResult] = useState(() =>\n copilotkit.getSuggestions(resolvedAgentId),\n );\n\n useEffect(() => {\n setResult(copilotkit.getSuggestions(resolvedAgentId));\n return ɵsubscribeToAgentSuggestions(copilotkit, resolvedAgentId, setResult);\n }, [copilotkit, resolvedAgentId]);\n\n const reloadSuggestions = useCallback(() => {\n copilotkit.reloadSuggestions(resolvedAgentId);\n // Loading state is handled by onSuggestionsStartedLoading event\n }, [copilotkit, resolvedAgentId]);\n\n const clearSuggestions = useCallback(() => {\n copilotkit.clearSuggestions(resolvedAgentId);\n // State updates are handled by onSuggestionsChanged event\n }, [copilotkit, resolvedAgentId]);\n\n return {\n suggestions: result.suggestions,\n reloadSuggestions,\n clearSuggestions,\n isLoading: result.isLoading,\n };\n}\n","import { useEffect, useRef } from \"react\";\nimport { useCopilotKit, useDefaultAgentId } from \"../context\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\nimport { DEFAULT_AGENT_ID } from \"@copilotkit/shared\";\nimport { ɵbindSuggestionsConfig } from \"@copilotkit/core\";\nimport type {\n ɵSuggestionsBinding,\n ɵSuggestionsConfigInput,\n} from \"@copilotkit/core\";\n\n/**\n * Registers a suggestions configuration (dynamic or static) for the current\n * chat. A global config (no `consumerAgentId`, or `\"*\"`) applies to every\n * agent and loads for the surrounding chat's agent first.\n *\n * Pass `deps` to reload suggestions when values the config reads change.\n *\n * @example\n * useConfigureSuggestions({\n * instructions: \"Suggest concise next steps for the user\",\n * available: \"always\",\n * });\n */\nexport function useConfigureSuggestions(\n config: ɵSuggestionsConfigInput | null | undefined,\n deps?: ReadonlyArray<unknown>,\n): void {\n const { copilotkit } = useCopilotKit();\n const chatConfig = useCopilotChatConfiguration();\n const providerAgentId = useDefaultAgentId();\n const chatAgentId =\n chatConfig?.agentId ?? providerAgentId ?? DEFAULT_AGENT_ID;\n const extraDeps = deps ?? [];\n\n const bindingRef = useRef<ɵSuggestionsBinding | null>(null);\n const latestRef = useRef({ config, chatAgentId });\n latestRef.current = { config, chatAgentId };\n\n useEffect(() => {\n const latest = latestRef.current;\n const binding = ɵbindSuggestionsConfig(copilotkit, latest.config, {\n chatAgentId: latest.chatAgentId,\n });\n bindingRef.current = binding;\n return () => {\n binding.dispose();\n if (bindingRef.current === binding) bindingRef.current = null;\n };\n }, [copilotkit]);\n\n // The binding compares configs by content, so a new inline object on every\n // render is a no-op.\n useEffect(() => {\n bindingRef.current?.update(config, { chatAgentId });\n }, [config, chatAgentId]);\n\n const depsMountedRef = useRef(false);\n useEffect(() => {\n if (!depsMountedRef.current) {\n depsMountedRef.current = true;\n return;\n }\n if (extraDeps.length > 0) bindingRef.current?.reload();\n }, [extraDeps.length, ...extraDeps]);\n}\n","import { useCopilotKit } from \"../context\";\nimport { useLayoutEffect, useMemo } from \"react\";\nimport { ɵserializeContextValue } from \"@copilotkit/core\";\nimport type { ɵJsonSerializable } from \"@copilotkit/core\";\n\n/**\n * Represents any value that can be serialized to JSON.\n */\nexport type JsonSerializable = ɵJsonSerializable;\n\n/**\n * Context configuration for useAgentContext.\n * Accepts any JSON-serializable value which will be converted to a string.\n */\nexport interface AgentContextInput {\n /** A human-readable description of what this context represents */\n description: string;\n /** The context value - will be converted to a JSON string if not already a string */\n value: JsonSerializable;\n}\n\nexport function useAgentContext(context: AgentContextInput) {\n const { description, value } = context;\n const { copilotkit } = useCopilotKit();\n\n const stringValue = useMemo(() => ɵserializeContextValue(value), [value]);\n\n useLayoutEffect(() => {\n if (!copilotkit) return;\n\n const id = copilotkit.addContext({ description, value: stringValue });\n return () => {\n copilotkit.removeContext(id);\n };\n }, [description, stringValue, copilotkit]);\n}\n","import { useCopilotKit } from \"../context\";\nimport { ɵThreadsController, ɵcreateThreadStore } from \"@copilotkit/core\";\nimport { useEffect, useState, useSyncExternalStore } from \"react\";\n\n/**\n * A conversation thread managed by CopilotKit Intelligence.\n *\n * Each thread has a unique `id`, an optional human-readable `name`, and\n * timestamp fields tracking creation and update times.\n */\nexport interface Thread {\n id: string;\n agentId: string;\n name: string | null;\n archived: boolean;\n createdAt: string;\n updatedAt: string;\n /**\n * ISO-8601 timestamp of the most recent agent run on this thread. Absent\n * when the thread has never been run. Prefer this over `updatedAt` for\n * user-facing \"last activity\" displays — it is not bumped by metadata-only\n * actions like rename or archive.\n */\n lastRunAt?: string;\n}\n\n/**\n * Configuration for the {@link useThreads} hook.\n *\n * Thread operations are scoped to the runtime-authenticated user and the\n * provided agent on CopilotKit Intelligence.\n */\nexport interface UseThreadsInput {\n /** The ID of the agent whose threads to list and manage. */\n agentId: string;\n /** When `true`, archived threads are included in the list. Defaults to `false`. */\n includeArchived?: boolean;\n /** Maximum number of threads to fetch per page. When set, enables cursor-based pagination. */\n limit?: number;\n /**\n * When `false`, the hook stays inert: no runtime context is dispatched, so\n * NO thread-list fetch or realtime subscription is issued. Used by gated\n * surfaces (e.g. an unlicensed `<CopilotThreadsDrawer>`) that must not touch the\n * network until the gate opens. Defaults to `true`.\n *\n * Flipping `enabled` back to `true` resumes normal fetching on the next\n * effect run; mutations are likewise short-circuited while disabled.\n */\n enabled?: boolean;\n}\n\n/**\n * Return value of the {@link useThreads} hook.\n *\n * The `threads` array is kept in sync with the platform via a realtime\n * WebSocket subscription (when available) and is sorted most-recently-updated\n * first. Mutations reject with an `Error` if the platform request fails.\n */\nexport interface UseThreadsResult {\n /**\n * Threads for the current user/agent pair, sorted by most recently\n * updated first. Updated in realtime when the platform pushes metadata\n * events. Includes archived threads only when `includeArchived` is set.\n */\n threads: Thread[];\n /**\n * `true` while the initial thread list is being fetched from the platform.\n * Subsequent realtime updates do not re-enter the loading state.\n */\n isLoading: boolean;\n /**\n * The most recent error from fetching threads or executing a mutation,\n * or `null` when there is no error. Reset to `null` on the next\n * successful fetch.\n *\n * This channel folds together developer/config errors (missing runtime URL,\n * runtime without thread endpoints) and genuine list-load/mutation failures.\n * End-user surfaces that must not leak config errors should prefer\n * {@link listError}, which excludes the config/runtime-setup errors.\n */\n error: Error | null;\n /**\n * The most recent genuine list-load or mutation error from the platform, or\n * `null`. Unlike {@link error}, this EXCLUDES developer/config errors (a\n * missing runtime URL, or a runtime that does not advertise thread\n * endpoints), so an end-user surface can render it directly without leaking\n * a developer-facing configuration message into the UI.\n */\n listError: Error | null;\n /**\n * The error from the most recent FAILED next-page (fetch-more) load, or\n * `null`. Tracked separately from {@link listError} so a paginated-load\n * failure surfaces an inline \"couldn't load more\" affordance while the\n * already-loaded list stays visible. Cleared when a fetch-more is retried or\n * succeeds.\n */\n fetchMoreError: Error | null;\n /**\n * `true` when there are more threads available to fetch via\n * {@link fetchMoreThreads}. Only meaningful when `limit` is set.\n */\n hasMoreThreads: boolean;\n /**\n * `true` while a subsequent page of threads is being fetched.\n */\n isFetchingMoreThreads: boolean;\n /**\n * `true` while at least one thread mutation (rename, archive, unarchive,\n * delete) is awaiting a server response. Mutations apply optimistically, so\n * this is primarily useful for disabling controls or showing a subtle\n * in-flight indicator.\n */\n isMutating: boolean;\n /**\n * Fetch the next page of threads. No-op when {@link hasMoreThreads} is\n * `false` or a fetch is already in progress.\n */\n fetchMoreThreads: () => void;\n /**\n * Re-fetch the thread list from the platform without clearing the current\n * list. Backs the drawer's error-state Retry and the Active/All filter\n * refetch. No-op until the runtime is connected.\n */\n refetchThreads: () => void;\n /**\n * Reset to a fresh, non-explicit client-side thread so the welcome screen\n * shows. Lazy creation: no row appears in {@link threads} until the new\n * thread's first run persists server-side.\n */\n startNewThread: () => void;\n /**\n * Rename a thread on the platform.\n * Resolves when the server confirms the update; rejects on failure.\n */\n renameThread: (threadId: string, name: string) => Promise<void>;\n /**\n * Archive a thread on the platform.\n * Archived threads are excluded from subsequent list results.\n * Resolves when the server confirms the update; rejects on failure.\n */\n archiveThread: (threadId: string) => Promise<void>;\n /**\n * Restore a previously archived thread on the platform.\n * The thread re-appears in default (non-archived) list results.\n * Resolves when the server confirms the update; rejects on failure.\n */\n unarchiveThread: (threadId: string) => Promise<void>;\n /**\n * Permanently delete a thread from the platform.\n * This is irreversible. Resolves when the server confirms deletion;\n * rejects on failure.\n */\n deleteThread: (threadId: string) => Promise<void>;\n}\n\n/**\n * React hook for listing and managing CopilotKit Intelligence threads.\n *\n * On mount the hook fetches the thread list for the runtime-authenticated user\n * and the given `agentId`. When CopilotKit Intelligence exposes a WebSocket\n * URL, it also opens a realtime subscription so the `threads` array stays\n * current without polling — thread creates, renames, archives, and deletes\n * from any client are reflected immediately.\n *\n * Mutation methods (`renameThread`, `archiveThread`, `unarchiveThread`,\n * `deleteThread`) return promises that resolve once the platform confirms the\n * operation and reject with an `Error` on failure.\n *\n * @param input - Agent identifier and optional list controls.\n * @returns Thread list state and stable mutation callbacks.\n *\n * @example\n * ```tsx\n * import { useThreads } from \"@copilotkit/react-core\";\n *\n * function ThreadList() {\n * const { threads, isLoading, renameThread, deleteThread } = useThreads({\n * agentId: \"agent-1\",\n * });\n *\n * if (isLoading) return <p>Loading…</p>;\n *\n * return (\n * <ul>\n * {threads.map((t) => (\n * <li key={t.id}>\n * {t.name ?? \"Untitled\"}\n * <button onClick={() => renameThread(t.id, \"New name\")}>Rename</button>\n * <button onClick={() => deleteThread(t.id)}>Delete</button>\n * </li>\n * ))}\n * </ul>\n * );\n * }\n * ```\n */\nexport function useThreads({\n agentId,\n includeArchived,\n limit,\n enabled = true,\n}: UseThreadsInput): UseThreadsResult {\n const { copilotkit } = useCopilotKit();\n\n // Core's ɵThreadsController owns the view model: thread projection, the\n // configuration errors, the gated and de-duplicated context dispatch, the\n // registry claim and the mutation guard. This hook feeds it and renders it.\n const [controller] = useState(\n () =>\n new ɵThreadsController(\n ɵcreateThreadStore({ fetch: copilotkit.ɵruntimeFetch }),\n { core: copilotkit, agentId, includeArchived, limit, enabled },\n ),\n );\n const {\n threads,\n isLoading,\n error,\n listError,\n fetchMoreError,\n hasMoreThreads,\n isFetchingMoreThreads,\n isMutating,\n } = useSyncExternalStore(\n controller.subscribe,\n controller.getSnapshot,\n controller.getServerSnapshot,\n );\n\n useEffect(() => controller.start(), [controller]);\n\n useEffect(() => {\n controller.update({\n core: copilotkit,\n agentId,\n includeArchived,\n limit,\n enabled,\n });\n }, [\n controller,\n copilotkit,\n agentId,\n includeArchived,\n limit,\n enabled,\n copilotkit.runtimeUrl,\n copilotkit.runtimeConnectionStatus,\n copilotkit.ɵheadersGeneration,\n copilotkit.intelligence?.wsUrl,\n copilotkit.threadEndpoints?.list,\n copilotkit.threadEndpoints?.mutations,\n ]);\n\n const {\n fetchMoreThreads,\n refetchThreads,\n startNewThread,\n renameThread,\n archiveThread,\n unarchiveThread,\n deleteThread,\n } = controller;\n\n return {\n threads,\n isLoading,\n error,\n listError,\n fetchMoreError,\n hasMoreThreads,\n isFetchingMoreThreads,\n isMutating,\n fetchMoreThreads,\n refetchThreads,\n startNewThread,\n renameThread,\n archiveThread,\n unarchiveThread,\n deleteThread,\n };\n}\n","import type React from \"react\";\nimport { ɵanySchema } from \"@copilotkit/shared\";\nimport type { StandardSchemaV1, InferSchemaOutput } from \"@copilotkit/shared\";\nimport type { ToolCallRenderProps } from \"@copilotkit/core\";\nimport type { ReactToolCallRenderer } from \"./react-tool-call-renderer\";\n\n/**\n * Helper to define a type-safe tool call renderer entry.\n * - Accepts a single object whose keys match ReactToolCallRenderer's fields: { name, args, render, agentId? }.\n * - Derives `args` type from the provided schema (any Standard Schema V1 compatible library).\n * - Ensures the render function param type exactly matches ReactToolCallRenderer<T>[\"render\"]'s param.\n * - For wildcard tools (name: \"*\"), args is optional and defaults to a schema that accepts any value.\n */\n// Overload for wildcard tools without args\nexport function defineToolCallRenderer(def: {\n name: \"*\";\n render: (props: ToolCallRenderProps<any>) => React.ReactElement | null;\n agentId?: string;\n group?: boolean;\n}): ReactToolCallRenderer<any>;\n\n// Overload for regular tools with args\nexport function defineToolCallRenderer<S extends StandardSchemaV1>(def: {\n name: string;\n args: S;\n render: (\n props: ToolCallRenderProps<InferSchemaOutput<S>>,\n ) => React.ReactElement | null;\n agentId?: string;\n group?: boolean;\n}): ReactToolCallRenderer<InferSchemaOutput<S>>;\n\n// Implementation\nexport function defineToolCallRenderer<S extends StandardSchemaV1>(def: {\n name: string;\n args?: S;\n render: (props: any) => React.ReactElement | null;\n agentId?: string;\n group?: boolean;\n}): ReactToolCallRenderer<any> {\n // For wildcard tools, default to a schema that accepts any value\n const argsSchema = def.name === \"*\" && !def.args ? ɵanySchema : def.args;\n\n return {\n name: def.name,\n args: argsSchema,\n render: def.render,\n ...(def.agentId ? { agentId: def.agentId } : {}),\n ...(def.group ? { group: true } : {}),\n };\n}\n","import { useEffect } from \"react\";\nimport type { StandardSchemaV1, InferSchemaOutput } from \"@copilotkit/shared\";\nimport { ToolCallStatus } from \"@copilotkit/core\";\nimport { useCopilotKit } from \"../context\";\nimport { defineToolCallRenderer } from \"../types/defineToolCallRenderer\";\nimport { useDepsVersion } from \"./tool-registration\";\n\nexport interface RenderToolInProgressProps<S extends StandardSchemaV1> {\n name: string;\n toolCallId: string;\n parameters: Partial<InferSchemaOutput<S>>;\n status: \"inProgress\";\n result: undefined;\n}\n\nexport interface RenderToolExecutingProps<S extends StandardSchemaV1> {\n name: string;\n toolCallId: string;\n parameters: InferSchemaOutput<S>;\n status: \"executing\";\n result: undefined;\n}\n\nexport interface RenderToolCompleteProps<S extends StandardSchemaV1> {\n name: string;\n toolCallId: string;\n parameters: InferSchemaOutput<S>;\n status: \"complete\";\n result: string;\n}\n\nexport type RenderToolProps<S extends StandardSchemaV1> =\n | RenderToolInProgressProps<S>\n | RenderToolExecutingProps<S>\n | RenderToolCompleteProps<S>;\n\ntype RenderToolConfig<S extends StandardSchemaV1> = {\n name: string;\n parameters?: S;\n render: (props: RenderToolProps<S>) => React.ReactElement | null;\n agentId?: string;\n group?: boolean;\n};\n\n/**\n * Registers a wildcard (`\"*\"`) renderer for tool calls.\n *\n * The wildcard renderer is used as a fallback when no exact name-matched\n * renderer is registered for a tool call.\n *\n * @param config - Wildcard renderer configuration.\n * @param deps - Optional dependencies to refresh registration.\n *\n * @example\n * ```tsx\n * useRenderTool(\n * {\n * name: \"*\",\n * render: ({ name, status }) => (\n * <div>\n * {status === \"complete\" ? \"✓\" : \"⏳\"} {name}\n * </div>\n * ),\n * },\n * [],\n * );\n * ```\n */\nexport function useRenderTool(\n config: {\n name: \"*\";\n render: (props: any) => React.ReactElement | null;\n agentId?: string;\n /** Let the chat group the calls this renderer draws (see `toolCallDisplay`). */\n group?: boolean;\n },\n deps?: ReadonlyArray<unknown>,\n): void;\n\n/**\n * Registers a name-scoped renderer for tool calls.\n *\n * The provided `parameters` schema defines the typed shape of `props.parameters`\n * in `render` for `executing` and `complete` states. Accepts any Standard Schema V1\n * compatible library (Zod, Valibot, ArkType, etc.).\n *\n * @typeParam S - Schema type describing tool call parameters.\n * @param config - Named renderer configuration.\n * @param deps - Optional dependencies to refresh registration.\n *\n * @example\n * ```tsx\n * useRenderTool(\n * {\n * name: \"searchDocs\",\n * parameters: z.object({ query: z.string() }),\n * render: ({ status, parameters, result }) => {\n * if (status === \"inProgress\") return <div>Preparing...</div>;\n * if (status === \"executing\") return <div>Searching {parameters.query}</div>;\n * return <div>{result}</div>;\n * },\n * },\n * [],\n * );\n * ```\n */\nexport function useRenderTool<S extends StandardSchemaV1>(\n config: {\n name: string;\n parameters: S;\n render: (props: RenderToolProps<S>) => React.ReactElement | null;\n agentId?: string;\n /** Let the chat group the calls this renderer draws (see `toolCallDisplay`). */\n group?: boolean;\n },\n deps?: ReadonlyArray<unknown>,\n): void;\n\n/**\n * Registers a renderer entry in CopilotKit's `renderToolCalls` registry.\n *\n * Key behavior:\n * - deduplicates by `agentId:name` (latest registration wins),\n * - keeps renderer entries on cleanup so historical chat tool calls can still render,\n * - refreshes registration when `deps` change.\n *\n * @typeParam S - Schema type describing tool call parameters.\n * @param config - Renderer config for wildcard or named tools.\n * @param deps - Optional dependencies to refresh registration.\n *\n * @example\n * ```tsx\n * useRenderTool(\n * {\n * name: \"searchDocs\",\n * parameters: z.object({ query: z.string() }),\n * render: ({ status, parameters, result }) => {\n * if (status === \"executing\") return <div>Searching {parameters.query}</div>;\n * if (status === \"complete\") return <div>{result}</div>;\n * return <div>Preparing...</div>;\n * },\n * },\n * [],\n * );\n * ```\n *\n * @example\n * ```tsx\n * useRenderTool(\n * {\n * name: \"summarize\",\n * parameters: z.object({ text: z.string() }),\n * agentId: \"research-agent\",\n * render: ({ name, status }) => <div>{name}: {status}</div>,\n * },\n * [selectedAgentId],\n * );\n * ```\n */\nexport function useRenderTool<S extends StandardSchemaV1>(\n config: RenderToolConfig<S>,\n deps?: ReadonlyArray<unknown>,\n): void {\n const { copilotkit } = useCopilotKit();\n // Plain data in `deps` compares by value, everything else by identity; see\n // useDepsVersion. `deps` is never serialized, so it may hold a circular\n // value such as the agent from useAgent.\n const depsVersion = useDepsVersion(deps);\n\n useEffect(() => {\n // Build the ReactToolCallRenderer via defineToolCallRenderer\n const renderer =\n config.name === \"*\" && !config.parameters\n ? defineToolCallRenderer({\n name: \"*\",\n render: (props) =>\n config.render({ ...props, parameters: props.args }),\n ...(config.agentId ? { agentId: config.agentId } : {}),\n group: config.group,\n })\n : defineToolCallRenderer({\n name: config.name,\n args: config.parameters!,\n // Branch per status so the discriminated union stays correlated\n // when `args` is re-exposed as `parameters`.\n render: (props) => {\n if (props.status === ToolCallStatus.InProgress) {\n return config.render({ ...props, parameters: props.args });\n }\n if (props.status === ToolCallStatus.Executing) {\n return config.render({ ...props, parameters: props.args });\n }\n return config.render({ ...props, parameters: props.args });\n },\n ...(config.agentId ? { agentId: config.agentId } : {}),\n group: config.group,\n });\n\n copilotkit.addHookRenderToolCall(renderer);\n\n // No cleanup removal — keeps renderer for chat history, same as useFrontendTool\n }, [config.name, config.group, copilotkit, depsVersion]);\n}\n","import React, {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useSyncExternalStore,\n} from \"react\";\nimport type { ToolCall, ToolMessage } from \"@ag-ui/core\";\nimport {\n ɵbuildToolCallRenderProps,\n ɵdescribeUnrenderedToolCalls,\n ɵgetToolCallRendererNames,\n ɵresolveToolCallAgentId,\n ɵresolveToolCallRenderer,\n} from \"@copilotkit/core\";\nimport { useCopilotKit } from \"../context\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\nimport type { ReactToolCallRenderer } from \"../types/react-tool-call-renderer\";\n\nexport interface UseRenderToolCallProps {\n toolCall: ToolCall;\n toolMessage?: ToolMessage;\n}\n\n/**\n * Props for the memoized ToolCallRenderer component\n */\ninterface ToolCallRendererProps {\n toolCall: ToolCall;\n toolMessage?: ToolMessage;\n RenderComponent: ReactToolCallRenderer<unknown>[\"render\"];\n isExecuting: boolean;\n}\n\n/**\n * Memoized component that renders a single tool call.\n * This prevents unnecessary re-renders when parent components update\n * but the tool call data hasn't changed.\n */\nconst ToolCallRenderer = React.memo(\n function ToolCallRenderer({\n toolCall,\n toolMessage,\n RenderComponent,\n isExecuting,\n }: ToolCallRendererProps) {\n // Rebuild only when the call, its result, or its executing state changes,\n // so `args` keeps a stable reference across unrelated renders.\n const props = useMemo(\n () => ɵbuildToolCallRenderProps(toolCall, toolMessage, { isExecuting }),\n [toolCall, toolMessage, isExecuting],\n );\n return <RenderComponent {...props} />;\n },\n // Custom comparison function to prevent re-renders when tool call data hasn't changed\n (prevProps, nextProps) => {\n // Compare tool call identity and content\n if (prevProps.toolCall.id !== nextProps.toolCall.id) return false;\n if (prevProps.toolCall.function.name !== nextProps.toolCall.function.name)\n return false;\n if (\n prevProps.toolCall.function.arguments !==\n nextProps.toolCall.function.arguments\n )\n return false;\n\n // Compare tool message (result)\n const prevResult = prevProps.toolMessage?.content;\n const nextResult = nextProps.toolMessage?.content;\n if (prevResult !== nextResult) return false;\n\n // Compare executing state\n if (prevProps.isExecuting !== nextProps.isExecuting) return false;\n\n // Compare render component reference\n if (prevProps.RenderComponent !== nextProps.RenderComponent) return false;\n\n return true;\n },\n);\n\nconst IS_DEVELOPMENT = process.env.NODE_ENV !== \"production\";\n\n/**\n * Reports tool calls that resolved to no renderer, once per tool name.\n *\n * A tool call with no renderer paints an empty message container and says\n * nothing else, so the only signal a developer gets today is a blank space in\n * the chat.\n *\n * @param toolNames - The unmatched tool names collected during render.\n * @param registered - The registry as it stands now, re-read at report time.\n * @param alreadyWarned - Names already reported, mutated to keep this once per name.\n */\nfunction warnAboutUnrenderedToolCalls(\n toolNames: readonly string[],\n registered: readonly { readonly name: string }[],\n alreadyWarned: Set<string>,\n): void {\n const fresh = toolNames.filter((name) => !alreadyWarned.has(name));\n const warnings = ɵdescribeUnrenderedToolCalls(fresh, registered);\n for (const { toolName, message } of warnings) {\n alreadyWarned.add(toolName);\n console.warn(message);\n }\n}\n\n/**\n * The tool-call renderers registered on the provider, kept current.\n * @internal\n */\nexport function useToolCallRenderers() {\n const { copilotkit } = useCopilotKit();\n // useSyncExternalStore so the value is current even if subscriptions run in\n // any order.\n return useSyncExternalStore(\n (callback) =>\n copilotkit.subscribe({ onRenderToolCallsChanged: callback }).unsubscribe,\n () => copilotkit.renderToolCalls,\n () => copilotkit.renderToolCalls,\n );\n}\n\n/**\n * Which tool names have a renderer of their own, whether a wildcard (`\"*\"`)\n * renderer is registered, and which of them opted into grouping.\n * @internal\n */\nexport function useToolCallRendererNames() {\n const renderers = useToolCallRenderers();\n return useMemo(() => ɵgetToolCallRendererNames(renderers), [renderers]);\n}\n\n/**\n * Hook that returns a function to render tool calls based on the render functions\n * defined in CopilotKitProvider.\n *\n * @returns A function that takes a tool call and optional tool message and returns the rendered component\n */\nexport function useRenderToolCall() {\n const { copilotkit, executingToolCallIds } = useCopilotKit();\n const config = useCopilotChatConfiguration();\n const agentId = ɵresolveToolCallAgentId(config?.agentId, undefined);\n\n // Development-only bookkeeping for the warning below. Collected during render\n // and reported afterwards, because the registry is not settled during render.\n const unrenderedToolNames = useRef<Set<string>>(new Set());\n const warnedToolNames = useRef<Set<string>>(new Set());\n\n const renderToolCalls = useToolCallRenderers();\n\n // `executingToolCallIds` mirrors core's set, which is filled from the first\n // `onToolExecutionStart`. A HITL call resumed on reconnect, before this\n // chat mounted, is therefore already executing on the first render.\n\n const renderToolCall = useCallback(\n ({\n toolCall,\n toolMessage,\n }: UseRenderToolCallProps): React.ReactElement | null => {\n // Rendering shows tool calls from every agent: agentId scoping only\n // affects handler execution (in core). The lookup prefers this agent's\n // renderer, then an unscoped one, then any agent's, then a wildcard.\n const renderConfig = ɵresolveToolCallRenderer(\n renderToolCalls,\n toolCall.function.name,\n agentId,\n );\n\n // No per-tool or wildcard renderer registered → render nothing.\n // Showing an unhandled tool call is opt-in: register a named/wildcard\n // renderer via useRenderTool, or call useDefaultRenderTool() for the\n // built-in card. Auto-painting a default card here would leak internal\n // tool names plus raw args/result JSON into every app's chat in\n // production, so the card must be explicitly enabled.\n if (!renderConfig) {\n if (IS_DEVELOPMENT) {\n unrenderedToolNames.current.add(toolCall.function.name);\n }\n return null;\n }\n\n const isExecuting = executingToolCallIds.has(toolCall.id);\n\n // Use the memoized ToolCallRenderer component to prevent unnecessary re-renders\n return (\n <ToolCallRenderer\n key={toolCall.id}\n toolCall={toolCall}\n toolMessage={toolMessage}\n RenderComponent={renderConfig.render}\n isExecuting={isExecuting}\n />\n );\n },\n [renderToolCalls, executingToolCallIds, agentId],\n );\n\n // Report unmatched tool calls after the commit that rendered them, deferred\n // one task past this subtree's effects. `useRenderTool` registers from an\n // effect in the component that renders the chat, and React runs child effects\n // before parent ones, so at effect time here a renderer the app does register\n // may not be in the registry yet. A timeout puts the check after every effect\n // in the tree, and `warnAboutUnrenderedToolCalls` re-reads the registry then.\n //\n // No dependency array on purpose: the misses live in a ref, so an effect that\n // only reran when `renderToolCalls` changed would never flush the common case\n // of a registry that never changes again.\n useEffect(() => {\n if (!IS_DEVELOPMENT) return;\n if (unrenderedToolNames.current.size === 0) return;\n\n const timer = setTimeout(() => {\n const pending = Array.from(unrenderedToolNames.current);\n unrenderedToolNames.current.clear();\n warnAboutUnrenderedToolCalls(\n pending,\n copilotkit.renderToolCalls,\n warnedToolNames.current,\n );\n }, 0);\n\n return () => clearTimeout(timer);\n });\n\n return renderToolCall;\n}\n","import type { AgentCapabilities } from \"@ag-ui/core\";\nimport { ɵgetAgentCapabilities } from \"@copilotkit/core\";\nimport { useAgent } from \"./use-agent\";\n\n/**\n * Returns the capabilities declared by the given agent (or the agent resolved\n * from the surrounding chat configuration, falling back to the default agent).\n * Capabilities are populated from the runtime `/info` response at connection\n * time. The hook reads them synchronously from the agent instance — there is\n * no separate loading state, but the value will be `undefined` until the\n * runtime handshake completes.\n *\n * @param agentId - Optional agent ID. If omitted, inherits the surrounding\n * chat configuration's agent, falling back to the default agent.\n * @returns The agent's capabilities, or `undefined` if the agent doesn't\n * declare capabilities.\n */\nexport function useCapabilities(\n agentId?: string,\n): AgentCapabilities | undefined {\n const { agent } = useAgent({ agentId });\n return ɵgetAgentCapabilities(agent);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,cACd,KACA,QACA;CACA,MAAM,YAAY,OAAO,OAAO;AAChC,WAAU,UAAU;CACpB,MAAM,iBAAiB,OACrB,OACD;CACD,MAAM,cAAc,OAAO,MAAM;CACjC,MAAM,GAAG,YAAY,YAAY,UAAkB,QAAQ,GAAG,EAAE;CAEhE,MAAM,UAAU,IAAI,WAAW,QAAQ;AACvC,KAAI,UAAU;AAEd,iBAAgB;AACd,eAAa,eAAe,QAAQ;AACpC,iBAAe,UAAU;EACzB,IAAI,OAAO,IAAI,WAAW,UAAU,SAAS;AAC7C,MAAI,YAAY,SAAS;AACvB,eAAY,UAAU;AACtB,UAAO,UAAU,SAAS;AAC1B,aAAU;;AAEZ,MAAI,UAAU;AACd,eAAa;AACX,kBAAe,UAAU,iBAAiB;AACxC,mBAAe,UAAU;AACzB,gBAAY,UAAU;AACtB,SAAK,SAAS;MACb,EAAE;;IAEN,CAAC,IAAI,CAAC;AAET,QAAO;;;;;;;;;AChDT,SAAgB,aACd,MACA,MACA;AACA,QAAO,oBAAoB,MAAM,KAAK;;;;;;AAOxC,SAASA,gBAAc,KAA8C;AACnE,QACE,QAAQ,QACR,OAAO,QAAQ,YACf,OAAO,UAAU,SAAS,KAAK,IAAI,KAAK;;;;;;;;;;;;;;;AAiB5C,SAAgB,oBAAuB,OAAa;CAClD,MAAM,MAAM,OAAO,MAAM;AAGzB,KAAI,IAAI,YAAY,MAAO,QAAO,IAAI;AAGtC,KAAIA,gBAAc,IAAI,QAAQ,IAAIA,gBAAc,MAAM,EACpD;MAAI,aAAa,IAAI,SAAS,MAAM,CAAE,QAAO,IAAI;;AAInD,KAAI,UAAU;AACd,QAAO,IA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AAC,CAAC,mBACzD,WAAW,uBACX,WAAW,gBAClB;;;;;;;;AAmBH,SAAgB,oBAAoB;CAClC,MAAM,EAAE,YAAY,yBAAyBA,iBAAe;CAE5D,MAAM,UAAU,wBADD,6BAA6B,EACI,SAAS,OAAU;CAInE,MAAM,sBAAsB,uBAAoB,IAAI,KAAK,CAAC;CAC1D,MAAM,kBAAkB,uBAAoB,IAAI,KAAK,CAAC;CAEtD,MAAM,kBAAkB,sBAAsB;CAM9C,MAAM,iBAAiB,aACpB,EACC,UACA,kBACuD;EAIvD,MAAM,eAAe,yBACnB,iBACA,SAAS,SAAS,MAClB,QACD;AAQD,MAAI,CAAC,cAAc;AACjB,OAAI,eACF,qBAAoB,QAAQ,IAAI,SAAS,SAAS,KAAK;AAEzD,UAAO;;EAGT,MAAM,cAAc,qBAAqB,IAAI,SAAS,GAAG;AAGzD,SACE,oBAAC;GAEW;GACG;GACb,iBAAiB,aAAa;GACjB;KAJR,SAAS,GAKd;IAGN;EAAC;EAAiB;EAAsB;EAAQ,CACjD;AAYD,iBAAgB;AACd,MAAI,CAAC,eAAgB;AACrB,MAAI,oBAAoB,QAAQ,SAAS,EAAG;EAE5C,MAAM,QAAQ,iBAAiB;GAC7B,MAAM,UAAU,MAAM,KAAK,oBAAoB,QAAQ;AACvD,uBAAoB,QAAQ,OAAO;AACnC,gCACE,SACA,WAAW,iBACX,gBAAgB,QACjB;KACA,EAAE;AAEL,eAAa,aAAa,MAAM;GAChC;AAEF,QAAO;;;;;;;;;;;;;;;;;;AChNT,SAAgB,gBACd,SAC+B;CAC/B,MAAM,EAAE,UAAU,SAAS,EAAE,SAAS,CAAC;AACvC,QAAO,sBAAsB,MAAM"}
|
|
1
|
+
{"version":3,"file":"headless.mjs","names":["isPlainObject","CopilotChatDefaultLabels","useCopilotKit","EMPTY_DEPS","useCopilotKit","useCopilotKit","useCopilotKit","useCopilotKit","useCopilotKit","useCopilotKit","useCopilotKit","useCopilotKit","useCopilotKit","useCopilotKit"],"sources":["../src/providers/use-owned-core.ts","../src/lib/shallow-stable-ref.ts","../src/providers/CopilotChatConfigurationProvider.tsx","../src/hooks/use-agent.tsx","../src/hooks/tool-registration.ts","../src/hooks/use-frontend-tool.tsx","../src/hooks/use-frontend-tools.tsx","../src/hooks/use-component.tsx","../src/hooks/use-human-in-the-loop.tsx","../src/hooks/use-interrupt.tsx","../src/hooks/use-suggestions.tsx","../src/hooks/use-configure-suggestions.tsx","../src/hooks/use-agent-context.tsx","../src/hooks/use-threads.tsx","../src/types/defineToolCallRenderer.ts","../src/hooks/use-render-tool.tsx","../src/hooks/use-render-tool-call.tsx","../src/hooks/use-capabilities.tsx"],"sourcesContent":["import { useEffect, useReducer, useRef } from \"react\";\nimport type { MutableRefObject } from \"react\";\n\n/** The part of a core this hook needs: something it can dispose. */\ninterface Disposable {\n dispose(): void;\n}\n\n/**\n * @internal Create a core for the provider's lifetime and dispose it on\n * unmount.\n *\n * The dispose waits one task. StrictMode (and Fast Refresh) unmount and\n * remount effects in the same commit, so the remount cancels the pending\n * dispose and the same core keeps working. When effects mount again after the\n * core was really disposed (for example an `<Activity>` that was hidden and\n * shown), the hook creates a new core and renders again: a disposed core is\n * never reused.\n *\n * `ref` holds the current core. The provider owns it, so code that runs\n * before the core exists can read `ref.current`.\n *\n * @example\n * const coreRef = useRef<CopilotKitCoreReact | null>(null);\n * const core = ɵuseOwnedCore(coreRef, () => new CopilotKitCoreReact(config));\n */\nexport function ɵuseOwnedCore<T extends Disposable>(\n ref: MutableRefObject<T | null>,\n create: () => T,\n) {\n const createRef = useRef(create);\n createRef.current = create;\n const pendingDispose = useRef<ReturnType<typeof setTimeout> | undefined>(\n undefined,\n );\n const disposedRef = useRef(false);\n const [, rerender] = useReducer((count: number) => count + 1, 0);\n\n const current = ref.current ?? create();\n ref.current = current;\n\n useEffect(() => {\n clearTimeout(pendingDispose.current);\n pendingDispose.current = undefined;\n let core = ref.current ?? createRef.current();\n if (disposedRef.current) {\n disposedRef.current = false;\n core = createRef.current();\n rerender();\n }\n ref.current = core;\n return () => {\n pendingDispose.current = setTimeout(() => {\n pendingDispose.current = undefined;\n disposedRef.current = true;\n core.dispose();\n }, 0);\n };\n }, [ref]);\n\n return current;\n}\n","import { useRef } from \"react\";\nimport { ɵshallowEqualRecord } from \"@copilotkit/core\";\n\n// Reference-stability helpers, kept in their own leaf module (not in ./slots)\n// so that DOM-free consumers — e.g. CopilotChatConfigurationProvider, which is\n// re-exported from the lean `@copilotkit/react-core/headless` entry — reach\n// them without pulling in the slot rendering code (issue #4893).\n\n/**\n * Shallow equality comparison for objects: same own keys, each holding the\n * same value (`Object.is`). Core's `ɵshallowEqualRecord` holds the rule.\n */\nexport function shallowEqual<T extends Record<string, unknown>>(\n obj1: T,\n obj2: T,\n) {\n return ɵshallowEqualRecord(obj1, obj2);\n}\n\n/**\n * Returns true only for plain JS objects (`{}`), excluding arrays, Dates,\n * class instances, and other exotic objects that happen to have typeof \"object\".\n */\nfunction isPlainObject(obj: unknown): obj is Record<string, unknown> {\n return (\n obj !== null &&\n typeof obj === \"object\" &&\n Object.prototype.toString.call(obj) === \"[object Object]\"\n );\n}\n\n/**\n * Returns the same reference as long as the value is shallowly equal to the\n * previous render's value.\n *\n * - Identical references bail out immediately (O(1)).\n * - Plain objects ({}) are shallow-compared key-by-key.\n * - Arrays, Dates, class instances, functions, and primitives are compared by\n * reference only — shallowEqual is never called on non-plain objects, which\n * avoids incorrect equality for e.g. [1,2] vs [1,2] (different arrays).\n *\n * Typical use: stabilize inline slot props so MemoizedSlotWrapper's shallow\n * equality check isn't defeated by a new object reference on every render.\n */\nexport function useShallowStableRef<T>(value: T): T {\n const ref = useRef(value);\n\n // 1. Identical reference — bail early, no comparison needed.\n if (ref.current === value) return ref.current;\n\n // 2. Both are plain objects — shallow-compare to detect structural equality.\n if (isPlainObject(ref.current) && isPlainObject(value)) {\n if (shallowEqual(ref.current, value)) return ref.current;\n }\n\n // 3. Different values (or non-comparable types) — update the ref.\n ref.current = value;\n return ref.current;\n}\n","import type { ReactNode } from \"react\";\nimport React, {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport {\n CopilotChatDefaultLabels,\n ɵChatConfigurationStore,\n} from \"@copilotkit/core\";\nimport type { CopilotChatLabels } from \"@copilotkit/core\";\nimport { CopilotKitContext, useDefaultAgentId } from \"../context\";\n// Import from the leaf module (not ../lib/slots) so this provider stays lean in\n// the headless entry (issue #4893).\nimport { useShallowStableRef } from \"../lib/shallow-stable-ref\";\n\nexport interface CopilotChatConfigurationValue {\n labels: CopilotChatLabels;\n agentId: string;\n threadId: string;\n isModalOpen: boolean;\n setModalOpen: (open: boolean) => void;\n /**\n * Whether the thread-list drawer is open. A sibling boolean to `isModalOpen`\n * (deliberately NOT folded into a tri-state enum): on desktop the chat modal\n * and the drawer coexist, so two independent booleans are required.\n */\n drawerOpen: boolean;\n /**\n * Toggles the drawer open state. On mobile viewports (`<768px`) opening the\n * drawer closes the chat modal (mutual exclusion); on desktop there is no\n * constraint.\n */\n setDrawerOpen: (open: boolean) => void;\n /**\n * True once a `<CopilotThreadsDrawer>` wrapper has registered itself with this chat\n * configuration. The header thread-list launcher renders ONLY when this is\n * set, so chats with no drawer stay byte-for-byte unchanged.\n */\n drawerRegistered: boolean;\n /**\n * Called by the drawer wrapper on mount to announce its presence (and flip\n * `drawerRegistered`). Returns a cleanup function that de-registers the\n * drawer on unmount.\n *\n * @returns A cleanup callback that reverses the registration.\n */\n registerDrawer: () => () => void;\n /**\n * Internal: registers the modal-close setter of the provider that actually\n * owns the rendered modal (a descendant that supplied `isModalDefaultOpen`),\n * so the drawer's mobile mutual-exclusion — owned by the top-most provider —\n * closes the modal that is genuinely on screen rather than the top-most\n * provider's own (possibly unrendered) modal state.\n *\n * @param closeModal - A setter the drawer may call to close the rendered modal.\n * @returns A cleanup callback that de-registers the closer.\n */\n ɵregisterModalCloser: (closeModal: (open: boolean) => void) => () => void;\n // True when the current threadId was chosen by the caller rather than\n // silently minted inside the provider chain. Consumers that only make\n // sense against a real backend thread (e.g. /connect, suppressing the\n // welcome screen on switch) gate on this instead of `!!threadId`.\n hasExplicitThreadId: boolean;\n /**\n * Imperatively sets the active thread for this chat configuration.\n *\n * Use this to drive the rendered thread without a host callback — e.g. a\n * `<CopilotThreadsDrawer>` selecting a thread row sets it explicitly so the chat\n * connects to that backend thread.\n *\n * Guarded like the top-level `<CopilotKit>` provider's `setThreadId`: when\n * the consumer controls the threadId via the `threadId` prop on this\n * provider, this is a no-op (a warning is logged) so a prop-controlled\n * threadId is never silently overridden.\n *\n * @param threadId - The thread id to make active.\n * @param options.explicit - Whether the thread is a caller choice. Defaults\n * to `true` (a picked thread). Pass `false` to set a non-explicit thread\n * so the welcome screen shows (see {@link startNewThread}).\n */\n setActiveThreadId: (\n threadId: string,\n options?: { explicit?: boolean },\n ) => void;\n /**\n * Resets the active thread to a fresh, non-explicit client-side thread: a\n * newly minted UUID with `hasExplicitThreadId=false`, so the welcome screen\n * shows. Pairs with the core `startNewThread()` to clear the conversation\n * with no host wiring.\n *\n * Guarded identically to {@link setActiveThreadId}: a no-op when the\n * threadId is prop-controlled.\n */\n startNewThread: () => void;\n /**\n * Internal: the core store behind this value, so a nested provider can link\n * its own store to it.\n */\n ɵstore?: ɵChatConfigurationStore;\n}\n\n// Create the configuration context\nconst CopilotChatConfiguration =\n createContext<CopilotChatConfigurationValue | null>(null);\n\n// Provider props interface\nexport interface CopilotChatConfigurationProviderProps {\n children: ReactNode;\n labels?: Partial<CopilotChatLabels>;\n agentId?: string;\n threadId?: string;\n // Lets internal wrappers (e.g. the v1 CopilotKit bridge, which pipes a\n // ThreadsProvider-minted UUID through as `threadId`) declare that the\n // threadId they are supplying is NOT a caller choice. When omitted, the\n // provider infers explicitness from whether the `threadId` prop itself\n // was supplied.\n hasExplicitThreadId?: boolean;\n isModalDefaultOpen?: boolean;\n}\n\n// Provider component\nexport const CopilotChatConfigurationProvider: React.FC<\n CopilotChatConfigurationProviderProps\n> = ({\n children,\n labels,\n agentId,\n threadId,\n hasExplicitThreadId,\n isModalDefaultOpen,\n}) => {\n const parentConfig = useContext(CopilotChatConfiguration);\n\n // Stabilize labels references so that inline objects (new reference on every\n // parent render) don't invalidate mergedLabels and churn the context value.\n // parentConfig?.labels is already stabilized by the parent provider's own\n // useShallowStableRef, so we only need to stabilize the local labels prop.\n const stableLabels = useShallowStableRef(labels);\n const mergedLabels: CopilotChatLabels = useMemo(\n () => ({\n ...CopilotChatDefaultLabels,\n ...parentConfig?.labels,\n ...stableLabels,\n }),\n [stableLabels, parentConfig?.labels],\n );\n\n // Core owns thread, agent, modal and drawer resolution across the provider\n // chain. This component feeds it props during render (so the value is\n // current on the first pass), reports them after commit (so subscribers such\n // as nested stores and the open-thread registration hear about it), and\n // projects the snapshot into context.\n const providerAgentId = useDefaultAgentId();\n const options = {\n agentId,\n threadId,\n hasExplicitThreadId,\n isModalDefaultOpen,\n providerAgentId,\n };\n const parentStore = parentConfig?.ɵstore ?? null;\n const [store] = useState(\n () => new ɵChatConfigurationStore(options, parentStore),\n );\n store.ɵsetOptions(options);\n const snapshot = useSyncExternalStore(\n store.subscribe,\n store.getSnapshot,\n store.getSnapshot,\n );\n useEffect(() => {\n store.update({\n agentId,\n threadId,\n hasExplicitThreadId,\n isModalDefaultOpen,\n providerAgentId,\n });\n }, [\n store,\n agentId,\n threadId,\n hasExplicitThreadId,\n isModalDefaultOpen,\n providerAgentId,\n ]);\n\n // Tell Core which Thread this view shows, so captured interactions can link\n // to it. Read the context directly: this provider also works without a\n // CopilotKitProvider, and then there is nothing to register with.\n const copilotkit = useContext(CopilotKitContext)?.copilotkit;\n useEffect(() => {\n if (copilotkit === undefined) return;\n return store.bindOpenThread(copilotkit);\n }, [copilotkit, store]);\n\n // A provider without its own modal shows the modal state in context above\n // it, which may be a ControlledModalOpenScope's host-controlled value.\n const ownsModal = isModalDefaultOpen !== undefined;\n const isModalOpen =\n ownsModal || !parentConfig\n ? snapshot.isModalOpen\n : parentConfig.isModalOpen;\n const setModalOpen =\n ownsModal || !parentConfig ? store.setModalOpen : parentConfig.setModalOpen;\n\n // Keyed on the snapshot's fields, not its identity: a drawer that\n // unregisters and re-registers in one commit yields an equal snapshot, and\n // a new context value there would re-run the drawer's effect forever.\n const {\n agentId: resolvedAgentId,\n threadId: resolvedThreadId,\n hasExplicitThreadId: resolvedHasExplicitThreadId,\n drawerOpen,\n drawerRegistered,\n } = snapshot;\n const configurationValue: CopilotChatConfigurationValue = useMemo(\n () => ({\n labels: mergedLabels,\n agentId: resolvedAgentId,\n threadId: resolvedThreadId,\n hasExplicitThreadId: resolvedHasExplicitThreadId,\n isModalOpen,\n setModalOpen,\n drawerOpen,\n setDrawerOpen: store.setDrawerOpen,\n drawerRegistered,\n registerDrawer: store.registerDrawer,\n ɵregisterModalCloser: store.registerModalCloser,\n setActiveThreadId: store.setActiveThreadId,\n startNewThread: store.startNewThread,\n ɵstore: store,\n }),\n [\n mergedLabels,\n resolvedAgentId,\n resolvedThreadId,\n resolvedHasExplicitThreadId,\n isModalOpen,\n setModalOpen,\n drawerOpen,\n drawerRegistered,\n store,\n ],\n );\n\n return (\n <CopilotChatConfiguration.Provider value={configurationValue}>\n {children}\n </CopilotChatConfiguration.Provider>\n );\n};\n\n// Hook to use the full configuration\nexport const useCopilotChatConfiguration =\n (): CopilotChatConfigurationValue | null => {\n const configuration = useContext(CopilotChatConfiguration);\n return configuration;\n };\n\n/**\n * Props for {@link ControlledModalOpenScope}.\n */\nexport interface ControlledModalOpenScopeProps {\n children: ReactNode;\n /**\n * The host-owned open state. When this is a boolean, everything inside the\n * scope reads it as `isModalOpen`, so the host prop is the single source of\n * truth for what is on screen. Leave it `undefined` to keep the underlying\n * state in charge and only report requests through `onOpenChange`.\n */\n open?: boolean;\n /**\n * Called with the requested state whenever something inside the scope asks\n * to open or close the modal (the toggle button, click-outside, a consumer\n * calling `setModalOpen`). Fires whether or not `open` is supplied.\n */\n onOpenChange?: (open: boolean) => void;\n}\n\n/**\n * Reports modal open/close requests to the host, and — when `open` is\n * supplied — makes the modal state of an already-established chat\n * configuration **controlled** for the subtree it wraps.\n *\n * This is deliberately a scope component rather than another mode inside\n * {@link CopilotChatConfigurationProvider}. The provider resolves modal state\n * across a nested chain (own state, parent sync, drawer mutual-exclusion, the\n * modal-closer registry); a controlled branch inside that resolution would add\n * a fourth interacting mode. Overriding the context for the subtree instead\n * leaves every one of those paths untouched:\n *\n * - `isModalOpen` is replaced with the host's `open`, so the rendered surface\n * follows the prop from the very first frame (no open-then-close flash).\n * - `setModalOpen` still calls the underlying setter, so the existing\n * parent-sync and drawer mutual-exclusion side effects continue to run, and\n * *then* reports the request through `onOpenChange`.\n * - The wrapped setter is registered as the modal closer, so the drawer's\n * mobile mutual-exclusion reaches the host instead of silently flipping\n * state that nothing displays.\n *\n * A host that supplies `open` and ignores `onOpenChange` gets a modal pinned\n * to `open`, which is the standard controlled-component contract. A host that\n * supplies only `onOpenChange` is notified while the modal keeps managing\n * itself.\n *\n * Renders `children` unchanged when no chat configuration is in scope.\n */\nexport const ControlledModalOpenScope: React.FC<\n ControlledModalOpenScopeProps\n> = ({ children, open, onOpenChange }) => {\n const parentConfig = useContext(CopilotChatConfiguration);\n const parentSetModalOpen = parentConfig?.setModalOpen;\n const registerModalCloser = parentConfig?.ɵregisterModalCloser;\n\n const setModalOpen = useCallback(\n (next: boolean) => {\n parentSetModalOpen?.(next);\n onOpenChange?.(next);\n },\n [parentSetModalOpen, onOpenChange],\n );\n\n useEffect(() => {\n if (!registerModalCloser) return;\n return registerModalCloser(setModalOpen);\n }, [registerModalCloser, setModalOpen]);\n\n const configurationValue = useMemo(\n () =>\n parentConfig\n ? {\n ...parentConfig,\n isModalOpen: open ?? parentConfig.isModalOpen,\n setModalOpen,\n }\n : null,\n [parentConfig, open, setModalOpen],\n );\n\n if (!configurationValue) {\n return <>{children}</>;\n }\n\n return (\n <CopilotChatConfiguration.Provider value={configurationValue}>\n {children}\n </CopilotChatConfiguration.Provider>\n );\n};\n\nControlledModalOpenScope.displayName = \"ControlledModalOpenScope\";\n","import { useCopilotKit, useDefaultAgentId } from \"../context\";\nimport { useMemo, useEffect, useReducer, useSyncExternalStore } from \"react\";\nimport {\n ɵgetAgentResolver,\n ɵresolveAgentId,\n ɵresolveAgentThreadId,\n ɵsubscribeToAgentUpdates,\n ɵvalidateAgentBinding,\n} from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\n\nexport enum UseAgentUpdate {\n OnMessagesChanged = \"OnMessagesChanged\",\n OnStateChanged = \"OnStateChanged\",\n OnRunStatusChanged = \"OnRunStatusChanged\",\n}\n\nconst ALL_UPDATES: UseAgentUpdate[] = [\n UseAgentUpdate.OnMessagesChanged,\n UseAgentUpdate.OnStateChanged,\n UseAgentUpdate.OnRunStatusChanged,\n];\n\ninterface UseAgentPropsBase {\n updates?: UseAgentUpdate[];\n /**\n * Throttle interval (in milliseconds) for re-renders triggered by\n * `onMessagesChanged` and `onStateChanged` notifications. Useful to reduce\n * re-render frequency during high-frequency streaming updates.\n *\n * Uses a leading+trailing pattern with a shared window — first update\n * fires immediately, subsequent updates within the window are coalesced,\n * and a trailing timer ensures the most recent update fires after the\n * window expires. See `CopilotKitCore.subscribeToAgentWithOptions` in `@copilotkit/core`\n * for details.\n *\n * Resolved as: `throttleMs ?? provider defaultThrottleMs ?? 0`.\n * Passing `throttleMs={0}` explicitly disables throttling even when the\n * provider specifies a non-zero `defaultThrottleMs`.\n *\n * Run lifecycle callbacks (`onRunInitialized`, `onRunFinalized`,\n * `onRunFailed`, `onRunErrorEvent`) always fire immediately.\n *\n * @default undefined\n * When unset, inherits from the provider's `defaultThrottleMs`;\n * if that is also unset, the effective value is `0` (no throttle).\n */\n throttleMs?: number;\n}\n\n/**\n * Thread-scoped variant. `agentId`, `runtimeAgentId`, and `threadId` are a\n * matched set: together they give this hook a *private* agent — registered\n * under the local `agentId`, routing outbound to `runtimeAgentId` — that is\n * safe to pin a thread onto. None of the three is meaningful without the other\n * two, so all are required here.\n */\ninterface UseAgentThreadScopedProps {\n /**\n * The name to register this hook's proxied agent under.\n *\n * Required, and must not already be taken. The usual fallbacks (the chat\n * configuration's agentId, then `DEFAULT_AGENT_ID`) name agents that already\n * exist, and registering over one either throws `already registered` or\n * silently shadows it, depending on whether runtime discovery has landed — so\n * the caller has to name it.\n */\n agentId: string;\n /**\n * Thread to scope the agent's run to. Written onto the underlying agent, so\n * `/agent/run`, `/agent/connect`, and `/agent/stop` address this thread.\n *\n * REQUIRES `runtimeAgentId`. A runtime agent registered under a given id is a\n * singleton, so writing a per-hook threadId directly onto it would let two\n * `useAgent` calls that share an `agentId` clobber each other's thread.\n * Passing a distinct local `agentId` plus the `runtimeAgentId` it routes to\n * gives this hook a private proxied agent to pin the thread onto instead of a\n * shared one.\n */\n threadId: string;\n /**\n * The id of the runtime agent to route outbound requests to, while this hook\n * exposes a distinct local `agentId`. Registers a proxied agent via\n * `CopilotKitCore.registerProxiedAgent`, letting several frontend agents\n * (e.g. one per open thread) mount against a single runtime agent without a\n * shared-singleton collision.\n *\n * When set, `agentId` is the *local* registry id (must not collide with an\n * existing local or runtime-discovered agent) and `runtimeAgentId` is the\n * runtime agent the proxy addresses on `/agent/run` etc.\n *\n * REQUIRES `threadId`. Registering a private agent is only worth doing to\n * scope a thread to it; without a `threadId` the private agent would take its\n * thread from the chat configuration, which is what binding to the shared\n * agent via `agentId` alone already does — just with an extra registration\n * and a local id to keep unique.\n */\n runtimeAgentId: string;\n}\n\n/**\n * Default variant: neither `threadId` nor `runtimeAgentId`. The hook binds to\n * the shared agent registered under `agentId` and leaves its threadId to the\n * chat configuration (or to the agent's own auto-minted UUID).\n *\n * Both props are typed `undefined` here rather than omitted so that supplying\n * either one on its own fails to match *both* branches — that is the\n * type-level enforcement of the all-or-nothing rule.\n */\ninterface UseAgentUnscopedProps {\n /**\n * Agent to bind to. Resolution precedence: this property, then the surrounding\n * chat configuration's agentId, then the global default.\n */\n agentId?: string;\n /** Requires `runtimeAgentId`. See {@link UseAgentThreadScopedProps.threadId}. */\n threadId?: undefined;\n /** Requires `threadId`. See {@link UseAgentThreadScopedProps.runtimeAgentId}. */\n runtimeAgentId?: undefined;\n}\n\n/**\n * Props for {@link useAgent}.\n *\n * There are exactly two valid shapes, and the type admits nothing in between:\n *\n * - **Bind to an agent** — `useAgent()`, `useAgent({ agentId })`. The shared\n * instance from the registry; the thread comes from the chat configuration.\n * - **Bind a private agent to a thread** —\n * `useAgent({ agentId, runtimeAgentId, threadId })`. All three required.\n *\n * So `useAgent({ agentId, threadId })`, `useAgent({ agentId, runtimeAgentId })`,\n * and `useAgent({ runtimeAgentId, threadId })` are all compile errors. Each\n * partial combination is either unsafe (a thread scoped onto a shared singleton)\n * or pointless (a private agent with no thread, or one registered over an id\n * that already belongs to a real agent).\n */\nexport type UseAgentProps = UseAgentPropsBase &\n (UseAgentThreadScopedProps | UseAgentUnscopedProps);\n\nexport function useAgent({\n agentId,\n threadId,\n runtimeAgentId,\n updates,\n throttleMs,\n}: UseAgentProps = {}) {\n // Runtime backstop for the all-or-nothing rule UseAgentProps enforces at\n // compile time (plain JS, `as any`, props widened at a call boundary).\n ɵvalidateAgentBinding({ agentId, threadId, runtimeAgentId });\n\n // Explicit prop, then the surrounding chat configuration (#5533), then the\n // provider default, then DEFAULT_AGENT_ID.\n const chatConfig = useCopilotChatConfiguration();\n const providerAgentId = useDefaultAgentId();\n const resolvedAgentId = ɵresolveAgentId({\n agentId,\n chatAgentId: chatConfig?.agentId,\n providerAgentId,\n });\n\n const { copilotkit } = useCopilotKit();\n const resolver = ɵgetAgentResolver(copilotkit);\n const revision = useSyncExternalStore(\n resolver.subscribe,\n resolver.getSnapshot,\n resolver.getSnapshot,\n );\n // Read the provider-level default so it appears in the effect's dep array.\n // subscribeToAgentWithOptions reads it from the core instance, but React\n // needs the dep to know when to re-subscribe.\n const providerThrottleMs = copilotkit.defaultThrottleMs;\n\n const [, forceUpdate] = useReducer((x) => x + 1, 0);\n\n const updateFlags = useMemo(\n () => updates ?? ALL_UPDATES,\n [JSON.stringify(updates)],\n );\n\n // Thread-scoped path: register a private proxied agent for this hook as one\n // balanced effect (StrictMode-safe: the cleanup unregisters before the\n // remount re-registers). The resolver notifies, so the hook swaps from the\n // provisional stand-in to the real proxy.\n useEffect(() => {\n if (runtimeAgentId == null) return;\n return resolver.bindProxy({ agentId: resolvedAgentId, runtimeAgentId });\n }, [resolver, resolvedAgentId, runtimeAgentId]);\n\n // Keyed on the header generation, not header values: a builder returning a\n // new token on every resolution must not re-resolve (#1937).\n const headersGeneration = copilotkit.ɵheadersGeneration;\n const { agent, isReady } = useMemo(\n () =>\n resolver.resolve({\n agentId: resolvedAgentId,\n runtimeAgentId,\n caller: \"useAgent\",\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n resolver,\n revision,\n resolvedAgentId,\n runtimeAgentId,\n copilotkit.agents,\n copilotkit.runtimeConnectionStatus,\n copilotkit.runtimeUrl,\n copilotkit.runtimeTransport,\n copilotkit.credentials,\n headersGeneration,\n ],\n );\n\n useEffect(\n () =>\n ɵsubscribeToAgentUpdates(copilotkit, agent, {\n updates: updateFlags,\n throttleMs,\n onUpdate: forceUpdate,\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [agent, forceUpdate, throttleMs, providerThrottleMs, updateFlags],\n );\n\n // Keep request settings fresh outside useMemo: mutating inside it is unsafe\n // in concurrent mode.\n useEffect(() => {\n resolver.refreshRequestSettings(agent);\n }, [resolver, agent, headersGeneration, copilotkit.credentials]);\n\n // Pin the thread onto the agent. AbstractAgent auto-mints a UUID, so without\n // this the agent ships its own random id in /agent/run, /agent/connect and\n // /agent/stop.\n const resolvedThreadId = ɵresolveAgentThreadId({\n threadId,\n chatThreadId: chatConfig?.threadId,\n chatHasExplicitThreadId: chatConfig?.hasExplicitThreadId,\n });\n useEffect(() => {\n if (!resolvedThreadId) return;\n agent.threadId = resolvedThreadId;\n }, [agent, resolvedThreadId]);\n\n return {\n agent,\n /**\n * Whether `agent` is the real, runtime-synced (or locally-registered) agent\n * rather than a provisional stand-in returned while the runtime is still\n * connecting (or in an error state).\n *\n * `agent` is always a fully-constructed `AbstractAgent`, so calling\n * `agent.subscribe(...)`, `agent.setState(...)`, etc. is always safe. But\n * while `isReady` is `false` the instance is a placeholder that will be\n * swapped for the real agent once the runtime `/info` sync resolves, at\n * which point `agent` changes reference and dependent effects re-run.\n * Guard on `isReady` when you only want to act against the real agent —\n * e.g. subscribing to run-lifecycle events you don't want to miss during\n * the provisional window (#5000).\n */\n isReady,\n };\n}\n","import { useRef } from \"react\";\n\n/**\n * Deps comparison shared by `useFrontendTool` (and through it\n * `useHumanInTheLoop` and `useComponent`) and `useRenderTool`. Not part of the\n * public API.\n */\n\nconst EMPTY_DEPS: ReadonlyArray<unknown> = [];\n\nfunction isPlainObject(value: object): boolean {\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * Plain data (primitives, plain objects, arrays, dates) compares by value.\n * Functions always compare equal: these hooks used to compare\n * `JSON.stringify(deps)`, which turns every function into `null`, and a\n * function that counted as changed would re-register on every render when it\n * is written inline (and loop in a component that also reads\n * `useRenderToolCall`). Everything else (class instances, maps, sets) compares\n * by identity. A cycle inside plain data is safe: a pair already being\n * compared counts as equal for that branch.\n */\nfunction depEqual(a: unknown, b: unknown, seen: Map<object, object>): boolean {\n if (Object.is(a, b)) return true;\n if (typeof a === \"function\" && typeof b === \"function\") return true;\n if (\n typeof a !== \"object\" ||\n typeof b !== \"object\" ||\n a === null ||\n b === null\n ) {\n return false;\n }\n if (a instanceof Date && b instanceof Date) {\n return Object.is(a.getTime(), b.getTime());\n }\n const aIsArray = Array.isArray(a);\n if (aIsArray !== Array.isArray(b)) return false;\n if (!aIsArray && !(isPlainObject(a) && isPlainObject(b))) return false;\n\n if (seen.get(a) === b) return true;\n seen.set(a, b);\n\n if (aIsArray) {\n const left = a as unknown[];\n const right = b as unknown[];\n if (left.length !== right.length) return false;\n for (let i = 0; i < left.length; i++) {\n if (!depEqual(left[i], right[i], seen)) return false;\n }\n return true;\n }\n\n const left = a as Record<string, unknown>;\n const right = b as Record<string, unknown>;\n const leftKeys = Object.keys(left);\n if (leftKeys.length !== Object.keys(right).length) return false;\n for (const key of leftKeys) {\n if (!Object.prototype.hasOwnProperty.call(right, key)) return false;\n if (!depEqual(left[key], right[key], seen)) return false;\n }\n return true;\n}\n\n/** Whether two deps arrays are equal. A change in length is always a change. */\nexport function depsEqual(\n prev: ReadonlyArray<unknown>,\n next: ReadonlyArray<unknown>,\n): boolean {\n if (prev.length !== next.length) return false;\n const seen = new Map<object, object>();\n for (let i = 0; i < prev.length; i++) {\n if (!depEqual(prev[i], next[i], seen)) return false;\n }\n return true;\n}\n\n/**\n * Turns a caller's `deps` array into a number that changes exactly when the\n * deps change, by the rules of {@link depsEqual}. Put the number, not the\n * array, in the registration effect's dependency list: that keeps the list a\n * constant length and never serializes a value.\n */\nexport function useDepsVersion(deps?: ReadonlyArray<unknown>): number {\n const next = deps ?? EMPTY_DEPS;\n const ref = useRef({ deps: next, version: 0 });\n if (ref.current.deps !== next && !depsEqual(ref.current.deps, next)) {\n ref.current = { deps: next, version: ref.current.version + 1 };\n }\n return ref.current.version;\n}\n","import { useLayoutEffect } from \"react\";\nimport { useCopilotKit } from \"../context\";\nimport type { ReactFrontendTool } from \"../types/frontend-tool\";\nimport { useDepsVersion } from \"./tool-registration\";\n\n/**\n * Register a frontend tool while the component is mounted. The agent can\n * call it, and its `render` component draws the call in the chat.\n *\n * A tool with the same name and agentId as a tool that is already registered\n * (for example one from the provider's `tools`) overrides it while this\n * component is mounted. When the component unmounts, the overridden tool is\n * active again. The renderer stays registered after unmount, so past tool\n * calls still render in the chat history.\n *\n * @param tool - The tool to register.\n * @param deps - Extra values that re-register the tool when they change. Use\n * it when the handler closes over a value that is not part of the tool.\n *\n * @example\n * ```tsx\n * useFrontendTool({\n * name: \"showWeather\",\n * description: \"Show the weather for a city\",\n * parameters: z.object({ city: z.string() }),\n * handler: async ({ city }) => `Sunny in ${city}`,\n * });\n * ```\n */\nexport function useFrontendTool<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(tool: ReactFrontendTool<T>, deps?: ReadonlyArray<unknown>) {\n const { copilotkit } = useCopilotKit();\n // Plain data in `deps` compares by value, everything else by identity; see\n // useDepsVersion. Only the resulting number enters the effect's dependency\n // list, so `deps` is never serialized and may hold a circular value such as\n // the agent from useAgent.\n const depsVersion = useDepsVersion(deps);\n\n useLayoutEffect(() => {\n const name = tool.name;\n\n // This registration hides any tool with the same name and agentId (a\n // provider tool or another hook) until this effect cleans up. Unregistering\n // brings the hidden tool back.\n if (copilotkit.getTool({ toolName: name, agentId: tool.agentId })) {\n console.warn(\n `Tool '${name}' already exists for agent '${tool.agentId || \"global\"}'. Overriding with latest registration.`,\n );\n }\n const unregister = copilotkit.addTool(tool);\n\n // Register/override renderer by name and agentId through core.\n // The render function is registered even when tool.parameters is\n // undefined — tools like HITL confirm dialogs have no parameters\n // but still need their UI rendered in the chat.\n if (tool.render) {\n copilotkit.addHookRenderToolCall({\n name,\n args: tool.parameters,\n agentId: tool.agentId,\n render: tool.render,\n });\n }\n\n return () => {\n unregister();\n // we are intentionally not removing the render here so that the tools can still render in the chat history\n };\n // Depend on stable keys by default and allow callers to opt into\n // additional dependencies for dynamic tool configuration.\n // tool.available is included so toggling availability re-registers the tool.\n // tool.webmcp is compared by value (it is commonly an object literal), so\n // a changed WebMCP config re-registers without churning on identity.\n }, [\n tool.name,\n tool.available,\n copilotkit,\n depsVersion,\n JSON.stringify(tool.webmcp ?? null),\n ]);\n}\n","import { useLayoutEffect } from \"react\";\nimport { useCopilotKit } from \"../context\";\nimport type { ReactFrontendTool } from \"../types/frontend-tool\";\n\nconst EMPTY_DEPS: ReadonlyArray<unknown> = [];\nconst EMPTY_TOOLS: ReadonlyArray<ReactFrontendTool<any>> = [];\n\n/**\n * Register a list of frontend tools whose length can change between renders.\n *\n * `useFrontendTool` registers exactly one tool per call, so it cannot be called\n * in a loop over a runtime-length list without breaking the rules of hooks.\n * This hook runs a single effect over the whole array instead, which makes it\n * safe to build the list from state, props, or a server response.\n *\n * Tools are keyed by `name` plus `agentId`, the same as `useFrontendTool`. A\n * tool that disappears from the array is unregistered on the next render, and\n * every tool is unregistered on unmount. A listed tool hides a tool with the\n * same name and agentId (for example one from the provider's `tools`) until it\n * is unregistered, and then the hidden tool is active again. Renderers stay\n * registered after unmount so past tool calls still render in the chat history.\n *\n * @param tools - The tools to register. May be empty and may change length.\n * @param deps - Extra dependencies that force re-registration, compared by\n * identity like the second argument of `useEffect`. Use this when a handler\n * closes over a value that is not part of the tool definition. Keep the array\n * a constant length across renders.\n *\n * @example\n * Register one tool per item in application state:\n * ```tsx\n * const [reports, setReports] = useState<Report[]>([]);\n *\n * useFrontendTools(\n * reports.map((report) => ({\n * name: `open_${report.id}`,\n * description: `Open the ${report.title} report`,\n * handler: async () => navigate(`/reports/${report.id}`),\n * })),\n * [navigate],\n * );\n * ```\n *\n * @example\n * Register tools described by the backend:\n * ```tsx\n * const { data } = useQuery(fetchToolDescriptors);\n *\n * useFrontendTools(\n * (data ?? []).map((descriptor) => ({\n * name: descriptor.name,\n * description: descriptor.description,\n * parameters: z.object({ query: z.string() }),\n * handler: async ({ query }) => runDescriptor(descriptor.id, query),\n * })),\n * );\n * ```\n */\nexport function useFrontendTools(\n tools: ReadonlyArray<ReactFrontendTool<any>> | undefined,\n deps?: ReadonlyArray<unknown>,\n) {\n const { copilotkit } = useCopilotKit();\n const toolList = tools ?? EMPTY_TOOLS;\n const extraDeps = deps ?? EMPTY_DEPS;\n\n // The array is usually built inline, so its identity changes on every render\n // and cannot be a dependency. Derive a value signature from the fields that\n // decide what the agent sees, so the effect re-runs when the set of tools\n // actually changes and not merely when the caller re-renders.\n //\n // `description` is in the signature even though useFrontendTool does not key\n // on it. A singular caller writes a literal description, so it never changes\n // without the component re-mounting. This hook exists to build tools from\n // data, where the description is usually derived from that data, and a\n // description the agent reads must not go stale while the names stay put.\n const signature = JSON.stringify(\n toolList.map((tool) => [\n tool.name,\n tool.description ?? null,\n tool.agentId ?? null,\n tool.available ?? null,\n tool.webmcp ?? null,\n ]),\n );\n\n useLayoutEffect(() => {\n // Collapse duplicate names so the last entry wins, which matches the\n // override behavior of useFrontendTool, and so the cleanup below removes\n // each (name, agentId) pair exactly once.\n const deduped = new Map<string, ReactFrontendTool<any>>();\n for (const tool of toolList) {\n const key = `${tool.agentId ?? \"\"}:${tool.name}`;\n if (deduped.has(key)) {\n console.warn(\n `Tool '${tool.name}' is listed more than once for agent '${tool.agentId || \"global\"}' in the same useFrontendTools call. Using the last entry.`,\n );\n }\n deduped.set(key, tool);\n }\n\n const registered = [...deduped.values()];\n const unregisters: Array<() => void> = [];\n\n for (const tool of registered) {\n // Each registration hides any tool with the same name and agentId (a\n // provider tool or another hook) until this effect cleans up.\n if (copilotkit.getTool({ toolName: tool.name, agentId: tool.agentId })) {\n console.warn(\n `Tool '${tool.name}' already exists for agent '${tool.agentId || \"global\"}'. Overriding with latest registration.`,\n );\n }\n unregisters.push(copilotkit.addTool(tool));\n\n // Register/override renderer by name and agentId through core.\n // The render function is registered even when tool.parameters is\n // undefined — tools like HITL confirm dialogs have no parameters\n // but still need their UI rendered in the chat.\n if (tool.render) {\n copilotkit.addHookRenderToolCall({\n name: tool.name,\n args: tool.parameters,\n agentId: tool.agentId,\n render: tool.render,\n });\n }\n }\n\n return () => {\n // Remove exactly what this run registered. Reading the current array here\n // would miss a tool that was dropped from it before the effect re-ran.\n // Unregistering brings back any tool these registrations hid.\n for (const unregister of unregisters) {\n unregister();\n }\n // we are intentionally not removing the render here so that the tools can still render in the chat history\n };\n // `signature` is the value-based key for `toolList`, so the array itself is\n // deliberately not a dependency. `available` and `webmcp` are folded into\n // the signature for the same reasons they are dependencies of\n // useFrontendTool: toggling either must re-register the tool.\n //\n // `deps` is spread rather than stringified. JSON.stringify maps a function\n // to null, so a stringified `[navigate]` is the constant \"[null]\", and a\n // changed callback would never re-register. That is exactly the case `deps`\n // exists to cover. Spreading gives the entries React's own identity\n // comparison, the same contract as the second argument of useEffect. Pass a\n // deps array of a constant length, as React requires everywhere else.\n }, [signature, copilotkit, ...extraDeps]);\n}\n","import type { StandardSchemaV1, InferSchemaOutput } from \"@copilotkit/shared\";\nimport { ɵcomponentToolDescription } from \"@copilotkit/core\";\nimport type { ComponentType } from \"react\";\nimport { useFrontendTool } from \"./use-frontend-tool\";\n\ntype InferRenderProps<T> = T extends StandardSchemaV1\n ? InferSchemaOutput<T>\n : any;\n\n/**\n * Registers a React component as a frontend tool renderer in chat.\n *\n * This hook is a convenience wrapper around `useFrontendTool` that:\n * - builds a model-facing tool description,\n * - forwards optional schema parameters (any Standard Schema V1 compatible library),\n * - renders your component with tool call parameters.\n *\n * Use this when you want to display a typed visual component for a tool call\n * without manually wiring a full frontend tool object.\n *\n * When `parameters` is provided, render props are inferred from the schema.\n * When omitted, the render component may accept any props.\n *\n * @typeParam TSchema - Schema describing tool parameters, or `undefined` when no schema is given.\n * @param config - Tool registration config.\n * @param deps - Optional dependencies to refresh registration (same semantics as `useEffect`).\n *\n * @example\n * ```tsx\n * // Without parameters — render accepts any props\n * useComponent({\n * name: \"showGreeting\",\n * render: ({ message }: { message: string }) => <div>{message}</div>,\n * });\n * ```\n *\n * @example\n * ```tsx\n * // With parameters — render props inferred from schema\n * useComponent({\n * name: \"showWeatherCard\",\n * parameters: z.object({ city: z.string() }),\n * render: ({ city }) => <div>{city}</div>,\n * });\n * ```\n *\n * @example\n * ```tsx\n * useComponent(\n * {\n * name: \"renderProfile\",\n * parameters: z.object({ userId: z.string() }),\n * render: ProfileCard,\n * agentId: \"support-agent\",\n * },\n * [selectedAgentId],\n * );\n * ```\n */\nexport function useComponent<\n TSchema extends StandardSchemaV1<any, Record<string, unknown>> | undefined =\n undefined,\n>(\n config: {\n name: string;\n description?: string;\n parameters?: TSchema;\n render: ComponentType<NoInfer<InferRenderProps<TSchema>>>;\n agentId?: string;\n followUp?: boolean;\n },\n deps?: ReadonlyArray<unknown>,\n): void {\n const fullDescription = ɵcomponentToolDescription(\n config.name,\n config.description,\n );\n\n useFrontendTool(\n {\n name: config.name,\n description: fullDescription,\n parameters: config.parameters,\n render: ({ args }: { args: unknown }) => {\n const Component = config.render;\n return <Component {...(args as InferRenderProps<TSchema>)} />;\n },\n agentId: config.agentId,\n followUp: config.followUp,\n },\n deps,\n );\n}\n","import { useCopilotKit } from \"../context\";\nimport type { ReactFrontendTool } from \"../types/frontend-tool\";\nimport type { ReactHumanInTheLoop } from \"../types/human-in-the-loop\";\nimport type { ReactToolCallRenderer } from \"../types/react-tool-call-renderer\";\nimport { ɵbuildHumanInTheLoopTool, ɵhitlRenderProps } from \"@copilotkit/core\";\nimport { useCallback, useLayoutEffect } from \"react\";\nimport React from \"react\";\nimport { useFrontendTool } from \"./use-frontend-tool\";\n\nexport function useHumanInTheLoop<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(tool: ReactHumanInTheLoop<T>, deps?: ReadonlyArray<unknown>) {\n const { copilotkit } = useCopilotKit();\n // Core parks each call by tool call id, so parallel calls of this tool\n // (or of a \"*\" catch-all) each get their own `respond`.\n const registry = copilotkit.ɵhumanInTheLoop;\n\n const RenderComponent: ReactToolCallRenderer<T>[\"render\"] = useCallback(\n (props) =>\n React.createElement(\n tool.render,\n ɵhitlRenderProps<T, typeof props>(props, tool, registry),\n ),\n // eslint-disable-next-line react-hooks/exhaustive-deps -- tool is a fresh object each render; depend on the fields the renderer reads\n [tool.render, tool.name, tool.description, tool.agentId, registry],\n );\n\n const frontendTool: ReactFrontendTool<T> = {\n ...ɵbuildHumanInTheLoopTool<T>(tool, registry),\n render: RenderComponent,\n };\n\n useFrontendTool(frontendTool, deps);\n\n // Human-in-the-loop tools should remove their renderer on unmount\n // since they can't respond to user interactions anymore.\n //\n // This MUST stay a layout effect to match `useFrontendTool`, which registers\n // the renderer in its own layout effect. React runs every cleanup in a phase\n // before any effect of that same phase, but it runs the whole layout phase\n // ahead of the whole passive phase. If this teardown were passive while the\n // registration is layout, a keyed remount would order the outgoing\n // instance's removal *after* the incoming instance's registration and delete\n // the renderer that had just been added, leaving the tool unrenderable.\n useLayoutEffect(() => {\n return () => {\n copilotkit.removeHookRenderToolCall(tool.name, tool.agentId);\n };\n }, [copilotkit, tool.name, tool.agentId]);\n}\n","import React, {\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport type { Interrupt } from \"@ag-ui/client\";\nimport { ɵInterruptController } from \"@copilotkit/core\";\nimport { useCopilotKit } from \"../context\";\nimport { useAgent } from \"./use-agent\";\nimport type {\n InterruptEvent,\n InterruptRenderProps,\n InterruptHandlerProps,\n} from \"../types/interrupt\";\n\nexport type {\n InterruptEvent,\n InterruptRenderProps,\n InterruptHandlerProps,\n Interrupt,\n};\n\ntype InterruptHandlerFn<TValue, TResult> = (\n props: InterruptHandlerProps<TValue>,\n) => TResult | PromiseLike<TResult>;\n\ntype InterruptResultFromHandler<THandler> = THandler extends (\n ...args: never[]\n) => infer TResult\n ? TResult extends PromiseLike<infer TResolved>\n ? TResolved | null\n : TResult | null\n : null;\n\ntype InterruptResult<TValue, TResult> = InterruptResultFromHandler<\n InterruptHandlerFn<TValue, TResult>\n>;\n\ntype InterruptRenderInChat = boolean | undefined;\n\ntype UseInterruptReturn<TRenderInChat extends InterruptRenderInChat> =\n TRenderInChat extends false\n ? React.ReactElement | null\n : TRenderInChat extends true | undefined\n ? void\n : React.ReactElement | null | void;\n\n/**\n * Configuration options for `useInterrupt`.\n */\ninterface UseInterruptConfigBase<TValue = unknown, TResult = never> {\n /**\n * Render function for the interrupt UI.\n *\n * Receives both the standard `interrupt`/`interrupts` and the legacy `event`.\n * Call `resolve(payload)` to resume with user input, or `cancel()` to cancel.\n */\n render: (\n props: InterruptRenderProps<TValue, InterruptResult<TValue, TResult>>,\n ) => React.ReactElement;\n /**\n * Optional pre-render handler invoked when an interrupt is received.\n * Return a sync or async value to expose as `result` in `render`.\n * Rejecting/throwing falls back to `result = null`.\n */\n handler?: InterruptHandlerFn<TValue, TResult>;\n /**\n * Optional predicate to filter which interrupts this hook handles.\n * Receives the legacy-compatible event (for standard interrupts, `value` is\n * the primary `Interrupt`). Return `false` to ignore.\n */\n enabled?: (event: InterruptEvent<TValue>) => boolean;\n /** Optional agent id. Defaults to the current configured chat agent. */\n agentId?: string;\n}\n\nexport interface UseInterruptInChatConfig<\n TValue = unknown,\n TResult = never,\n> extends UseInterruptConfigBase<TValue, TResult> {\n /** When true (default), the interrupt UI renders inside `<CopilotChat>` automatically. */\n renderInChat?: true;\n}\n\nexport interface UseInterruptExternalConfig<\n TValue = unknown,\n TResult = never,\n> extends UseInterruptConfigBase<TValue, TResult> {\n /** When false, the hook returns the interrupt element so you can place it yourself. */\n renderInChat: false;\n}\n\nexport interface UseInterruptDynamicConfig<\n TValue = unknown,\n TResult = never,\n> extends UseInterruptConfigBase<TValue, TResult> {\n /** Dynamic boolean mode. When non-literal, return type is a union. */\n renderInChat: boolean;\n}\n\nexport type UseInterruptConfig<\n TValue = unknown,\n TResult = never,\n TRenderInChat extends InterruptRenderInChat = undefined,\n> = UseInterruptConfigBase<TValue, TResult> & {\n /** When true (default), the interrupt UI renders inside `<CopilotChat>` automatically. */\n renderInChat?: TRenderInChat;\n};\n\n/**\n * Handles agent interrupts with optional filtering, preprocessing, and resume behavior.\n *\n * Supports both the AG-UI standard interrupt flow (`RUN_FINISHED` with\n * `outcome.type === \"interrupt\"`) and the legacy custom-event flow\n * (`on_interrupt`). For standard interrupts, `render` receives `interrupt`\n * (the primary one) and `interrupts` (the full open set); call `resolve(payload)`\n * to resume or `cancel()` to cancel. Resuming addresses the targeted interrupt\n * and, once every open interrupt is addressed, submits a single spec `resume`\n * array via `copilotkit.runAgent`.\n *\n * - `renderInChat: true` (default): the element is published into `<CopilotChat>`; returns `void`.\n * - `renderInChat: false`: the hook returns the interrupt element for manual placement.\n *\n * @example\n * ```tsx\n * useInterrupt({\n * render: ({ interrupt, resolve, cancel }) => (\n * <div>\n * <p>{interrupt?.message}</p>\n * <button onClick={() => resolve({ approved: true })}>Approve</button>\n * <button onClick={() => cancel()}>Cancel</button>\n * </div>\n * ),\n * });\n * ```\n */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport function useInterrupt<\n TResult = never,\n TRenderInChat extends InterruptRenderInChat = undefined,\n>(\n config: UseInterruptConfig<any, TResult, TRenderInChat>,\n): UseInterruptReturn<TRenderInChat> {\n /* eslint-enable @typescript-eslint/no-explicit-any */\n const { copilotkit } = useCopilotKit();\n const { agent } = useAgent({ agentId: config.agentId, updates: [] });\n\n // Read consumer callbacks through refs so inline lambdas neither recreate\n // the controller nor churn the element memo.\n const renderRef = useRef(config.render);\n renderRef.current = config.render;\n const enabledRef = useRef(config.enabled);\n enabledRef.current = config.enabled;\n const handlerRef = useRef(config.handler);\n handlerRef.current = config.handler;\n const copilotkitRef = useRef(copilotkit);\n copilotkitRef.current = copilotkit;\n\n const [controller] = useState(\n () =>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n new ɵInterruptController<any, TResult>(\n { runAgent: (params) => copilotkitRef.current.runAgent(params) },\n {\n enabled: (event) => enabledRef.current?.(event) ?? true,\n handler: (props) =>\n handlerRef.current ? handlerRef.current(props) : (null as TResult),\n },\n ),\n );\n\n useEffect(() => {\n controller.connect(agent);\n return () => controller.disconnect();\n }, [controller, agent]);\n\n const { renderProps } = useSyncExternalStore(\n controller.subscribe,\n controller.getSnapshot,\n controller.getSnapshot,\n );\n\n const element = useMemo(\n () => (renderProps ? renderRef.current(renderProps) : null),\n [renderProps],\n );\n\n // Publish to core for in-chat rendering. Publish-only.\n useEffect(() => {\n if (config.renderInChat === false) return;\n copilotkit.setInterruptElement(element);\n }, [element, config.renderInChat, copilotkit]);\n\n // Nullify on true unmount only.\n useEffect(() => {\n if (config.renderInChat === false) return;\n return () => {\n copilotkit.setInterruptElement(null);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n if (config.renderInChat === false) {\n return element as UseInterruptReturn<TRenderInChat>;\n }\n\n return undefined as UseInterruptReturn<TRenderInChat>;\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { ɵsubscribeToAgentSuggestions } from \"@copilotkit/core\";\nimport type { Suggestion } from \"@copilotkit/core\";\nimport { useCopilotKit, useDefaultAgentId } from \"../context\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\nimport { DEFAULT_AGENT_ID } from \"@copilotkit/shared\";\n\nexport interface UseSuggestionsOptions {\n agentId?: string;\n}\n\nexport interface UseSuggestionsResult {\n suggestions: Suggestion[];\n reloadSuggestions: () => void;\n clearSuggestions: () => void;\n isLoading: boolean;\n}\n\nexport function useSuggestions({\n agentId,\n}: UseSuggestionsOptions = {}): UseSuggestionsResult {\n const { copilotkit } = useCopilotKit();\n const config = useCopilotChatConfiguration();\n const providerAgentId = useDefaultAgentId();\n const resolvedAgentId = useMemo(\n () => agentId ?? config?.agentId ?? providerAgentId ?? DEFAULT_AGENT_ID,\n [agentId, config?.agentId, providerAgentId],\n );\n\n const [result, setResult] = useState(() =>\n copilotkit.getSuggestions(resolvedAgentId),\n );\n\n useEffect(() => {\n setResult(copilotkit.getSuggestions(resolvedAgentId));\n return ɵsubscribeToAgentSuggestions(copilotkit, resolvedAgentId, setResult);\n }, [copilotkit, resolvedAgentId]);\n\n const reloadSuggestions = useCallback(() => {\n copilotkit.reloadSuggestions(resolvedAgentId);\n // Loading state is handled by onSuggestionsStartedLoading event\n }, [copilotkit, resolvedAgentId]);\n\n const clearSuggestions = useCallback(() => {\n copilotkit.clearSuggestions(resolvedAgentId);\n // State updates are handled by onSuggestionsChanged event\n }, [copilotkit, resolvedAgentId]);\n\n return {\n suggestions: result.suggestions,\n reloadSuggestions,\n clearSuggestions,\n isLoading: result.isLoading,\n };\n}\n","import { useEffect, useRef } from \"react\";\nimport { useCopilotKit, useDefaultAgentId } from \"../context\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\nimport { DEFAULT_AGENT_ID } from \"@copilotkit/shared\";\nimport { ɵbindSuggestionsConfig } from \"@copilotkit/core\";\nimport type {\n ɵSuggestionsBinding,\n ɵSuggestionsConfigInput,\n} from \"@copilotkit/core\";\n\n/**\n * Registers a suggestions configuration (dynamic or static) for the current\n * chat. A global config (no `consumerAgentId`, or `\"*\"`) applies to every\n * agent and loads for the surrounding chat's agent first.\n *\n * Pass `deps` to reload suggestions when values the config reads change.\n *\n * @example\n * useConfigureSuggestions({\n * instructions: \"Suggest concise next steps for the user\",\n * available: \"always\",\n * });\n */\nexport function useConfigureSuggestions(\n config: ɵSuggestionsConfigInput | null | undefined,\n deps?: ReadonlyArray<unknown>,\n): void {\n const { copilotkit } = useCopilotKit();\n const chatConfig = useCopilotChatConfiguration();\n const providerAgentId = useDefaultAgentId();\n const chatAgentId =\n chatConfig?.agentId ?? providerAgentId ?? DEFAULT_AGENT_ID;\n const extraDeps = deps ?? [];\n\n const bindingRef = useRef<ɵSuggestionsBinding | null>(null);\n const latestRef = useRef({ config, chatAgentId });\n latestRef.current = { config, chatAgentId };\n\n useEffect(() => {\n const latest = latestRef.current;\n const binding = ɵbindSuggestionsConfig(copilotkit, latest.config, {\n chatAgentId: latest.chatAgentId,\n });\n bindingRef.current = binding;\n return () => {\n binding.dispose();\n if (bindingRef.current === binding) bindingRef.current = null;\n };\n }, [copilotkit]);\n\n // The binding compares configs by content, so a new inline object on every\n // render is a no-op.\n useEffect(() => {\n bindingRef.current?.update(config, { chatAgentId });\n }, [config, chatAgentId]);\n\n const depsMountedRef = useRef(false);\n useEffect(() => {\n if (!depsMountedRef.current) {\n depsMountedRef.current = true;\n return;\n }\n if (extraDeps.length > 0) bindingRef.current?.reload();\n }, [extraDeps.length, ...extraDeps]);\n}\n","import { useCopilotKit } from \"../context\";\nimport { useLayoutEffect, useMemo } from \"react\";\nimport { ɵserializeContextValue } from \"@copilotkit/core\";\nimport type { ɵJsonSerializable } from \"@copilotkit/core\";\n\n/**\n * Represents any value that can be serialized to JSON.\n */\nexport type JsonSerializable = ɵJsonSerializable;\n\n/**\n * Context configuration for useAgentContext.\n * Accepts any JSON-serializable value which will be converted to a string.\n */\nexport interface AgentContextInput {\n /** A human-readable description of what this context represents */\n description: string;\n /** The context value - will be converted to a JSON string if not already a string */\n value: JsonSerializable;\n}\n\nexport function useAgentContext(context: AgentContextInput) {\n const { description, value } = context;\n const { copilotkit } = useCopilotKit();\n\n const stringValue = useMemo(() => ɵserializeContextValue(value), [value]);\n\n useLayoutEffect(() => {\n if (!copilotkit) return;\n\n const id = copilotkit.addContext({ description, value: stringValue });\n return () => {\n copilotkit.removeContext(id);\n };\n }, [description, stringValue, copilotkit]);\n}\n","import { useCopilotKit } from \"../context\";\nimport { ɵThreadsController, ɵcreateThreadStore } from \"@copilotkit/core\";\nimport { useEffect, useState, useSyncExternalStore } from \"react\";\n\n/**\n * A conversation thread managed by CopilotKit Intelligence.\n *\n * Each thread has a unique `id`, an optional human-readable `name`, and\n * timestamp fields tracking creation and update times.\n */\nexport interface Thread {\n id: string;\n agentId: string;\n name: string | null;\n archived: boolean;\n createdAt: string;\n updatedAt: string;\n /**\n * ISO-8601 timestamp of the most recent agent run on this thread. Absent\n * when the thread has never been run. Prefer this over `updatedAt` for\n * user-facing \"last activity\" displays — it is not bumped by metadata-only\n * actions like rename or archive.\n */\n lastRunAt?: string;\n}\n\n/**\n * Configuration for the {@link useThreads} hook.\n *\n * Thread operations are scoped to the runtime-authenticated user and the\n * provided agent on CopilotKit Intelligence.\n */\nexport interface UseThreadsInput {\n /** The ID of the agent whose threads to list and manage. */\n agentId: string;\n /** When `true`, archived threads are included in the list. Defaults to `false`. */\n includeArchived?: boolean;\n /** Maximum number of threads to fetch per page. When set, enables cursor-based pagination. */\n limit?: number;\n /**\n * When `false`, the hook stays inert: no runtime context is dispatched, so\n * NO thread-list fetch or realtime subscription is issued. Used by gated\n * surfaces (e.g. an unlicensed `<CopilotThreadsDrawer>`) that must not touch the\n * network until the gate opens. Defaults to `true`.\n *\n * Flipping `enabled` back to `true` resumes normal fetching on the next\n * effect run; mutations are likewise short-circuited while disabled.\n */\n enabled?: boolean;\n}\n\n/**\n * Return value of the {@link useThreads} hook.\n *\n * The `threads` array is kept in sync with the platform via a realtime\n * WebSocket subscription (when available) and is sorted most-recently-updated\n * first. Mutations reject with an `Error` if the platform request fails.\n */\nexport interface UseThreadsResult {\n /**\n * Threads for the current user/agent pair, sorted by most recently\n * updated first. Updated in realtime when the platform pushes metadata\n * events. Includes archived threads only when `includeArchived` is set.\n */\n threads: Thread[];\n /**\n * `true` while the initial thread list is being fetched from the platform.\n * Subsequent realtime updates do not re-enter the loading state.\n */\n isLoading: boolean;\n /**\n * The most recent error from fetching threads or executing a mutation,\n * or `null` when there is no error. Reset to `null` on the next\n * successful fetch.\n *\n * This channel folds together developer/config errors (missing runtime URL,\n * runtime without thread endpoints) and genuine list-load/mutation failures.\n * End-user surfaces that must not leak config errors should prefer\n * {@link listError}, which excludes the config/runtime-setup errors.\n */\n error: Error | null;\n /**\n * The most recent genuine list-load or mutation error from the platform, or\n * `null`. Unlike {@link error}, this EXCLUDES developer/config errors (a\n * missing runtime URL, or a runtime that does not advertise thread\n * endpoints), so an end-user surface can render it directly without leaking\n * a developer-facing configuration message into the UI.\n */\n listError: Error | null;\n /**\n * The error from the most recent FAILED next-page (fetch-more) load, or\n * `null`. Tracked separately from {@link listError} so a paginated-load\n * failure surfaces an inline \"couldn't load more\" affordance while the\n * already-loaded list stays visible. Cleared when a fetch-more is retried or\n * succeeds.\n */\n fetchMoreError: Error | null;\n /**\n * `true` when there are more threads available to fetch via\n * {@link fetchMoreThreads}. Only meaningful when `limit` is set.\n */\n hasMoreThreads: boolean;\n /**\n * `true` while a subsequent page of threads is being fetched.\n */\n isFetchingMoreThreads: boolean;\n /**\n * `true` while at least one thread mutation (rename, archive, unarchive,\n * delete) is awaiting a server response. Mutations apply optimistically, so\n * this is primarily useful for disabling controls or showing a subtle\n * in-flight indicator.\n */\n isMutating: boolean;\n /**\n * Fetch the next page of threads. No-op when {@link hasMoreThreads} is\n * `false` or a fetch is already in progress.\n */\n fetchMoreThreads: () => void;\n /**\n * Re-fetch the thread list from the platform without clearing the current\n * list. Backs the drawer's error-state Retry and the Active/All filter\n * refetch. No-op until the runtime is connected.\n */\n refetchThreads: () => void;\n /**\n * Reset to a fresh, non-explicit client-side thread so the welcome screen\n * shows. Lazy creation: no row appears in {@link threads} until the new\n * thread's first run persists server-side.\n */\n startNewThread: () => void;\n /**\n * Rename a thread on the platform.\n * Resolves when the server confirms the update; rejects on failure.\n */\n renameThread: (threadId: string, name: string) => Promise<void>;\n /**\n * Archive a thread on the platform.\n * Archived threads are excluded from subsequent list results.\n * Resolves when the server confirms the update; rejects on failure.\n */\n archiveThread: (threadId: string) => Promise<void>;\n /**\n * Restore a previously archived thread on the platform.\n * The thread re-appears in default (non-archived) list results.\n * Resolves when the server confirms the update; rejects on failure.\n */\n unarchiveThread: (threadId: string) => Promise<void>;\n /**\n * Permanently delete a thread from the platform.\n * This is irreversible. Resolves when the server confirms deletion;\n * rejects on failure.\n */\n deleteThread: (threadId: string) => Promise<void>;\n}\n\n/**\n * React hook for listing and managing CopilotKit Intelligence threads.\n *\n * On mount the hook fetches the thread list for the runtime-authenticated user\n * and the given `agentId`. When CopilotKit Intelligence exposes a WebSocket\n * URL, it also opens a realtime subscription so the `threads` array stays\n * current without polling — thread creates, renames, archives, and deletes\n * from any client are reflected immediately.\n *\n * Mutation methods (`renameThread`, `archiveThread`, `unarchiveThread`,\n * `deleteThread`) return promises that resolve once the platform confirms the\n * operation and reject with an `Error` on failure.\n *\n * @param input - Agent identifier and optional list controls.\n * @returns Thread list state and stable mutation callbacks.\n *\n * @example\n * ```tsx\n * import { useThreads } from \"@copilotkit/react-core\";\n *\n * function ThreadList() {\n * const { threads, isLoading, renameThread, deleteThread } = useThreads({\n * agentId: \"agent-1\",\n * });\n *\n * if (isLoading) return <p>Loading…</p>;\n *\n * return (\n * <ul>\n * {threads.map((t) => (\n * <li key={t.id}>\n * {t.name ?? \"Untitled\"}\n * <button onClick={() => renameThread(t.id, \"New name\")}>Rename</button>\n * <button onClick={() => deleteThread(t.id)}>Delete</button>\n * </li>\n * ))}\n * </ul>\n * );\n * }\n * ```\n */\nexport function useThreads({\n agentId,\n includeArchived,\n limit,\n enabled = true,\n}: UseThreadsInput): UseThreadsResult {\n const { copilotkit } = useCopilotKit();\n\n // Core's ɵThreadsController owns the view model: thread projection, the\n // configuration errors, the gated and de-duplicated context dispatch, the\n // registry claim and the mutation guard. This hook feeds it and renders it.\n const [controller] = useState(\n () =>\n new ɵThreadsController(\n ɵcreateThreadStore({ fetch: copilotkit.ɵruntimeFetch }),\n { core: copilotkit, agentId, includeArchived, limit, enabled },\n ),\n );\n const {\n threads,\n isLoading,\n error,\n listError,\n fetchMoreError,\n hasMoreThreads,\n isFetchingMoreThreads,\n isMutating,\n } = useSyncExternalStore(\n controller.subscribe,\n controller.getSnapshot,\n controller.getServerSnapshot,\n );\n\n useEffect(() => controller.start(), [controller]);\n\n useEffect(() => {\n controller.update({\n core: copilotkit,\n agentId,\n includeArchived,\n limit,\n enabled,\n });\n }, [\n controller,\n copilotkit,\n agentId,\n includeArchived,\n limit,\n enabled,\n copilotkit.runtimeUrl,\n copilotkit.runtimeConnectionStatus,\n copilotkit.ɵheadersGeneration,\n copilotkit.intelligence?.wsUrl,\n copilotkit.threadEndpoints?.list,\n copilotkit.threadEndpoints?.mutations,\n ]);\n\n const {\n fetchMoreThreads,\n refetchThreads,\n startNewThread,\n renameThread,\n archiveThread,\n unarchiveThread,\n deleteThread,\n } = controller;\n\n return {\n threads,\n isLoading,\n error,\n listError,\n fetchMoreError,\n hasMoreThreads,\n isFetchingMoreThreads,\n isMutating,\n fetchMoreThreads,\n refetchThreads,\n startNewThread,\n renameThread,\n archiveThread,\n unarchiveThread,\n deleteThread,\n };\n}\n","import type React from \"react\";\nimport { ɵanySchema } from \"@copilotkit/shared\";\nimport type { StandardSchemaV1, InferSchemaOutput } from \"@copilotkit/shared\";\nimport type { ToolCallRenderProps } from \"@copilotkit/core\";\nimport type { ReactToolCallRenderer } from \"./react-tool-call-renderer\";\n\n/**\n * Helper to define a type-safe tool call renderer entry.\n * - Accepts a single object whose keys match ReactToolCallRenderer's fields: { name, args, render, agentId? }.\n * - Derives `args` type from the provided schema (any Standard Schema V1 compatible library).\n * - Ensures the render function param type exactly matches ReactToolCallRenderer<T>[\"render\"]'s param.\n * - For wildcard tools (name: \"*\"), args is optional and defaults to a schema that accepts any value.\n */\n// Overload for wildcard tools without args\nexport function defineToolCallRenderer(def: {\n name: \"*\";\n render: (props: ToolCallRenderProps<any>) => React.ReactElement | null;\n agentId?: string;\n group?: boolean;\n}): ReactToolCallRenderer<any>;\n\n// Overload for regular tools with args\nexport function defineToolCallRenderer<S extends StandardSchemaV1>(def: {\n name: string;\n args: S;\n render: (\n props: ToolCallRenderProps<InferSchemaOutput<S>>,\n ) => React.ReactElement | null;\n agentId?: string;\n group?: boolean;\n}): ReactToolCallRenderer<InferSchemaOutput<S>>;\n\n// Implementation\nexport function defineToolCallRenderer<S extends StandardSchemaV1>(def: {\n name: string;\n args?: S;\n render: (props: any) => React.ReactElement | null;\n agentId?: string;\n group?: boolean;\n}): ReactToolCallRenderer<any> {\n // For wildcard tools, default to a schema that accepts any value\n const argsSchema = def.name === \"*\" && !def.args ? ɵanySchema : def.args;\n\n return {\n name: def.name,\n args: argsSchema,\n render: def.render,\n ...(def.agentId ? { agentId: def.agentId } : {}),\n ...(def.group ? { group: true } : {}),\n };\n}\n","import { useEffect } from \"react\";\nimport type { StandardSchemaV1, InferSchemaOutput } from \"@copilotkit/shared\";\nimport { ToolCallStatus } from \"@copilotkit/core\";\nimport { useCopilotKit } from \"../context\";\nimport { defineToolCallRenderer } from \"../types/defineToolCallRenderer\";\nimport { useDepsVersion } from \"./tool-registration\";\n\nexport interface RenderToolInProgressProps<S extends StandardSchemaV1> {\n name: string;\n toolCallId: string;\n parameters: Partial<InferSchemaOutput<S>>;\n status: \"inProgress\";\n result: undefined;\n}\n\nexport interface RenderToolExecutingProps<S extends StandardSchemaV1> {\n name: string;\n toolCallId: string;\n parameters: InferSchemaOutput<S>;\n status: \"executing\";\n result: undefined;\n}\n\nexport interface RenderToolCompleteProps<S extends StandardSchemaV1> {\n name: string;\n toolCallId: string;\n parameters: InferSchemaOutput<S>;\n status: \"complete\";\n result: string;\n}\n\nexport type RenderToolProps<S extends StandardSchemaV1> =\n | RenderToolInProgressProps<S>\n | RenderToolExecutingProps<S>\n | RenderToolCompleteProps<S>;\n\ntype RenderToolConfig<S extends StandardSchemaV1> = {\n name: string;\n parameters?: S;\n render: (props: RenderToolProps<S>) => React.ReactElement | null;\n agentId?: string;\n group?: boolean;\n};\n\n/**\n * Registers a wildcard (`\"*\"`) renderer for tool calls.\n *\n * The wildcard renderer is used as a fallback when no exact name-matched\n * renderer is registered for a tool call.\n *\n * @param config - Wildcard renderer configuration.\n * @param deps - Optional dependencies to refresh registration.\n *\n * @example\n * ```tsx\n * useRenderTool(\n * {\n * name: \"*\",\n * render: ({ name, status }) => (\n * <div>\n * {status === \"complete\" ? \"✓\" : \"⏳\"} {name}\n * </div>\n * ),\n * },\n * [],\n * );\n * ```\n */\nexport function useRenderTool(\n config: {\n name: \"*\";\n render: (props: any) => React.ReactElement | null;\n agentId?: string;\n /** Let the chat group the calls this renderer draws (see `toolCallDisplay`). */\n group?: boolean;\n },\n deps?: ReadonlyArray<unknown>,\n): void;\n\n/**\n * Registers a name-scoped renderer for tool calls.\n *\n * The provided `parameters` schema defines the typed shape of `props.parameters`\n * in `render` for `executing` and `complete` states. Accepts any Standard Schema V1\n * compatible library (Zod, Valibot, ArkType, etc.).\n *\n * @typeParam S - Schema type describing tool call parameters.\n * @param config - Named renderer configuration.\n * @param deps - Optional dependencies to refresh registration.\n *\n * @example\n * ```tsx\n * useRenderTool(\n * {\n * name: \"searchDocs\",\n * parameters: z.object({ query: z.string() }),\n * render: ({ status, parameters, result }) => {\n * if (status === \"inProgress\") return <div>Preparing...</div>;\n * if (status === \"executing\") return <div>Searching {parameters.query}</div>;\n * return <div>{result}</div>;\n * },\n * },\n * [],\n * );\n * ```\n */\nexport function useRenderTool<S extends StandardSchemaV1>(\n config: {\n name: string;\n parameters: S;\n render: (props: RenderToolProps<S>) => React.ReactElement | null;\n agentId?: string;\n /** Let the chat group the calls this renderer draws (see `toolCallDisplay`). */\n group?: boolean;\n },\n deps?: ReadonlyArray<unknown>,\n): void;\n\n/**\n * Registers a renderer entry in CopilotKit's `renderToolCalls` registry.\n *\n * Key behavior:\n * - deduplicates by `agentId:name` (latest registration wins),\n * - keeps renderer entries on cleanup so historical chat tool calls can still render,\n * - refreshes registration when `deps` change.\n *\n * @typeParam S - Schema type describing tool call parameters.\n * @param config - Renderer config for wildcard or named tools.\n * @param deps - Optional dependencies to refresh registration.\n *\n * @example\n * ```tsx\n * useRenderTool(\n * {\n * name: \"searchDocs\",\n * parameters: z.object({ query: z.string() }),\n * render: ({ status, parameters, result }) => {\n * if (status === \"executing\") return <div>Searching {parameters.query}</div>;\n * if (status === \"complete\") return <div>{result}</div>;\n * return <div>Preparing...</div>;\n * },\n * },\n * [],\n * );\n * ```\n *\n * @example\n * ```tsx\n * useRenderTool(\n * {\n * name: \"summarize\",\n * parameters: z.object({ text: z.string() }),\n * agentId: \"research-agent\",\n * render: ({ name, status }) => <div>{name}: {status}</div>,\n * },\n * [selectedAgentId],\n * );\n * ```\n */\nexport function useRenderTool<S extends StandardSchemaV1>(\n config: RenderToolConfig<S>,\n deps?: ReadonlyArray<unknown>,\n): void {\n const { copilotkit } = useCopilotKit();\n // Plain data in `deps` compares by value, everything else by identity; see\n // useDepsVersion. `deps` is never serialized, so it may hold a circular\n // value such as the agent from useAgent.\n const depsVersion = useDepsVersion(deps);\n\n useEffect(() => {\n // Build the ReactToolCallRenderer via defineToolCallRenderer\n const renderer =\n config.name === \"*\" && !config.parameters\n ? defineToolCallRenderer({\n name: \"*\",\n render: (props) =>\n config.render({ ...props, parameters: props.args }),\n ...(config.agentId ? { agentId: config.agentId } : {}),\n group: config.group,\n })\n : defineToolCallRenderer({\n name: config.name,\n args: config.parameters!,\n // Branch per status so the discriminated union stays correlated\n // when `args` is re-exposed as `parameters`.\n render: (props) => {\n if (props.status === ToolCallStatus.InProgress) {\n return config.render({ ...props, parameters: props.args });\n }\n if (props.status === ToolCallStatus.Executing) {\n return config.render({ ...props, parameters: props.args });\n }\n return config.render({ ...props, parameters: props.args });\n },\n ...(config.agentId ? { agentId: config.agentId } : {}),\n group: config.group,\n });\n\n copilotkit.addHookRenderToolCall(renderer);\n\n // No cleanup removal — keeps renderer for chat history, same as useFrontendTool\n }, [config.name, config.group, copilotkit, depsVersion]);\n}\n","import React, {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useSyncExternalStore,\n} from \"react\";\nimport type { ToolCall, ToolMessage } from \"@ag-ui/core\";\nimport {\n ɵbuildToolCallRenderProps,\n ɵdescribeUnrenderedToolCalls,\n ɵgetToolCallRendererNames,\n ɵresolveToolCallAgentId,\n ɵresolveToolCallRenderer,\n} from \"@copilotkit/core\";\nimport { useCopilotKit } from \"../context\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\nimport type { ReactToolCallRenderer } from \"../types/react-tool-call-renderer\";\n\nexport interface UseRenderToolCallProps {\n toolCall: ToolCall;\n toolMessage?: ToolMessage;\n}\n\n/**\n * Props for the memoized ToolCallRenderer component\n */\ninterface ToolCallRendererProps {\n toolCall: ToolCall;\n toolMessage?: ToolMessage;\n RenderComponent: ReactToolCallRenderer[\"render\"];\n isExecuting: boolean;\n}\n\n/**\n * Memoized component that renders a single tool call.\n * This prevents unnecessary re-renders when parent components update\n * but the tool call data hasn't changed.\n */\nconst ToolCallRenderer = React.memo(\n function ToolCallRenderer({\n toolCall,\n toolMessage,\n RenderComponent,\n isExecuting,\n }: ToolCallRendererProps) {\n // Rebuild only when the call, its result, or its executing state changes,\n // so `args` keeps a stable reference across unrelated renders.\n const props = useMemo(\n () => ɵbuildToolCallRenderProps(toolCall, toolMessage, { isExecuting }),\n [toolCall, toolMessage, isExecuting],\n );\n return <RenderComponent {...props} />;\n },\n // Custom comparison function to prevent re-renders when tool call data hasn't changed\n (prevProps, nextProps) => {\n // Compare tool call identity and content\n if (prevProps.toolCall.id !== nextProps.toolCall.id) return false;\n if (prevProps.toolCall.function.name !== nextProps.toolCall.function.name)\n return false;\n if (\n prevProps.toolCall.function.arguments !==\n nextProps.toolCall.function.arguments\n )\n return false;\n\n // Compare tool message (result)\n const prevResult = prevProps.toolMessage?.content;\n const nextResult = nextProps.toolMessage?.content;\n if (prevResult !== nextResult) return false;\n\n // Compare executing state\n if (prevProps.isExecuting !== nextProps.isExecuting) return false;\n\n // Compare render component reference\n if (prevProps.RenderComponent !== nextProps.RenderComponent) return false;\n\n return true;\n },\n);\n\nconst IS_DEVELOPMENT = process.env.NODE_ENV !== \"production\";\n\n/**\n * Reports tool calls that resolved to no renderer, once per tool name.\n *\n * A tool call with no renderer paints an empty message container and says\n * nothing else, so the only signal a developer gets today is a blank space in\n * the chat.\n *\n * @param toolNames - The unmatched tool names collected during render.\n * @param registered - The registry as it stands now, re-read at report time.\n * @param alreadyWarned - Names already reported, mutated to keep this once per name.\n */\nfunction warnAboutUnrenderedToolCalls(\n toolNames: readonly string[],\n registered: readonly { readonly name: string }[],\n alreadyWarned: Set<string>,\n): void {\n const fresh = toolNames.filter((name) => !alreadyWarned.has(name));\n const warnings = ɵdescribeUnrenderedToolCalls(fresh, registered);\n for (const { toolName, message } of warnings) {\n alreadyWarned.add(toolName);\n console.warn(message);\n }\n}\n\n/**\n * The tool-call renderers registered on the provider, kept current.\n * @internal\n */\nexport function useToolCallRenderers() {\n const { copilotkit } = useCopilotKit();\n // useSyncExternalStore so the value is current even if subscriptions run in\n // any order.\n return useSyncExternalStore(\n (callback) =>\n copilotkit.subscribe({ onRenderToolCallsChanged: callback }).unsubscribe,\n () => copilotkit.renderToolCalls,\n () => copilotkit.renderToolCalls,\n );\n}\n\n/**\n * Which tool names have a renderer of their own, whether a wildcard (`\"*\"`)\n * renderer is registered, and which of them opted into grouping.\n * @internal\n */\nexport function useToolCallRendererNames() {\n const renderers = useToolCallRenderers();\n return useMemo(() => ɵgetToolCallRendererNames(renderers), [renderers]);\n}\n\n/**\n * Hook that returns a function to render tool calls based on the render functions\n * defined in CopilotKitProvider.\n *\n * @returns A function that takes a tool call and optional tool message and returns the rendered component\n */\nexport function useRenderToolCall() {\n const { copilotkit, executingToolCallIds } = useCopilotKit();\n const config = useCopilotChatConfiguration();\n const agentId = ɵresolveToolCallAgentId(config?.agentId, undefined);\n\n // Development-only bookkeeping for the warning below. Collected during render\n // and reported afterwards, because the registry is not settled during render.\n const unrenderedToolNames = useRef<Set<string>>(new Set());\n const warnedToolNames = useRef<Set<string>>(new Set());\n\n const renderToolCalls = useToolCallRenderers();\n\n // `executingToolCallIds` mirrors core's set, which is filled from the first\n // `onToolExecutionStart`. A HITL call resumed on reconnect, before this\n // chat mounted, is therefore already executing on the first render.\n\n const renderToolCall = useCallback(\n ({\n toolCall,\n toolMessage,\n }: UseRenderToolCallProps): React.ReactElement | null => {\n // Rendering shows tool calls from every agent: agentId scoping only\n // affects handler execution (in core). The lookup prefers this agent's\n // renderer, then an unscoped one, then any agent's, then a wildcard.\n const renderConfig = ɵresolveToolCallRenderer(\n renderToolCalls,\n toolCall.function.name,\n agentId,\n );\n\n // No per-tool or wildcard renderer registered → render nothing.\n // Showing an unhandled tool call is opt-in: register a named/wildcard\n // renderer via useRenderTool, or call useDefaultRenderTool() for the\n // built-in card. Auto-painting a default card here would leak internal\n // tool names plus raw args/result JSON into every app's chat in\n // production, so the card must be explicitly enabled.\n if (!renderConfig) {\n if (IS_DEVELOPMENT) {\n unrenderedToolNames.current.add(toolCall.function.name);\n }\n return null;\n }\n\n const isExecuting = executingToolCallIds.has(toolCall.id);\n\n // Use the memoized ToolCallRenderer component to prevent unnecessary re-renders\n return (\n <ToolCallRenderer\n key={toolCall.id}\n toolCall={toolCall}\n toolMessage={toolMessage}\n RenderComponent={renderConfig.render}\n isExecuting={isExecuting}\n />\n );\n },\n [renderToolCalls, executingToolCallIds, agentId],\n );\n\n // Report unmatched tool calls after the commit that rendered them, deferred\n // one task past this subtree's effects. `useRenderTool` registers from an\n // effect in the component that renders the chat, and React runs child effects\n // before parent ones, so at effect time here a renderer the app does register\n // may not be in the registry yet. A timeout puts the check after every effect\n // in the tree, and `warnAboutUnrenderedToolCalls` re-reads the registry then.\n //\n // No dependency array on purpose: the misses live in a ref, so an effect that\n // only reran when `renderToolCalls` changed would never flush the common case\n // of a registry that never changes again.\n useEffect(() => {\n if (!IS_DEVELOPMENT) return;\n if (unrenderedToolNames.current.size === 0) return;\n\n const timer = setTimeout(() => {\n const pending = Array.from(unrenderedToolNames.current);\n unrenderedToolNames.current.clear();\n warnAboutUnrenderedToolCalls(\n pending,\n copilotkit.renderToolCalls,\n warnedToolNames.current,\n );\n }, 0);\n\n return () => clearTimeout(timer);\n });\n\n return renderToolCall;\n}\n","import type { AgentCapabilities } from \"@ag-ui/core\";\nimport { ɵgetAgentCapabilities } from \"@copilotkit/core\";\nimport { useAgent } from \"./use-agent\";\n\n/**\n * Returns the capabilities declared by the given agent (or the agent resolved\n * from the surrounding chat configuration, falling back to the default agent).\n * Capabilities are populated from the runtime `/info` response at connection\n * time. The hook reads them synchronously from the agent instance — there is\n * no separate loading state, but the value will be `undefined` until the\n * runtime handshake completes.\n *\n * @param agentId - Optional agent ID. If omitted, inherits the surrounding\n * chat configuration's agent, falling back to the default agent.\n * @returns The agent's capabilities, or `undefined` if the agent doesn't\n * declare capabilities.\n */\nexport function useCapabilities(\n agentId?: string,\n): AgentCapabilities | undefined {\n const { agent } = useAgent({ agentId });\n return ɵgetAgentCapabilities(agent);\n}\n"],"mappings":";;;;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AM,sBAAsB,uBAAoB,IAAI,KAAK,CAAC;CAC1D,MAAM,kBAAkB,uBAAoB,IAAI,KAAK,CAAC;CAEtD,MAAM,kBAAkB,sBAAsB;CAM9C,MAAM,iBAAiB,aACpB,EACC,UACA,kBACuD;EAIvD,MAAM,eAAe,yBACnB,iBACA,SAAS,SAAS,MAClB,QACD;AAQD,MAAI,CAAC,cAAc;AACjB,OAAI,eACF,qBAAoB,QAAQ,IAAI,SAAS,SAAS,KAAK;AAEzD,UAAO;;EAGT,MAAM,cAAc,qBAAqB,IAAI,SAAS,GAAG;AAGzD,SACE,oBAAC;GAEW;GACG;GACb,iBAAiB,aAAa;GACjB;KAJR,SAAS,GAKd;IAGN;EAAC;EAAiB;EAAsB;EAAQ,CACjD;AAYD,iBAAgB;AACd,MAAI,CAAC,eAAgB;AACrB,MAAI,oBAAoB,QAAQ,SAAS,EAAG;EAE5C,MAAM,QAAQ,iBAAiB;GAC7B,MAAM,UAAU,MAAM,KAAK,oBAAoB,QAAQ;AACvD,uBAAoB,QAAQ,OAAO;AACnC,gCACE,SACA,WAAW,iBACX,gBAAgB,QACjB;KACA,EAAE;AAEL,eAAa,aAAa,MAAM;GAChC;AAEF,QAAO;;;;;;;;;;;;;;;;;;AChNT,SAAgB,gBACd,SAC+B;CAC/B,MAAM,EAAE,UAAU,SAAS,EAAE,SAAS,CAAC;AACvC,QAAO,sBAAsB,MAAM"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
|
|
3
3
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
4
|
-
const require_MarkdownSurfaces = require('./MarkdownSurfaces-
|
|
4
|
+
const require_MarkdownSurfaces = require('./MarkdownSurfaces-v9AplTEj.cjs');
|
|
5
5
|
let _copilotkit_core = require("@copilotkit/core");
|
|
6
6
|
let react = require("react");
|
|
7
7
|
react = require_MarkdownSurfaces.__toESM(react);
|
|
@@ -860,7 +860,7 @@ function ɵuseOwnedCore(ref, create) {
|
|
|
860
860
|
|
|
861
861
|
//#endregion
|
|
862
862
|
//#region package.json
|
|
863
|
-
var version$1 = "2.0.0-rc.
|
|
863
|
+
var version$1 = "2.0.0-rc.25";
|
|
864
864
|
|
|
865
865
|
//#endregion
|
|
866
866
|
//#region src/components/CopilotKitInspector.tsx
|
|
@@ -3349,7 +3349,7 @@ function useStableArrayProp(prop, warningMessage, isMeaningfulChange) {
|
|
|
3349
3349
|
return value;
|
|
3350
3350
|
}
|
|
3351
3351
|
/** Provide a shared core instance and synchronize runtime, tool, and UI configuration. */
|
|
3352
|
-
const CopilotKitProvider = ({ children, runtimeUrl, headers: headersProp = EMPTY_HEADERS, credentials, nonce, injectStyles = true, messageFilter, publicApiKey, publicLicenseKey,
|
|
3352
|
+
const CopilotKitProvider = ({ children, runtimeUrl, headers: headersProp = EMPTY_HEADERS, credentials, nonce, injectStyles = true, messageFilter, publicApiKey, publicLicenseKey, properties = EMPTY_PROPERTIES, agents__unsafe_dev_only: agents = EMPTY_AGENTS, selfManagedAgents = EMPTY_AGENTS, renderToolCalls, renderActivityMessages, renderCustomMessages, markdownRenderer, frontendTools, humanInTheLoop, openGenerativeUI, enableInspector, agentId, showIntelligenceIndicator = true, useSingleEndpoint, onError, a2ui, generativeUI, mcpApps, defaultThrottleMs, debug, learning }) => {
|
|
3353
3353
|
const learningConfig = (0, react.useMemo)(() => (0, _copilotkit_core.ɵtoLearningConfig)(learning), [learning]);
|
|
3354
3354
|
const [shouldRenderInspector, setShouldRenderInspector] = (0, react.useState)(false);
|
|
3355
3355
|
const [inspectorVisible, setInspectorVisible] = (0, react.useState)(false);
|
|
@@ -8280,7 +8280,7 @@ function CopilotChatView({ messageView, input, scrollView, suggestionView, welco
|
|
|
8280
8280
|
const [inputContainerHeight, setInputContainerHeight] = (0, react.useState)(0);
|
|
8281
8281
|
const [isResizing, setIsResizing] = (0, react.useState)(false);
|
|
8282
8282
|
const resizeTimeoutRef = (0, react.useRef)(null);
|
|
8283
|
-
const { isKeyboardOpen, keyboardHeight
|
|
8283
|
+
const { isKeyboardOpen, keyboardHeight } = useKeyboardHeight();
|
|
8284
8284
|
(0, react.useEffect)(() => {
|
|
8285
8285
|
const element = inputContainerEl;
|
|
8286
8286
|
if (!element) {
|