@datagrok/grokky 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/.eslintignore +2 -0
  2. package/.eslintrc.json +48 -0
  3. package/CHANGELOG.md +26 -0
  4. package/README.md +3 -0
  5. package/css/ai.css +200 -0
  6. package/detectors.js +9 -0
  7. package/dist/package-test.js +1738 -0
  8. package/dist/package-test.js.map +1 -0
  9. package/dist/package.js +92488 -0
  10. package/dist/package.js.map +1 -0
  11. package/dockerfiles/claude-runtime/.dockerignore +4 -0
  12. package/dockerfiles/claude-runtime/Dockerfile +27 -0
  13. package/dockerfiles/claude-runtime/container.json +5 -0
  14. package/dockerfiles/claude-runtime/package-lock.json +448 -0
  15. package/dockerfiles/claude-runtime/package.json +20 -0
  16. package/dockerfiles/claude-runtime/src/server.ts +273 -0
  17. package/dockerfiles/claude-runtime/src/types.ts +37 -0
  18. package/dockerfiles/claude-runtime/tsconfig.json +15 -0
  19. package/dockerfiles/mcp-server/Dockerfile +12 -0
  20. package/dockerfiles/mcp-server/container.json +1 -0
  21. package/dockerfiles/mcp-server/package-lock.json +1178 -0
  22. package/dockerfiles/mcp-server/package.json +15 -0
  23. package/dockerfiles/mcp-server/src/api-client.ts +100 -0
  24. package/dockerfiles/mcp-server/src/index.ts +155 -0
  25. package/dockerfiles/mcp-server/tsconfig.json +13 -0
  26. package/package.json +126 -0
  27. package/package.png +0 -0
  28. package/src/ai-panel.ts +174 -0
  29. package/src/claude-code/claude-panel.ts +34 -0
  30. package/src/claude-code/claude-runtime-client.ts +148 -0
  31. package/src/llm-utils/LLM-client.ts +251 -0
  32. package/src/llm-utils/combined-search.ts +162 -0
  33. package/src/llm-utils/creds.ts +30 -0
  34. package/src/llm-utils/db-index-tools.ts +642 -0
  35. package/src/llm-utils/deepwikiclient.ts +118 -0
  36. package/src/llm-utils/depr/AI-API-providers/openai-chat-completions-provider.ts +115 -0
  37. package/src/llm-utils/depr/AI-API-providers/openai-responses-provider.ts +108 -0
  38. package/src/llm-utils/depr/AI-API-providers/types.ts +106 -0
  39. package/src/llm-utils/depr/depr.ts +235 -0
  40. package/src/llm-utils/depr/embeddings.ts +58 -0
  41. package/src/llm-utils/depr/sql-utils.ts +377 -0
  42. package/src/llm-utils/indexes/biologics-index.ts +1098 -0
  43. package/src/llm-utils/indexes/chembl-index.ts +10074 -0
  44. package/src/llm-utils/indexes/dg-repository-index.ts +266 -0
  45. package/src/llm-utils/panel.ts +866 -0
  46. package/src/llm-utils/query-matching.ts +370 -0
  47. package/src/llm-utils/query-meta-utils.ts +106 -0
  48. package/src/llm-utils/script-tools.ts +784 -0
  49. package/src/llm-utils/sql-tools.ts +840 -0
  50. package/src/llm-utils/storage.ts +201 -0
  51. package/src/llm-utils/tableview-tools.ts +704 -0
  52. package/src/llm-utils/ui.ts +315 -0
  53. package/src/package-api.ts +83 -0
  54. package/src/package-test.ts +16 -0
  55. package/src/package.g.ts +122 -0
  56. package/src/package.ts +275 -0
  57. package/src/prompt-engine/chatgpt-assistant.ts +257 -0
  58. package/src/prompt-engine/interfaces.ts +170 -0
  59. package/src/prompt-engine/prompt-engine.ts +52 -0
  60. package/src/prompt-engine/rendering-tools.ts +103 -0
  61. package/src/prompts/is-help-request.ts +26 -0
  62. package/src/utils.ts +174 -0
  63. package/src/viewers-ai.ts +67 -0
  64. package/tsconfig.json +72 -0
  65. package/webpack.config.js +49 -0
