@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
@@ -3,8 +3,8 @@ 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
5
  import {getSchemaDescriptor} from '@datagrok-libraries/db-explorer/src/utils';
6
- import {LLMClient} from './LLM-client';
7
- import {JsonSchema} from '../prompt-engine/interfaces';
6
+ import {ClaudeRuntimeClient} from '../claude/runtime-client';
7
+ import {AiFeature} from '../claude/ai-feature';
8
8
 
9
9
  type DBIDWithSchema = `${string}.${string}`;
10
10
  type DBReference = `${string}.${string} -> ${string}.${string}`;
@@ -219,13 +219,13 @@ export async function genDBConnectionMeta(connection: DG.DataConnection, schemas
219
219
  }
220
220
 
221
221
  //NB: Uncomment the following lines to enable LLM-based post-processing of DB metadata
222
- //const enrichedMeta = await postProcessDBConnectionMeta(out, 'gpt-4o-mini');
222
+ //const enrichedMeta = await postProcessDBConnectionMeta(out);
223
223
  //return enrichedMeta;
224
224
  return out;
225
225
  }
226
226
 
227
227
  // Helper schemas for structured LLM output
228
- const ConnectionCommentSchema: JsonSchema = {
228
+ const ConnectionCommentSchema = {
229
229
  type: 'object',
230
230
  properties: {
231
231
  comment: {type: 'string', description: 'Brief overview of the database purpose and domain'},
@@ -235,7 +235,7 @@ const ConnectionCommentSchema: JsonSchema = {
235
235
  additionalProperties: false,
236
236
  };
237
237
 
238
- const SchemaCommentSchema: JsonSchema = {
238
+ const SchemaCommentSchema = {
239
239
  type: 'object',
240
240
  properties: {
241
241
  comment: {type: 'string', description: 'Brief description of schema purpose'},
@@ -245,7 +245,7 @@ const SchemaCommentSchema: JsonSchema = {
245
245
  additionalProperties: false,
246
246
  };
247
247
 
248
- const TableCommentSchema: JsonSchema = {
248
+ const TableCommentSchema = {
249
249
  type: 'object',
250
250
  properties: {
251
251
  comment: {type: 'string', description: 'Brief table description'},
@@ -255,7 +255,7 @@ const TableCommentSchema: JsonSchema = {
255
255
  additionalProperties: false,
256
256
  };
257
257
 
258
- const ColumnCommentsSchema: JsonSchema = {
258
+ const ColumnCommentsSchema = {
259
259
  type: 'object',
260
260
  properties: {
261
261
  columns: {
@@ -276,7 +276,7 @@ const ColumnCommentsSchema: JsonSchema = {
276
276
  additionalProperties: false,
277
277
  };
278
278
 
279
- const RelationCommentSchema: JsonSchema = {
279
+ const RelationCommentSchema = {
280
280
  type: 'object',
281
281
  properties: {
282
282
  comment: {type: 'string', description: 'Brief relation description'},
@@ -288,7 +288,7 @@ const RelationCommentSchema: JsonSchema = {
288
288
  additionalProperties: false,
289
289
  };
290
290
 
291
- const HiddenRelationsSchema: JsonSchema = {
291
+ const HiddenRelationsSchema = {
292
292
  type: 'object',
293
293
  properties: {
294
294
  hiddenRelations: {
@@ -316,25 +316,27 @@ const HiddenRelationsSchema: JsonSchema = {
316
316
  additionalProperties: false,
317
317
  };
318
318
 
319
+ async function queryLLM(systemPrompt: string, userPrompt: string, outputSchema: object): Promise<any> {
320
+ const client = ClaudeRuntimeClient.getInstance();
321
+ const result = await client.query(`${systemPrompt}\n\n${userPrompt}`, {outputSchema, feature: AiFeature.DbIndex});
322
+ return typeof result === 'string' ? JSON.parse(result) : result;
323
+ }
324
+
319
325
  /**
320
326
  * Post-processes DB metadata by enriching it with LLM-generated comments and insights
321
327
  * @param connectionMeta - The raw connection metadata
322
- * @param openAIModel - The OpenAI model to use (e.g., 'gpt-4o')
323
328
  */
324
- export async function postProcessDBConnectionMeta(connectionMeta: DBConnectionMeta, openAIModel: string): Promise<DBConnectionMeta> {
325
- const llmClient = LLMClient.getInstance();
329
+ export async function postProcessDBConnectionMeta(connectionMeta: DBConnectionMeta): Promise<DBConnectionMeta> {
326
330
  const result = {...connectionMeta};
327
331
 
328
332
  // Step 1: Generate connection-level comment
329
333
  console.log('Generating connection-level comment...');
330
334
  const connectionOverview = generateConnectionOverview(result);
331
- const connectionCommentResponse = await llmClient.generalPromptCached(
332
- openAIModel,
335
+ const connectionComment = await queryLLM(
333
336
  'You are a database documentation expert. Generate concise, informative descriptions for database connections.',
334
337
  `Database: ${result.name}\n\n${connectionOverview}\n\nGenerate a brief overview (comment) and an AI-friendly description (LLMComment) that helps AI models understand this database's purpose and structure.`,
335
338
  ConnectionCommentSchema
336
339
  );
337
- const connectionComment = JSON.parse(connectionCommentResponse);
338
340
  result.comment = connectionComment.comment;
339
341
  result.LLMComment = connectionComment.LLMComment;
340
342
 
@@ -344,13 +346,11 @@ export async function postProcessDBConnectionMeta(connectionMeta: DBConnectionMe
344
346
 
345
347
  // Generate schema comment
346
348
  const schemaOverview = generateSchemaOverview(schema);
347
- const schemaCommentResponse = await llmClient.generalPromptCached(
348
- openAIModel,
349
+ const schemaComment = await queryLLM(
349
350
  'You are a database documentation expert. Generate concise schema descriptions.',
350
351
  `Schema: ${schema.name}\n\n${schemaOverview}\n\nGenerate a brief description and AI-friendly context.`,
351
352
  SchemaCommentSchema
352
353
  );
353
- const schemaComment = JSON.parse(schemaCommentResponse);
354
354
  schema.comment = schemaComment.comment;
355
355
  schema.LLMComment = schemaComment.LLMComment;
356
356
 
@@ -360,31 +360,27 @@ export async function postProcessDBConnectionMeta(connectionMeta: DBConnectionMe
360
360
 
361
361
  // Generate table comment with full context
362
362
  const tableContext = generateTableContext(table, schema);
363
- const tableCommentResponse = await llmClient.generalPromptCached(
364
- openAIModel,
363
+ const tableComment = await queryLLM(
365
364
  'You are a database documentation expert. Generate table descriptions that help AI understand the domain.',
366
365
  `Table: ${schema.name}.${table.name}\n\n${tableContext}\n\nGenerate a brief description and AI-friendly context explaining this table's role.`,
367
366
  TableCommentSchema
368
367
  );
369
- const tableComment = JSON.parse(tableCommentResponse);
370
368
  table.comment = tableComment.comment;
371
369
  table.LLMComment = tableComment.LLMComment;
372
370
 
373
371
  // Step 4: Generate column comments (batch processing for efficiency)
374
372
  const columnContext = generateColumnContext(table);
375
- const columnCommentsResponse = await llmClient.generalPromptCached(
376
- openAIModel,
377
- `You are a database documentation expert. For each column, generate a brief description.
373
+ const columnComments = await queryLLM(
374
+ `You are a database documentation expert. For each column, generate a brief description.
378
375
  If a column is self-evident (like 'id' in a table named 'users' -> 'User ID'), you can use a very short description or leave empty strings.
379
376
  Focus on non-obvious columns, semantic types, and domain-specific meanings.`,
380
377
  `Table: ${schema.name}.${table.name}\n\n${columnContext}\n\nFor each column, provide comment and LLMComment. Leave both empty if the column is completely self-evident.`,
381
378
  ColumnCommentsSchema
382
379
  );
383
- const columnComments = JSON.parse(columnCommentsResponse);
384
380
 
385
381
  // Apply column comments
386
382
  for (const colComment of columnComments.columns) {
387
- const col = table.columns.find((c) => c.name === colComment.name);
383
+ const col = table.columns.find((c: any) => c.name === colComment.name);
388
384
  if (col) {
389
385
  col.comment = colComment.comment || undefined;
390
386
  col.LLMComment = colComment.LLMComment || undefined;
@@ -400,8 +396,7 @@ Focus on non-obvious columns, semantic types, and domain-specific meanings.`,
400
396
  const relation = result.relations[i];
401
397
  const relationContext = `${relation.fromSchema}.${relation.fromTable}(${relation.fromColumns.join(', ')}) -> ${relation.toSchema}.${relation.toTable}(${relation.toColumns.join(', ')})`;
402
398
 
403
- const relationCommentResponse = await llmClient.generalPromptCached(
404
- openAIModel,
399
+ const relationComment = await queryLLM(
405
400
  `You are a database expert. Analyze foreign key relationships and provide:
406
401
  1. Brief comment
407
402
  2. Natural language explanation (e.g., "Each assay_result belongs to one assay; one assay has many assay_results")
@@ -410,7 +405,6 @@ Focus on non-obvious columns, semantic types, and domain-specific meanings.`,
410
405
  `Relation: ${relationContext}\n\nDatabase context:\n${relationsContext}\n\nAnalyze this relationship.`,
411
406
  RelationCommentSchema
412
407
  );
413
- const relationComment = JSON.parse(relationCommentResponse);
414
408
  relation.comment = relationComment.comment;
415
409
  relation.LLMComment = relationComment.LLMComment;
416
410
  relation.cardinality = relationComment.cardinality;
@@ -419,8 +413,7 @@ Focus on non-obvious columns, semantic types, and domain-specific meanings.`,
419
413
 
420
414
  // Step 6: Discover hidden relations
421
415
  console.log('Discovering hidden relations...');
422
- const hiddenRelationsResponse = await llmClient.generalPromptCached(
423
- openAIModel,
416
+ const hiddenRelations = await queryLLM(
424
417
  `You are a database expert. Analyze the database schema and identify potential "hidden" relationships that are not defined as foreign keys but could be logically joined.
425
418
  Examples:
426
419
  - Tables with similar column names (e.g., user_id in different tables)
@@ -431,7 +424,6 @@ Only suggest high-confidence relationships that would be useful for queries. Ret
431
424
  `Database: ${result.name}\n\nSchemas and tables:\n${generateHiddenRelationsContext(result)}\n\nIdentify any hidden relationships.`,
432
425
  HiddenRelationsSchema
433
426
  );
434
- const hiddenRelations = JSON.parse(hiddenRelationsResponse);
435
427
 
436
428
  // Add hidden relations to the result
437
429
  if (hiddenRelations.hiddenRelations && hiddenRelations.hiddenRelations.length > 0) {
@@ -0,0 +1,336 @@
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 {BuiltinDBInfoMeta, getDBColumnMetaData, getDBTableMetaData} from './query-meta-utils';
6
+
7
+ const suspiciousSQlPatterns = ['DROP ', 'DELETE ', 'UPDATE ', 'INSERT ', 'ALTER ', 'CREATE ', 'TRUNCATE ', 'EXEC ', 'MERGE '];
8
+
9
+ // Tool definitions are registered in the MCP server (dockerfiles/mcp-server/src/index.ts).
10
+ // The Claude runtime intercepts calls to mcp__datagrok__db_* tools and forwards them
11
+ // to the browser, where handleToolCall() dispatches to the methods below.
12
+
13
+ /**
14
+ * Context class that manages tool execution for SQL generation.
15
+ * Supports multiple catalogs (e.g. for Databricks) with a default catalog.
16
+ */
17
+ export class SQLGenerationContext {
18
+ private dbInfoMap: Map<string, BuiltinDBInfoMeta> = new Map();
19
+
20
+ constructor(
21
+ private connectionID: string,
22
+ private defaultCatalog: string,
23
+ dbInfos: BuiltinDBInfoMeta[],
24
+ private connection: DG.DataConnection
25
+ ) {
26
+ for (const dbInfo of dbInfos)
27
+ this.dbInfoMap.set(dbInfo.name, dbInfo);
28
+ }
29
+
30
+ static async create(connectionID: string, defaultCatalog: string): Promise<SQLGenerationContext> {
31
+ const connection = await grok.dapi.connections.find(connectionID);
32
+ if (!connection)
33
+ throw new Error(`Connection with ID ${connectionID} not found.`);
34
+ const dbInfos = await BuiltinDBInfoMeta.allFromConnection(connection);
35
+ return new SQLGenerationContext(connectionID, defaultCatalog, dbInfos, connection);
36
+ }
37
+
38
+ private getDbInfo(catalogName?: string): BuiltinDBInfoMeta {
39
+ const name = catalogName ?? this.defaultCatalog;
40
+ const dbInfo = this.dbInfoMap.get(name);
41
+ if (!dbInfo)
42
+ throw new Error(`Catalog '${name}' not found. Available catalogs: ${Array.from(this.dbInfoMap.keys()).join(', ')}`);
43
+ return dbInfo;
44
+ }
45
+
46
+ /**
47
+ * Parses a table reference that may include catalog, schema, and table name.
48
+ * Supports: catalog.schema.table, schema.table, or just table
49
+ */
50
+ private parseTableRef(tableRef: string): {catalog: string, schema: string, table: string} {
51
+ const parts = tableRef.trim().split('.');
52
+ if (parts.length >= 3)
53
+ return {catalog: parts[0], schema: parts[1], table: parts.slice(2).join('.')};
54
+ if (parts.length === 2)
55
+ return {catalog: this.defaultCatalog, schema: parts[0], table: parts[1]};
56
+ return {catalog: this.defaultCatalog, schema: '', table: parts[0]};
57
+ }
58
+
59
+ async listCatalogs(): Promise<string[]> {
60
+ return Array.from(this.dbInfoMap.keys());
61
+ }
62
+
63
+ async listAllSchemas(catalogName?: string): Promise<string[]> {
64
+ return (await this.getDbInfo(catalogName).getSchemas()).map((s) => s.name);
65
+ }
66
+
67
+ /**
68
+ * Tool: list_tables
69
+ * Returns all tables with their descriptions
70
+ */
71
+ async listTables(includeAllDescriptions: boolean, schemaName: string, catalogName?: string): Promise<{description: string, tableCount: number}> {
72
+ const dbInfo = this.getDbInfo(catalogName);
73
+
74
+ const schema = (await dbInfo.getSchemas()).find((s) => s.name === schemaName);
75
+ if (!schema)
76
+ return {description: `Schema ${schemaName} not found in catalog ${catalogName ?? this.defaultCatalog}.`, tableCount: 0};
77
+
78
+ const tables = (await schema.getTables());
79
+ const tableDescs = tables.map((table) => {
80
+ const parts = [`${table.friendlyName ?? table.name}`];
81
+ const tableMeta = getDBTableMetaData(table);
82
+ if (includeAllDescriptions) {
83
+ if (tableMeta?.llmComment)
84
+ parts.push(` LLM Comment: ${tableMeta.llmComment.substring(0, 400)}...`);
85
+ else if (tableMeta.comment)
86
+ parts.push(` Description: ${tableMeta.comment.substring(0, 400)}...`);
87
+ }
88
+ parts.push(` Columns: ${table.columns.length}, ${tableMeta?.rowCount ? `Rows: ${tableMeta.rowCount}` : ''}`);
89
+ return parts.join('\n');
90
+ });
91
+ return {description: `Tables in ${schemaName}:\n\n${tableDescs.join('\n')}`, tableCount: tableDescs.length};
92
+ }
93
+
94
+ /**
95
+ * Tool: describe_tables
96
+ * Returns detailed column information for specified tables.
97
+ * Supports catalog.schema.table and schema.table formats.
98
+ */
99
+ async describeTables(tableNames: string[]): Promise<string> {
100
+ const refs = tableNames.map((t) => this.parseTableRef(t));
101
+ const descriptions: string[] = [];
102
+
103
+ // Group by catalog+schema for efficient fetching
104
+ const groupKey = (r: {catalog: string, schema: string}) => `${r.catalog}\0${r.schema}`;
105
+ const schemaTableCache: Map<string, DG.TableInfo[]> = new Map();
106
+
107
+ for (const key of new Set(refs.map(groupKey))) {
108
+ const [catalog, schema] = key.split('\0');
109
+ try {
110
+ const dbInfo = this.getDbInfo(catalog);
111
+ const schemaInfo = (await dbInfo.getSchemas()).find((s) => s.name === schema);
112
+ if (schemaInfo)
113
+ schemaTableCache.set(key, await schemaInfo.getTables());
114
+ } catch { /* catalog not found */ }
115
+ }
116
+
117
+ for (const ref of refs) {
118
+ const tables = schemaTableCache.get(groupKey(ref));
119
+ if (!tables) {
120
+ descriptions.push(`Schema ${ref.schema} not found in catalog ${ref.catalog}`);
121
+ continue;
122
+ }
123
+ const table = tables.find((t) => t.friendlyName === ref.table || t.name === ref.table);
124
+ if (!table) {
125
+ descriptions.push(`Table ${ref.table} not found in ${ref.schema}`);
126
+ continue;
127
+ }
128
+ descriptions.push(this.buildDetailedTableDescription(table));
129
+ }
130
+
131
+ return descriptions.join('\n\n---\n\n');
132
+ }
133
+
134
+ /**
135
+ * Tool: list_joins
136
+ * Returns all foreign key relationships involving the specified tables.
137
+ * Supports catalog.schema.table and schema.table formats.
138
+ */
139
+ async listJoins(tableNames: string[]): Promise<string> {
140
+ const refs = tableNames.map((t) => this.parseTableRef(t));
141
+
142
+ const schemaQualifiedTableSet = new Set<string>();
143
+ for (const ref of refs)
144
+ schemaQualifiedTableSet.add(`${ref.schema}.${ref.table}`);
145
+
146
+ // Collect unique catalog+schema pairs for efficient relation fetching
147
+ const catalogSchemaMap = new Map<string, Set<string>>();
148
+ for (const ref of refs) {
149
+ if (!catalogSchemaMap.has(ref.catalog))
150
+ catalogSchemaMap.set(ref.catalog, new Set());
151
+ catalogSchemaMap.get(ref.catalog)!.add(ref.schema);
152
+ }
153
+
154
+ const allRelations: DG.DbRelationInfo[] = [];
155
+ for (const [catalog, schemas] of catalogSchemaMap) {
156
+ const dbInfo = this.getDbInfo(catalog);
157
+ for (const schema of schemas) {
158
+ const relations = await dbInfo.getRelationsForSchema(schema);
159
+ allRelations.push(...relations);
160
+ }
161
+ }
162
+
163
+ const filteredRelations = allRelations
164
+ .filter((rel) => schemaQualifiedTableSet.has(`${rel.fromSchema}.${rel.fromTable}`) || schemaQualifiedTableSet.has(`${rel.toSchema}.${rel.toTable}`));
165
+ const joins = filteredRelations.map((rel) => this.buildJoinDescription(rel));
166
+
167
+ if (joins.length === 0)
168
+ return `No foreign key relationships found for tables: ${tableNames.join(', ')}`;
169
+
170
+ return `Foreign key relationships involving ${tableNames.join(', ')}:\n\n${joins.join('\n')}`;
171
+ }
172
+
173
+ static _lastFc: DG.FuncCall | null = null;
174
+ /**
175
+ * Tool: try_sql
176
+ * Executes SQL and returns row count and column names
177
+ */
178
+ async trySql(sql: string, description: string): Promise<string> {
179
+ console.log('trySql called with description:', description);
180
+ try {
181
+ // Add LIMIT if not present
182
+ let testSql = sql.trim();
183
+ if (testSql.endsWith(';'))
184
+ testSql = testSql.substring(0, testSql.length - 1);
185
+ if (!testSql.toUpperCase().includes('LIMIT'))
186
+ testSql += ' LIMIT 10';
187
+
188
+ // Basic safety check to prevent destructive queries
189
+ const upperSql = sql.toUpperCase();
190
+ if (suspiciousSQlPatterns.some((pattern) => upperSql.includes(pattern))) {
191
+ // prompt user confirmation
192
+
193
+ const p = new Promise<boolean>((resolve) => {
194
+ ui.dialog('Confirm SQL Execution')
195
+ .add(ui.divText('Our AI is trying to execute a potentially destructive SQL command. For your safety, please confirm if you want to proceed.'))
196
+ .add(ui.markdown(`\`\`\`sql\n${sql}\n\`\`\``, {sanitize: true}))
197
+ .onOK(() => resolve(true))
198
+ .onCancel(() => resolve(false))
199
+ .show();
200
+ });
201
+ const userConfirmed = await p;
202
+ if (!userConfirmed)
203
+ return 'SQL Execution Not allowed by User: Destructive commands are not allowed. Please revise the query.';
204
+ }
205
+ const queryName = `test-query-${Date.now()}`;
206
+ const wrappedSql = `--name: ${queryName}\n${testSql}`;
207
+
208
+ const fc = this.connection.query(queryName, wrappedSql).prepare({});
209
+ SQLGenerationContext._lastFc = fc;
210
+ await fc.call(false, undefined, {processed: true, report: false});
211
+ const df = await fc.getOutputParamValue();
212
+ SQLGenerationContext._lastFc = null;
213
+ if (!df)
214
+ throw new Error('No data returned');
215
+ const result = [
216
+ `Query executed successfully!`,
217
+ `Row count: ${df.rowCount}`,
218
+ `Columns (${df.columns.length}): ${df.columns.toList().map((c: DG.Column) => `${c.name} (${c.type})`).join(', ')}`,
219
+ ];
220
+
221
+ // If there are rows, show a sample
222
+ if (df.rowCount > 0) {
223
+ const sample = df.columns.toList().map((col: DG.Column) => {
224
+ const val = col.get(0);
225
+ return `${col.name}=${this.formatColValue(val)}`; // save some tokens by formatting (molfiles, images, etc.)
226
+ }).join(', ');
227
+ result.push(`Sample row: ${sample}`);
228
+ }
229
+
230
+ return result.join('\n');
231
+ } catch (error) {
232
+ SQLGenerationContext._lastFc = null;
233
+ const message = error instanceof Error ? error.message : String(error);
234
+ return `SQL Error: ${message}\n\nThis query failed to execute. Please revise the SQL based on the schema information.`;
235
+ }
236
+ }
237
+
238
+ /**
239
+ * Dispatches a client-side tool call to the appropriate handler.
240
+ * Returns the tool result as a string.
241
+ */
242
+ async handleToolCall(toolName: string, input: any): Promise<string> {
243
+ switch (toolName) {
244
+ case 'db_list_catalogs':
245
+ return (await this.listCatalogs()).join(', ');
246
+ case 'db_list_schemas':
247
+ return (await this.listAllSchemas(input.catalogName)).join(', ');
248
+ case 'db_list_tables': {
249
+ const res = await this.listTables(false, input.schemaName, input.catalogName);
250
+ return res.description;
251
+ }
252
+ case 'db_describe_tables':
253
+ return this.describeTables(input.tables);
254
+ case 'db_list_joins':
255
+ return this.listJoins(input.tables);
256
+ case 'db_try_sql':
257
+ return this.trySql(input.sql, input.description);
258
+ default:
259
+ return `Unknown tool: ${toolName}`;
260
+ }
261
+ }
262
+
263
+ private formatColValue(value: string | number | boolean | null | undefined | object): string {
264
+ if (value === null || value === undefined || value === '' || value === DG.FLOAT_NULL || value === DG.INT_NULL)
265
+ return 'NULL';
266
+ try {
267
+ const valueString = value?.toString();
268
+ return valueString.length > 50 ? `'${valueString.substring(0, 47)}...'` : `'${valueString}'`;
269
+ } catch {
270
+ return 'NON-STRINGIFIABLE-VALUE';
271
+ }
272
+ }
273
+
274
+ /**
275
+ * Helper: Build detailed table description
276
+ */
277
+ private buildDetailedTableDescription(table: DG.TableInfo): string {
278
+ const lines: string[] = [];
279
+ const tableMeta = getDBTableMetaData(table);
280
+ lines.push(`TABLE: ${table.friendlyName ?? table.name} (${tableMeta.rowCount ?? 'Unknown ammount of'} rows)`);
281
+ if (tableMeta.comment)
282
+ lines.push(`Comment: ${tableMeta.comment}`);
283
+ if (tableMeta.llmComment)
284
+ lines.push(`LLM Comment: ${tableMeta.llmComment}`);
285
+
286
+ lines.push('\nColumns:');
287
+
288
+ for (const col of table.columns) {
289
+ const colParts: string[] = [` ${col.name} (${col.type})`];
290
+ const colMeta = getDBColumnMetaData(col);
291
+
292
+
293
+ // not working currently, add back later
294
+ // if (col.semanticType)
295
+ // colParts.push(`[Semantic: ${col.semanticType}]`);
296
+ if (colMeta.isUnique)
297
+ colParts.push('[UNIQUE]');
298
+ if (colMeta.llmComment)
299
+ colParts.push(`- ${colMeta.llmComment}`);
300
+ else if (colMeta.comment)
301
+ colParts.push(`- ${colMeta.comment}`);
302
+ if (colMeta.min !== undefined && colMeta.max !== undefined)
303
+ colParts.push(`Range: ${colMeta.min} to ${colMeta.max}`);
304
+ if ((colMeta.values && colMeta.values.length > 0) || (colMeta.sampleValues && colMeta.sampleValues.length > 0)) {
305
+ const values = (Array.isArray(colMeta.values) ? colMeta.values : undefined) ?? colMeta.sampleValues!;
306
+ colParts.push(`Values: ${values.slice(0, 15).join(', ')}${values.length > 15 ? ', ...' : ''}`);
307
+ }
308
+ if (colMeta.uniqueCount)
309
+ colParts.push(`Unique Values Count: ${colMeta.uniqueCount}`);
310
+
311
+ lines.push(colParts.join(' '));
312
+ }
313
+
314
+ return lines.join('\n');
315
+ }
316
+
317
+ /**
318
+ * Helper: Build join description
319
+ */
320
+ private buildJoinDescription(relation: DG.DbRelationInfo): string {
321
+ const parts: string[] = [];
322
+
323
+ parts.push(`${relation.fromSchema}.${relation.fromTable}(${(relation.fromColumns ?? ['Unknown Column']).join(', ')}) -> ${relation.toSchema}.${relation.toTable}(${(relation.toColumns ?? ['Unknown Column']).join(', ')})`);
324
+
325
+ if (relation.cardinality)
326
+ parts.push(`[${relation.cardinality}]`);
327
+ if (relation.isPrimaryPath === false)
328
+ parts.push('[LEGACY - prefer other paths if available]');
329
+ if (relation.llmComment)
330
+ parts.push(`- ${relation.llmComment}`);
331
+ else if (relation.comment)
332
+ parts.push(`- ${relation.comment}`);
333
+
334
+ return parts.join(' ');
335
+ }
336
+ }