@datagrok/grokky 1.0.4 → 1.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.
Files changed (203) hide show
  1. package/.claude/skills/deploy-grokky/SKILL.md +193 -0
  2. package/.grokignore +2 -0
  3. package/.turbo/turbo-build.log +24 -0
  4. package/.vscode/settings.json +16 -0
  5. package/CHANGELOG.md +151 -8
  6. package/CLAUDE.md +284 -0
  7. package/CREDITS.md +173 -0
  8. package/LICENSE.md +16 -0
  9. package/README.md +24 -0
  10. package/bdd/bdd.config.json +1 -0
  11. package/bdd/bindings/elements.ts +9 -0
  12. package/bdd/bindings/steps.ts +787 -0
  13. package/bdd/features/ai-panel/platform-work.feature +63 -0
  14. package/bdd/features/ai-panel/session.feature +69 -0
  15. package/bdd/features/ai-panel/table-work.feature +99 -0
  16. package/bdd/generated/ai-panel/platform-work.test.ts +103 -0
  17. package/bdd/generated/ai-panel/session.test.ts +100 -0
  18. package/bdd/generated/ai-panel/table-work.test.ts +150 -0
  19. package/bdd/package.json +1 -0
  20. package/bdd/tsconfig.json +13 -0
  21. package/css/ai.css +637 -49
  22. package/dist/package-test.js +4 -1707
  23. package/dist/package-test.js.map +1 -1
  24. package/dist/package.js +742 -92317
  25. package/dist/package.js.map +1 -1
  26. package/dockerfiles/claude-runtime/.dockerignore +1 -0
  27. package/{.eslintrc.json → dockerfiles/claude-runtime/.eslintrc.json} +7 -16
  28. package/dockerfiles/claude-runtime/Dockerfile +73 -13
  29. package/dockerfiles/claude-runtime/agent/grokky_agent/__init__.py +0 -0
  30. package/dockerfiles/claude-runtime/agent/grokky_agent/__main__.py +80 -0
  31. package/dockerfiles/claude-runtime/agent/grokky_agent/browser_tools.py +180 -0
  32. package/dockerfiles/claude-runtime/agent/grokky_agent/config.py +26 -0
  33. package/dockerfiles/claude-runtime/agent/grokky_agent/formats.py +155 -0
  34. package/dockerfiles/claude-runtime/agent/grokky_agent/guard.py +87 -0
  35. package/dockerfiles/claude-runtime/agent/grokky_agent/hermes.py +212 -0
  36. package/dockerfiles/claude-runtime/agent/grokky_agent/hermes.yaml +45 -0
  37. package/dockerfiles/claude-runtime/agent/grokky_agent/hermes_plugin/__init__.py +8 -0
  38. package/dockerfiles/claude-runtime/agent/grokky_agent/hermes_plugin/plugin.yaml +3 -0
  39. package/dockerfiles/claude-runtime/agent/grokky_agent/protocol.py +174 -0
  40. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/__init__.py +21 -0
  41. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/anthropic.py +21 -0
  42. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/azure.py +46 -0
  43. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/base.py +127 -0
  44. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/bedrock.py +46 -0
  45. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/custom.py +40 -0
  46. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/databricks.py +54 -0
  47. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/openai_platform.py +41 -0
  48. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/openrouter.py +46 -0
  49. package/dockerfiles/claude-runtime/agent/grokky_agent/session.py +471 -0
  50. package/dockerfiles/claude-runtime/agent/grokky_agent/skills.py +44 -0
  51. package/dockerfiles/claude-runtime/agent/grokky_agent/structured.py +40 -0
  52. package/dockerfiles/claude-runtime/container.json +2 -2
  53. package/dockerfiles/claude-runtime/entrypoint.sh +20 -0
  54. package/dockerfiles/claude-runtime/package-lock.json +1721 -306
  55. package/dockerfiles/claude-runtime/package.json +20 -5
  56. package/dockerfiles/claude-runtime/plugin/.claude-plugin/plugin.json +5 -0
  57. package/dockerfiles/claude-runtime/plugin/skills/datagrok-calc-column/SKILL.md +92 -0
  58. package/dockerfiles/claude-runtime/plugin/skills/datagrok-chem-data/SKILL.md +250 -0
  59. package/dockerfiles/claude-runtime/plugin/skills/datagrok-chem-toolkit/SKILL.md +395 -0
  60. package/dockerfiles/claude-runtime/plugin/skills/datagrok-df-and-columns/SKILL.md +454 -0
  61. package/dockerfiles/claude-runtime/plugin/skills/datagrok-entities/SKILL.md +38 -0
  62. package/dockerfiles/claude-runtime/plugin/skills/datagrok-exec/SKILL.md +209 -0
  63. package/dockerfiles/claude-runtime/plugin/skills/datagrok-filtering/SKILL.md +185 -0
  64. package/dockerfiles/claude-runtime/plugin/skills/datagrok-grid-customization/SKILL.md +270 -0
  65. package/dockerfiles/claude-runtime/plugin/skills/datagrok-projects/SKILL.md +100 -0
  66. package/dockerfiles/claude-runtime/plugin/skills/datagrok-selection/SKILL.md +344 -0
  67. package/dockerfiles/claude-runtime/plugin/skills/datagrok-undo/SKILL.md +78 -0
  68. package/dockerfiles/claude-runtime/plugin/skills/datagrok-viewers/SKILL.md +303 -0
  69. package/dockerfiles/claude-runtime/pyproject.toml +18 -0
  70. package/dockerfiles/claude-runtime/src/agent/pool.ts +411 -0
  71. package/dockerfiles/claude-runtime/src/agent/turn.ts +153 -0
  72. package/dockerfiles/claude-runtime/src/constants.ts +20 -0
  73. package/dockerfiles/claude-runtime/src/credentials.ts +45 -0
  74. package/dockerfiles/claude-runtime/src/grounding.ts +104 -0
  75. package/dockerfiles/claude-runtime/src/help-index.ts +118 -0
  76. package/dockerfiles/claude-runtime/src/privileges.ts +8 -0
  77. package/dockerfiles/claude-runtime/src/prompts.ts +211 -0
  78. package/dockerfiles/claude-runtime/src/server.ts +134 -234
  79. package/dockerfiles/claude-runtime/src/session.ts +328 -0
  80. package/dockerfiles/claude-runtime/src/shared-api-client.ts +112 -0
  81. package/dockerfiles/claude-runtime/src/stream-filter.ts +80 -0
  82. package/dockerfiles/claude-runtime/src/sync/home-files.ts +80 -0
  83. package/dockerfiles/claude-runtime/src/sync/orchestrator.ts +214 -0
  84. package/dockerfiles/claude-runtime/src/sync/packages.ts +145 -0
  85. package/dockerfiles/claude-runtime/src/sync/shared-connections.ts +87 -0
  86. package/dockerfiles/claude-runtime/src/sync/workspace.ts +68 -0
  87. package/dockerfiles/claude-runtime/src/tasks.ts +124 -0
  88. package/dockerfiles/claude-runtime/src/tool-summary.ts +66 -0
  89. package/dockerfiles/claude-runtime/src/types.ts +142 -23
  90. package/dockerfiles/claude-runtime/src/user/installed-packages.ts +17 -0
  91. package/dockerfiles/claude-runtime/src/user/staged-workspace.ts +80 -0
  92. package/dockerfiles/claude-runtime/src/user/user-dir.ts +108 -0
  93. package/dockerfiles/claude-runtime/src/verify.ts +136 -0
  94. package/dockerfiles/claude-runtime/src/watchdog.ts +115 -0
  95. package/dockerfiles/claude-runtime/test/credentials.test.js +43 -0
  96. package/dockerfiles/claude-runtime/test/grounding.test.js +191 -0
  97. package/dockerfiles/claude-runtime/test/help-index.test.js +115 -0
  98. package/dockerfiles/claude-runtime/test/plugin-skills.test.js +57 -0
  99. package/dockerfiles/claude-runtime/test/prompts.test.js +62 -0
  100. package/dockerfiles/claude-runtime/test/reaper.test.js +60 -0
  101. package/dockerfiles/claude-runtime/test/stream-filter.test.js +132 -0
  102. package/dockerfiles/claude-runtime/test/tasks.test.js +74 -0
  103. package/dockerfiles/claude-runtime/test/user-dir.test.js +71 -0
  104. package/dockerfiles/claude-runtime/test/verify.test.js +187 -0
  105. package/dockerfiles/claude-runtime/test/watchdog.test.js +43 -0
  106. package/dockerfiles/mcp-server/.eslintrc.json +39 -0
  107. package/dockerfiles/mcp-server/Dockerfile +10 -2
  108. package/dockerfiles/mcp-server/package-lock.json +1743 -98
  109. package/dockerfiles/mcp-server/package.json +27 -5
  110. package/dockerfiles/mcp-server/src/api-client.ts +123 -66
  111. package/dockerfiles/mcp-server/src/format.ts +51 -0
  112. package/dockerfiles/mcp-server/src/index.ts +44 -113
  113. package/dockerfiles/mcp-server/src/ops.ts +325 -0
  114. package/dockerfiles/mcp-server/src/shared-api-client.ts +81 -0
  115. package/dockerfiles/mcp-server/test/format.test.js +62 -0
  116. package/dockerfiles/mcp-server/test/ops.test.js +84 -0
  117. package/dockerfiles/mcp-server/test/shared-api-client.test.js +35 -0
  118. package/dockerfiles/queue/Dockerfile +2 -0
  119. package/dockerfiles/queue/container.json +7 -0
  120. package/docs/AUDIT-2026-08-03.md +1064 -0
  121. package/docs/BENCHMARK.md +292 -0
  122. package/docs/CLAUDE_CODE_FLOW.md +746 -0
  123. package/docs/EXAMPLES.md +82 -0
  124. package/docs/FEATURES.md +71 -0
  125. package/docs/IMPLEMENTATION.md +128 -0
  126. package/docs/LATENCY.md +170 -0
  127. package/docs/VISION.md +36 -0
  128. package/files/benchmark/suite.yaml +404 -0
  129. package/files/scripts/process-cro-results.md +14 -0
  130. package/files/suggestions.yaml +344 -0
  131. package/package.json +39 -97
  132. package/src/ai/ai-window.ts +157 -0
  133. package/src/ai/benchmark/benchmark.ts +737 -0
  134. package/src/ai/db-view-functions.ts +56 -0
  135. package/src/ai/engine.ts +98 -0
  136. package/src/ai/gemma-engine.ts +81 -0
  137. package/src/ai/panel.ts +1385 -0
  138. package/src/ai/prompt-suggestions.ts +209 -0
  139. package/src/ai/search/combined-search.ts +244 -0
  140. package/src/{llm-utils → ai/search}/query-matching.ts +46 -167
  141. package/src/{llm-utils → ai}/storage.ts +0 -1
  142. package/src/ai/table-tools.ts +145 -0
  143. package/src/ai/ui.ts +720 -0
  144. package/src/ai/usage-limiter.ts +105 -0
  145. package/src/ai/view-tools.ts +352 -0
  146. package/src/claude/ai-feature.ts +16 -0
  147. package/src/claude/exec-blocks.ts +176 -0
  148. package/src/claude/queue-task.ts +84 -0
  149. package/src/claude/runtime-client.ts +310 -0
  150. package/src/claude/turn-log.ts +114 -0
  151. package/src/claude/undoable.ts +105 -0
  152. package/src/{llm-utils → db}/db-index-tools.ts +24 -32
  153. package/src/db/sql-tools.ts +336 -0
  154. package/src/depr/LLM-client.ts +251 -0
  155. package/src/depr/ai-panel.ts +174 -0
  156. package/src/depr/chatgpt-assistant.ts +257 -0
  157. package/src/depr/creds.ts +30 -0
  158. package/src/depr/deepwikiclient.ts +118 -0
  159. package/src/depr/indexes/dg-repository-index.ts +266 -0
  160. package/src/depr/interfaces.ts +170 -0
  161. package/src/depr/is-help-request.ts +39 -0
  162. package/src/depr/prompt-engine.ts +52 -0
  163. package/src/depr/rendering-tools.ts +103 -0
  164. package/src/depr/script-tools.ts +785 -0
  165. package/src/depr/tableview-tools.ts +746 -0
  166. package/src/depr/viewers-ai.ts +67 -0
  167. package/src/package-api.ts +87 -28
  168. package/src/package-test.ts +1 -0
  169. package/src/package.g.ts +98 -48
  170. package/src/package.ts +211 -157
  171. package/src/polyfills.ts +12 -0
  172. package/src/utils.ts +128 -0
  173. package/tsconfig.json +8 -70
  174. package/webpack.config.js +3 -49
  175. package/.eslintignore +0 -2
  176. package/src/ai-panel.ts +0 -174
  177. package/src/claude-code/claude-panel.ts +0 -34
  178. package/src/claude-code/claude-runtime-client.ts +0 -148
  179. package/src/llm-utils/LLM-client.ts +0 -251
  180. package/src/llm-utils/combined-search.ts +0 -162
  181. package/src/llm-utils/creds.ts +0 -30
  182. package/src/llm-utils/deepwikiclient.ts +0 -118
  183. package/src/llm-utils/indexes/dg-repository-index.ts +0 -266
  184. package/src/llm-utils/panel.ts +0 -866
  185. package/src/llm-utils/script-tools.ts +0 -784
  186. package/src/llm-utils/sql-tools.ts +0 -840
  187. package/src/llm-utils/tableview-tools.ts +0 -704
  188. package/src/llm-utils/ui.ts +0 -315
  189. package/src/prompt-engine/chatgpt-assistant.ts +0 -257
  190. package/src/prompt-engine/interfaces.ts +0 -170
  191. package/src/prompt-engine/prompt-engine.ts +0 -52
  192. package/src/prompt-engine/rendering-tools.ts +0 -103
  193. package/src/prompts/is-help-request.ts +0 -26
  194. package/src/viewers-ai.ts +0 -67
  195. /package/src/{llm-utils → db}/indexes/biologics-index.ts +0 -0
  196. /package/src/{llm-utils → db}/indexes/chembl-index.ts +0 -0
  197. /package/src/{llm-utils → db}/query-meta-utils.ts +0 -0
  198. /package/src/{llm-utils/depr → depr}/AI-API-providers/openai-chat-completions-provider.ts +0 -0
  199. /package/src/{llm-utils/depr → depr}/AI-API-providers/openai-responses-provider.ts +0 -0
  200. /package/src/{llm-utils/depr → depr}/AI-API-providers/types.ts +0 -0
  201. /package/src/{llm-utils/depr → depr}/depr.ts +0 -0
  202. /package/src/{llm-utils/depr → depr}/embeddings.ts +0 -0
  203. /package/src/{llm-utils/depr → depr}/sql-utils.ts +0 -0
