@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.
Files changed (203) hide show
  1. package/.claude/skills/deploy-grokky/SKILL.md +193 -0
  2. package/.grokignore +2 -0
  3. package/.turbo/turbo-build.log +24 -0
  4. package/.vscode/settings.json +16 -0
  5. package/CHANGELOG.md +151 -8
  6. package/CLAUDE.md +284 -0
  7. package/CREDITS.md +173 -0
  8. package/LICENSE.md +16 -0
  9. package/README.md +24 -0
  10. package/bdd/bdd.config.json +1 -0
  11. package/bdd/bindings/elements.ts +9 -0
  12. package/bdd/bindings/steps.ts +787 -0
  13. package/bdd/features/ai-panel/platform-work.feature +63 -0
  14. package/bdd/features/ai-panel/session.feature +69 -0
  15. package/bdd/features/ai-panel/table-work.feature +99 -0
  16. package/bdd/generated/ai-panel/platform-work.test.ts +103 -0
  17. package/bdd/generated/ai-panel/session.test.ts +100 -0
  18. package/bdd/generated/ai-panel/table-work.test.ts +150 -0
  19. package/bdd/package.json +1 -0
  20. package/bdd/tsconfig.json +13 -0
  21. package/css/ai.css +637 -49
  22. package/dist/package-test.js +4 -1707
  23. package/dist/package-test.js.map +1 -1
  24. package/dist/package.js +742 -92317
  25. package/dist/package.js.map +1 -1
  26. package/dockerfiles/claude-runtime/.dockerignore +1 -0
  27. package/{.eslintrc.json → dockerfiles/claude-runtime/.eslintrc.json} +7 -16
  28. package/dockerfiles/claude-runtime/Dockerfile +73 -13
  29. package/dockerfiles/claude-runtime/agent/grokky_agent/__init__.py +0 -0
  30. package/dockerfiles/claude-runtime/agent/grokky_agent/__main__.py +80 -0
  31. package/dockerfiles/claude-runtime/agent/grokky_agent/browser_tools.py +180 -0
  32. package/dockerfiles/claude-runtime/agent/grokky_agent/config.py +26 -0
  33. package/dockerfiles/claude-runtime/agent/grokky_agent/formats.py +155 -0
  34. package/dockerfiles/claude-runtime/agent/grokky_agent/guard.py +87 -0
  35. package/dockerfiles/claude-runtime/agent/grokky_agent/hermes.py +212 -0
  36. package/dockerfiles/claude-runtime/agent/grokky_agent/hermes.yaml +45 -0
  37. package/dockerfiles/claude-runtime/agent/grokky_agent/hermes_plugin/__init__.py +8 -0
  38. package/dockerfiles/claude-runtime/agent/grokky_agent/hermes_plugin/plugin.yaml +3 -0
  39. package/dockerfiles/claude-runtime/agent/grokky_agent/protocol.py +174 -0
  40. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/__init__.py +21 -0
  41. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/anthropic.py +21 -0
  42. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/azure.py +46 -0
  43. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/base.py +127 -0
  44. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/bedrock.py +46 -0
  45. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/custom.py +40 -0
  46. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/databricks.py +54 -0
  47. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/openai_platform.py +41 -0
  48. package/dockerfiles/claude-runtime/agent/grokky_agent/providers/openrouter.py +46 -0
  49. package/dockerfiles/claude-runtime/agent/grokky_agent/session.py +471 -0
  50. package/dockerfiles/claude-runtime/agent/grokky_agent/skills.py +44 -0
  51. package/dockerfiles/claude-runtime/agent/grokky_agent/structured.py +40 -0
  52. package/dockerfiles/claude-runtime/container.json +2 -2
  53. package/dockerfiles/claude-runtime/entrypoint.sh +20 -0
  54. package/dockerfiles/claude-runtime/package-lock.json +1721 -306
  55. package/dockerfiles/claude-runtime/package.json +20 -5
  56. package/dockerfiles/claude-runtime/plugin/.claude-plugin/plugin.json +5 -0
  57. package/dockerfiles/claude-runtime/plugin/skills/datagrok-calc-column/SKILL.md +92 -0
  58. package/dockerfiles/claude-runtime/plugin/skills/datagrok-chem-data/SKILL.md +250 -0
  59. package/dockerfiles/claude-runtime/plugin/skills/datagrok-chem-toolkit/SKILL.md +395 -0
  60. package/dockerfiles/claude-runtime/plugin/skills/datagrok-df-and-columns/SKILL.md +454 -0
  61. package/dockerfiles/claude-runtime/plugin/skills/datagrok-entities/SKILL.md +38 -0
  62. package/dockerfiles/claude-runtime/plugin/skills/datagrok-exec/SKILL.md +209 -0
  63. package/dockerfiles/claude-runtime/plugin/skills/datagrok-filtering/SKILL.md +185 -0
  64. package/dockerfiles/claude-runtime/plugin/skills/datagrok-grid-customization/SKILL.md +270 -0
  65. package/dockerfiles/claude-runtime/plugin/skills/datagrok-projects/SKILL.md +100 -0
  66. package/dockerfiles/claude-runtime/plugin/skills/datagrok-selection/SKILL.md +344 -0
  67. package/dockerfiles/claude-runtime/plugin/skills/datagrok-undo/SKILL.md +78 -0
  68. package/dockerfiles/claude-runtime/plugin/skills/datagrok-viewers/SKILL.md +303 -0
  69. package/dockerfiles/claude-runtime/pyproject.toml +18 -0
  70. package/dockerfiles/claude-runtime/src/agent/pool.ts +411 -0
  71. package/dockerfiles/claude-runtime/src/agent/turn.ts +153 -0
  72. package/dockerfiles/claude-runtime/src/constants.ts +20 -0
  73. package/dockerfiles/claude-runtime/src/credentials.ts +45 -0
  74. package/dockerfiles/claude-runtime/src/grounding.ts +104 -0
  75. package/dockerfiles/claude-runtime/src/help-index.ts +118 -0
  76. package/dockerfiles/claude-runtime/src/privileges.ts +8 -0
  77. package/dockerfiles/claude-runtime/src/prompts.ts +211 -0
  78. package/dockerfiles/claude-runtime/src/server.ts +134 -234
  79. package/dockerfiles/claude-runtime/src/session.ts +328 -0
  80. package/dockerfiles/claude-runtime/src/shared-api-client.ts +112 -0
  81. package/dockerfiles/claude-runtime/src/stream-filter.ts +80 -0
  82. package/dockerfiles/claude-runtime/src/sync/home-files.ts +80 -0
  83. package/dockerfiles/claude-runtime/src/sync/orchestrator.ts +214 -0
  84. package/dockerfiles/claude-runtime/src/sync/packages.ts +145 -0
  85. package/dockerfiles/claude-runtime/src/sync/shared-connections.ts +87 -0
  86. package/dockerfiles/claude-runtime/src/sync/workspace.ts +68 -0
  87. package/dockerfiles/claude-runtime/src/tasks.ts +124 -0
  88. package/dockerfiles/claude-runtime/src/tool-summary.ts +66 -0
  89. package/dockerfiles/claude-runtime/src/types.ts +142 -23
  90. package/dockerfiles/claude-runtime/src/user/installed-packages.ts +17 -0
  91. package/dockerfiles/claude-runtime/src/user/staged-workspace.ts +80 -0
  92. package/dockerfiles/claude-runtime/src/user/user-dir.ts +108 -0
  93. package/dockerfiles/claude-runtime/src/verify.ts +136 -0
  94. package/dockerfiles/claude-runtime/src/watchdog.ts +115 -0
  95. package/dockerfiles/claude-runtime/test/credentials.test.js +43 -0
  96. package/dockerfiles/claude-runtime/test/grounding.test.js +191 -0
  97. package/dockerfiles/claude-runtime/test/help-index.test.js +115 -0
  98. package/dockerfiles/claude-runtime/test/plugin-skills.test.js +57 -0
  99. package/dockerfiles/claude-runtime/test/prompts.test.js +62 -0
  100. package/dockerfiles/claude-runtime/test/reaper.test.js +60 -0
  101. package/dockerfiles/claude-runtime/test/stream-filter.test.js +132 -0
  102. package/dockerfiles/claude-runtime/test/tasks.test.js +74 -0
  103. package/dockerfiles/claude-runtime/test/user-dir.test.js +71 -0
  104. package/dockerfiles/claude-runtime/test/verify.test.js +187 -0
  105. package/dockerfiles/claude-runtime/test/watchdog.test.js +43 -0
  106. package/dockerfiles/mcp-server/.eslintrc.json +39 -0
  107. package/dockerfiles/mcp-server/Dockerfile +10 -2
  108. package/dockerfiles/mcp-server/package-lock.json +1743 -98
  109. package/dockerfiles/mcp-server/package.json +27 -5
  110. package/dockerfiles/mcp-server/src/api-client.ts +123 -66
  111. package/dockerfiles/mcp-server/src/format.ts +51 -0
  112. package/dockerfiles/mcp-server/src/index.ts +44 -113
  113. package/dockerfiles/mcp-server/src/ops.ts +325 -0
  114. package/dockerfiles/mcp-server/src/shared-api-client.ts +81 -0
  115. package/dockerfiles/mcp-server/test/format.test.js +62 -0
  116. package/dockerfiles/mcp-server/test/ops.test.js +84 -0
  117. package/dockerfiles/mcp-server/test/shared-api-client.test.js +35 -0
  118. package/dockerfiles/queue/Dockerfile +2 -0
  119. package/dockerfiles/queue/container.json +7 -0
  120. package/docs/AUDIT-2026-08-03.md +1064 -0
  121. package/docs/BENCHMARK.md +292 -0
  122. package/docs/CLAUDE_CODE_FLOW.md +746 -0
  123. package/docs/EXAMPLES.md +82 -0
  124. package/docs/FEATURES.md +71 -0
  125. package/docs/IMPLEMENTATION.md +128 -0
  126. package/docs/LATENCY.md +170 -0
  127. package/docs/VISION.md +36 -0
  128. package/files/benchmark/suite.yaml +404 -0
  129. package/files/scripts/process-cro-results.md +14 -0
  130. package/files/suggestions.yaml +344 -0
  131. package/package.json +39 -97
  132. package/src/ai/ai-window.ts +157 -0
  133. package/src/ai/benchmark/benchmark.ts +737 -0
  134. package/src/ai/db-view-functions.ts +56 -0
  135. package/src/ai/engine.ts +98 -0
  136. package/src/ai/gemma-engine.ts +81 -0
  137. package/src/ai/panel.ts +1385 -0
  138. package/src/ai/prompt-suggestions.ts +209 -0
  139. package/src/ai/search/combined-search.ts +244 -0
  140. package/src/{llm-utils → ai/search}/query-matching.ts +46 -167
  141. package/src/{llm-utils → ai}/storage.ts +0 -1
  142. package/src/ai/table-tools.ts +145 -0
  143. package/src/ai/ui.ts +720 -0
  144. package/src/ai/usage-limiter.ts +105 -0
  145. package/src/ai/view-tools.ts +352 -0
  146. package/src/claude/ai-feature.ts +16 -0
  147. package/src/claude/exec-blocks.ts +176 -0
  148. package/src/claude/queue-task.ts +84 -0
  149. package/src/claude/runtime-client.ts +310 -0
  150. package/src/claude/turn-log.ts +114 -0
  151. package/src/claude/undoable.ts +105 -0
  152. package/src/{llm-utils → db}/db-index-tools.ts +24 -32
  153. package/src/db/sql-tools.ts +336 -0
  154. package/src/depr/LLM-client.ts +251 -0
  155. package/src/depr/ai-panel.ts +174 -0
  156. package/src/depr/chatgpt-assistant.ts +257 -0
  157. package/src/depr/creds.ts +30 -0
  158. package/src/depr/deepwikiclient.ts +118 -0
  159. package/src/depr/indexes/dg-repository-index.ts +266 -0
  160. package/src/depr/interfaces.ts +170 -0
  161. package/src/depr/is-help-request.ts +39 -0
  162. package/src/depr/prompt-engine.ts +52 -0
  163. package/src/depr/rendering-tools.ts +103 -0
  164. package/src/depr/script-tools.ts +785 -0
  165. package/src/depr/tableview-tools.ts +746 -0
  166. package/src/depr/viewers-ai.ts +67 -0
  167. package/src/package-api.ts +87 -28
  168. package/src/package-test.ts +1 -0
  169. package/src/package.g.ts +98 -48
  170. package/src/package.ts +211 -157
  171. package/src/polyfills.ts +12 -0
  172. package/src/utils.ts +128 -0
  173. package/tsconfig.json +8 -70
  174. package/webpack.config.js +3 -49
  175. package/.eslintignore +0 -2
  176. package/src/ai-panel.ts +0 -174
  177. package/src/claude-code/claude-panel.ts +0 -34
  178. package/src/claude-code/claude-runtime-client.ts +0 -148
  179. package/src/llm-utils/LLM-client.ts +0 -251
  180. package/src/llm-utils/combined-search.ts +0 -162
  181. package/src/llm-utils/creds.ts +0 -30
  182. package/src/llm-utils/deepwikiclient.ts +0 -118
  183. package/src/llm-utils/indexes/dg-repository-index.ts +0 -266
  184. package/src/llm-utils/panel.ts +0 -866
  185. package/src/llm-utils/script-tools.ts +0 -784
  186. package/src/llm-utils/sql-tools.ts +0 -840
  187. package/src/llm-utils/tableview-tools.ts +0 -704
  188. package/src/llm-utils/ui.ts +0 -315
  189. package/src/prompt-engine/chatgpt-assistant.ts +0 -257
  190. package/src/prompt-engine/interfaces.ts +0 -170
  191. package/src/prompt-engine/prompt-engine.ts +0 -52
  192. package/src/prompt-engine/rendering-tools.ts +0 -103
  193. package/src/prompts/is-help-request.ts +0 -26
  194. package/src/viewers-ai.ts +0 -67
  195. /package/src/{llm-utils → db}/indexes/biologics-index.ts +0 -0
  196. /package/src/{llm-utils → db}/indexes/chembl-index.ts +0 -0
  197. /package/src/{llm-utils → db}/query-meta-utils.ts +0 -0
  198. /package/src/{llm-utils/depr → depr}/AI-API-providers/openai-chat-completions-provider.ts +0 -0
  199. /package/src/{llm-utils/depr → depr}/AI-API-providers/openai-responses-provider.ts +0 -0
  200. /package/src/{llm-utils/depr → depr}/AI-API-providers/types.ts +0 -0
  201. /package/src/{llm-utils/depr → depr}/depr.ts +0 -0
  202. /package/src/{llm-utils/depr → depr}/embeddings.ts +0 -0
  203. /package/src/{llm-utils/depr → depr}/sql-utils.ts +0 -0
