@copilotkit/react-native 1.57.0-canary.1778116520
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +54 -0
- package/dist/index.cjs +203 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +51 -0
- package/dist/index.d.mts +51 -0
- package/dist/index.mjs +101 -0
- package/dist/index.mjs.map +1 -0
- package/dist/polyfills/crypto.cjs +15 -0
- package/dist/polyfills/crypto.cjs.map +1 -0
- package/dist/polyfills/crypto.d.cts +1 -0
- package/dist/polyfills/crypto.d.mts +1 -0
- package/dist/polyfills/crypto.mjs +15 -0
- package/dist/polyfills/crypto.mjs.map +1 -0
- package/dist/polyfills/dom.cjs +59 -0
- package/dist/polyfills/dom.cjs.map +1 -0
- package/dist/polyfills/dom.d.cts +1 -0
- package/dist/polyfills/dom.d.mts +1 -0
- package/dist/polyfills/dom.mjs +59 -0
- package/dist/polyfills/dom.mjs.map +1 -0
- package/dist/polyfills/encoding.cjs +19 -0
- package/dist/polyfills/encoding.cjs.map +1 -0
- package/dist/polyfills/encoding.d.cts +1 -0
- package/dist/polyfills/encoding.d.mts +1 -0
- package/dist/polyfills/encoding.mjs +19 -0
- package/dist/polyfills/encoding.mjs.map +1 -0
- package/dist/polyfills/location.cjs +18 -0
- package/dist/polyfills/location.cjs.map +1 -0
- package/dist/polyfills/location.d.cts +1 -0
- package/dist/polyfills/location.d.mts +1 -0
- package/dist/polyfills/location.mjs +18 -0
- package/dist/polyfills/location.mjs.map +1 -0
- package/dist/polyfills/streams.cjs +20 -0
- package/dist/polyfills/streams.cjs.map +1 -0
- package/dist/polyfills/streams.d.cts +1 -0
- package/dist/polyfills/streams.d.mts +1 -0
- package/dist/polyfills/streams.mjs +20 -0
- package/dist/polyfills/streams.mjs.map +1 -0
- package/dist/polyfills.cjs +196 -0
- package/dist/polyfills.cjs.map +1 -0
- package/dist/polyfills.d.cts +1 -0
- package/dist/polyfills.d.mts +1 -0
- package/dist/polyfills.mjs +196 -0
- package/dist/polyfills.mjs.map +1 -0
- package/package.json +92 -0
- package/project.json +18 -0
- package/src/CopilotKitProvider.tsx +188 -0
- package/src/__tests__/copilotkit-provider.test.tsx +424 -0
- package/src/__tests__/headless-integration.test.tsx +378 -0
- package/src/__tests__/polyfills.test.ts +242 -0
- package/src/__tests__/setup.ts +9 -0
- package/src/__tests__/streaming-fetch.test.ts +486 -0
- package/src/index.ts +44 -0
- package/src/polyfills/crypto.ts +34 -0
- package/src/polyfills/dom.ts +85 -0
- package/src/polyfills/encoding.ts +20 -0
- package/src/polyfills/location.ts +30 -0
- package/src/polyfills/streams.ts +27 -0
- package/src/polyfills.ts +22 -0
- package/src/streaming-fetch.ts +336 -0
- package/src/types.d.ts +23 -0
- package/tsconfig.json +16 -0
- package/tsdown.config.ts +25 -0
- package/vitest.config.mjs +17 -0
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
//#region src/streaming-fetch.ts
|
|
2
|
+
function createAbortError() {
|
|
3
|
+
return new global.DOMException("The operation was aborted.", "AbortError");
|
|
4
|
+
}
|
|
5
|
+
function installStreamingFetch() {
|
|
6
|
+
try {
|
|
7
|
+
const testResponse = new Response("");
|
|
8
|
+
if (testResponse.body != null && typeof testResponse.body.getReader === "function") return;
|
|
9
|
+
} catch (e) {
|
|
10
|
+
if (__DEV__ && e instanceof Error && !(e instanceof ReferenceError) && !(e instanceof TypeError)) console.warn("[CopilotKit] Unexpected error during streaming fetch feature detection, installing XHR-based polyfill:", e);
|
|
11
|
+
}
|
|
12
|
+
const originalFetch = global.fetch;
|
|
13
|
+
const TextEncoder = global.TextEncoder;
|
|
14
|
+
const streamingFetch = function streamingFetch(input, init) {
|
|
15
|
+
const request = typeof input !== "string" && !(input instanceof URL) ? input : null;
|
|
16
|
+
let url;
|
|
17
|
+
if (typeof input === "string") url = input;
|
|
18
|
+
else if (input instanceof URL) url = input.href;
|
|
19
|
+
else url = input.url;
|
|
20
|
+
const method = init?.method || request?.method || "GET";
|
|
21
|
+
const headers = init?.headers || (request ? request.headers : {});
|
|
22
|
+
const body = init?.body ?? request?.body;
|
|
23
|
+
const signal = init?.signal || request?.signal;
|
|
24
|
+
return new Promise((resolve, reject) => {
|
|
25
|
+
if (signal?.aborted) {
|
|
26
|
+
reject(createAbortError());
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
const xhr = new XMLHttpRequest();
|
|
30
|
+
xhr.open(method, url);
|
|
31
|
+
xhr.timeout = 6e4;
|
|
32
|
+
let headerEntries;
|
|
33
|
+
if (headers instanceof Headers) headerEntries = Array.from(headers.entries());
|
|
34
|
+
else if (Array.isArray(headers)) headerEntries = headers;
|
|
35
|
+
else headerEntries = Object.entries(headers);
|
|
36
|
+
for (const [key, value] of headerEntries) xhr.setRequestHeader(key, value);
|
|
37
|
+
xhr.responseType = "text";
|
|
38
|
+
let streamController = null;
|
|
39
|
+
let lastIndex = 0;
|
|
40
|
+
let streamClosed = false;
|
|
41
|
+
let settled = false;
|
|
42
|
+
const encoder = new TextEncoder();
|
|
43
|
+
let resolveFullText;
|
|
44
|
+
let rejectFullText;
|
|
45
|
+
const fullTextPromise = new Promise((res, rej) => {
|
|
46
|
+
resolveFullText = res;
|
|
47
|
+
rejectFullText = rej;
|
|
48
|
+
});
|
|
49
|
+
fullTextPromise.catch(() => {});
|
|
50
|
+
function closeStream() {
|
|
51
|
+
if (streamController && !streamClosed) {
|
|
52
|
+
streamClosed = true;
|
|
53
|
+
streamController.close();
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function errorStream(err) {
|
|
57
|
+
if (streamController && !streamClosed) {
|
|
58
|
+
streamClosed = true;
|
|
59
|
+
streamController.error(err);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
function flushChunks() {
|
|
63
|
+
if (streamController && !streamClosed && xhr.responseText.length > lastIndex) {
|
|
64
|
+
const newData = xhr.responseText.slice(lastIndex);
|
|
65
|
+
lastIndex = xhr.responseText.length;
|
|
66
|
+
streamController.enqueue(encoder.encode(newData));
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/** Centralized error handler — errors the stream, rejects fullTextPromise,
|
|
70
|
+
* and rejects the outer fetch promise if not yet settled. */
|
|
71
|
+
function fail(err) {
|
|
72
|
+
cleanupAbortListener();
|
|
73
|
+
errorStream(err);
|
|
74
|
+
rejectFullText(err);
|
|
75
|
+
if (!settled) {
|
|
76
|
+
settled = true;
|
|
77
|
+
reject(err);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
const onAbort = () => {
|
|
81
|
+
fail(createAbortError());
|
|
82
|
+
xhr.abort();
|
|
83
|
+
};
|
|
84
|
+
if (signal) signal.addEventListener("abort", onAbort);
|
|
85
|
+
function cleanupAbortListener() {
|
|
86
|
+
if (signal) signal.removeEventListener("abort", onAbort);
|
|
87
|
+
}
|
|
88
|
+
const stream = new ReadableStream({
|
|
89
|
+
start(controller) {
|
|
90
|
+
streamController = controller;
|
|
91
|
+
},
|
|
92
|
+
cancel() {
|
|
93
|
+
xhr.abort();
|
|
94
|
+
rejectFullText(createAbortError());
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
xhr.onprogress = function() {
|
|
98
|
+
try {
|
|
99
|
+
flushChunks();
|
|
100
|
+
} catch (err) {
|
|
101
|
+
fail(err instanceof Error ? err : new Error(String(err)));
|
|
102
|
+
xhr.abort();
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
xhr.onload = function() {
|
|
106
|
+
cleanupAbortListener();
|
|
107
|
+
try {
|
|
108
|
+
flushChunks();
|
|
109
|
+
} catch (err) {
|
|
110
|
+
fail(err instanceof Error ? err : new Error(String(err)));
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
closeStream();
|
|
114
|
+
resolveFullText(xhr.responseText);
|
|
115
|
+
};
|
|
116
|
+
xhr.onerror = function() {
|
|
117
|
+
fail(/* @__PURE__ */ new TypeError("Network request failed"));
|
|
118
|
+
};
|
|
119
|
+
xhr.ontimeout = function() {
|
|
120
|
+
fail(/* @__PURE__ */ new TypeError("Network request timed out"));
|
|
121
|
+
};
|
|
122
|
+
let resp = null;
|
|
123
|
+
xhr.onreadystatechange = function() {
|
|
124
|
+
if (xhr.readyState === 4 && !settled && !resp) {
|
|
125
|
+
fail(/* @__PURE__ */ new TypeError(`Network request to ${url} completed with status ${xhr.status} but no response was produced. This may indicate a CORS failure, DNS error, or React Native networking issue.`));
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
if (xhr.readyState >= 2 && !resp && xhr.status !== 0) {
|
|
129
|
+
const respHeaders = {};
|
|
130
|
+
const rawHeaders = xhr.getAllResponseHeaders() || "";
|
|
131
|
+
for (const line of rawHeaders.trim().split("\r\n")) {
|
|
132
|
+
const idx = line.indexOf(": ");
|
|
133
|
+
if (idx > 0) respHeaders[line.slice(0, idx).toLowerCase()] = line.slice(idx + 2);
|
|
134
|
+
}
|
|
135
|
+
const responseHeaders = new Headers(respHeaders);
|
|
136
|
+
let bodyUsed = false;
|
|
137
|
+
resp = {
|
|
138
|
+
ok: xhr.status >= 200 && xhr.status < 300,
|
|
139
|
+
status: xhr.status,
|
|
140
|
+
statusText: xhr.statusText,
|
|
141
|
+
url,
|
|
142
|
+
type: "basic",
|
|
143
|
+
redirected: false,
|
|
144
|
+
get bodyUsed() {
|
|
145
|
+
return bodyUsed;
|
|
146
|
+
},
|
|
147
|
+
headers: responseHeaders,
|
|
148
|
+
body: stream,
|
|
149
|
+
json: async () => {
|
|
150
|
+
bodyUsed = true;
|
|
151
|
+
const text = await fullTextPromise;
|
|
152
|
+
try {
|
|
153
|
+
return JSON.parse(text);
|
|
154
|
+
} catch (e) {
|
|
155
|
+
throw new TypeError(`Failed to parse JSON from ${method} ${url} (status ${xhr.status}): ${text.length > 200 ? text.slice(0, 200) + "..." : text}`);
|
|
156
|
+
}
|
|
157
|
+
},
|
|
158
|
+
text: async () => {
|
|
159
|
+
bodyUsed = true;
|
|
160
|
+
return fullTextPromise;
|
|
161
|
+
},
|
|
162
|
+
arrayBuffer: async () => {
|
|
163
|
+
bodyUsed = true;
|
|
164
|
+
return encoder.encode(await fullTextPromise).buffer;
|
|
165
|
+
},
|
|
166
|
+
blob: async () => {
|
|
167
|
+
bodyUsed = true;
|
|
168
|
+
const buf = encoder.encode(await fullTextPromise);
|
|
169
|
+
if (typeof Blob !== "undefined") return new Blob([buf], { type: responseHeaders.get("content-type") || "" });
|
|
170
|
+
throw new Error("Blob is not available in this React Native environment.");
|
|
171
|
+
},
|
|
172
|
+
clone: () => {
|
|
173
|
+
throw new Error("Response.clone() is not supported by the React Native streaming fetch polyfill.");
|
|
174
|
+
},
|
|
175
|
+
formData: async () => {
|
|
176
|
+
throw new Error("Response.formData() is not supported by the React Native streaming fetch polyfill.");
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
settled = true;
|
|
180
|
+
resolve(resp);
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
xhr.send(body ?? null);
|
|
184
|
+
});
|
|
185
|
+
};
|
|
186
|
+
streamingFetch.__originalFetch = originalFetch;
|
|
187
|
+
global.fetch = streamingFetch;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
//#endregion
|
|
191
|
+
//#region src/polyfills.ts
|
|
192
|
+
installStreamingFetch();
|
|
193
|
+
|
|
194
|
+
//#endregion
|
|
195
|
+
export { };
|
|
196
|
+
//# sourceMappingURL=polyfills.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"polyfills.mjs","names":[],"sources":["../src/streaming-fetch.ts","../src/polyfills.ts"],"sourcesContent":["/**\n * Streaming fetch implementation for React Native.\n *\n * React Native's built-in fetch doesn't support response.body.getReader()\n * (ReadableStream). This replaces global.fetch with an XHR-based\n * implementation that streams chunks via ReadableStream, enabling\n * CopilotKit's SSE-based agent communication.\n *\n * If native fetch already supports ReadableStream bodies (newer RN / Hermes),\n * the replacement is skipped entirely.\n *\n * Call `installStreamingFetch()` once at app startup after polyfills.\n */\n\ndeclare const global: typeof globalThis;\n\n/** Subset of the Response interface implemented by the streaming fetch polyfill. */\ninterface StreamingFetchResponse {\n readonly ok: boolean;\n readonly status: number;\n readonly statusText: string;\n readonly url: string;\n readonly type: string;\n readonly redirected: boolean;\n readonly bodyUsed: boolean;\n readonly headers: Headers;\n readonly body: ReadableStream<Uint8Array>;\n json(): Promise<unknown>;\n text(): Promise<string>;\n arrayBuffer(): Promise<ArrayBuffer>;\n blob(): Promise<Blob>;\n clone(): never;\n formData(): Promise<never>;\n}\n\nfunction createAbortError(): DOMException {\n return new (global as any).DOMException(\n \"The operation was aborted.\",\n \"AbortError\",\n );\n}\n\nexport function installStreamingFetch(): void {\n // Skip if native fetch already supports ReadableStream body.\n // Newer React Native versions (Hermes) may support this natively.\n try {\n const testResponse = new Response(\"\");\n if (\n testResponse.body != null &&\n typeof testResponse.body.getReader === \"function\"\n ) {\n return;\n }\n } catch (e) {\n // Response constructor unavailable — expected in older RN environments.\n if (\n __DEV__ &&\n e instanceof Error &&\n !(e instanceof ReferenceError) &&\n !(e instanceof TypeError)\n ) {\n console.warn(\n \"[CopilotKit] Unexpected error during streaming fetch feature detection, \" +\n \"installing XHR-based polyfill:\",\n e,\n );\n }\n }\n\n const originalFetch = global.fetch;\n const TextEncoder = global.TextEncoder;\n\n const streamingFetch = function streamingFetch(\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> {\n // Extract defaults from Request object when input is a Request\n const request =\n typeof input !== \"string\" && !(input instanceof URL) ? input : null;\n let url: string;\n if (typeof input === \"string\") {\n url = input;\n } else if (input instanceof URL) {\n url = input.href;\n } else {\n url = (input as Request).url;\n }\n const method = init?.method || request?.method || \"GET\";\n const headers = init?.headers || (request ? request.headers : {});\n const body = (init?.body ?? request?.body) as string | null | undefined;\n const signal = init?.signal || request?.signal;\n\n return new Promise((resolve, reject) => {\n // Reject immediately if signal is already aborted (per fetch spec)\n if (signal?.aborted) {\n reject(createAbortError());\n return;\n }\n\n const xhr = new XMLHttpRequest();\n xhr.open(method, url);\n\n // Default 60s timeout to prevent hanging on stalled mobile connections\n // (WiFi→cellular transitions, tunnels, serverless cold starts).\n // Callers can still use AbortSignal.timeout() for finer control.\n xhr.timeout = 60_000;\n\n let headerEntries: [string, string][];\n if (headers instanceof Headers) {\n headerEntries = Array.from(headers.entries());\n } else if (Array.isArray(headers)) {\n headerEntries = headers as [string, string][];\n } else {\n headerEntries = Object.entries(headers as Record<string, string>);\n }\n for (const [key, value] of headerEntries) {\n xhr.setRequestHeader(key, value as string);\n }\n\n xhr.responseType = \"text\";\n\n let streamController: ReadableStreamDefaultController<Uint8Array> | null =\n null;\n let lastIndex = 0;\n let streamClosed = false;\n let settled = false;\n const encoder = new TextEncoder();\n\n // Promise that resolves/rejects when XHR completes or fails\n let resolveFullText: (text: string) => void;\n let rejectFullText: (error: Error) => void;\n const fullTextPromise = new Promise<string>((res, rej) => {\n resolveFullText = res;\n rejectFullText = rej;\n });\n // Prevent unhandled rejection when error occurs but .text()/.json() is never called\n fullTextPromise.catch(() => {});\n\n function closeStream() {\n if (streamController && !streamClosed) {\n streamClosed = true;\n streamController.close();\n }\n }\n\n function errorStream(err: Error) {\n if (streamController && !streamClosed) {\n streamClosed = true;\n streamController.error(err);\n }\n }\n\n function flushChunks() {\n if (\n streamController &&\n !streamClosed &&\n xhr.responseText.length > lastIndex\n ) {\n const newData = xhr.responseText.slice(lastIndex);\n lastIndex = xhr.responseText.length;\n streamController.enqueue(encoder.encode(newData));\n }\n }\n\n /** Centralized error handler — errors the stream, rejects fullTextPromise,\n * and rejects the outer fetch promise if not yet settled. */\n function fail(err: Error) {\n cleanupAbortListener();\n errorStream(err);\n rejectFullText(err);\n if (!settled) {\n settled = true;\n reject(err);\n }\n }\n\n const onAbort = () => {\n fail(createAbortError());\n xhr.abort();\n };\n\n if (signal) {\n signal.addEventListener(\"abort\", onAbort);\n }\n\n function cleanupAbortListener() {\n if (signal) {\n signal.removeEventListener(\"abort\", onAbort);\n }\n }\n\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n streamController = controller;\n },\n cancel() {\n xhr.abort();\n rejectFullText(createAbortError());\n },\n });\n\n xhr.onprogress = function () {\n try {\n flushChunks();\n } catch (err) {\n fail(err instanceof Error ? err : new Error(String(err)));\n xhr.abort();\n }\n };\n\n xhr.onload = function () {\n cleanupAbortListener();\n try {\n flushChunks();\n } catch (err) {\n fail(err instanceof Error ? err : new Error(String(err)));\n return;\n }\n closeStream();\n resolveFullText(xhr.responseText);\n };\n\n xhr.onerror = function () {\n fail(new TypeError(\"Network request failed\"));\n };\n\n xhr.ontimeout = function () {\n fail(new TypeError(\"Network request timed out\"));\n };\n\n // Resolve with Response once headers arrive.\n // Guard against status === 0 which XHR produces for CORS failures,\n // DNS errors, and mixed-content blocks — let onerror handle those.\n let resp: StreamingFetchResponse | null = null;\n xhr.onreadystatechange = function () {\n // Safety net: if XHR completed but we never resolved/rejected, fail explicitly.\n // This can happen when status === 0 and onerror doesn't fire (some RN networking impls).\n if (xhr.readyState === 4 && !settled && !resp) {\n fail(\n new TypeError(\n `Network request to ${url} completed with status ${xhr.status} but no response was produced. ` +\n `This may indicate a CORS failure, DNS error, or React Native networking issue.`,\n ),\n );\n return;\n }\n\n if (xhr.readyState >= 2 && !resp && xhr.status !== 0) {\n const respHeaders: Record<string, string> = {};\n const rawHeaders = xhr.getAllResponseHeaders() || \"\";\n for (const line of rawHeaders.trim().split(\"\\r\\n\")) {\n const idx = line.indexOf(\": \");\n if (idx > 0) {\n respHeaders[line.slice(0, idx).toLowerCase()] = line.slice(\n idx + 2,\n );\n }\n }\n\n const responseHeaders = new Headers(respHeaders);\n\n let bodyUsed = false;\n\n resp = {\n // Duck-typed Response object (not a native Response instance)\n ok: xhr.status >= 200 && xhr.status < 300,\n status: xhr.status,\n statusText: xhr.statusText,\n url: url,\n type: \"basic\",\n redirected: false,\n get bodyUsed() {\n return bodyUsed;\n },\n headers: responseHeaders,\n body: stream,\n json: async () => {\n bodyUsed = true;\n const text = await fullTextPromise;\n try {\n return JSON.parse(text);\n } catch (e) {\n throw new TypeError(\n `Failed to parse JSON from ${method} ${url} (status ${xhr.status}): ${\n text.length > 200 ? text.slice(0, 200) + \"...\" : text\n }`,\n );\n }\n },\n text: async () => {\n bodyUsed = true;\n return fullTextPromise;\n },\n arrayBuffer: async () => {\n bodyUsed = true;\n return encoder.encode(await fullTextPromise).buffer;\n },\n blob: async () => {\n bodyUsed = true;\n const buf = encoder.encode(await fullTextPromise);\n if (typeof Blob !== \"undefined\") {\n return new Blob([buf], {\n type: responseHeaders.get(\"content-type\") || \"\",\n });\n }\n throw new Error(\n \"Blob is not available in this React Native environment.\",\n );\n },\n clone: () => {\n throw new Error(\n \"Response.clone() is not supported by the React Native streaming fetch polyfill.\",\n );\n },\n formData: async () => {\n throw new Error(\n \"Response.formData() is not supported by the React Native streaming fetch polyfill.\",\n );\n },\n };\n settled = true;\n // NOTE: abort listener is NOT removed here — the signal must remain\n // wired to xhr.abort() for mid-stream cancellation. Cleanup happens\n // in terminal handlers (onload, onerror, ontimeout) or onAbort itself.\n resolve(resp as unknown as Response);\n }\n };\n\n xhr.send(body ?? null);\n });\n };\n\n // Expose original fetch for opt-out (e.g., third-party libs that need native behavior)\n (streamingFetch as any).__originalFetch = originalFetch;\n global.fetch = streamingFetch;\n}\n","/**\n * All polyfills required for CopilotKit to work in React Native.\n *\n * Import this BEFORE any CopilotKit code in your app entry point:\n * import \"@copilotkit/react-native/polyfills\";\n *\n * For granular control, import individual polyfills instead:\n * import \"@copilotkit/react-native/polyfills/streams\";\n * import \"@copilotkit/react-native/polyfills/encoding\";\n * import \"@copilotkit/react-native/polyfills/crypto\";\n * import \"@copilotkit/react-native/polyfills/dom\";\n * import \"@copilotkit/react-native/polyfills/location\";\n */\n\nimport \"./polyfills/streams\";\nimport \"./polyfills/encoding\";\nimport \"./polyfills/crypto\";\nimport \"./polyfills/dom\";\nimport \"./polyfills/location\";\n\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G,IAAI,GAAG,QAAQ,OAEpD;;;MAGL,MAAM,YAAY;AAChB,kBAAW;AACX,cAAO;;MAET,aAAa,YAAY;AACvB,kBAAW;AACX,cAAO,QAAQ,OAAO,MAAM,gBAAgB,CAAC;;MAE/C,MAAM,YAAY;AAChB,kBAAW;OACX,MAAM,MAAM,QAAQ,OAAO,MAAM,gBAAgB;AACjD,WAAI,OAAO,SAAS,YAClB,QAAO,IAAI,KAAK,CAAC,IAAI,EAAE,EACrB,MAAM,gBAAgB,IAAI,eAAe,IAAI,IAC9C,CAAC;AAEJ,aAAM,IAAI,MACR,0DACD;;MAEH,aAAa;AACX,aAAM,IAAI,MACR,kFACD;;MAEH,UAAU,YAAY;AACpB,aAAM,IAAI,MACR,qFACD;;MAEJ;AACD,eAAU;AAIV,aAAQ,KAA4B;;;AAIxC,OAAI,KAAK,QAAQ,KAAK;IACtB;;AAIJ,CAAC,eAAuB,kBAAkB;AAC1C,QAAO,QAAQ;;;;;ACzTjB,uBAAuB"}
|
package/package.json
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@copilotkit/react-native",
|
|
3
|
+
"version": "1.57.0-canary.1778116520",
|
|
4
|
+
"private": false,
|
|
5
|
+
"keywords": [
|
|
6
|
+
"ai",
|
|
7
|
+
"assistant",
|
|
8
|
+
"copilot",
|
|
9
|
+
"copilotkit",
|
|
10
|
+
"mobile",
|
|
11
|
+
"react-native"
|
|
12
|
+
],
|
|
13
|
+
"homepage": "https://github.com/CopilotKit/CopilotKit",
|
|
14
|
+
"license": "MIT",
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "https://github.com/CopilotKit/CopilotKit.git"
|
|
18
|
+
},
|
|
19
|
+
"type": "module",
|
|
20
|
+
"sideEffects": [
|
|
21
|
+
"./dist/polyfills.*",
|
|
22
|
+
"./dist/polyfills/**/*"
|
|
23
|
+
],
|
|
24
|
+
"main": "./dist/index.cjs",
|
|
25
|
+
"module": "./dist/index.mjs",
|
|
26
|
+
"types": "./dist/index.d.cts",
|
|
27
|
+
"exports": {
|
|
28
|
+
".": {
|
|
29
|
+
"import": "./dist/index.mjs",
|
|
30
|
+
"require": "./dist/index.cjs"
|
|
31
|
+
},
|
|
32
|
+
"./polyfills": {
|
|
33
|
+
"import": "./dist/polyfills.mjs",
|
|
34
|
+
"require": "./dist/polyfills.cjs"
|
|
35
|
+
},
|
|
36
|
+
"./polyfills/streams": {
|
|
37
|
+
"import": "./dist/polyfills/streams.mjs",
|
|
38
|
+
"require": "./dist/polyfills/streams.cjs"
|
|
39
|
+
},
|
|
40
|
+
"./polyfills/encoding": {
|
|
41
|
+
"import": "./dist/polyfills/encoding.mjs",
|
|
42
|
+
"require": "./dist/polyfills/encoding.cjs"
|
|
43
|
+
},
|
|
44
|
+
"./polyfills/crypto": {
|
|
45
|
+
"import": "./dist/polyfills/crypto.mjs",
|
|
46
|
+
"require": "./dist/polyfills/crypto.cjs"
|
|
47
|
+
},
|
|
48
|
+
"./polyfills/dom": {
|
|
49
|
+
"import": "./dist/polyfills/dom.mjs",
|
|
50
|
+
"require": "./dist/polyfills/dom.cjs"
|
|
51
|
+
},
|
|
52
|
+
"./polyfills/location": {
|
|
53
|
+
"import": "./dist/polyfills/location.mjs",
|
|
54
|
+
"require": "./dist/polyfills/location.cjs"
|
|
55
|
+
},
|
|
56
|
+
"./package.json": "./package.json"
|
|
57
|
+
},
|
|
58
|
+
"publishConfig": {
|
|
59
|
+
"access": "public"
|
|
60
|
+
},
|
|
61
|
+
"dependencies": {
|
|
62
|
+
"text-encoding": "^0.7.0",
|
|
63
|
+
"web-streams-polyfill": "^4.2.0",
|
|
64
|
+
"@copilotkit/core": "1.57.0-canary.1778116520",
|
|
65
|
+
"@copilotkit/react-core": "1.57.0-canary.1778116520",
|
|
66
|
+
"@copilotkit/shared": "1.57.0-canary.1778116520"
|
|
67
|
+
},
|
|
68
|
+
"devDependencies": {
|
|
69
|
+
"@testing-library/react": "^16.3.0",
|
|
70
|
+
"@types/react": "^19.2.0",
|
|
71
|
+
"jsdom": "^26.1.0",
|
|
72
|
+
"react": "^19.1.0",
|
|
73
|
+
"react-dom": "^19.1.0",
|
|
74
|
+
"tsdown": "^0.20.3",
|
|
75
|
+
"typescript": "^5.8.3",
|
|
76
|
+
"vitest": "^3.2.4"
|
|
77
|
+
},
|
|
78
|
+
"peerDependencies": {
|
|
79
|
+
"react": "^18 || ^19",
|
|
80
|
+
"react-native": ">=0.70"
|
|
81
|
+
},
|
|
82
|
+
"scripts": {
|
|
83
|
+
"build": "tsdown",
|
|
84
|
+
"dev": "tsdown --watch",
|
|
85
|
+
"test": "vitest run",
|
|
86
|
+
"check-types": "tsc --noEmit",
|
|
87
|
+
"publint": "publint .",
|
|
88
|
+
"attw": "attw --pack . --profile node16 --ignore-rules internal-resolution-error",
|
|
89
|
+
"link:global": "pnpm link --global",
|
|
90
|
+
"unlink:global": "pnpm unlink --global"
|
|
91
|
+
}
|
|
92
|
+
}
|
package/project.json
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@copilotkit/react-native",
|
|
3
|
+
"$schema": "../../node_modules/nx/schemas/project-schema.json",
|
|
4
|
+
"sourceRoot": "packages/react-native/src",
|
|
5
|
+
"projectType": "library",
|
|
6
|
+
"targets": {
|
|
7
|
+
"build": {
|
|
8
|
+
"executor": "nx:run-commands",
|
|
9
|
+
"options": {
|
|
10
|
+
"command": "pnpm run build",
|
|
11
|
+
"cwd": "packages/react-native"
|
|
12
|
+
},
|
|
13
|
+
"dependsOn": ["^build"],
|
|
14
|
+
"inputs": ["production", "^production"],
|
|
15
|
+
"outputs": ["{projectRoot}/dist/**"]
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
}
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import React, {
|
|
2
|
+
type ReactNode,
|
|
3
|
+
useEffect,
|
|
4
|
+
useMemo,
|
|
5
|
+
useRef,
|
|
6
|
+
useState,
|
|
7
|
+
} from "react";
|
|
8
|
+
import {
|
|
9
|
+
CopilotKitContext,
|
|
10
|
+
type CopilotKitContextValue,
|
|
11
|
+
LicenseContext,
|
|
12
|
+
} from "@copilotkit/react-core/v2/context";
|
|
13
|
+
import { CopilotKitCoreReact } from "@copilotkit/react-core/v2/headless";
|
|
14
|
+
import type { CopilotKitCoreErrorCode } from "@copilotkit/core";
|
|
15
|
+
|
|
16
|
+
export interface CopilotKitNativeProviderProps {
|
|
17
|
+
children: ReactNode;
|
|
18
|
+
/** URL of the CopilotKit runtime endpoint */
|
|
19
|
+
runtimeUrl: string;
|
|
20
|
+
/** Custom headers sent with every request */
|
|
21
|
+
headers?: Record<string, string>;
|
|
22
|
+
/** Whether the runtime uses a single-route endpoint */
|
|
23
|
+
useSingleEndpoint?: boolean;
|
|
24
|
+
/** Custom properties forwarded to agents */
|
|
25
|
+
properties?: Record<string, unknown>;
|
|
26
|
+
/**
|
|
27
|
+
* Error handler called when CopilotKit encounters an error.
|
|
28
|
+
* Fires for all error types (runtime connection failures, agent errors, tool errors).
|
|
29
|
+
* If not provided, errors are logged to console.error.
|
|
30
|
+
*/
|
|
31
|
+
onError?: (event: {
|
|
32
|
+
error: Error;
|
|
33
|
+
code: CopilotKitCoreErrorCode;
|
|
34
|
+
context: Record<string, any>;
|
|
35
|
+
}) => void;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* CopilotKit provider for React Native.
|
|
40
|
+
*
|
|
41
|
+
* A lightweight alternative to the web CopilotKitProvider that avoids
|
|
42
|
+
* web-only dependencies (DOM, CSS, Radix UI, Lit, etc).
|
|
43
|
+
*
|
|
44
|
+
* Usage:
|
|
45
|
+
* ```tsx
|
|
46
|
+
* import "@copilotkit/react-native/polyfills";
|
|
47
|
+
* import { CopilotKitProvider } from "@copilotkit/react-native";
|
|
48
|
+
*
|
|
49
|
+
* function App() {
|
|
50
|
+
* return (
|
|
51
|
+
* <CopilotKitProvider runtimeUrl="https://your-runtime/api/copilotkit">
|
|
52
|
+
* <ChatScreen />
|
|
53
|
+
* </CopilotKitProvider>
|
|
54
|
+
* );
|
|
55
|
+
* }
|
|
56
|
+
* ```
|
|
57
|
+
*/
|
|
58
|
+
export const CopilotKitProvider: React.FC<CopilotKitNativeProviderProps> = ({
|
|
59
|
+
children,
|
|
60
|
+
runtimeUrl,
|
|
61
|
+
headers,
|
|
62
|
+
useSingleEndpoint,
|
|
63
|
+
properties,
|
|
64
|
+
onError,
|
|
65
|
+
}) => {
|
|
66
|
+
// Stabilize headers/properties references to avoid effect churn when callers
|
|
67
|
+
// pass inline object literals (e.g. headers={{}} or the undefined default).
|
|
68
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
69
|
+
const stableHeaders = useMemo(() => headers ?? {}, [JSON.stringify(headers)]);
|
|
70
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
71
|
+
const stableProperties = useMemo(
|
|
72
|
+
() => properties ?? {},
|
|
73
|
+
[JSON.stringify(properties)],
|
|
74
|
+
);
|
|
75
|
+
|
|
76
|
+
const copilotkitRef = useRef<CopilotKitCoreReact | null>(null);
|
|
77
|
+
|
|
78
|
+
if (copilotkitRef.current === null) {
|
|
79
|
+
copilotkitRef.current = new CopilotKitCoreReact({
|
|
80
|
+
runtimeUrl,
|
|
81
|
+
runtimeTransport:
|
|
82
|
+
useSingleEndpoint === true
|
|
83
|
+
? "single"
|
|
84
|
+
: useSingleEndpoint === false
|
|
85
|
+
? "rest"
|
|
86
|
+
: "auto",
|
|
87
|
+
headers: stableHeaders,
|
|
88
|
+
properties: stableProperties,
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const copilotkit = copilotkitRef.current;
|
|
93
|
+
|
|
94
|
+
// Sync props to core instance
|
|
95
|
+
useEffect(() => {
|
|
96
|
+
copilotkit.setRuntimeUrl(runtimeUrl);
|
|
97
|
+
copilotkit.setRuntimeTransport(
|
|
98
|
+
useSingleEndpoint === true
|
|
99
|
+
? "single"
|
|
100
|
+
: useSingleEndpoint === false
|
|
101
|
+
? "rest"
|
|
102
|
+
: "auto",
|
|
103
|
+
);
|
|
104
|
+
copilotkit.setHeaders(stableHeaders);
|
|
105
|
+
copilotkit.setProperties(stableProperties);
|
|
106
|
+
}, [
|
|
107
|
+
runtimeUrl,
|
|
108
|
+
useSingleEndpoint,
|
|
109
|
+
stableHeaders,
|
|
110
|
+
stableProperties,
|
|
111
|
+
copilotkit,
|
|
112
|
+
]);
|
|
113
|
+
|
|
114
|
+
// Track executing tool call IDs at the provider level.
|
|
115
|
+
// Critical for HITL reconnection: onToolExecutionStart fires before child
|
|
116
|
+
// components mount, so we must capture the state here.
|
|
117
|
+
const [executingToolCallIds, setExecutingToolCallIds] = useState<
|
|
118
|
+
ReadonlySet<string>
|
|
119
|
+
>(() => new Set());
|
|
120
|
+
|
|
121
|
+
// Use ref to avoid subscription churn when onError changes
|
|
122
|
+
const onErrorRef = useRef(onError);
|
|
123
|
+
useEffect(() => {
|
|
124
|
+
onErrorRef.current = onError;
|
|
125
|
+
}, [onError]);
|
|
126
|
+
|
|
127
|
+
// Single subscription for tool execution tracking and error handling.
|
|
128
|
+
// Tool call IDs are tracked at the provider level because onToolExecutionStart
|
|
129
|
+
// fires before child components mount — critical for HITL reconnection.
|
|
130
|
+
useEffect(() => {
|
|
131
|
+
const subscription = copilotkit.subscribe({
|
|
132
|
+
onToolExecutionStart: ({ toolCallId }) => {
|
|
133
|
+
setExecutingToolCallIds((prev) => {
|
|
134
|
+
if (prev.has(toolCallId)) return prev;
|
|
135
|
+
const next = new Set(prev);
|
|
136
|
+
next.add(toolCallId);
|
|
137
|
+
return next;
|
|
138
|
+
});
|
|
139
|
+
},
|
|
140
|
+
onToolExecutionEnd: ({ toolCallId }) => {
|
|
141
|
+
setExecutingToolCallIds((prev) => {
|
|
142
|
+
if (!prev.has(toolCallId)) return prev;
|
|
143
|
+
const next = new Set(prev);
|
|
144
|
+
next.delete(toolCallId);
|
|
145
|
+
return next;
|
|
146
|
+
});
|
|
147
|
+
},
|
|
148
|
+
onError: (event) => {
|
|
149
|
+
if (onErrorRef.current) {
|
|
150
|
+
onErrorRef.current(event);
|
|
151
|
+
} else {
|
|
152
|
+
console.error(
|
|
153
|
+
`[CopilotKit] Error (${event.code}):`,
|
|
154
|
+
event.error,
|
|
155
|
+
event.context ?? {},
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
},
|
|
159
|
+
});
|
|
160
|
+
return () => subscription.unsubscribe();
|
|
161
|
+
}, [copilotkit]);
|
|
162
|
+
|
|
163
|
+
const contextValue: CopilotKitContextValue = useMemo(
|
|
164
|
+
() => ({
|
|
165
|
+
copilotkit,
|
|
166
|
+
executingToolCallIds,
|
|
167
|
+
}),
|
|
168
|
+
[copilotkit, executingToolCallIds],
|
|
169
|
+
);
|
|
170
|
+
|
|
171
|
+
const licenseContextValue = useMemo(
|
|
172
|
+
() => ({
|
|
173
|
+
status: null as null,
|
|
174
|
+
license: null as null,
|
|
175
|
+
checkFeature: () => true,
|
|
176
|
+
getLimit: () => null,
|
|
177
|
+
}),
|
|
178
|
+
[],
|
|
179
|
+
);
|
|
180
|
+
|
|
181
|
+
return (
|
|
182
|
+
<CopilotKitContext.Provider value={contextValue}>
|
|
183
|
+
<LicenseContext.Provider value={licenseContextValue}>
|
|
184
|
+
{children}
|
|
185
|
+
</LicenseContext.Provider>
|
|
186
|
+
</CopilotKitContext.Provider>
|
|
187
|
+
);
|
|
188
|
+
};
|