@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,66 @@
1
+ import {bareToolName, DOMAIN_TOOLS} from './verify';
2
+
3
+ interface ToolInputs {
4
+ read_file: {path?: string};
5
+ write_file: {path?: string};
6
+ patch: {path?: string};
7
+ search_files: {pattern?: string; target?: 'content' | 'files'; path?: string};
8
+ terminal: {command?: string};
9
+ process_manage: {action?: string};
10
+ skills_list: {category?: string};
11
+ skill_view: {name?: string};
12
+ web_search: {query?: string};
13
+ web_extract: {urls?: string[]};
14
+ datagrok_exec: {code?: string};
15
+ datagrok_verify: {assertion?: string; description?: string};
16
+ datagrok_show_entities: {entities?: unknown[]};
17
+ AskUserQuestion: {questions?: {question?: string}[]};
18
+ }
19
+
20
+ type ToolName = keyof ToolInputs;
21
+
22
+ /** The Datagrok MCP server has one tool per domain, each dispatching on `op` (mcp-server/src/ops.ts). */
23
+ interface DomainToolInput {
24
+ op?: string;
25
+ args?: Record<string, any>;
26
+ }
27
+
28
+ const inPath = (path?: string) => path ? ` in ${path}` : '';
29
+
30
+ const toolFormatters: {[K in ToolName]: (i: ToolInputs[K]) => string} = {
31
+ read_file: (i) => `Read ${i.path ?? ''}`,
32
+ write_file: (i) => `Write ${i.path ?? ''}`,
33
+ patch: (i) => `Edit ${i.path ?? ''}`,
34
+ search_files: (i) => i.target === 'files' ? `Find files ${i.pattern ?? ''}${inPath(i.path)}` :
35
+ `Search '${i.pattern ?? ''}'${inPath(i.path)}`,
36
+ terminal: () => 'Run a command',
37
+ process_manage: (i) => `Background process: ${i.action ?? ''}`,
38
+ skills_list: () => 'List skills',
39
+ skill_view: (i) => `Load skill ${i.name ?? ''}`,
40
+ web_search: (i) => `Search the web: ${i.query ?? ''}`,
41
+ web_extract: (i) => `Fetch ${(i.urls ?? []).join(', ')}`,
42
+ datagrok_exec: () => 'Execute in browser',
43
+ datagrok_verify: (i) => `Verify: ${i.description ?? 'action outcome'}`,
44
+ datagrok_show_entities: (i) => {
45
+ const n = (i.entities ?? []).length;
46
+ return `Show ${n} entit${n === 1 ? 'y' : 'ies'}`;
47
+ },
48
+ AskUserQuestion: (i) => `Asking: ${i.questions?.[0]?.question ?? 'a question'}`,
49
+ };
50
+
51
+ function domainSummary(domain: string, i: DomainToolInput): string {
52
+ if (!i.op)
53
+ return `List ${domain} operations`;
54
+ const subject = i.args?.name ?? i.args?.id ?? i.args?.path ?? i.args?.filter ?? '';
55
+ return `${domain}: ${i.op.replace(/_/g, ' ')}${subject ? ' ' + subject : ''}`;
56
+ }
57
+
58
+ /** One line for the panel while a tool runs. View tools and unknown tools read as their name. */
59
+ export function toolSummary(name: string, input: Record<string, unknown>): string {
60
+ // Tool names come from the browser and MCP servers: `in` would also find `constructor` or `__proto__`.
61
+ if (Object.prototype.hasOwnProperty.call(toolFormatters, name))
62
+ return toolFormatters[name as ToolName](input as ToolInputs[ToolName]);
63
+ const bare = bareToolName(name);
64
+ return DOMAIN_TOOLS.has(bare) ? domainSummary(bare.replace('datagrok_', ''), input as DomainToolInput) :
65
+ bare.replace(/_/g, ' ');
66
+ }
@@ -1,37 +1,156 @@
1
- export interface ToolInputs {
2
- Read: {file_path?: string};
3
- Write: {file_path?: string};
4
- Edit: {file_path?: string};
5
- Bash: {command?: string};
6
- Glob: {pattern?: string; path?: string};
7
- Grep: {pattern?: string; path?: string};
8
- WebSearch: {query?: string};
9
- WebFetch: {url?: string};
10
- }
1
+ import type {ProviderCredentials} from './credentials';
2
+
3
+ // Browser ↔ runtime WebSocket protocol
4
+
5
+ export type PromptMode = 'datagrok' | 'search' | 'bash' | 'none';
11
6
 