@@ -0,0 +1,266 @@
1
+ /* eslint-disable max-len */
2
+ import * as grok from 'datagrok-api/grok';
3
+ import * as DG from 'datagrok-api/dg';
4
+ import * as ui from 'datagrok-api/ui';
5
+
6
+ import {LLMClient} from '../LLM-client';
7
+ import OpenAI from 'openai';
8
+
9
+ const VECTOR_STORE_NAME = 'datagrok-public-index';
10
+ const MAX_CONCURRENCY = 3;
11
+ const MAX_RETRIES = 5;
12
+ const BASE_RETRY_DELAY_MS = 1000;
13
+
14
+ function sleep(ms: number): Promise<void> {
15
+ return new Promise((resolve) => setTimeout(resolve, ms));
16
+ }
17
+
18
+ function isRetryableError(err: any): boolean {
19
+ const status = err?.status ?? err?.response?.status ?? err?.statusCode;
20
+ if (status === 429)
21
+ return true;
22
+ if (status >= 500 && status < 600)
23
+ return true;
24
+ const code = err?.code ?? err?.cause?.code;
25
+ return code === 'ETIMEDOUT' || code === 'ECONNRESET' || code === 'ENOTFOUND';
26
+ }
27
+
28
+ async function withRetry<T>(fn: () => Promise<T>, label: string): Promise<T> {
29
+ let attempt = 0;
30
+ while (true) {
31
+ try {
32
+ return await fn();
33
+ } catch (err) {
34
+ attempt++;
35
+ if (attempt >= MAX_RETRIES || !isRetryableError(err))
36
+ throw err;
37
+ const delay = BASE_RETRY_DELAY_MS * Math.pow(2, attempt - 1) + Math.floor(Math.random() * 250);
38
+ console.warn(`Retrying ${label} (attempt ${attempt}/${MAX_RETRIES}) after ${delay}ms`, err);
39
+ await sleep(delay);
40
+ }
41
+ }
42
+ }
43
+
44
+ async function getOrCreateVectorStoreId(client: OpenAI, name: string, pg: DG.TaskBarProgressIndicator): Promise<string> {
45
+ console.log(`Checking for existing vector store with name: ${name}`);
46
+ pg.update(0, `Checking for existing vector store`);
47
+ let page: OpenAI.VectorStores.VectorStoresPage | null = null;
48
+ while (true) {
49
+ if (!page)
50
+ page = await client.vectorStores.list();
51
+ else
52
+ page = await page.getNextPage();
53
+ const found = page.data?.find((vs) => vs.name === name);
54
+ if (found) {
55
+ console.log(`Found existing vector store with name: ${name}, id: ${found.id}`);
56
+ return found.id;
57
+ }
58
+ if (!page.has_more)
59
+ break;
60
+ }
61
+ console.log(`No existing vector store found with name: ${name}. Creating a new one.`);
62
+ const created = await client.vectorStores
63
+ .create({name, description: 'Datagrok public repository vector store with all indexable files (code + docs).'});
64
+ console.log(`Created new vector store with name: ${name}, id: ${created.id}`);
65
+ DG.Utils.download('vector-store-id.txt', created.id);
66
+ return created.id;
67
+ }
68
+
69
+ async function clearVectorStore(client: OpenAI, vectorStoreId: string, pg: DG.TaskBarProgressIndicator): Promise<void> {
70
+ let page: OpenAI.VectorStores.Files.VectorStoreFilesPage | undefined = undefined;
71
+ console.log(`Clearing vector store with id: ${vectorStoreId}`);
72
+ pg.update(0, `Clearing vector store`);
73
+ const processedSet = new Set<string>();
74
+ while (true) {
75
+ if (!page)
76
+ page = await client.vectorStores.files.list(vectorStoreId, {limit: 100});
77
+ else
78
+ page = await page.getNextPage();
79
+ const files = page.data ?? [];
80
+ const count = files.length;
81
+ let loopCount = 0;
82
+ const curProcessedSize = processedSet.size;
83
+ for (const f of files) {
84
+ if (processedSet.has(f.id))
85
+ continue;
86
+ processedSet.add(f.id);
87
+ pg.update(loopCount / count * 100, `Deleting file ${loopCount + 1} of ${count}`);
88
+ try {
89
+ await client.files.delete(f.id); // delete file and also remove it from any vector stores.
90
+ } catch (e) {
91
+ console.error(`Error deleting file : ${f.id}`, e);
92
+ }
93
+ loopCount++;
94
+ }
95
+ if (processedSet.size === curProcessedSize) {
96
+ console.log('No more files to delete.');
97
+ // openai API does some weird thing with caching.... and has more flag is not reliable
98
+ break;
99
+ }
100
+ if (!page.has_more)
101
+ break;
102
+ }
103
+ }
104
+
105
+ export async function listIndexableFiles(owner: string, repo: string): Promise<string[]> {
106
+ const repoInfo = await grok.dapi.fetchProxy(
107
+ `https://api.github.com/repos/${owner}/${repo}`
108
+ ).then((r) => r.json());
109
+ const sha = repoInfo.default_branch;
110
+
111
+ const tree = await grok.dapi.fetchProxy(
112
+ `https://api.github.com/repos/${owner}/${repo}/git/trees/${sha}?recursive=1`
113
+ ).then((r) => r.json());
114
+
115
+ const allowedExtensions = [
116
+ '.ts',
117
+ '.tsx',
118
+ '.md',
119
+ '.mdx',
120
+ '.js',
121
+ '.py',
122
+ '.sql',
123
+ '.r',
124
+ '.cpp',
125
+ '.h',
126
+ ];
127
+ const isAllowedExtension = (path: string) =>
128
+ allowedExtensions.some((ext) => path.endsWith(ext));
129
+ const nonAllowedDirs = [
130
+ '/node_modules/',
131
+ '/dist/',
132
+ '/build/',
133
+ '.git/',
134
+ '/.github/',
135
+ 'grok_connect',
136
+ 'docusaurus',
137
+ ];
138
+ const isInNonAllowedDir = (path: string) =>
139
+ nonAllowedDirs.some((dir) => path.includes(dir));
140
+ return tree.tree
141
+ .filter(
142
+ (item: any) =>
143
+ item.type === 'blob' &&
144
+ isAllowedExtension(item.path) &&
145
+ !isInNonAllowedDir(item.path)
146
+ )
147
+ .map((item: any) => item.path);
148
+ }
149
+
150
+ export async function uploadFilesToVectorStroreOneByOne() {
151
+ const pg = DG.TaskBarProgressIndicator.create(
152
+ 'Uploading files to vector store...'
153
+ );
154
+ const links = await listIndexableFiles('datagrok-ai', 'public').then(
155
+ (res) => {
156
+ // save to a file
157
+ /** */
158
+ const downloadLinks = res.map(
159
+ (p) =>
160
+ `https://raw.githubusercontent.com/datagrok-ai/public/master/${p}`
161
+ );
162
+ DG.Utils.download('indexed_files.txt', downloadLinks.join('\n'));
163
+ // console.log('indexed_files.txt', downloadLinks.join('\n'));
164
+ return downloadLinks;
165
+ }
166
+ );
167
+ // go one by one and upload
168
+ const client = LLMClient.getInstance().openai;
169
+
170
+ // check if the vector store with name 'datagrok-public-index' already exists, if not, create it
171
+ const vectorStoreId = await getOrCreateVectorStoreId(client, VECTOR_STORE_NAME, pg);
172
+ await clearVectorStore(client, vectorStoreId, pg);
173
+
174
+ // const file = await client.vectorStores.files.uploadAndPoll(
175
+ // process.env.VECTOR_STORE_ID,
176
+ // fs.createReadStream('C:/Users/rizhi/Desktop/GROK/public/help/learn/custom-machine-learning-models.md')
177
+ // );
178
+
179
+ const errors: any[] = [];
180
+ let count = 0;
181
+ const processedIds: string[] = [];
182
+ let nextIndex = 0;
183
+
184
+ const processLink = async (link: string) => {
185
+ const response = await withRetry(() => fetch(link), 'download');
186
+ if (!response || !response.ok) {
187
+ throw new Error(
188
+ `Failed to download file: ${response ? response.statusText : 'No response'}`
189
+ );
190
+ }
191
+
192
+ const buffer = await response.arrayBuffer();
193
+ const rawBase = 'https://raw.githubusercontent.com/datagrok-ai/public/master/';
194
+ const repoPath = link.substring(rawBase.length);
195
+ const normalizedPath = repoPath
196
+ .replace('.mdx', '.md')
197
+ .replace('.tsx', '.ts')
198
+ .replace('.sql', '.txt')
199
+ .replace('.r', '.txt')
200
+ .replace('.h', '.c')
201
+ .replace('.ts', '.js')// )))) apparently they made ts unsupported in vector store... so we upload as js
202
+ .replace('.cpp', '.c')
203
+ .replace('.c', '.txt');
204
+
205
+ const fileName = normalizedPath;
206
+ const originalExtension = repoPath.includes('.') ?
207
+ repoPath.split('.').pop()! :
208
+ 'txt';
209
+ const lastSlash = normalizedPath.lastIndexOf('/');
210
+ const dir = lastSlash >= 0 ? normalizedPath.slice(0, lastSlash) : '';
211
+
212
+ const file = new File([buffer], fileName);
213
+
214
+ const fileObj = await withRetry(() => client.files.create({
215
+ file,
216
+ purpose: 'assistants',
217
+ }), 'files.create');
218
+
219
+ const fileRes = await withRetry(() => client.vectorStores.files.create(vectorStoreId, {
220
+ file_id: fileObj.id, attributes: {
221
+ repoPath: repoPath,
222
+ originalExtension: originalExtension,
223
+ directory: dir,
224
+ firstParentFolder: dir.split('/')[0] ?? '', // good for JS-api specific searches
225
+ secondParentFolder: dir.split('/')[1] ?? '', // good for libraries / packages
226
+ originalFileName: repoPath.includes('/') ?
227
+ repoPath.slice(repoPath.lastIndexOf('/') + 1) :
228
+ repoPath,
229
+ }
230
+ }), 'vectorStores.files.create');
231
+ processedIds.push(fileRes.id);
232
+ };
233
+
234
+ const workers = Array.from({length: Math.min(MAX_CONCURRENCY, links.length)}, async () => {
235
+ while (true) {
236
+ const i = nextIndex++;
237
+ if (i >= links.length)
238
+ break;
239
+ const link = links[i];
240
+ try {
241
+ await processLink(link);
242
+ } catch (err) {
243
+ console.error('Error uploading file from link:', link, err);
244
+ errors.push({link, error: err ? err : 'unknown error'});
245
+ }
246
+ count++;
247
+ console.log(`progressed so far: ${count}/${links.length}`);
248
+ pg.update((count / links.length) * 100, `Uploaded ${count} of ${links.length} files`);
249
+ }
250
+ });
251
+
252
+ await Promise.all(workers);
253
+
254
+ pg.close();
255
+
256
+
257
+ console.log(`\n✓ Uploaded ${processedIds.length} of ${links.length} files`);
258
+
259
+ // save errors to a file
260
+ DG.Utils.download('upload_errors.json', JSON.stringify(errors, null, 2));
261
+ // save processed ids to a file
262
+ DG.Utils.download('processed_file_ids.txt', processedIds.join('\n'));
263
+ // download the vector store id
264
+ grok.shell.info(`File upload to vector store completed with ${errors.length} / ${processedIds.length} errors.`);
265
+ grok.shell.info('Make sure to update the vector store id in the CHATGPT plugin settings and refresh the page.');
266
+ }