@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
@@ -1,315 +0,0 @@
1
- /* eslint-disable max-len */
2
-
3
- import * as grok from 'datagrok-api/grok';
4
- import * as ui from 'datagrok-api/ui';
5
- import * as DG from 'datagrok-api/dg';
6
- import {askDeepWiki} from './deepwikiclient';
7
- import {askOpenAIHelp, ModelType} from './LLM-client';
8
- import {CombinedAISearchAssistant} from './combined-search';
9
- import {ChatGPTPromptEngine} from '../prompt-engine/prompt-engine';
10
- import {ChatGptAssistant} from '../prompt-engine/chatgpt-assistant';
11
- import * as api from '../package-api';
12
- import {Plan} from '../prompt-engine/interfaces';
13
- import {AssistantRenderer} from '../prompt-engine/rendering-tools';
14
- import {fireAIAbortEvent, fireAIPanelToggleEvent} from '../utils';
15
- import {generateAISqlQueryWithTools} from './sql-tools';
16
- import {BuiltinDBInfoMeta} from './query-meta-utils';
17
- import {processTableViewAIRequest} from './tableview-tools';
18
- import {DBAIPanel, ScriptingAIPanel, TVAIPanel} from './panel';
19
- import {ClaudeRuntimeClient} from '../claude-code/claude-runtime-client';
20
- import {generateDatagrokScript} from './script-tools';
21
-
22
-
23
- export async function askWiki(question: string, useOpenAI: boolean = true) {
24
- try {
25
- const res = !useOpenAI ? (await askDeepWiki(question)) : (await askOpenAIHelp(question));
26
- const markdown = ui.markdown(res);
27
- markdown.style.userSelect = 'text';
28
- return DG.Widget.fromRoot(markdown);
29
- } catch (error: any) {
30
- console.error('Error during DeepGROK ask:', error);
31
- return DG.Widget.fromRoot(ui.divText(`Error during DeepGROK ask: ${error.message}`));
32
- }
33
- }
34
-
35
- export async function smartExecution(prompt: string, modelName: string) {
36
- const gptEngine = ChatGPTPromptEngine.getInstance(modelName);
37
- const gptAssistant = new ChatGptAssistant(gptEngine);
38
-
39
- const mainWaitDiv = ui.wait(async () => {
40
- const resDiv = ui.divV([], 'chatgpt-ask-ai-result');
41
- const plan = JSON.parse(await api.funcs.getExecutionPlan(prompt)) as Plan;
42
- const planDiv = AssistantRenderer.renderPlan(plan);
43
- resDiv.appendChild(planDiv);
44
- resDiv.appendChild(ui.wait(async () => {
45
- const result = await gptAssistant.execute(plan);
46
- const resRen = AssistantRenderer.renderResult(result);
47
- return resRen;
48
- }));
49
- return resDiv;
50
- });
51
- return DG.Widget.fromRoot(mainWaitDiv);
52
- }
53
-
54
- // sets up the ui button for the input
55
- export function setupSearchUI() {
56
- if (!grok.ai.config.configured) {
57
- console.warn('LLM API key is not set up. Search UI will not have AI assistance.');
58
- return;
59
- }
60
-
61
- const maxRetries = 10;
62
- function searchForSearchBox() {
63
- const searchBoxContainer = document.getElementsByClassName('power-pack-welcome-view')[0];
64
- if (!searchBoxContainer)
65
- return null;
66
- const searchInput = Array.from(searchBoxContainer.getElementsByClassName('power-search-search-everywhere-input'))[0] as HTMLInputElement;
67
- return searchInput;
68
- }
69
-
70
- function initInput(searchInput: HTMLInputElement) {
71
- const parent: HTMLElement = searchInput.parentElement!;
72
- const aiIcon = ui.iconFA('magic', () => { aiCombinedSearch(searchInput.value); }, 'Ask AI');
73
- aiIcon.style.cursor = 'pointer';
74
- aiIcon.style.color = 'var(--blue-1)';
75
- aiIcon.style.marginLeft = '4px';
76
- aiIcon.style.marginRight = '4px';
77
- parent.appendChild(aiIcon);
78
-
79
- const onSearchChanged = () => {
80
- if (!searchInput.value?.trim())
81
- aiIcon.style.display = 'none';
82
- else
83
- aiIcon.style.display = 'flex';
84
- };
85
- searchInput.addEventListener('input', onSearchChanged);
86
- // set up the enter key listener and modify suggestion
87
- const searchHelpDiv = document.getElementsByClassName('power-search-help-text-container')[0] as HTMLDivElement;
88
- if (searchHelpDiv)
89
- searchHelpDiv.innerText = `Press Enter to grok. ${searchHelpDiv.innerText}`;
90
-
91
- searchInput.addEventListener('keyup', (event: KeyboardEvent) => {
92
- if (event.key === 'Enter' && searchInput.value?.trim()) {
93
- event.preventDefault();
94
- setTimeout(() => aiCombinedSearch(searchInput.value), 400); // timeout needed to allow other enter handlers to run first
95
- }
96
- if (searchHelpDiv)
97
- searchHelpDiv.style.visibility = searchInput.value?.trim().split(' ').length > 1 ? 'visible' : 'hidden';
98
- });
99
-
100
- onSearchChanged();
101
- }
102
-
103
- const retries = 0;
104
- const intervalId = setInterval(() => {
105
- const searchInput = searchForSearchBox();
106
- if (searchInput) {
107
- clearInterval(intervalId);
108
- initInput(searchInput);
109
- } else if (retries >= maxRetries) {
110
- clearInterval(intervalId);
111
- console.warn('Search input box not found after maximum retries.');
112
- }
113
- }, 1000);
114
- }
115
-
116
- async function aiCombinedSearch(prompt: string) {
117
- // hide the menu
118
- document.querySelector('.d4-menu-popup')?.remove();
119
- await CombinedAISearchAssistant.instance.searchUI(prompt);
120
- }
121
-
122
- export async function setupAIQueryEditorUI(v: DG.ViewBase, connectionID: string, queryEditorRoot: HTMLElement, setAndRunFunc: (query: string) => void): Promise<boolean> {
123
- if (!grok.ai.config.configured)
124
- return false;
125
- const connection = await grok.dapi.connections.find(connectionID);
126
- if (!connection) { // should not happen but just in case
127
- grok.shell.error(`Connection with ID ${connectionID} not found.`);
128
- return false;
129
- }
130
-
131
- const allDbInfos = await BuiltinDBInfoMeta.allFromConnection(connection);
132
- const catalogs = allDbInfos.map((d) => d.name);
133
- const defaultCatalog = connection.parameters?.['catalog'] ?? connection.parameters?.['db'] ?? catalogs[0] ?? '';
134
-
135
- const panel = new DBAIPanel(catalogs, defaultCatalog, connectionID, v);
136
- panel.show();
137
-
138
- panel.onRunRequest.subscribe(async (args) => {
139
- ui.setUpdateIndicator(queryEditorRoot, true, 'Grokking Query...', () => { fireAIAbortEvent(); });
140
- const session = panel.startChatSession();
141
- try {
142
- const sqlQuery = await generateAISqlQueryWithTools(args.currentPrompt.prompt, connectionID, {
143
- catalogName: args.currentPrompt.catalogName,
144
- oldMessages: args.prevMessages,
145
- aiPanel: session.session, modelType: panel.getCurrentInputs().model,
146
- });
147
- if (sqlQuery && typeof sqlQuery === 'string' && sqlQuery.trim().length > 0)
148
- setAndRunFunc(sqlQuery);
149
- } catch (error: any) {
150
- ui.setUpdateIndicator(queryEditorRoot, false);
151
- grok.shell.error(`Error during AI query generation`);
152
- console.error('Error during AI query generation:', error);
153
- }
154
- ui.setUpdateIndicator(queryEditorRoot, false);
155
- session.endSession();
156
- });
157
- return true;
158
- }
159
-
160
- async function runClaudeStreaming(panel: TVAIPanel, userPrompt: string, tableView: DG.TableView) {
161
- const chatSession = panel.startChatSession();
162
- const sessionId = panel.sessionId;
163
- let accumulated = '';
164
- let toolStatus = '';
165
- const subs: {unsubscribe: () => void}[] = [];
166
- const cleanup = () => subs.forEach((s) => s.unsubscribe());
167
-
168
- const forSession = <T extends {sessionId: string}>(
169
- source: {subscribe: (cb: (evt: T) => void) => {unsubscribe: () => void}},
170
- handler: (evt: T) => void,
171
- ) => subs.push(source.subscribe((evt) => {
172
- if (evt.sessionId === sessionId)
173
- handler(evt);
174
- }));
175
-
176
- const endWithError = (msg: string) => {
177
- panel.clearStreaming();
178
- grok.shell.error(msg);
179
- chatSession.endSession();
180
- cleanup();
181
- };
182
-
183
- try {
184
- const client = ClaudeRuntimeClient.getInstance();
185
- await client.ensureConnected();
186
-
187
- chatSession.session.addUiMessage(userPrompt, true);
188
-
189
- forSession(client.onChunk, (evt) => {
190
- accumulated += evt.content;
191
- toolStatus = '';
192
- panel.updateStreaming(accumulated, chatSession.loader);
193
- });
194
-
195
- forSession(client.onToolActivity, (evt) => {
196
- toolStatus = `\n\n---\n**${evt.summary}**`;
197
- panel.updateStreaming(accumulated + toolStatus, chatSession.loader);
198
- });
199
-
200
- forSession(client.onToolResult, (evt) => {
201
- toolStatus = `\n\n---\n\`\`\`\n${evt.content}\n\`\`\``;
202
- panel.updateStreaming(accumulated + toolStatus, chatSession.loader);
203
- });
204
-
205
- forSession(client.onFinal, (evt) => {
206
- panel.finalizeStreaming(evt.content, tableView);
207
- chatSession.endSession();
208
- cleanup();
209
- });
210
-
211
- forSession(client.onError, (evt) => endWithError(`Claude: ${evt.message}`));
212
-
213
- subs.push(client.onClose.subscribe(() => endWithError('Claude: connection lost')));
214
-
215
- const prompt = panel.prependViewContext(userPrompt, tableView);
216
- client.send(sessionId, prompt);
217
- }
218
- catch (e: any) {
219
- panel.clearStreaming();
220
- grok.shell.error(`Claude runtime: ${e.message}`);
221
- console.error('Claude runtime error:', e);
222
- chatSession.endSession();
223
- cleanup();
224
- }
225
- }
226
-
227
- export async function setupTableViewAIPanelUI() {
228
- if (!grok.ai.config.configured)
229
- return;
230
- const handleView = (tableView: DG.TableView) => {
231
- // setup ribbon panel icon
232
- const iconFse = ui.iconSvg('ai.svg', () => fireAIPanelToggleEvent(tableView), 'Ask AI \n Ctrl+I');
233
- iconFse.style.width = iconFse.style.height = '18px';
234
- tableView.setRibbonPanels([...tableView.getRibbonPanels(), [iconFse]]);
235
- // setup the panel itself
236
- const panel = new TVAIPanel(tableView);
237
- panel.hide();
238
-
239
- // Setup request handler
240
- panel.onRunRequest.subscribe(async (args) => {
241
- if (panel.currentEngine === 'Claude') {
242
- await runClaudeStreaming(panel, args.currentPrompt.prompt, tableView);
243
- } else {
244
- const chatSession = panel.startChatSession();
245
- try {
246
- await processTableViewAIRequest(
247
- args.currentPrompt.prompt,
248
- tableView,
249
- {
250
- oldMessages: args.prevMessages,
251
- aiPanel: chatSession.session,
252
- modelType: panel.getCurrentInputs().model,
253
- }
254
- );
255
- } catch (error: any) {
256
- grok.shell.error('Error during AI table view processing');
257
- console.error('Error during AI table view processing:', error);
258
- }
259
- chatSession.endSession();
260
- }
261
- });
262
- };
263
- // also handle already opened views
264
- Array.from(grok.shell.tableViews).filter((v) => v.dataFrame != null).forEach((view) => {
265
- handleView(view as DG.TableView);
266
- });
267
-
268
- grok.events.onViewAdded.subscribe((view) => {
269
- if (view.type === DG.VIEW_TYPE.TABLE_VIEW)
270
- handleView(view as DG.TableView);
271
- });
272
- }
273
-
274
- export async function setupScriptsAIPanelUI() {
275
- const handleView = (scriptView: DG.ScriptView) => {
276
- // setup ribbon panel icon
277
- const iconFse = ui.iconSvg('ai.svg', () => fireAIPanelToggleEvent(scriptView), 'Ask AI \n Ctrl+I');
278
- iconFse.style.width = iconFse.style.height = '18px';
279
- scriptView.setRibbonPanels([...scriptView.getRibbonPanels(), [iconFse]]);
280
- // Setup request handler
281
- // setup the panel itself
282
- const panel = new ScriptingAIPanel(scriptView);
283
- panel.hide();
284
- panel.onRunRequest.subscribe(async (args) => {
285
- ui.setUpdateIndicator(scriptView.root, true, 'Vibe-Grokking Script...', () => { fireAIAbortEvent(); });
286
- const indicator = scriptView.root.querySelector('.d4-update-shadow') as HTMLElement;
287
- if (indicator)
288
- indicator.style.zIndex = '1000';
289
- const session = panel.startChatSession();
290
- try {
291
- const res = await generateDatagrokScript(
292
- args.currentPrompt.prompt,
293
- panel.getCurrentInputs().language,
294
- {
295
- oldMessages: args.prevMessages,
296
- aiPanel: session.session
297
- }
298
- );
299
- if (res && res.trim().length > 0)
300
- scriptView.code = res;
301
- console.log('Generated script:', res);
302
- } catch (error: any) {
303
- grok.shell.error('Error during AI table view processing');
304
- console.error('Error during AI table view processing:', error);
305
- }
306
- ui.setUpdateIndicator(scriptView.root, false);
307
- session.endSession();
308
- });
309
- };
310
-
311
- grok.events.onViewAdded.subscribe((view) => {
312
- if (view.type === 'ScriptView')
313
- setTimeout(() => handleView(view as DG.ScriptView), 500);
314
- });
315
- }
@@ -1,257 +0,0 @@
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
- }