@copilotkit/react-native 2.0.0-rc.20 → 2.0.0-rc.21

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.
@@ -8,78 +8,37 @@ import type {
8
8
  CopilotKitContextValue,
9
9
  CopilotKitCoreReact as CopilotKitCoreReactInstance,
10
10
  } from "@copilotkit/react-core/context";
11
- import { CopilotKitCoreReact } from "@copilotkit/react-core/headless";
11
+ import {
12
+ CopilotKitCoreReact,
13
+ ɵuseOwnedCore,
14
+ } from "@copilotkit/react-core/headless";
12
15
  import type {
13
- CopilotKitCoreErrorCode,
14
- CopilotKitMessageFilter,
16
+ ɵCopilotKitProviderBaseOptions,
17
+ ɵRuntimeInfo,
18
+ } from "@copilotkit/core";
19
+ import {
20
+ ɵreportProviderConfigDiagnostics,
21
+ ɵresolveProviderConfig,
15
22
  } from "@copilotkit/core";
16
- import type { DebugConfig, RuntimeLicenseStatus } from "@copilotkit/shared";
17
23
  import { createLicenseContextValue } from "@copilotkit/shared";
18
24
  import { MarkdownRendererProvider } from "./components/MarkdownRendererContext";
19
25
  import type { MarkdownRendererValue } from "./components/MarkdownRendererContext";
20
26
 
