@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
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import * as grok from 'datagrok-api/grok';
|
|
2
|
+
import * as DG from 'datagrok-api/dg';
|
|
3
|
+
import dayjs from 'dayjs';
|
|
4
|
+
import {_package} from '../package';
|
|
5
|
+
|
|
6
|
+
const USAGE_EVENT_TYPE = 'ai-request';
|
|
7
|
+
const SETTINGS_NAME = 'Grokky.UsageLimiter';
|
|
8
|
+
const SETTINGS_KEY_DATE = 'date';
|
|
9
|
+
const SETTINGS_KEY_COUNT = 'count';
|
|
10
|
+
|
|
11
|
+
interface LimitsConfig {
|
|
12
|
+
defaultDailyLimit: number;
|
|
13
|
+
groupLimits: Record<string, number>;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const DEFAULT_CONFIG: LimitsConfig = {
|
|
17
|
+
defaultDailyLimit: 20,
|
|
18
|
+
groupLimits: {
|
|
19
|
+
'AI Folks': 1000,
|
|
20
|
+
'Developers': 1000,
|
|
21
|
+
'Administrators': 1000,
|
|
22
|
+
},
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export class UsageLimiter {
|
|
26
|
+
private static _instance: UsageLimiter | null = null;
|
|
27
|
+
private config: LimitsConfig = DEFAULT_CONFIG;
|
|
28
|
+
private todayCount = 0;
|
|
29
|
+
private lastCountDate = '';
|
|
30
|
+
private dailyLimit: number | null = null;
|
|
31
|
+
|
|
32
|
+
private constructor() {}
|
|
33
|
+
|
|
34
|
+
static getInstance(): UsageLimiter {
|
|
35
|
+
UsageLimiter._instance ??= new UsageLimiter();
|
|
36
|
+
return UsageLimiter._instance;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async init(): Promise<void> {
|
|
40
|
+
this.loadCount();
|
|
41
|
+
await this.resolveDailyLimit();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
private today(): string { return dayjs().format('YYYY-MM-DD'); }
|
|
45
|
+
|
|
46
|
+
private loadCount(): void {
|
|
47
|
+
const saved = grok.userSettings.get(SETTINGS_NAME, true);
|
|
48
|
+
const today = this.today();
|
|
49
|
+
if (saved?.[SETTINGS_KEY_DATE] === today) {
|
|
50
|
+
this.todayCount = Number(saved[SETTINGS_KEY_COUNT]) || 0;
|
|
51
|
+
this.lastCountDate = today;
|
|
52
|
+
} else {
|
|
53
|
+
this.todayCount = 0;
|
|
54
|
+
this.lastCountDate = today;
|
|
55
|
+
this.saveCount();
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
private saveCount(): void {
|
|
60
|
+
grok.userSettings.put(SETTINGS_NAME, {
|
|
61
|
+
[SETTINGS_KEY_DATE]: this.lastCountDate,
|
|
62
|
+
[SETTINGS_KEY_COUNT]: String(this.todayCount),
|
|
63
|
+
}, true);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
private async resolveDailyLimit(): Promise<number> {
|
|
67
|
+
if (this.dailyLimit != null)
|
|
68
|
+
return this.dailyLimit;
|
|
69
|
+
const userGroup = await grok.dapi.groups.find(grok.shell.user.group.id);
|
|
70
|
+
const groups = [...userGroup.memberships, ...userGroup.adminMemberships].map((g: DG.Group) => g.friendlyName);
|
|
71
|
+
let max = this.config.defaultDailyLimit;
|
|
72
|
+
for (const [group, limit] of Object.entries(this.config.groupLimits)) {
|
|
73
|
+
if (groups.includes(group) && limit > max)
|
|
74
|
+
max = limit;
|
|
75
|
+
}
|
|
76
|
+
this.dailyLimit = max;
|
|
77
|
+
return max;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async checkAndIncrement(feature: string, model?: string): Promise<void> {
|
|
81
|
+
this.loadCount();
|
|
82
|
+
const limit = await this.resolveDailyLimit();
|
|
83
|
+
if (this.todayCount >= limit)
|
|
84
|
+
throw new Error(`You've reached your daily AI request limit (${limit}). Contact your administrator for a higher quota.`);
|
|
85
|
+
this.todayCount++;
|
|
86
|
+
this.saveCount();
|
|
87
|
+
_package.logger.usage(`${USAGE_EVENT_TYPE}:${feature} | ${model ?? 'unknown'}`);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Checks the limit and increments. Returns true if allowed, shows warning and returns false if over limit. */
|
|
91
|
+
async tryCheckAndIncrement(feature: string, model?: string): Promise<boolean> {
|
|
92
|
+
try {
|
|
93
|
+
await this.checkAndIncrement(feature, model);
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
catch (e: any) {
|
|
97
|
+
grok.shell.warning(e.message);
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
get remaining(): number { return Math.max(0, (this.dailyLimit ?? this.config.defaultDailyLimit) - this.todayCount); }
|
|
103
|
+
get limit(): number { return this.dailyLimit ?? this.config.defaultDailyLimit; }
|
|
104
|
+
get used(): number { return this.todayCount; }
|
|
105
|
+
}
|
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
import * as grok from 'datagrok-api/grok';
|
|
2
|
+
import * as DG from 'datagrok-api/dg';
|
|
3
|
+
import {TABLE_TOOL_DEFS, TABLE_TOOL_RUNNERS} from './table-tools';
|
|
4
|
+
|
|
5
|
+
export interface ViewToolDef {
|
|
6
|
+
name: string;
|
|
7
|
+
description: string;
|
|
8
|
+
inputSchema?: object;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Tools sent to the Claude runtime: serializable defs go in the user message,
|
|
12
|
+
* runners execute the matching input_request round-trips in the browser. */
|
|
13
|
+
export interface CollectedViewTools {
|
|
14
|
+
defs: ViewToolDef[];
|
|
15
|
+
runners: Map<string, (args: any) => any>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export const NO_VIEW_TOOLS: CollectedViewTools = {defs: [], runners: new Map()};
|
|
19
|
+
|
|
20
|
+
const FIND_LIMIT = 10;
|
|
21
|
+
const WIDGET_LIMIT = 100;
|
|
22
|
+
const WIDGET_DEPTH = 4;
|
|
23
|
+
|
|
24
|
+
/** Defensive accessors — widgets can be Dart-backed wrappers or pure JS, old or new api. */
|
|
25
|
+
function widgetChildren(w: any): any[] {
|
|
26
|
+
try {
|
|
27
|
+
const c = w?.children;
|
|
28
|
+
return Array.isArray(c) ? c.filter(Boolean) : [];
|
|
29
|
+
} catch (_) {
|
|
30
|
+
return [];
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function widgetAiDescription(w: any): string | null {
|
|
35
|
+
try {
|
|
36
|
+
const d = w?.aiDescription;
|
|
37
|
+
if (d)
|
|
38
|
+
return d;
|
|
39
|
+
} catch (_) {}
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function widgetFunctions(w: any): DG.Func[] {
|
|
44
|
+
try {
|
|
45
|
+
const list = w?.getFunctions?.();
|
|
46
|
+
return Array.isArray(list) ? list.filter((f: any) => f?.name) : [];
|
|
47
|
+
} catch (_) {
|
|
48
|
+
return [];
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface WidgetBrief {
|
|
53
|
+
ref: string;
|
|
54
|
+
type: string;
|
|
55
|
+
aiDescription?: string;
|
|
56
|
+
functions?: number;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Dialogs are widgets too, but they live outside the view's DOM subtree —
|
|
60
|
+
* surface them as extra widget roots (refs 'dlg0', 'dlg0.1', ...). */
|
|
61
|
+
function openDialogs(): any[] {
|
|
62
|
+
try {
|
|
63
|
+
const list = (DG.Dialog as any).getOpenDialogs?.();
|
|
64
|
+
return Array.isArray(list) ? list.filter(Boolean) : [];
|
|
65
|
+
} catch (_) {
|
|
66
|
+
return [];
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Flattens the widget tree of [view] plus any open dialogs into refs ('0', '0.2',
|
|
71
|
+
* 'dlg0', 'dlg0.1', ...) — index paths through `Widget.children`, resolvable back
|
|
72
|
+
* with resolveWidgetRef. */
|
|
73
|
+
export function collectWidgets(view: DG.ViewBase | null): WidgetBrief[] {
|
|
74
|
+
const result: WidgetBrief[] = [];
|
|
75
|
+
const walk = (w: any, ref: string, depth: number) => {
|
|
76
|
+
if (depth > WIDGET_DEPTH || result.length >= WIDGET_LIMIT)
|
|
77
|
+
return;
|
|
78
|
+
if (ref !== '') {
|
|
79
|
+
const ai = widgetAiDescription(w);
|
|
80
|
+
const funcCount = widgetFunctions(w).length;
|
|
81
|
+
result.push({
|
|
82
|
+
ref,
|
|
83
|
+
type: (() => { try { return w?.type ?? 'Widget'; } catch (_) { return 'Widget'; } })(),
|
|
84
|
+
...(ai ? {aiDescription: ai} : {}),
|
|
85
|
+
...(funcCount ? {functions: funcCount} : {}),
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
widgetChildren(w).forEach((c, i) => walk(c, ref === '' ? `${i}` : `${ref}.${i}`, depth + 1));
|
|
89
|
+
};
|
|
90
|
+
if (view)
|
|
91
|
+
walk(view, '', 0);
|
|
92
|
+
openDialogs().forEach((d, i) => walk(d, `dlg${i}`, 1));
|
|
93
|
+
return result;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Resolves a ref from collectWidgets back to the live widget; '' / null → the view itself. */
|
|
97
|
+
function resolveWidgetRef(view: DG.ViewBase | null, ref: string | null | undefined): any {
|
|
98
|
+
if (ref == null || ref === '')
|
|
99
|
+
return view;
|
|
100
|
+
const parts = String(ref).split('.');
|
|
101
|
+
const dlg = /^dlg(\d+)$/.exec(parts[0]);
|
|
102
|
+
let w: any = view;
|
|
103
|
+
if (dlg) {
|
|
104
|
+
w = openDialogs()[Number(dlg[1])];
|
|
105
|
+
parts.shift();
|
|
106
|
+
}
|
|
107
|
+
for (const part of parts) {
|
|
108
|
+
if (!w)
|
|
109
|
+
return null;
|
|
110
|
+
w = widgetChildren(w)[Number(part)];
|
|
111
|
+
}
|
|
112
|
+
return w ?? null;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Widgets of [view] that carry an AI briefing — used in the workspace context snapshot. */
|
|
116
|
+
export function widgetBriefings(view: DG.ViewBase | null, max: number = 6): WidgetBrief[] {
|
|
117
|
+
return collectWidgets(view).filter((w) => w.aiDescription).slice(0, max);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Functions applicable to a view, via `view.getFunctions()`: registered functions whose
|
|
121
|
+
* `meta.viewType` matches, view-specific functions added by Dart overrides (query/script
|
|
122
|
+
* editors), TableView commands, and — through the JsViewHost forwarding — functions a
|
|
123
|
+
* JS-defined view (e.g. Flow) returns from its own `getFunctions()` override. */
|
|
124
|
+
function viewFunctions(view: DG.ViewBase | null): DG.Func[] {
|
|
125
|
+
if (!view)
|
|
126
|
+
return [];
|
|
127
|
+
const funcs: DG.Func[] = [];
|
|
128
|
+
const seen = new Set<string>();
|
|
129
|
+
const collect = (list: any) => {
|
|
130
|
+
if (Array.isArray(list))
|
|
131
|
+
for (const f of list) {
|
|
132
|
+
const name = f?.name;
|
|
133
|
+
if (name && !seen.has(name)) {
|
|
134
|
+
seen.add(name);
|
|
135
|
+
funcs.push(f);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
try {
|
|
140
|
+
collect((view as any).getFunctions?.());
|
|
141
|
+
} catch (e: any) {
|
|
142
|
+
console.warn('Grokky: view.getFunctions failed:', e.message);
|
|
143
|
+
}
|
|
144
|
+
// Belt-and-braces for JS-defined views: reach the original ViewBase directly too.
|
|
145
|
+
try {
|
|
146
|
+
collect((view as any).jsView?.getFunctions?.());
|
|
147
|
+
} catch (e: any) {
|
|
148
|
+
console.warn('Grokky: jsView.getFunctions failed:', e.message);
|
|
149
|
+
}
|
|
150
|
+
return funcs;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** OR-ranking: how many query words appear in the function's name/description.
|
|
154
|
+
* AND-matching proved too strict — a query like "flow node pipeline graph" must
|
|
155
|
+
* still surface listFlowNodes even though "pipeline" matches nothing. */
|
|
156
|
+
function matchScore(query: string, ...haystacks: (string | null | undefined)[]): number {
|
|
157
|
+
const terms = query.toLowerCase().split(/\s+/).filter((t) => t.length > 0);
|
|
158
|
+
if (terms.length === 0)
|
|
159
|
+
return 1;
|
|
160
|
+
const text = haystacks.filter(Boolean).join(' ').toLowerCase();
|
|
161
|
+
return terms.filter((t) => text.includes(t)).length;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Compact, LLM-friendly description of a function: name, description, and inputs
|
|
165
|
+
* (the `view`/`widget` inputs are injected automatically at call time, so they are not listed). */
|
|
166
|
+
function funcBrief(f: DG.Func): object {
|
|
167
|
+
let inputs: object[] = [];
|
|
168
|
+
try {
|
|
169
|
+
inputs = f.inputs
|
|
170
|
+
.filter((p) => p.name !== 'view' && (p.propertyType as string) !== 'view' &&
|
|
171
|
+
p.name !== 'widget' && (p.propertyType as string) !== 'widget')
|
|
172
|
+
.map((p) => ({
|
|
173
|
+
name: p.name,
|
|
174
|
+
type: p.propertyType,
|
|
175
|
+
...(p.description ? {description: p.description} : {}),
|
|
176
|
+
}));
|
|
177
|
+
} catch (_) {}
|
|
178
|
+
return {
|
|
179
|
+
name: f.name,
|
|
180
|
+
description: f.description || f.friendlyName || f.name,
|
|
181
|
+
...(inputs.length ? {inputs} : {}),
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Result values can be DG objects — reduce them to something JSON-serializable. */
|
|
186
|
+
function serializeResult(value: any): any {
|
|
187
|
+
if (value == null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean')
|
|
188
|
+
return value;
|
|
189
|
+
if (value instanceof DG.DataFrame)
|
|
190
|
+
return {type: 'dataframe', name: value.name, rowCount: value.rowCount, columns: value.columns.names()};
|
|
191
|
+
if (value instanceof DG.Column)
|
|
192
|
+
return {type: 'column', name: value.name, length: value.length};
|
|
193
|
+
if (value instanceof DG.ViewBase)
|
|
194
|
+
return {type: 'view', name: value.name};
|
|
195
|
+
try {
|
|
196
|
+
return JSON.parse(JSON.stringify(value));
|
|
197
|
+
} catch (_) {
|
|
198
|
+
return String(value);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Function list for a tool call: the view's own set, or a sub-widget's when a
|
|
203
|
+
* `widget` ref (from list_view_widgets) is passed. */
|
|
204
|
+
function targetFunctions(view: DG.ViewBase | null, widgetRef: string | null | undefined): DG.Func[] | null {
|
|
205
|
+
if (widgetRef == null || widgetRef === '')
|
|
206
|
+
return viewFunctions(view);
|
|
207
|
+
const w = resolveWidgetRef(view, widgetRef);
|
|
208
|
+
return w ? widgetFunctions(w) : null;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async function invokeViewFunction(args: any): Promise<any> {
|
|
212
|
+
const view = grok.shell.v;
|
|
213
|
+
const name = args?.name;
|
|
214
|
+
const funcs = targetFunctions(view, args?.widget);
|
|
215
|
+
if (funcs === null)
|
|
216
|
+
return {success: false, error: `No widget '${args?.widget}' in the current view — call list_view_widgets for the current refs`};
|
|
217
|
+
const f = funcs.find((x) => x.name === name);
|
|
218
|
+
if (!f) {
|
|
219
|
+
return {
|
|
220
|
+
success: false,
|
|
221
|
+
error: `No function '${name}' on the current ${args?.widget ? 'widget' : 'view'} — call list_view_functions to see what is available`,
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
const params: {[key: string]: any} = {...(args?.parameters ?? {})};
|
|
225
|
+
// the targeted widget (when a ref was passed) — injected into `widget`-typed inputs,
|
|
226
|
+
// the calling convention of shared widget-action vocabularies (one Func per action,
|
|
227
|
+
// taking the widget it acts on)
|
|
228
|
+
const targetWidget = args?.widget != null && args.widget !== '' ? resolveWidgetRef(view, args.widget) : null;
|
|
229
|
+
for (const inp of f.inputs) {
|
|
230
|
+
if (inp.name in params)
|
|
231
|
+
continue;
|
|
232
|
+
if (inp.name === 'view' || (inp.propertyType as string) === 'view')
|
|
233
|
+
params[inp.name] = view;
|
|
234
|
+
else if (inp.name === 'widget' || (inp.propertyType as string) === 'widget')
|
|
235
|
+
params[inp.name] = targetWidget ?? view;
|
|
236
|
+
}
|
|
237
|
+
const result = await f.apply(params);
|
|
238
|
+
return {success: true, ...(result != null ? {result: serializeResult(result)} : {})};
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const widgetRefProperty = {
|
|
242
|
+
widget: {type: 'string', description: 'Optional widget ref from list_view_widgets (e.g. "0.2", or "dlg0" for an open dialog) to target that widget instead of the view itself.'},
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
const invocationSchema = {
|
|
246
|
+
type: 'object',
|
|
247
|
+
properties: {
|
|
248
|
+
name: {type: 'string', description: 'Function name, exactly as returned by list_view_functions.'},
|
|
249
|
+
parameters: {type: 'object', description: 'Arguments keyed by input name (the view argument is injected automatically).'},
|
|
250
|
+
...widgetRefProperty,
|
|
251
|
+
},
|
|
252
|
+
required: ['name'],
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
const confirmSchema = {
|
|
256
|
+
type: 'object',
|
|
257
|
+
properties: {
|
|
258
|
+
action: {type: 'string', description: 'Short imperative label, at most three words, e.g. "Delete project" — the card title.'},
|
|
259
|
+
name: {type: 'string', description: 'Entity name shown to the user.'},
|
|
260
|
+
owner: {type: 'string', description: 'Owner login or display name.'},
|
|
261
|
+
created: {type: 'string', description: 'Creation date as YYYY-MM-DD.'},
|
|
262
|
+
details: {type: 'string', description: 'Any other user-facing facts, e.g. "3 tables; shared with Chemists". Never ids.'},
|
|
263
|
+
},
|
|
264
|
+
required: ['action', 'name'],
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
/** The meta-tools are static — same defs every turn (prompt-cache friendly);
|
|
268
|
+
* the runners resolve the live current view (and optional widget ref) at call time. */
|
|
269
|
+
const VIEW_TOOL_DEFS: ViewToolDef[] = [
|
|
270
|
+
{
|
|
271
|
+
name: 'list_view_functions',
|
|
272
|
+
description: 'Search the functions applicable to the current view — its commands and view-specific ' +
|
|
273
|
+
'operations (e.g. the query editor\'s SQL tools, Flow\'s graph tools). A view can have hundreds, ' +
|
|
274
|
+
`so ALWAYS pass a query; at most ${FIND_LIMIT} matches are returned. ` +
|
|
275
|
+
'Call this first when acting on the current view or when asked what you can do "here". ' +
|
|
276
|
+
'Pass a widget ref (from list_view_widgets) to list a specific sub-widget\'s functions instead.',
|
|
277
|
+
inputSchema: {
|
|
278
|
+
type: 'object',
|
|
279
|
+
properties: {
|
|
280
|
+
query: {type: 'string', description: 'One or two broad words matched against function names and descriptions (OR-ranked — more matching words rank higher). Omit to see the first 10.'},
|
|
281
|
+
...widgetRefProperty,
|
|
282
|
+
},
|
|
283
|
+
},
|
|
284
|
+
},
|
|
285
|
+
{
|
|
286
|
+
name: 'list_view_widgets',
|
|
287
|
+
description: 'List the widget tree of the current view (grid, viewers, editors, tab controls, panels) ' +
|
|
288
|
+
'plus any OPEN DIALOGS (refs dlg0, dlg0.1, ...), each with its ref, type, AI briefing ' +
|
|
289
|
+
'(aiDescription), and function count. Use a ref as the `widget` argument of list_view_functions / ' +
|
|
290
|
+
'get_view_function_result / call_view_function to inspect or drive that specific widget — e.g. a ' +
|
|
291
|
+
'dialog exposes getDialogInfo / setInput / clickButton. Call it when the view-level functions ' +
|
|
292
|
+
'are not enough, or whenever a dialog is open.',
|
|
293
|
+
inputSchema: {type: 'object', properties: {}},
|
|
294
|
+
},
|
|
295
|
+
{
|
|
296
|
+
name: 'get_view_function_result',
|
|
297
|
+
description: 'Invoke a READ-ONLY function of the current view or one of its widgets (one that inspects ' +
|
|
298
|
+
'state without changing anything, e.g. getQueryInfo, listFlowNodes) and return its result. ' +
|
|
299
|
+
'For functions that change state, use call_view_function instead.',
|
|
300
|
+
inputSchema: invocationSchema,
|
|
301
|
+
},
|
|
302
|
+
{
|
|
303
|
+
name: 'call_view_function',
|
|
304
|
+
description: 'Invoke a state-changing function of the current view or one of its widgets ' +
|
|
305
|
+
'(e.g. setQueryAndRun, addFlowNode). Function name and parameters come from list_view_functions.',
|
|
306
|
+
inputSchema: invocationSchema,
|
|
307
|
+
},
|
|
308
|
+
{
|
|
309
|
+
name: 'datagrok_confirm',
|
|
310
|
+
description: 'Ask the user to approve a destructive action (delete, overwrite) after a dryRun ' +
|
|
311
|
+
'tool response, before repeating that call with its confirm token. The card presents the ' +
|
|
312
|
+
'facts — do NOT restate them in your message text. Returns {confirmed: boolean}; treat a ' +
|
|
313
|
+
'timeout or error as not confirmed.',
|
|
314
|
+
inputSchema: confirmSchema,
|
|
315
|
+
},
|
|
316
|
+
];
|
|
317
|
+
|
|
318
|
+
/** Tool set declared to the runtime on every full-mode prompt. */
|
|
319
|
+
export function viewFunctionTools(): CollectedViewTools {
|
|
320
|
+
const runners = new Map<string, (args: any) => any>(TABLE_TOOL_RUNNERS);
|
|
321
|
+
runners.set('list_view_widgets', () => {
|
|
322
|
+
const widgets = collectWidgets(grok.shell.v);
|
|
323
|
+
return {
|
|
324
|
+
total: widgets.length,
|
|
325
|
+
widgets,
|
|
326
|
+
...(widgets.length === 0 ? {note: 'This view exposes no sub-widgets — use the view-level functions'} : {}),
|
|
327
|
+
};
|
|
328
|
+
});
|
|
329
|
+
runners.set('list_view_functions', (args: any) => {
|
|
330
|
+
const funcs = targetFunctions(grok.shell.v, args?.widget);
|
|
331
|
+
if (funcs === null)
|
|
332
|
+
return {total: 0, functions: [], note: `No widget '${args?.widget}' in the current view — call list_view_widgets for the current refs`};
|
|
333
|
+
let matched = funcs;
|
|
334
|
+
if (args?.query) {
|
|
335
|
+
matched = funcs
|
|
336
|
+
.map((f) => ({f, score: matchScore(args.query, f.name, f.friendlyName, f.description)}))
|
|
337
|
+
.filter((x) => x.score > 0)
|
|
338
|
+
.sort((a, b) => b.score - a.score)
|
|
339
|
+
.map((x) => x.f);
|
|
340
|
+
}
|
|
341
|
+
if (matched.length === 0 && funcs.length > 0)
|
|
342
|
+
return {total: 0, functions: [], note: `No matches, but this view has ${funcs.length} functions — retry with a broader word or no query`};
|
|
343
|
+
return {
|
|
344
|
+
total: matched.length,
|
|
345
|
+
functions: matched.slice(0, FIND_LIMIT).map(funcBrief),
|
|
346
|
+
...(matched.length > FIND_LIMIT ? {note: `Showing ${FIND_LIMIT} of ${matched.length} — refine the query`} : {}),
|
|
347
|
+
};
|
|
348
|
+
});
|
|
349
|
+
runners.set('get_view_function_result', invokeViewFunction);
|
|
350
|
+
runners.set('call_view_function', invokeViewFunction);
|
|
351
|
+
return {defs: [...VIEW_TOOL_DEFS, ...TABLE_TOOL_DEFS], runners};
|
|
352
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** The AI features, as the prefixes of their session IDs: the usage log reads a turn's feature from its session. */
|
|
2
|
+
export enum AiFeature {
|
|
3
|
+
Chat = 'chat',
|
|
4
|
+
Engine = 'engine',
|
|
5
|
+
Execute = 'execute',
|
|
6
|
+
Help = 'help',
|
|
7
|
+
Search = 'search',
|
|
8
|
+
QueryMatch = 'query-match',
|
|
9
|
+
DbIndex = 'db-index',
|
|
10
|
+
Benchmark = 'benchmark',
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Chats restored from before these prefixes start with `claude-`, so anything unmatched is a chat. */
|
|
14
|
+
export function featureOf(sessionId: string): AiFeature {
|
|
15
|
+
return Object.values(AiFeature).find((f) => sessionId.startsWith(`${f}-`)) ?? AiFeature.Chat;
|
|
16
|
+
}
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import * as grok from 'datagrok-api/grok';
|
|
2
|
+
import * as ui from 'datagrok-api/ui';
|
|
3
|
+
import * as DG from 'datagrok-api/dg';
|
|
4
|
+
import {widgetBriefings} from '../ai/view-tools';
|
|
5
|
+
import {undoable} from './undoable';
|
|
6
|
+
|
|
7
|
+
export interface ExecError {
|
|
8
|
+
blockIndex: number;
|
|
9
|
+
error: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export async function executeSingleBlock(
|
|
13
|
+
code: string, view: DG.ViewBase, blockIndex: number,
|
|
14
|
+
): Promise<{element: HTMLElement | null; value: any; error: ExecError | null}> {
|
|
15
|
+
try {
|
|
16
|
+
// Prefer the live current view: Claude may have opened a new view earlier in the same turn.
|
|
17
|
+
const liveView = grok.shell.v ?? view;
|
|
18
|
+
const t = liveView?.type === DG.VIEW_TYPE.TABLE_VIEW ? (liveView as DG.TableView).dataFrame : undefined;
|
|
19
|
+
const result = await new Function('grok', 'ui', 'DG', 'view', 't', 'undoable',
|
|
20
|
+
'return (async () => {' + code + '})()',
|
|
21
|
+
)(grok, ui, DG, liveView, t, undoable);
|
|
22
|
+
const element = result instanceof HTMLElement ? result : null;
|
|
23
|
+
return {element, value: element ? undefined : result, error: null};
|
|
24
|
+
} catch (e: any) {
|
|
25
|
+
return {element: null, value: undefined, error: {blockIndex, error: e?.message ?? String(e)}};
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const VERIFY_TIMEOUT_MS = 30000;
|
|
30
|
+
|
|
31
|
+
export interface VerificationResult {
|
|
32
|
+
passed: boolean;
|
|
33
|
+
observed: any;
|
|
34
|
+
error: string | null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Models routinely write assertions as bare expressions ("view.viewers.length >= 5"); inside the
|
|
38
|
+
* async IIFE that evaluates to undefined, and a successful action then reads as a failed verify —
|
|
39
|
+
* which sends the model into a redo loop that duplicates the action. Wrap single-expression
|
|
40
|
+
* assertions in a return; multi-statement code is left as written. */
|
|
41
|
+
function wrapAssertion(assertion: string): string {
|
|
42
|
+
if (/\breturn\b/.test(assertion))
|
|
43
|
+
return assertion;
|
|
44
|
+
try {
|
|
45
|
+
new Function('return (' + assertion + '\n)');
|
|
46
|
+
return 'return (' + assertion + '\n)';
|
|
47
|
+
} catch (_) {
|
|
48
|
+
return assertion;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export async function runVerification(
|
|
53
|
+
assertion: string, view: DG.ViewBase,
|
|
54
|
+
): Promise<VerificationResult> {
|
|
55
|
+
const liveView = grok.shell.v ?? view;
|
|
56
|
+
const timeout = new Promise<null>((resolve) => setTimeout(() => resolve(null), VERIFY_TIMEOUT_MS));
|
|
57
|
+
const res = await Promise.race([executeSingleBlock(wrapAssertion(assertion), liveView, 0), timeout]);
|
|
58
|
+
if (res === null)
|
|
59
|
+
return {passed: false, observed: undefined, error: `Verification timed out after ${VERIFY_TIMEOUT_MS / 1000}s`};
|
|
60
|
+
if (res.element)
|
|
61
|
+
return {passed: false, observed: undefined, error: 'Assertion must return the observed value, not a DOM element'};
|
|
62
|
+
if (res.error == null && res.value === undefined) {
|
|
63
|
+
return {passed: false, observed: undefined,
|
|
64
|
+
error: 'assertion returned undefined — it must `return` the observed value. ' +
|
|
65
|
+
'This says nothing about the action itself, which may well have succeeded: ' +
|
|
66
|
+
're-read the live state with a corrected read-only assertion before redoing anything.'};
|
|
67
|
+
}
|
|
68
|
+
// A comparison can be true for the wrong reason (`undefined === undefined` when both names are wrong).
|
|
69
|
+
if (res.error == null && res.value === true) {
|
|
70
|
+
return {passed: false, observed: true,
|
|
71
|
+
error: 'assertion returned bare `true` — return the values it read (e.g. `{type: col.meta.colors.getType()}`), ' +
|
|
72
|
+
'so the observed state shows. The action itself may well have succeeded: re-read, do not redo it.'};
|
|
73
|
+
}
|
|
74
|
+
return {passed: res.error == null && !!res.value, observed: res.value, error: res.error?.error ?? null};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function describeTable(df: DG.DataFrame): string {
|
|
78
|
+
const cols = df.columns.toList().map((c) => `${c.name}(${c.type})`).join(', ');
|
|
79
|
+
return `Table "${df.name}" (${df.rowCount} rows): ${cols}`;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function buildViewContext(view: DG.ViewBase): string {
|
|
83
|
+
if (view.type === DG.VIEW_TYPE.TABLE_VIEW) {
|
|
84
|
+
const df = (view as DG.TableView).dataFrame;
|
|
85
|
+
return df ? describeTable(df) : '';
|
|
86
|
+
}
|
|
87
|
+
if (view.type === 'ScriptView') {
|
|
88
|
+
const scriptView = view as DG.ScriptView;
|
|
89
|
+
const code = scriptView.code;
|
|
90
|
+
if (code)
|
|
91
|
+
return `ScriptView "${view.name}"\nCurrent script:\n\`\`\`\n${code}\n\`\`\``;
|
|
92
|
+
return `ScriptView "${view.name}" (empty script)`;
|
|
93
|
+
}
|
|
94
|
+
return '';
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Snapshot of everything the user has open: current view (detailed), other views, and workspace tables. */
|
|
98
|
+
export function buildWorkspaceContext(): string {
|
|
99
|
+
const lines: string[] = [];
|
|
100
|
+
const current = grok.shell.v;
|
|
101
|
+
if (current) {
|
|
102
|
+
lines.push(`Current view: "${current.name}" (${current.type})`);
|
|
103
|
+
const ai = (current as any).aiDescription;
|
|
104
|
+
if (ai)
|
|
105
|
+
lines.push(`About this view: ${ai}`);
|
|
106
|
+
const briefed = widgetBriefings(current);
|
|
107
|
+
if (briefed.length > 0)
|
|
108
|
+
lines.push('Widgets here, including open dialogs (drill in with list_view_widgets / list_view_functions): ' +
|
|
109
|
+
briefed.map((w) => `${w.type} — ${w.aiDescription}`).join('; '));
|
|
110
|
+
const details = buildViewContext(current);
|
|
111
|
+
if (details)
|
|
112
|
+
lines.push(details);
|
|
113
|
+
}
|
|
114
|
+
const others = Array.from(grok.shell.views).filter((v) => v !== current);
|
|
115
|
+
if (others.length > 0) {
|
|
116
|
+
lines.push('Other open views: ' + others.map((v) => {
|
|
117
|
+
const df = v.type === DG.VIEW_TYPE.TABLE_VIEW ? (v as DG.TableView).dataFrame : null;
|
|
118
|
+
return `"${v.name}" (${v.type}${df ? `, table "${df.name}"` : ''})`;
|
|
119
|
+
}).join(', '));
|
|
120
|
+
}
|
|
121
|
+
const currentTable = current?.type === DG.VIEW_TYPE.TABLE_VIEW ? (current as DG.TableView).dataFrame : null;
|
|
122
|
+
for (const t of grok.shell.tables.filter((t) => t !== currentTable))
|
|
123
|
+
lines.push(describeTable(t));
|
|
124
|
+
return lines.length > 0 ? 'Workspace state (live, changes as the user navigates):\n' + lines.join('\n') : '';
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export interface DgEntityRef {
|
|
128
|
+
type: 'file' | 'script' | 'query' | 'connection' | 'project' | 'space' | 'group' | 'user';
|
|
129
|
+
name: string;
|
|
130
|
+
id?: string;
|
|
131
|
+
connector?: string;
|
|
132
|
+
path?: string;
|
|
133
|
+
isDirectory?: boolean;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async function fetchEntity(ref: DgEntityRef): Promise<any> {
|
|
137
|
+
switch (ref.type) {
|
|
138
|
+
case 'file':
|
|
139
|
+
if (ref.isDirectory)
|
|
140
|
+
return null;
|
|
141
|
+
if (ref.connector && ref.name) {
|
|
142
|
+
const files = await grok.dapi.files.list(`${ref.connector}/`, true, ref.name);
|
|
143
|
+
return files.find((f) => f.fileName === ref.name) ?? null;
|
|
144
|
+
}
|
|
145
|
+
return null;
|
|
146
|
+
case 'script':
|
|
147
|
+
return ref.id ? grok.dapi.scripts.find(ref.id) : null;
|
|
148
|
+
case 'query':
|
|
149
|
+
return ref.id ? grok.dapi.queries.find(ref.id) : null;
|
|
150
|
+
case 'connection':
|
|
151
|
+
return ref.id ? grok.dapi.connections.find(ref.id) : null;
|
|
152
|
+
case 'project':
|
|
153
|
+
return ref.id ? grok.dapi.projects.find(ref.id) : null;
|
|
154
|
+
case 'space':
|
|
155
|
+
return ref.id ? grok.dapi.spaces.find(ref.id) : null;
|
|
156
|
+
case 'group':
|
|
157
|
+
return ref.id ? grok.dapi.groups.find(ref.id) : null;
|
|
158
|
+
case 'user':
|
|
159
|
+
return ref.id ? grok.dapi.users.find(ref.id) : null;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function renderEntityRef(ref: DgEntityRef): HTMLElement | null {
|
|
164
|
+
const placeholder = ui.divText(ref.name);
|
|
165
|
+
fetchEntity(ref).then((entity) => {
|
|
166
|
+
if (entity && document.contains(placeholder))
|
|
167
|
+
placeholder.replaceWith(ui.renderCard(entity));
|
|
168
|
+
}).catch(() => {});
|
|
169
|
+
return placeholder;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export function renderEntityRefList(refs: DgEntityRef[]): HTMLElement {
|
|
173
|
+
const cards = refs.map(renderEntityRef).filter((c): c is HTMLElement => c !== null);
|
|
174
|
+
return ui.divV(cards, 'grokky-entity-cards');
|
|
175
|
+
}
|
|
176
|
+
|