@@ -0,0 +1,257 @@
1
+ // /* eslint-disable max-len */
2
+ // import * as grok from 'datagrok-api/grok';
3
+ // import * as ui from 'datagrok-api/ui';
4
+ // import * as DG from 'datagrok-api/dg';
5
+ // import {PromptEngine} from './prompt-engine';
6
+ // import {ChatGptFuncParams, ExecutePlanResult, ExecutionContext, FunctionMeta, JsonSchema, PackageInfo, PackageSelection, PackageSelectionSchema, Plan, PlanSchema} from './interfaces';
7
+
8
+ // export class ChatGptAssistant {
9
+ // private delimiter = '####';
10
+
11
+ // constructor(private promptEngine: PromptEngine) {}
12
+
13
+ // private async chat<T>(
14
+ // prompt: string,
15
+ // options: { system?: string; schema: JsonSchema }
16
+ // ): Promise<T> {
17
+ // const systemPrompt = options.system ?? `
18
+ // You are an assistant that outputs only valid JSON.
19
+ // Do NOT include explanations or extra text.
20
+ // User input is delimited by ${this.delimiter}.
21
+ // Always respond strictly in JSON format.
22
+ // `;
23
+
24
+ // const raw = await this.promptEngine.generate(
25
+ // `${this.delimiter}${prompt}${this.delimiter}`,
26
+ // systemPrompt,
27
+ // options.schema
28
+ // );
29
+
30
+ // try {
31
+ // return JSON.parse(raw) as T;
32
+ // } catch (err) {
33
+ // throw new Error(`Failed to parse JSON from LLM output: ${raw}\nError: ${err}`);
34
+ // }
35
+ // }
36
+
37
+ // private getProperties(f: DG.Func): ChatGptFuncParams {
38
+ // const props: ChatGptFuncParams = {};
39
+ // for (const p of f.inputs) {
40
+ // props[p.name] = {
41
+ // type: p.propertyType,
42
+ // description: p.description ?? '',
43
+ // default: p.options['default'],
44
+ // optional: p.options['optional'],
45
+ // };
46
+ // }
47
+ // return props;
48
+ // }
49
+
50
+ // // TODO: Substitute with the list of available roles along with descriptions
51
+ // private packagesInfo: PackageInfo[] = [
52
+ // {
53
+ // name: 'Admetica',
54
+ // description: 'Assessment of ADMET Properties',
55
+ // },
56
+ // {
57
+ // name: 'Bio',
58
+ // description: 'Bioinformatics support (import/export of sequences, HELM and other format conversion, visualization, analysis). [See more](https://github.com/datagrok-ai/public/blob/master/packages/Bio/README.md) for details.',
59
+ // },
60
+ // {
61
+ // name: 'Chem',
62
+ // description:
63
+ // 'Cheminformatics support: import, rendering, sketching, calculation of properties, predictive models, augmentations, multiple analyses. Includes multiple different calculators(descriptors, properties, solubility(LogS through properties) and many more). Can be used in conjunction to peptides, conversion tools to optimize/maximize/minimize different properties.',
64
+ // },
65
+ // {
66
+ // name: 'Chembl',
67
+ // description: 'Chembl integration, commonly used queries and browser',
68
+ // },
69
+ // {
70
+ // name: 'ClinicalCase',
71
+ // description: 'Analysis of the clinical data represented in the [SDTM](https://www.cdisc.org/standards/foundational/sdtm) and [SEND](https://www.cdisc.org/standards/foundational/send) formats.',
72
+ // },
73
+ // {
74
+ // name: 'Retrosynthesis',
75
+ // description: 'Creates retrosynthesis paths for the selected molecule',
76
+ // },
77
+ // {
78
+ // name: 'Biologics',
79
+ // description: 'Database with ADC, protein sequences, peptides, drugs and their assay data. contains tools and queries into the database. compounds identifiers for peptides, sequences, drugs, ADCs etc. like GROKPEP-######, GROKADC-###### etc.',
80
+ // },
81
+ // {
82
+ // name: 'SequenceTranslator',
83
+ // description: 'Contains tools for enumerating sequences at different positions and monomers. very useful when trying to maximize/minimize/optimize certain properties of peptides/proteins by sequence enumeration.',
84
+ // },
85
+ // {
86
+ // name: 'MolTrack',
87
+ // description: 'A lightweight, flexible, and extendable FastAPI server for managing chemical compounds, batches, and properties, powered by RDKit-enabled Postgres for chemical intelligence'
88
+ // }
89
+ // ];
90
+
91
+ // private async selectPackages(userGoal: string): Promise<string[]> {
92
+ // const prompt = `User goal: "${userGoal}"
93
+ // Available packages:
94
+ // ${JSON.stringify(this.packagesInfo, null, 2)}
95
+
96
+ // Determine which packages are relevant for achieving this goal.
97
+ // Respond ONLY in JSON with the folllowing structure, no Markdown or extra text.
98
+ // {
99
+ // "selected_packages": [
100
+ // { "name": "<package_name>", "reason": "<why this helps>" }
101
+ // ]
102
+ // }
103
+
104
+ // Rules:
105
+ // - Include only packages that can meaningfully contribute.
106
+ // - Rank them from most to least relevant.
107
+ // - Do not include packages that clearly don't apply.`;
108
+
109
+ // const res = await this.chat<PackageSelection>(prompt, {schema: PackageSelectionSchema});
110
+ // console.log('Selected packages:', res);
111
+ // return res.selected_packages.map((p: any) => p.name);
112
+ // }
113
+
114
+ // private readonly reasoningSystemPrompt = `
115
+ // You are a reasoning assistant that plans how to achieve user goals using available functions.
116
+
117
+ // General output rules:
118
+ // - Output ONLY valid JSON.
119
+ // - Produce the smallest possible sequence of steps.
120
+ // - Each step should be:
121
+ // { "action": "call_function", "function": "<name>", "inputs": {...}, "outputs": [...] }
122
+
123
+ // STRICT INPUT RULES (applies to ALL models):
124
+ // - You MUST include EVERY REQUIRED input parameter defined for the function.
125
+ // - Optional inputs:
126
+ // - If a value is provided, include it in the "inputs" object.
127
+ // - If no value is provided, the field may be omitted.
128
+ // - Inputs with default values are treated as required:
129
+ // - You MUST include them in the "inputs", even if the value equals the default.
130
+ // - Leaving out a required input or a defaulted input is considered an ERROR.
131
+ // - Inputs should appear exactly as defined in the function metadata.
132
+ // - Today's date is ${new Date().toISOString().split('T')[0]}. Always use this date when interpreting natural language like "last week", "this year", or "next month".
133
+
134
+ // Referencing previous steps:
135
+ // - If an input value comes from a previous step's output, prefix it with "$".
136
+
137
+ // Planning rules:
138
+ // - Produce the minimal number of steps needed to achieve the user’s goal.
139
+ // - If one function can directly satisfy the goal, output only that step.
140
+ // - Do not use helper or lookup functions unless required by the goal.
141
+ // - Ensure all steps are valid according to the function metadata.
142
+ // - Include a short "analysis" explaining your reasoning.
143
+ // - When asked to optimize or maximize/minimize something, make sure that the calculation of the said property is also done.
144
+ // `;
145
+
146
+ // private async planFunctions(userGoal: string, functions: FunctionMeta[]): Promise<Plan> {
147
+ // const prompt = `
148
+ // User request: "${userGoal}"
149
+ // Available functions:
150
+ // ${JSON.stringify(functions, null, 2)}
151
+
152
+ // Analyze what needs to be done and produce the minimal sequence of steps.
153
+ // Respond strictly as JSON with this structure:
154
+ // {
155
+ // "goal": "<restated_goal>",
156
+ // "analysis": ["...reasoning..."],
157
+ // "steps": [ { "action": "call_function", "function": "...", "inputs": {...}, "outputs": [...] } ]
158
+ // }`;
159
+ // return await this.chat<Plan>(prompt, {
160
+ // system: this.reasoningSystemPrompt,
161
+ // schema: PlanSchema,
162
+ // });
163
+ // }
164
+
165
+ // private async getFunctionsByPackage(pkg: string): Promise<FunctionMeta[]> {
166
+ // const funcs = DG.Func.find({package: pkg});
167
+ // return funcs.map((f) => {
168
+ // return {
169
+ // name: f.name,
170
+ // description: (f.nqName || f.package.name) + ': ' + (f.description || f.options['description'] || f.friendlyName || f.name),
171
+ // inputs: {type: 'object', properties: this.getProperties(f)},
172
+ // outputs: f.outputs.map((o) => ({
173
+ // name: o.name,
174
+ // type: o.propertyType,
175
+ // }))
176
+ // };
177
+ // });
178
+ // }
179
+
180
+ // public async executePlan(plan: Plan): Promise<ExecutePlanResult | null> {
181
+ // if (!plan?.steps?.length) {
182
+ // console.warn('No steps to execute in plan.');
183
+ // return null;
184
+ // }
185
+
186
+ // const context: ExecutionContext = {};
187
+ // for (const [index, step] of plan.steps.entries()) {
188
+ // if (step.action !== 'call_function') continue;
189
+
190
+ // const func = DG.Func.find({name: step.function})[0];
191
+ // if (!func) {
192
+ // console.warn(`Function not found: ${step.function}`);
193
+ // continue;
194
+ // }
195
+
196
+ // const resolvedInputs: Record<string, any> = {};
197
+ // for (const [key, val] of Object.entries(step.inputs ?? {})) {
198
+ // if (typeof val === 'string' && val.startsWith('$')) {
199
+ // const varName = val.slice(1);
200
+ // resolvedInputs[key] = context[varName]['value'];
201
+ // } else
202
+ // resolvedInputs[key] = val;
203
+ // }
204
+
205
+ // let result;
206
+ // try {
207
+ // result = await func.apply(resolvedInputs);
208
+ // } catch (err) {
209
+ // console.error(`Error executing ${func.name}:`, err);
210
+ // result = null;
211
+ // }
212
+
213
+ // if (Array.isArray(step.outputs)) {
214
+ // const outputName = step.outputs[0] ?? func.name;
215
+ // const funcOutputMeta = func.outputs.length === 1 ? func.outputs[0] : func.outputs.find((o) => o.name === outputName);
216
+ // context[outputName] = {value: result, meta: funcOutputMeta};
217
+ // }
218
+ // }
219
+
220
+ // const finalKey = plan.steps.at(-1)?.outputs?.[0];
221
+ // const finalResult = finalKey ? context[finalKey] : null;
222
+ // if (!finalKey) {
223
+ // // some functions along the steps can be such that they just alter the dataFrame and do nothing, so search for the last dataFrame in the context
224
+ // for (let i = plan.steps.length - 2; i >= 0; i--) {
225
+ // const step = plan.steps[i];
226
+ // const outputMeta = step.outputs?.length ? context[step.outputs[0]]?.meta : null;
227
+ // if (outputMeta?.propertyType === 'dataframe')
228
+ // return {context, finalResult: context[step.outputs[0]]};
229
+ // else if (step.outputs?.length)
230
+ // break;
231
+ // }
232
+ // }
233
+
234
+ // return {context, finalResult};
235
+ // }
236
+
237
+ // public async plan(userGoal: string): Promise<Plan> {
238
+ // const packages = await this.selectPackages(userGoal);
239
+ // await setTimeout(() => {}, 25000);
240
+
241
+ // const allFunctions: FunctionMeta[] = [];
242
+ // for (const pkg of packages) {
243
+ // const funcs = await this.getFunctionsByPackage(pkg);
244
+ // allFunctions.push(...funcs);
245
+ // await setTimeout(() => {}, 25000);
246
+ // }
247
+
248
+ // const plan = await this.planFunctions(userGoal, allFunctions);
249
+ // await setTimeout(() => {}, 25000);
250
+
251
+ // return plan;
252
+ // }
253
+
254
+ // public async execute(plan: Plan): Promise<ExecutePlanResult | null> {
255
+ // return await this.executePlan(plan);
256
+ // }
257
+ // }
@@ -0,0 +1,30 @@
1
+ // import * as grok from 'datagrok-api/grok';
2
+ // import * as DG from 'datagrok-api/dg';
3
+
4
+ // const OPENAIVectorStoreName = 'vectorStoreId';
5
+
6
+ // export class LLMCredsManager {
7
+ // vectorStoreId: string;
8
+ // private constructor(vectorStoreId: string) {
9
+ // this.vectorStoreId = vectorStoreId;
10
+ // }
11
+
12
+ // private static _instance: LLMCredsManager | null = null;
13
+ // // Initialize the singleton instance
14
+ // // TODO: in future this will probably move to credentials manager
15
+ // static init(pckg: DG.Package): void {
16
+ // const hasAIKey = grok.ai.config.configured;
17
+ // const vectorStoreId = pckg.settings[OPENAIVectorStoreName];
18
+ // LLMCredsManager._instance =
19
+ // new LLMCredsManager(hasAIKey ? vectorStoreId ?? '' : '');
20
+ // }
21
+ // static getInstance(): LLMCredsManager {
22
+ // return LLMCredsManager._instance!;
23
+ // }
24
+ // static getVectorStoreId(): string {
25
+ // const res = LLMCredsManager.getInstance().vectorStoreId;
26
+ // if (!res || !res.trim())
27
+ // return '';
28
+ // return res;
29
+ // }
30
+ // }
@@ -0,0 +1,118 @@
1
+ // /* eslint-disable max-len */
2
+ // import {Client} from '@modelcontextprotocol/sdk/client/index.js';
3
+ // import {SSEClientTransport} from '@modelcontextprotocol/sdk/client/sse';
4
+
5
+ // interface DeepWikiClientConfig {
6
+ // repository: string;
7
+ // openaiApiKey: string;
8
+ // openaiModel?: string;
9
+ // }
10
+
11
+ // export const helpAIName = 'WIKITOR GROKOWSKY';
12
+
13
+ // class DeepWikiMCPClient {
14
+ // private mcpClient: Client;
15
+ // private transport: SSEClientTransport | null = null;
16
+ // private readonly askTool = {
17
+ // name: 'ask_question',
18
+ // description: 'Ask a question about the repository and get an answer based on its documentation.',
19
+ // };
20
+ // private static _instance: DeepWikiMCPClient | null = null;
21
+ // static getInstance(repo?: string): DeepWikiMCPClient {
22
+ // DeepWikiMCPClient._instance ??= new DeepWikiMCPClient(repo);
23
+ // return DeepWikiMCPClient._instance;
24
+ // }
25
+ // private constructor(private repoName: string = 'datagrok-ai/public') {
26
+ // this.mcpClient = new Client(
27
+ // {
28
+ // name: 'deepwiki-GROKOWSKY-client',
29
+ // version: '1.0.0',
30
+ // },
31
+ // {
32
+ // capabilities: {},
33
+ // }
34
+ // );
35
+ // }
36
+
37
+ // async connect(): Promise<void> {
38
+ // if (this.transport) {
39
+ // console.log('Already connected to MCP server');
40
+ // return;
41
+ // }
42
+ // console.log('Connecting to DeepWiki MCP server...');
43
+
44
+ // // Connect to DeepWiki's free mcp endpoint
45
+ // this.transport = new SSEClientTransport(
46
+ // new URL('https://mcp.deepwiki.com/mcp')
47
+ // );
48
+
49
+ // await this.mcpClient.connect(this.transport);
50
+ // }
51
+
52
+ // async disconnect(): Promise<void> {
53
+ // if (this.transport) {
54
+ // await this.transport.close();
55
+ // console.log('\n✓ Disconnected from DeepWiki MCP server');
56
+ // }
57
+ // }
58
+
59
+ // async askDeepWiki(question: string): Promise<string> {
60
+ // if (!this.transport)
61
+ // throw new Error('Not connected to MCP server. Call connect() first.');
62
+
63
+
64
+ // const q = `You are a helpful assistant with access to documentation for the ${this.repoName} GitHub repository.
65
+
66
+ // VERY IMPORTANT TO REMEMER!!!: you are a UI side assistant for Datagrok platform users, so when asked about how to do something in Datagrok, try to answer with UI in mind and also the code.
67
+
68
+ // Make sure the output is nicely formatted with markdown syntax where applicable.
69
+
70
+ // Do not repeat the question in your answer, and do not include the deepwiki links!!!.
71
+
72
+ // user: ${question}
73
+ // `;
74
+ // // just call the ask tool directly
75
+ // const toolArgs = {
76
+ // repoName: this.repoName,
77
+ // repository: this.repoName,
78
+ // question: q,
79
+ // };
80
+
81
+ // const result = await this.mcpClient.callTool({
82
+ // name: this.askTool.name,
83
+ // arguments: toolArgs,
84
+ // });
85
+
86
+ // const contentArray = Array.isArray(result.content) ? result.content : [];
87
+ // const toolResult = contentArray
88
+ // .filter((item: any) => item.type === 'text')
89
+ // .map((item: any) => item.text || '')
90
+ // .join('\n');
91
+ // if (!toolResult || toolResult.length === 0)
92
+ // return 'No response generated.';
93
+
94
+ // // remove deepwiki links from the answer
95
+ // const lines = toolResult.split('\n').filter((line) => !line.includes('deepwiki.com')).join('\n');
96
+ // return lines;
97
+ // }
98
+ // }
99
+
100
+ // // Example usage
101
+ // export async function askDeepWiki(question: string) {
102
+ // const client = DeepWikiMCPClient.getInstance('datagrok-ai/public');
103
+
104
+ // try {
105
+ // await client.connect();
106
+
107
+ // const response = await client.askDeepWiki(
108
+ // question
109
+ // );
110
+
111
+ // return response;
112
+ // } catch (error) {
113
+ // console.error('Error:', error);
114
+ // return `Error: ${error}`;
115
+ // }
116
+ // }
117
+
118
+
@@ -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
+ // }