21
- export interface CopilotKitNativeProviderProps {
27
+ export interface CopilotKitNativeProviderProps extends Pick<
28
+ ɵCopilotKitProviderBaseOptions,
29
+ | "credentials"
30
+ | "messageFilter"
31
+ | "useSingleEndpoint"
32
+ | "properties"
33
+ | "onError"
34
+ | "debug"
35
+ | "defaultThrottleMs"
36
+ > {
22
37
  children: ReactNode;
23
38
  /** URL of the CopilotKit runtime endpoint */
24
39
  runtimeUrl: string;
25
40
  /** Custom headers sent with every request */
26
41
  headers?: Record<string, string> | (() => Record<string, string>);
27
- /**
28
- * Credentials mode for fetch requests (e.g., "include" for HTTP-only cookies in cross-origin requests).
29
- */
30
- credentials?: RequestCredentials;
31
- /**
32
- * Rewrites the message list sent to runtime agents on every run.
33
- *
34
- * CopilotKit sends the whole thread each time. When your agent already
35
- * stores the conversation, most of that payload is waste, and an agent that
36
- * merges the inbound list with its own store can show the model every turn
37
- * twice. Return the messages to send:
38
- *
39
- * ```tsx
40
- * <CopilotKitProvider
41
- * runtimeUrl="/api/copilotkit"
42
- * messageFilter={(messages) => messages.slice(-1)}
43
- * />
44
- * ```
45
- *
46
- * The filter changes the request body only. The transcript the UI renders is
47
- * untouched. Broken tool-call pairs are repaired before the request is sent,
48
- * so a filter this blunt cannot strand a tool result mid-HITL.
49
- *
50
- * Agents reached through your CopilotRuntime honor this. An agent your app
51
- * passes in directly does not, and neither Intelligence runs nor suggestion
52
- * runs are ever filtered.
53
- *
54
- * Prefer a stable reference (`useCallback`). An inline arrow re-registers the
55
- * filter on every render, which is harmless but needless.
56
- */
57
- messageFilter?: CopilotKitMessageFilter;
58
- /** Whether the runtime uses a single-route endpoint */
59
- useSingleEndpoint?: boolean;
60
- /** Custom properties forwarded to agents */
61
- properties?: Record<string, unknown>;
62
- /**
63
- * Error handler called when CopilotKit encounters an error.
64
- * Fires for all error types (runtime connection failures, agent errors, tool errors).
65
- * If not provided, errors are logged to console.error.
66
- */
67
- onError?: (event: {
68
- error: Error;
69
- code: CopilotKitCoreErrorCode;
70
- context: Record<string, any>;
71
- }) => void | Promise<void>;
72
- /**
73
- * Enable debug logging for the client-side event pipeline.
74
- * `true` logs event and lifecycle summaries. Pass `{ verbose: true }` for
75
- * full event payloads.
76
- */
77
- debug?: DebugConfig;
78
- /**
79
- * Default throttle interval (ms) for `onMessagesChanged` / `onStateChanged`
80
- * subscriptions. Individual subscriptions can override with their own `throttleMs`.
81
- */
82
- defaultThrottleMs?: number;
83
42
  /**
84
43
  * Custom markdown renderer for assistant messages. Either a component (escape
85
44
  * hatch — receives `content` and an optional `isStreaming` flag) used instead
@@ -144,66 +103,75 @@ export const CopilotKitProvider: React.FC<CopilotKitNativeProviderProps> = ({
144
103
  [JSON.stringify(properties)],
145
104
  );
146
105
 
106
+ // Transport mapping and config checks come from core.
107
+ const resolvedConfig = useMemo(
108
+ () =>
109
+ ɵresolveProviderConfig({
110
+ runtimeUrl,
111
+ useSingleEndpoint,
112
+ properties: stableProperties,
113
+ }),
114
+ [runtimeUrl, useSingleEndpoint, stableProperties],
115
+ );
116
+ const loggedDiagnosticsRef = useRef(new Set<string>());
117
+ ɵreportProviderConfigDiagnostics(resolvedConfig.diagnostics, {
118
+ isProduction: process.env.NODE_ENV === "production",
119
+ logged: loggedDiagnosticsRef.current,
120
+ });
121
+
122
+ // One core for the provider lifetime, disposed on unmount (StrictMode
123
+ // safe, see `ɵuseOwnedCore`).
147
124
  const copilotkitRef = useRef<CopilotKitCoreReactInstance | null>(null);
125
+ const copilotkit = ɵuseOwnedCore(
126
+ copilotkitRef,
127
+ (): CopilotKitCoreReactInstance =>
128
+ new CopilotKitCoreReact({
129
+ runtimeUrl: resolvedConfig.runtimeUrl,
130
+ runtimeTransport: resolvedConfig.runtimeTransport,
131
+ // `/info` starts from the effect below, so a render React discards
132
+ // never fetches it (#5801).
133
+ deferInitialConnection: true,
134
+ headers: stableHeaders,
135
+ credentials,
136
+ messageFilter,
137
+ properties: resolvedConfig.properties,
138
+ debug,
139
+ // Set at construction so child hooks see it on their first render.
140
+ defaultThrottleMs,
141
+ onError,
142
+ }),
143
+ );
148
144
 
149
- if (copilotkitRef.current === null) {
150
- const instance: CopilotKitCoreReactInstance = new CopilotKitCoreReact({
151
- runtimeUrl,
152
- runtimeTransport:
153
- useSingleEndpoint === true
154
- ? "single"
155
- : useSingleEndpoint === false
156
- ? "rest"
157
- : "auto",
145
+ // Core calls `onError`, and logs the error itself when there is none.
146
+ useEffect(() => {
147
+ copilotkit.setErrorHandler(onError);
148
+ }, [copilotkit, onError]);
149
+
150
+ // Sync props to the core. Core applies only what changed.
151
+ useEffect(() => {
152
+ copilotkit.ɵupdateConfig({
153
+ messageFilter,
154
+ runtimeUrl: resolvedConfig.runtimeUrl,
155
+ runtimeTransport: resolvedConfig.runtimeTransport,
158
156
  headers: stableHeaders,
159
157
  credentials,
160
- messageFilter,
161
- properties: stableProperties,
158
+ properties: resolvedConfig.properties,
162
159
  debug,
160
+ defaultThrottleMs,
163
161
  });
164
- // Set initial defaultThrottleMs synchronously so child hooks see the
165
- // correct value on their first render (before useEffect fires).
166
- if (defaultThrottleMs !== undefined) {
167
- instance.setDefaultThrottleMs(defaultThrottleMs);
168
- }
169
- copilotkitRef.current = instance;
170
- }
171
-
172
- const copilotkit = copilotkitRef.current;
173
-
174
- // Sync props to core instance
175
- useEffect(() => {
176
- copilotkit.setRuntimeUrl(runtimeUrl);
177
- copilotkit.setRuntimeTransport(
178
- useSingleEndpoint === true
179
- ? "single"
180
- : useSingleEndpoint === false
181
- ? "rest"
182
- : "auto",
183
- );
184
- copilotkit.setHeaders(stableHeaders);
185
- copilotkit.setCredentials(credentials);
186
- copilotkit.setMessageFilter(messageFilter);
187
- copilotkit.setProperties(stableProperties);
188
- copilotkit.setDebug(debug);
162
+ copilotkit.connect();
189
163
  }, [
190
- runtimeUrl,
191
- useSingleEndpoint,
164
+ copilotkit,
165
+ messageFilter,
166
+ resolvedConfig.runtimeUrl,
167
+ resolvedConfig.runtimeTransport,
192
168
  stableHeaders,
193
169
  credentials,
194
- messageFilter,
195
- stableProperties,
170
+ resolvedConfig.properties,
196
171
  debug,
197
- copilotkit,
172
+ defaultThrottleMs,
198
173
  ]);
199
174
 
200
- // Sync defaultThrottleMs to the core instance on prop changes.
201
- // Initial value is set synchronously during instance creation (inside the
202
- // ref guard above), so this only handles subsequent updates.
203
- useEffect(() => {
204
- copilotkit.setDefaultThrottleMs(defaultThrottleMs);
205
- }, [copilotkit, defaultThrottleMs]);
206
-
207
175
  // Track executing tool call IDs at the provider level.
208
176
  // Critical for HITL reconnection: onToolExecutionStart fires before child
209
177
  // components mount, so we must capture the state here.
@@ -211,17 +179,19 @@ export const CopilotKitProvider: React.FC<CopilotKitNativeProviderProps> = ({
211
179
  ReadonlySet<string>
212
180
  >(() => new Set());
213
181
 
214
- const [runtimeLicenseStatus, setRuntimeLicenseStatus] = useState<
215
- RuntimeLicenseStatus | undefined
216
- >(undefined);
182
+ const [runtimeInfo, setRuntimeInfo] = useState<ɵRuntimeInfo | null>(null);
183
+ const runtimeLicenseStatus = runtimeInfo?.licenseStatus;
217
184
 
218
- // Use ref to avoid subscription churn when onError changes
219
- const onErrorRef = useRef(onError);
185
+ // Project core's runtime info snapshot; the catch-up read reflects a status
186
+ // that settled before this effect ran.
220
187
  useEffect(() => {
221
- onErrorRef.current = onError;
222
- }, [onError]);
188
+ const syncRuntimeInfo = () => setRuntimeInfo(copilotkit.ɵruntimeInfo);
189
+ const unsubscribe = copilotkit.ɵsubscribeToRuntimeInfo(syncRuntimeInfo);
190
+ syncRuntimeInfo();
191
+ return unsubscribe;
192
+ }, [copilotkit]);
223
193
 
224
- // Single subscription for tool execution tracking and error handling.
194
+ // Tool execution tracking.
225
195
  // Tool call IDs are tracked at the provider level because onToolExecutionStart
226
196
  // fires before child components mount — critical for HITL reconnection.
227
197
  useEffect(() => {
@@ -242,20 +212,6 @@ export const CopilotKitProvider: React.FC<CopilotKitNativeProviderProps> = ({
242
212
  return next;
243
213
  });
244
214
  },
245
- onError: (event) => {
246
- if (onErrorRef.current) {
247
- void onErrorRef.current(event);
248
- } else {
249
- console.error(
250
- `[CopilotKit] Error (${event.code}):`,
251
- event.error,
252
- event.context ?? {},
253
- );
254
- }
255
- },
256
- onRuntimeConnectionStatusChanged: () => {
257
- setRuntimeLicenseStatus(copilotkit.licenseStatus);
258
- },
259
215
  });
260
216
  return () => subscription.unsubscribe();
261
217
  }, [copilotkit]);
@@ -62,6 +62,12 @@ function createMockCore() {
62
62
  setMessageFilter: vi.fn(),
63
63
  setDebug: vi.fn(),
64
64
  setDefaultThrottleMs: vi.fn(),
65
+ ɵupdateConfig: vi.fn(),
66
+ ɵruntimeInfo: { status: "disconnected" },
67
+ ɵsubscribeToRuntimeInfo: vi.fn(() => () => {}),
68
+ setErrorHandler: vi.fn(),
69
+ connect: vi.fn(),
70
+ dispose: vi.fn(),
65
71
  getAgent: vi.fn(() => undefined),
66
72
  runAgent: (...args: any[]) => mockRunAgent(...args),
67
73
  runtimeUrl: "https://api.test",
@@ -82,13 +88,17 @@ function createMockCore() {
82
88
 
83
89
  let mockCoreInstance: ReturnType<typeof createMockCore>;
84
90
 
85
- vi.mock("@copilotkit/react-core/headless", () => {
91
+ vi.mock("@copilotkit/react-core/headless", async (importOriginal) => {
92
+ // The real entry, so the provider gets the real `ɵuseOwnedCore`.
93
+ const actual =
94
+ await importOriginal<typeof import("@copilotkit/react-core/headless")>();
86
95
  function CopilotKitCoreReact(this: any, ...args: any[]) {
87
96
  hoisted.MockCoreConstructor(...args);
88
97
  const instance = hoisted.MockCoreConstructor.mock.results.at(-1)?.value;
89
98
  if (instance) Object.assign(this, instance);
90
99
  }
91
100
  return {
101
+ ...actual,
92
102
  CopilotKitCoreReact,
93
103
  useAgent: () => {
94
104
  const ctx = require("react").useContext(hoisted.RealContext);
@@ -147,7 +157,10 @@ vi.mock("@copilotkit/react-core/context", () => {
147
157
  };
148
158
  });
149
159
 
150
- vi.mock("@copilotkit/shared", () => ({
160
+ vi.mock("@copilotkit/shared", async (importOriginal) => ({
161
+ // The real module first: the provider evaluates @copilotkit/core, which
162
+ // needs shared's value exports.
163
+ ...(await importOriginal<typeof import("@copilotkit/shared")>()),
151
164
  DEFAULT_AGENT_ID: "default",
152
165
  randomUUID: () => "test-uuid-" + Math.random().toString(36).slice(2, 8),
153
166
  getModalityFromMimeType: (mimeType: string) => {
@@ -33,6 +33,12 @@ function createMockCore() {
33
33
  setMessageFilter: vi.fn(),
34
34
  setDebug: vi.fn(),
35
35
  setDefaultThrottleMs: vi.fn(),
36
+ ɵupdateConfig: vi.fn(),
37
+ ɵruntimeInfo: { status: "disconnected" },
38
+ ɵsubscribeToRuntimeInfo: vi.fn(() => () => {}),
39
+ setErrorHandler: vi.fn(),
40
+ connect: vi.fn(),
41
+ dispose: vi.fn(),
36
42
  getAgent: vi.fn(() => undefined),
37
43
  runtimeUrl: "https://api.test",
38
44
  runtimeTransport: "auto",
@@ -52,13 +58,17 @@ function createMockCore() {
52
58
 
53
59
  let mockCoreInstance: ReturnType<typeof createMockCore>;
54
60
 
55
- vi.mock("@copilotkit/react-core/headless", () => {
61
+ vi.mock("@copilotkit/react-core/headless", async (importOriginal) => {
62
+ // The real entry, so the provider gets the real `ɵuseOwnedCore`.
63
+ const actual =
64
+ await importOriginal<typeof import("@copilotkit/react-core/headless")>();
56
65
  function CopilotKitCoreReact(this: any, ...args: any[]) {
57
66
  hoisted.MockCoreConstructor(...args);
58
67
  const instance = hoisted.MockCoreConstructor.mock.results.at(-1)?.value;
59
68
  if (instance) Object.assign(this, instance);
60
69
  }
61
70
  return {
71
+ ...actual,
62
72
  CopilotKitCoreReact,
63
73
  useAgent: (props: any) => {
64
74
  const ctx = require("react").useContext(hoisted.RealContext);
@@ -118,7 +128,10 @@ vi.mock("@copilotkit/react-core/context", () => {
118
128
  };
119
129
  });
120
130
 
121
- vi.mock("@copilotkit/shared", () => ({
131
+ vi.mock("@copilotkit/shared", async (importOriginal) => ({
132
+ // The real module first: the provider evaluates @copilotkit/core, which
133
+ // needs shared's value exports.
134
+ ...(await importOriginal<typeof import("@copilotkit/shared")>()),
122
135
  DEFAULT_AGENT_ID: "default",
123
136
  createLicenseContextValue: () => ({
124
137
  status: null,
@@ -60,6 +60,12 @@ function createMockCore() {
60
60
  setMessageFilter: vi.fn(),
61
61
  setDebug: vi.fn(),
62
62
  setDefaultThrottleMs: vi.fn(),
63
+ ɵupdateConfig: vi.fn(),
64
+ ɵruntimeInfo: { status: "disconnected" },
65
+ ɵsubscribeToRuntimeInfo: vi.fn(() => () => {}),
66
+ setErrorHandler: vi.fn(),
67
+ connect: vi.fn(),
68
+ dispose: vi.fn(),
63
69
  getAgent: vi.fn(() => undefined),
64
70
  runAgent: mockRunAgent,
65
71
  runtimeUrl: "https://api.test",
@@ -80,13 +86,17 @@ function createMockCore() {
80
86
 
81
87
  let mockCoreInstance: ReturnType<typeof createMockCore>;
82
88
 
83
- vi.mock("@copilotkit/react-core/headless", () => {
89
+ vi.mock("@copilotkit/react-core/headless", async (importOriginal) => {
90
+ // The real entry, so the provider gets the real `ɵuseOwnedCore`.
91
+ const actual =
92
+ await importOriginal<typeof import("@copilotkit/react-core/headless")>();
84
93
  function CopilotKitCoreReact(this: any, ...args: any[]) {
85
94
  hoisted.MockCoreConstructor(...args);
86
95
  const instance = hoisted.MockCoreConstructor.mock.results.at(-1)?.value;
87
96
  if (instance) Object.assign(this, instance);
88
97
  }
89
98
  return {
99
+ ...actual,
90
100
  CopilotKitCoreReact,
91
101
  useAgent: () => {
92
102
  const ctx = require("react").useContext(hoisted.RealContext);
@@ -145,7 +155,10 @@ vi.mock("@copilotkit/react-core/context", () => {
145
155
  };
146
156
  });
147
157
 
148
- vi.mock("@copilotkit/shared", () => ({
158
+ vi.mock("@copilotkit/shared", async (importOriginal) => ({
159
+ // The real module first: the provider evaluates @copilotkit/core, which
160
+ // needs shared's value exports.
161
+ ...(await importOriginal<typeof import("@copilotkit/shared")>()),
149
162
  DEFAULT_AGENT_ID: "default",
150
163
  randomUUID: () => "test-uuid-" + Math.random().toString(36).slice(2, 8),
151
164
  getModalityFromMimeType: (mimeType: string) => {
@@ -33,6 +33,12 @@ function createMockCore() {
33
33
  setMessageFilter: vi.fn(),
34
34
  setDebug: vi.fn(),
35
35
  setDefaultThrottleMs: vi.fn(),
36
+ ɵupdateConfig: vi.fn(),
37
+ ɵruntimeInfo: { status: "disconnected" },
38
+ ɵsubscribeToRuntimeInfo: vi.fn(() => () => {}),
39
+ setErrorHandler: vi.fn(),
40
+ connect: vi.fn(),
41
+ dispose: vi.fn(),
36
42
  getAgent: vi.fn(() => undefined),
37
43
  runtimeUrl: "https://api.test",
38
44
  runtimeTransport: "auto",
@@ -52,13 +58,17 @@ function createMockCore() {
52
58
 
53
59
  let mockCoreInstance: ReturnType<typeof createMockCore>;
54
60
 
55
- vi.mock("@copilotkit/react-core/headless", () => {
61
+ vi.mock("@copilotkit/react-core/headless", async (importOriginal) => {
62
+ // The real entry, so the provider gets the real `ɵuseOwnedCore`.
63
+ const actual =
64
+ await importOriginal<typeof import("@copilotkit/react-core/headless")>();
56
65
  function CopilotKitCoreReact(this: any, ...args: any[]) {
57
66
  hoisted.MockCoreConstructor(...args);
58
67
  const instance = hoisted.MockCoreConstructor.mock.results.at(-1)?.value;
59
68
  if (instance) Object.assign(this, instance);
60
69
  }
61
70
  return {
71
+ ...actual,
62
72
  CopilotKitCoreReact,
63
73
  useAgent: (props: any) => {
64
74
  const ctx = require("react").useContext(hoisted.RealContext);
@@ -118,7 +128,10 @@ vi.mock("@copilotkit/react-core/context", () => {
118
128
  };
119
129
  });
120
130
 
121
- vi.mock("@copilotkit/shared", () => ({
131
+ vi.mock("@copilotkit/shared", async (importOriginal) => ({
132
+ // The real module first: the provider evaluates @copilotkit/core, which
133
+ // needs shared's value exports.
134
+ ...(await importOriginal<typeof import("@copilotkit/shared")>()),
122
135
  DEFAULT_AGENT_ID: "default",
123
136
  randomUUID: () => "test-uuid-" + Math.random().toString(36).slice(2, 8),
124
137
  getModalityFromMimeType: (mimeType: string) => {
@@ -33,6 +33,12 @@ function createMockCore() {
33
33
  setMessageFilter: vi.fn(),
34
34
  setDebug: vi.fn(),
35
35
  setDefaultThrottleMs: vi.fn(),
36
+ ɵupdateConfig: vi.fn(),
37
+ ɵruntimeInfo: { status: "disconnected" },
38
+ ɵsubscribeToRuntimeInfo: vi.fn(() => () => {}),
39
+ setErrorHandler: vi.fn(),
40
+ connect: vi.fn(),
41
+ dispose: vi.fn(),
36
42
  getAgent: vi.fn(() => undefined),
37
43
  runtimeUrl: "https://api.test",
38
44
  runtimeTransport: "auto",
@@ -52,13 +58,17 @@ function createMockCore() {
52
58
 
53
59
  let mockCoreInstance: ReturnType<typeof createMockCore>;
54
60
 
55
- vi.mock("@copilotkit/react-core/headless", () => {
61
+ vi.mock("@copilotkit/react-core/headless", async (importOriginal) => {
62
+ // The real entry, so the provider gets the real `ɵuseOwnedCore`.
63
+ const actual =
64
+ await importOriginal<typeof import("@copilotkit/react-core/headless")>();
56
65
  function CopilotKitCoreReact(this: any, ...args: any[]) {
57
66
  hoisted.MockCoreConstructor(...args);
58
67
  const instance = hoisted.MockCoreConstructor.mock.results.at(-1)?.value;
59
68
  if (instance) Object.assign(this, instance);
60
69
  }
61
70
  return {
71
+ ...actual,
62
72
  CopilotKitCoreReact,
63
73
  useAgent: (props: any) => {
64
74
  const ctx = require("react").useContext(hoisted.RealContext);
@@ -118,7 +128,10 @@ vi.mock("@copilotkit/react-core/context", () => {
118
128
  };
119
129
  });
120
130
 
121
- vi.mock("@copilotkit/shared", () => ({
131
+ vi.mock("@copilotkit/shared", async (importOriginal) => ({
132
+ // The real module first: the provider evaluates @copilotkit/core, which
133
+ // needs shared's value exports.
134
+ ...(await importOriginal<typeof import("@copilotkit/shared")>()),
122
135
  DEFAULT_AGENT_ID: "default",
123
136
  randomUUID: () => "test-uuid-" + Math.random().toString(36).slice(2, 8),
124
137
  getModalityFromMimeType: (mimeType: string) => {