@datagrok/grokky 1.0.4 → 1.1.0

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