12
- export interface McpInputs {
13
- call_function: {name?: string};
14
- list_functions: {filter?: string};
15
- get_function: {id?: string};
16
- list_files: {path?: string};
17
- download_file: {path?: string};
18
- upload_file: {path?: string};
7
+ export interface ImageAttachment {
8
+ mediaType: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp';
9
+ data: string;
19
10
  }
20
11
 
21
- export type ToolName = keyof ToolInputs;
22
- export type McpName = keyof McpInputs;
12
+ /** A tool declared by the browser for this turn (usually supplied by the current view).
13
+ * Calls round-trip to the browser via input_request / input_response. */
14
+ export interface ClientToolDef {
15
+ name: string;
16
+ description: string;
17
+ /** JSON Schema (object type) describing the arguments. */
18
+ inputSchema?: object;
19
+ }
23
20
 
24
21
  export interface UserMessage {
25
22
  type: 'user_message';
26
23
  sessionId: string;
27
24
  message: string;
25
+ images?: ImageAttachment[];
28
26
  apiKey?: string;
29
27
  mcpServerUrl?: string;
28
+ outputSchema?: object;
29
+ systemPromptMode?: PromptMode;
30
+ clientTools?: ClientToolDef[];
31
+ /** Per-turn gate switches, for A/B experiments (benchmark arms, dev harness). Both default
32
+ * true; the gates are quality mechanisms, not security boundaries, so a client may turn its
33
+ * own off. */
34
+ gates?: {grounding?: boolean; verify?: boolean};
35
+ resumeExpected?: boolean;
36
+ /** Id of the queued admission task: the turn holds until the matching
37
+ * `Grokky:aiChatTurnTask` celery task claims it (see tasks.ts). */
38
+ taskId?: string;
39
+ }
40
+
41
+ export interface AbortMessage {
42
+ type: 'abort';
43
+ sessionId: string;
44
+ }
45
+
46
+ export interface InputResponseMessage {
47
+ type: 'input_response';
48
+ sessionId: string;
49
+ requestId?: string;
50
+ value: unknown;
51
+ }
52
+
53
+ export interface TurnMetrics {
54
+ model?: string;
55
+ inputTokens: number | null;
56
+ outputTokens: number | null;
57
+ cacheReadTokens: number | null;
58
+ cacheCreationTokens: number | null;
59
+ costUsd: number | null;
60
+ numTurns: number | null;
61
+ durationMs: number | null;
62
+ durationApiMs: number | null;
30
63
  }
31
64
 
32
65
  export type OutgoingMessage =
33
66
  | {type: 'chunk'; sessionId: string; content: string}
34
- | {type: 'tool_activity'; sessionId: string; summary: string}
35
- | {type: 'tool_result'; sessionId: string; content: string}
36
- | {type: 'final'; sessionId: string; content: string}
37
- | {type: 'error'; sessionId: string; message: string};
67
+ // `name` is the bare tool name (mcp prefix stripped), so a harness can assert which path a turn took.
68
+ | {type: 'tool_activity'; sessionId: string; summary: string; name: string}
69
+ // A gate (verifier / grounding) blocked the turn's Stop and a revision is being generated.
70
+ // The visible answer stays; the revision streams hidden, and `final.revision` says whether it
71
+ // replaces the original ('replaced') or the original stands ('kept').
72
+ | {type: 'revision_start'; sessionId: string}
73
+ | {type: 'final'; sessionId: string; content: string; structured_output?: unknown; unverified?: boolean;
74
+ metrics?: TurnMetrics; revision?: 'kept' | 'replaced'}
75
+ | {type: 'error'; sessionId: string; message: string; metrics?: TurnMetrics}
76
+ | {type: 'session_reset'; sessionId: string}
77
+ | {type: 'queued'; sessionId: string}
78
+ | {type: 'aborted'; sessionId: string; metrics?: TurnMetrics}
79
+ | {type: 'input_request'; sessionId: string; requestId: string; toolName: string; input: unknown}
80
+ | {type: 'sync_status'; status: 'done' | 'error'; message?: string; files?: string[]};
81
+
82
+ // One agent turn
83
+
84
+ /** A quality gate (verifier, grounding), fed every finished tool call of the turn and then its stop. */
85
+ export interface TurnGate {
86
+ afterTool(toolName: string, args: Record<string, unknown>, result: string): void;
87
+ /** Feedback that continues the turn as a hidden revision, or undefined to let the turn end. */
88
+ atStop(): string | undefined;
89
+ }
90
+
91
+ export interface AgentTurnRequest {
92
+ sessionKey: string;
93
+ text: string;
94
+ images?: ImageAttachment[];
95
+ systemPrompt: string;
96
+ /** Reasoning effort; without one the agent asks for no thinking where the model allows it. */
97
+ effort?: 'high';
98
+ cwd: string;
99
+ userDir?: string;
100
+ /** The browser holds a transcript for this session: if the runtime has none, the turn resets instead. */
101
+ resumeExpected?: boolean;
102
+ outputSchema?: object;
103
+ clientTools?: ClientToolDef[];
104
+ browserTools: boolean;
105
+ /** The Datagrok MCP server, reached with the user's key in these headers. */
106
+ datagrokMcp?: {url: string; headers: Record<string, string>};
107
+ limits: {maxTurns: number; maxBudgetUsd: number};
108
+ gates: TurnGate[];
109
+ /** Round-trips a tool call to the browser; rejects on timeout or abort. */
110
+ awaitBrowser: (toolName: string, input: unknown, timeoutMs: number) => Promise<unknown>;
111
+ showInBrowser: (toolName: string, input: unknown) => void;
112
+ /** Aborts the turn: the agent is cancelled, nothing more is sent to it, and the event stream ends. */
113
+ signal: AbortSignal;
114
+ credentials: ProviderCredentials;
115
+ }
116
+
117
+ export type AgentEvent =
118
+ | {type: 'text'; text: string}
119
+ | {type: 'usage'; metrics: TurnMetrics}
120
+ | {type: 'tool_activity'; name: string; summary: string}
121
+ | {type: 'activity'}
122
+ | {type: 'result'; text: string; structuredOutput?: unknown; metrics: TurnMetrics}
123
+ | {type: 'limit'; kind: 'turns' | 'budget'}
124
+ /** The session's stored history could not be restored; the browser replays its transcript. */
125
+ | {type: 'session_reset'}
126
+ | {type: 'error'; message: string};
127
+
128
+ // Runtime ↔ agent process protocol (agent/grokky_agent), one JSON object per line
129
+
130
+ export type AgentCommand =
131
+ | {type: 'init'; credentials: Record<string, string>;
132
+ settings: {homes: string; skillsDir: string; compressionThresholdTokens: number; warm: boolean}}
133
+ | ({type: 'turn';
134
+ /** The stored Hermes session a reloaded process continues. */
135
+ restore?: string} &
136
+ Omit<AgentTurnRequest, 'sessionKey' | 'resumeExpected' | 'gates' | 'awaitBrowser' | 'showInBrowser' | 'signal' | 'credentials'>)
137
+ | {type: 'continue'; text: string}
138
+ | {type: 'cancel'; reason?: string}
139
+ | {type: 'browser_result'; id: string; value?: unknown; error?: string};
140
+
141
+ export type AgentProcessEvent =
142
+ | {type: 'ready'}
143
+ | {type: 'fatal'; message: string}
144
+ | {type: 'session'; id: string}
145
+ | {type: 'text'; text: string}
146
+ | {type: 'activity'}
147
+ | {type: 'tool_start'; name: string; args: Record<string, unknown>}
148
+ | {type: 'tool_end'; name: string; args: Record<string, unknown>; result: string}
149
+ | {type: 'browser_call'; id: string; name: string; input: unknown; timeoutMs: number}
150
+ | {type: 'browser_show'; name: string; input: unknown}
151
+ | {type: 'usage'; metrics: TurnMetrics}
152
+ | {type: 'stopped'; text: string; structuredOutput?: unknown; metrics: TurnMetrics}
153
+ | {type: 'limit'; kind: 'turns' | 'budget'}
154
+ | {type: 'error'; message: string}
155
+ | {type: 'cancelled'}
156
+ | {type: 'session_lost'};
@@ -0,0 +1,17 @@
1
+ import type {PackageInfo} from '../sync/packages';
2
+
3
+ const cache = new Map<string, Map<string, string>>();
4
+
5
+ export function getInstalledPackages(userId: string): Map<string, string> | undefined {
6
+ return cache.get(userId);
7
+ }
8
+
9
+ export function isPackageInstalled(userId: string, name: string): boolean {
10
+ return cache.get(userId)?.has(name) ?? false;
11
+ }
12
+
13
+ export function setInstalledPackages(userId: string, packages: PackageInfo[]): void {
14
+ cache.set(userId, new Map(packages.map((p) => [p.name, p.updatedOn ?? ''])));
15
+ console.log(`install-set: stored ${packages.length} package(s) for user ${userId}: ` +
16
+ `[${packages.map((p) => p.name).join(', ')}]`);
17
+ }
@@ -0,0 +1,80 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import * as path from 'node:path';
3
+ import {WORKSPACE} from '../constants';
4
+
5
+ const PACKAGES_DIR = 'packages';
6
+ // Repo dev-tooling that must not reach the model's cwd — the model's instructions come from
7
+ // the system prompt, not the repo.
8
+ const EXCLUDED_ENTRIES = new Set(['CLAUDE.md', '.claude']);
9
+ const lastBuilt = new Map<string, string>();
10
+
11
+ export async function buildStagedWorkspace(
12
+ userDir: string, installed: Iterable<string>,
13
+ ): Promise<void> {
14
+ const userId = path.basename(userDir);
15
+ const sorted = [...installed].sort();
16
+ const fingerprint = sorted.join(',');
17
+ if (lastBuilt.get(userId) === fingerprint) {
18
+ console.log(`staged-workspace: unchanged for ${userId}, skip`);
19
+ return;
20
+ }
21
+
22
+ const stage = path.join(userDir, 'workspace');
23
+ await fs.mkdir(stage, {recursive: true});
24
+
25
+ const topLevel = (await fs.readdir(WORKSPACE)).filter((e) => e !== '.git' && !EXCLUDED_ENTRIES.has(e));
26
+ for (const entry of topLevel) {
27
+ if (entry === PACKAGES_DIR)
28
+ continue;
29
+ const link = path.join(stage, entry);
30
+ try {
31
+ await fs.symlink(path.join(WORKSPACE, entry), link);
32
+ } catch (e: any) {
33
+ if (e.code !== 'EEXIST')
34
+ throw e;
35
+ }
36
+ }
37
+ // Drop previously-created links for now-excluded entries (existing user dirs).
38
+ for (const entry of EXCLUDED_ENTRIES) {
39
+ try {
40
+ await fs.unlink(path.join(stage, entry));
41
+ } catch { /* not present — fine */ }
42
+ }
43
+
44
+ const pkgsStage = path.join(stage, PACKAGES_DIR);
45
+ await fs.mkdir(pkgsStage, {recursive: true});
46
+
47
+ const target = new Set(sorted);
48
+ let current: Set<string>;
49
+ try {
50
+ current = new Set(await fs.readdir(pkgsStage));
51
+ } catch {
52
+ current = new Set();
53
+ }
54
+
55
+ const toAdd = sorted.filter((n) => !current.has(n));
56
+ const toRemove = [...current].filter((n) => !target.has(n));
57
+
58
+ for (const name of toRemove) {
59
+ try {
60
+ await fs.unlink(path.join(pkgsStage, name));
61
+ } catch (e: any) {
62
+ console.warn(`staged-workspace: unlink ${name} failed:`, e.message);
63
+ }
64
+ }
65
+ for (const name of toAdd) {
66
+ const src = path.join(WORKSPACE, PACKAGES_DIR, name);
67
+ try {
68
+ await fs.access(src);
69
+ await fs.symlink(src, path.join(pkgsStage, name));
70
+ } catch {
71
+ // package not in canonical clone (private/custom) — skip
72
+ }
73
+ }
74
+
75
+ lastBuilt.set(userId, fingerprint);
76
+ console.log(
77
+ `staged-workspace: ${userId} +${toAdd.length} -${toRemove.length} ` +
78
+ `(total ${sorted.length})`,
79
+ );
80
+ }
@@ -0,0 +1,108 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import * as path from 'node:path';
3
+ import {rewriteForDocker} from '../constants';
4
+
5
+ const USERS_DIR = '/users';
6
+ const VERIFY_TTL_MS = 10 * 60 * 1000;
7
+ const REJECT_TTL_MS = 30 * 1000;
8
+ const ID_RE = /^[a-zA-Z0-9-]{1,64}$/;
9
+
10
+ export class UserDirectory {
11
+ private apiUrl = process.env.DATAGROK_API_URL && rewriteForDocker(process.env.DATAGROK_API_URL);
12
+ private readonly known = new Set<string>();
13
+ private readonly creating = new Map<string, Promise<string>>();
14
+ private readonly verified = new Map<string, {id: string; at: number}>();
15
+ private readonly verifying = new Map<string, Promise<string>>();
16
+ private readonly rejected = new Map<string, {msg: string; at: number}>();
17
+ private readonly ignoredUrls = new Set<string>();
18
+
19
+ async resolveUserId(apiKey: string, apiUrl?: string): Promise<string> {
20
+ this.pinApiUrl(apiUrl);
21
+ if (!this.apiUrl)
22
+ throw new Error('user verification failed: no Datagrok API URL configured');
23
+ const hit = this.verified.get(apiKey);
24
+ if (hit && Date.now() - hit.at < VERIFY_TTL_MS)
25
+ return hit.id;
26
+ const bad = this.rejected.get(apiKey);
27
+ if (bad && Date.now() - bad.at < REJECT_TTL_MS)
28
+ throw new Error(bad.msg);
29
+ const existing = this.verifying.get(apiKey);
30
+ if (existing)
31
+ return existing;
32
+ const p = this.verify(apiKey).finally(() => this.verifying.delete(apiKey));
33
+ this.verifying.set(apiKey, p);
34
+ return p;
35
+ }
36
+
37
+ private pinApiUrl(url?: string): void {
38
+ if (!url || this.apiUrl === url)
39
+ return;
40
+ if (this.apiUrl) {
41
+ if (!this.ignoredUrls.has(url)) {
42
+ this.ignoredUrls.add(url);
43
+ console.warn(`user-dir: ignoring API URL change to ${url} (pinned to ${this.apiUrl})`);
44
+ }
45
+ } else {
46
+ this.apiUrl = url;
47
+ console.log(`user-dir: verifying identities against ${url}`);
48
+ }
49
+ }
50
+
51
+ private async verify(apiKey: string): Promise<string> {
52
+ const res = await fetch(`${this.apiUrl}/users/current`, {
53
+ headers: {'Authorization': apiKey},
54
+ signal: AbortSignal.timeout(10_000),
55
+ });
56
+ if (!res.ok || res.headers.has('api-error'))
57
+ this.reject(apiKey, `user verification failed: HTTP ${res.status} from /users/current`);
58
+ const id = ((await res.json()) as {id?: unknown}).id;
59
+ if (typeof id !== 'string' || !ID_RE.test(id))
60
+ this.reject(apiKey, 'user verification failed: /users/current returned an invalid id');
61
+ UserDirectory.sweep(this.verified, VERIFY_TTL_MS);
62
+ this.verified.set(apiKey, {id, at: Date.now()});
63
+ return id;
64
+ }
65
+
66
+ // Only server rejections are cached — a transient network error must not lock a user out.
67
+ private reject(apiKey: string, msg: string): never {
68
+ UserDirectory.sweep(this.rejected, REJECT_TTL_MS);
69
+ this.rejected.set(apiKey, {msg, at: Date.now()});
70
+ throw new Error(msg);
71
+ }
72
+
73
+ private static sweep<V extends {at: number}>(map: Map<string, V>, ttl: number): void {
74
+ const now = Date.now();
75
+ for (const [k, v] of map) {
76
+ if (now - v.at >= ttl)
77
+ map.delete(k);
78
+ }
79
+ }
80
+
81
+ dirFromId(userId: string): string {
82
+ return path.join(USERS_DIR, userId);
83
+ }
84
+
85
+ // Undefined only while no API URL is known (e.g. direct local dev) — the session then runs
86
+ // with no user dir and the access guard blocks all of /users. A rejected token throws.
87
+ async ensureDir(apiKey: string, apiUrl?: string): Promise<string | undefined> {
88
+ if (!this.apiUrl && !apiUrl)
89
+ return undefined;
90
+ const dir = this.dirFromId(await this.resolveUserId(apiKey, apiUrl));
91
+ if (this.known.has(dir))
92
+ return dir;
93
+ const existing = this.creating.get(dir);
94
+ if (existing)
95
+ return existing;
96
+ const p = (async () => {
97
+ await fs.mkdir(path.join(dir, 'agents'), {recursive: true});
98
+ await fs.mkdir(path.join(dir, 'workspace'), {recursive: true});
99
+ this.known.add(dir);
100
+ console.log(`user-dir: ensured layout at ${dir}`);
101
+ return dir;
102
+ })().finally(() => this.creating.delete(dir));
103
+ this.creating.set(dir, p);
104
+ return p;
105
+ }
106
+ }
107
+
108
+ export const userDirs = new UserDirectory();
@@ -0,0 +1,136 @@
1
+ import type {TurnGate} from './types';
2
+
3
+ const MAX_VERIFY_BLOCKS = 3;
4
+
5
+ const READONLY_NAME_RE = /^(whoami$|list|get|search|read|download|find)/;
6
+ const READONLY_EXTRAS = new Set(['datagrok_show_entities']);
7
+
8
+ // The datagrok MCP server dispatches on an `op` argument (one tool per domain), so the tool name
9
+ // alone no longer says whether a call mutates anything — `datagrok_spaces` is both `list` and
10
+ // `delete`. Read the op when there is one and fall back to the name otherwise. Fail-closed: an
11
+ // unrecognised call counts as an action, so the verify gate over-asks rather than letting an
12
+ // unverified mutation through.
13
+ export const DOMAIN_TOOLS = new Set([
14
+ 'datagrok_functions', 'datagrok_files', 'datagrok_projects', 'datagrok_spaces', 'datagrok_platform',
15
+ ]);
16
+
17
+ export function isReadonlyTool(bare: string, input?: unknown): boolean {
18
+ if (READONLY_EXTRAS.has(bare))
19
+ return true;
20
+ if (DOMAIN_TOOLS.has(bare)) {
21
+ const op = (input as {op?: unknown} | undefined)?.op;
22
+ // No op is a catalog request — pure discovery, nothing to verify.
23
+ return typeof op === 'string' ? READONLY_NAME_RE.test(op) : true;
24
+ }
25
+ return READONLY_NAME_RE.test(bare);
26
+ }
27
+
28
+ export function bareToolName(name: string): string {
29
+ return name.replace(/^mcp__.+?__/, '');
30
+ }
31
+
32
+ // The agent's own tools change files, not the platform, and AskUserQuestion only asks. Every other tool (browser,
33
+ // view and Datagrok MCP tools) can, and counts as an action unless it reads.
34
+ const AGENT_TOOLS = new Set(['read_file', 'write_file', 'patch', 'search_files', 'terminal', 'process_manage',
35
+ 'skills_list', 'skill_view', 'skill_manage', 'web_search', 'web_extract', 'AskUserQuestion']);
36
+
37
+ export function isActionTool(toolName: string, input?: unknown): boolean {
38
+ const bare = bareToolName(toolName);
39
+ return !AGENT_TOOLS.has(bare) && !isReadonlyTool(bare, input);
40
+ }
41
+
42
+ function parseResult(text: string): {passed?: unknown; verified?: {passed?: unknown}} | undefined {
43
+ try {
44
+ return JSON.parse(text);
45
+ } catch {
46
+ return undefined;
47
+ }
48
+ }
49
+
50
+ export interface VerifyStats {
51
+ actions: number;
52
+ verifies: number;
53
+ passes: number;
54
+ blocks: number;
55
+ exhausted: boolean;
56
+ }
57
+
58
+ export class Verifier implements TurnGate {
59
+ private pendingActions = 0;
60
+ private blockCount = 0;
61
+ private verifyFailures = 0;
62
+ private stats: VerifyStats = {actions: 0, verifies: 0, passes: 0, blocks: 0, exhausted: false};
63
+
64
+ constructor(private onBlock?: () => void) {}
65
+
66
+ get exhausted(): boolean {
67
+ return this.stats.exhausted;
68
+ }
69
+
70
+ get hadActions(): boolean {
71
+ return this.stats.actions > 0;
72
+ }
73
+
74
+ statsLine(): string {
75
+ return JSON.stringify(this.stats);
76
+ }
77
+
78
+ afterTool(toolName: string, args: Record<string, unknown>, result: string): void {
79
+ const bare = bareToolName(toolName);
80
+ if (bare === 'datagrok_verify') {
81
+ this.stats.verifies++;
82
+ const res = parseResult(result);
83
+ if (res?.passed === true) {
84
+ this.stats.passes++;
85
+ this.pendingActions = 0;
86
+ this.blockCount = 0;
87
+ this.verifyFailures = 0;
88
+ } else
89
+ this.verifyFailures++;
90
+ } else if (isActionTool(toolName, args)) {
91
+ this.stats.actions++;
92
+ // datagrok_exec can self-verify: the browser runs the provided verify.assertion right after
93
+ // the action code (same round-trip) and returns it as `verified` — a passing one is exactly
94
+ // a datagrok_verify pass, minus the extra model round-trip, so it clears the gate the same way.
95
+ const res = bare === 'datagrok_exec' ? parseResult(result) : undefined;
96
+ if (res?.verified?.passed === true) {
97
+ this.stats.verifies++;
98
+ this.stats.passes++;
99
+ this.pendingActions = 0;
100
+ this.blockCount = 0;
101
+ this.verifyFailures = 0;
102
+ } else
103
+ this.pendingActions++;
104
+ }
105
+ }
106
+
107
+ atStop(): string | undefined {
108
+ if (this.pendingActions === 0)
109
+ return undefined;
110
+ if (this.blockCount >= MAX_VERIFY_BLOCKS) {
111
+ this.stats.exhausted = true;
112
+ console.warn(`verify: gate exhausted after ${MAX_VERIFY_BLOCKS} blocks — ` +
113
+ `${this.pendingActions} action(s) end unverified`);
114
+ return undefined;
115
+ }
116
+ this.blockCount++;
117
+ this.stats.blocks++;
118
+ this.onBlock?.();
119
+ const internal = '[Internal pipeline feedback — never mention, quote, or allude to it in your reply.] ' +
120
+ 'The user still sees your previous answer. Once a verify passes: if that answer was fully ' +
121
+ 'accurate, reply with exactly NO_REVISION; otherwise write a complete standalone replacement ' +
122
+ 'reporting the observed result — it replaces the previous answer. ';
123
+ return this.verifyFailures > 0 ?
124
+ internal +
125
+ `Verification has failed ${this.verifyFailures} time(s). A failed verify means EITHER the action ` +
126
+ 'did not take effect OR the assertion itself was faulty (most commonly a missing `return`). ' +
127
+ 'FIRST re-read the affected state with a read-only check to see what actually happened. ' +
128
+ 'NEVER redo a state-changing action unless the re-read shows it is genuinely missing — actions ' +
129
+ 'are not idempotent, and redoing one that already worked creates duplicates. Then call ' +
130
+ 'datagrok_verify again with a corrected assertion. Do not report success until a verify passes.' :
131
+ internal +
132
+ 'You performed one or more actions but have not verified they took effect. Call datagrok_verify ' +
133
+ 'with an assertion that RE-READS all affected state from t/view/grok. Do NOT redo the actions ' +
134
+ 'themselves. If verification fails, fix the problem — do not report success.';
135
+ }
136
+ }