@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
@@ -2,20 +2,10 @@
2
2
  import * as grok from 'datagrok-api/grok';
3
3
  import * as ui from 'datagrok-api/ui';
4
4
  import * as DG from 'datagrok-api/dg';
5
- import {ChatGPTPromptEngine, GeminiPromptEngine, PromptEngine} from '../prompt-engine/prompt-engine';
6
- import {_package} from '../package';
7
- import {dartLike, fireAIAbortEvent} from '../utils';
8
- import {AIPanelFuncs, MessageType} from './panel';
9
- import {generateAISqlQueryWithTools} from './sql-tools';
10
- import {ModelType} from './LLM-client';
11
- import {JsonSchema} from '../prompt-engine/interfaces';
12
-
13
-
14
- /// Prompt API: https://developer.chrome.com/docs/ai/prompt-api
15
- /// Enable all Gemini Nano-related flags here:
16
- /// chrome://flags/#prompt-api-for-gemini-nano
17
-
18
- let _progress: DG.TaskBarProgressIndicator | null = null;
5
+ import {_package} from '../../package';
6
+ import {ClaudeRuntimeClient} from '../../claude/runtime-client';
7
+ import {RENDERED_EVENT} from '../ui';
8
+ import {AiFeature} from '../../claude/ai-feature';
19
9
 
