@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/ai/ui.ts
ADDED
|
@@ -0,0 +1,720 @@
|
|
|
1
|
+
/* eslint-disable max-len */
|
|
2
|
+
|
|
3
|
+
import * as grok from 'datagrok-api/grok';
|
|
4
|
+
import * as ui from 'datagrok-api/ui';
|
|
5
|
+
import * as DG from 'datagrok-api/dg';
|
|
6
|
+
import * as rxjs from 'rxjs';
|
|
7
|
+
|
|
8
|
+
import {CombinedAISearchAssistant} from './search/combined-search';
|
|
9
|
+
import {fireAIPanelToggleEvent, getAIAbortSubscription, fireBeforeUserPromptEvent,
|
|
10
|
+
fireAfterUserPromptEvent, UserPromptEventArgs, createStyledMarkdown, tryMarkdown, plainTextEl,
|
|
11
|
+
SHORTCUT_HINT, copyToClipboard} from '../utils';
|
|
12
|
+
import {AIPanel, StreamingPanel, StripStyle} from './panel';
|
|
13
|
+
import {AIWindowManager} from './ai-window';
|
|
14
|
+
import {ClaudeRuntimeClient, ErrorEvent, FinalEvent, ToolActivityEvent} from '../claude/runtime-client';
|
|
15
|
+
import {executeSingleBlock, runVerification, renderEntityRefList} from '../claude/exec-blocks';
|
|
16
|
+
import {sendChatTurn} from '../claude/queue-task';
|
|
17
|
+
import {UsageLimiter} from './usage-limiter';
|
|
18
|
+
import {viewFunctionTools, NO_VIEW_TOOLS} from './view-tools';
|
|
19
|
+
import {resolveScopes, showSuggestionsMenu, SearchProvider} from './prompt-suggestions';
|
|
20
|
+
import {AiFeature} from '../claude/ai-feature';
|
|
21
|
+
|
|
22
|
+
interface ExecutionPlan {
|
|
23
|
+
plan: string[];
|
|
24
|
+
code: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const executionPlanSchema = {
|
|
28
|
+
type: 'object',
|
|
29
|
+
properties: {
|
|
30
|
+
plan: {
|
|
31
|
+
type: 'array',
|
|
32
|
+
items: {type: 'string'},
|
|
33
|
+
description: 'Steps to achieve the goal. Each item is a single step, plain text, without any leading number, bullet, or punctuation prefix.',
|
|
34
|
+
},
|
|
35
|
+
code: {
|
|
36
|
+
type: 'string',
|
|
37
|
+
description: 'Datagrok JavaScript code to execute. Uses globals: grok, ui, DG, view (current view), t (DataFrame if in TableView). Use await freely. Return an HTMLElement to display a result.',
|
|
38
|
+
},
|
|
39
|
+
},
|
|
40
|
+
required: ['plan', 'code'],
|
|
41
|
+
additionalProperties: false,
|
|
42
|
+
} as const;
|
|
43
|
+
|
|
44
|
+
const MAX_ACTIVITY_LINES = 5;
|
|
45
|
+
|
|
46
|
+
interface StreamingOpts {
|
|
47
|
+
sessionPrefix: AiFeature;
|
|
48
|
+
sessionId?: string;
|
|
49
|
+
outputSchema?: object;
|
|
50
|
+
onFinal: (evt: FinalEvent, host: HTMLElement) => void | Promise<void>;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
interface ConfirmInput {
|
|
54
|
+
action?: string;
|
|
55
|
+
name?: string;
|
|
56
|
+
owner?: string;
|
|
57
|
+
created?: string;
|
|
58
|
+
details?: string;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
type ConfirmOutcome = 'confirmed' | 'cancelled' | 'unanswered';
|
|
62
|
+
|
|
63
|
+
interface ConfirmCard {
|
|
64
|
+
root: HTMLElement;
|
|
65
|
+
close: (outcome: ConfirmOutcome) => void;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const CONFIRM_OUTCOMES: Record<ConfirmOutcome, {style: StripStyle, icon: string, text: string}> = {
|
|
69
|
+
confirmed: {style: 'success', icon: 'check', text: 'Confirmed'},
|
|
70
|
+
cancelled: {style: 'muted', icon: 'times', text: 'Cancelled'},
|
|
71
|
+
unanswered: {style: 'muted', icon: 'minus', text: 'Not answered'},
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
enum Status {
|
|
75
|
+
None = '',
|
|
76
|
+
Tool = 'tool',
|
|
77
|
+
Writing = 'writing',
|
|
78
|
+
Revising = 'revising',
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export const RENDERED_EVENT = 'grokky-rendered';
|
|
82
|
+
|
|
83
|
+
async function streamingWidget(prompt: string, opts: StreamingOpts): Promise<DG.Widget> {
|
|
84
|
+
const client = ClaudeRuntimeClient.getInstance();
|
|
85
|
+
await client.ensureConnected();
|
|
86
|
+
const sessionId = opts.sessionId ?? `${opts.sessionPrefix}-${crypto.randomUUID()}`;
|
|
87
|
+
|
|
88
|
+
const activityHost = ui.divV([], 'grokky-stream-activity');
|
|
89
|
+
const contentHost = ui.div([], 'grokky-stream-content');
|
|
90
|
+
const container = ui.divV([activityHost, contentHost], 'grokky-stream');
|
|
91
|
+
|
|
92
|
+
let onFirstEvent: () => void = () => {};
|
|
93
|
+
const firstEvent = new Promise<void>((res) => { onFirstEvent = res; });
|
|
94
|
+
|
|
95
|
+
const widget = DG.Widget.fromRoot(ui.wait(async () => {
|
|
96
|
+
await firstEvent;
|
|
97
|
+
return container;
|
|
98
|
+
}));
|
|
99
|
+
|
|
100
|
+
const signalRendered = () => grok.events.fireCustomEvent(RENDERED_EVENT, sessionId);
|
|
101
|
+
|
|
102
|
+
const sessionSubs: rxjs.Subscription[] = [];
|
|
103
|
+
const forSession = <T extends {sessionId: string}>(
|
|
104
|
+
src: rxjs.Observable<T>, handler: (evt: T) => void,
|
|
105
|
+
) => {
|
|
106
|
+
const sub = src.subscribe((evt) => {
|
|
107
|
+
if (evt.sessionId === sessionId)
|
|
108
|
+
handler(evt);
|
|
109
|
+
});
|
|
110
|
+
widget.subs.push(sub);
|
|
111
|
+
sessionSubs.push(sub);
|
|
112
|
+
};
|
|
113
|
+
const stopListening = () => sessionSubs.forEach((s) => s.unsubscribe());
|
|
114
|
+
|
|
115
|
+
forSession<ToolActivityEvent>(client.onToolActivity, (evt) => {
|
|
116
|
+
activityHost.appendChild(ui.divText(evt.summary, 'grokky-stream-activity-line'));
|
|
117
|
+
while (activityHost.children.length > MAX_ACTIVITY_LINES)
|
|
118
|
+
activityHost.removeChild(activityHost.firstChild!);
|
|
119
|
+
onFirstEvent();
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
forSession<FinalEvent>(client.onFinal, async (evt) => {
|
|
123
|
+
activityHost.remove();
|
|
124
|
+
onFirstEvent();
|
|
125
|
+
try {
|
|
126
|
+
await opts.onFinal(evt, contentHost);
|
|
127
|
+
} finally {
|
|
128
|
+
signalRendered();
|
|
129
|
+
stopListening();
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
forSession<ErrorEvent>(client.onError, (evt) => {
|
|
134
|
+
activityHost.remove();
|
|
135
|
+
contentHost.appendChild(ui.info(`Error: ${evt.message}`));
|
|
136
|
+
onFirstEvent();
|
|
137
|
+
signalRendered();
|
|
138
|
+
stopListening();
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
client.send(sessionId, prompt, {logPrompt: prompt, outputSchema: opts.outputSchema, systemPromptMode: 'search'});
|
|
142
|
+
return widget;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export async function smartExecution(prompt: string, sessionId?: string): Promise<DG.Widget> {
|
|
146
|
+
return streamingWidget(prompt, {
|
|
147
|
+
sessionId,
|
|
148
|
+
sessionPrefix: AiFeature.Execute,
|
|
149
|
+
outputSchema: executionPlanSchema,
|
|
150
|
+
onFinal: async (evt, host) => {
|
|
151
|
+
const result = evt.structured_output as ExecutionPlan | undefined;
|
|
152
|
+
if (!result) {
|
|
153
|
+
host.appendChild(ui.divText(evt.content || 'No plan returned.'));
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
host.appendChild(ui.markdown(result.plan.map((s, i) => `${i + 1}. ${s}`).join('\n'), {sanitize: true}));
|
|
158
|
+
if (!result.code)
|
|
159
|
+
return;
|
|
160
|
+
|
|
161
|
+
const codeAcc = ui.accordion();
|
|
162
|
+
const fencedCode = '```datagrok-exec\n' + result.code + '\n```';
|
|
163
|
+
codeAcc.addPane('Code', () => createStyledMarkdown(fencedCode), false);
|
|
164
|
+
host.appendChild(codeAcc.root);
|
|
165
|
+
|
|
166
|
+
let resolveExec: () => void = () => {};
|
|
167
|
+
const execDone = new Promise<void>((res) => { resolveExec = res; });
|
|
168
|
+
host.appendChild(ui.wait(async () => {
|
|
169
|
+
try {
|
|
170
|
+
const {element, error} = await executeSingleBlock(result.code, grok.shell.v, 0);
|
|
171
|
+
if (error)
|
|
172
|
+
return ui.info(`Execution error: ${error.error}`);
|
|
173
|
+
return element ?? ui.divText('');
|
|
174
|
+
} finally {
|
|
175
|
+
resolveExec();
|
|
176
|
+
}
|
|
177
|
+
}));
|
|
178
|
+
await execDone;
|
|
179
|
+
},
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export async function askWiki(question: string, sessionId?: string): Promise<DG.Widget> {
|
|
184
|
+
return streamingWidget(question, {
|
|
185
|
+
sessionId,
|
|
186
|
+
sessionPrefix: AiFeature.Help,
|
|
187
|
+
onFinal: (evt, host) => {
|
|
188
|
+
const text = evt.content || '';
|
|
189
|
+
const md = tryMarkdown(text) ?? plainTextEl(text);
|
|
190
|
+
md.style.userSelect = 'text';
|
|
191
|
+
host.appendChild(md);
|
|
192
|
+
},
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// sets up the ui button for the input
|
|
197
|
+
export function setupSearchUI() {
|
|
198
|
+
if (!ClaudeRuntimeClient.getInstance().available) {
|
|
199
|
+
console.warn('Claude runtime container not found. Search UI will not have AI assistance.');
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const maxRetries = 10;
|
|
204
|
+
function searchForSearchBox() {
|
|
205
|
+
return document.querySelector<HTMLInputElement>('.power-search-search-everywhere-input');
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function initInput(searchInput: HTMLInputElement) {
|
|
209
|
+
const parent: HTMLElement = searchInput.parentElement!;
|
|
210
|
+
const wandIcon = ui.iconFA('magic', async (e) => {
|
|
211
|
+
const scopes = await resolveScopes('powerSearch');
|
|
212
|
+
showSuggestionsMenu(scopes, (s, provider) => {
|
|
213
|
+
const prompt = s.prompt ?? '';
|
|
214
|
+
searchInput.value = prompt;
|
|
215
|
+
searchInput.dispatchEvent(new Event('input', {bubbles: true}));
|
|
216
|
+
// PowerPack's input handler debounces 500ms and then calls ui.empty(host) on power-pack-search-host;
|
|
217
|
+
// wait past that so the AI loader/result isn't wiped immediately after we prepend it.
|
|
218
|
+
setTimeout(() => {
|
|
219
|
+
CombinedAISearchAssistant.instance.resetSearchUI();
|
|
220
|
+
aiCombinedSearch(prompt, provider);
|
|
221
|
+
}, 600);
|
|
222
|
+
}, e);
|
|
223
|
+
}, 'Prompt suggestions');
|
|
224
|
+
wandIcon.classList.add('grokky-search-wand');
|
|
225
|
+
parent.insertBefore(wandIcon, searchInput);
|
|
226
|
+
|
|
227
|
+
const searchHelpDiv = document.getElementsByClassName('power-search-help-text-container')[0] as HTMLDivElement;
|
|
228
|
+
if (searchHelpDiv) {
|
|
229
|
+
searchHelpDiv.innerText = `Press Enter to grok. ${searchHelpDiv.innerText}`;
|
|
230
|
+
searchHelpDiv.style.display = 'none';
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
searchInput.addEventListener('keyup', (event: KeyboardEvent) => {
|
|
234
|
+
if (event.key === 'Enter' && searchInput.value?.trim()) {
|
|
235
|
+
event.preventDefault();
|
|
236
|
+
setTimeout(() => aiCombinedSearch(searchInput.value), 400); // timeout needed to allow other enter handlers to run first
|
|
237
|
+
}
|
|
238
|
+
if (searchHelpDiv)
|
|
239
|
+
searchHelpDiv.style.display = searchInput.value?.trim().split(' ').length > 1 ? '' : 'none';
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
let retries = 0;
|
|
244
|
+
const intervalId = setInterval(() => {
|
|
245
|
+
const searchInput = searchForSearchBox();
|
|
246
|
+
if (searchInput) {
|
|
247
|
+
clearInterval(intervalId);
|
|
248
|
+
initInput(searchInput);
|
|
249
|
+
} else if (++retries >= maxRetries) {
|
|
250
|
+
clearInterval(intervalId);
|
|
251
|
+
console.warn('Search input box not found after maximum retries.');
|
|
252
|
+
}
|
|
253
|
+
}, 1000);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export async function aiCombinedSearch(prompt: string, provider?: SearchProvider) {
|
|
257
|
+
// hide the menu
|
|
258
|
+
document.querySelector('.d4-menu-popup')?.remove();
|
|
259
|
+
await CombinedAISearchAssistant.instance.searchUI(prompt, provider);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// Called by the core query editor to decide whether to show its AI toggle icon.
|
|
263
|
+
// The query view needs no dedicated panel anymore: its functions (getQueryInfo,
|
|
264
|
+
// setQueryAndRun + the meta.viewType-registered SQL schema functions) are reached
|
|
265
|
+
// by the singleton panel through the view-function meta-tools.
|
|
266
|
+
export async function setupAIQueryEditorUI(_v: DG.ViewBase, _connectionID: string, _queryEditorRoot: HTMLElement, _setAndRunFunc: (query: string) => void): Promise<boolean> {
|
|
267
|
+
if (!ClaudeRuntimeClient.getInstance().available)
|
|
268
|
+
return false;
|
|
269
|
+
initAIWindow();
|
|
270
|
+
return true;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
async function withinLimit(panel: StreamingPanel, quotaCategory: string): Promise<boolean> {
|
|
274
|
+
try {
|
|
275
|
+
await UsageLimiter.getInstance().checkAndIncrement(quotaCategory);
|
|
276
|
+
return true;
|
|
277
|
+
} catch (e: any) {
|
|
278
|
+
panel.showError(e.message);
|
|
279
|
+
return false;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
export async function runPromptWithLifecycle(
|
|
284
|
+
panel: StreamingPanel,
|
|
285
|
+
prompt: string,
|
|
286
|
+
view: DG.ViewBase,
|
|
287
|
+
quotaCategory: string,
|
|
288
|
+
displayPrompt?: string,
|
|
289
|
+
isAnswer = false,
|
|
290
|
+
): Promise<void> {
|
|
291
|
+
if (prompt.startsWith('!!'))
|
|
292
|
+
prompt = prompt.slice(1); // !!cmd → !cmd, falls through to normal pipeline
|
|
293
|
+
else if (prompt.startsWith('!')) {
|
|
294
|
+
const command = prompt.slice(1).trimStart();
|
|
295
|
+
if (!await withinLimit(panel, quotaCategory))
|
|
296
|
+
return;
|
|
297
|
+
await runClaudeStreaming(panel, command, view, 'bash');
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
let session: ReturnType<StreamingPanel['startChatSession']> | undefined;
|
|
301
|
+
if (!panel.rawRender) {
|
|
302
|
+
const args: UserPromptEventArgs = {prompt, context: view, handled: false};
|
|
303
|
+
fireBeforeUserPromptEvent(args);
|
|
304
|
+
if (args.handled)
|
|
305
|
+
return;
|
|
306
|
+
|
|
307
|
+
// Echo the user message before routing so it never disappears, even when
|
|
308
|
+
// grok.ai.processPrompt's built-in handler claims the prompt.
|
|
309
|
+
session = panel.startChatSession();
|
|
310
|
+
if (displayPrompt) {
|
|
311
|
+
session.session.addEngineMessage({role: 'user', content: [{type: 'text', text: prompt}]});
|
|
312
|
+
session.session.addUiMessage(displayPrompt, false, {system: true});
|
|
313
|
+
} else
|
|
314
|
+
session.session.addUserMessage({role: 'user', content: [{type: 'text', text: prompt}]}, prompt);
|
|
315
|
+
|
|
316
|
+
if (!isAnswer && await grok.ai.processPrompt(prompt)) {
|
|
317
|
+
// Built-in handler claimed the prompt — no AI response, just a green check next to it.
|
|
318
|
+
session.session.markHandledNatively();
|
|
319
|
+
session.endSession();
|
|
320
|
+
panel.pushNativeContext(prompt);
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
if (!await withinLimit(panel, quotaCategory)) {
|
|
325
|
+
session?.endSession();
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
await runClaudeStreaming(panel, prompt, view, undefined, session);
|
|
329
|
+
if (!panel.rawRender)
|
|
330
|
+
fireAfterUserPromptEvent({prompt, context: view, handled: false});
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function buildConfirmCard(input: ConfirmInput, onClose: (outcome: ConfirmOutcome) => void): ConfirmCard {
|
|
334
|
+
const close = (outcome: ConfirmOutcome): void => {
|
|
335
|
+
const {style, icon, text} = CONFIRM_OUTCOMES[outcome];
|
|
336
|
+
buttons.remove();
|
|
337
|
+
strip.classList.replace('grokky-strip-danger', `grokky-strip-${style}`);
|
|
338
|
+
strip.append(ui.divH([ui.iconFA(icon), ui.divText(text)], 'grokky-strip-answer'));
|
|
339
|
+
onClose(outcome);
|
|
340
|
+
};
|
|
341
|
+
const strip = ui.divH([ui.divText(input.action ?? 'Confirm action')], 'grokky-strip grokky-strip-danger');
|
|
342
|
+
const buttons = ui.divH([
|
|
343
|
+
ui.bigButton('OK', () => close('confirmed')),
|
|
344
|
+
ui.button('CANCEL', () => close('cancelled')),
|
|
345
|
+
]);
|
|
346
|
+
const root = ui.divV([
|
|
347
|
+
strip,
|
|
348
|
+
ui.divV([
|
|
349
|
+
ui.tableFromMap({
|
|
350
|
+
...(input.name ? {Name: input.name} : {}),
|
|
351
|
+
...(input.owner ? {Owner: input.owner} : {}),
|
|
352
|
+
...(input.created ? {Created: input.created} : {}),
|
|
353
|
+
...(input.details ? {Details: input.details} : {}),
|
|
354
|
+
}),
|
|
355
|
+
buttons,
|
|
356
|
+
], 'grokky-confirm-body'),
|
|
357
|
+
], 'grokky-confirm-card');
|
|
358
|
+
return {root, close};
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
async function runClaudeStreaming(
|
|
362
|
+
panel: StreamingPanel, userPrompt: string, view: DG.ViewBase,
|
|
363
|
+
systemPromptMode?: string,
|
|
364
|
+
existingSession?: ReturnType<StreamingPanel['startChatSession']>,
|
|
365
|
+
): Promise<void> {
|
|
366
|
+
const session = existingSession ?? panel.startChatSession();
|
|
367
|
+
if (!existingSession)
|
|
368
|
+
session.session.addUserMessage({role: 'user', content: [{type: 'text', text: userPrompt}]}, userPrompt);
|
|
369
|
+
try {
|
|
370
|
+
await streamOnce(panel, userPrompt, view, systemPromptMode, session);
|
|
371
|
+
} finally {
|
|
372
|
+
session.endSession();
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
async function streamOnce(
|
|
377
|
+
panel: StreamingPanel, userPrompt: string, view: DG.ViewBase,
|
|
378
|
+
systemPromptMode: string | undefined,
|
|
379
|
+
chatSession: ReturnType<StreamingPanel['startChatSession']>,
|
|
380
|
+
): Promise<void> {
|
|
381
|
+
return new Promise<void>(async (resolve) => {
|
|
382
|
+
const sessionId = panel.sessionId;
|
|
383
|
+
let accumulated = '';
|
|
384
|
+
let segmentStart = 0;
|
|
385
|
+
let status = Status.None;
|
|
386
|
+
let nextBlockIndex = 0;
|
|
387
|
+
const execCodes: string[] = [];
|
|
388
|
+
let preRevisionExecCodes: string[] | null = null;
|
|
389
|
+
const subs: {unsubscribe: () => void}[] = [];
|
|
390
|
+
let dismissConfirm: (() => void) | null = null;
|
|
391
|
+
const cleanup = () => {
|
|
392
|
+
subs.forEach((s) => s.unsubscribe());
|
|
393
|
+
dismissConfirm?.();
|
|
394
|
+
};
|
|
395
|
+
let resentAfterReset = false;
|
|
396
|
+
|
|
397
|
+
const forSession = <T extends {sessionId: string}>(
|
|
398
|
+
source: {subscribe: (cb: (evt: T) => void) => {unsubscribe: () => void}},
|
|
399
|
+
handler: (evt: T) => void,
|
|
400
|
+
) => subs.push(source.subscribe((evt) => {
|
|
401
|
+
if (evt.sessionId === sessionId)
|
|
402
|
+
handler(evt);
|
|
403
|
+
}));
|
|
404
|
+
|
|
405
|
+
const endWithError = (msg: string) => {
|
|
406
|
+
panel.clearStreaming();
|
|
407
|
+
panel.showError(msg);
|
|
408
|
+
cleanup();
|
|
409
|
+
resolve();
|
|
410
|
+
};
|
|
411
|
+
|
|
412
|
+
try {
|
|
413
|
+
const client = ClaudeRuntimeClient.getInstance();
|
|
414
|
+
const nativeCtx = panel.flushNativeContext();
|
|
415
|
+
const enrichedUserPrompt = nativeCtx ? nativeCtx + userPrompt : userPrompt;
|
|
416
|
+
const prompt = panel.rawRender ? enrichedUserPrompt : panel.prependViewContext(panel.prependEntityContext(enrichedUserPrompt), view);
|
|
417
|
+
|
|
418
|
+
// Three static meta-tools let Claude search and invoke the current view's functions
|
|
419
|
+
// (view.getFunctions()) without declaring them all. Defs are identical every turn
|
|
420
|
+
// (prompt-cache friendly); the runners resolve the live grok.shell.v at call time.
|
|
421
|
+
const fullMode = !systemPromptMode && !panel.noPrompt;
|
|
422
|
+
const viewTools = fullMode ? viewFunctionTools() : NO_VIEW_TOOLS;
|
|
423
|
+
|
|
424
|
+
await client.ensureConnected();
|
|
425
|
+
|
|
426
|
+
// Text before and after a tool call arrives as separate assistant segments; without a
|
|
427
|
+
// separator they concatenate mid-sentence ("…check those.No, there are…").
|
|
428
|
+
let pendingSegmentBreak = false;
|
|
429
|
+
forSession(client.onChunk, (evt) => {
|
|
430
|
+
if (pendingSegmentBreak) {
|
|
431
|
+
pendingSegmentBreak = false;
|
|
432
|
+
if (accumulated && !/\n\s*$/.test(accumulated))
|
|
433
|
+
accumulated += '\n\n';
|
|
434
|
+
}
|
|
435
|
+
accumulated += evt.content;
|
|
436
|
+
if (status !== Status.Writing) {
|
|
437
|
+
status = Status.Writing;
|
|
438
|
+
panel.setStatus('Writing…');
|
|
439
|
+
}
|
|
440
|
+
panel.updateStreaming(accumulated.slice(segmentStart));
|
|
441
|
+
});
|
|
442
|
+
|
|
443
|
+
forSession(client.onToolActivity, (evt) => {
|
|
444
|
+
pendingSegmentBreak = true;
|
|
445
|
+
status = Status.Tool;
|
|
446
|
+
panel.setStatus(evt.summary);
|
|
447
|
+
chatSession.session.addEngineMessage({role: 'assistant', content: [{type: 'text', text: `[tool-activity] ${evt.summary}`}]});
|
|
448
|
+
});
|
|
449
|
+
|
|
450
|
+
let revisingTimer: number | null = null;
|
|
451
|
+
forSession(client.onRevisionStart, () => {
|
|
452
|
+
// A gate demanded a revision. The visible answer stays put; the revision streams hidden
|
|
453
|
+
// (the runtime suppresses its chunks) and `final.revision` decides whether it replaces the
|
|
454
|
+
// original. The status appears only if revising takes noticeable time — an immediate
|
|
455
|
+
// NO_REVISION resolves before it ever shows.
|
|
456
|
+
revisingTimer = window.setTimeout(() => {
|
|
457
|
+
if (status === Status.Tool) return;
|
|
458
|
+
status = Status.Revising;
|
|
459
|
+
panel.setStatus('Revising…');
|
|
460
|
+
}, 1200);
|
|
461
|
+
preRevisionExecCodes = [...execCodes];
|
|
462
|
+
});
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
forSession(client.onFinal, async (evt) => {
|
|
466
|
+
// Always end the turn: otherwise the panel stays busy and the chat is not saved.
|
|
467
|
+
try {
|
|
468
|
+
if (revisingTimer != null) {
|
|
469
|
+
clearTimeout(revisingTimer);
|
|
470
|
+
revisingTimer = null;
|
|
471
|
+
}
|
|
472
|
+
if (evt.revision === 'replaced') {
|
|
473
|
+
// The revision supersedes the visible answer — render it in place of the original.
|
|
474
|
+
accumulated = evt.content;
|
|
475
|
+
segmentStart = 0;
|
|
476
|
+
}
|
|
477
|
+
const fullContent = accumulated || evt.content;
|
|
478
|
+
const segmentContent = accumulated ? accumulated.slice(segmentStart) : fullContent;
|
|
479
|
+
chatSession.session.addEngineMessage({role: 'assistant', content: [{type: 'text', text: fullContent}]});
|
|
480
|
+
const finalExecCodes = evt.revision === 'kept' && preRevisionExecCodes ? preRevisionExecCodes : execCodes;
|
|
481
|
+
await panel.finalizeStreaming(segmentContent, finalExecCodes, view);
|
|
482
|
+
if (evt.unverified) {
|
|
483
|
+
const warn = 'Not verified — the assistant could not confirm this action took effect.';
|
|
484
|
+
panel.appendStreamedElement(ui.divText(warn, 'grokky-unverified-warning'));
|
|
485
|
+
}
|
|
486
|
+
} finally {
|
|
487
|
+
cleanup();
|
|
488
|
+
resolve();
|
|
489
|
+
}
|
|
490
|
+
});
|
|
491
|
+
|
|
492
|
+
forSession(client.onError, (evt) => {
|
|
493
|
+
endWithError(evt.message);
|
|
494
|
+
});
|
|
495
|
+
|
|
496
|
+
forSession(client.onAborted, async () => {
|
|
497
|
+
panel.clearStreaming();
|
|
498
|
+
panel.dismissQuestion();
|
|
499
|
+
chatSession.session.addUiMessage('Stopped', false, {system: true});
|
|
500
|
+
cleanup();
|
|
501
|
+
resolve();
|
|
502
|
+
});
|
|
503
|
+
|
|
504
|
+
forSession(client.onInputRequest, async (evt) => {
|
|
505
|
+
// datagrok_exec: run the JS here, return the outcome so Claude responds AFTER knowing it.
|
|
506
|
+
if (evt.toolName === 'datagrok_exec') {
|
|
507
|
+
// Record the code that actually ran — this is what makes a history-restored
|
|
508
|
+
// conversation reproducible ("do that again") instead of a text-only memory.
|
|
509
|
+
chatSession.session.addEngineMessage({role: 'assistant',
|
|
510
|
+
content: [{type: 'text', text: `[executed datagrok_exec]\n${(evt.input.code ?? '').slice(0, 1500)}`}]});
|
|
511
|
+
const {element, value, error} = await executeSingleBlock(evt.input.code ?? '', view, nextBlockIndex++);
|
|
512
|
+
if (evt.input.code && !error)
|
|
513
|
+
execCodes.push(evt.input.code);
|
|
514
|
+
if (element) {
|
|
515
|
+
panel.appendStreamedElement(element);
|
|
516
|
+
segmentStart = accumulated.length;
|
|
517
|
+
}
|
|
518
|
+
let result: any = error ?
|
|
519
|
+
{success: false, error: error.error} :
|
|
520
|
+
{success: true, ...(value != null ? {returnValue: value} : {})};
|
|
521
|
+
// In-round-trip verification: run the provided assertion right after the action code, so a
|
|
522
|
+
// passing action needs no separate datagrok_verify round-trip (see verify.ts in the runtime).
|
|
523
|
+
if (!error && evt.input.verify?.assertion) {
|
|
524
|
+
const v = await runVerification(evt.input.verify.assertion, view);
|
|
525
|
+
result = {...result, verified: {passed: v.passed,
|
|
526
|
+
...(v.observed !== undefined ? {observed: v.observed} : {}), ...(v.error ? {error: v.error} : {})}};
|
|
527
|
+
}
|
|
528
|
+
client.respondToInput(sessionId, evt.requestId, result);
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
if (evt.toolName === 'datagrok_verify') {
|
|
532
|
+
const {passed, observed, error} = await runVerification(evt.input.assertion ?? '', view);
|
|
533
|
+
client.respondToInput(sessionId, evt.requestId, {
|
|
534
|
+
passed,
|
|
535
|
+
...(observed !== undefined ? {observed} : {}),
|
|
536
|
+
...(error ? {error} : {}),
|
|
537
|
+
});
|
|
538
|
+
return;
|
|
539
|
+
}
|
|
540
|
+
// datagrok_confirm: render the approval card and hold the round-trip until a button is clicked.
|
|
541
|
+
if (evt.toolName === 'datagrok_confirm') {
|
|
542
|
+
const outcome = await new Promise<ConfirmOutcome>((resolve) => {
|
|
543
|
+
const card = buildConfirmCard(evt.input ?? {}, resolve);
|
|
544
|
+
dismissConfirm = () => card.close('unanswered');
|
|
545
|
+
panel.appendStreamedElement(card.root);
|
|
546
|
+
});
|
|
547
|
+
dismissConfirm = null;
|
|
548
|
+
if (outcome === 'unanswered')
|
|
549
|
+
return;
|
|
550
|
+
segmentStart = accumulated.length;
|
|
551
|
+
client.respondToInput(sessionId, evt.requestId, {confirmed: outcome === 'confirmed'});
|
|
552
|
+
return;
|
|
553
|
+
}
|
|
554
|
+
// datagrok_show_entities: render entity cards immediately, no user interaction needed.
|
|
555
|
+
if (evt.toolName === 'datagrok_show_entities') {
|
|
556
|
+
panel.appendStreamedElement(renderEntityRefList(evt.input.entities ?? []));
|
|
557
|
+
segmentStart = accumulated.length;
|
|
558
|
+
client.respondToInput(sessionId, evt.requestId, {success: true});
|
|
559
|
+
return;
|
|
560
|
+
}
|
|
561
|
+
// View-declared tool call — run the tool's implementation from the current view.
|
|
562
|
+
const runner = viewTools.runners.get(evt.toolName);
|
|
563
|
+
if (runner) {
|
|
564
|
+
try {
|
|
565
|
+
const result = await runner(evt.input ?? {});
|
|
566
|
+
client.respondToInput(sessionId, evt.requestId, result === undefined ? {success: true} : result);
|
|
567
|
+
} catch (e: any) {
|
|
568
|
+
client.respondToInput(sessionId, evt.requestId, {success: false, error: e.message});
|
|
569
|
+
}
|
|
570
|
+
return;
|
|
571
|
+
}
|
|
572
|
+
// Default: AskUserQuestion
|
|
573
|
+
accumulated = '';
|
|
574
|
+
segmentStart = 0;
|
|
575
|
+
panel.clearStreaming();
|
|
576
|
+
panel.showInputRequest(evt.input);
|
|
577
|
+
});
|
|
578
|
+
|
|
579
|
+
subs.push(client.onClose.subscribe(() =>
|
|
580
|
+
endWithError('Connection lost, the request was stopped. Send it again.')));
|
|
581
|
+
|
|
582
|
+
subs.push(getAIAbortSubscription().subscribe(() => {
|
|
583
|
+
client.abort(sessionId);
|
|
584
|
+
}));
|
|
585
|
+
|
|
586
|
+
const resolvedMode = systemPromptMode ?? (panel.noPrompt ? 'none' : undefined);
|
|
587
|
+
const sendPrompt = () => {
|
|
588
|
+
const transcript = resolvedMode === 'bash' || client.isResumable(sessionId) ? '' : panel.restoredTranscript();
|
|
589
|
+
const message = transcript ? transcript + '\n---\n\n' + prompt : prompt;
|
|
590
|
+
const options = {
|
|
591
|
+
...(resolvedMode ? {systemPromptMode: resolvedMode} : {}),
|
|
592
|
+
...(viewTools.defs.length ? {clientTools: viewTools.defs} : {}),
|
|
593
|
+
logPrompt: userPrompt,
|
|
594
|
+
};
|
|
595
|
+
// Queued-task admission (queue-task.ts): the queued call only holds the turn's
|
|
596
|
+
// admission slot; the turn itself streams over this socket as usual.
|
|
597
|
+
sendChatTurn(client, sessionId, message, options)
|
|
598
|
+
.catch((e: any) => endWithError(e?.message ?? String(e)));
|
|
599
|
+
};
|
|
600
|
+
|
|
601
|
+
forSession(client.onSessionReset, () => {
|
|
602
|
+
if (resentAfterReset)
|
|
603
|
+
return endWithError('The session was lost and could not be restored. Start a new chat.');
|
|
604
|
+
resentAfterReset = true;
|
|
605
|
+
sendPrompt();
|
|
606
|
+
});
|
|
607
|
+
|
|
608
|
+
sendPrompt();
|
|
609
|
+
} catch (e: any) {
|
|
610
|
+
console.error('Claude runtime error:', e);
|
|
611
|
+
endWithError(e.message);
|
|
612
|
+
}
|
|
613
|
+
});
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
let _shellAIPanel: AIPanel | null = null;
|
|
617
|
+
|
|
618
|
+
export function initAIWindow(): AIPanel | null {
|
|
619
|
+
if (!ClaudeRuntimeClient.getInstance().available)
|
|
620
|
+
return null;
|
|
621
|
+
if (!_shellAIPanel) {
|
|
622
|
+
_shellAIPanel = new AIPanel('shell-ai-panel', null as any);
|
|
623
|
+
_shellAIPanel.onRunRequest.subscribe(async (args) => {
|
|
624
|
+
if (args.currentPrompt.prompt.trim() === '/noprompt') {
|
|
625
|
+
_shellAIPanel!.enableNoPrompt();
|
|
626
|
+
return;
|
|
627
|
+
}
|
|
628
|
+
await runPromptWithLifecycle(_shellAIPanel!, args.currentPrompt.prompt, grok.shell.v, 'shell-ai', undefined, args.currentPrompt.isAnswer);
|
|
629
|
+
});
|
|
630
|
+
AIWindowManager.instance.init(_shellAIPanel);
|
|
631
|
+
}
|
|
632
|
+
return _shellAIPanel;
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
export function setupShellAIPanelUI(): void {
|
|
636
|
+
if (!initAIWindow())
|
|
637
|
+
return;
|
|
638
|
+
AIWindowManager.instance.show();
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
const AI_ICON_SELECTOR = 'i[data-name="ai"]';
|
|
642
|
+
|
|
643
|
+
export async function setupTableViewAIPanelUI() {
|
|
644
|
+
if (!ClaudeRuntimeClient.getInstance().available)
|
|
645
|
+
return;
|
|
646
|
+
const handleView = (tableView: DG.TableView) => {
|
|
647
|
+
if (tableView.root?.parentElement?.querySelector(AI_ICON_SELECTOR) != null)
|
|
648
|
+
return;
|
|
649
|
+
// Ribbon icon toggles the shared singleton panel; table context is picked up at prompt time.
|
|
650
|
+
const iconFse = ui.iconFA('user-robot', () => fireAIPanelToggleEvent(tableView), `Ask AI \n ${SHORTCUT_HINT}`);
|
|
651
|
+
iconFse.style.width = iconFse.style.height = '18px';
|
|
652
|
+
tableView.setRibbonPanels([...tableView.getRibbonPanels(), [iconFse]]);
|
|
653
|
+
};
|
|
654
|
+
// also handle already opened views
|
|
655
|
+
Array.from(grok.shell.tableViews).filter((v) => v.dataFrame != null).forEach((view) => {
|
|
656
|
+
handleView(view as DG.TableView);
|
|
657
|
+
});
|
|
658
|
+
|
|
659
|
+
grok.events.onViewAdded.subscribe((view) => {
|
|
660
|
+
if (view.type === DG.VIEW_TYPE.TABLE_VIEW)
|
|
661
|
+
handleView(view as DG.TableView);
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
export async function setupScriptsAIPanelUI() {
|
|
666
|
+
const handleView = (scriptView: DG.ScriptView) => {
|
|
667
|
+
if (scriptView.root?.parentElement?.querySelector(AI_ICON_SELECTOR) != null)
|
|
668
|
+
return;
|
|
669
|
+
// The singleton panel picks up the script view's AI tools (get/set code) at prompt time.
|
|
670
|
+
const iconFse = ui.iconSvg('ai.svg', () => fireAIPanelToggleEvent(scriptView), `Ask AI \n ${SHORTCUT_HINT}`);
|
|
671
|
+
iconFse.style.width = iconFse.style.height = '18px';
|
|
672
|
+
scriptView.setRibbonPanels([...scriptView.getRibbonPanels(), [iconFse]]);
|
|
673
|
+
};
|
|
674
|
+
|
|
675
|
+
grok.events.onViewAdded.subscribe((view) => {
|
|
676
|
+
if (view.type === 'ScriptView') {
|
|
677
|
+
const scriptView = view as DG.ScriptView;
|
|
678
|
+
setTimeout(() => {
|
|
679
|
+
handleView(scriptView);
|
|
680
|
+
scriptView.subs.push(scriptView.tabs.onTabChanged.subscribe(() => handleView(scriptView)));
|
|
681
|
+
}, 500);
|
|
682
|
+
}
|
|
683
|
+
});
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
// Adds a "Run" button to the ribbon of file views opened from MyFiles/agents/scripts/.
|
|
687
|
+
export function setupAgentScriptsUI(): void {
|
|
688
|
+
grok.events.onViewAdded.subscribe((view) => {
|
|
689
|
+
try {
|
|
690
|
+
const basePath = view.basePath ?? view.path ?? '';
|
|
691
|
+
if (!basePath.includes('/agents/scripts/'))
|
|
692
|
+
return;
|
|
693
|
+
const {name} = view;
|
|
694
|
+
const runIcon = ui.iconFA('play', () => runAgentScript(name), `Run ${name}`);
|
|
695
|
+
runIcon.classList.add('fas');
|
|
696
|
+
view.setRibbonPanels([...view.getRibbonPanels(), [runIcon]]);
|
|
697
|
+
} catch (e: any) {
|
|
698
|
+
console.warn('Grokky: failed to add run button:', e.message);
|
|
699
|
+
}
|
|
700
|
+
});
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
async function runAgentScript(name: string): Promise<void> {
|
|
704
|
+
try {
|
|
705
|
+
const shell = initAIWindow();
|
|
706
|
+
if (!shell)
|
|
707
|
+
return;
|
|
708
|
+
AIWindowManager.instance.showPanel(shell);
|
|
709
|
+
shell.resetSession();
|
|
710
|
+
const conn = await grok.dapi.connections.filter('name = "My files"').first();
|
|
711
|
+
const workflow = await grok.dapi.files.readAsText(`${conn.nqName}/agents/scripts/${name}.md`);
|
|
712
|
+
const prompt =
|
|
713
|
+
`Execute the following workflow. After each step, post a one-line status update to chat.\n\n` +
|
|
714
|
+
`---\n${workflow}\n---`;
|
|
715
|
+
const displayPrompt = `▶ Running workflow: ${name}`;
|
|
716
|
+
await runPromptWithLifecycle(shell, prompt, grok.shell.v, 'shell-ai', displayPrompt);
|
|
717
|
+
} catch (e: any) {
|
|
718
|
+
grok.shell.error(`Failed to run ${name}: ${e.message}`);
|
|
719
|
+
}
|
|
720
|
+
}
|