@datagrok/grokky 1.0.4
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.
- package/.eslintignore +2 -0
- package/.eslintrc.json +48 -0
- package/CHANGELOG.md +26 -0
- package/README.md +3 -0
- package/css/ai.css +200 -0
- package/detectors.js +9 -0
- package/dist/package-test.js +1738 -0
- package/dist/package-test.js.map +1 -0
- package/dist/package.js +92488 -0
- package/dist/package.js.map +1 -0
- package/dockerfiles/claude-runtime/.dockerignore +4 -0
- package/dockerfiles/claude-runtime/Dockerfile +27 -0
- package/dockerfiles/claude-runtime/container.json +5 -0
- package/dockerfiles/claude-runtime/package-lock.json +448 -0
- package/dockerfiles/claude-runtime/package.json +20 -0
- package/dockerfiles/claude-runtime/src/server.ts +273 -0
- package/dockerfiles/claude-runtime/src/types.ts +37 -0
- package/dockerfiles/claude-runtime/tsconfig.json +15 -0
- package/dockerfiles/mcp-server/Dockerfile +12 -0
- package/dockerfiles/mcp-server/container.json +1 -0
- package/dockerfiles/mcp-server/package-lock.json +1178 -0
- package/dockerfiles/mcp-server/package.json +15 -0
- package/dockerfiles/mcp-server/src/api-client.ts +100 -0
- package/dockerfiles/mcp-server/src/index.ts +155 -0
- package/dockerfiles/mcp-server/tsconfig.json +13 -0
- package/package.json +126 -0
- package/package.png +0 -0
- package/src/ai-panel.ts +174 -0
- package/src/claude-code/claude-panel.ts +34 -0
- package/src/claude-code/claude-runtime-client.ts +148 -0
- package/src/llm-utils/LLM-client.ts +251 -0
- package/src/llm-utils/combined-search.ts +162 -0
- package/src/llm-utils/creds.ts +30 -0
- package/src/llm-utils/db-index-tools.ts +642 -0
- package/src/llm-utils/deepwikiclient.ts +118 -0
- package/src/llm-utils/depr/AI-API-providers/openai-chat-completions-provider.ts +115 -0
- package/src/llm-utils/depr/AI-API-providers/openai-responses-provider.ts +108 -0
- package/src/llm-utils/depr/AI-API-providers/types.ts +106 -0
- package/src/llm-utils/depr/depr.ts +235 -0
- package/src/llm-utils/depr/embeddings.ts +58 -0
- package/src/llm-utils/depr/sql-utils.ts +377 -0
- package/src/llm-utils/indexes/biologics-index.ts +1098 -0
- package/src/llm-utils/indexes/chembl-index.ts +10074 -0
- package/src/llm-utils/indexes/dg-repository-index.ts +266 -0
- package/src/llm-utils/panel.ts +866 -0
- package/src/llm-utils/query-matching.ts +370 -0
- package/src/llm-utils/query-meta-utils.ts +106 -0
- package/src/llm-utils/script-tools.ts +784 -0
- package/src/llm-utils/sql-tools.ts +840 -0
- package/src/llm-utils/storage.ts +201 -0
- package/src/llm-utils/tableview-tools.ts +704 -0
- package/src/llm-utils/ui.ts +315 -0
- package/src/package-api.ts +83 -0
- package/src/package-test.ts +16 -0
- package/src/package.g.ts +122 -0
- package/src/package.ts +275 -0
- package/src/prompt-engine/chatgpt-assistant.ts +257 -0
- package/src/prompt-engine/interfaces.ts +170 -0
- package/src/prompt-engine/prompt-engine.ts +52 -0
- package/src/prompt-engine/rendering-tools.ts +103 -0
- package/src/prompts/is-help-request.ts +26 -0
- package/src/utils.ts +174 -0
- package/src/viewers-ai.ts +67 -0
- package/tsconfig.json +72 -0
- package/webpack.config.js +49 -0
|
@@ -0,0 +1,784 @@
|
|
|
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
|
+
}
|