@copilotkit/react-native 1.71.1 → 1.72.0

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.
@@ -1,501 +0,0 @@
1
- import { useEffect, useRef } from "react";
2
- import {
3
- useFrontendTool,
4
- useRenderTool as useCoreRenderTool,
5
- } from "@copilotkit/react-core/v2/headless";
6
- import type {
7
- ReactFrontendTool,
8
- RenderToolProps,
9
- } from "@copilotkit/react-core/v2/headless";
10
- import { ToolCallStatus } from "@copilotkit/core";
11
- import type { FrontendToolHandlerContext } from "@copilotkit/core";
12
- import type { InferSchemaOutput, StandardSchemaV1 } from "@copilotkit/shared";
13
-
14
- /**
15
- * TEMPORARY COMPATIBILITY SHIM — scheduled for removal in the next minor.
16
- * Removal is tracked in CopilotKit/CopilotKit#6976 (Linear OSS-1148).
17
- *
18
- * ─── Why this exists at all ──────────────────────────────────────────────────
19
- *
20
- * `@copilotkit/react-native` used to export a hook named `useRenderTool` that
21
- * was NOT react-core's `useRenderTool`: its whole body forwarded to core's
22
- * OTHER hook, `useFrontendTool`, while wearing this one's name. The two are not
23
- * interchangeable — `useFrontendTool` registers a TOOL (advertised to the model,
24
- * callable by it) *and* its renderer through `addTool`, while `useRenderTool`
25
- * registers a RENDERER ONLY through `addHookRenderToolCall` and special-cases
26
- * `name: "*"` into a schema-less fallback. Under the alias, `name: "*"`
27
- * registered a frontend tool literally named `*`.
28
- *
29
- * ─── What a tool named `*` actually does ─────────────────────────────────────
30
- *
31
- * NOT "gets advertised to the model": core has never offered it. `*` is core's
32
- * catch-all HANDLER name, and `buildFrontendTools` filters it out of the list
33
- * it hands the agent (`core/src/core/run-handler.ts`, at the
34
- * `tool.name !== WILDCARD_TOOL_NAME` clause) precisely so the model is not
35
- * offered a tool whose name is a glob.
36
- *
37
- * What it does instead is worse for the affected caller. When a tool call has
38
- * no matching frontend tool and no result yet, core reaches for
39
- * `getWildcardTool()` and runs `executeWildcardTool`. Inside it, the parse /
40
- * handler / subscriber work is guarded by `if (wildcardTool?.handler)` — but
41
- * the tool-result splice and the follow-up return sit OUTSIDE that guard, and
42
- * `toolCallResult` is initialised to `""`. So a handler-less wildcard tool —
43
- * exactly what a caller who wanted a display-only fallback wrote — still
44
- * splices an EMPTY tool result for the call and still asks for another turn.
45
- *
46
- * Driving one turn through it (an assistant message calling a tool nobody
47
- * registered) shows the difference directly: through the old hook, two turns
48
- * and a spliced `{ toolCallId, content: "" }`; through core's `useRenderTool`,
49
- * one turn and no tool result. So an RN app whose author wanted a display-only
50
- * fallback was also auto-answering every otherwise-unanswered tool call with an
51
- * empty result and paying for a follow-up turn.
52
- *
53
- * The scope of that is bounded: it only bites a tool call with no exact-name
54
- * frontend tool AND no result yet, so a server-side tool call whose result has
55
- * already arrived never reaches the branch.
56
- *
57
- * The convergence deleted RN's hook and re-exported core's two instead. That is
58
- * a break, and this package ships in the `monorepo` release scope — 16 packages
59
- * versioned in lockstep — so it lands in a MINOR, not a major. The compiler is
60
- * therefore the only signal that reaches most consumers, and there are call
61
- * shapes the compiler cannot see:
62
- *
63
- * • a HOISTED config object whose `render` ignores its props (TypeScript's
64
- * excess-property check only fires on a fresh object literal);
65
- * • the old fields arriving via a SPREAD into an otherwise fresh literal;
66
- * • an UNTYPED or `@ts-nocheck` call site — plain-JS React Native screens are
67
- * common.
68
- *
69
- * In all three, core's `useRenderTool` would silently ignore `description` and
70
- * `handler`; and because core's renderer bridge spreads
71
- * `{ ...props, parameters: props.args }`, an old `render: ({ args }) => …` keeps
72
- * painting EXACTLY as before. The screen looks unchanged while the tool stops
73
- * being registered and advertised and the handler never runs again. That is the
74
- * failure this shim exists to prevent: it routes such calls the way the old hook
75
- * did, and says so out loud.
76
- *
77
- * ─── Warning idiom ───────────────────────────────────────────────────────────
78
- *
79
- * `[CopilotKit] `-prefixed `console.warn`, deduped through a module-level `Set`
80
- * so a render path cannot spam it — the same shape as
81
- * react-core's `warnedUnknownStatuses` in `use-default-render-tool.tsx`.
82
- *
83
- * The dev gate is `process.env.NODE_ENV !== "production"`, which is what
84
- * react-core's own hooks/components use and what a test can flip. Other RN
85
- * modules in this package gate on React Native's `__DEV__` global instead; both
86
- * are compile-time-inlined by Metro, so either is stripped from a release
87
- * bundle. `NODE_ENV` is chosen here because this module sits between two
88
- * react-core hooks and is asserted against directly in the suite.
89
- */
90
-
91
- /**
92
- * The two hooks a call can be routed to. Named for the core hook that ends up
93
- * owning the registration, because that is the thing a consumer must change
94
- * their call to.
95
- */
96
- type Route = "useFrontendTool" | "useRenderTool";
97
-
98
- /**
99
- * Dedup key set for the deprecation warning: one warning per distinct tool
100
- * name, not one per render. Module-level (not a ref) so remounting the same
101
- * screen does not re-warn either.
102
- */
103
- const warnedToolNames = new Set<string>();
104
-
105
- /** Tool-shaped fields that only `useFrontendTool` can honour. */
106
- const LEGACY_TOOL_FIELDS = ["description", "handler"] as const;
107
-
108
- /**
109
- * Fields the OLD React Native hook accepted, kept optional here so the call
110
- * shapes the compiler cannot see (hoisted / spread / untyped) still type-check
111
- * and get routed rather than silently dropped.
112
- *
113
- * @typeParam A - The parsed argument type a legacy `handler` receives.
114
- */
115
- interface LegacyToolFields<A> {
116
- /**
117
- * @deprecated A description is a TOOL field: it is what gets advertised to
118
- * the model. Supplying it routes this call to `useFrontendTool` — rename the
119
- * call to `useFrontendTool` instead.
120
- */
121
- description?: string;
122
- /**
123
- * @deprecated A handler is a TOOL field: it is what the model's call
124
- * executes. Supplying it routes this call to `useFrontendTool` — rename the
125
- * call to `useFrontendTool` instead. Note that core's handler receives a
126
- * SECOND argument (the {@link FrontendToolHandlerContext}, carrying
127
- * `stopAgent()`'s abort signal), which the old React Native hook dropped.
128
- */
129
- handler?: (args: A, context: FrontendToolHandlerContext) => Promise<unknown>;
130
- }
131
-
132
- /** The wildcard call shape: a fallback renderer for every unclaimed tool call. */
133
- type WildcardConfig = {
134
- name: "*";
135
- render: (props: any) => React.ReactElement | null;
136
- agentId?: string;
137
- } & LegacyToolFields<Record<string, unknown>> & {
138
- /**
139
- * @deprecated A wildcard renderer paints tool calls it does not own, so it
140
- * has no schema of its own — core's wildcard path ignores this. Remove it.
141
- */
142
- parameters?: StandardSchemaV1;
143
- };
144
-
145
- /** The name-scoped call shape. */
146
- type NamedConfig<S extends StandardSchemaV1> = {
147
- name: string;
148
- parameters: S;
149
- render: (props: RenderToolProps<S>) => React.ReactElement | null;
150
- agentId?: string;
151
- } & LegacyToolFields<InferSchemaOutput<S>>;
152
-
153
- /**
154
- * The IMPLEMENTATION-side shape: the union of both public overloads with
155
- * everything optional and the schema-dependent positions left as `any`.
156
- *
157
- * Deliberately permissive, and invisible to consumers — the two overloads above
158
- * are the public API. This is the same shape react-core gives its own
159
- * implementation signatures (`useRenderTool`, `defineToolCallRenderer`), and it
160
- * is what lets this body forward a config to either core hook without a single
161
- * cast: the alternative — a generic implementation signature — cannot be
162
- * satisfied by both a `name: "*"` config with no schema and a named config with
163
- * one.
164
- */
165
- type ShimConfig = {
166
- name: string;
167
- // `<any, any>` rather than the bare default (`<unknown, unknown>`): a
168
- // schema's OUTPUT type sits in an invariant position on the Standard Schema
169
- // interface, so the bare default is not assignable to the
170
- // `StandardSchemaV1<any, Record<string, unknown>>` that core's
171
- // `ReactFrontendTool` declares. Bridging that variance here — in the
172
- // implementation-only shape — is what keeps the body cast-free.
173
- parameters?: StandardSchemaV1<any, any>;
174
- render: (props: any) => React.ReactElement | null;
175
- agentId?: string;
176
- } & LegacyToolFields<any>;
177
-
178
- /**
179
- * Which core hook a config routes to.
180
- *
181
- * Rule 1 — `name === "*"` WINS, UNCONDITIONALLY. This is deliberately not the
182
- * obvious reading of "old fields mean the old hook". The old RN hook made
183
- * `description` REQUIRED, so anyone who ever attempted a wildcard renderer
184
- * necessarily wrote it WITH the old tool fields. Routing "has old fields" to
185
- * `useFrontendTool` would therefore recreate the original `*`-named-tool bug for
186
- * precisely the people who had tried hardest to use the wildcard. A wildcard
187
- * always means renderer-only.
188
- *
189
- * Rule 2 — otherwise, `handler` or `description` present means the caller wanted
190
- * a tool AND its renderer, which is what the old hook actually did:
191
- * `useFrontendTool`.
192
- *
193
- * Rule 3 — otherwise, `useRenderTool`, i.e. core's hook, unchanged.
194
- *
195
- * One consequence worth knowing about the renderer-only routes (1 and 3): they
196
- * change the EFFECT PHASE the registration lands in. `useFrontendTool`
197
- * registers in a `useLayoutEffect`, core's `useRenderTool` in a `useEffect`, so
198
- * a call that used to register during the layout phase now registers one phase
199
- * later. Only untyped-JS callers can be affected (a typed old call site had to
200
- * supply the required `description`, which routes to `useFrontendTool` and
201
- * keeps the layout phase), and the later phase is what core's `useRenderTool`
202
- * has always done on the web, so this is documented rather than compensated
203
- * for.
204
- */
205
- function routeFor(config: {
206
- name: string;
207
- description?: unknown;
208
- handler?: unknown;
209
- }): Route {
210
- if (config.name === "*") return "useRenderTool";
211
- if (config.description !== undefined || config.handler !== undefined) {
212
- return "useFrontendTool";
213
- }
214
- return "useRenderTool";
215
- }
216
-
217
- /** Legacy field names actually supplied on this config, in declaration order. */
218
- function legacyFieldsOn(config: ShimConfig): string[] {
219
- const supplied: string[] = LEGACY_TOOL_FIELDS.filter(
220
- (field) => config[field] !== undefined,
221
- );
222
- // `parameters` is only a legacy field on the wildcard path, where core has no
223
- // use for it. On the named path it is core's own field and must not be named.
224
- if (config.name === "*" && config.parameters !== undefined) {
225
- supplied.push("parameters");
226
- }
227
- return supplied;
228
- }
229
-
230
- /** `description`, `handler` -> "`description`, `handler`" */
231
- const quoteList = (names: readonly string[]) =>
232
- names.map((name) => `\`${name}\``).join(", ");
233
-
234
- const SHIM_NOTICE =
235
- "React Native's `useRenderTool` is a temporary compatibility shim " +
236
- "(deprecated, scheduled for removal in the next minor).";
237
-
238
- /**
239
- * TEST-ONLY escape hatch for the per-name dedup above.
240
- *
241
- * Not re-exported from any package entry (`src/headless.ts` exports only the
242
- * hook), so it is not public API. It exists because the dedup key is the tool
243
- * NAME and lives for the lifetime of the module: the wildcard's name is the
244
- * same `"*"` for every caller, so without this the second test to assert the
245
- * wildcard's warning would silently observe zero calls and have to be written
246
- * order-dependently instead.
247
- */
248
- export function __resetRenderToolShimWarnings(): void {
249
- warnedToolNames.clear();
250
- }
251
-
252
- function warnOnce(name: string, message: string): void {
253
- if (process.env.NODE_ENV === "production") return;
254
- if (warnedToolNames.has(name)) return;
255
- warnedToolNames.add(name);
256
- console.warn(message);
257
- }
258
-
259
- /**
260
- * Says what was received, which hook the call was routed to, and what to change
261
- * the call to. Dev-only and once per distinct tool name.
262
- *
263
- * EVERY route warns — including the renderer-only route that supplied no legacy
264
- * fields at all. That route looks like a no-op and is not. `description` was
265
- * REQUIRED on the old hook, so a TypeScript caller could never reach
266
- * `{ name, parameters, render }` — but an untyped JS caller could, and untyped
267
- * JS is the whole population this shim exists for. `FrontendTool.handler` is
268
- * optional (`core/src/types.ts`) and `buildFrontendTools` does not filter on
269
- * it, so on the old hook that same call DID register AND advertise a real tool.
270
- * Routing cannot recover the intent, because `{ name, parameters, render }` is
271
- * equally the correct NEW renderer-only spelling — so the warning has to carry
272
- * it, or this one shape stays silent while losing registration.
273
- */
274
- function warnRouted(
275
- name: string,
276
- route: Route,
277
- legacyFields: readonly string[],
278
- ): void {
279
- if (legacyFields.length === 0) {
280
- // Guarded on the ROUTE, not just on the absence of legacy fields: a config
281
- // that HAD them on its first render and then dropped them keeps its frozen
282
- // `useFrontendTool` route, and calling that "renderer only" would be false.
283
- // That case already warned on the first render (and gets the drift warning
284
- // besides), so there is nothing to add here.
285
- if (route !== "useRenderTool") return;
286
-
287
- const registersRendererOnly =
288
- `[CopilotKit] \`useRenderTool({ name: "${name}" })\` from ` +
289
- `@copilotkit/react-native registers a RENDERER ONLY: it supplies UI for a ` +
290
- `tool call and registers no tool of its own. `;
291
-
292
- warnOnce(
293
- name,
294
- name === "*"
295
- ? registersRendererOnly +
296
- `That is the right behaviour for a wildcard, and it is NOT what the ` +
297
- `old React Native \`useRenderTool\` did: that registered a tool ` +
298
- `literally named "*", which is core's catch-all HANDLER name, so it ` +
299
- `auto-answered every otherwise-unanswered tool call with an empty ` +
300
- `tool result and asked for a follow-up turn. ${SHIM_NOTICE} Switch ` +
301
- `to \`useRenderTool\` from \`@copilotkit/react-core\`.`
302
- : registersRendererOnly +
303
- `On the old React Native hook this SAME call also registered and ` +
304
- `advertised a tool named "${name}" to the model, so if you relied on ` +
305
- `that, this call has quietly stopped doing it — use ` +
306
- `\`useFrontendTool\` instead. If you only ever wanted to supply UI ` +
307
- `for a tool somebody else owns, this call is already correct: switch ` +
308
- `it to \`useRenderTool\` from \`@copilotkit/react-core\`. ` +
309
- `${SHIM_NOTICE}`,
310
- );
311
- return;
312
- }
313
-
314
- const received =
315
- `[CopilotKit] \`useRenderTool({ name: "${name}" })\` from ` +
316
- `@copilotkit/react-native received ${quoteList(legacyFields)}. `;
317
-
318
- if (route === "useFrontendTool") {
319
- warnOnce(
320
- name,
321
- received +
322
- `Those are TOOL fields, so this call was routed to \`useFrontendTool\` — ` +
323
- `the hook that registers a tool AND its renderer, which is what the old ` +
324
- `React Native \`useRenderTool\` did. ${SHIM_NOTICE} Rename the call to ` +
325
- `\`useFrontendTool\` (same config object; render props rename \`args\` to ` +
326
- `\`parameters\`). If you only meant to supply UI for a tool somebody else ` +
327
- `owns, drop ${quoteList(legacyFields)} and keep \`useRenderTool\`.`,
328
- );
329
- return;
330
- }
331
-
332
- // Reached with legacy fields present but the renderer-only route in force.
333
- // Normally that is the wildcard (rule 1); it is also what a frozen route
334
- // looks like if a config grew legacy fields after its first render.
335
- warnOnce(
336
- name,
337
- received +
338
- `This call registers a RENDERER ONLY through react-core's ` +
339
- `\`useRenderTool\`, which cannot use them, so they were IGNORED. ` +
340
- (name === "*"
341
- ? `No tool named "*" is registered — the old React Native ` +
342
- `\`useRenderTool\` did register one, and that was the bug: "*" is ` +
343
- `core's catch-all HANDLER name, so it auto-answered every ` +
344
- `otherwise-unanswered tool call with an empty tool result and asked ` +
345
- `for a follow-up turn. `
346
- : `The route was fixed at this component's first render and cannot ` +
347
- `change for its lifetime. `) +
348
- `${SHIM_NOTICE} Remove ${quoteList(legacyFields)} from this call. ` +
349
- `If you meant to register a real frontend tool, give it a real name and ` +
350
- `use \`useFrontendTool\`.`,
351
- );
352
- }
353
-
354
- /**
355
- * Registers a wildcard (`"*"`) renderer for tool calls.
356
- *
357
- * @deprecated Use `useRenderTool` from `@copilotkit/react-core` (re-exported by
358
- * `@copilotkit/react-native/headless` once this shim is gone) for a
359
- * renderer-only registration, or `useFrontendTool` to register a tool and its
360
- * renderer together. This shim is scheduled for removal in the next minor.
361
- *
362
- * @param config - Wildcard renderer configuration.
363
- * @param deps - Optional dependencies to refresh registration.
364
- */
365
- export function useRenderTool(
366
- config: WildcardConfig,
367
- deps?: ReadonlyArray<unknown>,
368
- ): void;
369
-
370
- /**
371
- * Registers a name-scoped renderer for tool calls — or, if `description` or
372
- * `handler` is supplied, a frontend tool and its renderer (what the old React
373
- * Native hook did), with a development warning.
374
- *
375
- * @deprecated Use `useRenderTool` from `@copilotkit/react-core` (re-exported by
376
- * `@copilotkit/react-native/headless` once this shim is gone) for a
377
- * renderer-only registration, or `useFrontendTool` to register a tool and its
378
- * renderer together. This shim is scheduled for removal in the next minor.
379
- *
380
- * @typeParam S - Schema type describing tool call parameters.
381
- * @param config - Named renderer configuration.
382
- * @param deps - Optional dependencies to refresh registration.
383
- */
384
- export function useRenderTool<S extends StandardSchemaV1>(
385
- config: NamedConfig<S>,
386
- deps?: ReadonlyArray<unknown>,
387
- ): void;
388
-
389
- /**
390
- * @deprecated Temporary compatibility shim over react-core's `useRenderTool` /
391
- * `useFrontendTool`; scheduled for removal in the next minor. See the routing
392
- * rules on {@link routeFor}.
393
- */
394
- export function useRenderTool(
395
- config: ShimConfig,
396
- deps?: ReadonlyArray<unknown>,
397
- ): void {
398
- const route = routeFor(config);
399
-
400
- // The route is FROZEN at first render. A hook cannot be called conditionally
401
- // unless the condition is stable for the component's lifetime, and a config
402
- // whose shape changes between renders (`handler: enabled ? fn : undefined`)
403
- // would otherwise flip which core hook is called. Freezing keeps the call
404
- // order constant; the drift is reported below rather than acted on, because
405
- // silently re-routing a live registration is the failure mode this whole shim
406
- // exists to prevent.
407
- const frozenRouteRef = useRef<Route | null>(null);
408
- frozenRouteRef.current ??= route;
409
- const frozenRoute = frozenRouteRef.current;
410
-
411
- const legacyFields = legacyFieldsOn(config);
412
-
413
- useEffect(() => {
414
- warnRouted(config.name, frozenRoute, legacyFields);
415
- // The warning is keyed on the tool name, so re-running it for a changed
416
- // render closure would be pure noise; `warnOnce` dedups anyway.
417
- // eslint-disable-next-line react-hooks/exhaustive-deps
418
- }, [config.name, frozenRoute, legacyFields.join(",")]);
419
-
420
- useEffect(() => {
421
- if (route === frozenRoute) return;
422
- warnOnce(
423
- `${config.name}:route-drift`,
424
- `[CopilotKit] \`useRenderTool({ name: "${config.name}" })\` from ` +
425
- `@copilotkit/react-native changed shape between renders: it now routes ` +
426
- `to \`${route}\` but was registered through \`${frozenRoute}\` and stays ` +
427
- `there for this component's lifetime (a hook cannot be swapped mid-life). ` +
428
- `Call \`${route}\` directly instead of varying \`description\`/\`handler\`.`,
429
- );
430
- }, [config.name, route, frozenRoute]);
431
-
432
- if (frozenRoute === "useFrontendTool") {
433
- // Registration is DELEGATED, never reimplemented: this package must own no
434
- // render-tool registry of its own (RN once did, and `useComponent` — which
435
- // registers into core's — then rendered nowhere on RN).
436
- // eslint-disable-next-line react-hooks/rules-of-hooks
437
- useFrontendTool(toFrontendTool(config), deps);
438
- return;
439
- }
440
-
441
- if (config.name === "*") {
442
- // Rule 1: core's schema-less wildcard branch, whatever else was supplied.
443
- // eslint-disable-next-line react-hooks/rules-of-hooks
444
- useCoreRenderTool(
445
- {
446
- name: "*",
447
- render: config.render,
448
- ...(config.agentId ? { agentId: config.agentId } : {}),
449
- },
450
- deps,
451
- );
452
- return;
453
- }
454
-
455
- // eslint-disable-next-line react-hooks/rules-of-hooks
456
- useCoreRenderTool(
457
- {
458
- name: config.name,
459
- parameters: config.parameters!,
460
- render: config.render,
461
- ...(config.agentId ? { agentId: config.agentId } : {}),
462
- },
463
- deps,
464
- );
465
- }
466
-
467
- /**
468
- * Builds the `ReactFrontendTool` for the `useFrontendTool` route.
469
- *
470
- * The renderer bridge mirrors react-core's own (`use-render-tool.tsx`): core's
471
- * registry invokes a renderer with `args` and an enum `status`, while this
472
- * hook's `render` is declared with core's public `parameters` / string-literal
473
- * `status` shape. Spreading per status keeps the discriminated union correlated
474
- * — and spreading `...props` (rather than picking fields) is also what keeps an
475
- * old `render: ({ args }) => …` painting unchanged at runtime.
476
- */
477
- function toFrontendTool(config: ShimConfig): ReactFrontendTool {
478
- const render: ReactFrontendTool["render"] = (props) => {
479
- // Three byte-identical branches, deliberately: see the note above.
480
- if (props.status === ToolCallStatus.InProgress) {
481
- return config.render({ ...props, parameters: props.args });
482
- }
483
- if (props.status === ToolCallStatus.Executing) {
484
- return config.render({ ...props, parameters: props.args });
485
- }
486
- return config.render({ ...props, parameters: props.args });
487
- };
488
-
489
- return {
490
- name: config.name,
491
- ...(config.description !== undefined
492
- ? { description: config.description }
493
- : {}),
494
- ...(config.parameters !== undefined
495
- ? { parameters: config.parameters }
496
- : {}),
497
- ...(config.handler !== undefined ? { handler: config.handler } : {}),
498
- ...(config.agentId ? { agentId: config.agentId } : {}),
499
- render,
500
- };
501
- }