@automattic/jetpack-ai-client 0.1.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.
package/.gitattributes ADDED
@@ -0,0 +1,7 @@
1
+ # Files not needed to be distributed in the package.
2
+ .gitattributes export-ignore
3
+ node_modules export-ignore
4
+
5
+ # Files to exclude from the mirror repo
6
+ /changelog/** production-exclude
7
+ /.eslintrc.cjs production-exclude
package/CHANGELOG.md ADDED
@@ -0,0 +1,19 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## 0.1.0 - 2023-07-25
9
+ ### Added
10
+ - Add Jetpack AI Client [#30855]
11
+ - AI Client: add askQuestion() lib [#31964]
12
+ - AI Client: export SuggestionsEventSource updated library [#31944]
13
+ - AI Client: update and expose JWT library [#31924]
14
+
15
+ ### Changed
16
+ - AI Client: stop using smart document visibility handling on the fetchEventSource library, so it does not restart the completion when changing tabs. [#32004]
17
+ - Updated package dependencies. [#31468]
18
+ - Updated package dependencies. [#31659]
19
+ - Updated package dependencies. [#31785]
package/LICENSE.txt ADDED
@@ -0,0 +1,357 @@
1
+ This program is free software; you can redistribute it and/or modify
2
+ it under the terms of the GNU General Public License as published by
3
+ the Free Software Foundation; either version 2 of the License, or
4
+ (at your option) any later version.
5
+
6
+ This program is distributed in the hope that it will be useful,
7
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
8
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9
+ GNU General Public License for more details.
10
+
11
+ You should have received a copy of the GNU General Public License
12
+ along with this program; if not, write to the Free Software
13
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
14
+
15
+
16
+ ===================================
17
+
18
+
19
+ GNU GENERAL PUBLIC LICENSE
20
+ Version 2, June 1991
21
+
22
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
23
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24
+ Everyone is permitted to copy and distribute verbatim copies
25
+ of this license document, but changing it is not allowed.
26
+
27
+ Preamble
28
+
29
+ The licenses for most software are designed to take away your
30
+ freedom to share and change it. By contrast, the GNU General Public
31
+ License is intended to guarantee your freedom to share and change free
32
+ software--to make sure the software is free for all its users. This
33
+ General Public License applies to most of the Free Software
34
+ Foundation's software and to any other program whose authors commit to
35
+ using it. (Some other Free Software Foundation software is covered by
36
+ the GNU Lesser General Public License instead.) You can apply it to
37
+ your programs, too.
38
+
39
+ When we speak of free software, we are referring to freedom, not
40
+ price. Our General Public Licenses are designed to make sure that you
41
+ have the freedom to distribute copies of free software (and charge for
42
+ this service if you wish), that you receive source code or can get it
43
+ if you want it, that you can change the software or use pieces of it
44
+ in new free programs; and that you know you can do these things.
45
+
46
+ To protect your rights, we need to make restrictions that forbid
47
+ anyone to deny you these rights or to ask you to surrender the rights.
48
+ These restrictions translate to certain responsibilities for you if you
49
+ distribute copies of the software, or if you modify it.
50
+
51
+ For example, if you distribute copies of such a program, whether
52
+ gratis or for a fee, you must give the recipients all the rights that
53
+ you have. You must make sure that they, too, receive or can get the
54
+ source code. And you must show them these terms so they know their
55
+ rights.
56
+
57
+ We protect your rights with two steps: (1) copyright the software, and
58
+ (2) offer you this license which gives you legal permission to copy,
59
+ distribute and/or modify the software.
60
+
61
+ Also, for each author's protection and ours, we want to make certain
62
+ that everyone understands that there is no warranty for this free
63
+ software. If the software is modified by someone else and passed on, we
64
+ want its recipients to know that what they have is not the original, so
65
+ that any problems introduced by others will not reflect on the original
66
+ authors' reputations.
67
+
68
+ Finally, any free program is threatened constantly by software
69
+ patents. We wish to avoid the danger that redistributors of a free
70
+ program will individually obtain patent licenses, in effect making the
71
+ program proprietary. To prevent this, we have made it clear that any
72
+ patent must be licensed for everyone's free use or not licensed at all.
73
+
74
+ The precise terms and conditions for copying, distribution and
75
+ modification follow.
76
+
77
+ GNU GENERAL PUBLIC LICENSE
78
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
79
+
80
+ 0. This License applies to any program or other work which contains
81
+ a notice placed by the copyright holder saying it may be distributed
82
+ under the terms of this General Public License. The "Program", below,
83
+ refers to any such program or work, and a "work based on the Program"
84
+ means either the Program or any derivative work under copyright law:
85
+ that is to say, a work containing the Program or a portion of it,
86
+ either verbatim or with modifications and/or translated into another
87
+ language. (Hereinafter, translation is included without limitation in
88
+ the term "modification".) Each licensee is addressed as "you".
89
+
90
+ Activities other than copying, distribution and modification are not
91
+ covered by this License; they are outside its scope. The act of
92
+ running the Program is not restricted, and the output from the Program
93
+ is covered only if its contents constitute a work based on the
94
+ Program (independent of having been made by running the Program).
95
+ Whether that is true depends on what the Program does.
96
+
97
+ 1. You may copy and distribute verbatim copies of the Program's
98
+ source code as you receive it, in any medium, provided that you
99
+ conspicuously and appropriately publish on each copy an appropriate
100
+ copyright notice and disclaimer of warranty; keep intact all the
101
+ notices that refer to this License and to the absence of any warranty;
102
+ and give any other recipients of the Program a copy of this License
103
+ along with the Program.
104
+
105
+ You may charge a fee for the physical act of transferring a copy, and
106
+ you may at your option offer warranty protection in exchange for a fee.
107
+
108
+ 2. You may modify your copy or copies of the Program or any portion
109
+ of it, thus forming a work based on the Program, and copy and
110
+ distribute such modifications or work under the terms of Section 1
111
+ above, provided that you also meet all of these conditions:
112
+
113
+ a) You must cause the modified files to carry prominent notices
114
+ stating that you changed the files and the date of any change.
115
+
116
+ b) You must cause any work that you distribute or publish, that in
117
+ whole or in part contains or is derived from the Program or any
118
+ part thereof, to be licensed as a whole at no charge to all third
119
+ parties under the terms of this License.
120
+
121
+ c) If the modified program normally reads commands interactively
122
+ when run, you must cause it, when started running for such
123
+ interactive use in the most ordinary way, to print or display an
124
+ announcement including an appropriate copyright notice and a
125
+ notice that there is no warranty (or else, saying that you provide
126
+ a warranty) and that users may redistribute the program under
127
+ these conditions, and telling the user how to view a copy of this
128
+ License. (Exception: if the Program itself is interactive but
129
+ does not normally print such an announcement, your work based on
130
+ the Program is not required to print an announcement.)
131
+
132
+ These requirements apply to the modified work as a whole. If
133
+ identifiable sections of that work are not derived from the Program,
134
+ and can be reasonably considered independent and separate works in
135
+ themselves, then this License, and its terms, do not apply to those
136
+ sections when you distribute them as separate works. But when you
137
+ distribute the same sections as part of a whole which is a work based
138
+ on the Program, the distribution of the whole must be on the terms of
139
+ this License, whose permissions for other licensees extend to the
140
+ entire whole, and thus to each and every part regardless of who wrote it.
141
+
142
+ Thus, it is not the intent of this section to claim rights or contest
143
+ your rights to work written entirely by you; rather, the intent is to
144
+ exercise the right to control the distribution of derivative or
145
+ collective works based on the Program.
146
+
147
+ In addition, mere aggregation of another work not based on the Program
148
+ with the Program (or with a work based on the Program) on a volume of
149
+ a storage or distribution medium does not bring the other work under
150
+ the scope of this License.
151
+
152
+ 3. You may copy and distribute the Program (or a work based on it,
153
+ under Section 2) in object code or executable form under the terms of
154
+ Sections 1 and 2 above provided that you also do one of the following:
155
+
156
+ a) Accompany it with the complete corresponding machine-readable
157
+ source code, which must be distributed under the terms of Sections
158
+ 1 and 2 above on a medium customarily used for software interchange; or,
159
+
160
+ b) Accompany it with a written offer, valid for at least three
161
+ years, to give any third party, for a charge no more than your
162
+ cost of physically performing source distribution, a complete
163
+ machine-readable copy of the corresponding source code, to be
164
+ distributed under the terms of Sections 1 and 2 above on a medium
165
+ customarily used for software interchange; or,
166
+
167
+ c) Accompany it with the information you received as to the offer
168
+ to distribute corresponding source code. (This alternative is
169
+ allowed only for noncommercial distribution and only if you
170
+ received the program in object code or executable form with such
171
+ an offer, in accord with Subsection b above.)
172
+
173
+ The source code for a work means the preferred form of the work for
174
+ making modifications to it. For an executable work, complete source
175
+ code means all the source code for all modules it contains, plus any
176
+ associated interface definition files, plus the scripts used to
177
+ control compilation and installation of the executable. However, as a
178
+ special exception, the source code distributed need not include
179
+ anything that is normally distributed (in either source or binary
180
+ form) with the major components (compiler, kernel, and so on) of the
181
+ operating system on which the executable runs, unless that component
182
+ itself accompanies the executable.
183
+
184
+ If distribution of executable or object code is made by offering
185
+ access to copy from a designated place, then offering equivalent
186
+ access to copy the source code from the same place counts as
187
+ distribution of the source code, even though third parties are not
188
+ compelled to copy the source along with the object code.
189
+
190
+ 4. You may not copy, modify, sublicense, or distribute the Program
191
+ except as expressly provided under this License. Any attempt
192
+ otherwise to copy, modify, sublicense or distribute the Program is
193
+ void, and will automatically terminate your rights under this License.
194
+ However, parties who have received copies, or rights, from you under
195
+ this License will not have their licenses terminated so long as such
196
+ parties remain in full compliance.
197
+
198
+ 5. You are not required to accept this License, since you have not
199
+ signed it. However, nothing else grants you permission to modify or
200
+ distribute the Program or its derivative works. These actions are
201
+ prohibited by law if you do not accept this License. Therefore, by
202
+ modifying or distributing the Program (or any work based on the
203
+ Program), you indicate your acceptance of this License to do so, and
204
+ all its terms and conditions for copying, distributing or modifying
205
+ the Program or works based on it.
206
+
207
+ 6. Each time you redistribute the Program (or any work based on the
208
+ Program), the recipient automatically receives a license from the
209
+ original licensor to copy, distribute or modify the Program subject to
210
+ these terms and conditions. You may not impose any further
211
+ restrictions on the recipients' exercise of the rights granted herein.
212
+ You are not responsible for enforcing compliance by third parties to
213
+ this License.
214
+
215
+ 7. If, as a consequence of a court judgment or allegation of patent
216
+ infringement or for any other reason (not limited to patent issues),
217
+ conditions are imposed on you (whether by court order, agreement or
218
+ otherwise) that contradict the conditions of this License, they do not
219
+ excuse you from the conditions of this License. If you cannot
220
+ distribute so as to satisfy simultaneously your obligations under this
221
+ License and any other pertinent obligations, then as a consequence you
222
+ may not distribute the Program at all. For example, if a patent
223
+ license would not permit royalty-free redistribution of the Program by
224
+ all those who receive copies directly or indirectly through you, then
225
+ the only way you could satisfy both it and this License would be to
226
+ refrain entirely from distribution of the Program.
227
+
228
+ If any portion of this section is held invalid or unenforceable under
229
+ any particular circumstance, the balance of the section is intended to
230
+ apply and the section as a whole is intended to apply in other
231
+ circumstances.
232
+
233
+ It is not the purpose of this section to induce you to infringe any
234
+ patents or other property right claims or to contest validity of any
235
+ such claims; this section has the sole purpose of protecting the
236
+ integrity of the free software distribution system, which is
237
+ implemented by public license practices. Many people have made
238
+ generous contributions to the wide range of software distributed
239
+ through that system in reliance on consistent application of that
240
+ system; it is up to the author/donor to decide if he or she is willing
241
+ to distribute software through any other system and a licensee cannot
242
+ impose that choice.
243
+
244
+ This section is intended to make thoroughly clear what is believed to
245
+ be a consequence of the rest of this License.
246
+
247
+ 8. If the distribution and/or use of the Program is restricted in
248
+ certain countries either by patents or by copyrighted interfaces, the
249
+ original copyright holder who places the Program under this License
250
+ may add an explicit geographical distribution limitation excluding
251
+ those countries, so that distribution is permitted only in or among
252
+ countries not thus excluded. In such case, this License incorporates
253
+ the limitation as if written in the body of this License.
254
+
255
+ 9. The Free Software Foundation may publish revised and/or new versions
256
+ of the General Public License from time to time. Such new versions will
257
+ be similar in spirit to the present version, but may differ in detail to
258
+ address new problems or concerns.
259
+
260
+ Each version is given a distinguishing version number. If the Program
261
+ specifies a version number of this License which applies to it and "any
262
+ later version", you have the option of following the terms and conditions
263
+ either of that version or of any later version published by the Free
264
+ Software Foundation. If the Program does not specify a version number of
265
+ this License, you may choose any version ever published by the Free Software
266
+ Foundation.
267
+
268
+ 10. If you wish to incorporate parts of the Program into other free
269
+ programs whose distribution conditions are different, write to the author
270
+ to ask for permission. For software which is copyrighted by the Free
271
+ Software Foundation, write to the Free Software Foundation; we sometimes
272
+ make exceptions for this. Our decision will be guided by the two goals
273
+ of preserving the free status of all derivatives of our free software and
274
+ of promoting the sharing and reuse of software generally.
275
+
276
+ NO WARRANTY
277
+
278
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
279
+ FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
280
+ OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
281
+ PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
282
+ OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
283
+ MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
284
+ TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
285
+ PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
286
+ REPAIR OR CORRECTION.
287
+
288
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
289
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
290
+ REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
291
+ INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
292
+ OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
293
+ TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
294
+ YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
295
+ PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
296
+ POSSIBILITY OF SUCH DAMAGES.
297
+
298
+ END OF TERMS AND CONDITIONS
299
+
300
+ How to Apply These Terms to Your New Programs
301
+
302
+ If you develop a new program, and you want it to be of the greatest
303
+ possible use to the public, the best way to achieve this is to make it
304
+ free software which everyone can redistribute and change under these terms.
305
+
306
+ To do so, attach the following notices to the program. It is safest
307
+ to attach them to the start of each source file to most effectively
308
+ convey the exclusion of warranty; and each file should have at least
309
+ the "copyright" line and a pointer to where the full notice is found.
310
+
311
+ <one line to give the program's name and a brief idea of what it does.>
312
+ Copyright (C) <year> <name of author>
313
+
314
+ This program is free software; you can redistribute it and/or modify
315
+ it under the terms of the GNU General Public License as published by
316
+ the Free Software Foundation; either version 2 of the License, or
317
+ (at your option) any later version.
318
+
319
+ This program is distributed in the hope that it will be useful,
320
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
321
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
322
+ GNU General Public License for more details.
323
+
324
+ You should have received a copy of the GNU General Public License along
325
+ with this program; if not, write to the Free Software Foundation, Inc.,
326
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
327
+
328
+ Also add information on how to contact you by electronic and paper mail.
329
+
330
+ If the program is interactive, make it output a short notice like this
331
+ when it starts in an interactive mode:
332
+
333
+ Gnomovision version 69, Copyright (C) year name of author
334
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
335
+ This is free software, and you are welcome to redistribute it
336
+ under certain conditions; type `show c' for details.
337
+
338
+ The hypothetical commands `show w' and `show c' should show the appropriate
339
+ parts of the General Public License. Of course, the commands you use may
340
+ be called something other than `show w' and `show c'; they could even be
341
+ mouse-clicks or menu items--whatever suits your program.
342
+
343
+ You should also get your employer (if you work as a programmer) or your
344
+ school, if any, to sign a "copyright disclaimer" for the program, if
345
+ necessary. Here is a sample; alter the names:
346
+
347
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
348
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
349
+
350
+ <signature of Ty Coon>, 1 April 1989
351
+ Ty Coon, President of Vice
352
+
353
+ This General Public License does not permit incorporating your program into
354
+ proprietary programs. If your program is a subroutine library, you may
355
+ consider it more useful to permit linking proprietary applications with the
356
+ library. If this is what you want to do, use the GNU Lesser General
357
+ Public License instead of this License.
package/README.md ADDED
@@ -0,0 +1,141 @@
1
+ # Jetpack AI Client
2
+
3
+ JavaScript client for consuming Jetpack AI services. This client provides functionalities to fetch images and request completions from the Jetpack AI API as well as managing authentication tokens for the Jetpack AI streaming completion API.
4
+
5
+ ## Installation
6
+
7
+ To install the Jetpack AI Client, clone the repository to your local machine and install the dependencies with npm:
8
+
9
+ ```
10
+ npm install @automattic/jetpack-ai-client
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ### Example
16
+
17
+ ```
18
+ import { requestCompletion } from '@automattic/jetpack-ai-client';
19
+
20
+ const MyComp = ( props ) => {
21
+ const [ completion, setCompletion ] = useState( '' );
22
+
23
+ const newHaiku = async () => {
24
+ const eventSource = await requestCompletion( 'Write a haiku about WordPress' );
25
+ eventSource.addEventListener( 'suggestion', answer => setCompletion( answer.detail ) );
26
+ eventSource.addEventListener( 'done', event => {
27
+ console.log( "Full completion", event.detail );
28
+ } );
29
+
30
+ eventSource.addEventListener( 'suggestion', event => {
31
+ console.log( "Received so far", event.detail );
32
+ } );
33
+
34
+ eventSource.addEventListener( 'error_quota_exceeded', event => {
35
+ console.log( "You reached the AI query quota for your current plan.", event.detail );
36
+ } );
37
+ };
38
+
39
+ return (
40
+ <div>
41
+ <div> { completion } </div>
42
+ <button onClick={ newHaiku }>Get new Haiku</button>
43
+ </div>
44
+ )
45
+ };
46
+ ```
47
+
48
+ ### Requesting a Completion from the Jetpack AI API
49
+
50
+ You can request a completion from the Jetpack AI API using the `requestCompletion` function. This function takes a prompt and optionally a post ID as parameters and returns an instance of `SuggestionsEventSource`.
51
+
52
+ ```
53
+ import { requestCompletion } from '@automattic/jetpack-ai-client';
54
+
55
+ // postId is the post where the request is being triggered
56
+ // It's only used for loggin purposes and can be omitted.
57
+ const postId = 123;
58
+ const eventSource = requestCompletion( 'A haiku', postId ))
59
+
60
+ eventSource.addEventListener('done', event => {
61
+ console.log( "Full completion", event.detail );
62
+ } );
63
+
64
+ eventSource.addEventListener('suggestion', event => {
65
+ console.log( "Received so far", event.detail );
66
+ } );
67
+ ```
68
+
69
+ ### Requesting Images from the Jetpack AI API
70
+
71
+ You can fetch images from Jetpack AI using the `requestImages` function. This function takes a prompt and a post ID as parameters and returns a promise that resolves to an array of base64 encoded images.
72
+
73
+ ```
74
+ import { requestImages } from '@automattic/jetpack-ai-client';
75
+
76
+ requestImages( 'a flower', postId )
77
+ .then( images => {
78
+ document.getElementById("imgid").src= image[0]
79
+ } )
80
+ .catch( error => {
81
+ // Handle the error
82
+ } );
83
+ ```
84
+
85
+ ### Using the SuggestionsEventSource Class
86
+
87
+ The `SuggestionsEventSource` class is a wrapper around `EventSource` that emits events for each chunk of data received, when the stream is closed, and when a full suggestion has been received.
88
+
89
+ You shouldn't need to instantiate this class. You get one of these by calling `requestCompletion()`.
90
+
91
+ ```
92
+ import { requestCompletion } from '@automattic/jetpack-ai-client';
93
+
94
+ const eventSource = new SuggestionsEventSource( url );
95
+
96
+ eventSource.addEventListener( 'done', event => {
97
+ console.log( "Full completion", event.detail );
98
+ } );
99
+
100
+ eventSource.addEventListener( 'suggestion', event => {
101
+ console.log( "Received so far", event.detail );
102
+ } );
103
+ ```
104
+
105
+ ### Requesting a Token from the Jetpack Site
106
+
107
+ You can request a token from the Jetpack site using the `requestCompletionAuthToken` function. This function returns a promise that resolves to an object containing the token and the blogId.
108
+
109
+ This function behaves properly whether it's called from a Jetpack environment or a WordPress.com one.
110
+
111
+ ```
112
+ import { requestCompletionAuthToken } from '@automattic/jetpack-ai-client';
113
+
114
+ requestCompletionAuthToken()
115
+ .then(tokenData => {
116
+ // Do something with the token data
117
+ })
118
+ .catch(error => {
119
+ // Handle the error
120
+ });
121
+ ```
122
+
123
+ ## Contribute
124
+
125
+ We welcome contributions from the community. Please submit your pull requests on the GitHub repository.
126
+
127
+ ## Get Help
128
+
129
+ If you encounter any issues or have any questions, please open an issue on the GitHub repository.
130
+
131
+ ## Using this package in your WordPress plugin
132
+
133
+ If you plan on using this package in your WordPress plugin, we would recommend that you use [Jetpack Autoloader](https://packagist.org/packages/automattic/jetpack-autoloader) as your autoloader. This will allow for maximum interoperability with other plugins that use this package as well.
134
+
135
+ ## Security
136
+
137
+ Need to report a security vulnerability? Go to [https://automattic.com/security/](https://automattic.com/security/) or directly to our security bug bounty site [https://hackerone.com/automattic](https://hackerone.com/automattic).
138
+
139
+ ## License
140
+
141
+ Jetpack AI Client is licensed under the GNU General Public License v2 (or later).
package/SECURITY.md ADDED
@@ -0,0 +1,38 @@
1
+ # Security Policy
2
+
3
+ Full details of the Automattic Security Policy can be found on [automattic.com](https://automattic.com/security/).
4
+
5
+ ## Supported Versions
6
+
7
+ Generally, only the latest version of Jetpack has continued support. If a critical vulnerability is found in the current version of Jetpack, we may opt to backport any patches to previous versions.
8
+
9
+ ## Reporting a Vulnerability
10
+
11
+ [Jetpack](https://jetpack.com/) is an open-source plugin for WordPress. Our HackerOne program covers the plugin software, as well as a variety of related projects and infrastructure.
12
+
13
+ **For responsible disclosure of security issues and to be eligible for our bug bounty program, please submit your report via the [HackerOne](https://hackerone.com/automattic) portal.**
14
+
15
+ Our most critical targets are:
16
+
17
+ * Jetpack and the Jetpack composer packages (all within this repo)
18
+ * Jetpack.com -- the primary marketing site.
19
+ * cloud.jetpack.com -- a management site.
20
+ * wordpress.com -- the shared management site for both Jetpack and WordPress.com sites.
21
+
22
+ For more targets, see the `In Scope` section on [HackerOne](https://hackerone.com/automattic).
23
+
24
+ _Please note that the **WordPress software is a separate entity** from Automattic. Please report vulnerabilities for WordPress through [the WordPress Foundation's HackerOne page](https://hackerone.com/wordpress)._
25
+
26
+ ## Guidelines
27
+
28
+ We're committed to working with security researchers to resolve the vulnerabilities they discover. You can help us by following these guidelines:
29
+
30
+ * Follow [HackerOne's disclosure guidelines](https://www.hackerone.com/disclosure-guidelines).
31
+ * Pen-testing Production:
32
+ * Please **setup a local environment** instead whenever possible. Most of our code is open source (see above).
33
+ * If that's not possible, **limit any data access/modification** to the bare minimum necessary to reproduce a PoC.
34
+ * **_Don't_ automate form submissions!** That's very annoying for us, because it adds extra work for the volunteers who manage those systems, and reduces the signal/noise ratio in our communication channels.
35
+ * To be eligible for a bounty, all of these guidelines must be followed.
36
+ * Be Patient - Give us a reasonable time to correct the issue before you disclose the vulnerability.
37
+
38
+ We also expect you to comply with all applicable laws. You're responsible to pay any taxes associated with your bounties.
package/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export { default as requestJwt } from './src/jwt';
2
+ export { default as SuggestionsEventSource } from './src/suggestions-event-source';
3
+ export { default as askQuestion } from './src/ask-question';
4
+ export * from './src/index.js';
@@ -0,0 +1,5 @@
1
+ const baseConfig = require( 'jetpack-js-tools/jest/config.base.js' );
2
+
3
+ module.exports = {
4
+ ...baseConfig,
5
+ };
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "private": false,
3
+ "name": "@automattic/jetpack-ai-client",
4
+ "version": "0.1.0",
5
+ "description": "A JS client for consuming Jetpack AI services",
6
+ "homepage": "https://github.com/Automattic/jetpack/tree/HEAD/projects/js-packages/ai-client/#readme",
7
+ "bugs": {
8
+ "url": "https://github.com/Automattic/jetpack/labels/[JS Package] Ai Client"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://github.com/Automattic/jetpack.git",
13
+ "directory": "projects/js-packages/ai-client"
14
+ },
15
+ "license": "GPL-2.0-or-later",
16
+ "author": "Automattic",
17
+ "scripts": {
18
+ "build": "pnpm run compile-ts",
19
+ "compile-ts": "tsc --pretty",
20
+ "test": "NODE_OPTIONS=--experimental-vm-modules jest"
21
+ },
22
+ "type": "module",
23
+ "devDependencies": {
24
+ "jest": "*",
25
+ "jest-environment-jsdom": "29.5.0",
26
+ "typescript": "5.0.4"
27
+ },
28
+ "exports": {
29
+ ".": "./index.ts"
30
+ },
31
+ "dependencies": {
32
+ "@automattic/jetpack-connection": "workspace:*",
33
+ "@automattic/jetpack-shared-extension-utils": "^0.10.9",
34
+ "@microsoft/fetch-event-source": "2.0.1",
35
+ "@wordpress/api-fetch": "6.34.0",
36
+ "debug": "4.3.4"
37
+ }
38
+ }
@@ -0,0 +1,42 @@
1
+ # askQuestion
2
+
3
+ `askQuestion` is an asynchronous function that takes a question and optional configurations, sends a request to obtain a JWT token, and returns an instance of `SuggestionsEventSource`.
4
+
5
+ ## Syntax
6
+
7
+ ```typescript
8
+ function askQuestion(
9
+ question: string | PromptItemProps[],
10
+ { postId = null, fromCache = false, feature }: AskQuestionOptionsArgProps = {}
11
+ ): Promise< SuggestionsEventSource >
12
+ ```
13
+
14
+ ## Parameters
15
+
16
+ - `question` (**string** | **PromptItemProps[]**):
17
+ - The question to ask.
18
+ - Can be a simple string or an array of `PromptItemProps` objects.
19
+
20
+ - `options` (**AskQuestionOptionsArgProps**):
21
+ - An optional object for additional configuration.
22
+ - **postId** (**number**, optional): ID of the post where the question is asked.
23
+ - **fromCache** (**boolean**, optional): If set to true, the answer will be fetched from the cache. Default value is false.
24
+ - **feature** (**string**, optional): Allows to use a specific AI assistant feature.
25
+
26
+ ## Returns
27
+
28
+ - A `Promise` that resolves to an instance of the `SuggestionsEventSource` class, containing the token, question, and options.
29
+
30
+ ## Example
31
+
32
+ ```typescript
33
+ const question = "What is the meaning of life?";
34
+ const options = {
35
+ postId: 1,
36
+ fromCache: true,
37
+ feature: 'ai-assistant-experimental'
38
+ }
39
+ askQuestion( question, options ).then( suggestionsEventSource => {
40
+ // handle suggestionsEventSource
41
+ } );
42
+ ```
@@ -0,0 +1,58 @@
1
+ /**
2
+ * External dependencies
3
+ */
4
+ import debugFactory from 'debug';
5
+ import requestJwt from '../jwt';
6
+ import SuggestionsEventSource from '../suggestions-event-source';
7
+ /*
8
+ * Types & constants
9
+ */
10
+ import type { PromptItemProps } from '../types';
11
+
12
+ type AskQuestionOptionsArgProps = {
13
+ /*
14
+ * ID of the post where the question is asked.
15
+ */
16
+ postId?: number;
17
+
18
+ /*
19
+ * If set to true, the answer will be fetched from the cache. Default value is false.
20
+ */
21
+ fromCache?: boolean;
22
+
23
+ /*
24
+ * Allows to use a specific AI assistant feature. Default value is undefined.
25
+ */
26
+ feature?: 'ai-assistant-experimental' | string | undefined;
27
+ };
28
+
29
+ const debug = debugFactory( 'jetpack-ai-client:ask-question' );
30
+
31
+ /**
32
+ * An asynchronous function that asks a question
33
+ * and returns an event source with suggestions.
34
+ *
35
+ * @param {string|PromptItemProps[]} question - The question to ask. It can be a simple string or an array of PromptItemProps objects.
36
+ * @param {AskQuestionOptionsArgProps} options - An optional object for additional configuration:
37
+ * @returns {Promise<SuggestionsEventSource>} A promise that resolves to an instance of the SuggestionsEventSource
38
+ * @example
39
+ * const question = "What is the meaning of life?";
40
+ * const options = {
41
+ * postId: 1,
42
+ * fromCache: true,
43
+ * feature: 'ai-assistant-experimental'
44
+ * }
45
+ * askQuestion( question, options ).then( suggestionsEventSource => {
46
+ * // handle suggestionsEventSource
47
+ * } );
48
+ */
49
+ export default async function askQuestion(
50
+ question: string | PromptItemProps[],
51
+ { postId = null, fromCache = false, feature }: AskQuestionOptionsArgProps = {}
52
+ ): Promise< SuggestionsEventSource > {
53
+ debug( 'Asking question: %o. options: %o', question, { postId, fromCache, feature } );
54
+
55
+ const { token } = await requestJwt();
56
+
57
+ return new SuggestionsEventSource( { question, token, options: { postId, feature, fromCache } } );
58
+ }
@@ -0,0 +1,9 @@
1
+ export declare global {
2
+ interface Window {
3
+ JP_CONNECTION_INITIAL_STATE: {
4
+ apiNonce: string;
5
+ siteSuffix: string;
6
+ siteId: string;
7
+ };
8
+ }
9
+ }
package/src/index.js ADDED
@@ -0,0 +1,26 @@
1
+ import apiFetch from '@wordpress/api-fetch';
2
+
3
+ /**
4
+ * Fetches images from Jetpack AI
5
+ *
6
+ * It's up to the consumer to catch errors
7
+ *
8
+ * @param {*} prompt - The prompt to send to Jetpack AI
9
+ * @param {*} postId - The post ID where the completion is being requested
10
+ * @returns {Promise<Array<string>>} The images
11
+ */
12
+ export function requestImages( prompt, postId ) {
13
+ return apiFetch( {
14
+ path: '/wpcom/v2/jetpack-ai/images/generations',
15
+ method: 'POST',
16
+ data: {
17
+ prompt,
18
+ post_id: postId,
19
+ },
20
+ } ).then( res => {
21
+ const images = res.data.map( image => {
22
+ return 'data:image/png;base64,' + image.b64_json;
23
+ } );
24
+ return images;
25
+ } );
26
+ }
@@ -0,0 +1,36 @@
1
+ # Jetpack AI JWT Library
2
+
3
+ This JavaScript library provides a convenient way to acquire and handle JWT tokens for Jetpack AI. It is designed to work with both Jetpack sites and Simple or Atomic sites, while managing token expiration and storage for you.
4
+
5
+ ## Features
6
+
7
+ - Acquires JWT tokens from either Jetpack or WP.com sites.
8
+ - Caches tokens in the browser's `localStorage`.
9
+ - Automatically handles token expiration by setting a default expiration time.
10
+ - Allows customization of request options such as `apiNonce`, `siteId` and `expirationTime`.
11
+
12
+ ## Installation
13
+
14
+ To install this library, run the following command in your project root:
15
+
16
+ ```bash
17
+ npm install --save @automattic/jetpack-ai-client
18
+ ```
19
+
20
+ ## Usage
21
+
22
+ ```javascript
23
+ import { requestJwt } from '@automattic/jetpack-ai-client';
24
+
25
+ const tokenData = await requestJwt();
26
+ ```
27
+
28
+ `requestJwt` is an asynchronous function that returns a Promise. The Promise resolves with an object containing the token, blogId, and expire time.
29
+
30
+ ```javascript
31
+ {
32
+ token: 'YOUR_JWT_TOKEN',
33
+ blogId: 'YOUR_BLOG_ID',
34
+ expire: 1652492550000, // Token expiration time in milliseconds since the Unix Epoch
35
+ }
36
+ ```
@@ -0,0 +1,109 @@
1
+ /**
2
+ * External dependencies
3
+ */
4
+ import { isSimpleSite } from '@automattic/jetpack-shared-extension-utils';
5
+ import apiFetch from '@wordpress/api-fetch';
6
+ import debugFactory from 'debug';
7
+ /*
8
+ * Types & constants
9
+ */
10
+ type RequestTokenOptions = {
11
+ apiNonce?: string;
12
+ siteId?: string;
13
+ isJetpackSite?: boolean;
14
+ expirationTime?: number;
15
+ };
16
+
17
+ type TokenDataProps = {
18
+ token: string;
19
+ blogId: string;
20
+ expire: number;
21
+ };
22
+
23
+ type TokenDataEndpointResponseProps = {
24
+ token: string;
25
+ blog_id: string;
26
+ };
27
+
28
+ const debug = debugFactory( 'jetpack-ai-client:jwt' );
29
+
30
+ const JWT_TOKEN_ID = 'jetpack-ai-jwt';
31
+ const JWT_TOKEN_EXPIRATION_TIME = 2 * 60 * 1000; // 2 minutes
32
+
33
+ /**
34
+ * Request a token from the Jetpack site.
35
+ *
36
+ * @param {RequestTokenOptions} options - Options
37
+ * @returns {Promise<TokenDataProps>} The token and the blogId
38
+ */
39
+ export default async function requestJwt( {
40
+ apiNonce,
41
+ siteId,
42
+ expirationTime,
43
+ }: RequestTokenOptions = {} ): Promise< TokenDataProps > {
44
+ // Default values
45
+ apiNonce = apiNonce || window.JP_CONNECTION_INITIAL_STATE.apiNonce;
46
+ siteId = siteId || window.JP_CONNECTION_INITIAL_STATE.siteSuffix;
47
+ expirationTime = expirationTime || JWT_TOKEN_EXPIRATION_TIME;
48
+
49
+ const isSimple = isSimpleSite();
50
+
51
+ // Trying to pick the token from localStorage
52
+ const token = localStorage.getItem( JWT_TOKEN_ID );
53
+ let tokenData: TokenDataProps | null = null;
54
+
55
+ if ( token ) {
56
+ try {
57
+ tokenData = JSON.parse( token );
58
+ } catch ( err ) {
59
+ debug( 'Error parsing token', err );
60
+ }
61
+ }
62
+
63
+ if ( tokenData && tokenData?.expire > Date.now() ) {
64
+ debug( 'Using cached token' );
65
+ return tokenData;
66
+ }
67
+
68
+ let data: TokenDataEndpointResponseProps;
69
+
70
+ if ( ! isSimple ) {
71
+ data = await apiFetch( {
72
+ /*
73
+ * This endpoint is registered in the Jetpack plugin.
74
+ * Provably we should move it to another package, but for now it's here.
75
+ * issue: https://github.com/Automattic/jetpack/issues/31938
76
+ */
77
+ path: '/jetpack/v4/jetpack-ai-jwt?_cacheBuster=' + Date.now(),
78
+ credentials: 'same-origin',
79
+ headers: {
80
+ 'X-WP-Nonce': apiNonce,
81
+ },
82
+ method: 'POST',
83
+ } );
84
+ } else {
85
+ data = await apiFetch( {
86
+ path: '/wpcom/v2/sites/' + siteId + '/jetpack-openai-query/jwt',
87
+ method: 'POST',
88
+ } );
89
+ }
90
+
91
+ const newTokenData = {
92
+ token: data.token,
93
+ /**
94
+ * TODO: make sure we return id from the .com token acquisition endpoint too
95
+ */
96
+ blogId: ! isSimple ? data.blog_id : siteId,
97
+
98
+ /**
99
+ * Let's expire the token in 2 minutes
100
+ */
101
+ expire: Date.now() + expirationTime,
102
+ };
103
+
104
+ // Store the token in localStorage
105
+ debug( 'Storing new token' );
106
+ localStorage.setItem( JWT_TOKEN_ID, JSON.stringify( newTokenData ) );
107
+
108
+ return newTokenData;
109
+ }
@@ -0,0 +1,78 @@
1
+ # SuggestionsEventSource
2
+
3
+ The `SuggestionsEventSource` is a class that wraps around `EventTarget`. It's specifically designed to handle a stream of suggestions retrieved from an AI model. When instantiated, it initializes a connection to an EventSource and listens for incoming data chunks. These chunks are concatenated into a full message which is processed and emitted through events.
4
+
5
+ ### Dependencies
6
+
7
+ - `EventSourceMessage, fetchEventSource` from `@microsoft/fetch-event-source`
8
+ - `debugFactory` from `debug`
9
+
10
+ ### Events
11
+
12
+ - `'suggestion'`: Emitted when the full suggestion has been received so far
13
+ - `'message'`: Emitted when a message has been received
14
+ - `'chunk'`: Emitted for each chunk of data received
15
+ - `'done'`: Emitted when the stream has been closed and no more data will be received
16
+
17
+ #### Error events
18
+ - `'error'`: Emitted when an error has occurred
19
+ - `'error_network'`: Emitted when the EventSource connection to the server returned some error
20
+ - `'error_service_unavailable'`: Emitted when the server returned a 503 error
21
+ - `'error_quota_exceeded'`: Emitted when the server returned a 429 error
22
+ - `'error_moderation'`: Emitted when the server returned a 422 error
23
+ - `'error_unclear_prompt'`: Emitted when the server returned a message starting with JETPACK_AI_ERROR
24
+
25
+ ### Class Properties
26
+
27
+ - `fullMessage`: String that accumulates the incoming chunks of data into a complete message
28
+ - `isPromptClear`: Boolean that represents whether the prompt is clear or not
29
+ - `controller`: AbortController instance used to close the fetchEventSource connection
30
+
31
+ ### Constructor
32
+
33
+ The constructor takes an object with the following properties:
34
+
35
+ - `url` (optional): URL of the EventSource. If not provided, the default will be used.
36
+ - `question`: The prompt/question to the AI model. It can be a string or an array of `PromptItemProps` objects.
37
+ - `token`: The token to authenticate the request.
38
+ - `options` (optional): An object that may include the following properties:
39
+ - `postId` (optional): The post ID.
40
+ - `feature` (optional): A string that specifies the AI model to use (default or 'ai-assistant-experimental').
41
+ - `fromCache` (optional): A boolean to indicate whether to fetch the response from cache.
42
+
43
+ ### Usage
44
+
45
+ To use this class, you would instantiate it with the necessary data, and then you can listen to its events to get and handle the suggestions.
46
+
47
+ Here is a basic usage example:
48
+
49
+ ```es6
50
+ const eventSource = new SuggestionsEventSource( {
51
+ question: "Who won the world cup in 2022?",
52
+ token: "your_token_here",
53
+ } );
54
+
55
+ eventSource.addEventListener( 'suggestion', event => {
56
+ console.log( event.detail ); // Logs the suggestion
57
+ } );
58
+ ```
59
+
60
+ It's possible to simulate a "conversation" when requesting a suggestion by providing an array of `PromptItemProps`. Each `PromptItemProps` is an object with a `role` (either 'system', 'user', or 'assistant') and `content`:
61
+
62
+ ```es6
63
+ const eventSource = new SuggestionsEventSource( {
64
+ question: [
65
+ { role: 'system', content: 'You are a helpful assistant.' },
66
+ { role: 'user', content: 'Who won the world cup in 2022?' },
67
+ ],
68
+ token: "your_token_here",
69
+ } );
70
+
71
+ eventSource.addEventListener( 'suggestion', event => {
72
+ console.log( event.detail ); // Logs the suggestion
73
+ } );
74
+ ```
75
+
76
+ In this example, we've passed an array of prompts to the `question` parameter. The 'system' role typically represents the context or environment in which the 'user' and 'assistant' are interacting.
77
+ The 'user' and 'assistant' roles denote the roles of user and assistant in a conversation, respectively.
78
+ The prompts are processed in the order they appear in the array, simulating a conversation that culminates with the final question: "Who won the world cup in 2022?".
@@ -0,0 +1,219 @@
1
+ /**
2
+ * External dependencies
3
+ */
4
+ import { EventSourceMessage, fetchEventSource } from '@microsoft/fetch-event-source';
5
+ import debugFactory from 'debug';
6
+ /*
7
+ * Types & constants
8
+ */
9
+ import type { PromptItemProps } from '../types';
10
+
11
+ type SuggestionsEventSourceConstructorArgs = {
12
+ url?: string;
13
+ question: string | PromptItemProps[];
14
+ token: string;
15
+ options?: {
16
+ postId?: number;
17
+ feature?: 'ai-assistant-experimental' | string | undefined;
18
+ fromCache?: boolean;
19
+ };
20
+ };
21
+
22
+ const debug = debugFactory( 'jetpack-ai-client:suggestions-event-source' );
23
+
24
+ /**
25
+ * SuggestionsEventSource is a wrapper around EvenTarget that emits
26
+ * a 'chunk' event for each chunk of data received, and a 'done' event
27
+ * when the stream is closed.
28
+ * It also emits a 'suggestion' event with the full suggestion received so far
29
+ *
30
+ * @returns {EventSource} The event source
31
+ * @fires suggestion - The full suggestion has been received so far
32
+ * @fires message - A message has been received
33
+ * @fires chunk - A chunk of data has been received
34
+ * @fires done - The stream has been closed. No more data will be received
35
+ * @fires error - An error has occurred
36
+ * @fires error_network - The EventSource connection to the server returned some error
37
+ * @fires error_service_unavailable - The server returned a 503 error
38
+ * @fires error_quota_exceeded - The server returned a 429 error
39
+ * @fires error_moderation - The server returned a 422 error
40
+ * @fires error_unclear_prompt - The server returned a message starting with JETPACK_AI_ERROR
41
+ */
42
+ export default class SuggestionsEventSource extends EventTarget {
43
+ fullMessage: string;
44
+ isPromptClear: boolean;
45
+ controller: AbortController;
46
+
47
+ constructor( data: SuggestionsEventSourceConstructorArgs ) {
48
+ super();
49
+ this.fullMessage = '';
50
+ this.isPromptClear = false;
51
+
52
+ // The AbortController is used to close the fetchEventSource connection
53
+ this.controller = new AbortController();
54
+
55
+ this.initEventSource( data );
56
+ }
57
+
58
+ async initEventSource( {
59
+ url,
60
+ question,
61
+ token,
62
+ options = {},
63
+ }: SuggestionsEventSourceConstructorArgs ) {
64
+ const bodyData = { post_id: options?.postId, messages: [], question: '', feature: '' };
65
+
66
+ // If the url is not provided, we use the default one
67
+ if ( ! url ) {
68
+ const urlHandler = new URL( 'https://public-api.wordpress.com/wpcom/v2/jetpack-ai-query' );
69
+
70
+ // Support response from cache option
71
+ if ( options?.fromCache ) {
72
+ urlHandler.searchParams.append( 'stream_cache', 'true' );
73
+ }
74
+
75
+ url = urlHandler.toString();
76
+ debug( 'URL not provided, using default: %o', url );
77
+ }
78
+
79
+ // question can be a string or an array of PromptItemProps
80
+ if ( Array.isArray( question ) ) {
81
+ bodyData.messages = question;
82
+ } else {
83
+ bodyData.question = question;
84
+ }
85
+
86
+ // Propagate the feature option
87
+ if ( options?.feature?.length ) {
88
+ debug( 'Feature: %o', options.feature );
89
+ bodyData.feature = options.feature;
90
+ }
91
+
92
+ await fetchEventSource( url, {
93
+ openWhenHidden: true,
94
+ method: 'POST',
95
+ headers: {
96
+ 'Content-type': 'application/json',
97
+ Authorization: 'Bearer ' + token,
98
+ },
99
+ body: JSON.stringify( bodyData ),
100
+
101
+ onclose: () => {
102
+ debug( 'Stream closed' );
103
+ },
104
+
105
+ onerror: err => {
106
+ this.processErrorEvent( err );
107
+ throw err; // rethrow to stop the operation otherwise it will retry forever
108
+ },
109
+
110
+ onmessage: ev => {
111
+ this.processEvent( ev );
112
+ },
113
+
114
+ onopen: async response => {
115
+ if ( response.ok ) {
116
+ return;
117
+ }
118
+ if (
119
+ response.status >= 400 &&
120
+ response.status <= 500 &&
121
+ ! [ 422, 429 ].includes( response.status )
122
+ ) {
123
+ this.processConnectionError( response );
124
+ }
125
+
126
+ /*
127
+ * error code 503
128
+ * service unavailable
129
+ */
130
+ if ( response.status === 503 ) {
131
+ this.dispatchEvent( new CustomEvent( 'error_service_unavailable' ) );
132
+ }
133
+
134
+ /*
135
+ * error code 429
136
+ * you exceeded your current quota please check your plan and billing details
137
+ */
138
+ if ( response.status === 429 ) {
139
+ this.dispatchEvent( new CustomEvent( 'error_quota_exceeded' ) );
140
+ }
141
+
142
+ /*
143
+ * error code 422
144
+ * request flagged by moderation system
145
+ */
146
+ if ( response.status === 422 ) {
147
+ this.dispatchEvent( new CustomEvent( 'error_moderation' ) );
148
+ }
149
+
150
+ throw new Error();
151
+ },
152
+
153
+ signal: this.controller.signal,
154
+ } );
155
+ }
156
+
157
+ checkForUnclearPrompt() {
158
+ if ( this.isPromptClear ) {
159
+ return;
160
+ }
161
+
162
+ /*
163
+ * Sometimes the first token of the message is not received,
164
+ * so we check only for JETPACK_AI_ERROR, ignoring:
165
+ * - the double underscores (italic markdown)
166
+ * - the double asterisks (bold markdown)
167
+ */
168
+ const replacedMessage = this.fullMessage.replace( /__|(\*\*)/g, '' );
169
+ if ( replacedMessage.startsWith( 'JETPACK_AI_ERROR' ) ) {
170
+ // The unclear prompt marker was found, so we dispatch an error event
171
+ this.dispatchEvent( new CustomEvent( 'error_unclear_prompt' ) );
172
+ } else if ( 'JETPACK_AI_ERROR'.startsWith( replacedMessage ) ) {
173
+ // Partial unclear prompt marker was found, so we wait for more data and print a debug message without dispatching an event
174
+ debug( this.fullMessage );
175
+ } else {
176
+ // Mark the prompt as clear
177
+ this.isPromptClear = true;
178
+ }
179
+ }
180
+
181
+ close() {
182
+ this.controller.abort();
183
+ }
184
+
185
+ processEvent( e: EventSourceMessage ) {
186
+ if ( e.data === '[DONE]' ) {
187
+ // Dispatch an event with the full content
188
+ this.dispatchEvent( new CustomEvent( 'done', { detail: this.fullMessage } ) );
189
+ debug( 'Done: %o', this.fullMessage );
190
+ return;
191
+ }
192
+
193
+ const data = JSON.parse( e.data );
194
+ const chunk = data.choices[ 0 ].delta.content;
195
+ if ( chunk ) {
196
+ this.fullMessage += chunk;
197
+ this.checkForUnclearPrompt();
198
+
199
+ if ( this.isPromptClear ) {
200
+ // Dispatch an event with the chunk
201
+ this.dispatchEvent( new CustomEvent( 'chunk', { detail: chunk } ) );
202
+ // Dispatch an event with the full message
203
+ this.dispatchEvent( new CustomEvent( 'suggestion', { detail: this.fullMessage } ) );
204
+ }
205
+ }
206
+ }
207
+
208
+ processConnectionError( response ) {
209
+ debug( 'Connection error: %o', response );
210
+ this.dispatchEvent( new CustomEvent( 'error_network', { detail: response } ) );
211
+ }
212
+
213
+ processErrorEvent( e ) {
214
+ debug( 'onerror: %o', e );
215
+
216
+ // Dispatch a generic network error event
217
+ this.dispatchEvent( new CustomEvent( 'error_network', { detail: e } ) );
218
+ }
219
+ }
package/src/types.ts ADDED
@@ -0,0 +1,4 @@
1
+ export type PromptItemProps = {
2
+ role: 'system' | 'user' | 'assistant';
3
+ content: string;
4
+ };
@@ -0,0 +1,13 @@
1
+ // We recommend using `jest` for testing. If you're testing React code, we recommend `@testing-library/react` and related packages.
2
+ // Please match the versions used elsewhere in the monorepo.
3
+ //
4
+ // Please don't add new uses of `mocha`, `chai`, `sinon`, `enzyme`, and so on. We're trying to standardize on one testing framework.
5
+ //
6
+ // The default setup is to have files named like "name.test.js" (or .jsx, .ts, or .tsx) in this `tests/` directory.
7
+ // But you could instead put them in `src/`, or put files like "name.js" (or .jsx, .ts, or .tsx) in `test` or `__tests__` directories somewhere.
8
+
9
+ describe( 'ai-client', () => {
10
+ it( 'should export something', () => {
11
+ expect( true ).toBe( true );
12
+ } );
13
+ } );