@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,784 +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 {AIPanelFuncs, MessageType} from './panel';
6
- import {getAIAbortSubscription} from '../utils';
7
- import {ModelType, LLMClient} from './LLM-client';
8
- import {LLMCredsManager} from './creds';
9
- import {ComparisonFilter, CompoundFilter} from 'openai/resources/shared';
10
- import {LanguageModelV3FunctionTool, LanguageModelV3Message} from '@ai-sdk/provider';
11
- import {findLast} from '../utils';
12
-
13
-
14
- class ClarificationNeededError extends Error {
15
- constructor() {
16
- super('CLARIFICATION_NEEDED');
17
- }
18
- }
19
-
20
- class NoScriptGeneratedError extends Error {
21
- constructor() {
22
- super('NO_SCRIPT_GENERATED');
23
- }
24
- }
25
-
26
- type JsonPrimitive = string | number | boolean | null;
27
- type JsonValue = JsonPrimitive | JsonObject | JsonValue[];
28
- type JsonObject = { [key: string]: JsonValue };
29
-
30
- function isJsonObject(value: JsonValue | object | null | undefined): value is JsonObject {
31
- return !!value && typeof value === 'object' && !Array.isArray(value);
32
- }
33
-
34
- function getStringProp(obj: JsonObject | null | undefined, key: string): string | null {
35
- const v = obj?.[key];
36
- return typeof v === 'string' ? v : null;
37
- }
38
-
39
- function getNumberProp(obj: JsonObject | null | undefined, key: string): number | null {
40
- const v = obj?.[key];
41
- return typeof v === 'number' ? v : null;
42
- }
43
-
44
- function parseJsonObject(text: string): JsonObject | null {
45
- try {
46
- const parsed = JSON.parse(text) as JsonValue;
47
- return isJsonObject(parsed) ? parsed : null;
48
- } catch {
49
- return null;
50
- }
51
- }
52
-
53
- function isSafeJsMemberExpression(expr: string): boolean {
54
- // Allow only dotted identifiers like: grok.chem, DG, ui, grok.shell.tv
55
- // Disallow calls, indexing, quotes, spaces, operators, etc.
56
- return /^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)*$/.test(expr);
57
- }
58
-
59
-
60
- /**
61
- * Generates a Datagrok script using function calling approach with Responses API
62
- * @throws Error if script generation fails
63
- * @param prompt - User's natural language description of the script
64
- * @param language - Programming language for the script
65
- * @param options - Additional options including message history and AI panel functions
66
- */
67
- export async function generateDatagrokScript(
68
- prompt: string,
69
- language: DG.ScriptingLanguage,
70
- options: {
71
- oldMessages?: MessageType[],
72
- aiPanel?: AIPanelFuncs<MessageType>,
73
- disableVerbose?: boolean,
74
- } = {}
75
- ): Promise<string> {
76
- let aborted = false;
77
-
78
- options.aiPanel?.addUiMessage(prompt, true);
79
-
80
- // Create tool execution context
81
- const vectorStoreId = LLMCredsManager.getVectorStoreId();
82
- const context = new ScriptGenerationContext(vectorStoreId);
83
- const abortSub = getAIAbortSubscription().subscribe(() => {
84
- aborted = true;
85
- console.log('Aborting script generation as per user request');
86
- try {
87
- context.dispose();
88
- } catch {
89
- // ignore
90
- }
91
- abortSub.unsubscribe();
92
- });
93
-
94
- try {
95
- // Initialize OpenAI client
96
- // const openai = OpenAIClient.getInstance().openai;
97
- const langTool = LLMClient.getInstance();
98
- const client = langTool.aiModels.Coding;
99
-
100
- // System message with strict guidelines
101
- const systemMessage = getSystemPrompt(language, vectorStoreId);
102
-
103
- // Create a running input list we will add to over time (per Responses API docs)
104
- const input: MessageType[] = options.oldMessages ? [...options.oldMessages] : [];
105
- if (!input.length) {
106
- const systemMsg = langTool.createSystemMessage(systemMessage);
107
- input.push(systemMsg);
108
- options.aiPanel?.addEngineMessage(systemMsg);
109
- }
110
- const userMsg = langTool.createUserMessage(prompt);
111
- options.aiPanel?.addEngineMessage(userMsg);
112
- input.push(userMsg);
113
- // options.aiPanel?.addEngineMessage(systemMessage);
114
- // Define available tools
115
- const tools = getTools(language, vectorStoreId);
116
-
117
- // Function calling loop using Responses API
118
- let iterations = 0;
119
- let maxIterations = 20; // Prevent infinite loops
120
-
121
-
122
- while (iterations < maxIterations) {
123
- if (aborted) {
124
- grok.shell.info('SQL generation aborted by user.');
125
- return '';
126
- }
127
- iterations++;
128
- console.log(`\n=== Iteration ${iterations} ===`);
129
-
130
- const response = await client.doGenerate({
131
- prompt: input,
132
- tools,
133
- providerOptions: {
134
- openai: {
135
- ...(ModelType.Coding.startsWith('gpt-5') ? {reasoning: {effort: 'medium'}} : {}),
136
- }
137
- }
138
- });
139
- // The AI SDK's doGenerate puts item IDs in providerMetadata, but the
140
- // Responses API input converter only reads reasoning items from providerOptions
141
- // (tool-call has a fallback to providerMetadata, but reasoning does not).
142
- // Copy providerMetadata → providerOptions so reasoning item_references are created.
143
- const fixedContent = response.content.map((item) => {
144
- const patched = {
145
- ...item,
146
- providerOptions: (item as any).providerOptions ?? (item as any).providerMetadata,
147
- };
148
- if (item.type === 'tool-call') {
149
- return {
150
- ...patched,
151
- input: typeof item.input === 'string' ? parseJsonObject(item.input) ?? item.input : item.input
152
- };
153
- }
154
- return patched;
155
- });
156
-
157
- const formattedOutput: LanguageModelV3Message = {
158
- role: 'assistant',
159
- // @ts-ignore
160
- content: fixedContent
161
- };
162
- //const outputs: MessageType[] = response.content.map((item) => ({role: 'assistant', content: [item]} as MessageType));
163
- input.push(formattedOutput);
164
- options.aiPanel?.addEngineMessage(formattedOutput);
165
- // outputs.forEach((item) =>
166
- // options.aiPanel?.addEngineMessage(item));
167
-
168
- // Execute function calls (if any)
169
- let hadToolCalls = false;
170
- for (const call of response.content.filter((c) => c.type === 'tool-call')) {
171
- hadToolCalls = true;
172
-
173
- const functionName = call.toolName;
174
- const callId = call.toolCallId;
175
- const rawArgs = call.input ?? '{}';
176
- const args = parseJsonObject(rawArgs);
177
-
178
- if (!functionName || !callId) {
179
- const errorText = 'Error: malformed function call (missing name/call_id).';
180
- const outputItem = langTool.createToolOutputMessage(callId ?? '', functionName ?? '', errorText);
181
- if (callId) {
182
- input.push(outputItem);
183
- options.aiPanel?.addEngineMessage(outputItem);
184
- }
185
- continue;
186
- }
187
-
188
- let result = '';
189
- try {
190
- result = await executeFunction(context, functionName, language, args, options.aiPanel);
191
- } catch (e) {
192
- const msg = e instanceof Error ? e.message : String(e);
193
- result = `Error executing ${functionName}: ${msg}`;
194
- }
195
-
196
- const outputItem = langTool.createToolOutputMessage(callId, functionName, result);
197
- input.push(outputItem);
198
- options.aiPanel?.addEngineMessage(outputItem);
199
-
200
- // Clarification is a terminal action: ask the user and stop.
201
- if (functionName === 'ask_user_for_clarification')
202
- return '';
203
- }
204
-
205
- // If the model called tools, we must continue so it can consume tool outputs.
206
- if (hadToolCalls) {
207
- if (iterations >= maxIterations && options.aiPanel) {
208
- const cont = await options.aiPanel.addConfirmMessage('Maximum iterations reached. Do you want to continue generating the SQL query?');
209
- if (cont)
210
- maxIterations += 10; // reset max iterations to continue
211
- }
212
- continue;
213
- }
214
-
215
- const content = findLast(response.content, (c) => c.type === 'text')?.text!;
216
- if ((content?.length ?? 0) === 0)
217
- throw new Error('Model returned no text and no tool calls');
218
-
219
- if (content.startsWith('CLARIFICATION NEEDED:')) {
220
- const clarificationMsg = content.replace('CLARIFICATION NEEDED:', '').trim();
221
- options.aiPanel?.addUiMessage(clarificationMsg, false);
222
- return '';
223
- }
224
-
225
- if (content.startsWith('REPLY ONLY:')) {
226
- const reply = content.replace('REPLY ONLY:', '').trim();
227
- options.aiPanel?.addUiMessage(reply, false);
228
- return '';
229
- }
230
- // let sanitizedContent = content;
231
- // if (content && content)
232
-
233
- const validationError = validateScriptHeader(content, language);
234
- if (validationError) {
235
- const fixMsg = langTool.createUserMessage(`The generated script has an issue: ${validationError}. Please fix it and provide the corrected script. ALWAYS REMEMBER THAT YOU SHOULD OUTPUT THE CODE ONLY, WITHOUT ANY EXPLANATION, MARKDOWN, OR FORMATTING WITH CORRECT COMMENTS.`);
236
- input.push(fixMsg);
237
- options.aiPanel?.addEngineMessage(fixMsg);
238
- continue;
239
- }
240
-
241
- return content;
242
- }
243
-
244
- // If we exhausted iterations
245
- throw new Error('Failed to generate script: Maximum iterations reached or no valid script returned');
246
- } catch (e) {
247
- if (e instanceof ClarificationNeededError)
248
- return '';
249
- else if (e instanceof NoScriptGeneratedError)
250
- throw new Error('No script was generated based on the user request.');
251
- else {
252
- const msg = e instanceof Error ? e.message : String(e);
253
- throw new Error(`Script generation failed: ${msg}`);
254
- }
255
- } finally {
256
- abortSub.unsubscribe();
257
- context.dispose();
258
- }
259
- }
260
-
261
- /**
262
- * Generates the system prompt based on language
263
- */
264
- function getSystemPrompt(language: DG.ScriptingLanguage, vectorStoreId: string | null): string {
265
- const languageSpecifics = getLanguageSpecifics(language);
266
-
267
- return `You are an expert Datagrok script developer specializing in ${language.toUpperCase()}. Your task is to generate production-ready Datagrok scripts based on user requirements.
268
-
269
- IN CASE OF JAVASCRIPT SCRIPTS - NEVER USE TYPESCRIPT SYNTAX OR FEATURES, plain JAVASCRIPT ONLY.
270
- YOUR RESPONSE CODE MUST BE STANDALONE, NO IMPORTS OR EXPORTS. ALL THAT IS AVAILABLE YOU CAN ASSUME IS ALREADY IMPORTED IN THE ENVIRONMENT.
271
-
272
- Your name is Datagrok Script Expert.
273
-
274
- CRITICAL SCRIPT FORMAT REQUIREMENTS:
275
- ${languageSpecifics.headerFormat}
276
-
277
- AVAILABLE LIBRARIES AND APIS:
278
- ${languageSpecifics.availableLibraries}
279
-
280
- WORKFLOW:
281
- 1. Analyze the user's request thoroughly
282
- 2. Identify required parameters and decide which must be script inputs.
283
- - If the user did not specify required parameters (e.g., "aggregate the table by given column"), you MUST infer that these are missing and MUST become explicit script inputs.
284
- - Typical examples of required parameters that should become inputs:
285
- * group-by column(s)
286
- * value/measure column(s)
287
- * aggregation function(s) (sum/avg/min/max/count/etc.)
288
- * filtering conditions, date ranges, thresholds
289
- * output shape (dataframe/column/graphics) when not obvious
290
- 3. If any required parameter is still ambiguous (too many plausible interpretations), ask clarifying questions and STOP.
291
- - Use the tool ask_user_for_clarification.
292
- - Ask only the minimum questions needed to proceed.
293
- - The clarification questions MUST directly map to future #input lines (columns/strings/numbers/booleans).
294
- - After asking for clarification, DO NOT generate code in the same turn.
295
- 4. Use search_documentation to understand Datagrok APIs and features (MANDATORY before using any Datagrok-specific API)
296
- 5. Use find_similar_script_samples to find code examples for similar functionality (HIGHLY RECOMMENDED)
297
- 6. (JavaScript only) Before using any DG/grok/ui member that is NOT directly present in the examples you found, verify it exists:
298
- - Call list_js_members on the parent object/namespace (e.g., list_js_members("grok.chem") before using grok.chem.sketcher)
299
- - If the member is not present, do NOT use it; pick an alternative from docs/examples or ask for clarification.
300
- 6.1 (JavaScript only, if available) Before using any Datagrok JS API method/property (e.g., grok.data.demo, DG.DataFrame.fromCsv, ui.dialog), you ALWAYS MUST (!!!!!) check it exists with search_js_api_sources.
301
- - This tool returns source code chunks from the datagrok js-api; use it to verify the API surface.
302
- - If the member does not appear in the returned source chunks, do NOT use it; pick an alternative or ask for clarification.
303
- 7. Generate the complete script with proper header comments
304
- 8. Validate the script has all required annotations
305
- 9. Return ONLY the complete script code (plain text; no markdown, no code fences, no explanations)
306
-
307
-
308
- CRITICAL RULES:
309
- - ALWAYS include proper header comments with #name, #description, #language, #input, and #output annotations
310
- - Treat any user-specified or clarified parameters as #input annotations (do not hardcode them unless the user explicitly wants a fixed constant)
311
- - NEVER hallucinate API methods or properties - ALWAYS search documentation first
312
- - For any language: ALWAYS use find_similar_script_samples before writing code that uses DG, grok, or ui namespaces
313
- - For JavaScript: if you use a DG/grok/ui method/property that you did not see in examples, you MUST first verify it exists using list_js_members
314
- - Input columns should have semantic types when relevant (e.g., {semType: Molecule} for molecular data)
315
- - Common script patterns:
316
- * Data transformation: input dataframe + column(s) → output dataframe
317
- * Column calculation: input dataframe + column(s) → output column
318
- * Visualization: input dataframe + params → output graphics/viewer
319
- * Analysis: input dataframe → output string/value
320
- - Use precise semantic types: Molecule, Sequence, Cell Line, etc.
321
- - ALWAYS test your understanding by searching documentation before implementation
322
- - If you cannot generate a valid script after research, use ask_user_for_clarification${vectorStoreId ? '\n- Documentation search is MANDATORY for any Datagrok-specific functionality' : ''}${vectorStoreId && language === 'javascript' ? '\n- For JavaScript, you MUST use search_js_api_sources to verify JS API members before use' : ''}
323
- - If the user is just asking a question or chatting (not requesting a script), respond with "REPLY ONLY: [your response]"
324
- - Final output MUST be only the script code. Do not include markdown, bullets, backticks, headings, or any extra text.
325
- - THE SCRIPT YOU GENERATE MUST BE a script that is run directly, not a function.
326
- - MAKE SURE YOU DO NOT REDECLARE THE VARIABLES THAT ARE ALREADY DECLARED IN THE HEADER COMMENTS AS INPUTS (the output variable you MUST DECLARE). you can assume that input variables are already declared!!!!.
327
- - Avalialable Variable types: dataframe, column, string, int, double, boolean, graphics, viewer, list, dynamic. DO NOT USE ANY OTHER VARIABLE TYPES (except if seen in examples)!!!!
328
-
329
- RESPONSE MODES:
330
- 1. SCRIPT MODE (default): Return complete script code with header comments
331
- 2. REPLY ONLY MODE: Start response with "REPLY ONLY:" for non-script questions
332
- 3. CLARIFICATION MODE: Use ask_user_for_clarification tool when essential info is missing, then stop.
333
-
334
- When you have the final script ready, respond with ONLY the complete script code including header comments (no markdown code blocks, no extra explanation).
335
-
336
- NEVER IMPORT ANYTHING in JAVASCRIPT SCRIPTS, In python/R/Julia/Matlab scripts, use only standard libraries mentioned in available libraries section.
337
- NEVER EXPORT ANYTHING
338
- NEVER RETURN ANYTHING. IF YOU HAVE AN OUTPUT, You just assign your output variable as per the header comments
339
- for example:
340
- //output: dataframe result [Output description]
341
- result = ...
342
-
343
- ALWAYS USE DOCUMENTATION SEARCH AND SIMILAR SCRIPTS SEARCH BEFORE outputing final result. DO NOT ASSUME STUFF!!!!
344
- `;
345
- }
346
-
347
- /**
348
- * Gets language-specific information
349
- */
350
- function getLanguageSpecifics(language: DG.ScriptingLanguage): {
351
- headerFormat: string,
352
- availableLibraries: string,
353
- commentPrefix: string
354
- } {
355
- switch (language) {
356
- case 'javascript':
357
- return {
358
- commentPrefix: '//',
359
- headerFormat: `JavaScript scripts MUST start with these comment annotations:
360
- //name: [Category] | [Script Name]
361
- //description: [Brief description]
362
- //language: javascript
363
- //input: dataframe table [Description of dataframe input]
364
- //input: column col {semType: [SemanticType]} [Column description]
365
- //output: dataframe result [Output description]
366
-
367
- Example:
368
- //name: Transform | Calculate Descriptors
369
- //description: Calculates molecular descriptors
370
- //language: javascript
371
- //input: dataframe table
372
- //input: column molecules {semType: Molecule}
373
- //output: dataframe descriptors`,
374
- availableLibraries: `- Full Datagrok JavaScript API via DG, grok, and ui namespaces
375
- - DG.DataFrame, DG.Column, DG.Viewer for data manipulation
376
- - grok.shell, grok.data, grok.chem for platform features
377
- - ui.div, ui.button, ui.input for UI components
378
- - MANDATORY: Search documentation and find similar samples before using any API`
379
- };
380
- case 'python':
381
- return {
382
- commentPrefix: '#',
383
- headerFormat: `Python scripts MUST start with these comment annotations:
384
- #name: [Category] | [Script Name]
385
- #description: [Brief description]
386
- #language: python
387
- #input: dataframe table [Description]
388
- #input: string column {semType: [Type]} [Description]
389
- #output: dataframe result [Description]
390
-
391
- Example:
392
- #name: Chemistry | Gasteiger Partial Charges
393
- #description: RDKit-based script for calculating charges
394
- #language: python
395
- #input: string mol = "CCO" {semType: Molecule} [Molecule in SMILES]
396
- #output: graphics charges [The Gasteiger partial charges]`,
397
- availableLibraries: `- rdkit: Full RDKit library for chemistry
398
- - pandas: DataFrame operations
399
- - numpy: Numerical operations
400
- - Standard Python libraries`
401
- };
402
- case 'r':
403
- return {
404
- commentPrefix: '#',
405
- headerFormat: `R scripts MUST start with these comment annotations:
406
- #name: [Category] | [Script Name]
407
- #description: [Brief description]
408
- #language: r
409
- #input: dataframe table
410
- #input: column col {semType: [Type]}
411
- #output: dataframe result`,
412
- availableLibraries: `- Standard R libraries and packages
413
- - Data manipulation with data.frame, dplyr
414
- - Statistical functions`
415
- };
416
- case 'julia':
417
- return {
418
- commentPrefix: '#',
419
- headerFormat: `Julia scripts MUST start with these comment annotations:
420
- #name: [Category] | [Script Name]
421
- #description: [Brief description]
422
- #language: julia
423
- #input: dataframe table
424
- #output: dataframe result`,
425
- availableLibraries: `- Standard Julia packages
426
- - DataFrames.jl for data manipulation`
427
- };
428
- case 'octave':
429
- return {
430
- commentPrefix: '%',
431
- headerFormat: `MATLAB scripts MUST start with these comment annotations:
432
- %name: [Category] | [Script Name]
433
- %description: [Brief description]
434
- %language: matlab
435
- %input: dataframe table
436
- %output: dataframe result`,
437
- availableLibraries: `- Standard MATLAB functions and toolboxes
438
- - Table and array operations`
439
- };
440
- default:
441
- throw new Error(`Unsupported language: ${language}`);
442
- }
443
- }
444
-
445
- /**
446
- * Defines tools available for script generation
447
- */
448
- function getTools(language: DG.ScriptingLanguage, vectorStoreId: string | null) {
449
- const tools: LanguageModelV3FunctionTool[] = [
450
- {
451
- type: 'function',
452
- name: 'ask_user_for_clarification',
453
- description: 'Ask the user for clarification when the requirements are vague or missing critical information. Use this when you need to know: required inputs, expected outputs, specific parameters, data types, or any other essential details.',
454
- inputSchema: {
455
- type: 'object',
456
- properties: {
457
- question: {
458
- type: 'string',
459
- description: 'Clear, specific question(s) for the user in markdown format. Be professional and helpful.'
460
- }
461
- },
462
- required: ['question'],
463
- additionalProperties: false
464
- },
465
- strict: true
466
- },
467
- {
468
- type: 'function',
469
- name: 'reply_to_user',
470
- description: 'Send a message to the user to explain your reasoning, provide updates, or answer questions. Use this for intermediate communication, NOT for the final script.',
471
- inputSchema: {
472
- type: 'object',
473
- properties: {
474
- message: {
475
- type: 'string',
476
- description: 'Your message to the user in markdown format'
477
- }
478
- },
479
- required: ['message'],
480
- additionalProperties: false
481
- },
482
- strict: true
483
- }
484
- ];
485
-
486
- // Add documentation search if vector store is available
487
- if (vectorStoreId) {
488
- tools.push({
489
- type: 'function',
490
- name: 'search_documentation',
491
- description: 'Search Datagrok documentation and API references. MANDATORY before using any Datagrok API. Returns detailed information about classes, methods, properties, and usage examples.',
492
- inputSchema: {
493
- type: 'object',
494
- properties: {
495
- query: {
496
- type: 'string',
497
- description: 'Detailed search query describing what API or feature you need to understand. Include context about what you are trying to do.'
498
- },
499
- maxResults: {
500
- type: 'integer',
501
- description: 'Maximum number of results to return (1-50)',
502
- default: 4
503
- }
504
- },
505
- required: ['query', 'maxResults'],
506
- additionalProperties: false
507
- },
508
- strict: true
509
- });
510
- }
511
-
512
- // Add API sample search for any language
513
- tools.push({
514
- type: 'function',
515
- name: 'find_similar_script_samples',
516
- description: 'Find similar scripts code samples from Datagrok codebase. HIGHLY RECOMMENDED before writing any code using DG, grok, or ui APIs. Returns real working examples.',
517
- inputSchema: {
518
- type: 'object',
519
- properties: {
520
- description: {
521
- type: 'string',
522
- description: 'Description of the functionality you want to implement'
523
- }
524
- },
525
- required: ['description'],
526
- additionalProperties: false
527
- },
528
- strict: true
529
- });
530
-
531
- if (language === 'javascript') {
532
- if (vectorStoreId) {
533
- tools.push({
534
- type: 'function',
535
- name: 'search_js_api_sources',
536
- description: 'Search Datagrok JavaScript API source code (js-api) to verify that a method/property exists. Use this before calling any grok/ui/DG members that are not already confirmed by examples. Returns relevant source chunks.',
537
- inputSchema: {
538
- type: 'object',
539
- properties: {
540
- query: {
541
- type: 'string',
542
- description: 'Search query for the JS API source code (e.g., "grok.data.demo", "DG.DataFrame.fromCsv", "ui.dialog")'
543
- },
544
- maxResults: {
545
- type: 'integer',
546
- description: 'Maximum number of results to return (1-50)',
547
- default: 4
548
- }
549
- },
550
- required: ['query', 'maxResults'],
551
- additionalProperties: false
552
- },
553
- strict: true
554
- });
555
- }
556
- tools.push({
557
- type: 'function',
558
- name: 'list_js_members',
559
- description: 'List enumerable members (Object.keys) of a JavaScript object/namespace to verify methods/properties exist. Use this to avoid hallucinating APIs. Input must be a dotted identifier expression like "grok.chem" or "DG" or "ui".',
560
- inputSchema: {
561
- type: 'object',
562
- properties: {
563
- expression: {
564
- type: 'string',
565
- description: 'A dotted identifier expression referring to an in-scope object/namespace (e.g., "grok.chem", "grok.shell", "DG", "ui", "grok.dapi.entities", etc)'
566
- }
567
- },
568
- required: ['expression'],
569
- additionalProperties: false
570
- },
571
- strict: true
572
- });
573
- }
574
-
575
-
576
- return tools;
577
- }
578
-
579
- /**
580
- * Executes a function call from the model
581
- */
582
- async function executeFunction(
583
- context: ScriptGenerationContext,
584
- functionName: string,
585
- language: DG.ScriptingLanguage,
586
- args: JsonObject | null,
587
- aiPanel?: AIPanelFuncs<MessageType>
588
- ): Promise<string> {
589
- switch (functionName) {
590
- case 'search_documentation':
591
- aiPanel?.addUiMessage(`Searching documentation for "${getStringProp(args, 'query') ?? ''}"...`, false);
592
- return await context.searchDocumentation(getStringProp(args, 'query') ?? '', getNumberProp(args, 'maxResults'));
593
-
594
- case 'find_similar_script_samples':
595
- aiPanel?.addUiMessage('Looking for similar JavaScript samples...', false);
596
- return await context.findSimilarScriptSamples(getStringProp(args, 'description') ?? '', language);
597
-
598
- case 'search_js_api_sources':
599
- aiPanel?.addUiMessage(`Searching JS API resources for "${getStringProp(args, 'query') ?? ''}"...`, false);
600
- return await context.searchJsApiSources(getStringProp(args, 'query') ?? '', getNumberProp(args, 'maxResults'));
601
-
602
- case 'list_js_members':
603
- aiPanel?.addUiMessage(`Checking JS members for "${getStringProp(args, 'expression') ?? ''}"...`, false);
604
- return context.listJsMembers(getStringProp(args, 'expression') ?? '');
605
-
606
- case 'ask_user_for_clarification':
607
- // Show question to user through panel
608
- if (aiPanel)
609
- aiPanel.addUiMessage(getStringProp(args, 'question') ?? '', false);
610
-
611
- return 'Question shown to user. Wait for user response before proceeding.';
612
-
613
- case 'reply_to_user':
614
- // Show message to user through panel
615
- if (aiPanel)
616
- aiPanel.addUiMessage(getStringProp(args, 'message') ?? '', false);
617
-
618
- return 'Message sent to user.';
619
-
620
- default:
621
- throw new Error(`Unknown function: ${functionName}`);
622
- }
623
- }
624
-
625
- /**
626
- * Validates script header format
627
- */
628
- function validateScriptHeader(script: string, language: DG.ScriptingLanguage): string | null {
629
- const lines = script.split('\n');
630
- const commentPrefix = getLanguageSpecifics(language).commentPrefix;
631
-
632
- // Check for required annotations
633
- let hasName = false;
634
- let hasDescription = false;
635
- let hasLanguage = false;
636
- let hasOutput = false;
637
- let iter = 0;
638
- if (lines[0]?.startsWith('```'))
639
- return 'Script should not be enclosed in markdown code fences, there SHOULD BE NO ``` OR ANY MARKDOWN!!! CODE ONLY!!!';
640
- for (const line of lines.slice(0, 20)) { // Check first 20 lines
641
- const trimmed = line.trim();
642
- if (trimmed.startsWith(`${commentPrefix}name:`) && iter === 0) hasName = true;
643
- if (trimmed.startsWith(`${commentPrefix}description:`)) hasDescription = true;
644
- if (trimmed.startsWith(`${commentPrefix}language:`)) hasLanguage = true;
645
- if (trimmed.startsWith(`${commentPrefix}output:`)) hasOutput = true;
646
- iter++;
647
- }
648
-
649
- if (!hasName) return 'Missing required annotation: name. SCRIPT MUST start with name annotation.';
650
- if (!hasDescription) return 'Missing required annotation: description';
651
- if (!hasLanguage) return 'Missing required annotation: language';
652
- if (!hasOutput) return 'Missing required annotation: output';
653
-
654
- // check if last line includes return statement or output assignment
655
- if (lines[lines.length - 1].includes('return '))
656
- return 'Script should not use return statement. Assign output variable as per header comments.';
657
- // Input is optional for some scripts
658
-
659
- return null; // Valid
660
- }
661
-
662
- /**
663
- * Context class that manages tool execution for script generation
664
- */
665
- export class ScriptGenerationContext {
666
- constructor(private vectorStoreId: string | null) {}
667
-
668
- dispose() {
669
- // Cleanup if needed
670
- }
671
-
672
- async searchDocumentation(query: string, maxResults: number | null, filterOptions?: {
673
- fileExtension?: string,
674
- firstFolder?: string, // useful for specific searches, like "js-api", "libraries", "packages" etc.
675
- secondFolder?: string, // useful for specific searches, inside of the firstFolder, like specific plugin, library, etc.
676
- }): Promise<string> {
677
- if (!this.vectorStoreId)
678
- return 'Documentation search is not available. Vector store ID not configured.';
679
-
680
- if (!query || query.trim().length === 0)
681
- return 'Error: empty documentation search query.';
682
-
683
- try {
684
- const openai = LLMClient.getInstance().openai;
685
- const filterObject = {filters: [] as ComparisonFilter[], type: 'and'} satisfies CompoundFilter;
686
- if (filterOptions) {
687
- if (filterOptions.fileExtension) {
688
- filterObject.filters.push({
689
- key: 'originalExtension',
690
- value: filterOptions.fileExtension,
691
- type: 'eq',
692
- });
693
- }
694
- if (filterOptions.firstFolder) {
695
- filterObject.filters.push({
696
- key: 'firstParentFolder',
697
- value: filterOptions.firstFolder,
698
- type: 'eq',
699
- });
700
- }
701
- if (filterOptions.secondFolder) {
702
- filterObject.filters.push({
703
- key: 'secondParentFolder',
704
- value: filterOptions.secondFolder,
705
- type: 'eq',
706
- });
707
- }
708
- }
709
- const searchData = await openai.vectorStores.search(this.vectorStoreId, {
710
- query,
711
- max_num_results: maxResults ?? 4,
712
- rewrite_query: false,
713
- filters: filterObject.filters.length > 0 ? filterObject : undefined,
714
- });
715
-
716
- if (!searchData.data || searchData.data.length === 0)
717
- return 'No relevant documentation found for this query.';
718
-
719
- let formattedResults = `Found ${searchData.data.length} relevant documentation sections:\n\n`;
720
- for (const item of searchData.data) {
721
- formattedResults += `**Source**: ${item.filename} (score: ${item.score.toFixed(2)})\n`;
722
- for (const content of item.content) {
723
- if (content.type === 'text')
724
- formattedResults += `${content.text}\n\n`;
725
- }
726
- formattedResults += '---\n\n';
727
- }
728
- return formattedResults;
729
- } catch (e) {
730
- const msg = e instanceof Error ? e.message : String(e);
731
- return `Error searching documentation: ${msg}`;
732
- }
733
- }
734
-
735
- async findSimilarScriptSamples(description: string, language?: DG.ScriptingLanguage): Promise<string> {
736
- const similarSampels = await grok.ai.searchEntities(description, 0.3, 10, ['Script']);
737
- if (similarSampels.length === 0)
738
- return 'No similar script samples found.';
739
- const scripts = similarSampels
740
- .filter((e) => e instanceof DG.Script && (!language || e.language === language)) as DG.Script[];
741
- if (scripts.length === 0)
742
- return 'No similar script samples found.';
743
- let result = `Found ${scripts.length} similar script samples:\n\n`;
744
- for (const script of scripts) {
745
- result += `**Name**: ${script.name}\n`;
746
- result += `**Description**: ${script.description}\n`;
747
- result += `**Code**:\n${script.script}\n\n---\n\n`;
748
- }
749
- return result;
750
- }
751
-
752
- async searchJsApiSources(query: string, maxResults: number | null): Promise<string> {
753
- if (!this.vectorStoreId)
754
- return 'JS API source search is not available. Vector store ID not configured.';
755
-
756
- if (!query || query.trim().length === 0)
757
- return 'Error: empty JS API source search query.';
758
-
759
- return await this.searchDocumentation(query, maxResults, {
760
- firstFolder: 'js-api',
761
- });
762
- }
763
-
764
- listJsMembers(expression: string): string {
765
- if (!expression || expression.trim().length === 0)
766
- return 'Error: expression is required.';
767
- const expr = expression.trim();
768
- if (!isSafeJsMemberExpression(expr))
769
- return 'Error: unsafe expression. Only dotted identifiers like "grok.chem" are allowed. consider use js-api search instead';
770
-
771
- try {
772
- // eslint-disable-next-line no-eval
773
- const value = eval(expr) as object | null | undefined;
774
- if (value === null || value === undefined)
775
- return 'Error: expression evaluated to null/undefined.';
776
-
777
- const keys = Object.keys(value as Record<string, string | number | boolean | null | object>);
778
- return JSON.stringify(keys);
779
- } catch (e) {
780
- const msg = e instanceof Error ? e.message : String(e);
781
- return `Error evaluating expression: ${msg}`;
782
- }
783
- }
784
- }