@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.
- package/.claude/skills/deploy-grokky/SKILL.md +193 -0
- package/.grokignore +2 -0
- package/.turbo/turbo-build.log +24 -0
- package/.vscode/settings.json +16 -0
- package/CHANGELOG.md +151 -8
- package/CLAUDE.md +284 -0
- package/CREDITS.md +173 -0
- package/LICENSE.md +16 -0
- package/README.md +24 -0
- package/bdd/bdd.config.json +1 -0
- package/bdd/bindings/elements.ts +9 -0
- package/bdd/bindings/steps.ts +787 -0
- package/bdd/features/ai-panel/platform-work.feature +63 -0
- package/bdd/features/ai-panel/session.feature +69 -0
- package/bdd/features/ai-panel/table-work.feature +99 -0
- package/bdd/generated/ai-panel/platform-work.test.ts +103 -0
- package/bdd/generated/ai-panel/session.test.ts +100 -0
- package/bdd/generated/ai-panel/table-work.test.ts +150 -0
- package/bdd/package.json +1 -0
- package/bdd/tsconfig.json +13 -0
- package/css/ai.css +637 -49
- package/dist/package-test.js +4 -1707
- package/dist/package-test.js.map +1 -1
- package/dist/package.js +742 -92317
- package/dist/package.js.map +1 -1
- package/dockerfiles/claude-runtime/.dockerignore +1 -0
- package/{.eslintrc.json → dockerfiles/claude-runtime/.eslintrc.json} +7 -16
- package/dockerfiles/claude-runtime/Dockerfile +73 -13
- package/dockerfiles/claude-runtime/agent/grokky_agent/__init__.py +0 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/__main__.py +80 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/browser_tools.py +180 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/config.py +26 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/formats.py +155 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/guard.py +87 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/hermes.py +212 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/hermes.yaml +45 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/hermes_plugin/__init__.py +8 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/hermes_plugin/plugin.yaml +3 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/protocol.py +174 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/__init__.py +21 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/anthropic.py +21 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/azure.py +46 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/base.py +127 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/bedrock.py +46 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/custom.py +40 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/databricks.py +54 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/openai_platform.py +41 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/openrouter.py +46 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/session.py +471 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/skills.py +44 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/structured.py +40 -0
- package/dockerfiles/claude-runtime/container.json +2 -2
- package/dockerfiles/claude-runtime/entrypoint.sh +20 -0
- package/dockerfiles/claude-runtime/package-lock.json +1721 -306
- package/dockerfiles/claude-runtime/package.json +20 -5
- package/dockerfiles/claude-runtime/plugin/.claude-plugin/plugin.json +5 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-calc-column/SKILL.md +92 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-chem-data/SKILL.md +250 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-chem-toolkit/SKILL.md +395 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-df-and-columns/SKILL.md +454 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-entities/SKILL.md +38 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-exec/SKILL.md +209 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-filtering/SKILL.md +185 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-grid-customization/SKILL.md +270 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-projects/SKILL.md +100 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-selection/SKILL.md +344 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-undo/SKILL.md +78 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-viewers/SKILL.md +303 -0
- package/dockerfiles/claude-runtime/pyproject.toml +18 -0
- package/dockerfiles/claude-runtime/src/agent/pool.ts +411 -0
- package/dockerfiles/claude-runtime/src/agent/turn.ts +153 -0
- package/dockerfiles/claude-runtime/src/constants.ts +20 -0
- package/dockerfiles/claude-runtime/src/credentials.ts +45 -0
- package/dockerfiles/claude-runtime/src/grounding.ts +104 -0
- package/dockerfiles/claude-runtime/src/help-index.ts +118 -0
- package/dockerfiles/claude-runtime/src/privileges.ts +8 -0
- package/dockerfiles/claude-runtime/src/prompts.ts +211 -0
- package/dockerfiles/claude-runtime/src/server.ts +134 -234
- package/dockerfiles/claude-runtime/src/session.ts +328 -0
- package/dockerfiles/claude-runtime/src/shared-api-client.ts +112 -0
- package/dockerfiles/claude-runtime/src/stream-filter.ts +80 -0
- package/dockerfiles/claude-runtime/src/sync/home-files.ts +80 -0
- package/dockerfiles/claude-runtime/src/sync/orchestrator.ts +214 -0
- package/dockerfiles/claude-runtime/src/sync/packages.ts +145 -0
- package/dockerfiles/claude-runtime/src/sync/shared-connections.ts +87 -0
- package/dockerfiles/claude-runtime/src/sync/workspace.ts +68 -0
- package/dockerfiles/claude-runtime/src/tasks.ts +124 -0
- package/dockerfiles/claude-runtime/src/tool-summary.ts +66 -0
- package/dockerfiles/claude-runtime/src/types.ts +142 -23
- package/dockerfiles/claude-runtime/src/user/installed-packages.ts +17 -0
- package/dockerfiles/claude-runtime/src/user/staged-workspace.ts +80 -0
- package/dockerfiles/claude-runtime/src/user/user-dir.ts +108 -0
- package/dockerfiles/claude-runtime/src/verify.ts +136 -0
- package/dockerfiles/claude-runtime/src/watchdog.ts +115 -0
- package/dockerfiles/claude-runtime/test/credentials.test.js +43 -0
- package/dockerfiles/claude-runtime/test/grounding.test.js +191 -0
- package/dockerfiles/claude-runtime/test/help-index.test.js +115 -0
- package/dockerfiles/claude-runtime/test/plugin-skills.test.js +57 -0
- package/dockerfiles/claude-runtime/test/prompts.test.js +62 -0
- package/dockerfiles/claude-runtime/test/reaper.test.js +60 -0
- package/dockerfiles/claude-runtime/test/stream-filter.test.js +132 -0
- package/dockerfiles/claude-runtime/test/tasks.test.js +74 -0
- package/dockerfiles/claude-runtime/test/user-dir.test.js +71 -0
- package/dockerfiles/claude-runtime/test/verify.test.js +187 -0
- package/dockerfiles/claude-runtime/test/watchdog.test.js +43 -0
- package/dockerfiles/mcp-server/.eslintrc.json +39 -0
- package/dockerfiles/mcp-server/Dockerfile +10 -2
- package/dockerfiles/mcp-server/package-lock.json +1743 -98
- package/dockerfiles/mcp-server/package.json +27 -5
- package/dockerfiles/mcp-server/src/api-client.ts +123 -66
- package/dockerfiles/mcp-server/src/format.ts +51 -0
- package/dockerfiles/mcp-server/src/index.ts +44 -113
- package/dockerfiles/mcp-server/src/ops.ts +325 -0
- package/dockerfiles/mcp-server/src/shared-api-client.ts +81 -0
- package/dockerfiles/mcp-server/test/format.test.js +62 -0
- package/dockerfiles/mcp-server/test/ops.test.js +84 -0
- package/dockerfiles/mcp-server/test/shared-api-client.test.js +35 -0
- package/dockerfiles/queue/Dockerfile +2 -0
- package/dockerfiles/queue/container.json +7 -0
- package/docs/AUDIT-2026-08-03.md +1064 -0
- package/docs/BENCHMARK.md +292 -0
- package/docs/CLAUDE_CODE_FLOW.md +746 -0
- package/docs/EXAMPLES.md +82 -0
- package/docs/FEATURES.md +71 -0
- package/docs/IMPLEMENTATION.md +128 -0
- package/docs/LATENCY.md +170 -0
- package/docs/VISION.md +36 -0
- package/files/benchmark/suite.yaml +404 -0
- package/files/scripts/process-cro-results.md +14 -0
- package/files/suggestions.yaml +344 -0
- package/package.json +39 -97
- package/src/ai/ai-window.ts +157 -0
- package/src/ai/benchmark/benchmark.ts +737 -0
- package/src/ai/db-view-functions.ts +56 -0
- package/src/ai/engine.ts +98 -0
- package/src/ai/gemma-engine.ts +81 -0
- package/src/ai/panel.ts +1385 -0
- package/src/ai/prompt-suggestions.ts +209 -0
- package/src/ai/search/combined-search.ts +244 -0
- package/src/{llm-utils → ai/search}/query-matching.ts +46 -167
- package/src/{llm-utils → ai}/storage.ts +0 -1
- package/src/ai/table-tools.ts +145 -0
- package/src/ai/ui.ts +720 -0
- package/src/ai/usage-limiter.ts +105 -0
- package/src/ai/view-tools.ts +352 -0
- package/src/claude/ai-feature.ts +16 -0
- package/src/claude/exec-blocks.ts +176 -0
- package/src/claude/queue-task.ts +84 -0
- package/src/claude/runtime-client.ts +310 -0
- package/src/claude/turn-log.ts +114 -0
- package/src/claude/undoable.ts +105 -0
- package/src/{llm-utils → db}/db-index-tools.ts +24 -32
- package/src/db/sql-tools.ts +336 -0
- package/src/depr/LLM-client.ts +251 -0
- package/src/depr/ai-panel.ts +174 -0
- package/src/depr/chatgpt-assistant.ts +257 -0
- package/src/depr/creds.ts +30 -0
- package/src/depr/deepwikiclient.ts +118 -0
- package/src/depr/indexes/dg-repository-index.ts +266 -0
- package/src/depr/interfaces.ts +170 -0
- package/src/depr/is-help-request.ts +39 -0
- package/src/depr/prompt-engine.ts +52 -0
- package/src/depr/rendering-tools.ts +103 -0
- package/src/depr/script-tools.ts +785 -0
- package/src/depr/tableview-tools.ts +746 -0
- package/src/depr/viewers-ai.ts +67 -0
- package/src/package-api.ts +87 -28
- package/src/package-test.ts +1 -0
- package/src/package.g.ts +98 -48
- package/src/package.ts +211 -157
- package/src/polyfills.ts +12 -0
- package/src/utils.ts +128 -0
- package/tsconfig.json +8 -70
- package/webpack.config.js +3 -49
- package/.eslintignore +0 -2
- package/src/ai-panel.ts +0 -174
- package/src/claude-code/claude-panel.ts +0 -34
- package/src/claude-code/claude-runtime-client.ts +0 -148
- package/src/llm-utils/LLM-client.ts +0 -251
- package/src/llm-utils/combined-search.ts +0 -162
- package/src/llm-utils/creds.ts +0 -30
- package/src/llm-utils/deepwikiclient.ts +0 -118
- package/src/llm-utils/indexes/dg-repository-index.ts +0 -266
- package/src/llm-utils/panel.ts +0 -866
- package/src/llm-utils/script-tools.ts +0 -784
- package/src/llm-utils/sql-tools.ts +0 -840
- package/src/llm-utils/tableview-tools.ts +0 -704
- package/src/llm-utils/ui.ts +0 -315
- package/src/prompt-engine/chatgpt-assistant.ts +0 -257
- package/src/prompt-engine/interfaces.ts +0 -170
- package/src/prompt-engine/prompt-engine.ts +0 -52
- package/src/prompt-engine/rendering-tools.ts +0 -103
- package/src/prompts/is-help-request.ts +0 -26
- package/src/viewers-ai.ts +0 -67
- /package/src/{llm-utils → db}/indexes/biologics-index.ts +0 -0
- /package/src/{llm-utils → db}/indexes/chembl-index.ts +0 -0
- /package/src/{llm-utils → db}/query-meta-utils.ts +0 -0
- /package/src/{llm-utils/depr → depr}/AI-API-providers/openai-chat-completions-provider.ts +0 -0
- /package/src/{llm-utils/depr → depr}/AI-API-providers/openai-responses-provider.ts +0 -0
- /package/src/{llm-utils/depr → depr}/AI-API-providers/types.ts +0 -0
- /package/src/{llm-utils/depr → depr}/depr.ts +0 -0
- /package/src/{llm-utils/depr → depr}/embeddings.ts +0 -0
- /package/src/{llm-utils/depr → depr}/sql-utils.ts +0 -0
package/src/package.ts
CHANGED
|
@@ -1,27 +1,25 @@
|
|
|
1
1
|
/* eslint-disable max-len */
|
|
2
|
+
import './polyfills'; // must run before anything else, see polyfills.ts
|
|
2
3
|
/* Do not change these import lines to match external modules in webpack configuration */
|
|
3
4
|
import * as grok from 'datagrok-api/grok';
|
|
4
5
|
import * as ui from 'datagrok-api/ui';
|
|
5
6
|
import * as DG from 'datagrok-api/dg';
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
7
|
+
import {findBestMatchingQuery, tableQueriesFunctionsSearchLlm} from './ai/search/query-matching';
|
|
8
|
+
import {askWiki, smartExecution, setupAgentScriptsUI, setupAIQueryEditorUI, setupScriptsAIPanelUI, setupSearchUI, setupShellAIPanelUI, setupTableViewAIPanelUI, initAIWindow} from './ai/ui';
|
|
9
|
+
import {CombinedAISearchAssistant} from './ai/search/combined-search';
|
|
10
|
+
import {ClaudeEngine} from './ai/engine';
|
|
11
|
+
import {GemmaEngine} from './ai/gemma-engine';
|
|
12
|
+
import {UsageLimiter} from './ai/usage-limiter';
|
|
13
|
+
import {ClaudeRuntimeClient} from './claude/runtime-client';
|
|
14
|
+
import {genDBConnectionMeta, moveDBMetaToStickyMetaOhCoolItEvenRhymes} from './db/db-index-tools';
|
|
15
|
+
import {listDbCatalogs, listDbSchemas, listDbTables, getDbTableDetails, listDbJoins, getSqlTestResult} from './ai/db-view-functions';
|
|
16
|
+
import {biologicsIndex} from './db/indexes/biologics-index';
|
|
17
|
+
import {chemblIndex} from './db/indexes/chembl-index';
|
|
18
|
+
import {runBenchmark as runBenchmarkImpl, compareBenchmarks as compareBenchmarksImpl} from './ai/benchmark/benchmark';
|
|
19
|
+
import {holdChatTurnTask} from './claude/queue-task';
|
|
19
20
|
export * from './package.g';
|
|
20
21
|
|
|
21
22
|
export class ChatGPTPackage extends DG.Package {
|
|
22
|
-
get settings(): PackageSettings {
|
|
23
|
-
return super.settings as PackageSettings;
|
|
24
|
-
}
|
|
25
23
|
}
|
|
26
24
|
|
|
27
25
|
export const _package = new ChatGPTPackage();
|
|
@@ -30,46 +28,104 @@ export const _package = new ChatGPTPackage();
|
|
|
30
28
|
export class PackageFunctions {
|
|
31
29
|
@grok.decorators.init({tags: ['init']})
|
|
32
30
|
static async init() {
|
|
33
|
-
|
|
34
|
-
|
|
31
|
+
// Headless Node celery worker: skip all browser UI wiring
|
|
32
|
+
if ((globalThis as any).process?.versions?.node)
|
|
33
|
+
return;
|
|
34
|
+
await UsageLimiter.getInstance().init();
|
|
35
|
+
const aiAvailable = await ClaudeRuntimeClient.getInstance().discover();
|
|
35
36
|
setupSearchUI();
|
|
37
|
+
initAIWindow();
|
|
36
38
|
setupTableViewAIPanelUI();
|
|
37
39
|
setupScriptsAIPanelUI();
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
//
|
|
40
|
+
setupAgentScriptsUI();
|
|
41
|
+
PackageFunctions.ensureAgentsFolder();
|
|
42
|
+
// Warm the WebSocket to claude-runtime so the first user turn doesn't pay container-lookup + WS handshake cost.
|
|
43
|
+
if (aiAvailable)
|
|
44
|
+
ClaudeRuntimeClient.getInstance().ensureConnected().catch(() => {});
|
|
45
|
+
PackageFunctions.subscribeToSyncEvents();
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Creates agents/ folder in My Files if it doesn't exist yet, and seeds agents/scripts/
|
|
49
|
+
// with any demo files from the package's files/scripts/ folder.
|
|
50
|
+
static async ensureAgentsFolder(): Promise<void> {
|
|
51
|
+
try {
|
|
52
|
+
const conn = await grok.dapi.connections.filter('name = "My files"').first();
|
|
53
|
+
if (!conn)
|
|
54
|
+
return;
|
|
55
|
+
const agentsPath = `${conn.nqName}/agents`;
|
|
56
|
+
const exists = await grok.dapi.files.exists(agentsPath);
|
|
57
|
+
if (!exists) {
|
|
58
|
+
await grok.dapi.files.writeAsText(`${agentsPath}/README.md`,
|
|
59
|
+
'Place your personal knowledge files here. The AI assistant will use them as context.');
|
|
60
|
+
console.log('Grokky: created agents/ folder');
|
|
61
|
+
}
|
|
62
|
+
await PackageFunctions.seedScriptsFolder(`${agentsPath}/scripts`);
|
|
63
|
+
} catch (e: any) {
|
|
64
|
+
console.warn('Grokky: failed to ensure agents folder:', e.message);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
41
67
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
68
|
+
// Copies demo files from the package's files/scripts/ into MyFiles agents/scripts/.
|
|
69
|
+
// Existing files are left untouched so user edits are preserved.
|
|
70
|
+
static async seedScriptsFolder(destPath: string): Promise<void> {
|
|
71
|
+
const sourceFiles: DG.FileInfo[] = await _package.files.list('scripts', false);
|
|
72
|
+
for (const fi of sourceFiles) {
|
|
73
|
+
if (fi.isDirectory)
|
|
74
|
+
continue;
|
|
75
|
+
const destFilePath = `${destPath}/${fi.name}`;
|
|
76
|
+
if (await grok.dapi.files.exists(destFilePath))
|
|
77
|
+
continue;
|
|
78
|
+
const content = await fi.readAsString();
|
|
79
|
+
await grok.dapi.files.writeAsText(destFilePath, content);
|
|
80
|
+
console.log(`Grokky: seeded ${fi.name} into agents/scripts/`);
|
|
81
|
+
}
|
|
45
82
|
}
|
|
46
83
|
|
|
84
|
+
static isAgentsFile(fi: DG.FileInfo): boolean {
|
|
85
|
+
return (fi.fullPath ?? fi.path ?? fi.name ?? '').includes('agents');
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Subscribes to platform events that should trigger file sync.
|
|
89
|
+
static subscribeToSyncEvents(): void {
|
|
90
|
+
// Background sync is best-effort: swallow errors (e.g. runtime container not running) so they
|
|
91
|
+
// don't surface as unhandled rejections that get auto-reported on every package load.
|
|
92
|
+
const sync = (...args: Parameters<ClaudeRuntimeClient['syncUserFiles']>) =>
|
|
93
|
+
ClaudeRuntimeClient.getInstance().syncUserFiles(...args).catch(() => {});
|
|
94
|
+
|
|
95
|
+
// MyFiles agents: file operations (create, upload, delete, rename, move)
|
|
96
|
+
grok.events.onEvent('d4-file-event').subscribe((eventData: any) => {
|
|
97
|
+
const dartFiles = eventData?.dart?.files;
|
|
98
|
+
if (!dartFiles)
|
|
99
|
+
return;
|
|
100
|
+
const files: DG.FileInfo[] = Array.from({length: dartFiles.length}, (_: any, i: number) => DG.toJs(dartFiles[i]));
|
|
101
|
+
if (files.some(PackageFunctions.isAgentsFile))
|
|
102
|
+
sync('user-files');
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
// MyFiles agents: in-place file edits (save)
|
|
106
|
+
grok.events.onFileEdited.subscribe((fi: DG.FileInfo) => {
|
|
107
|
+
if (PackageFunctions.isAgentsFile(fi))
|
|
108
|
+
sync('user-files');
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
// Packages: when a JS bundle is loaded
|
|
112
|
+
grok.events.onPackageLoaded.subscribe((pkg: DG.Package) => {
|
|
113
|
+
if (pkg?.name)
|
|
114
|
+
sync('packages', pkg.name);
|
|
115
|
+
});
|
|
116
|
+
}
|
|
47
117
|
|
|
48
118
|
@grok.decorators.autostart({tags: ['autostart']})
|
|
49
119
|
static autostart() {
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
// initAiPanel();
|
|
60
|
-
// // Add keyboard shortcut for toggling AI panel
|
|
61
|
-
// document.addEventListener('keydown', (event) => {
|
|
62
|
-
// // Check for Ctrl+I (Ctrl key + I key)
|
|
63
|
-
// if (event.ctrlKey && event.key === 'i') {
|
|
64
|
-
// event.preventDefault(); // Prevent default browser behavior
|
|
65
|
-
// const isVisible = getAiPanelVisibility();
|
|
66
|
-
// setAiPanelVisibility(!isVisible);
|
|
67
|
-
// }
|
|
68
|
-
// });
|
|
69
|
-
// } catch (e) {
|
|
70
|
-
// console.log('AI autostart failed.');
|
|
71
|
-
// console.log(e);
|
|
72
|
-
// }
|
|
120
|
+
if (grok.shell.windows.showAI)
|
|
121
|
+
setupShellAIPanelUI();
|
|
122
|
+
let prevShowAI = grok.shell.windows.showAI;
|
|
123
|
+
grok.shell.windows.onPanelVisibilityChanged.subscribe(() => {
|
|
124
|
+
const showAI = grok.shell.windows.showAI;
|
|
125
|
+
if (showAI && !prevShowAI)
|
|
126
|
+
setupShellAIPanelUI();
|
|
127
|
+
prevShowAI = showAI;
|
|
128
|
+
});
|
|
73
129
|
}
|
|
74
130
|
|
|
75
131
|
|
|
@@ -77,7 +133,7 @@ export class PackageFunctions {
|
|
|
77
133
|
meta: {role: 'searchProvider'},
|
|
78
134
|
})
|
|
79
135
|
static combinedLLMSearchProvider(): DG.SearchProvider {
|
|
80
|
-
const
|
|
136
|
+
const client = ClaudeRuntimeClient.getInstance();
|
|
81
137
|
return {
|
|
82
138
|
'home': {
|
|
83
139
|
name: 'Ask AI Assistant',
|
|
@@ -86,32 +142,73 @@ export class PackageFunctions {
|
|
|
86
142
|
return null;
|
|
87
143
|
},
|
|
88
144
|
getSuggestions: (_query: string) => [],
|
|
89
|
-
isApplicable: (query: string) =>
|
|
145
|
+
isApplicable: (query: string) => client.available ? query?.trim().length >= 2 : false,
|
|
90
146
|
description: 'Get answers form AI assistant',
|
|
91
147
|
onValueEnter: async (query) => {
|
|
92
|
-
|
|
148
|
+
client.available && query?.trim().length >= 2 &&
|
|
93
149
|
await CombinedAISearchAssistant.instance.searchUI(query);
|
|
94
150
|
}
|
|
95
151
|
}
|
|
96
152
|
} satisfies DG.SearchProvider;
|
|
97
153
|
}
|
|
98
154
|
|
|
155
|
+
@grok.decorators.func({meta: {role: 'aiEngine'}})
|
|
156
|
+
static gemmaEngine(): DG.AIEngine {
|
|
157
|
+
return new GemmaEngine();
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
@grok.decorators.func({meta: {role: 'aiEngine'}})
|
|
161
|
+
static claudeEngine(): DG.AIEngine {
|
|
162
|
+
return new ClaudeEngine();
|
|
163
|
+
}
|
|
164
|
+
|
|
99
165
|
@grok.decorators.func({meta: {
|
|
100
166
|
role: 'aiSearchProvider',
|
|
101
|
-
useWhen: 'If the user is asking questions about how to do something, how to write the code on platform, how to execute tasks, or any other questions related to Datagrok platform functionalities and capabilities. The tone of the prompt should generally sound like "how do I do this" / "what is this". for example, "what sequence notations are supported?'
|
|
167
|
+
useWhen: 'If the user is asking questions about how to do something, how to write the code on platform, how to execute tasks, or any other questions related to Datagrok platform functionalities and capabilities. The tone of the prompt should generally sound like "how do I do this" / "what is this". for example, "what sequence notations are supported?',
|
|
102
168
|
}, name: 'Help',
|
|
103
|
-
description: 'Get answers from
|
|
104
|
-
static async askHelpLLMProvider(
|
|
105
|
-
|
|
169
|
+
description: 'Get answers from AI assistant based on Datagrok documentation and public code.', result: {type: 'widget', name: 'result'}})
|
|
170
|
+
static async askHelpLLMProvider(
|
|
171
|
+
@grok.decorators.param({type: 'string'}) prompt: string,
|
|
172
|
+
@grok.decorators.param({type: 'string', options: {optional: true}}) sessionId?: string
|
|
173
|
+
): Promise<DG.Widget | null> {
|
|
174
|
+
return await askWiki(prompt, sessionId);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
@grok.decorators.func({name: 'runBenchmark',
|
|
178
|
+
description: 'Run the Grokky latency/accuracy benchmark suite (files/benchmark/suite.yaml) and download a JSON + Markdown report tagged with the given label. Run after logging in; open no special view.'})
|
|
179
|
+
static async runBenchmark(
|
|
180
|
+
@grok.decorators.param({type: 'string', options: {description: 'Config label for this run, e.g. baseline / medium-effort'}}) label: string,
|
|
181
|
+
@grok.decorators.param({type: 'int', options: {optional: true, description: 'Repetitions per prompt (default 3)'}}) reps?: number,
|
|
182
|
+
@grok.decorators.param({type: 'string', options: {optional: true,
|
|
183
|
+
description: 'Run only part of the suite: comma-separated categories, difficulties, or prompt substrings.'}}) only?: string,
|
|
184
|
+
): Promise<string> {
|
|
185
|
+
return runBenchmarkImpl(label, reps ?? 3, only);
|
|
106
186
|
}
|
|
107
187
|
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
188
|
+
@grok.decorators.func({name: 'aiChatTurnTask', meta: {queue: 'true'},
|
|
189
|
+
description: 'Holds the admission slot for one AI chat turn streaming over the browser WebSocket - see queue-task.ts'})
|
|
190
|
+
static async aiChatTurnTask(sessionId: string, taskId: string): Promise<string> {
|
|
191
|
+
return holdChatTurnTask(sessionId, taskId);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
@grok.decorators.func({name: 'compareBenchmarks',
|
|
195
|
+
description: 'Compare two or more saved benchmark runs (comma-separated labels) into one Markdown report and download it.'})
|
|
196
|
+
static async compareBenchmarks(
|
|
197
|
+
@grok.decorators.param({type: 'string', options: {description: 'Comma-separated run labels, the first being the reference arm'}}) labels: string,
|
|
198
|
+
): Promise<string> {
|
|
199
|
+
return compareBenchmarksImpl(labels);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
@grok.decorators.func({meta: {
|
|
203
|
+
role: 'aiSearchProvider',
|
|
204
|
+
useWhen: 'If the prompt looks like a user has a goal to achieve something with concrete input(s), and wants the system to plan and execute a series of steps/functions to achieve that goal. This relates to functions that analyse or mutate data, not get it. for example, adme properties of CHEMBL1234, enumerate some peptide, etc... Also, if the tone of the prompt sounds like "Do something to something", use this function',
|
|
205
|
+
}, name: 'Execute',
|
|
206
|
+
description: 'Plans and executes function steps to achieve needed results', result: {type: 'widget', name: 'result'}})
|
|
207
|
+
static async smartChainExecutionProvider(
|
|
208
|
+
@grok.decorators.param({type: 'string'}) prompt: string,
|
|
209
|
+
@grok.decorators.param({type: 'string', options: {optional: true}}) sessionId?: string
|
|
210
|
+
): Promise<DG.Widget | null> {
|
|
211
|
+
return await smartExecution(prompt, sessionId);
|
|
115
212
|
}
|
|
116
213
|
|
|
117
214
|
@grok.decorators.func({meta: {
|
|
@@ -119,8 +216,11 @@ export class PackageFunctions {
|
|
|
119
216
|
useWhen: 'if the prompt suggest that the user is looking for a data table result and the prompt resembles a query pattern. for example, "bioactivity data for shigella" or "compounds similar to aspirin" or first 100 chembl compounds. there should be some parts of user prompt that could match parameters in some query, like shigella, aspirin, first 100 etc. Always use this function when user wants to get the data without any further processing or calculating'
|
|
120
217
|
}, name: 'Query',
|
|
121
218
|
description: 'Tries to find a query which has the similar pattern as the prompt user entered and executes it', result: {type: 'widget', name: 'result'}})
|
|
122
|
-
static async llmSearchQueryProvider(
|
|
123
|
-
|
|
219
|
+
static async llmSearchQueryProvider(
|
|
220
|
+
@grok.decorators.param({type: 'string'}) prompt: string,
|
|
221
|
+
@grok.decorators.param({type: 'string', options: {optional: true}}) sessionId?: string
|
|
222
|
+
): Promise<DG.Widget | null> {
|
|
223
|
+
return await tableQueriesFunctionsSearchLlm(prompt, sessionId);
|
|
124
224
|
}
|
|
125
225
|
|
|
126
226
|
@grok.decorators.func({
|
|
@@ -129,119 +229,73 @@ export class PackageFunctions {
|
|
|
129
229
|
'cache.invalidateOn': '0 0 1 * *'
|
|
130
230
|
}
|
|
131
231
|
})
|
|
132
|
-
static async
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
prompt: string,
|
|
136
|
-
schema?: JsonSchema
|
|
137
|
-
): Promise<string> {
|
|
138
|
-
const client = LLMClient.getInstance();
|
|
139
|
-
// this is used only here to provide caching
|
|
140
|
-
return await client.generalPrompt(model, systemPrompt, prompt, schema);
|
|
232
|
+
static async findMatchingPatternQuery(prompt: string): Promise<string> {
|
|
233
|
+
const queryMatchResult = await findBestMatchingQuery(prompt);
|
|
234
|
+
return JSON.stringify(queryMatchResult);
|
|
141
235
|
}
|
|
142
236
|
|
|
143
|
-
@grok.decorators.func({
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
'cache.invalidateOn': '0 0 1 * *'
|
|
147
|
-
}
|
|
148
|
-
})
|
|
149
|
-
static async ask(
|
|
150
|
-
question: string,
|
|
151
|
-
): Promise<string> {
|
|
152
|
-
const client = LLMClient.getInstance();
|
|
153
|
-
// this is used only here to provide caching
|
|
154
|
-
return await client.generalPrompt(ModelType.Fast, 'You are a helpful assistant.', question);
|
|
237
|
+
@grok.decorators.func({})
|
|
238
|
+
static async setupAIQueryEditor(view: DG.ViewBase, connectionID: string, queryEditorRoot: HTMLElement, @grok.decorators.param({type: 'dynamic'}) setAndRunFunc: Function): Promise<boolean> {
|
|
239
|
+
return setupAIQueryEditorUI(view, connectionID, queryEditorRoot, setAndRunFunc as (query: string) => void);
|
|
155
240
|
}
|
|
156
241
|
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
}
|
|
162
|
-
})
|
|
163
|
-
|
|
164
|
-
const gptEngine = ChatGPTPromptEngine.getInstance(ModelType['Deep Research']);
|
|
165
|
-
const gptAssistant = new ChatGptAssistant(gptEngine);
|
|
166
|
-
const plan: Plan = await gptAssistant.plan(userGoal);
|
|
167
|
-
// Cache only works with scalar values, so we serialize the plan to a string
|
|
168
|
-
return JSON.stringify(plan);
|
|
242
|
+
// Functions applicable to the database query editor (surfaced via View.getFunctions()
|
|
243
|
+
// by their meta.viewType). Each takes the view; the AI assistant injects it automatically.
|
|
244
|
+
|
|
245
|
+
@grok.decorators.func({meta: {viewType: 'DataQueryView'},
|
|
246
|
+
description: 'List the catalogs available on this connection'})
|
|
247
|
+
static async listDbCatalogs(@grok.decorators.param({type: 'view'}) view: any): Promise<string> {
|
|
248
|
+
return listDbCatalogs(view);
|
|
169
249
|
}
|
|
170
250
|
|
|
171
|
-
@grok.decorators.func({
|
|
172
|
-
'
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
static async findMatchingPatternQuery(prompt: string): Promise<string> {
|
|
178
|
-
const queryMatchResult = await findBestMatchingQuery(prompt);
|
|
179
|
-
return JSON.stringify(queryMatchResult);
|
|
251
|
+
@grok.decorators.func({meta: {viewType: 'DataQueryView'},
|
|
252
|
+
description: 'List schemas of a catalog (defaults to the connection default catalog)'})
|
|
253
|
+
static async listDbSchemas(
|
|
254
|
+
@grok.decorators.param({type: 'view'}) view: any,
|
|
255
|
+
@grok.decorators.param({type: 'string', options: {optional: true}}) catalogName?: string): Promise<string> {
|
|
256
|
+
return listDbSchemas(view, catalogName);
|
|
180
257
|
}
|
|
181
258
|
|
|
182
|
-
@grok.decorators.func({
|
|
183
|
-
'
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
const client = LLMClient.getInstance();
|
|
190
|
-
return await client.getHelpAnswer(prompt);
|
|
259
|
+
@grok.decorators.func({meta: {viewType: 'DataQueryView'},
|
|
260
|
+
description: 'List tables of a schema with row counts'})
|
|
261
|
+
static async listDbTables(
|
|
262
|
+
@grok.decorators.param({type: 'view'}) view: any,
|
|
263
|
+
schemaName: string,
|
|
264
|
+
@grok.decorators.param({type: 'string', options: {optional: true}}) catalogName?: string): Promise<string> {
|
|
265
|
+
return listDbTables(view, schemaName, catalogName);
|
|
191
266
|
}
|
|
192
267
|
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
// static async generateSqlQuery(prompt: string, connectionID: string, schemaName: string): Promise<string> {
|
|
200
|
-
// return await generateAISqlQuery(prompt, connectionID, schemaName);
|
|
201
|
-
// }
|
|
202
|
-
@grok.decorators.func({})
|
|
203
|
-
static async setupAIQueryEditor(view: DG.ViewBase, connectionID: string, queryEditorRoot: HTMLElement, @grok.decorators.param({type: 'dynamic'}) setAndRunFunc: Function): Promise<boolean> {
|
|
204
|
-
return setupAIQueryEditorUI(view, connectionID, queryEditorRoot, setAndRunFunc as (query: string) => void);
|
|
268
|
+
@grok.decorators.func({meta: {viewType: 'DataQueryView'},
|
|
269
|
+
description: 'Detailed column info (types, comments, ranges, sample values) for the given tables. Table refs: catalog.schema.table, schema.table, or table'})
|
|
270
|
+
static async getDbTableDetails(
|
|
271
|
+
@grok.decorators.param({type: 'view'}) view: any,
|
|
272
|
+
@grok.decorators.param({type: 'string', options: {description: 'Comma-separated table references to describe'}}) tables: string): Promise<string> {
|
|
273
|
+
return getDbTableDetails(view, tables);
|
|
205
274
|
}
|
|
206
275
|
|
|
207
|
-
@grok.decorators.func({}
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
276
|
+
@grok.decorators.func({meta: {viewType: 'DataQueryView'},
|
|
277
|
+
description: 'Foreign-key relationships involving the given tables — use to build correct JOINs'})
|
|
278
|
+
static async listDbJoins(
|
|
279
|
+
@grok.decorators.param({type: 'view'}) view: any,
|
|
280
|
+
@grok.decorators.param({type: 'string', options: {description: 'Comma-separated table references'}}) tables: string): Promise<string> {
|
|
281
|
+
return listDbJoins(view, tables);
|
|
211
282
|
}
|
|
212
283
|
|
|
213
|
-
@grok.decorators.func({}
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
.add(keyWordInput)
|
|
221
|
-
.onOK(async () => {
|
|
222
|
-
if (keyWordInput.value !== 'DG-index-admin') {
|
|
223
|
-
grok.shell.error('Incorrect passkey. Operation aborted.');
|
|
224
|
-
return;
|
|
225
|
-
}
|
|
226
|
-
await
|
|
227
|
-
uploadFilesToVectorStroreOneByOne();
|
|
228
|
-
})
|
|
229
|
-
.show();
|
|
284
|
+
@grok.decorators.func({meta: {viewType: 'DataQueryView'},
|
|
285
|
+
description: 'Test-execute a SELECT (auto-LIMITed) and report row count, columns, and a sample row. Use to validate SQL before setQueryAndRun'})
|
|
286
|
+
static async getSqlTestResult(
|
|
287
|
+
@grok.decorators.param({type: 'view'}) view: any,
|
|
288
|
+
@grok.decorators.param({type: 'string', options: {description: 'The SQL to test'}}) sql: string,
|
|
289
|
+
@grok.decorators.param({type: 'string', options: {description: 'One line describing what the query does'}}) description: string): Promise<string> {
|
|
290
|
+
return getSqlTestResult(view, sql, description);
|
|
230
291
|
}
|
|
231
292
|
|
|
232
293
|
@grok.decorators.func({})
|
|
233
|
-
static async
|
|
234
|
-
const
|
|
235
|
-
|
|
236
|
-
const f = await openAIClient.vectorStores.search('vs_696fbf9985f8819191dc6f71e04b6593', {query: query, max_num_results: 5, filters: {
|
|
237
|
-
key: 'firstParentFolder',
|
|
238
|
-
type: 'eq',
|
|
239
|
-
value: 'datagrok-celery-task'
|
|
240
|
-
}});
|
|
241
|
-
console.log(f.data);
|
|
294
|
+
static async moveMetaToDB(@grok.decorators.param({type: 'string', options: {choices: ['biologics', 'chembl']}})dbName: string): Promise<void> {
|
|
295
|
+
const meta = dbName === 'biologics' ? biologicsIndex : chemblIndex;
|
|
296
|
+
await moveDBMetaToStickyMetaOhCoolItEvenRhymes(meta);
|
|
242
297
|
}
|
|
243
298
|
|
|
244
|
-
|
|
245
299
|
@grok.decorators.func({})
|
|
246
300
|
static async indexDatabaseSchema() {
|
|
247
301
|
grok.shell.info('Do not touch this function if you are not a developer. :D :D :D');
|
package/src/polyfills.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/* eslint-disable */
|
|
2
|
+
/**
|
|
3
|
+
* Runtime APIs that current browsers still lack in some contexts. Imported as the first import from
|
|
4
|
+
* `package.ts` / `package-test.ts`, so these are in place before any other module runs.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
(function installPolyfills() {
|
|
8
|
+
// SpeechRecognition: Chrome ships only webkitSpeechRecognition
|
|
9
|
+
const W: any = (typeof window !== 'undefined') ? window : undefined;
|
|
10
|
+
if (W && !W.SpeechRecognition && W.webkitSpeechRecognition)
|
|
11
|
+
W.SpeechRecognition = W.webkitSpeechRecognition;
|
|
12
|
+
})();
|
package/src/utils.ts
CHANGED
|
@@ -6,6 +6,14 @@ import * as rxjs from 'rxjs';
|
|
|
6
6
|
|
|
7
7
|
const AI_SQL_QUERY_ABORT_EVENT = 'd4-ai-generation-abort';
|
|
8
8
|
const AI_PANEL_TOGGLE_EVENT = 'd4-ai-panel-toggle';
|
|
9
|
+
const AI_BEFORE_USER_PROMPT_EVENT = 'd4-ai-before-user-prompt';
|
|
10
|
+
const AI_AFTER_USER_PROMPT_EVENT = 'd4-ai-after-user-prompt';
|
|
11
|
+
|
|
12
|
+
export type UserPromptEventArgs = {
|
|
13
|
+
prompt: string;
|
|
14
|
+
context: any;
|
|
15
|
+
handled: boolean;
|
|
16
|
+
};
|
|
9
17
|
|
|
10
18
|
const dummy = grok.data.testData('demog');
|
|
11
19
|
let viewerDescriptions: string = '';
|
|
@@ -138,6 +146,41 @@ export type AbortPointer = {
|
|
|
138
146
|
aborted: boolean;
|
|
139
147
|
}
|
|
140
148
|
|
|
149
|
+
export const SHORTCUT_HINT = 'Ctrl+I';
|
|
150
|
+
|
|
151
|
+
export function isToggleKey(e: KeyboardEvent): boolean {
|
|
152
|
+
return e.ctrlKey && (e.key === 'i' || e.keyCode === 73);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Copies text to the clipboard, resolving to whether it succeeded (never rejects).
|
|
156
|
+
* Falls back to `document.execCommand('copy')` when `navigator.clipboard` is unavailable
|
|
157
|
+
* (insecure, plain-HTTP contexts). */
|
|
158
|
+
export async function copyToClipboard(text: string): Promise<boolean> {
|
|
159
|
+
if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
|
|
160
|
+
try {
|
|
161
|
+
await navigator.clipboard.writeText(text);
|
|
162
|
+
return true;
|
|
163
|
+
} catch (e) {
|
|
164
|
+
console.warn('clipboard.writeText failed, falling back to execCommand', e);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
try {
|
|
168
|
+
const ta = document.createElement('textarea');
|
|
169
|
+
ta.value = text;
|
|
170
|
+
ta.style.position = 'fixed';
|
|
171
|
+
ta.style.left = '-9999px';
|
|
172
|
+
ta.setAttribute('readonly', '');
|
|
173
|
+
document.body.appendChild(ta);
|
|
174
|
+
ta.select();
|
|
175
|
+
const ok = document.execCommand('copy');
|
|
176
|
+
document.body.removeChild(ta);
|
|
177
|
+
return ok;
|
|
178
|
+
} catch (e) {
|
|
179
|
+
console.error('copyToClipboard failed', e);
|
|
180
|
+
return false;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
141
184
|
export function dartLike<T extends any>(obj: T) {
|
|
142
185
|
return {
|
|
143
186
|
set: function<K extends keyof T>(key: K, value: T[K]) {
|
|
@@ -164,6 +207,22 @@ export function fireAIPanelToggleEvent(v: DG.View | DG.ViewBase) {
|
|
|
164
207
|
grok.events.fireCustomEvent(AI_PANEL_TOGGLE_EVENT, v);
|
|
165
208
|
}
|
|
166
209
|
|
|
210
|
+
export function fireBeforeUserPromptEvent(args: UserPromptEventArgs): void {
|
|
211
|
+
grok.events.fireCustomEvent(AI_BEFORE_USER_PROMPT_EVENT, args);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export function onBeforeUserPromptEvent(): rxjs.Observable<UserPromptEventArgs> {
|
|
215
|
+
return grok.events.onCustomEvent(AI_BEFORE_USER_PROMPT_EVENT);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export function fireAfterUserPromptEvent(args: UserPromptEventArgs): void {
|
|
219
|
+
grok.events.fireCustomEvent(AI_AFTER_USER_PROMPT_EVENT, args);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
export function onAfterUserPromptEvent(): rxjs.Observable<UserPromptEventArgs> {
|
|
223
|
+
return grok.events.onCustomEvent(AI_AFTER_USER_PROMPT_EVENT);
|
|
224
|
+
}
|
|
225
|
+
|
|
167
226
|
export function findLast<T, K extends T>(array: T[], predicate: (value: T, index: number, obj: T[]) => value is K): K | undefined {
|
|
168
227
|
for (let i = array.length - 1; i >= 0; i--) {
|
|
169
228
|
const value = array[i];
|
|
@@ -172,3 +231,72 @@ export function findLast<T, K extends T>(array: T[], predicate: (value: T, index
|
|
|
172
231
|
}
|
|
173
232
|
return undefined;
|
|
174
233
|
}
|
|
234
|
+
|
|
235
|
+
/** GFM forbids a table from interrupting a paragraph, and the platform's Dart markdown parser is
|
|
236
|
+
* spec-strict — but models routinely emit `**Section**` directly followed by `| header |` rows,
|
|
237
|
+
* which then render as one glued paragraph of pipes. Insert the missing blank line before a table
|
|
238
|
+
* block (a `|` line whose next line is the `|---|` separator) when it follows a non-table line.
|
|
239
|
+
* Fence-aware so code blocks with ASCII pipes are untouched. */
|
|
240
|
+
export function normalizeMarkdownTables(text: string): string {
|
|
241
|
+
if (!text.includes('|'))
|
|
242
|
+
return text;
|
|
243
|
+
const lines = text.split('\n');
|
|
244
|
+
const out: string[] = [];
|
|
245
|
+
let inFence = false;
|
|
246
|
+
for (let i = 0; i < lines.length; i++) {
|
|
247
|
+
const line = lines[i];
|
|
248
|
+
if (/^\s*```/.test(line))
|
|
249
|
+
inFence = !inFence;
|
|
250
|
+
const prev = out.length ? out[out.length - 1] : '';
|
|
251
|
+
if (!inFence && /^\s*\|/.test(line) && prev.trim() !== '' && !/^\s*\|/.test(prev) &&
|
|
252
|
+
/^\s*\|?[\s:|-]+\|?\s*$/.test(lines[i + 1] ?? '') && (lines[i + 1] ?? '').includes('-'))
|
|
253
|
+
out.push('');
|
|
254
|
+
out.push(line);
|
|
255
|
+
}
|
|
256
|
+
return out.join('\n');
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** The platform's markdown links `[text](url)` and `<url>` but not a bare URL, which models still write
|
|
260
|
+
* (`Documentation: https://datagrok.ai/help/…`). Outside code, a bare http(s) URL at a line's start or after a
|
|
261
|
+
* space becomes `<url>`, with trailing punctuation left outside it. */
|
|
262
|
+
export function linkBareUrls(text: string): string {
|
|
263
|
+
return text.split(/(```[\s\S]*?```|`[^`\n]*`)/).map((part, i) => i % 2 ? part :
|
|
264
|
+
part.replace(/(^|\s)(https?:\/\/[^\s<>()[\]`]*[^\s<>()[\]`.,;:!?'"*_])/g, '$1<$2>')).join('');
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** Null when the platform's markdown parser throws (it did on a paragraph ending in `](`). */
|
|
268
|
+
export function tryMarkdown(content: string): HTMLElement | null {
|
|
269
|
+
try {
|
|
270
|
+
return ui.markdown(normalizeMarkdownTables(linkBareUrls(content)), {sanitize: true});
|
|
271
|
+
} catch {
|
|
272
|
+
return null;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
export function plainTextEl(content: string): HTMLElement {
|
|
277
|
+
return ui.divText(content, 'grokky-markdown-fallback');
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Renders markdown content with copy-on-code-blocks behavior and selectable text. */
|
|
281
|
+
export function createStyledMarkdown(content: string): HTMLElement {
|
|
282
|
+
const markDown = tryMarkdown(content) ?? plainTextEl(content);
|
|
283
|
+
markDown.style.position = 'relative';
|
|
284
|
+
dartLike(markDown.style).set('userSelect', 'text').set('maxWidth', '100%');
|
|
285
|
+
markDown.querySelectorAll('pre > code').forEach((code) =>
|
|
286
|
+
codeCard(code.parentElement!, /language-(\S+)/.exec(code.className)?.[1] ?? 'Code'));
|
|
287
|
+
return markDown;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
export function codeCard(pre: HTMLElement, language: string): HTMLElement {
|
|
291
|
+
const copy = ui.divH([ui.iconFA('copy'), ui.divText('Copy')], 'grokky-code-copy');
|
|
292
|
+
copy.onclick = async (): Promise<void> => {
|
|
293
|
+
if (await copyToClipboard(pre.textContent || ''))
|
|
294
|
+
grok.shell.info('Code copied to clipboard');
|
|
295
|
+
else
|
|
296
|
+
grok.shell.error('Failed to copy code to clipboard');
|
|
297
|
+
};
|
|
298
|
+
const card = ui.divV([ui.divH([ui.divText(language), copy], 'grokky-code-head')], 'grokky-code-card');
|
|
299
|
+
pre.replaceWith(card);
|
|
300
|
+
card.appendChild(pre);
|
|
301
|
+
return card;
|
|
302
|
+
}
|