@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.
Files changed (65) hide show
  1. package/.eslintignore +2 -0
  2. package/.eslintrc.json +48 -0
  3. package/CHANGELOG.md +26 -0
  4. package/README.md +3 -0
  5. package/css/ai.css +200 -0
  6. package/detectors.js +9 -0
  7. package/dist/package-test.js +1738 -0
  8. package/dist/package-test.js.map +1 -0
  9. package/dist/package.js +92488 -0
  10. package/dist/package.js.map +1 -0
  11. package/dockerfiles/claude-runtime/.dockerignore +4 -0
  12. package/dockerfiles/claude-runtime/Dockerfile +27 -0
  13. package/dockerfiles/claude-runtime/container.json +5 -0
  14. package/dockerfiles/claude-runtime/package-lock.json +448 -0
  15. package/dockerfiles/claude-runtime/package.json +20 -0
  16. package/dockerfiles/claude-runtime/src/server.ts +273 -0
  17. package/dockerfiles/claude-runtime/src/types.ts +37 -0
  18. package/dockerfiles/claude-runtime/tsconfig.json +15 -0
  19. package/dockerfiles/mcp-server/Dockerfile +12 -0
  20. package/dockerfiles/mcp-server/container.json +1 -0
  21. package/dockerfiles/mcp-server/package-lock.json +1178 -0
  22. package/dockerfiles/mcp-server/package.json +15 -0
  23. package/dockerfiles/mcp-server/src/api-client.ts +100 -0
  24. package/dockerfiles/mcp-server/src/index.ts +155 -0
  25. package/dockerfiles/mcp-server/tsconfig.json +13 -0
  26. package/package.json +126 -0
  27. package/package.png +0 -0
  28. package/src/ai-panel.ts +174 -0
  29. package/src/claude-code/claude-panel.ts +34 -0
  30. package/src/claude-code/claude-runtime-client.ts +148 -0
  31. package/src/llm-utils/LLM-client.ts +251 -0
  32. package/src/llm-utils/combined-search.ts +162 -0
  33. package/src/llm-utils/creds.ts +30 -0
  34. package/src/llm-utils/db-index-tools.ts +642 -0
  35. package/src/llm-utils/deepwikiclient.ts +118 -0
  36. package/src/llm-utils/depr/AI-API-providers/openai-chat-completions-provider.ts +115 -0
  37. package/src/llm-utils/depr/AI-API-providers/openai-responses-provider.ts +108 -0
  38. package/src/llm-utils/depr/AI-API-providers/types.ts +106 -0
  39. package/src/llm-utils/depr/depr.ts +235 -0
  40. package/src/llm-utils/depr/embeddings.ts +58 -0
  41. package/src/llm-utils/depr/sql-utils.ts +377 -0
  42. package/src/llm-utils/indexes/biologics-index.ts +1098 -0
  43. package/src/llm-utils/indexes/chembl-index.ts +10074 -0
  44. package/src/llm-utils/indexes/dg-repository-index.ts +266 -0
  45. package/src/llm-utils/panel.ts +866 -0
  46. package/src/llm-utils/query-matching.ts +370 -0
  47. package/src/llm-utils/query-meta-utils.ts +106 -0
  48. package/src/llm-utils/script-tools.ts +784 -0
  49. package/src/llm-utils/sql-tools.ts +840 -0
  50. package/src/llm-utils/storage.ts +201 -0
  51. package/src/llm-utils/tableview-tools.ts +704 -0
  52. package/src/llm-utils/ui.ts +315 -0
  53. package/src/package-api.ts +83 -0
  54. package/src/package-test.ts +16 -0
  55. package/src/package.g.ts +122 -0
  56. package/src/package.ts +275 -0
  57. package/src/prompt-engine/chatgpt-assistant.ts +257 -0
  58. package/src/prompt-engine/interfaces.ts +170 -0
  59. package/src/prompt-engine/prompt-engine.ts +52 -0
  60. package/src/prompt-engine/rendering-tools.ts +103 -0
  61. package/src/prompts/is-help-request.ts +26 -0
  62. package/src/utils.ts +174 -0
  63. package/src/viewers-ai.ts +67 -0
  64. package/tsconfig.json +72 -0
  65. package/webpack.config.js +49 -0