20
10
  export interface QueryMatchResult {
21
11
  searchPattern: string;
@@ -25,16 +15,6 @@ export interface QueryMatchResult {
25
15
  reasoning?: string;
26
16
  }
27
17
 
28
- export function geminiDownloadMonitor(m: CreateMonitor) {
29
- m.addEventListener('downloadprogress', (e) => {
30
- if (!_progress) {
31
- grok.shell.info('Gemini model download started. This might take a few minutes.');
32
- _progress = DG.TaskBarProgressIndicator.create('Downloading Gemini...');
33
- }
34
- _progress.update(e.loaded * 100, 'Downloading Gemini...');
35
- });
36
- }
37
-
38
18
  type PatternQueryMatchResult = {
39
19
  searchPattern: string;
40
20
  parameters: Record<string, string>;
@@ -43,13 +23,25 @@ type PatternQueryMatchResult = {
43
23
  reasoning?: string;
44
24
  };
45
25
 
26
+ const NO_MATCH = 'NO_MATCH';
27
+
46
28
  export async function findBestMatchingQuery(
47
29
  question: string,
48
30
  ): Promise<QueryMatchResult | null> {
49
- const schema: JsonSchema = {
31
+ const tableQueriesSearchFunctions = DG.Func.find({meta: {searchPattern: null}, returnType: 'dataframe'})
32
+ .filter((f) => f.options['searchPattern']);
33
+ if (tableQueriesSearchFunctions.length === 0)
34
+ return null;
35
+
36
+ const searchPatterns = tableQueriesSearchFunctions.map((f) => removeTrailingQuotes(f.options['searchPattern'] as string));
37
+
38
+ const schema = {
50
39
  type: 'object',
51
40
  properties: {
52
- searchPattern: {type: 'string'},
41
+ searchPattern: {
42
+ enum: [...new Set(searchPatterns), NO_MATCH],
43
+ description: `The exact pattern chosen from the provided list, or ${NO_MATCH} if none fits.`,
44
+ },
53
45
  parameters: {
54
46
  type: 'array',
55
47
  description: 'Array of parameter key-value pairs extracted from the search pattern.',
@@ -70,10 +62,7 @@ export async function findBestMatchingQuery(
70
62
  required: ['searchPattern', 'parameters', 'confidence', 'suggestedConnection', 'reasoning'],
71
63
  additionalProperties: false,
72
64
  } as const;
73
- const tableQueriesSearchFunctions = DG.Func.find({meta: {searchPattern: null}, returnType: 'dataframe'})
74
- .filter((f) => f.options['searchPattern']);
75
65
 
76
- const searchPatterns = tableQueriesSearchFunctions.map((f) => f.options['searchPattern'] as string);
77
66
  const descriptions = tableQueriesSearchFunctions.map((f) => f.description ?? 'No description');
78
67
  const connectionIds = tableQueriesSearchFunctions.map((c) => (c instanceof DG.DataQuery) ? c.connection.id ?? 'unknown' : 'unknown');
79
68
  const idSet = new Set(connectionIds.filter((id) => id !== 'unknown'));
@@ -152,7 +141,7 @@ User request:
152
141
  "${question}"
153
142
 
154
143
  Analyze the user request and return a JSON object with:
155
- - searchPattern: the exact pattern string from above (or closest match if confidence is low)
144
+ - searchPattern: the exact pattern string from above, or ${NO_MATCH} if nothing fits
156
145
  - parameters: array of objects with 'key' and 'value' properties for extracted parameter values
157
146
  - confidence: your confidence score (0 to 1)
158
147
  - suggestedConnection: infer the most likely connection from available list (be generous with inference); return null only if truly no clues exist
@@ -160,68 +149,21 @@ Analyze the user request and return a JSON object with:
160
149
  `;
161
150
 
162
151
  try {
163
- let engine: PromptEngine;
164
-
165
- const isGeminiAvailable = await ('LanguageModel' in window ? LanguageModel : null)?.availability();
166
- if (isGeminiAvailable === 'available') {
167
- _package.logger.info('Using built-in Gemini model for fuzzy matching.');
168
- engine = GeminiPromptEngine.getInstance(geminiDownloadMonitor);
169
- } else {
170
- _package.logger.info('Using GPT engine for fuzzy matching.');
171
- engine = ChatGPTPromptEngine.getInstance(ModelType.Fast);
172
- }
173
-
174
- const responseText = await engine.generate(userPrompt, systemPrompt, schema);
175
-
176
- // Robust parsing with validation
177
- let result: QueryMatchResult;
178
- try {
179
- // Remove any potential markdown formatting that might slip through
180
- const cleanedResponse = responseText
181
- .replace(/^```json\s*/i, '')
182
- .replace(/^```\s*/i, '')
183
- .replace(/```\s*$/i, '')
184
- .trim();
185
-
186
- const rawResult = JSON.parse(cleanedResponse) as {
187
- searchPattern: string;
188
- parameters: Array<{key: string; value: string}>;
189
- confidence: number;
190
- suggestedConnection?: string | null;
191
- reasoning?: string;
192
- };
193
-
194
- // Validate required fields
195
- if (typeof rawResult.searchPattern !== 'string')
196
- throw new Error('searchPattern must be a string');
197
- if (!Array.isArray(rawResult.parameters))
198
- throw new Error('parameters must be an array');
199
- if (typeof rawResult.confidence !== 'number' || rawResult.confidence < 0 || rawResult.confidence > 1)
200
- throw new Error('confidence must be a number between 0 and 1');
201
- if (rawResult.suggestedConnection !== undefined && rawResult.suggestedConnection !== null && typeof rawResult.suggestedConnection !== 'string')
202
- throw new Error('suggestedConnection must be a string or null');
203
- if (rawResult.reasoning !== undefined && typeof rawResult.reasoning !== 'string')
204
- throw new Error('reasoning must be a string');
205
-
206
- // Convert array format to Record format
207
- const parametersRecord: Record<string, string> = {};
208
- for (const param of rawResult.parameters) {
209
- if (typeof param.key !== 'string' || typeof param.value !== 'string')
210
- throw new Error('Each parameter must have string key and value properties');
211
- parametersRecord[param.key] = param.value;
212
- }
213
-
214
- result = {
215
- searchPattern: rawResult.searchPattern,
216
- parameters: parametersRecord,
217
- confidence: rawResult.confidence,
218
- suggestedConnection: rawResult.suggestedConnection ?? null,
219
- reasoning: rawResult.reasoning ?? 'No reasoning provided',
220
- };
221
- } catch (parseError) {
222
- _package.logger.error(`Failed to parse LLM response: ${parseError}. Response was: ${responseText}`);
152
+ const rawResult = await ClaudeRuntimeClient.getInstance().query(`${systemPrompt}\n\n${userPrompt}`,
153
+ {outputSchema: schema, feature: AiFeature.QueryMatch, logPrompt: question});
154
+ if (rawResult.searchPattern === NO_MATCH)
223
155
  return null;
224
- }
156
+ const parametersRecord: Record<string, string> = {};
157
+ for (const param of rawResult.parameters)
158
+ parametersRecord[param.key] = param.value;
159
+
160
+ const result: QueryMatchResult = {
161
+ searchPattern: rawResult.searchPattern,
162
+ parameters: parametersRecord,
163
+ confidence: rawResult.confidence,
164
+ suggestedConnection: rawResult.suggestedConnection ?? null,
165
+ reasoning: rawResult.reasoning ?? 'No reasoning provided',
166
+ };
225
167
 
226
168
  _package.logger.info(`Match found with confidence ${result.confidence}. Reasoning: ${result.reasoning}`);
227
169
  if (result.suggestedConnection)
@@ -234,7 +176,14 @@ Analyze the user request and return a JSON object with:
234
176
  }
235
177
  }
236
178
 
237
- export async function tableQueriesFunctionsSearchLlm(s: string): Promise<DG.Widget> {
179
+ export async function tableQueriesFunctionsSearchLlm(s: string, sessionId?: string): Promise<DG.Widget> {
180
+ const widget = await buildQueryWidget(s);
181
+ if (sessionId)
182
+ grok.events.fireCustomEvent(RENDERED_EVENT, sessionId);
183
+ return widget;
184
+ }
185
+
186
+ async function buildQueryWidget(s: string): Promise<DG.Widget> {
238
187
  const tvWidgeFunc = DG.Func.find({name: 'getFuncTableViewWidget'})[0];
239
188
  if (!tvWidgeFunc)
240
189
  return DG.Widget.fromRoot(ui.divText('Power Pack plugin not installed'));
@@ -242,7 +191,7 @@ export async function tableQueriesFunctionsSearchLlm(s: string): Promise<DG.Widg
242
191
  const tableQueriesSearchFunctions = DG.Func.find({meta: {searchPattern: null}, returnType: 'dataframe'})
243
192
  .filter((f) => f.options['searchPattern']);
244
193
  const matches: PatternQueryMatchResult | null = JSON.parse(await grok.functions
245
- .call('ChatGPT:findMatchingPatternQuery', {prompt: s}));
194
+ .call('Grokky:findMatchingPatternQuery', {prompt: s}));
246
195
 
247
196
  if (!matches)
248
197
  return DG.Widget.fromRoot(ui.divText('Unable to process query. Please try rephrasing.'));
@@ -274,7 +223,9 @@ export async function tableQueriesFunctionsSearchLlm(s: string): Promise<DG.Widg
274
223
  `but the connection was not found. Please refine your query with more specific details.`
275
224
  ));
276
225
  }
277
- return runQueryAIprompt(s, connection, tvWidgeFunc);
226
+ return DG.Widget.fromRoot(ui.divText(
227
+ `I couldn't find an exact query for "${connection.name}". Open a query editor for this connection and use the AI assistant (Ctrl+I) to generate a custom query.`
228
+ ));
278
229
  }