@@ -0,0 +1,84 @@
1
+ /** Queued-task admission for AI chat turns: the queued aiChatTurnTask call holds one celery
2
+ * slot for exactly the turn's duration while the turn streams over the browser WebSocket;
3
+ * no conversation content ever enters the queue. */
4
+ import * as grok from 'datagrok-api/grok';
5
+ import * as DG from 'datagrok-api/dg';
6
+ import {ClaudeRuntimeClient} from './runtime-client';
7
+
8
+ // Bounds a hold whose turn end was never observed (runtime restarted mid-poll).
9
+ const HOLD_CAP_MS = 30 * 60_000;
10
+
11
+ // ---------------------------------------------------------------- worker side
12
+
13
+ /** Holds one admission slot: long-polls the runtime until it reports the turn ended. */
14
+ export async function holdChatTurnTask(sessionId: string, taskId: string): Promise<string> {
15
+ const started = Date.now();
16
+ const client = ClaudeRuntimeClient.getInstance();
17
+ if (!await client.discover())
18
+ throw new Error('claude-runtime container not found');
19
+ const containerId = client.runtimeContainerId!;
20
+ const post = async (path: string) => {
21
+ const r = await grok.dapi.docker.dockerContainers.fetchProxy(containerId, path, {
22
+ // fetchProxy authenticates via browser cookies; headless workers must send the token.
23
+ method: 'POST', headers: {'Content-Type': 'application/json',
24
+ 'Authorization': (globalThis as any).getTokenFromAsyncLocalStorage?.() ?? grok.dapi.token},
25
+ body: JSON.stringify({taskId, sessionId}),
26
+ });
27
+ if (!r.ok)
28
+ throw new Error(`${path}: HTTP ${r.status}`);
29
+ return r.json();
30
+ };
31
+ for (;;) {
32
+ try {
33
+ (globalThis as any).DG_TASK_PROGRESS?.(null, `holding AI turn slot (${Math.round((Date.now() - started) / 1000)}s)`);
34
+ } catch (_) {
35
+ // Task revoked platform-side (admin cancel): give the slot back and abort the turn.
36
+ await post('/task/release').catch(() => {});
37
+ return JSON.stringify({status: 'released', heldMs: Date.now() - started});
38
+ }
39
+ const out = await post('/task/claim');
40
+ if (out.status !== 'running')
41
+ return JSON.stringify({...out, heldMs: Date.now() - started});
42
+ if (Date.now() - started > HOLD_CAP_MS)
43
+ return JSON.stringify({status: 'timeout', heldMs: Date.now() - started});
44
+ }
45
+ }
46
+
47
+ // --------------------------------------------------------------- browser side
48
+
49
+ let taskFunc: DG.Func | null | undefined = undefined;
50
+
51
+ async function taskRoute(): Promise<DG.Func | null> {
52
+ if (taskFunc === undefined) {
53
+ try {
54
+ taskFunc = await grok.dapi.functions.filter('name = "aiChatTurnTask" and options.queue = "true"').first() ?? null;
55
+ } catch (e: any) {
56
+ // Lookup failed (not "function absent") — retry on the next turn instead of caching null.
57
+ console.warn(`Grokky: task route lookup failed: ${e?.message ?? e}`);
58
+ return null;
59
+ }
60
+ }
61
+ return taskFunc;
62
+ }
63
+
64
+ export interface ChatTurnOptions {
65
+ systemPromptMode?: string;
66
+ clientTools?: {name: string; description: string; inputSchema?: object}[];
67
+ logPrompt?: string;
68
+ }
69
+
70
+ /** Sends one chat turn, admitted through a queued task when `aiChatTurnTask` is deployed,
71
+ * falling back to a plain send otherwise; a failed admission task is logged, not fatal. */
72
+ export async function sendChatTurn(
73
+ client: ClaudeRuntimeClient, sessionId: string, message: string, options: ChatTurnOptions,
74
+ ): Promise<void> {
75
+ await client.ensureConnected();
76
+ const func = await taskRoute();
77
+ if (!func)
78
+ return client.send(sessionId, message, options);
79
+ // Send first: a task admitting a message that never reached the runtime would hold its slot until HOLD_CAP_MS.
80
+ const taskId = crypto.randomUUID();
81
+ client.send(sessionId, message, {...options, taskId});
82
+ func.prepare({sessionId: sessionId, taskId: taskId}).call()
83
+ .catch((e: any) => console.warn(`Grokky: turn admission task failed (turn proceeds unmetered): ${e?.message ?? e}`));
84
+ }
@@ -0,0 +1,310 @@
1
+ import * as grok from 'datagrok-api/grok';
2
+ import * as rxjs from 'rxjs';
3
+ import {AiFeature} from './ai-feature';
4
+ import {TurnLog} from './turn-log';
5
+
6
+ export type ChunkEvent = {sessionId: string, content: string};
7
+ export type ImageAttachment = {mediaType: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp', data: string};
8
+ /** `name` is the bare tool name (mcp prefix stripped). */
9
+ export type ToolActivityEvent = {sessionId: string, summary: string, name: string};
10
+ /** A runtime gate blocked the turn's Stop — a revision is being generated behind the visible
11
+ * answer; `FinalEvent.revision` will say whether it replaces the original or the original stands. */
12
+ export type RevisionStartEvent = {sessionId: string};
13
+ /** Per-turn token, cost and timing metrics the runtime reports on `final` (see docs/BENCHMARK.md). */
14
+ export type TurnServerMetrics = {
15
+ model?: string,
16
+ inputTokens: number | null, outputTokens: number | null,
17
+ cacheReadTokens: number | null, cacheCreationTokens: number | null,
18
+ costUsd: number | null, numTurns: number | null,
19
+ durationMs: number | null, durationApiMs: number | null,
20
+ };
21
+ export type FinalEvent = {sessionId: string, content: string, structured_output?: any, unverified?: boolean, metrics?: TurnServerMetrics, revision?: 'kept' | 'replaced'};
22
+ export type ErrorEvent = {sessionId: string, message: string};
23
+ export type SessionResetEvent = {sessionId: string};
24
+ export type AbortedEvent = {sessionId: string};
25
+ export type InputRequestEvent = {sessionId: string, requestId: string, toolName: string, input: any};
26
+
27
+ export class ClaudeRuntimeClient {
28
+ private static instance: ClaudeRuntimeClient | null = null;
29
+ private ws: WebSocket | null = null;
30
+ private containerId: string | null = null;
31
+ private mcpServerUrl: string | null = null;
32
+ private _connectPromise: Promise<void> | null = null;
33
+ private _discovery: Promise<boolean> | null = null;
34
+
35
+
36
+ public onChunk = new rxjs.Subject<ChunkEvent>();
37
+ public onToolActivity = new rxjs.Subject<ToolActivityEvent>();
38
+ public onRevisionStart = new rxjs.Subject<RevisionStartEvent>();
39
+ public onFinal = new rxjs.Subject<FinalEvent>();
40
+ public onError = new rxjs.Subject<ErrorEvent>();
41
+ public onSessionReset = new rxjs.Subject<SessionResetEvent>();
42
+ public onAborted = new rxjs.Subject<AbortedEvent>();
43
+ public onInputRequest = new rxjs.Subject<InputRequestEvent>();
44
+ public onSyncStatus = new rxjs.Subject<{status: string; message?: string}>();
45
+ public onClose = new rxjs.Subject<void>();
46
+ private _resumable = new Set<string>();
47
+ private _turnLog = new TurnLog();
48
+
49
+ private constructor() {}
50
+
51
+ static getInstance(): ClaudeRuntimeClient {
52
+ if (!ClaudeRuntimeClient.instance)
53
+ ClaudeRuntimeClient.instance = new ClaudeRuntimeClient();
54
+ return ClaudeRuntimeClient.instance;
55
+ }
56
+
57
+ get connected(): boolean {
58
+ return this.ws !== null && this.ws.readyState === WebSocket.OPEN;
59
+ }
60
+
61
+ get available(): boolean {
62
+ return this.containerId !== null;
63
+ }
64
+
65
+ get runtimeContainerId(): string | null {
66
+ return this.containerId;
67
+ }
68
+
69
+ discover(): Promise<boolean> {
70
+ if (!this._discovery) {
71
+ this._discovery = (async () => {
72
+ const [runtimeContainers, mcpContainers] = await Promise.all([
73
+ grok.dapi.docker.dockerContainers.filter('name = "grokky-claude-runtime"').list(),
74
+ grok.dapi.docker.dockerContainers.filter('name = "grokky-mcp-server"').list(),
75
+ ]);
76
+ this.containerId = runtimeContainers[0]?.id ?? null;
77
+ this.mcpServerUrl = mcpContainers[0] ?
78
+ `${grok.dapi.root}/docker/containers/proxy/${mcpContainers[0].id}/mcp` :
79
+ null;
80
+ return this.containerId !== null;
81
+ })().catch((e) => {
82
+ console.warn('Grokky: container discovery failed:', e);
83
+ this._discovery = null;
84
+ return false;
85
+ });
86
+ }
87
+ return this._discovery;
88
+ }
89
+
90
+ async ensureConnected(): Promise<void> {
91
+ if (this.connected)
92
+ return;
93
+ if (!this._connectPromise) {
94
+ this._connectPromise = this.connect()
95
+ .finally(() => { this._connectPromise = null; });
96
+ }
97
+ return this._connectPromise;
98
+ }
99
+
100
+ async connect(): Promise<void> {
101
+ if (this.connected)
102
+ return;
103
+
104
+ for (let attempt = 0; attempt < 2 && !this.ws && await this.discover(); attempt++) {
105
+ try {
106
+ this.ws = await grok.dapi.docker.dockerContainers.webSocketProxy(this.containerId!, '/ws', 180_000);
107
+ } catch (e) {
108
+ this._discovery = null;
109
+ this.containerId = null;
110
+ this.mcpServerUrl = null;
111
+ console.error('Failed to connect to Claude runtime:', e);
112
+ }
113
+ }
114
+
115
+ if (!this.ws)
116
+ throw new Error('The AI runtime is not available. Try again in a minute.');
117
+
118
+ this.ws.onmessage = (event: MessageEvent) => {
119
+ let data: any;
120
+ try {
121
+ data = JSON.parse(event.data);
122
+ } catch {
123
+ console.error('ClaudeRuntimeClient: failed to parse message', event.data);
124
+ return;
125
+ }
126
+
127
+ switch (data.type) {
128
+ case 'chunk':
129
+ this._turnLog.chunk(data.sessionId, data.content);
130
+ this.onChunk.next({sessionId: data.sessionId, content: data.content});
131
+ break;
132
+ case 'tool_activity':
133
+ this._turnLog.toolActivity(data.sessionId, data.name, data.summary);
134
+ this.onToolActivity.next({sessionId: data.sessionId, summary: data.summary, name: data.name});
135
+ break;
136
+ case 'revision_start':
137
+ this._turnLog.revisionStart(data.sessionId);
138
+ this.onRevisionStart.next({sessionId: data.sessionId});
139
+ break;
140
+ case 'final':
141
+ this._resumable.add(data.sessionId);
142
+ const final: FinalEvent = {
143
+ sessionId: data.sessionId, content: data.content,
144
+ ...(data.structured_output ? {structured_output: data.structured_output} : {}),
145
+ ...(data.unverified ? {unverified: true} : {}),
146
+ ...(data.metrics ? {metrics: data.metrics} : {}),
147
+ ...(data.revision ? {revision: data.revision} : {}),
148
+ };
149
+ this.onFinal.next(final);
150
+ this._turnLog.finish(final, 'ok');
151
+ break;
152
+ case 'error':
153
+ this._resumable.add(data.sessionId);
154
+ this.onError.next({sessionId: data.sessionId, message: data.message});
155
+ this._turnLog.finish({sessionId: data.sessionId, content: '', metrics: data.metrics}, 'error');
156
+ break;
157
+ case 'session_reset':
158
+ this._resumable.delete(data.sessionId);
159
+ this._turnLog.drop(data.sessionId);
160
+ this.onSessionReset.next({sessionId: data.sessionId});
161
+ break;
162
+ case 'aborted':
163
+ this._resumable.add(data.sessionId);
164
+ this.onAborted.next({sessionId: data.sessionId});
165
+ this._turnLog.finish({sessionId: data.sessionId, content: '', metrics: data.metrics}, 'aborted');
166
+ break;
167
+ case 'input_request':
168
+ this.onInputRequest.next({sessionId: data.sessionId, requestId: data.requestId, toolName: data.toolName, input: data.input});
169
+ break;
170
+ case 'sync_status':
171
+ this.onSyncStatus.next({status: data.status, message: data.message});
172
+ break;
173
+ }
174
+ };
175
+
176
+ this.ws.onclose = () => {
177
+ this.ws = null;
178
+ this._turnLog.clear();
179
+ this.onClose.next();
180
+ };
181
+
182
+ this.ws.onerror = () => {
183
+ this.ws = null;
184
+ };
185
+ }
186
+
187
+ isResumable(sessionId: string): boolean {
188
+ return this._resumable.has(sessionId);
189
+ }
190
+
191
+ /** The runtime may still hold this session (a chat reopened from its history): the next turn resumes it. */
192
+ expectResume(sessionId: string): void {
193
+ this._resumable.add(sessionId);
194
+ }
195
+
196
+ send(sessionId: string, message: string, options?: {outputSchema?: object; systemPromptMode?: string;
197
+ taskId?: string; clientTools?: {name: string; description: string; inputSchema?: object}[];
198
+ images?: ImageAttachment[]; logPrompt?: string}): void {
199
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN)
200
+ throw new Error('ClaudeRuntimeClient: WebSocket is not connected');
201
+ this.ws.send(JSON.stringify({
202
+ type: 'user_message', sessionId, message,
203
+ apiKey: grok.dapi.token,
204
+ mcpServerUrl: this.mcpServerUrl,
205
+ ...(this._resumable.has(sessionId) ? {resumeExpected: true} : {}),
206
+ ...(options?.outputSchema ? {outputSchema: options.outputSchema} : {}),
207
+ ...(options?.systemPromptMode ? {systemPromptMode: options.systemPromptMode} : {}),
208
+ ...(options?.taskId ? {taskId: options.taskId} : {}),
209
+ ...(options?.clientTools?.length ? {clientTools: options.clientTools} : {}),
210
+ ...(options?.images?.length ? {images: options.images} : {}),
211
+ }));
212
+ this._turnLog.start(sessionId, options?.logPrompt);
213
+ }
214
+
215
+ async syncUserFiles(
216
+ scope: 'all' | 'user-files' | 'packages' | 'shared' = 'all',
217
+ packageName?: string,
218
+ ): Promise<void> {
219
+ await this.ensureConnected();
220
+ this.ws!.send(JSON.stringify({
221
+ type: 'sync_user_files',
222
+ apiKey: grok.dapi.token,
223
+ mcpServerUrl: this.mcpServerUrl,
224
+ scope,
225
+ ...(packageName ? {packageName} : {}),
226
+ }));
227
+ }
228
+
229
+ abort(sessionId: string): void {
230
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN)
231
+ return;
232
+ this.ws.send(JSON.stringify({type: 'abort', sessionId}));
233
+ }
234
+
235
+ respondToInput(sessionId: string, requestId: string, value: any): void {
236
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN)
237
+ return;
238
+ let payload: string;
239
+ try {
240
+ payload = JSON.stringify({type: 'input_response', sessionId, requestId, value});
241
+ } catch {
242
+ // Non-serializable executed-JS return: reply with a failure both datagrok_exec and datagrok_verify can read.
243
+ const fallback = {success: false, passed: false, error: 'result is not serializable'};
244
+ payload = JSON.stringify({type: 'input_response', sessionId, requestId, value: fallback});
245
+ }
246
+ this.ws.send(payload);
247
+ }
248
+
249
+ async query(message: string, options: {feature: AiFeature, sessionId?: string, outputSchema?: object,
250
+ systemPromptMode?: string, timeoutMs?: number, logPrompt?: string}): Promise<any> {
251
+ await this.ensureConnected();
252
+ const sid = options.sessionId ?? `${options.feature}-${Date.now()}-${Math.floor(Math.random() * 1e6)}`;
253
+ // Bounds a turn whose socket or runtime vanished: no final or error arrives then.
254
+ const timeoutMs = options.timeoutMs ?? 120_000;
255
+ return new Promise((resolve, reject) => {
256
+ const subs: {unsubscribe: () => void}[] = [];
257
+ const timer = window.setTimeout(() => {
258
+ cleanup();
259
+ this.abort(sid);
260
+ reject(new Error(`query timed out after ${timeoutMs / 1000}s`));
261
+ }, timeoutMs);
262
+ const cleanup = () => {
263
+ window.clearTimeout(timer);
264
+ subs.forEach((s) => s.unsubscribe());
265
+ };
266
+ subs.push(this.onFinal.subscribe((evt) => {
267
+ if (evt.sessionId !== sid) return;
268
+ cleanup();
269
+ resolve(options.outputSchema && evt.structured_output ? evt.structured_output : evt.content);
270
+ }));
271
+ subs.push(this.onError.subscribe((evt) => {
272
+ if (evt.sessionId !== sid) return;
273
+ cleanup();
274
+ reject(new Error(evt.message));
275
+ }));
276
+ this.send(sid, message, {
277
+ ...(options.outputSchema ? {outputSchema: options.outputSchema} : {}),
278
+ ...(options.systemPromptMode ? {systemPromptMode: options.systemPromptMode} : {}),
279
+ logPrompt: options.logPrompt,
280
+ });
281
+ });
282
+ }
283
+
284
+ disconnect(): void {
285
+ if (this.ws) {
286
+ this.ws.close();
287
+ this.ws = null;
288
+ }
289
+ this.onChunk.complete();
290
+ this.onToolActivity.complete();
291
+ this.onRevisionStart.complete();
292
+ this.onFinal.complete();
293
+ this.onError.complete();
294
+ this.onSessionReset.complete();
295
+ this.onAborted.complete();
296
+ this.onInputRequest.complete();
297
+ this.onSyncStatus.complete();
298
+ this.onClose.complete();
299
+ this.onChunk = new rxjs.Subject<ChunkEvent>();
300
+ this.onToolActivity = new rxjs.Subject<ToolActivityEvent>();
301
+ this.onRevisionStart = new rxjs.Subject<RevisionStartEvent>();
302
+ this.onFinal = new rxjs.Subject<FinalEvent>();
303
+ this.onError = new rxjs.Subject<ErrorEvent>();
304
+ this.onSessionReset = new rxjs.Subject<SessionResetEvent>();
305
+ this.onAborted = new rxjs.Subject<AbortedEvent>();
306
+ this.onInputRequest = new rxjs.Subject<InputRequestEvent>();
307
+ this.onSyncStatus = new rxjs.Subject<{status: string; message?: string}>();
308
+ this.onClose = new rxjs.Subject<void>();
309
+ }
310
+ }
@@ -0,0 +1,114 @@
1
+ import {_package} from '../package';
2
+ import {featureOf} from './ai-feature';
3
+ import type {FinalEvent} from './runtime-client';
4
+
5
+ // A longer value fails the btree index on event_parameter_values, and the log batch with it.
6
+ const MAX_TEXT_BYTES = 2500;
7
+
8
+ type Turn = {turnId: string, logResponses: boolean, logToolCalls: boolean, chunks: string[], visibleText: string,
9
+ toolCalls: string[]};
10
+
11
+ function contentLogging(): {prompts: boolean, responses: boolean, toolCalls: boolean} {
12
+ const settings = _package.settings ?? {};
13
+ return {
14
+ prompts: String(settings.logPrompts) === 'true',
15
+ responses: String(settings.logResponses) === 'true',
16
+ toolCalls: String(settings.logToolCalls) === 'true',
17
+ };
18
+ }
19
+
20
+ function capped(text: string): string {
21
+ return new TextDecoder().decode(new TextEncoder().encode(text).slice(0, MAX_TEXT_BYTES));
22
+ }
23
+
24
+ export class TurnLog {
25
+ private turns = new Map<string, Turn[]>();
26
+
27
+ start(sessionId: string, prompt?: string): void {
28
+ const logging = contentLogging();
29
+ const logsText = prompt != null;
30
+ const turn: Turn = {turnId: crypto.randomUUID(), logResponses: logsText && logging.responses,
31
+ logToolCalls: logsText && logging.toolCalls, chunks: [], visibleText: '', toolCalls: []};
32
+ const queue = this.turns.get(sessionId);
33
+ if (queue)
34
+ queue.push(turn);
35
+ else
36
+ this.turns.set(sessionId, [turn]);
37
+ if (prompt && logging.prompts)
38
+ this.logContent(sessionId, turn.turnId, {prompt: capped(prompt)});
39
+ }
40
+
41
+ chunk(sessionId: string, content: string): void {
42
+ const turn = this.turns.get(sessionId)?.[0];
43
+ if (turn?.logResponses)
44
+ turn.chunks.push(content);
45
+ }
46
+
47
+ toolActivity(sessionId: string, name: string, summary: string): void {
48
+ const turn = this.turns.get(sessionId)?.[0];
49
+ if (turn?.logToolCalls)
50
+ turn.toolCalls.push(`${name}: ${summary}`);
51
+ }
52
+
53
+ revisionStart(sessionId: string): void {
54
+ const turn = this.turns.get(sessionId)?.[0];
55
+ if (!turn)
56
+ return;
57
+ turn.visibleText = turn.chunks.join('');
58
+ turn.chunks = [];
59
+ }
60
+
61
+ drop(sessionId: string): Turn | undefined {
62
+ const queue = this.turns.get(sessionId);
63
+ const turn = queue?.shift();
64
+ if (queue && !queue.length)
65
+ this.turns.delete(sessionId);
66
+ return turn;
67
+ }
68
+
69
+ clear(): void {
70
+ this.turns.clear();
71
+ }
72
+
73
+ finish(final: FinalEvent, status: 'ok' | 'error' | 'aborted'): void {
74
+ if (!final.sessionId)
75
+ return;
76
+ const turn = this.drop(final.sessionId);
77
+ const metrics = final.metrics;
78
+ const turnId = turn?.turnId ?? crypto.randomUUID();
79
+ const usage: {[key: string]: string | number} = {turnId, chatId: final.sessionId,
80
+ feature: featureOf(final.sessionId), status};
81
+ // Names avoid `token`: the log redactor blanks such parameters.
82
+ const values: {[key: string]: string | number | null | undefined} = {
83
+ model: metrics?.model,
84
+ inputCount: metrics?.inputTokens, outputCount: metrics?.outputTokens,
85
+ cacheReadCount: metrics?.cacheReadTokens, cacheCreationCount: metrics?.cacheCreationTokens,
86
+ costUsd: metrics?.costUsd, numTurns: metrics?.numTurns,
87
+ durationMs: metrics?.durationMs, apiDurationMs: metrics?.durationApiMs,
88
+ };
89
+ for (const [name, value] of Object.entries(values)) {
90
+ if (value != null)
91
+ usage[name] = value;
92
+ }
93
+ _package.logger.usage('ai-turn', usage, 'ai-turn');
94
+ if (!turn)
95
+ return;
96
+ const content: {[key: string]: string} = {};
97
+ if (turn.logResponses) {
98
+ const structured = final.structured_output ? JSON.stringify(final.structured_output) : '';
99
+ const response = final.revision === 'replaced' ? final.content :
100
+ turn.visibleText || turn.chunks.join('') || final.content || structured;
101
+ if (response)
102
+ content.response = capped(response);
103
+ }
104
+ if (turn.toolCalls.length)
105
+ content.toolCalls = capped(turn.toolCalls.join('\n'));
106
+ if (Object.keys(content).length)
107
+ this.logContent(final.sessionId, turnId, content);
108
+ }
109
+
110
+ private logContent(sessionId: string, turnId: string, content: {[key: string]: string}): void {
111
+ _package.logger.usage('ai-turn-content', {turnId, chatId: sessionId, feature: featureOf(sessionId), ...content},
112
+ 'ai-turn-content');
113
+ }
114
+ }
@@ -0,0 +1,105 @@
1
+ import * as grok from 'datagrok-api/grok';
2
+ import * as DG from 'datagrok-api/dg';
3
+
4
+ // The platform keeps at most 20 MB per undo step: this many cells of kept or copied columns stay under it.
5
+ const MAX_KEPT_CELLS = 2_500_000;
6
+
7
+ function push(name: string, context: DG.DataFrame | DG.ViewBase, undo: () => void, redo?: () => void): boolean {
8
+ DG.UndoService?.push(name, undo, {redo, context});
9
+ return DG.UndoService != null;
10
+ }
11
+
12
+ /** Table changes that Ctrl+Z takes back, for the AI's tools and scripts: each makes the change and records the
13
+ * step. A boolean result is false when the change was made without a step, so it cannot be undone. */
14
+ export const undoable = {
15
+ removeColumns(t: DG.DataFrame, names: string[]): boolean {
16
+ const all = t.columns.names();
17
+ const removed = [...new Set(names.map((n) => t.getCol(n)))].map((col) => ({col, at: all.indexOf(col.name)}))
18
+ .sort((a, b) => a.at - b.at);
19
+ const remove = () => removed.forEach(({col}) => t.columns.remove(col.name));
20
+ remove();
21
+ if (removed.length === 0 || removed.length * t.rowCount > MAX_KEPT_CELLS)
22
+ return false;
23
+ return push(removed.length === 1 ? `Remove column ${removed[0].col.name}` : `Remove ${removed.length} columns`, t,
24
+ () => removed.forEach(({col, at}) => t.columns.insert(col, at)), remove);
25
+ },
26
+
27
+ /** Removes the rows [where] holds for with the platform's command, which records the step itself and drops it
28
+ * when the rows are too large to keep. The user's selection of the other rows stays. */
29
+ async removeRows(t: DG.DataFrame, where: (i: number) => boolean): Promise<boolean> {
30
+ if (grok.shell.t !== t)
31
+ throw new Error(`Rows are removed from the current table only: make the view of "${t.name}" current first`);
32
+ const rowCount = t.rowCount;
33
+ const mask = Array.from({length: rowCount}, (_, i) => !!where(i));
34
+ const removed = mask.filter(Boolean).length;
35
+ if (removed === 0)
36
+ return false;
37
+ const selected = t.selection.clone();
38
+ t.selection.init((i) => mask[i]);
39
+ try {
40
+ await grok.functions.call('CmdRemoveSelectedRows');
41
+ } finally {
42
+ if (t.rowCount === rowCount - removed) {
43
+ const kept = Array.from({length: rowCount}, (_, i) => i).filter((i) => !mask[i]);
44
+ t.selection.init((i) => selected.get(kept[i]));
45
+ } else
46
+ t.selection.copyFrom(selected);
47
+ }
48
+ return DG.UndoService?.undoName === `Remove ${removed} rows`;
49
+ },
50
+
51
+ /** Records a column the script has just added to its table. */
52
+ columnAdded(col: DG.Column): boolean {
53
+ const t = col.dataFrame;
54
+ const at = t.columns.names().indexOf(col.name);
55
+ return push(`Add column ${col.name}`, t, () => t.columns.remove(col.name), () => t.columns.insert(col, at));
56
+ },
57
+
58
+ /** Runs [change], which rewrites the values of [col]; a column too large to copy is changed without a step.
59
+ * A change that throws is rolled back. */
60
+ async changeValues(col: DG.Column, change: () => any): Promise<boolean> {
61
+ const before = col.length <= MAX_KEPT_CELLS ? col.clone() : null;
62
+ const restore = () => col.dataFrame.columns.replace(col.name, before!);
63
+ try {
64
+ await change();
65
+ } catch (e) {
66
+ if (before)
67
+ restore();
68
+ throw e;
69
+ }
70
+ return before != null && push(`Change ${col.name}`, col.dataFrame, restore);
71
+ },
72
+
73
+ /** Runs [change], which renames [col] or sets its tags: format, color coding, units, semantic type.
74
+ * A change that throws is rolled back. */
75
+ async editColumn(col: DG.Column, change: () => any): Promise<boolean> {
76
+ const state = () => ({name: col.name, tags: Object.fromEntries(col.tags) as Record<string, string>});
77
+ const restore = (to: ReturnType<typeof state>) => {
78
+ col.name = to.name;
79
+ for (const key of Object.keys(state().tags)) {
80
+ if (!(key in to.tags))
81
+ delete col.tags[key];
82
+ }
83
+ Object.assign(col.tags, to.tags);
84
+ };
85
+ const before = state();
86
+ try {
87
+ await change();
88
+ } catch (e) {
89
+ restore(before);
90
+ throw e;
91
+ }
92
+ const after = state();
93
+ return JSON.stringify(before) !== JSON.stringify(after) &&
94
+ push(`Edit column ${after.name}`, col.dataFrame, () => restore(before), () => restore(after));
95
+ },
96
+
97
+ addViewer(view: DG.TableView, type: string, options?: object): DG.Viewer {
98
+ let viewer = view.addViewer(type, options);
99
+ push(`Add ${type.toLowerCase()}`, view, () => {
100
+ if (Array.from(view.viewers).includes(viewer))
101
+ viewer.close();
102
+ }, () => viewer = view.addViewer(type, options));
103
+ return viewer;
104
+ },
105
+ };