@copilotkit/react-native 1.70.3 → 1.71.1

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.
Files changed (33) hide show
  1. package/USAGE.md +76 -5
  2. package/dist/headless.cjs +1 -1
  3. package/dist/headless.d.cts +59 -3
  4. package/dist/headless.d.mts +59 -3
  5. package/dist/headless.mjs +1 -1
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +3 -3
  8. package/dist/index.d.mts +3 -3
  9. package/dist/index.mjs +1 -1
  10. package/dist/useRenderTool-DFz206nL.d.cts +149 -0
  11. package/dist/useRenderTool-DsCxzyAP.d.mts +149 -0
  12. package/dist/useRenderTool-L3Rw6SYD.cjs +298 -0
  13. package/dist/useRenderTool-L3Rw6SYD.cjs.map +1 -0
  14. package/dist/useRenderTool-pLM3upcs.mjs +285 -0
  15. package/dist/useRenderTool-pLM3upcs.mjs.map +1 -0
  16. package/package.json +4 -4
  17. package/src/__mocks__/test-copilotkit.tsx +14 -2
  18. package/src/__tests__/frontend-tool-render.test-d.tsx +148 -0
  19. package/src/__tests__/headless-entry-surface.test.ts +232 -2
  20. package/src/__tests__/headless-value-exports.test.ts +16 -5
  21. package/src/components/__tests__/CopilotChatToolCalls.test.tsx +26 -22
  22. package/src/headless.ts +79 -7
  23. package/src/hooks/__tests__/render-tool-call.integration.test.tsx +17 -15
  24. package/src/hooks/__tests__/useRenderTool.test.tsx +733 -202
  25. package/src/hooks/useRenderTool.ts +482 -49
  26. package/dist/useRenderTool-BBxnOOeJ.d.mts +0 -161
  27. package/dist/useRenderTool-BWo11PCL.d.cts +0 -161
  28. package/dist/useRenderTool-CKEPq7MQ.cjs +0 -162
  29. package/dist/useRenderTool-CKEPq7MQ.cjs.map +0 -1
  30. package/dist/useRenderTool-l7M-I8rT.mjs +0 -149
  31. package/dist/useRenderTool-l7M-I8rT.mjs.map +0 -1
  32. package/src/hooks/index.ts +0 -3
  33. package/src/hooks/render-tool-types.ts +0 -55
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useRenderTool-pLM3upcs.mjs","names":["useRenderTool"],"sources":["../src/CopilotKitProvider.tsx","../src/hooks/useRenderTool.ts"],"sourcesContent":["import React, { useEffect, useMemo, useRef, useState } from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n CopilotKitContext,\n LicenseContext,\n} from \"@copilotkit/react-core/v2/context\";\nimport type {\n CopilotKitContextValue,\n CopilotKitCoreReact as CopilotKitCoreReactInstance,\n} from \"@copilotkit/react-core/v2/context\";\nimport { CopilotKitCoreReact } from \"@copilotkit/react-core/v2/headless\";\nimport type { CopilotKitCoreErrorCode } from \"@copilotkit/core\";\nimport type { DebugConfig, RuntimeLicenseStatus } from \"@copilotkit/shared\";\nimport { createLicenseContextValue } from \"@copilotkit/shared\";\n\nexport interface CopilotKitNativeProviderProps {\n children: ReactNode;\n /** URL of the CopilotKit runtime endpoint */\n runtimeUrl: string;\n /** Custom headers sent with every request */\n headers?: Record<string, string> | (() => Record<string, string>);\n /**\n * Credentials mode for fetch requests (e.g., \"include\" for HTTP-only cookies in cross-origin requests).\n */\n credentials?: RequestCredentials;\n /** Whether the runtime uses a single-route endpoint */\n useSingleEndpoint?: boolean;\n /** Custom properties forwarded to agents */\n properties?: Record<string, unknown>;\n /**\n * Error handler called when CopilotKit encounters an error.\n * Fires for all error types (runtime connection failures, agent errors, tool errors).\n * If not provided, errors are logged to console.error.\n */\n onError?: (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => void | Promise<void>;\n /**\n * Enable debug logging for the client-side event pipeline.\n * When `true`, enables verbose logging from the core instance.\n */\n debug?: DebugConfig;\n /**\n * Default throttle interval (ms) for `onMessagesChanged` / `onStateChanged`\n * subscriptions. Individual subscriptions can override with their own `throttleMs`.\n */\n defaultThrottleMs?: number;\n // Cloud features (publicApiKey, licenseToken) — not yet supported on React Native\n}\n\n/**\n * CopilotKit provider for React Native.\n *\n * A lightweight alternative to the web CopilotKitProvider that avoids\n * web-only dependencies (DOM, CSS, Radix UI, Lit, etc).\n *\n * Polyfills are auto-imported when `@copilotkit/react-native` is loaded,\n * so a separate `import \"@copilotkit/react-native/polyfills\"` is no longer\n * required (though it remains available for advanced use).\n *\n * Usage:\n * ```tsx\n * import { CopilotKitProvider } from \"@copilotkit/react-native\";\n *\n * function App() {\n * return (\n * <CopilotKitProvider runtimeUrl=\"https://your-runtime/api/copilotkit\">\n * <ChatScreen />\n * </CopilotKitProvider>\n * );\n * }\n * ```\n */\nexport const CopilotKitProvider: React.FC<CopilotKitNativeProviderProps> = ({\n children,\n runtimeUrl,\n headers: headersProp,\n credentials,\n useSingleEndpoint,\n properties,\n onError,\n debug,\n defaultThrottleMs,\n}) => {\n // Resolve headers from function or static object (matches web provider pattern)\n const resolvedHeaders =\n typeof headersProp === \"function\" ? headersProp() : headersProp;\n\n // Stabilize headers/properties references to avoid effect churn when callers\n // pass inline object literals (e.g. headers={{}} or the undefined default).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const stableHeaders = useMemo(\n () => resolvedHeaders ?? {},\n [JSON.stringify(resolvedHeaders)],\n );\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const stableProperties = useMemo(\n () => properties ?? {},\n [JSON.stringify(properties)],\n );\n\n const copilotkitRef = useRef<CopilotKitCoreReactInstance | null>(null);\n\n if (copilotkitRef.current === null) {\n const instance: CopilotKitCoreReactInstance = new CopilotKitCoreReact({\n runtimeUrl,\n runtimeTransport:\n useSingleEndpoint === true\n ? \"single\"\n : useSingleEndpoint === false\n ? \"rest\"\n : \"auto\",\n headers: stableHeaders,\n credentials,\n properties: stableProperties,\n debug,\n });\n // Set initial defaultThrottleMs synchronously so child hooks see the\n // correct value on their first render (before useEffect fires).\n if (defaultThrottleMs !== undefined) {\n instance.setDefaultThrottleMs(defaultThrottleMs);\n }\n copilotkitRef.current = instance;\n }\n\n const copilotkit = copilotkitRef.current;\n\n // Sync props to core instance\n useEffect(() => {\n copilotkit.setRuntimeUrl(runtimeUrl);\n copilotkit.setRuntimeTransport(\n useSingleEndpoint === true\n ? \"single\"\n : useSingleEndpoint === false\n ? \"rest\"\n : \"auto\",\n );\n copilotkit.setHeaders(stableHeaders);\n copilotkit.setCredentials(credentials);\n copilotkit.setProperties(stableProperties);\n copilotkit.setDebug(debug);\n }, [\n runtimeUrl,\n useSingleEndpoint,\n stableHeaders,\n credentials,\n stableProperties,\n debug,\n copilotkit,\n ]);\n\n // Sync defaultThrottleMs to the core instance on prop changes.\n // Initial value is set synchronously during instance creation (inside the\n // ref guard above), so this only handles subsequent updates.\n useEffect(() => {\n copilotkit.setDefaultThrottleMs(defaultThrottleMs);\n }, [copilotkit, defaultThrottleMs]);\n\n // Track executing tool call IDs at the provider level.\n // Critical for HITL reconnection: onToolExecutionStart fires before child\n // components mount, so we must capture the state here.\n const [executingToolCallIds, setExecutingToolCallIds] = useState<\n ReadonlySet<string>\n >(() => new Set());\n\n const [runtimeLicenseStatus, setRuntimeLicenseStatus] = useState<\n RuntimeLicenseStatus | undefined\n >(undefined);\n\n // Use ref to avoid subscription churn when onError changes\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n // Single subscription for tool execution tracking and error handling.\n // Tool call IDs are tracked at the provider level because onToolExecutionStart\n // fires before child components mount — critical for HITL reconnection.\n useEffect(() => {\n const subscription = copilotkit.subscribe({\n onToolExecutionStart: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.add(toolCallId);\n return next;\n });\n },\n onToolExecutionEnd: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (!prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.delete(toolCallId);\n return next;\n });\n },\n onError: (event) => {\n if (onErrorRef.current) {\n onErrorRef.current(event);\n } else {\n console.error(\n `[CopilotKit] Error (${event.code}):`,\n event.error,\n event.context ?? {},\n );\n }\n },\n onRuntimeConnectionStatusChanged: () => {\n setRuntimeLicenseStatus(copilotkit.licenseStatus);\n },\n });\n return () => subscription.unsubscribe();\n }, [copilotkit]);\n\n const contextValue: CopilotKitContextValue = useMemo(\n () => ({\n copilotkit,\n executingToolCallIds,\n }),\n [copilotkit, executingToolCallIds],\n );\n\n // License context — driven by server-reported status via /info endpoint\n const licenseContextValue = useMemo(\n () => createLicenseContextValue(runtimeLicenseStatus),\n [runtimeLicenseStatus],\n );\n\n return (\n <CopilotKitContext.Provider value={contextValue}>\n <LicenseContext.Provider value={licenseContextValue}>\n {children}\n </LicenseContext.Provider>\n </CopilotKitContext.Provider>\n );\n};\n","import { useEffect, useRef } from \"react\";\nimport {\n useFrontendTool,\n useRenderTool as useCoreRenderTool,\n} from \"@copilotkit/react-core/v2/headless\";\nimport type {\n ReactFrontendTool,\n RenderToolProps,\n} from \"@copilotkit/react-core/v2/headless\";\nimport { ToolCallStatus } from \"@copilotkit/core\";\nimport type { FrontendToolHandlerContext } from \"@copilotkit/core\";\nimport type { InferSchemaOutput, StandardSchemaV1 } from \"@copilotkit/shared\";\n\n/**\n * TEMPORARY COMPATIBILITY SHIM — scheduled for removal in the next minor.\n * Removal is tracked in CopilotKit/CopilotKit#6976 (Linear OSS-1148).\n *\n * ─── Why this exists at all ──────────────────────────────────────────────────\n *\n * `@copilotkit/react-native` used to export a hook named `useRenderTool` that\n * was NOT react-core's `useRenderTool`: its whole body forwarded to core's\n * OTHER hook, `useFrontendTool`, while wearing this one's name. The two are not\n * interchangeable — `useFrontendTool` registers a TOOL (advertised to the model,\n * callable by it) *and* its renderer through `addTool`, while `useRenderTool`\n * registers a RENDERER ONLY through `addHookRenderToolCall` and special-cases\n * `name: \"*\"` into a schema-less fallback. Under the alias, `name: \"*\"`\n * registered a frontend tool literally named `*`.\n *\n * ─── What a tool named `*` actually does ─────────────────────────────────────\n *\n * NOT \"gets advertised to the model\": core has never offered it. `*` is core's\n * catch-all HANDLER name, and `buildFrontendTools` filters it out of the list\n * it hands the agent (`core/src/core/run-handler.ts`, at the\n * `tool.name !== WILDCARD_TOOL_NAME` clause) precisely so the model is not\n * offered a tool whose name is a glob.\n *\n * What it does instead is worse for the affected caller. When a tool call has\n * no matching frontend tool and no result yet, core reaches for\n * `getWildcardTool()` and runs `executeWildcardTool`. Inside it, the parse /\n * handler / subscriber work is guarded by `if (wildcardTool?.handler)` — but\n * the tool-result splice and the follow-up return sit OUTSIDE that guard, and\n * `toolCallResult` is initialised to `\"\"`. So a handler-less wildcard tool —\n * exactly what a caller who wanted a display-only fallback wrote — still\n * splices an EMPTY tool result for the call and still asks for another turn.\n *\n * Driving one turn through it (an assistant message calling a tool nobody\n * registered) shows the difference directly: through the old hook, two turns\n * and a spliced `{ toolCallId, content: \"\" }`; through core's `useRenderTool`,\n * one turn and no tool result. So an RN app whose author wanted a display-only\n * fallback was also auto-answering every otherwise-unanswered tool call with an\n * empty result and paying for a follow-up turn.\n *\n * The scope of that is bounded: it only bites a tool call with no exact-name\n * frontend tool AND no result yet, so a server-side tool call whose result has\n * already arrived never reaches the branch.\n *\n * The convergence deleted RN's hook and re-exported core's two instead. That is\n * a break, and this package ships in the `monorepo` release scope — 16 packages\n * versioned in lockstep — so it lands in a MINOR, not a major. The compiler is\n * therefore the only signal that reaches most consumers, and there are call\n * shapes the compiler cannot see:\n *\n * • a HOISTED config object whose `render` ignores its props (TypeScript's\n * excess-property check only fires on a fresh object literal);\n * • the old fields arriving via a SPREAD into an otherwise fresh literal;\n * • an UNTYPED or `@ts-nocheck` call site — plain-JS React Native screens are\n * common.\n *\n * In all three, core's `useRenderTool` would silently ignore `description` and\n * `handler`; and because core's renderer bridge spreads\n * `{ ...props, parameters: props.args }`, an old `render: ({ args }) => …` keeps\n * painting EXACTLY as before. The screen looks unchanged while the tool stops\n * being registered and advertised and the handler never runs again. That is the\n * failure this shim exists to prevent: it routes such calls the way the old hook\n * did, and says so out loud.\n *\n * ─── Warning idiom ───────────────────────────────────────────────────────────\n *\n * `[CopilotKit] `-prefixed `console.warn`, deduped through a module-level `Set`\n * so a render path cannot spam it — the same shape as\n * react-core's `warnedUnknownStatuses` in `use-default-render-tool.tsx`.\n *\n * The dev gate is `process.env.NODE_ENV !== \"production\"`, which is what\n * react-core's own hooks/components use and what a test can flip. Other RN\n * modules in this package gate on React Native's `__DEV__` global instead; both\n * are compile-time-inlined by Metro, so either is stripped from a release\n * bundle. `NODE_ENV` is chosen here because this module sits between two\n * react-core hooks and is asserted against directly in the suite.\n */\n\n/**\n * The two hooks a call can be routed to. Named for the core hook that ends up\n * owning the registration, because that is the thing a consumer must change\n * their call to.\n */\ntype Route = \"useFrontendTool\" | \"useRenderTool\";\n\n/**\n * Dedup key set for the deprecation warning: one warning per distinct tool\n * name, not one per render. Module-level (not a ref) so remounting the same\n * screen does not re-warn either.\n */\nconst warnedToolNames = new Set<string>();\n\n/** Tool-shaped fields that only `useFrontendTool` can honour. */\nconst LEGACY_TOOL_FIELDS = [\"description\", \"handler\"] as const;\n\n/**\n * Fields the OLD React Native hook accepted, kept optional here so the call\n * shapes the compiler cannot see (hoisted / spread / untyped) still type-check\n * and get routed rather than silently dropped.\n *\n * @typeParam A - The parsed argument type a legacy `handler` receives.\n */\ninterface LegacyToolFields<A> {\n /**\n * @deprecated A description is a TOOL field: it is what gets advertised to\n * the model. Supplying it routes this call to `useFrontendTool` — rename the\n * call to `useFrontendTool` instead.\n */\n description?: string;\n /**\n * @deprecated A handler is a TOOL field: it is what the model's call\n * executes. Supplying it routes this call to `useFrontendTool` — rename the\n * call to `useFrontendTool` instead. Note that core's handler receives a\n * SECOND argument (the {@link FrontendToolHandlerContext}, carrying\n * `stopAgent()`'s abort signal), which the old React Native hook dropped.\n */\n handler?: (args: A, context: FrontendToolHandlerContext) => Promise<unknown>;\n}\n\n/** The wildcard call shape: a fallback renderer for every unclaimed tool call. */\ntype WildcardConfig = {\n name: \"*\";\n render: (props: any) => React.ReactElement | null;\n agentId?: string;\n} & LegacyToolFields<Record<string, unknown>> & {\n /**\n * @deprecated A wildcard renderer paints tool calls it does not own, so it\n * has no schema of its own — core's wildcard path ignores this. Remove it.\n */\n parameters?: StandardSchemaV1;\n };\n\n/** The name-scoped call shape. */\ntype NamedConfig<S extends StandardSchemaV1> = {\n name: string;\n parameters: S;\n render: (props: RenderToolProps<S>) => React.ReactElement | null;\n agentId?: string;\n} & LegacyToolFields<InferSchemaOutput<S>>;\n\n/**\n * The IMPLEMENTATION-side shape: the union of both public overloads with\n * everything optional and the schema-dependent positions left as `any`.\n *\n * Deliberately permissive, and invisible to consumers — the two overloads above\n * are the public API. This is the same shape react-core gives its own\n * implementation signatures (`useRenderTool`, `defineToolCallRenderer`), and it\n * is what lets this body forward a config to either core hook without a single\n * cast: the alternative — a generic implementation signature — cannot be\n * satisfied by both a `name: \"*\"` config with no schema and a named config with\n * one.\n */\ntype ShimConfig = {\n name: string;\n // `<any, any>` rather than the bare default (`<unknown, unknown>`): a\n // schema's OUTPUT type sits in an invariant position on the Standard Schema\n // interface, so the bare default is not assignable to the\n // `StandardSchemaV1<any, Record<string, unknown>>` that core's\n // `ReactFrontendTool` declares. Bridging that variance here — in the\n // implementation-only shape — is what keeps the body cast-free.\n parameters?: StandardSchemaV1<any, any>;\n render: (props: any) => React.ReactElement | null;\n agentId?: string;\n} & LegacyToolFields<any>;\n\n/**\n * Which core hook a config routes to.\n *\n * Rule 1 — `name === \"*\"` WINS, UNCONDITIONALLY. This is deliberately not the\n * obvious reading of \"old fields mean the old hook\". The old RN hook made\n * `description` REQUIRED, so anyone who ever attempted a wildcard renderer\n * necessarily wrote it WITH the old tool fields. Routing \"has old fields\" to\n * `useFrontendTool` would therefore recreate the original `*`-named-tool bug for\n * precisely the people who had tried hardest to use the wildcard. A wildcard\n * always means renderer-only.\n *\n * Rule 2 — otherwise, `handler` or `description` present means the caller wanted\n * a tool AND its renderer, which is what the old hook actually did:\n * `useFrontendTool`.\n *\n * Rule 3 — otherwise, `useRenderTool`, i.e. core's hook, unchanged.\n *\n * One consequence worth knowing about the renderer-only routes (1 and 3): they\n * change the EFFECT PHASE the registration lands in. `useFrontendTool`\n * registers in a `useLayoutEffect`, core's `useRenderTool` in a `useEffect`, so\n * a call that used to register during the layout phase now registers one phase\n * later. Only untyped-JS callers can be affected (a typed old call site had to\n * supply the required `description`, which routes to `useFrontendTool` and\n * keeps the layout phase), and the later phase is what core's `useRenderTool`\n * has always done on the web, so this is documented rather than compensated\n * for.\n */\nfunction routeFor(config: {\n name: string;\n description?: unknown;\n handler?: unknown;\n}): Route {\n if (config.name === \"*\") return \"useRenderTool\";\n if (config.description !== undefined || config.handler !== undefined) {\n return \"useFrontendTool\";\n }\n return \"useRenderTool\";\n}\n\n/** Legacy field names actually supplied on this config, in declaration order. */\nfunction legacyFieldsOn(config: ShimConfig): string[] {\n const supplied: string[] = LEGACY_TOOL_FIELDS.filter(\n (field) => config[field] !== undefined,\n );\n // `parameters` is only a legacy field on the wildcard path, where core has no\n // use for it. On the named path it is core's own field and must not be named.\n if (config.name === \"*\" && config.parameters !== undefined) {\n supplied.push(\"parameters\");\n }\n return supplied;\n}\n\n/** `description`, `handler` -> \"`description`, `handler`\" */\nconst quoteList = (names: readonly string[]) =>\n names.map((name) => `\\`${name}\\``).join(\", \");\n\nconst SHIM_NOTICE =\n \"React Native's `useRenderTool` is a temporary compatibility shim \" +\n \"(deprecated, scheduled for removal in the next minor).\";\n\n/**\n * TEST-ONLY escape hatch for the per-name dedup above.\n *\n * Not re-exported from any package entry (`src/headless.ts` exports only the\n * hook), so it is not public API. It exists because the dedup key is the tool\n * NAME and lives for the lifetime of the module: the wildcard's name is the\n * same `\"*\"` for every caller, so without this the second test to assert the\n * wildcard's warning would silently observe zero calls and have to be written\n * order-dependently instead.\n */\nexport function __resetRenderToolShimWarnings(): void {\n warnedToolNames.clear();\n}\n\nfunction warnOnce(name: string, message: string): void {\n if (process.env.NODE_ENV === \"production\") return;\n if (warnedToolNames.has(name)) return;\n warnedToolNames.add(name);\n console.warn(message);\n}\n\n/**\n * Says what was received, which hook the call was routed to, and what to change\n * the call to. Dev-only and once per distinct tool name.\n *\n * EVERY route warns — including the renderer-only route that supplied no legacy\n * fields at all. That route looks like a no-op and is not. `description` was\n * REQUIRED on the old hook, so a TypeScript caller could never reach\n * `{ name, parameters, render }` — but an untyped JS caller could, and untyped\n * JS is the whole population this shim exists for. `FrontendTool.handler` is\n * optional (`core/src/types.ts`) and `buildFrontendTools` does not filter on\n * it, so on the old hook that same call DID register AND advertise a real tool.\n * Routing cannot recover the intent, because `{ name, parameters, render }` is\n * equally the correct NEW renderer-only spelling — so the warning has to carry\n * it, or this one shape stays silent while losing registration.\n */\nfunction warnRouted(\n name: string,\n route: Route,\n legacyFields: readonly string[],\n): void {\n if (legacyFields.length === 0) {\n // Guarded on the ROUTE, not just on the absence of legacy fields: a config\n // that HAD them on its first render and then dropped them keeps its frozen\n // `useFrontendTool` route, and calling that \"renderer only\" would be false.\n // That case already warned on the first render (and gets the drift warning\n // besides), so there is nothing to add here.\n if (route !== \"useRenderTool\") return;\n\n const registersRendererOnly =\n `[CopilotKit] \\`useRenderTool({ name: \"${name}\" })\\` from ` +\n `@copilotkit/react-native registers a RENDERER ONLY: it supplies UI for a ` +\n `tool call and registers no tool of its own. `;\n\n warnOnce(\n name,\n name === \"*\"\n ? registersRendererOnly +\n `That is the right behaviour for a wildcard, and it is NOT what the ` +\n `old React Native \\`useRenderTool\\` did: that registered a tool ` +\n `literally named \"*\", which is core's catch-all HANDLER name, so it ` +\n `auto-answered every otherwise-unanswered tool call with an empty ` +\n `tool result and asked for a follow-up turn. ${SHIM_NOTICE} Switch ` +\n `to \\`useRenderTool\\` from \\`@copilotkit/react-core\\`.`\n : registersRendererOnly +\n `On the old React Native hook this SAME call also registered and ` +\n `advertised a tool named \"${name}\" to the model, so if you relied on ` +\n `that, this call has quietly stopped doing it — use ` +\n `\\`useFrontendTool\\` instead. If you only ever wanted to supply UI ` +\n `for a tool somebody else owns, this call is already correct: switch ` +\n `it to \\`useRenderTool\\` from \\`@copilotkit/react-core\\`. ` +\n `${SHIM_NOTICE}`,\n );\n return;\n }\n\n const received =\n `[CopilotKit] \\`useRenderTool({ name: \"${name}\" })\\` from ` +\n `@copilotkit/react-native received ${quoteList(legacyFields)}. `;\n\n if (route === \"useFrontendTool\") {\n warnOnce(\n name,\n received +\n `Those are TOOL fields, so this call was routed to \\`useFrontendTool\\` — ` +\n `the hook that registers a tool AND its renderer, which is what the old ` +\n `React Native \\`useRenderTool\\` did. ${SHIM_NOTICE} Rename the call to ` +\n `\\`useFrontendTool\\` (same config object; render props rename \\`args\\` to ` +\n `\\`parameters\\`). If you only meant to supply UI for a tool somebody else ` +\n `owns, drop ${quoteList(legacyFields)} and keep \\`useRenderTool\\`.`,\n );\n return;\n }\n\n // Reached with legacy fields present but the renderer-only route in force.\n // Normally that is the wildcard (rule 1); it is also what a frozen route\n // looks like if a config grew legacy fields after its first render.\n warnOnce(\n name,\n received +\n `This call registers a RENDERER ONLY through react-core's ` +\n `\\`useRenderTool\\`, which cannot use them, so they were IGNORED. ` +\n (name === \"*\"\n ? `No tool named \"*\" is registered — the old React Native ` +\n `\\`useRenderTool\\` did register one, and that was the bug: \"*\" is ` +\n `core's catch-all HANDLER name, so it auto-answered every ` +\n `otherwise-unanswered tool call with an empty tool result and asked ` +\n `for a follow-up turn. `\n : `The route was fixed at this component's first render and cannot ` +\n `change for its lifetime. `) +\n `${SHIM_NOTICE} Remove ${quoteList(legacyFields)} from this call. ` +\n `If you meant to register a real frontend tool, give it a real name and ` +\n `use \\`useFrontendTool\\`.`,\n );\n}\n\n/**\n * Registers a wildcard (`\"*\"`) renderer for tool calls.\n *\n * @deprecated Use `useRenderTool` from `@copilotkit/react-core` (re-exported by\n * `@copilotkit/react-native/headless` once this shim is gone) for a\n * renderer-only registration, or `useFrontendTool` to register a tool and its\n * renderer together. This shim is scheduled for removal in the next minor.\n *\n * @param config - Wildcard renderer configuration.\n * @param deps - Optional dependencies to refresh registration.\n */\nexport function useRenderTool(\n config: WildcardConfig,\n deps?: ReadonlyArray<unknown>,\n): void;\n\n/**\n * Registers a name-scoped renderer for tool calls — or, if `description` or\n * `handler` is supplied, a frontend tool and its renderer (what the old React\n * Native hook did), with a development warning.\n *\n * @deprecated Use `useRenderTool` from `@copilotkit/react-core` (re-exported by\n * `@copilotkit/react-native/headless` once this shim is gone) for a\n * renderer-only registration, or `useFrontendTool` to register a tool and its\n * renderer together. This shim is scheduled for removal in the next minor.\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 */\nexport function useRenderTool<S extends StandardSchemaV1>(\n config: NamedConfig<S>,\n deps?: ReadonlyArray<unknown>,\n): void;\n\n/**\n * @deprecated Temporary compatibility shim over react-core's `useRenderTool` /\n * `useFrontendTool`; scheduled for removal in the next minor. See the routing\n * rules on {@link routeFor}.\n */\nexport function useRenderTool(\n config: ShimConfig,\n deps?: ReadonlyArray<unknown>,\n): void {\n const route = routeFor(config);\n\n // The route is FROZEN at first render. A hook cannot be called conditionally\n // unless the condition is stable for the component's lifetime, and a config\n // whose shape changes between renders (`handler: enabled ? fn : undefined`)\n // would otherwise flip which core hook is called. Freezing keeps the call\n // order constant; the drift is reported below rather than acted on, because\n // silently re-routing a live registration is the failure mode this whole shim\n // exists to prevent.\n const frozenRouteRef = useRef<Route | null>(null);\n frozenRouteRef.current ??= route;\n const frozenRoute = frozenRouteRef.current;\n\n const legacyFields = legacyFieldsOn(config);\n\n useEffect(() => {\n warnRouted(config.name, frozenRoute, legacyFields);\n // The warning is keyed on the tool name, so re-running it for a changed\n // render closure would be pure noise; `warnOnce` dedups anyway.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [config.name, frozenRoute, legacyFields.join(\",\")]);\n\n useEffect(() => {\n if (route === frozenRoute) return;\n warnOnce(\n `${config.name}:route-drift`,\n `[CopilotKit] \\`useRenderTool({ name: \"${config.name}\" })\\` from ` +\n `@copilotkit/react-native changed shape between renders: it now routes ` +\n `to \\`${route}\\` but was registered through \\`${frozenRoute}\\` and stays ` +\n `there for this component's lifetime (a hook cannot be swapped mid-life). ` +\n `Call \\`${route}\\` directly instead of varying \\`description\\`/\\`handler\\`.`,\n );\n }, [config.name, route, frozenRoute]);\n\n if (frozenRoute === \"useFrontendTool\") {\n // Registration is DELEGATED, never reimplemented: this package must own no\n // render-tool registry of its own (RN once did, and `useComponent` — which\n // registers into core's — then rendered nowhere on RN).\n // eslint-disable-next-line react-hooks/rules-of-hooks\n useFrontendTool(toFrontendTool(config), deps);\n return;\n }\n\n if (config.name === \"*\") {\n // Rule 1: core's schema-less wildcard branch, whatever else was supplied.\n // eslint-disable-next-line react-hooks/rules-of-hooks\n useCoreRenderTool(\n {\n name: \"*\",\n render: config.render,\n ...(config.agentId ? { agentId: config.agentId } : {}),\n },\n deps,\n );\n return;\n }\n\n // eslint-disable-next-line react-hooks/rules-of-hooks\n useCoreRenderTool(\n {\n name: config.name,\n parameters: config.parameters!,\n render: config.render,\n ...(config.agentId ? { agentId: config.agentId } : {}),\n },\n deps,\n );\n}\n\n/**\n * Builds the `ReactFrontendTool` for the `useFrontendTool` route.\n *\n * The renderer bridge mirrors react-core's own (`use-render-tool.tsx`): core's\n * registry invokes a renderer with `args` and an enum `status`, while this\n * hook's `render` is declared with core's public `parameters` / string-literal\n * `status` shape. Spreading per status keeps the discriminated union correlated\n * — and spreading `...props` (rather than picking fields) is also what keeps an\n * old `render: ({ args }) => …` painting unchanged at runtime.\n */\nfunction toFrontendTool(config: ShimConfig): ReactFrontendTool {\n const render: ReactFrontendTool[\"render\"] = (props) => {\n // Three byte-identical branches, deliberately: see the note above.\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\n return {\n name: config.name,\n ...(config.description !== undefined\n ? { description: config.description }\n : {}),\n ...(config.parameters !== undefined\n ? { parameters: config.parameters }\n : {}),\n ...(config.handler !== undefined ? { handler: config.handler } : {}),\n ...(config.agentId ? { agentId: config.agentId } : {}),\n render,\n };\n}\n"],"mappings":"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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@copilotkit/react-native",
3
- "version": "1.70.3",
3
+ "version": "1.71.1",
4
4
  "private": false,