@@ -0,0 +1,273 @@
1
+ import {Hono} from 'hono';
2
+ import {serve} from '@hono/node-server';
3
+ import {createNodeWebSocket} from '@hono/node-ws';
4
+ import {query} from '@anthropic-ai/claude-agent-sdk';
5
+ import type {SDKMessage} from '@anthropic-ai/claude-agent-sdk';
6
+ import type {UserMessage, OutgoingMessage, ToolInputs, McpInputs, ToolName, McpName} from './types';
7
+
8
+ const WORKSPACE = process.env['CLAUDE_WORKSPACE'] || '/workspace';
9
+ const PORT = 5355;
10
+ const MAX_SESSIONS = 200;
11
+
12
+ const DATAGROK_PROMPT = `\
13
+ You are Datagrok Code Assistant — an AI coding agent embedded in the Datagrok data analytics platform.
14
+ You have full access to the Datagrok public repository at ${WORKSPACE}, including the JS API source,
15
+ 70+ extension packages, API samples, and documentation.
16
+
17
+ NEVER guess API methods, property names, or function signatures — ALWAYS search the codebase first.
18
+ Key lookup paths: js-api/src/ (core API), packages/ApiSamples/ (usage examples), help/ (docs).
19
+
20
+ ## Code Execution
21
+
22
+ When the user asks you to **do** something (add a viewer, modify data, run a script, etc.):
23
+ 1. FIRST search the codebase to find the correct API (method names, property names, option keys).
24
+ 2. THEN emit the code in a \`\`\`datagrok-exec fenced block — this is the ONLY way code gets executed.
25
+
26
+ NEVER emit a \`\`\`datagrok-exec block with guessed or unverified API calls.
27
+ Regular \`\`\`javascript blocks are for explanations only and will NOT run.
28
+
29
+ ### Globals in \`\`\`datagrok-exec blocks
30
+
31
+ | Variable | Type | When available |
32
+ |----------|------|----------------|
33
+ | \`grok\` | module | Always |
34
+ | \`ui\` | module | Always |
35
+ | \`DG\` | module | Always |
36
+ | \`view\` | \`DG.ViewBase\` | Always — check \`view.type\` for specific view type |
37
+ | \`t\` | \`DG.DataFrame\` | Only in TableView (\`view.type === 'TableView'\`) |
38
+
39
+ ### Rules
40
+ - \`await\` works directly — the block runs in an async context.
41
+ - Keep blocks short and focused: one action per block.
42
+ - Do NOT import \`grok\`, \`ui\`, or \`DG\` — they are already in scope.
43
+ - Prefer the JS API over console commands or scripts.
44
+ - Keep responses concise.`;
45
+
46
+ const sessions = new Map<string, string>();
47
+
48
+ function storeSession(clientId: string, sdkId: string): void {
49
+ sessions.delete(clientId);
50
+ sessions.set(clientId, sdkId);
51
+ if (sessions.size > MAX_SESSIONS)
52
+ sessions.delete(sessions.keys().next().value!);
53
+ }
54
+
55
+ function getSession(clientId: string): string | undefined {
56
+ const sid = sessions.get(clientId);
57
+ if (sid !== undefined) {
58
+ sessions.delete(clientId);
59
+ sessions.set(clientId, sid);
60
+ }
61
+ return sid;
62
+ }
63
+
64
+ async function* promptStream(message: string) {
65
+ yield {
66
+ type: 'user' as const,
67
+ session_id: '',
68
+ message: {role: 'user' as const, content: message},
69
+ parent_tool_use_id: null,
70
+ };
71
+ }
72
+
73
+ function rewriteForDocker(url: string): string {
74
+ return url.replace('//localhost', '//host.docker.internal');
75
+ }
76
+
77
+ function buildMcpHeaders(apiKey?: string, apiUrl?: string): Record<string, string> {
78
+ const headers: Record<string, string> = {};
79
+ if (apiKey) {
80
+ headers['Authorization'] = apiKey;
81
+ headers['x-user-api-key'] = apiKey;
82
+ }
83
+ if (apiUrl)
84
+ headers['x-datagrok-api-url'] = apiUrl;
85
+ return headers;
86
+ }
87
+
88
+ function apiUrlFromMcpUrl(mcpUrl: string): string | undefined {
89
+ const idx = mcpUrl.indexOf('/docker/containers/proxy/');
90
+ return idx > 0 ? mcpUrl.substring(0, idx) : undefined;
91
+ }
92
+
93
+ function buildOptions(resume?: string, apiKey?: string, mcpServerUrl?: string) {
94
+ const mcpUrl = mcpServerUrl || '';
95
+ const apiUrl = mcpUrl ? apiUrlFromMcpUrl(mcpUrl) : undefined;
96
+ return {
97
+ systemPrompt: DATAGROK_PROMPT,
98
+ allowedTools: ['Read', 'Glob', 'Grep', 'Edit', 'Write', 'Bash', 'WebSearch', 'WebFetch'],
99
+ ...(mcpUrl ? {
100
+ mcpServers: {
101
+ datagrok: {
102
+ type: 'http' as const,
103
+ url: mcpUrl,
104
+ headers: buildMcpHeaders(apiKey, apiUrl),
105
+ },
106
+ },
107
+ } : {}),
108
+ permissionMode: 'bypassPermissions' as const,
109
+ allowDangerouslySkipPermissions: true,
110
+ model: 'opus' as const,
111
+ includePartialMessages: true,
112
+ cwd: WORKSPACE,
113
+ ...(resume ? {resume} : {}),
114
+ };
115
+ }
116
+
117
+ const toolFormatters: {[K in ToolName]: (i: ToolInputs[K]) => string} = {
118
+ Read: (i) => `Read ${i.file_path ?? ''}`,
119
+ Write: (i) => `Write ${i.file_path ?? ''}`,
120
+ Edit: (i) => `Edit ${i.file_path ?? ''}`,
121
+ Bash: (i) => `Bash: ${(i.command ?? '').slice(0, 120)}`,
122
+ Glob: (i) => `Glob ${i.pattern ?? ''} ${i.path ? 'in ' + i.path : ''}`.trim(),
123
+ Grep: (i) => `Grep '${i.pattern ?? ''}' ${i.path ? 'in ' + i.path : ''}`.trim(),
124
+ WebSearch: (i) => `WebSearch: ${i.query ?? ''}`,
125
+ WebFetch: (i) => `WebFetch: ${i.url ?? ''}`,
126
+ };
127
+
128
+ const mcpFormatters: {[K in McpName]: (i: McpInputs[K]) => string} = {
129
+ call_function: (i) => `Call ${i.name ?? 'function'}`,
130
+ list_functions: (i) => `List functions${i.filter ? ': ' + i.filter : ''}`,
131
+ get_function: (i) => `Get function ${i.id ?? ''}`,
132
+ list_files: (i) => `list files ${i.path ?? ''}`.trim(),
133
+ download_file: (i) => `download file ${i.path ?? ''}`.trim(),
134
+ upload_file: (i) => `upload file ${i.path ?? ''}`.trim(),
135
+ };
136
+
137
+ function toolSummary(name: string, input: Record<string, unknown>): string {
138
+ if (name in toolFormatters)
139
+ return toolFormatters[name as ToolName](input as ToolInputs[ToolName]);
140
+ const mcp = name.replace(/^mcp__[^_]+__/, '');
141
+ if (mcp !== name) {
142
+ if (mcp in mcpFormatters)
143
+ return mcpFormatters[mcp as McpName](input as McpInputs[McpName]);
144
+ return mcp.replace(/_/g, ' ');
145
+ }
146
+ return name;
147
+ }
148
+
149
+ function extractResult(evt: any): string | null {
150
+ const r = evt.tool_use_result ?? evt.tool_result;
151
+ if (!r)
152
+ return null;
153
+ if (typeof r === 'string')
154
+ return r || null;
155
+ if (Array.isArray(r))
156
+ return r.filter((b: any) => b.type === 'text').map((b: any) => b.text).join('\n') || null;
157
+ return null;
158
+ }
159
+
160
+ interface WsSender {
161
+ send(data: string): void;
162
+ }
163
+
164
+ function emit(ws: WsSender, msg: OutgoingMessage): void {
165
+ ws.send(JSON.stringify(msg));
166
+ }
167
+
168
+ function forwardEvent(ws: WsSender, sid: string, event: SDKMessage): void {
169
+ const e = event as any;
170
+ switch (event.type) {
171
+ case 'system':
172
+ if (event.subtype === 'init' && e.session_id)
173
+ storeSession(sid, e.session_id);
174
+ break;
175
+ case 'assistant':
176
+ for (const block of e.message?.content ?? []) {
177
+ if (block.type === 'tool_use')
178
+ emit(ws, {type: 'tool_activity', sessionId: sid, summary: toolSummary(block.name, block.input ?? {})});
179
+ }
180
+ break;
181
+ case 'user': {
182
+ const content = extractResult(e);
183
+ if (content)
184
+ emit(ws, {type: 'tool_result', sessionId: sid, content});
185
+ break;
186
+ }
187
+ case 'stream_event':
188
+ if (e.event?.delta?.type === 'text_delta' && e.event.delta.text)
189
+ emit(ws, {type: 'chunk', sessionId: sid, content: e.event.delta.text});
190
+ break;
191
+ case 'tool_progress':
192
+ emit(ws, {type: 'tool_activity', sessionId: sid, summary: `Running ${e.tool_name ?? ''}…`});
193
+ break;
194
+ case 'tool_use_summary':
195
+ emit(ws, {type: 'tool_activity', sessionId: sid, summary: e.summary ?? ''});
196
+ break;
197
+ case 'result':
198
+ if (e.subtype === 'success')
199
+ emit(ws, {type: 'final', sessionId: sid, content: e.result || ''});
200
+ else
201
+ emit(ws, {type: 'error', sessionId: sid, message: (e.errors ?? []).join(', ') || e.subtype || 'unknown'});
202
+ break;
203
+ }
204
+ }
205
+
206
+ async function handleMessage(ws: WsSender, data: UserMessage): Promise<void> {
207
+ const sid = data.sessionId ?? '';
208
+ const message = data.message ?? '';
209
+ if (!message)
210
+ return emit(ws, {type: 'error', sessionId: sid, message: 'Empty message'});
211
+
212
+ const mcpUrl = rewriteForDocker(data.mcpServerUrl || '');
213
+
214
+ let gotResult = false;
215
+ try {
216
+ const opts = buildOptions(getSession(sid), data.apiKey, mcpUrl);
217
+ for await (const event of query({prompt: promptStream(message), options: opts})) {
218
+ if (event.type === 'result')
219
+ gotResult = true;
220
+ forwardEvent(ws, sid, event);
221
+ }
222
+ } catch (e: any) {
223
+ if (!gotResult || !/exited with code/i.test(String(e.message)))
224
+ emit(ws, {type: 'error', sessionId: sid, message: String(e.message || e)});
225
+ }
226
+ }
227
+
228
+ const app = new Hono();
229
+ const {injectWebSocket, upgradeWebSocket} = createNodeWebSocket({app});
230
+
231
+ app.get('/health', (c) => c.json({status: 'ok'}));
232
+
233
+ app.get('/ws', upgradeWebSocket(() => {
234
+ let busy = false;
235
+ return {
236
+ onMessage(evt: any, ws: any) {
237
+ const sender = ws as unknown as WsSender;
238
+ let data: any;
239
+ try {
240
+ data = JSON.parse(String(evt.data));
241
+ } catch {
242
+ return emit(sender, {type: 'error', sessionId: '', message: 'Invalid JSON'});
243
+ }
244
+
245
+ if (data.type !== 'user_message') {
246
+ return emit(sender, {
247
+ type: 'error', sessionId: data.sessionId ?? '',
248
+ message: `Unknown type: ${data.type}`,
249
+ });
250
+ }
251
+
252
+ if (busy) {
253
+ return emit(sender, {
254
+ type: 'error', sessionId: data.sessionId ?? '',
255
+ message: 'Query already in progress',
256
+ });
257
+ }
258
+
259
+ busy = true;
260
+ handleMessage(sender, data).finally(() => { busy = false; });
261
+ },
262
+ };
263
+ }));
264
+
265
+ app.notFound((c) => c.json({error: 'Not found'}, 404));
266
+ app.onError((err, c) => c.json({error: String(err)}, 500));
267
+
268
+ if (!process.env['ANTHROPIC_API_KEY'])
269
+ console.warn('ANTHROPIC_API_KEY is not set — Claude API calls will fail');
270
+
271
+ const server = serve({fetch: app.fetch, port: PORT});
272
+ injectWebSocket(server);
273
+ console.log(`claude-runtime listening on :${PORT}`);
@@ -0,0 +1,37 @@
1
+ export interface ToolInputs {
2
+ Read: {file_path?: string};
3
+ Write: {file_path?: string};
4
+ Edit: {file_path?: string};
5
+ Bash: {command?: string};
6
+ Glob: {pattern?: string; path?: string};
7
+ Grep: {pattern?: string; path?: string};
8
+ WebSearch: {query?: string};
9
+ WebFetch: {url?: string};
10
+ }
11
+
12
+ export interface McpInputs {
13
+ call_function: {name?: string};
14
+ list_functions: {filter?: string};
15
+ get_function: {id?: string};
16
+ list_files: {path?: string};
17
+ download_file: {path?: string};
18
+ upload_file: {path?: string};
19
+ }
20
+
21
+ export type ToolName = keyof ToolInputs;
22
+ export type McpName = keyof McpInputs;
23
+
24
+ export interface UserMessage {
25
+ type: 'user_message';
26
+ sessionId: string;
27
+ message: string;
28
+ apiKey?: string;
29
+ mcpServerUrl?: string;
30
+ }
31
+
32
+ export type OutgoingMessage =
33
+ | {type: 'chunk'; sessionId: string; content: string}
34
+ | {type: 'tool_activity'; sessionId: string; summary: string}
35
+ | {type: 'tool_result'; sessionId: string; content: string}
36
+ | {type: 'final'; sessionId: string; content: string}
37
+ | {type: 'error'; sessionId: string; message: string};
@@ -0,0 +1,15 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2020",
4
+ "module": "CommonJS",
5
+ "outDir": "dist",
6
+ "rootDir": "src",
7
+ "sourceMap": true,
8
+ "strict": true,
9
+ "esModuleInterop": true,
10
+ "forceConsistentCasingInFileNames": true,
11
+ "skipLibCheck": true
12
+ },
13
+ "include": ["src/**/*.ts"],
14
+ "exclude": ["node_modules", "dist"]
15
+ }
@@ -0,0 +1,12 @@
1
+ FROM node:20-slim
2
+ WORKDIR /app
3
+ COPY package.json package-lock.json* ./
4
+ RUN npm ci
5
+ COPY tsconfig.json ./
6
+ COPY src ./src
7
+ RUN npx tsc && rm -rf src tsconfig.json && npm prune --production
8
+ USER node
9
+ EXPOSE 3003
10
+ HEALTHCHECK --interval=5s --timeout=3s --start-period=10s --retries=3 \
11
+ CMD node -e "fetch('http://127.0.0.1:3003/health').then(r=>r.ok?process.exit(0):process.exit(1)).catch(()=>process.exit(1))"
12
+ CMD ["node", "dist/index.js"]
@@ -0,0 +1 @@
1
+ { "cpu": 0.5, "memory": 512, "on_demand": true }