279
230
 
280
231
  return DG.Widget.fromRoot(ui.divText(
@@ -282,84 +233,12 @@ export async function tableQueriesFunctionsSearchLlm(s: string): Promise<DG.Widg
282
233
  ));
283
234
  }
284
235
  } catch (error) {
285
- console.error('Error calling ChatGPT:findMatchingPatternQuery', error);
236
+ console.error('Error calling Grokky:findMatchingPatternQuery', error);
286
237
  return DG.Widget.fromRoot(ui.divText(`Error during AI-powered table query search. Check console for details.`));
287
238
  }
288
239
  return DG.Widget.fromRoot(ui.divText('No matching query found via AI'));
289
240
  }
290
241
 
291
- function runQueryAIprompt(userPrompt: string, connection: DG.DataConnection, tvWidgetFunc: DG.Func): DG.Widget {
292
- const outputDiv = ui.divV([
293
- ui.h2(`Looks like you are trying to query the "${connection.name}" database`),
294
- ui.divText('Your prompt did not match any known query patterns.'),
295
- ui.divText('Would you like me to help you construct a query?'),
296
- ui.button('Generate Query', async () => {
297
- await runPrompt();
298
- })
299
- ], {style: {width: '100%', height: '100%'}});
300
- const outputWidget = DG.Widget.fromRoot(outputDiv);
301
- const abort = () => {
302
- fireAIAbortEvent();
303
- };
304
-
305
-
306
- const dummyAIPanelFuncs: AIPanelFuncs<MessageType> = {
307
- addUserMessage: (_aiMsg: any, _msg: string) => {},
308
- addAIMessage: (_aiMsg: any, _title: string, _msg: string) => {},
309
- addEngineMessage: (_aiMsg: any) => {},
310
- addUiMessage: (msg: string, fromUser: boolean, _messageOptions?: any) => {
311
- if (!fromUser)
312
- ui.setUpdateIndicator(outputDiv, true, msg.substring(0, 40) + (msg.length > 40 ? '...' : ''), abort);
313
- },
314
- addConfirmMessage: (_msg?: string) => Promise.resolve(true),
315
- };
316
-
317
- async function runPrompt() {
318
- try {
319
- ui.setUpdateIndicator(outputDiv, true, 'Generating query...', abort);
320
- const sqlResult = await generateAISqlQueryWithTools(
321
- userPrompt,
322
- connection.id!,
323
- {
324
- aiPanel: dummyAIPanelFuncs,
325
- modelType: 'Deep Research',
326
- disableVerbose: true
327
- }
328
- );
329
- ui.setUpdateIndicator(outputDiv, false);
330
- if (sqlResult && sqlResult.trim().length > 0) {
331
- const queryFunc = connection.query(userPrompt, sqlResult);
332
- const outWidget = await tvWidgetFunc.apply({func: queryFunc, inputParams: {}});
333
- if (!outWidget)
334
- throw new Error('Failed to generate widget from AI query');
335
- // replace the output div content with the result widget
336
- outputDiv.replaceWith(outWidget.root);
337
- setTimeout(() => {
338
- const plusIcon = outWidget.root.querySelector('.d4-dialog-header .grok-icon.fal.fa-plus');
339
- if (!plusIcon)
340
- return;
341
- const editIcon = ui.icons.edit(() => {
342
- setTimeout(() => {
343
- const qf = connection.query(userPrompt, sqlResult);
344
- const v = DG.DataQueryView.create(qf);
345
- grok.shell.addView(v);
346
- // grok.shell.v = av;
347
- });
348
- }, 'Edit query');
349
- dartLike(editIcon.style).set('fontSize', '14px').set('width', '20px');
350
- plusIcon.parentNode?.insertBefore(editIcon, plusIcon);
351
- }, 1000);
352
- } else
353
- grok.shell.error('No SQL query was generated from the prompt. Please try rephrasing your request.');
354
- } catch (error: any) {
355
- ui.setUpdateIndicator(outputDiv, false);
356
- grok.shell.error(`Error during AI query generation`);
357
- console.error('Error during AI query generation:', error);
358
- }
359
- };
360
- return outputWidget;
361
- }
362
-
363
242
  function removeTrailingQuotes(s: string): string {
364
243
  let ms = s;
365
244
  if (s.startsWith('"') || s.startsWith('\''))
@@ -1,7 +1,6 @@
1
1
  /* eslint-disable max-len */
2
2
  /* Create a new file: conversation-storage.ts */
3
3
 
4
- import {OpenAI} from 'openai';
5
4
  import {MessageType, UIMessage} from './panel';
6
5
 
7
6
  export interface StoredConversation<T extends MessageType = MessageType, TMeta = any> {
@@ -0,0 +1,145 @@
1
+ import * as grok from 'datagrok-api/grok';
2
+ import * as DG from 'datagrok-api/dg';
3
+ import {undoable} from '../claude/undoable';
4
+ import type {ViewToolDef} from './view-tools';
5
+
6
+ const UNDO = ' Recorded as one undo step (Edit | Undo, Ctrl+Z) when the result has `undoable: true`.';
7
+ const ROW_CODE = 'JS expression evaluated for every row: `i` is the row index, `t` the table, `v` the current value ' +
8
+ 'where there is one (null when missing).';
9
+ const column = {type: 'string', description: 'Column name.'};
10
+
11
+ export const TABLE_TOOL_DEFS: ViewToolDef[] = [
12
+ {
13
+ name: 'table_remove_columns',
14
+ description: 'Remove columns from the table of the current table view.' + UNDO,
15
+ inputSchema: {type: 'object', required: ['columns'], properties: {
16
+ columns: {type: 'array', items: {type: 'string'}, description: 'Names of the columns to remove.'}}},
17
+ },
18
+ {
19
+ name: 'table_remove_rows',
20
+ description: 'Remove rows from the table of the current table view. The user\'s row selection is kept.' + UNDO,
21
+ inputSchema: {type: 'object', required: ['where'], properties: {
22
+ where: {type: 'string',
23
+ description: `True for a row to remove, e.g. "t.getCol('HEIGHT').isNone(i)". ${ROW_CODE}`}}},
24
+ },
25
+ {
26
+ name: 'table_add_column',
27
+ description: 'Add a column to the table of the current table view, filled from `value` or calculated by ' +
28
+ '`formula`.' + UNDO,
29
+ inputSchema: {type: 'object', required: ['name'], properties: {
30
+ name: {type: 'string', description: 'Name of the new column; made unique when taken.'},
31
+ type: {type: 'string', enum: ['double', 'int', 'string', 'bool', 'datetime'],
32
+ description: 'Type of a `value` column.'},
33
+ value: {type: 'string', description: `Value of the row, null for a missing one. ${ROW_CODE}`},
34
+ formula: {type: 'string', description: 'Platform formula of a calculated column, e.g. "${WEIGHT} / 2".'}}},
35
+ },
36
+ {
37
+ name: 'table_set_values',
38
+ description: 'Overwrite the values of a column of the current table view.' + UNDO,
39
+ inputSchema: {type: 'object', required: ['column', 'value'], properties: {
40
+ column, value: {type: 'string', description: `New value of the row, null for a missing one. ${ROW_CODE}`}}},
41
+ },
42
+ {
43
+ name: 'table_edit_column',
44
+ description: 'Rename a column of the current table view or set its metadata.' + UNDO,
45
+ inputSchema: {type: 'object', required: ['column'], properties: {
46
+ column,
47
+ name: {type: 'string', description: 'New name.'},
48
+ format: {type: 'string', description: 'Display format, e.g. "0.00" or "yyyy-MM-dd"; "" clears it.'},
49
+ units: {type: 'string', description: 'Units; "" clears them.'},
50
+ semType: {type: 'string', description: 'Semantic type, e.g. "Molecule".'},
51
+ colorCoding: {type: 'string', enum: ['Linear', 'Categorical', 'Conditional', 'Off'],
52
+ description: 'Color coding with the platform\'s default scheme.'},
53
+ tags: {type: 'object', description: 'Other column tags to set, by name.'}}},
54
+ },
55
+ {
56
+ name: 'table_add_viewer',
57
+ description: 'Add a viewer to the current table view.' + UNDO,
58
+ inputSchema: {type: 'object', required: ['type'], properties: {
59
+ type: {type: 'string', description: 'Viewer type, e.g. "Scatter plot", "Histogram", "Bar chart".'},
60
+ options: {type: 'object',
61
+ description: 'Viewer properties, e.g. {"xColumnName": "HEIGHT", "yColumnName": "WEIGHT"}.'}}},
62
+ },
63
+ ];
64
+
65
+ const COLOR_CODING: {[type: string]: (col: DG.Column) => void} = {
66
+ Linear: (col) => col.meta.colors.setLinear(),
67
+ Categorical: (col) => col.meta.colors.setCategorical(),
68
+ Conditional: (col) => col.meta.colors.setConditional(),
69
+ Off: (col) => col.meta.colors.setDisabled(),
70
+ };
71
+
72
+ function tableView(): DG.TableView {
73
+ const view = grok.shell.v;
74
+ if (view?.type !== DG.VIEW_TYPE.TABLE_VIEW)
75
+ throw new Error('The current view is not a table view');
76
+ return view as DG.TableView;
77
+ }
78
+
79
+ function rowCode(code: string, t: DG.DataFrame, col?: DG.Column): (i: number) => any {
80
+ const f = new Function('i', 't', 'v', 'grok', 'DG', `return (${code}\n);`);
81
+ return (i) => f(i, t, col ? (col.isNone(i) ? null : col.get(i)) : undefined, grok, DG);
82
+ }
83
+
84
+ type Runner = (args: any) => any;
85
+
86
+ export const TABLE_TOOL_RUNNERS = new Map<string, Runner>([
87
+ ['table_remove_columns', (args) => {
88
+ const t = tableView().dataFrame;
89
+ const recorded = undoable.removeColumns(t, args.columns);
90
+ return {success: true, undoable: recorded, columns: t.columns.names()};
91
+ }],
92
+ ['table_remove_rows', async (args) => {
93
+ const t = tableView().dataFrame;
94
+ const before = t.rowCount;
95
+ const recorded = await undoable.removeRows(t, rowCode(args.where, t));
96
+ return {success: true, undoable: recorded, removed: before - t.rowCount, rowCount: t.rowCount};
97
+ }],
98
+ ['table_add_column', async (args) => {
99
+ const t = tableView().dataFrame;
100
+ const name = t.columns.getUnusedName(args.name);
101
+ const value = args.formula ? null : rowCode(args.value, t);
102
+ const col = value ? t.columns.addNew(name, args.type ?? DG.TYPE.FLOAT) :
103
+ await t.columns.addNewCalculated(name, args.formula);
104
+ try {
105
+ if (value)
106
+ col.init(value);
107
+ } catch (e) {
108
+ t.columns.remove(col.name);
109
+ throw e;
110
+ }
111
+ return {success: true, undoable: undoable.columnAdded(col), name: col.name, type: col.type,
112
+ missing: col.stats.missingValueCount};
113
+ }],
114
+ ['table_set_values', async (args) => {
115
+ const t = tableView().dataFrame;
116
+ const col = t.getCol(args.column);
117
+ const value = rowCode(args.value, t, col);
118
+ const recorded = await undoable.changeValues(col, () => col.init(value));
119
+ return {success: true, undoable: recorded, column: col.name, missing: col.stats.missingValueCount};
120
+ }],
121
+ ['table_edit_column', async (args) => {
122
+ const t = tableView().dataFrame;
123
+ const col = t.getCol(args.column);
124
+ if (args.name != null && t.col(args.name) && t.col(args.name) !== col)
125
+ throw new Error(`The table already has a column named "${args.name}"`);
126
+ const recorded = await undoable.editColumn(col, () => {
127
+ if (args.name != null)
128
+ col.name = args.name;
129
+ if (args.format != null)
130
+ col.meta.format = args.format;
131
+ if (args.units != null)
132
+ col.meta.units = args.units;
133
+ if (args.semType != null)
134
+ col.semType = args.semType;
135
+ COLOR_CODING[args.colorCoding]?.(col);
136
+ Object.assign(col.tags, args.tags ?? {});
137
+ });
138
+ return {success: true, undoable: recorded, name: col.name, colorCoding: col.meta.colors.getType(),
139
+ format: col.meta.format, units: col.meta.units, semType: col.semType};
140
+ }],
141
+ ['table_add_viewer', (args) => {
142
+ const viewer = undoable.addViewer(tableView(), args.type, args.options);
143
+ return {success: true, undoable: DG.UndoService != null, type: viewer.type};
144
+ }],
145
+ ]);