5
5
  "keywords": [
6
6
  "ai",
@@ -76,9 +76,9 @@
76
76
  "@ag-ui/client": "0.0.59",
77
77
  "text-encoding": "^0.7.0",
78
78
  "web-streams-polyfill": "^4.2.0",
79
- "@copilotkit/core": "1.70.3",
80
- "@copilotkit/react-core": "1.70.3",
81
- "@copilotkit/shared": "1.70.3"
79
+ "@copilotkit/core": "1.71.1",
80
+ "@copilotkit/shared": "1.71.1",
81
+ "@copilotkit/react-core": "1.71.1"
82
82
  },
83
83
  "devDependencies": {
84
84
  "@testing-library/react": "^16.3.0",
@@ -72,6 +72,17 @@ export interface TestCopilotKitProps {
72
72
  * the array the test just mutated.
73
73
  */
74
74
  agentRef?: React.MutableRefObject<AbstractAgent | null>;
75
+ /**
76
+ * The agent to register as "default", instead of the built-in `SeededAgent`.
77
+ *
78
+ * For tests that must observe what core hands an agent on a REAL run — the
79
+ * `tools` list core advertises is built inside `RunHandler.runAgent` and is
80
+ * reachable no other way from a consumer's position — pass an agent that
81
+ * records its `runAgent` input. Captured on first render like the built-in
82
+ * one, so a later re-render with a different agent is ignored (the core
83
+ * instance, and therefore the registered renderers, must stay stable).
84
+ */
85
+ agent?: AbstractAgent;
75
86
  children: React.ReactNode;
76
87
  }
77
88
 
@@ -79,11 +90,12 @@ export function TestCopilotKit({
79
90
  messages,
80
91
  executingToolCallIds = EMPTY_SET,
81
92
  agentRef: publishAgentRef,
93
+ agent,
82
94
  children,
83
95
  }: TestCopilotKitProps) {
84
- const agentRef = useRef<SeededAgent | null>(null);
96
+ const agentRef = useRef<AbstractAgent | null>(null);
85
97
  if (agentRef.current === null) {
86
- agentRef.current = new SeededAgent();
98
+ agentRef.current = agent ?? new SeededAgent();
87
99
  }
88
100
  if (publishAgentRef) publishAgentRef.current = agentRef.current;
89
101
 
@@ -0,0 +1,148 @@
1
+ import { Text } from "react-native";
2
+ import { z } from "zod";
3
+ import { useFrontendTool } from "../headless";
4
+ import type {
5
+ FrontendToolRenderFunction,
6
+ ReactToolCallRenderer,
7
+ } from "../headless";
8
+
9
+ /**
10
+ * Type-level guard for `FrontendToolRenderFunction`.
11
+ *
12
+ * ─── Why this file is a `.test-d.tsx` and not a vitest suite ─────────────────
13
+ *
14
+ * There is nothing to observe at runtime: the whole property is "the compiler
15
+ * rejects this". `packages/react-native/tsconfig.json` has `include: ["src"]`,
16
+ * so `tsc --noEmit` (`nx run @copilotkit/react-native:check-types`) compiles
17
+ * this file, and every `@ts-expect-error` below is therefore load-bearing —
18
+ * `tsc` fails with "Unused '@ts-expect-error' directive" the moment one of them
19
+ * starts compiling. The `.test-d.` infix keeps it out of vitest's
20
+ * `src/**\/__tests__/**\/*.{test,spec}.{ts,tsx}` glob, which would otherwise
21
+ * collect it as a suite with no tests in it.
22
+ *
23
+ * ─── What is being guarded ───────────────────────────────────────────────────
24
+ *
25
+ * `useFrontendTool`'s `render` is `ReactToolCallRenderer<T>["render"]`, a
26
+ * `React.ComponentType`, so its return type is `ReactNode` and a bare string
27
+ * compiles — then throws *Text strings must be rendered within a `<Text>`
28
+ * component* on a device. `FrontendToolRenderFunction<T>` is the opt-in
29
+ * annotation that rejects that at compile time, and this file pins both
30
+ * directions of it plus the gap it exists to cover.
31
+ */
32
+
33
+ type Args = { city: string };
34
+
35
+ // ─── 1. The gap. ─────────────────────────────────────────────────────────────
36
+ // core's contract accepts a bare string, which is exactly why the annotation
37
+ // below is worth having. If this line ever STOPS compiling, core narrowed its
38
+ // own contract and `FrontendToolRenderFunction` can be retired — `tsc` will say
39
+ // so here rather than leaving the type sitting around unnecessary.
40
+ const unannotated: ReactToolCallRenderer<Args>["render"] = (props) =>
41
+ `Weather in ${props.args.city}`;
42
+ void unannotated;
43
+
44
+ // ─── 2. Accepted: an element-returning renderer. ─────────────────────────────
45
+ const returnsElement: FrontendToolRenderFunction<Args> = ({ args }) => (
46
+ <Text>{args.city}</Text>
47
+ );
48
+
49
+ // `null` draws nothing, and is the documented way to suppress a tool call's UI.
50
+ const returnsNull: FrontendToolRenderFunction<Args> = () => null;
51
+
52
+ // The props come from core's contract UNCHANGED, so all three arms and both
53
+ // non-argument fields are reachable, and `args` is partial only while the call
54
+ // is still streaming.
55
+ const readsEveryProp: FrontendToolRenderFunction<Args> = (props) => {
56
+ const label: string = `${props.name}/${props.toolCallId}`;
57
+ if (props.status === "inProgress") {
58
+ // `Partial<Args>` here: the agent has not finished writing the call.
59
+ const partial: string | undefined = props.args.city;
60
+ return <Text>{`${label} ${partial ?? ""}`}</Text>;
61
+ }
62
+ if (props.status === "executing") {
63
+ const city: string = props.args.city;
64
+ return <Text>{`${label} ${city}`}</Text>;
65
+ }
66
+ const result: string = props.result;
67
+ return <Text>{`${label} ${result}`}</Text>;
68
+ };
69
+
70
+ // The props are core's contract and NOTHING else, which is what "derived, not
71
+ // re-declared" has to mean if it is to be worth anything. Without this, the
72
+ // props position could be widened to `any` — every assertion in §3 would still
73
+ // pass, because a directive fires on the RETURN type — and the derivation would
74
+ // have quietly stopped holding. `parameters` is the name core's OTHER render
75
+ // shape (`RenderToolProps`, the one `useRenderTool` uses) carries arguments
76
+ // under, so it is the mistake a reader is most likely to make here.
77
+ const readsAPropCoreDoesNotHave: FrontendToolRenderFunction<Args> = (props) => {
78
+ // @ts-expect-error core's `ReactToolCallRenderer` props expose `args`
79
+ void props.parameters;
80
+ return null;
81
+ };
82
+ void readsAPropCoreDoesNotHave;
83
+
84
+ // Usable without a type argument — the default `Record<string, unknown>` keeps
85
+ // the bare spelling legal, unlike core's `RenderToolProps`, which has no
86
+ // default and fails `TS2314` when written bare.
87
+ const bare: FrontendToolRenderFunction = () => null;
88
+ void bare;
89
+
90
+ // ─── 3. Rejected: a bare-string-returning renderer. ──────────────────────────
91
+ // The exact shape that used to be rejected before RN's render type was deleted,
92
+ // and the reason a React Native consumer wants it rejected: this compiles
93
+ // against core's contract (§1) and throws on a device.
94
+ //
95
+ // Block bodies throughout so `tsc` reports the mismatch on the DECLARATION —
96
+ // which is the line each directive sits above. A concise-body arrow is reported
97
+ // at its expression instead, one line further down, where the directive would
98
+ // not reach it and would itself fail as unused.
99
+ //
100
+ // Without its directive: `TS2322: Type 'string' is not assignable to type
101
+ // 'ReactElement<unknown, string | JSXElementConstructor<any>>'`.
102
+ // @ts-expect-error a bare string is not `ReactElement | null`
103
+ const returnsString: FrontendToolRenderFunction<Args> = (props) => {
104
+ return `Weather in ${props.args.city}`;
105
+ };
106
+ void returnsString;
107
+
108
+ // A number, an element array and `undefined` are all `ReactNode` and all
109
+ // equally undrawable by React Native's `FlatList`.
110
+ // @ts-expect-error a number is not `ReactElement | null`
111
+ const returnsNumber: FrontendToolRenderFunction<Args> = () => {
112
+ return 42;
113
+ };
114
+ void returnsNumber;
115
+
116
+ // @ts-expect-error an element array is not a single `ReactElement`
117
+ const returnsArray: FrontendToolRenderFunction<Args> = () => {
118
+ return [<Text key="a">a</Text>];
119
+ };
120
+ void returnsArray;
121
+
122
+ // @ts-expect-error `undefined` is not `ReactElement | null`
123
+ const returnsUndefined: FrontendToolRenderFunction<Args> = () => {
124
+ return undefined;
125
+ };
126
+ void returnsUndefined;
127
+
128
+ // ─── 4. An annotated renderer still fits the hook it is for. ─────────────────
129
+ // A narrowing that core's `render` slot rejected would be useless, so the
130
+ // assignability is asserted rather than assumed.
131
+ function Probe() {
132
+ useFrontendTool(
133
+ {
134
+ name: "showWeather",
135
+ description: "Show the weather",
136
+ parameters: z.object({ city: z.string() }),
137
+ handler: async ({ city }) => city,
138
+ render: returnsElement,
139
+ },
140
+ [],
141
+ );
142
+
143
+ useFrontendTool<Args>({ name: "silent", render: returnsNull });
144
+ useFrontendTool<Args>({ name: "verbose", render: readsEveryProp });
145
+
146
+ return null;
147
+ }
148
+ void Probe;
@@ -5,6 +5,9 @@ import path from "node:path";
5
5
  // deliberately loads at runtime (and is not part of the walked graph either —
6
6
  // the walk starts at src/headless.ts / src/index.ts, not at this test).
7
7
  import type * as HeadlessEntry from "../headless";
8
+ // Same reason, and additionally: the identity assertion below needs the module
9
+ // this entry re-exports FROM, to compare bindings rather than merely count them.
10
+ import type * as CoreHeadlessEntry from "@copilotkit/react-core/v2/headless";
8
11
 
9
12
  /**
10
13
  * Guards the `@copilotkit/react-native/headless` entry (src/headless.ts).
@@ -81,6 +84,9 @@ const FORBIDDEN_LOCAL = [
81
84
  "use-attachments",
82
85
  ];
83
86
 
87
+ // The one react-core entry this package's hooks come from.
88
+ const CORE_HEADLESS = "@copilotkit/react-core/v2/headless";
89
+
84
90
  // ─── #4893 bundle guard ──────────────────────────────────────────────────────
85
91
  // @copilotkit/react-core/v2 (the "fat" entry) re-exports from a monolithic chunk
86
92
  // that pulls the chat-message rendering stack: streamdown -> shiki (~5.5 MB of
@@ -89,10 +95,52 @@ const FORBIDDEN_LOCAL = [
89
95
  // all of it in every consumer's app bundle (issue #4893). PR #5883 moved the lean
90
96
  // hooks into /v2/headless precisely so this package never needs the fat entry.
91
97
  const ALLOWED_REACT_CORE_ENTRIES = [
92
- "@copilotkit/react-core/v2/headless",
98
+ CORE_HEADLESS,
93
99
  "@copilotkit/react-core/v2/context",
94
100
  ];
95
101
 
102
+ /**
103
+ * Registry-owning APIs and primitives no module in the headless graph may use.
104
+ *
105
+ * `CopilotKitCoreReact` is the ONE render-tool/tool registry, and this package
106
+ * reaches it only through react-core's hooks. That is not a style preference: RN
107
+ * used to keep its own `Map` behind a `RenderToolProvider`, and the consequences
108
+ * were that `useComponent` (which registers into core's registry) rendered
109
+ * nowhere on RN, and that renderers vanished from chat history on unmount.
110
+ *
111
+ * Paired with the delegation test below, this is the replacement for the
112
+ * `useRenderTool` identity assertion: identity cannot police a deprecated shim
113
+ * that is RN's own binding by construction, but "RN owns no registry" and "the
114
+ * shim delegates" together catch everything identity caught — a local hook
115
+ * re-grown under the name has to either write to a registry itself (caught
116
+ * here) or stop calling core's hooks (caught there).
117
+ */
118
+ const FORBIDDEN_REGISTRY_APIS: readonly (readonly [
119
+ identifier: string,
120
+ why: string,
121
+ ])[] = [
122
+ [
123
+ "addTool",
124
+ "registers a frontend tool directly — go through react-core's `useFrontendTool`",
125
+ ],
126
+ [
127
+ "removeTool",
128
+ "unregisters a frontend tool directly — go through react-core's `useFrontendTool`",
129
+ ],
130
+ [
131
+ "addHookRenderToolCall",
132
+ "writes a renderer into the registry directly — go through react-core's `useRenderTool` / `useFrontendTool`",
133
+ ],
134
+ [
135
+ "renderToolCalls",
136
+ "reads or writes the renderer registry directly — go through react-core's `useRenderToolCall`",
137
+ ],
138
+ [
139
+ "createContext",
140
+ "a React context in the headless graph is how an RN-local registry would be rebuilt (`RenderToolProvider` was exactly that). If a context here is genuinely unrelated to tool registration, exempt it deliberately in this list with a reason",
141
+ ],
142
+ ];
143
+
96
144
  // Heavy modules that must never appear as a direct import from this package.
97
145
  // (Transitive leakage through react-core's own entry is covered separately by
98
146
  // packages/react-core/scripts/assert-headless-purity.mjs — this walker cannot
@@ -267,6 +315,28 @@ function resolveLocal(fromFile: string, spec: string): string | null {
267
315
  return null;
268
316
  }
269
317
 
318
+ /**
319
+ * The module specifier a VALUE export is re-exported from, or null.
320
+ *
321
+ * Matches either side of an `as` (the local name is the one whose
322
+ * implementation is in question; the exported name is what a consumer imports)
323
+ * and skips `export type { … }` blocks, which carry no runtime binding.
324
+ */
325
+ function reExportSpecifierOf(code: string, name: string): string | null {
326
+ const stripped = stripComments(code);
327
+ const re = /export\s+(type\s+)?\{([^}]*)\}\s*from\s*["'`]([^"'`]+)["'`]/g;
328
+ for (const m of stripped.matchAll(re)) {
329
+ if (m[1]) continue;
330
+ for (const raw of m[2]!.split(",")) {
331
+ const clause = raw.trim();
332
+ if (!clause || /^type\s+/.test(clause)) continue;
333
+ const [local, exported] = clause.split(/\s+as\s+/).map((s) => s.trim());
334
+ if (local === name || exported === name) return m[3]!;
335
+ }
336
+ }
337
+ return null;
338
+ }
339
+
270
340
  interface Graph {
271
341
  /** Every source file reachable from the entry, including the entry. */
272
342
  seen: Set<string>;
@@ -442,6 +512,33 @@ describe("@copilotkit/react-native/headless entry", () => {
442
512
  ).toEqual([]);
443
513
  });
444
514
 
515
+ it("owns no tool/renderer registry of its own anywhere in the headless graph", () => {
516
+ const { seen } = graphFor(headlessEntry);
517
+ // Non-vacuity comes from REQUIRED_HEADLESS_MODULES above (a truncated walk
518
+ // fails there first), so this only has to be a deny-list.
519
+ const offenders: string[] = [];
520
+ for (const file of seen) {
521
+ // Comments stripped: this file's own graph is heavily documented and the
522
+ // modules in it name these APIs in prose to explain why they do NOT call
523
+ // them. A raw text match would fail on the documentation.
524
+ const code = stripComments(fs.readFileSync(file, "utf8"));
525
+ for (const [identifier, why] of FORBIDDEN_REGISTRY_APIS) {
526
+ if (new RegExp(`\\b${identifier}\\b`).test(code)) {
527
+ offenders.push(
528
+ `${path.relative(srcDir, file)}: ${identifier} — ${why}`,
529
+ );
530
+ }
531
+ }
532
+ }
533
+ expect(
534
+ offenders,
535
+ `module(s) in the headless graph touch registry internals directly:\n ` +
536
+ `${offenders.join("\n ")}\n` +
537
+ `CopilotKitCoreReact is the single registry and this package must reach ` +
538
+ `it only through react-core's hooks.`,
539
+ ).toEqual([]);
540
+ });
541
+
445
542
  /**
446
543
  * The four checks below need the entry EVALUATED, not just read: they assert
447
544
  * that the named exports exist as runtime values (a re-export of a name that
@@ -480,9 +577,16 @@ describe("@copilotkit/react-native/headless entry", () => {
480
577
  // blast-radius problem as blind spot #4, just moved into a hook.
481
578
  describe("runtime export surface", () => {
482
579
  let mod: typeof HeadlessEntry;
580
+ let coreHeadless: typeof CoreHeadlessEntry;
483
581
 
484
582
  beforeAll(async () => {
485
- mod = await import("../headless");
583
+ // Both loads live in the ONE budgeted hook. core's /v2/headless is already
584
+ // inside this entry's own graph, so importing it here is a module-cache
585
+ // hit rather than a second traversal.
586
+ [mod, coreHeadless] = await Promise.all([
587
+ import("../headless"),
588
+ import("@copilotkit/react-core/v2/headless"),
589
+ ]);
486
590
  }, IMPORT_BUDGET_MS);
487
591
 
488
592
  it("does export the provider + core headless hooks", () => {
@@ -510,6 +614,132 @@ describe("@copilotkit/react-native/headless entry", () => {
510
614
  }
511
615
  });
512
616
 
617
+ it("exports react-core's `useFrontendTool` ITSELF, not an RN copy of it", () => {
618
+ // IDENTITY, which the two presence checks above deliberately do not assert
619
+ // — and could not have. RN used to ship a LOCAL `useRenderTool` whose whole
620
+ // body forwarded to react-core's `useFrontendTool`: core's OTHER hook,
621
+ // wearing this one's name. Both names were present in that world and are
622
+ // present in this one, so every presence check stayed green across the
623
+ // deletion, having verified nothing about which hook a consumer gets.
624
+ //
625
+ // The difference is what a consumer is billed for. `useFrontendTool`
626
+ // registers a tool AND its renderer, so the tool is advertised to the model
627
+ // and callable by it; `useRenderTool` registers a renderer only. Under the
628
+ // alias, `name: "*"` — the documented spelling of "render every tool call
629
+ // nothing else claims" — registered a frontend tool literally named `*`,
630
+ // schema-less and description-less. Core never OFFERED that one to the
631
+ // model (`buildFrontendTools` filters the name out), but `*` is core's
632
+ // catch-all HANDLER name, so the registration made a display-only wildcard
633
+ // auto-answer every otherwise-unanswered tool call with an empty tool
634
+ // result and request a follow-up turn
635
+ // (src/hooks/__tests__/useRenderTool.test.tsx pins the behaviour; this pins
636
+ // the wiring).
637
+ //
638
+ // `useRenderTool` is currently a deprecated compatibility SHIM (removal
639
+ // scheduled for the next minor), so its binding is RN's own by
640
+ // construction and identity cannot be the instrument. The tests below
641
+ // carry that half instead, deliberately at equal strength: the shim must
642
+ // DELEGATE, and no module in this entry's graph may own a registry.
643
+ expect(
644
+ mod.useFrontendTool,
645
+ "`useFrontendTool` on the RN headless entry is NOT the binding from " +
646
+ "@copilotkit/react-core/v2/headless. RN must own no implementation of " +
647
+ "it: re-export core's, or a local one will drift from it silently " +
648
+ "under a name consumers already trust.",
649
+ ).toBe(coreHeadless.useFrontendTool);
650
+ });
651
+
652
+ it("`useRenderTool` is core's hook, or a shim that DELEGATES to core's hooks", () => {
653
+ // The replacement for the `useRenderTool` half of the identity assertion
654
+ // above, at equal strength and with the same target: RN must never own a
655
+ // render-tool implementation, whatever the export is called.
656
+ //
657
+ // Two admissible states, and the guard picks its instrument from the entry
658
+ // source rather than being told which world it is in:
659
+ //
660
+ // • the END STATE (shim removed): `headless.ts` re-exports the name
661
+ // straight from `@copilotkit/react-core/v2/headless`, and this asserts
662
+ // RUNTIME IDENTITY — the original assertion, unweakened;
663
+ // • the SHIM STATE (now): the name comes from a local module, which must
664
+ // import BOTH core hooks from core's headless entry and CALL both. A
665
+ // local reimplementation — a hook that registers by itself instead of
666
+ // forwarding — fails here, and so does a shim that quietly stops
667
+ // delegating (the calls are what is asserted, not the imports alone).
668
+ //
669
+ // What this cannot see is WHICH core hook a given config reaches; that is
670
+ // routing, and it is asserted against core's own observable state (getTool,
671
+ // core.tools, the advertised tool list on a real run) in
672
+ // src/hooks/__tests__/useRenderTool.test.tsx.
673
+ const source = fs.readFileSync(headlessEntry, "utf8");
674
+ const from = reExportSpecifierOf(source, "useRenderTool");
675
+ expect(
676
+ from,
677
+ 'no `export { useRenderTool … } from "…"` found in src/headless.ts — ' +
678
+ "this guard cannot tell what a consumer gets. If the export moved to " +
679
+ "another form, teach `reExportSpecifierOf` about it.",
680
+ ).not.toBeNull();
681
+
682
+ if (from === CORE_HEADLESS) {
683
+ expect(
684
+ mod.useRenderTool,
685
+ "`useRenderTool` on the RN headless entry is NOT the binding from " +
686
+ `${CORE_HEADLESS}, though src/headless.ts re-exports it from there.`,
687
+ ).toBe(coreHeadless.useRenderTool);
688
+ return;
689
+ }
690
+
691
+ expect(
692
+ from!.startsWith("."),
693
+ `src/headless.ts re-exports \`useRenderTool\` from "${from}", which is ` +
694
+ `neither ${CORE_HEADLESS} nor a local module. Only those two are ` +
695
+ `admissible: anything else is an implementation RN does not control.`,
696
+ ).toBe(true);
697
+
698
+ const shimFile = resolveLocal(headlessEntry, from!);
699
+ expect(
700
+ shimFile,
701
+ `cannot resolve the module "${from}" that src/headless.ts exports ` +
702
+ `\`useRenderTool\` from`,
703
+ ).not.toBeNull();
704
+ // Non-vacuity: the deny-list test below reasons about this file too, so a
705
+ // shim outside the walked graph would make both pass for the wrong reason.
706
+ expect(
707
+ rel(graphFor(headlessEntry).seen),
708
+ `the shim module "${from}" is not in the walked headless graph`,
709
+ ).toContain(path.relative(srcDir, shimFile!));
710
+
711
+ const shimSource = stripComments(fs.readFileSync(shimFile!, "utf8"));
712
+ const { specs } = extractSpecs(shimSource);
713
+ expect(
714
+ specs,
715
+ `${path.relative(srcDir, shimFile!)} does not import from ` +
716
+ `${CORE_HEADLESS}, so it cannot be delegating to core's hooks — it is ` +
717
+ `an RN-local implementation of \`useRenderTool\`.`,
718
+ ).toContain(CORE_HEADLESS);
719
+
720
+ // Both core hooks must be REACHED, not merely imported: the shim's whole
721
+ // job is to route a legacy tool-shaped call to `useFrontendTool` and
722
+ // everything else to core's `useRenderTool`. An import with no call site
723
+ // is a shim that has stopped delegating.
724
+ for (const hook of ["useRenderTool", "useFrontendTool"]) {
725
+ const imported = new RegExp(
726
+ `\\b${hook}\\b(?:\\s+as\\s+(\\w+))?[^;]*?from\\s*["'\`]${CORE_HEADLESS.replace(/[/.]/g, "\\$&")}["'\`]`,
727
+ ).exec(shimSource);
728
+ expect(
729
+ imported,
730
+ `${path.relative(srcDir, shimFile!)} does not import \`${hook}\` from ` +
731
+ `${CORE_HEADLESS}. The shim must delegate BOTH routes to core.`,
732
+ ).not.toBeNull();
733
+ const localName = imported?.[1] ?? hook;
734
+ expect(
735
+ new RegExp(`\\b${localName}\\s*\\(`).test(shimSource),
736
+ `${path.relative(srcDir, shimFile!)} imports \`${hook}\` (as ` +
737
+ `\`${localName}\`) from ${CORE_HEADLESS} but never calls it. A shim ` +
738
+ `that does not delegate registers nothing, or registers it itself.`,
739
+ ).toBe(true);
740
+ }
741
+ });
742
+
513
743
  it("no longer exports the removed registry hook or its provider", () => {
514
744
  // Both removed (BREAKING). Asserted so neither creeps back as a shim:
515
745
  // useRenderToolRegistry cannot be honoured (core's renderers need
@@ -1,6 +1,7 @@
1
1
  import { describe, it, expect } from "vitest";
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
+ import { z } from "zod";
4
5
 
5
6
  import * as headlessEntry from "../headless";
6
7
  import * as barrelEntry from "../index";
@@ -318,14 +319,24 @@ describe("react-native entries: no runtime value is re-exported type-only", () =
318
319
 
319
320
  describe("react-native entries: runtime values are usable as values", () => {
320
321
  it("branches a render-prop status against ToolCallStatus members", () => {
321
- // The reported symptom. `RenderToolProps["status"]` is the `ToolCallStatus`
322
- // enum type, so it rejects a bare `"executing"` literal too — without the
323
- // value export there is no expression that compiles here at all.
322
+ // The reported symptom. Comparing a render prop's `status` against an enum
323
+ // MEMBER needs the enum's runtime binding: with `export type` the member is
324
+ // unnameable and this line is `TS1362`, whatever the field's own type is.
324
325
  //
325
- // Read through an annotated signature so `status` keeps the full enum type
326
+ // `RenderToolProps` is react-core's, so `status` here is the string-literal
327
+ // union `"inProgress" | "executing" | "complete"` rather than the enum — a
328
+ // bare `"executing"` literal would compile against it too. That does not
329
+ // weaken this assertion (the enum member is still what is being named), but
330
+ // it does mean this is no longer the ONLY expression a consumer could write;
331
+ // §1 and §2 above are the load-bearing guards for the export kind.
332
+ //
333
+ // Read through an annotated signature so `status` keeps the full union
326
334
  // instead of narrowing to the single member assigned, which would turn the
327
335
  // comparisons below into TS2367 ("no overlap") rather than exercising them.
328
- const readStatus = (): RenderToolProps<{ city: string }>["status"] =>
336
+ // `RenderToolProps` is generic over the SCHEMA, so the parameter is a schema
337
+ // type read back off a real one.
338
+ const citySchema = z.object({ city: z.string() });
339
+ const readStatus = (): RenderToolProps<typeof citySchema>["status"] =>
329
340
  ToolCallStatus.InProgress;
330
341
  const status = readStatus();
331
342
  const branch: string =