@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,746 @@
1
+ # Claude Code Flow
2
+
3
+ This document describes how the Claude agent runtime is deployed and integrated into Datagrok: how the server-side
4
+ containers are set up, how messages travel between the browser and the containers, and how Claude's
5
+ responses are turned into live Datagrok UI.
6
+
7
+ ---
8
+
9
+ ## Architecture Overview
10
+
11
+ Three components work together:
12
+
13
+ ```
14
+ Browser (TypeScript)
15
+ └── ClaudeRuntimeClient ──WebSocket──▶ claude-runtime container ──MCP──▶ mcp-server container
16
+ │ │
17
+ one agent process per session grok.dapi.*
18
+ (Hermes Agent, JSON lines on stdio) (Datagrok API over HTTP)
19
+ ```
20
+
21
+ | Component | Location | Port |
22
+ |----------------------------|-------------------------------------------------------------------|------|
23
+ | Browser client | [`src/claude/runtime-client.ts`](../src/claude/runtime-client.ts) | — |
24
+ | `claude-runtime` container | [`dockerfiles/claude-runtime/`](../dockerfiles/claude-runtime/) | 5355 |
25
+ | `mcp-server` container | [`dockerfiles/mcp-server/`](../dockerfiles/mcp-server/) | 3003 |
26
+
27
+ ---
28
+
29
+ ## Deployment
30
+
31
+ ### Containers
32
+
33
+ Both containers live under [`dockerfiles/`](../dockerfiles/) and are managed by the Datagrok platform's
34
+ Docker subsystem. The platform discovers and starts them automatically when the Grokky package is published.
35
+
36
+ **`claude-runtime`** ([`Dockerfile`](../dockerfiles/claude-runtime/Dockerfile)):
37
+
38
+ - Base image: `node:22-trixie-slim`, pinned by digest.
39
+ - Clones the public Datagrok repo into `/workspace` (and the help repo into `/workspace/help`) at build
40
+ time — this gives Claude read access to the JS API source, packages, samples, and documentation
41
+ without fetching them at runtime.
42
+ - Runs `dist/server.js` (compiled from [`src/server.ts`](../dockerfiles/claude-runtime/src/server.ts))
43
+ on port 5355 under `tini`; the server starts as root and drops to uid 1001 before anything else runs.
44
+ - Runs the agent loop in [Hermes Agent](https://github.com/NousResearch/hermes-agent) (pinned commit,
45
+ `/opt/hermes`): one `python -m grokky_agent` process per chat session
46
+ ([`agent/grokky_agent/`](../dockerfiles/claude-runtime/agent/grokky_agent/)), which embeds Hermes' `AIAgent`
47
+ and exchanges JSON lines with the server over stdin/stdout. See [Operations](#operations).
48
+ - The provider key reaches each agent process only in the first line of its stdin; Hermes calls the
49
+ provider's model API directly. No key is in an agent's environment or in a file.
50
+ - Ships the `datagrok-*` skills ([`plugin/`](../dockerfiles/claude-runtime/plugin/)).
51
+ - Health check: `GET /health` → `{status: "ok"}`.
52
+
53
+ **`mcp-server`** ([`Dockerfile`](../dockerfiles/mcp-server/Dockerfile)):
54
+
55
+ - Runs `dist/index.js` (compiled from [`src/index.ts`](../dockerfiles/mcp-server/src/index.ts))
56
+ on port 3003.
57
+ - Exposes Datagrok operations as MCP tools (HTTP/streamable transport).
58
+ - Auth is passed per-request via `x-user-api-key` and `x-datagrok-api-url` headers, which each session's
59
+ agent sends on every call.
60
+
61
+ ### Container Discovery (browser side)
62
+
63
+ [`ClaudeRuntimeClient.discover()`](../src/claude/runtime-client.ts) finds both containers at
64
+ runtime via `grok.dapi.docker`:
65
+
66
+ ```typescript
67
+ const [runtimeContainers, mcpContainers] = await Promise.all([
68
+ grok.dapi.docker.dockerContainers.filter('name = "grokky-claude-runtime"').list(),
69
+ grok.dapi.docker.dockerContainers.filter('name = "grokky-mcp-server"').list(),
70
+ ]);
71
+ this.ws = await grok.dapi.docker.dockerContainers.webSocketProxy(containerId, '/ws');
72
+ this.mcpServerUrl = `${grok.dapi.root}/docker/containers/proxy/${mcpContainerId}/mcp`;
73
+ ```
74
+
75
+ The WebSocket and MCP HTTP traffic both flow through Datagrok's reverse proxy, so the browser never
76
+ talks to the containers directly.
77
+
78
+ Container code compiles **inside** the image, so `grok publish` / `npm run build` (browser bundle
79
+ only) do not update it — rebuild the image and redeploy after any change under `dockerfiles/`.
80
+
81
+ ---
82
+
83
+ ## Message Protocol
84
+
85
+ All communication between the browser and `claude-runtime` is JSON over a single WebSocket connection.
86
+ Message types are defined in [`dockerfiles/claude-runtime/src/types.ts`](../dockerfiles/claude-runtime/src/types.ts).
87
+
88
+ ### Incoming messages (browser → runtime)
89
+
90
+ | `type` | Purpose | Key fields |
91
+ |--------|---------|------------|
92
+ | `user_message` | Send a prompt, start or resume a session | `sessionId`, `message`, `images?`, `apiKey`, `mcpServerUrl`, `outputSchema?`, `systemPromptMode?` (`datagrok`/`search`/`bash`/`none`), `model?`, `clientTools?`, `gates?`, `resumeExpected?`, `taskId?` |
93
+ | `abort` | Cancel an in-progress query | `sessionId` |
94
+ | `input_response` | Reply to an `input_request` (browser tool result or user answer) | `sessionId`, `requestId`, `value` |
95
+ | `sync_user_files` | Trigger a skills/knowledge sync | `apiKey`, `mcpServerUrl`, `scope?`, `packageName?` |
96
+
97
+ Notes on `user_message` fields:
98
+
99
+ - `images` — base64 attachments (`ImageAttachment[]`) prepended to the prompt content.
100
+ - `clientTools` — tool definitions declared by the browser for this turn (the static view-function
101
+ meta-tools plus `datagrok_confirm`); their calls round-trip to the browser via
102
+ `input_request`/`input_response`.
103
+ - `gates` — per-turn switches for the verify/grounding gates (both default on; used by benchmark arms).
104
+ - `taskId` — id of the queued admission task: the turn holds until the matching
105
+ `Grokky:aiChatTurnTask` celery task claims it via `POST /task/claim` (see
106
+ [`tasks.ts`](../dockerfiles/claude-runtime/src/tasks.ts), [`src/claude/queue-task.ts`](../src/claude/queue-task.ts)).
107
+
108
+ ### Outgoing messages (runtime → browser)
109
+
110
+ | `type` | Purpose | Key fields |
111
+ |--------|---------|------------|
112
+ | `chunk` | Incremental text delta from Claude | `sessionId`, `content` |
113
+ | `tool_activity` | Human-readable summary of a tool call in progress | `sessionId`, `summary`, `name` (bare tool name) |
114
+ | `revision_start` | A gate (verifier/grounding) blocked the turn's Stop; a revision streams hidden — `final.revision` says whether it replaces the visible answer | `sessionId` |
115
+ | `final` | Completed response | `sessionId`, `content`, `structured_output?`, `unverified?`, `metrics?` (tokens/cost/turns/duration), `revision?` (`kept`/`replaced`) |
116
+ | `error` | Session error | `sessionId`, `message` |
117
+ | `session_reset` | The session record is gone but the browser sent `resumeExpected` — the turn was not run; the browser resends the prompt with the conversation transcript prepended | `sessionId` |
118
+ | `aborted` | Confirmed abort | `sessionId` |
119
+ | `queued` | Turn is waiting — behind the session's active query, or for its celery admission claim (re-sent every 60s while waiting) | `sessionId` |
120
+ | `keepalive` | Every 20s while the socket has a turn open, so a proxy never sees it idle; the browser ignores it | |
121
+ | `input_request` | Runtime needs the browser to execute a tool or answer a question | `sessionId`, `requestId`, `toolName`, `input` |
122
+ | `sync_status` | Result of a `sync_user_files` request | `status`, `files?`, `message?` |
123
+
124
+ ---
125
+
126
+ ## Server-Side: claude-runtime
127
+
128
+ [`server.ts`](../dockerfiles/claude-runtime/src/server.ts) is a [Hono](https://hono.dev) server with a
129
+ WebSocket endpoint at `/ws`, `GET /health`, and `POST /task/claim` / `/task/release` for the celery
130
+ admission long-poll. [`session.ts`](../dockerfiles/claude-runtime/src/session.ts) runs the turns;
131
+ [`agent/pool.ts`](../dockerfiles/claude-runtime/src/agent/pool.ts) owns the agent processes and
132
+ [`agent/turn.ts`](../dockerfiles/claude-runtime/src/agent/turn.ts) drives one turn on one of them. Every
133
+ message shape — WebSocket protocol, turn request, agent commands and events — is in
134
+ [`types.ts`](../dockerfiles/claude-runtime/src/types.ts).
135
+
136
+ ### Process model
137
+
138
+ ```
139
+ tini (pid 1)
140
+ └── node dist/server.js drops from root to uid 1001 at start, so it is not dumpable
141
+ ├── python -m grokky_agent one per chat session: own process group, own HERMES_HOME
142
+ │ │ stdin init (credentials, settings), then turn / continue / cancel / browser_result
143
+ │ │ stdout events: ready, session, text, tool_start, tool_end, browser_call, stopped, …
144
+ │ ├── Hermes AIAgent ──▶ the provider's model API (apiKey)
145
+ │ ├── MCP client ──▶ mcp-server (the user's Datagrok key in the headers)
146
+ │ └── tool processes (terminal, …)
147
+ └── python -m grokky_agent warm spare, not yet bound to a session
148
+
149
+ /var/lib/grokky/hermes/<uuid>/ a live agent's HERMES_HOME; it stays, with its state.db, after the agent
150
+ dies holding its session, and the next turn reloads it there
151
+ /var/lib/grokky/hermes/parked/<uuid>/ state.db of an evicted session, reloaded by its next turn
152
+ ```
153
+
154
+ ### Turn lifecycle
155
+
156
+ [`handleMessage()`](../dockerfiles/claude-runtime/src/session.ts) handles each `user_message`:
157
+
158
+ 1. Chains the turn on the session's FIFO queue (`sessionChains`) — a second prompt for the same
159
+ session waits behind the first, emitting `queued` heartbeats.
160
+ 2. If the message carries a `taskId`, waits for the celery admission claim (the queue container's
161
+ concurrency limit is the only cap on concurrent turns), failing open if no claim arrives.
162
+ 3. Resolves the per-user directory (`/users/<id>`, the user verified with their key), which becomes
163
+ the turn's working directory, and syncs the user's files (the first sync per user blocks; later
164
+ turns serve what is on disk).
165
+ 4. Picks the [system prompt](#system-prompt) for `systemPromptMode` and the turn's limits: 100 model
166
+ calls and $2.50 in full mode, 10 calls and $0.25 in `bash`/`none`. Full mode also gets the gates
167
+ below and `high` reasoning effort.
168
+ 5. [`runTurn()`](../dockerfiles/claude-runtime/src/agent/turn.ts) answers `session_reset` if the browser
169
+ expects to resume (`resumeExpected`) but the runtime holds neither a live process nor a parked session
170
+ for it; the browser then replays its transcript once. Otherwise it takes the session's agent process
171
+ from the pool (live, reloaded from its parked store, a warm spare, or a new one) and sends a `turn`
172
+ command: text and images, system prompt, effort, cwd, output schema, the browser's
173
+ `clientTools`, the Datagrok MCP URL with the user's key in its headers, and the limits.
174
+ 6. The agent ([`session.py`](../dockerfiles/claude-runtime/agent/grokky_agent/session.py)) prepares its
175
+ `AIAgent` on the configured model ([Credentials](#credentials)), this turn's
176
+ view tools and MCP server (re-registered only when they change), thinking on or off — and runs the
177
+ conversation. The hooks registered by the in-process plugin
178
+ ([`hermes_plugin/`](../dockerfiles/claude-runtime/agent/grokky_agent/hermes_plugin/)) act for the turn:
179
+ - `pre_tool_call` reports `tool_start`, applies the [access guard](#security-model), and makes a relative
180
+ `write_file`/`patch` path absolute against the turn's directory;
181
+ - `post_tool_call` reports `tool_end`, which feeds the gates;
182
+ - `pre_api_request` clears the previous attempt's error, `post_api_request` counts tokens and cost,
183
+ `api_request_error` keeps the provider's error text, and `pre_auxiliary_call` / `post_auxiliary_call`
184
+ track and count history compression;
185
+ - the `llm_request` middleware puts the turn's system prompt and output format on every model
186
+ request, in the request's format. If it cannot, it sends a request the API refuses instead, so nothing
187
+ of the conversation leaves the process.
188
+ 7. `session.ts` forwards the agent's events (mapping below), racing each against a 90 s idle watchdog
189
+ ([`watchdog.ts`](../dockerfiles/claude-runtime/src/watchdog.ts)). Browser round-trips in flight don't
190
+ count, and the agent sends an `activity` heartbeat at most every 30 s while a tool or compression call
191
+ runs or the model streams anything, thinking and tool-call arguments included (Hermes stamps every
192
+ stream event on its activity clock). Hermes' other stamps (its waits, wait notices, reconnects) do not
193
+ count, so a provider that sends nothing still trips the watchdog; during a history compression, only
194
+ once Hermes gives up on the compression call (after 300 s at least, 600 s at most).
195
+ A turn that goes silent gets an `error`, and its session is parked: the process tree is killed and the
196
+ next turn reloads the history in a fresh process.
197
+
198
+ The agent's tools are the same in every mode: Hermes' native toolsets `file` (`read_file`, `write_file`,
199
+ `patch`, `search_files`), `terminal` (`terminal`, `process_manage`), `skills` (`skills_list`, `skill_view`;
200
+ `skill_manage` is blocked) and `web` (`web_search`, `web_extract`); the browser tools below; and the
201
+ Datagrok MCP server's tools, named `mcp__datagrok__*`, whose results (like the web tools') Hermes hands to
202
+ the model inside its `<untrusted_tool_result>` envelope.
203
+
204
+ The agent counts model calls and cost per turn, gate revisions and structured-output retries included; at a
205
+ limit the run stops, a call past it is refused before it is sent, and the turn ends in an `error` naming the
206
+ turn or cost limit.
207
+
208
+ ### Browser round-trips: `input_request` / `input_response`
209
+
210
+ [`browser_tools.py`](../dockerfiles/claude-runtime/agent/grokky_agent/browser_tools.py) registers the
211
+ tools that run in the Datagrok tab as native Hermes tools, so their results reach the model as they
212
+ are. A call is checked against the tool's schema, then relayed: the agent emits `browser_call`, the
213
+ server sends an `input_request` and waits for the matching `input_response` (correlated by
214
+ `requestId`, so parallel calls don't cross wires), and the answer goes back to the agent as
215
+ `browser_result`. A call the browser does not answer in time returns an error result to the model.
216
+
217
+ - **`datagrok_exec`** (300s timeout) — JS executed in the tab against the live view; an optional
218
+ inline `verify` assertion runs in the same round-trip.
219
+ - **`datagrok_verify`** (60s) — standalone re-read-the-state assertion.
220
+ - **`datagrok_show_entities`** (30s) — renders interactive entity cards in the chat.
221
+ - **View tools** (120s) — whatever the browser declared in `clientTools`: the static meta-tools
222
+ `list_view_functions` / `list_view_widgets` / `get_view_function_result` / `call_view_function`
223
+ (searching and invoking the current view's `getFunctions()` set) plus `datagrok_confirm`
224
+ (see [`src/ai/view-tools.ts`](../src/ai/view-tools.ts)). A declared tool needs a plain name and a
225
+ description; a name another tool already has is skipped.
226
+
227
+ `AskUserQuestion` does not wait: the card is shown, the turn ends, and Submit sends the choice as the next prompt.
228
+
229
+ ### Verification and grounding gates
230
+
231
+ Full-prompt turns (not `bash`/`none`) are gated in Node: each finished tool call arrives as the agent's
232
+ `tool_end` event (a call the guard refused is not reported), and the stop check runs when the agent
233
+ reports `stopped`. The browser can switch either gate off per turn via `gates`.
234
+
235
+ - **[`verify.ts`](../dockerfiles/claude-runtime/src/verify.ts)** enforces act → verify: any
236
+ `datagrok_exec` (including failed ones), or a browser, view or MCP tool call that does not read, marks
237
+ the turn as needing proof (reads are recognized fail-closed: the domain tools by their `op` argument,
238
+ other tools by their name's verb). A passing verification clears it; a stop with proof pending is
239
+ blocked up to 3 times, after which `final` carries `unverified: true` and the panel shows a
240
+ "Not verified" warning.
241
+ - **[`grounding.ts`](../dockerfiles/claude-runtime/src/grounding.ts)** checks at stop whether an
242
+ answer makes platform how-to claims without having opened a source this turn, and demands a
243
+ grounded revision if so. Small talk and structured-output turns skip it.
244
+
245
+ When a gate blocks the stop, the runtime emits `revision_start` and sends the agent a `continue`
246
+ command carrying the gate's feedback. The revision streams *hidden*
247
+ ([`stream-filter.ts`](../dockerfiles/claude-runtime/src/stream-filter.ts) suppresses its chunks);
248
+ the visible answer stays put until `final.revision` says whether the revision replaces it
249
+ (`replaced`) or the original stands (`kept`, signaled by the model answering `NO_REVISION`).
250
+
251
+ ### Agent event → WebSocket message mapping
252
+
253
+ The agent writes one JSON event per stdout line; [`turn.ts`](../dockerfiles/claude-runtime/src/agent/turn.ts)
254
+ turns them into turn events, which `forwardEvent()` in [`session.ts`](../dockerfiles/claude-runtime/src/session.ts)
255
+ emits:
256
+
257
+ | Agent event | → WS message |
258
+ |---------------------------------|---------------------------------------------------------------------|
259
+ | `text` | `chunk` (through the fence/revision buffer) |
260
+ | `tool_start` | `tool_activity` |
261
+ | `tool_end` | — (fed to the gates) |
262
+ | `browser_call` | `input_request`; the reply goes back to the agent as `browser_result` |
263
+ | `stopped`, gates pass | `final` (with the turn's `metrics`) |
264
+ | `stopped`, a gate blocks | `revision_start`, and a `continue` command to the agent |
265
+ | `limit` | `error` (turn/cost limit text) |
266
+ | `error` | `error` (e.g. the provider's message) |
267
+ | `session_lost` | `session_reset` (the stored history could not be restored) |
268
+ | `activity`, `cancelled` | — (`activity` only keeps the watchdog fed) |
269
+
270
+ `ready`, `fatal` and `session` belong to the process's startup and bookkeeping (see
271
+ [Agent processes and sessions](#agent-processes-and-sessions)). In a structured-output turn the agent
272
+ reports text deltas as `activity`, and the answer arrives whole in `final`.
273
+
274
+ Tool results are not forwarded — the browser sees only activity summaries, generated by
275
+ [`toolSummary()`](../dockerfiles/claude-runtime/src/tool-summary.ts) from `toolFormatters` and, for the Datagrok
276
+ MCP tools, their `op`; view tools and unknown tools read as their name.
277
+
278
+ ### System prompt
279
+
280
+ [`prompts.ts`](../dockerfiles/claude-runtime/src/prompts.ts) defines one prompt per
281
+ `systemPromptMode`, built once at startup so it stays byte-stable for prompt caching:
282
+
283
+ - `datagrok` (default): `DATAGROK_PROMPT`, the inlined `datagrok-exec` and `datagrok-entities` skill
284
+ bodies, and an index of every skill in `plugin/skills/` (name and description) to load with
285
+ `skill_view`.
286
+ - `search`: the `datagrok` prompt plus a note that no browser tools are available. The agent runs without
287
+ them: nothing answers a browser call from the search bar's Help and Execute tabs.
288
+ - `bash`: a short prompt to run the given command with the terminal tool and output only its stdout. Its
289
+ text does not stream: the answer is the final message, since models remark before the tool call anyway.
290
+ - `none`: no system prompt at all.
291
+
292
+ The agent's `llm_request` middleware
293
+ ([`formats.py`](../dockerfiles/claude-runtime/agent/grokky_agent/formats.py)) puts the turn's prompt where
294
+ the request's format has it (Anthropic's `system` with `cache_control: ephemeral`, Responses' `instructions`,
295
+ Chat Completions' leading message), or removes it in `none` mode, so the mode can change from turn to turn
296
+ within a session. Full mode runs with thinking at `high` effort; `bash` and `none` turns ask for no thinking
297
+ and run without gates, which Hermes maps per model: off on Haiku 5.5, between tool calls only on Sonnet 5.5,
298
+ and Opus 5.5 keeps its adaptive thinking, which it cannot turn off. On the Responses format `none` is sent as
299
+ `low`, since some GPT models always reason.
300
+
301
+ `DATAGROK_PROMPT` instructs the model to:
302
+
303
+ - Use `workspace/`-relative paths for the public repo clone (absolute `/workspace` is blocked by the access guard).
304
+ - Route capability-shaped requests through the `datagrok-*` skills (`skill_view`).
305
+ - Reach the current view's operations through the view meta-tools, preferring view
306
+ functions over generic `datagrok_exec` code.
307
+ - Reach server-side entities through the per-domain MCP tools, discovering `op` parameters instead
308
+ of guessing names.
309
+ - Ground answers in sources opened this turn (`workspace/help/INDEX.md` for product questions,
310
+ skills for code), never in memory.
311
+ - Use `AskUserQuestion` only when the intent itself is unclear.
312
+
313
+ ---
314
+
315
+ ## Browser Side: ClaudeRuntimeClient
316
+
317
+ [`ClaudeRuntimeClient`](../src/claude/runtime-client.ts) is a singleton WebSocket client.
318
+
319
+ **API:**
320
+
321
+ | Method | Purpose |
322
+ |--------|---------|
323
+ | `send(sessionId, message, options?)` | Send a prompt; options: `outputSchema`, `systemPromptMode`, `model`, `taskId`, `clientTools` |
324
+ | `abort(sessionId)` | Cancel an in-progress query |
325
+ | `respondToInput(sessionId, requestId, value)` | Reply to an `input_request` |
326
+ | `query(message, options?)` | One-shot promise-based call with timeout; wraps send/subscribe/cleanup |
327
+ | `syncUserFiles(scope?, packageName?)` | Trigger a skills/knowledge sync |
328
+ | `isResumable(sessionId)` | Whether the runtime holds this session (drives `resumeExpected`) |
329
+ | `expectResume(sessionId)` | Marks a session the runtime may still hold (a chat reopened from the history) |
330
+
331
+ **RxJS subjects** (one per outgoing message type): `onChunk`, `onToolActivity`, `onRevisionStart`,
332
+ `onFinal`, `onError`, `onSessionReset`, `onAborted`, `onInputRequest`, `onSyncStatus`, plus `onClose`
333
+ for the socket itself.
334
+
335
+ ---
336
+
337
+ ## Streaming to the Panel UI
338
+
339
+ The assistant UI is ONE singleton [`AIPanel`](../src/ai/panel.ts) (created by `initAIWindow()`),
340
+ used for every view. [`runPromptWithLifecycle()`](../src/ai/ui.ts) is the central routing function —
341
+ it intercepts `!`/`!!` command prefixes and usage limits, then `runClaudeStreaming()` in
342
+ [`src/ai/ui.ts`](../src/ai/ui.ts) connects `ClaudeRuntimeClient` events to the panel:
343
+
344
+ ```
345
+ client.onChunk → panel.updateStreaming(accumulated) (live markdown update)
346
+ client.onToolActivity → panel.updateStreaming(accumulated + status) (tool badge)
347
+ client.onRevisionStart → delayed "Revising…" status
348
+ client.onFinal → panel.finalizeStreaming(content) (render; swap in revision if 'replaced')
349
+ client.onError → panel.showError(msg) (status strip above the prompt box) + cleanup
350
+ client.onClose → the same, "Connection lost, …"
351
+ client.onAborted → panel.clearStreaming() + cleanup
352
+ client.onSessionReset → resend prompt with restored transcript prepended (once)
353
+ client.onInputRequest → dispatch by toolName:
354
+ datagrok_exec → executeSingleBlock() (+ inline verify) → respondToInput(outcome)
355
+ datagrok_verify → runVerification() → respondToInput({passed, observed})
356
+ datagrok_confirm → approval card, held until a button is clicked
357
+ datagrok_show_entities → renderEntityRefList() entity cards
358
+ view tools → viewFunctionTools() runner against the live grok.shell.v
359
+ AskUserQuestion → panel.showInputRequest() inline form
360
+ ```
361
+
362
+ Every prompt gets a fresh workspace snapshot from
363
+ [`buildWorkspaceContext()`](../src/claude/exec-blocks.ts) (current view details and AI briefing,
364
+ widget briefings, all open views, all workspace tables) prepended browser-side, and full-mode turns
365
+ declare the static view-function meta-tools as `clientTools`. When the queued route is deployed,
366
+ `sendChatTurn()` ([`src/claude/queue-task.ts`](../src/claude/queue-task.ts)) first launches the
367
+ `aiChatTurnTask` celery task that holds the admission slot; the turn itself streams over the
368
+ WebSocket as usual.
369
+
370
+ Claude executes JS through the `datagrok_exec` tool *during* the turn (an `input_request`
371
+ round-trip via [`exec-blocks.ts`](../src/claude/exec-blocks.ts) `executeSingleBlock()`), so it
372
+ responds only after knowing the real outcome — responses are not post-processed for fenced code
373
+ blocks. If the executed code returns an `HTMLElement`, it is appended to the chat as a result
374
+ widget.
375
+
376
+ ### Panel entry points
377
+
378
+ All are setup functions in [`src/ai/ui.ts`](../src/ai/ui.ts) called from `init()` in
379
+ [`src/package.ts`](../src/package.ts); the ribbon icons toggle the singleton panel rather than
380
+ creating per-view panels:
381
+
382
+ | Function | Context |
383
+ |----------|---------|
384
+ | `setupShellAIPanelUI()` | Shows the singleton panel in the AI window |
385
+ | `setupTableViewAIPanelUI()` | AI ribbon icon on table views |
386
+ | `setupScriptsAIPanelUI()` | AI ribbon icon on script views |
387
+ | `setupAIQueryEditorUI()` | Called by the core query editor — just reports whether AI is configured |
388
+ | `setupSearchUI()` | Global search bar — routes to `CombinedAISearchAssistant` |
389
+ | `setupAgentScriptsUI()` | Run button on file views under `MyFiles/agents/scripts/` |
390
+
391
+ ---
392
+
393
+ ## MCP Server Tools
394
+
395
+ [`dockerfiles/mcp-server/src/index.ts`](../dockerfiles/mcp-server/src/index.ts) registers tools using
396
+ `@modelcontextprotocol/sdk`. Tool calls are authenticated per-request via the headers each session's
397
+ agent sends (the user's key, which the runtime passes with every turn); all actual HTTP calls are made by
398
+ [`src/api-client.ts`](../dockerfiles/mcp-server/src/api-client.ts).
399
+
400
+ **One tool per domain, dispatching on `op`.** Each of the 34 operations used to be its own MCP
401
+ tool, so all 34 schemas sat in the model's prompt prefix on every turn — measured at 3,847
402
+ tokens/call. Collapsing them to five tools whose descriptions carry only the operation *names*
403
+ brought that to 1,061 tokens/call, and a call with no `op` returns the full parameter schema for
404
+ that domain, so nothing became undiscoverable. Registry:
405
+ [`src/ops.ts`](../dockerfiles/mcp-server/src/ops.ts).
406
+
407
+ | Tool | Operations |
408
+ |----------|-------|
409
+ | `datagrok_functions` | `list`, `get`, `call`, `list_scripts`, `list_queries`, `create_script`, `create_query` |
410
+ | `datagrok_files` | `list`, `download`, `upload` |
411
+ | `datagrok_projects` | `list`, `get`, `create`, `delete`, `search`, `list_recent`, `attach_entity`, `share`, `list_shares` |
412
+ | `datagrok_spaces` | `list`, `get`, `create`, `delete`, `create_subspace`, `list_children`, `add_entity`, `remove_entity`, `read_file`, `write_file`, `delete_file` |
413
+ | `datagrok_platform` | `whoami`, `list_users`, `list_groups`, `list_connections` |
414
+
415
+ Results are compact JSON, arrays are paged (50 by default, `offset`/`limit` to page), and
416
+ everything is capped — a tool result stays in the transcript and is re-read on every later hop, so
417
+ an unpaged list taxes the whole turn ([`src/format.ts`](../dockerfiles/mcp-server/src/format.ts)).
418
+
419
+ **Op names are load-bearing**: the runtime's verify gate decides whether a call mutated anything by
420
+ matching the *op* against read-verb prefixes (`list`/`get`/`search`/`read`/`download`/`find`/`whoami`).
421
+ An op named outside that convention silently changes whether verification is demanded, so
422
+ `mcp-server/test/ops.test.js` asserts every op starts with a known read or write verb.
423
+
424
+ ---
425
+
426
+ ## End-to-End Flow Example
427
+
428
+ Below is the full path for "Add a scatter plot of Height vs Weight":
429
+
430
+ ```
431
+ 1. User types in the AI panel → runPromptWithLifecycle() → UsageLimiter.tryCheckAndIncrement()
432
+ 2. runClaudeStreaming() → client.ensureConnected(); buildWorkspaceContext() prepended
433
+ 3. sendChatTurn() holds the celery admission slot (when deployed), then
434
+ WS → {type:'user_message', sessionId, message, apiKey, mcpServerUrl, clientTools}
435
+
436
+ 4. claude-runtime handleMessage():
437
+ - agent/turn.ts runTurn(): {type:'turn', …} to the session's agent process; the agent's
438
+ llm_request middleware puts DATAGROK_PROMPT on each model request
439
+
440
+ 5. Claude reads JS API source (read_file on workspace/js-api/src/viewer.ts)
441
+ → pre_tool_call (access guard) → agent event tool_start
442
+ → {type:'tool_activity', summary:'Read workspace/js-api/src/viewer.ts'} → browser shows the badge
443
+
444
+ 6. Claude calls datagrok_exec with the viewer code + inline verify assertion
445
+ → agent event browser_call → {type:'input_request', toolName:'datagrok_exec', input:{code, verify}}
446
+ → browser executeSingleBlock() adds the scatter plot to the live view,
447
+ runVerification() re-reads view.viewers, respondToInput({success:true, verified:{passed:true}})
448
+ → browser_result to the agent; post_tool_call → tool_end → the verify gate marks the action proven
449
+
450
+ 7. Claude emits text deltas
451
+ → agent event text → {type:'chunk', content:'Added a scatter plot…'}
452
+ → browser onChunk → accumulated text, panel.updateStreaming()
453
+
454
+ 8. The agent reports stopped, gates pass → {type:'final', content, metrics}
455
+ → browser onFinal → panel.finalizeStreaming() renders the final markdown
456
+ ```
457
+
458
+ ---
459
+
460
+ ## Key Files Reference
461
+
462
+ Runtime paths are relative to [`dockerfiles/claude-runtime/`](../dockerfiles/claude-runtime/).
463
+
464
+ | File | Purpose |
465
+ |------|---------|
466
+ | [`Dockerfile`](../dockerfiles/claude-runtime/Dockerfile) | Hermes stage (pinned), public repo in `/workspace`, `src/` via tsc, the agent package in `/app/agent` |
467
+ | [`entrypoint.sh`](../dockerfiles/claude-runtime/entrypoint.sh) | Execs the server under `env -i` with an allowlist |
468
+ | [`src/privileges.ts`](../dockerfiles/claude-runtime/src/privileges.ts) | The server's first import: drops from root to uid 1001 |
469
+ | [`src/server.ts`](../dockerfiles/claude-runtime/src/server.ts) | Hono server: `/ws` dispatch, `/health`, task claim/release, pool start, shutdown |
470
+ | [`src/session.ts`](../dockerfiles/claude-runtime/src/session.ts) | Per-session queue, file sync, gates, idle watchdog, browser round-trips, event forwarding, abort |
471
+ | [`src/agent/pool.ts`](../dockerfiles/claude-runtime/src/agent/pool.ts) | Agent processes: spawn with `init`, warm spares, LRU and idle eviction, parking and reload, process-tree kills |
472
+ | [`src/credentials.ts`](../dockerfiles/claude-runtime/src/credentials.ts) | The user's provider credentials, bought from Datlas with the connection's container token |
473
+ | [`src/agent/turn.ts`](../dockerfiles/claude-runtime/src/agent/turn.ts) | One turn over the JSON-lines protocol: commands out, events in, gate continuation, cancel |
474
+ | [`src/types.ts`](../dockerfiles/claude-runtime/src/types.ts) | WebSocket protocol, turn request, `AgentCommand` / `AgentProcessEvent`, tool inputs |
475
+ | [`src/prompts.ts`](../dockerfiles/claude-runtime/src/prompts.ts) | System prompts, inlined skills, skills index (`buildSystemPrompt`) |
476
+ | [`src/tool-summary.ts`](../dockerfiles/claude-runtime/src/tool-summary.ts) | Tool-activity summaries |
477
+ | [`src/verify.ts`](../dockerfiles/claude-runtime/src/verify.ts) | Act → verify gate |
478
+ | [`src/grounding.ts`](../dockerfiles/claude-runtime/src/grounding.ts) | Grounding gate for platform how-to claims |
479
+ | [`src/stream-filter.ts`](../dockerfiles/claude-runtime/src/stream-filter.ts) | Fence-aware chunk filtering, hidden revision streaming |
480
+ | [`src/watchdog.ts`](../dockerfiles/claude-runtime/src/watchdog.ts) | Idle race, process-tree kills, orphan reaper |
481
+ | [`src/tasks.ts`](../dockerfiles/claude-runtime/src/tasks.ts) | Celery admission-task claim/release registry |
482
+ | [`src/constants.ts`](../dockerfiles/claude-runtime/src/constants.ts) | Paths (with their test overrides), the credential names handed to agents |
483
+ | [`agent/grokky_agent/__main__.py`](../dockerfiles/claude-runtime/agent/grokky_agent/__main__.py) | Agent entry: non-dumpable, `init`, plugin check, command loop |
484
+ | [`agent/grokky_agent/session.py`](../dockerfiles/claude-runtime/agent/grokky_agent/session.py) | The session on Hermes' `AIAgent`: hooks, limits, cancel, structured output, heartbeat, browser relay |
485
+ | [`agent/grokky_agent/hermes_plugin/`](../dockerfiles/claude-runtime/agent/grokky_agent/hermes_plugin/) | In-process Hermes plugin that registers the session's hooks and middleware |
486
+ | [`agent/grokky_agent/browser_tools.py`](../dockerfiles/claude-runtime/agent/grokky_agent/browser_tools.py) | Browser and view tools as native Hermes tools |
487
+ | [`agent/grokky_agent/guard.py`](../dockerfiles/claude-runtime/agent/grokky_agent/guard.py) | Access guard on tool arguments, relative edit paths |
488
+ | [`agent/grokky_agent/hermes.yaml`](../dockerfiles/claude-runtime/agent/grokky_agent/hermes.yaml), [`config.py`](../dockerfiles/claude-runtime/agent/grokky_agent/config.py) | Hermes' config for every session, written to `HERMES_HOME/config.yaml` with the skills directory and compression threshold |
489
+ | [`agent/grokky_agent/formats.py`](../dockerfiles/claude-runtime/agent/grokky_agent/formats.py) | The wire formats (Anthropic Messages, OpenAI Responses, Chat Completions): system prompt and output schema placement, the refused request |
490
+ | [`agent/grokky_agent/hermes.py`](../dockerfiles/claude-runtime/agent/grokky_agent/hermes.py) | Every Hermes API the driver calls, typed |
491
+ | [`agent/grokky_agent/protocol.py`](../dockerfiles/claude-runtime/agent/grokky_agent/protocol.py) | The JSON-lines protocol (`AgentCommand` / `AgentProcessEvent` in `src/types.ts`) |
492
+ | [`agent/grokky_agent/structured.py`](../dockerfiles/claude-runtime/agent/grokky_agent/structured.py) | Output-schema check (`jsonschema`) |
493
+ | [`agent/grokky_agent/providers/`](../dockerfiles/claude-runtime/agent/grokky_agent/providers/) | One class per provider: credential checks, the formats it serves and where (`routes`), price list, error hints |
494
+ | [`dockerfiles/mcp-server/src/index.ts`](../dockerfiles/mcp-server/src/index.ts) | MCP tool registry |
495
+ | [`dockerfiles/mcp-server/src/api-client.ts`](../dockerfiles/mcp-server/src/api-client.ts) | HTTP client to Datagrok API |
496
+ | [`src/claude/runtime-client.ts`](../src/claude/runtime-client.ts) | Browser WebSocket client, RxJS subjects, `ClaudeRuntimeClient` singleton |
497
+ | [`src/claude/exec-blocks.ts`](../src/claude/exec-blocks.ts) | `executeSingleBlock()`, `runVerification()`, `buildWorkspaceContext()`, entity cards |
498
+ | [`src/claude/queue-task.ts`](../src/claude/queue-task.ts) | Queued-task admission (`aiChatTurnTask` holds the celery slot) |
499
+ | [`src/ai/view-tools.ts`](../src/ai/view-tools.ts) | View-function meta-tools declared as `clientTools` |
500
+ | [`src/ai/ui.ts`](../src/ai/ui.ts) | `runPromptWithLifecycle()`, streaming orchestration, panel setup functions |
501
+ | [`src/ai/panel.ts`](../src/ai/panel.ts) | `AIPanel` — the singleton chat panel (`StreamingPanel` interface) |
502
+
503
+ ---
504
+
505
+ ## Operations
506
+
507
+ How to configure, run, test, debug and roll back the `claude-runtime` container. Paths are relative to
508
+ [`dockerfiles/claude-runtime/`](../dockerfiles/claude-runtime/).
509
+
510
+ ### Agent processes and sessions
511
+
512
+ See the [process model](#process-model).
513
+
514
+ - PID 1 is `tini` (reaps orphaned tool processes); it runs `entrypoint.sh`, which execs the server under
515
+ `env -i` with an allowlist: the variables in [Configure](#configure), the credentials and a few fixed
516
+ paths. The server's first import (`src/privileges.ts`) drops it from root to uid 1001.
517
+ - Each chat session gets one long-lived agent process (`src/agent/pool.ts`): `python -m grokky_agent` run
518
+ with Hermes' venv Python, in a process group of its own, with cwd `/` (root-owned, so a stray relative
519
+ path never lands in runtime state) and its own `HERMES_HOME` at `/var/lib/grokky/hermes/<uuid>`
520
+ (generated `config.yaml`, a link to the plugin, Hermes' session store `state.db`, logs; kept off `/tmp`,
521
+ which an agent may clear). Its environment holds only `PATH`, `HOME`/`HERMES_HOME`, `TERM`, `LANG`,
522
+ `PYTHONUNBUFFERED` and `PYTHONPATH`.
523
+ - Startup: the first stdin line is `init` (the provider credentials and settings). The agent writes its
524
+ config, loads the plugin, and answers `ready`, or `fatal` with the reason (a refused credential, the
525
+ plugin not loading). An agent that is not ready within the ready timeout is disposed and its turn errors
526
+ with "The assistant could not start: …".
527
+ - Warm spares are started ahead with Hermes loaded and an `AIAgent` built for the configured model; a new chat
528
+ takes a ready spare, or takes over one that is still starting rather than starting a second process.
529
+ - An idle session's process is evicted after the idle TTL (checked every minute), or earlier at the process
530
+ cap when a new chat has no spare to take: spares go first, then the least recently used idle session. A busy session is never evicted, so the
531
+ pool can run over the cap. Eviction kills the process tree and, once the process has exited, moves its
532
+ `state.db` (with `-wal`/`-shm`) to `/var/lib/grokky/hermes/parked/<uuid>/`. The next turn starts a fresh
533
+ process on that home, which first deletes everything in it but the session store, and continues the
534
+ stored session. Past the session cap (live plus parked) the oldest parked session is deleted. A session
535
+ whose stored history is gone answers `session_reset`; a reload that fails to start keeps the session
536
+ parked, so the turn errors and the next one retries. A process that dies holding a session (killed, out
537
+ of memory, crashed) keeps its session store where it is, and the next turn reloads it; a reloaded process
538
+ holds the stored session until its agent has opened it, so a turn that fails before that (an unusable
539
+ output schema) or is stopped while the process starts loses nothing either.
540
+ - The browser saves each chat's session id with the conversation: a chat reopened from the history, after a
541
+ page reload too, resumes that session while the runtime still has it, and otherwise gets
542
+ `session_reset` and sends the turn again with the saved transcript.
543
+ - Abort: the server sends `cancel` with the reason; the agent interrupts Hermes and fails its pending browser
544
+ calls with it: "The user stopped this request." on Stop, and on a lost connection a note that the call's
545
+ code may still be running in the tab. Once the turn has settled, the server kills everything under the agent process, since Hermes
546
+ does not stop what a tool started in a session of its own. The next turn continues the conversation,
547
+ which keeps the interrupted request.
548
+ - Disposing a process kills its whole descendant tree (read from `/proc`), then its process group. SIGTERM
549
+ or SIGINT disposes every agent and exits; startup deletes whatever a previous run left under
550
+ `/var/lib/grokky/hermes`, parked sessions included. An orphan reaper (every 30 s) kills any
551
+ `-m grokky_agent` process the pool does not track, with its tree.
552
+ - Hermes compresses the history once the estimated prompt passes the compression threshold, keeping the
553
+ recent messages verbatim; the compression call counts toward the turn's cost.
554
+ - The Hermes config (`agent/grokky_agent/hermes.yaml`) turns Hermes' own additions off — nudges and
555
+ guidance, tool search, connectors, loop guardrails, approvals, title generation, the remote model
556
+ catalog, borrowed logins — because the runtime owns the prompt and the loop's policy. `AIAgent` runs
557
+ without context files (no `AGENTS.md`/`CLAUDE.md` from the workspace), memory or background review.
558
+ `agent.api_max_retries: 4` is the number of attempts per model call.
559
+ - Web tools: with no web backend configured, Hermes' `web_search` and `web_extract` rotate through the
560
+ keyless free tiers of Exa, Parallel, Firecrawl and Keenable (`web.keyless_fallback`, on by default), so
561
+ queries and URLs go to those vendors.
562
+ - The Datagrok MCP server is connected when a turn first carries it. The connect, the MCP handshake and
563
+ the tool listing are bounded by 30 s (Hermes' default is 60 s), so a slow server cannot hold the turn
564
+ past the idle watchdog. A server that could not be reached is dropped, and the next turn connects again:
565
+ while it refuses connections that costs each turn Hermes' three quick retries (about 7 s); one that does
566
+ not answer costs the 30 s, then Hermes waits 30 s (doubling) before it tries again.
567
+
568
+ ### Configure
569
+
570
+ | Env var (server) | Default | Meaning |
571
+ |---|---|---|
572
+ | `HERMES_MAX_PROCESSES` | 12 | live agent processes, spares included; at the cap the least recently used idle session is evicted (logged `agent: evicting session … (LRU, cap 12)`) |
573
+ | `HERMES_IDLE_TTL_MS` | 900000 | an idle session's process is evicted after this (logged `… (idle N min)`); its next turn reloads it |
574
+ | `HERMES_MAX_SESSIONS` | 200 | live plus parked sessions; past it the oldest parked session is deleted (logged `agent: dropped the stored state of session …`) and gets `session_reset` |
575
+ | `HERMES_WARM_SPARES` | 2 | agent processes started ahead of need |
576
+ | `HERMES_READY_TIMEOUT_MS` | 30000 | an agent that has not answered `ready` by then is disposed; its turn errors |
577
+ | `HERMES_COMPRESSION_THRESHOLD_TOKENS` | 160000 | history compression trigger (estimated prompt tokens) |
578
+ | `HERMES_LOG_STDERR` | unset | any value forwards every agent stderr line to the runtime log |
579
+ | `DATAGROK_API_URL` | injected by Datlas | the URL user identity is verified against; without it, the first client-supplied URL is trusted (dev only) |
580
+
581
+ `entrypoint.sh` passes each of these variables through `env -i`, so
582
+ `docker run -e HERMES_LOG_STDERR=1 …` works. The agent homes
583
+ (`/var/lib/grokky/hermes`), skills (`/app/plugin`), agent package (`/app/agent`) and agent Python
584
+ (`/opt/hermes/.venv/bin/python`) are fixed by the image; a server run outside it overrides them with
585
+ `GROKKY_HERMES_HOMES`, `GROKKY_PLUGIN_DIR`, `GROKKY_AGENT_DIR` and `GROKKY_AGENT_PYTHON`
586
+ (`src/constants.ts`). `HERMES_RUNTIME_DIR` is Hermes' own package-manager store, not a runtime setting.
587
+
588
+ Hermes' `config.yaml` is written by each agent at startup from `agent/grokky_agent/hermes.yaml` (with the
589
+ skills directory and the compression threshold); change settings there. Memory: an idle agent holds about 250 MB RSS, so the 12 processes, spares included, fit the 8 GB
590
+ limit in `container.json`.
591
+
592
+ ### Credentials
593
+
594
+ Keys and setup: [README](../README.md#model-credentials). The runtime has no other source of provider credentials.
595
+
596
+ - Every connection the platform proxies carries `X-Datagrok-Container-Token`, a 15-minute token scoped to
597
+ `GET /docker/credentials` ([AUTH_RESOURCES](https://github.com/datagrok-ai/core/blob/master/docs/AUTH_RESOURCES.md#from-a-docker-container)).
598
+ The server trades it for the user's credentials, resolved by their groups, when the WebSocket opens (`src/credentials.ts`).
599
+ - No token, no credentials or a failed lookup fails the connection's turns and closes it; the next prompt
600
+ reconnects with a new token.
601
+ - Only the `PROVIDER_CREDENTIALS` keys (`src/constants.ts`) are kept, and an agent gets them in its `init` line.
602
+ `TEST_UPSTREAM` (test stubs only) replaces the scheme, host and port of every model URL: http(s) to `127.0.0.1`,
603
+ `localhost`, `[::1]` or `host.docker.internal`, or https to the provider's own host; any other value is refused.
604
+ - An agent serves only turns of the credentials it started with. Other credentials on a live session park it and
605
+ reload its history in a new agent.
606
+ - Warm spares use the credentials an agent last started with (none before the first user) and go only to
607
+ sessions with the same credentials.
608
+ - Agent output is redacted of the agent's own key. A provider that refuses the credentials fails the turn with
609
+ "The assistant could not start: …", naming the credential, never its value.
610
+ - Each provider (`agent/grokky_agent/providers/`) declares the formats it serves; with two, a model whose name
611
+ contains `claude` uses Anthropic's Messages format and any other OpenAI's Responses format.
612
+
613
+ Prices come from Hermes' list for the provider (`agent/usage_pricing.py`: Anthropic's and OpenAI's published
614
+ prices, OpenRouter's live ones). Bedrock, Azure, Databricks and custom endpoints have none, nor does a model the
615
+ list lacks (it stops at Claude Sonnet 5 and Opus 5): such a turn reports `costUsd: null` and only its call limit
616
+ bounds it. Hermes finds the context window itself; images go to the model as they are.
617
+
618
+ Provider notes:
619
+
620
+ - Anthropic: a Claude subscription token is refused, for any key bound for `api.anthropic.com`: Anthropic allows
621
+ those only in its own applications
622
+ ([legal and compliance](https://code.claude.com/docs/en/legal-and-compliance#authentication-and-credential-use)).
623
+ - OpenRouter: the account needs purchased credits (a key limit alone ends in 402); Claude turns with an output
624
+ schema ask for hosts that support it (`provider.require_parameters`).
625
+ - Azure: a Foundry resource serves Claude and GPT, an Azure OpenAI one GPT only. A Claude deployment's name must
626
+ contain `claude` and no dot (Hermes picks Claude's thinking by the name); its key goes as `x-api-key`
627
+ (`hermes.send_keys_by_type`). Entra ID is not supported.
628
+ - Bedrock: a long-term key (a short-term one ends with its console session). The agent refuses Hermes' runtime
629
+ install of the AWS SDK (`hermes.refuse_aws_sdk`): it only served a context probe and cost about 35 s.
630
+ - Databricks: `model` a model service such as `system.ai.claude-sonnet-5-5`; with `service`, the workspace's
631
+ own service (an external provider's model) goes in the `Databricks-Model-Provider-Service` header and
632
+ `model` is the provider's model id. A Free Edition workspace reaches Claude only that way.
633
+ - Custom: https only, the key as Bearer. OpenAI's Chat Completions refuses GPT-6 tools with a reasoning effort.
634
+ - Claude's signed thinking is sent back only to hosts that can verify it (Anthropic, Bedrock, Azure); on
635
+ OpenRouter, Databricks and other hosts Claude does not see its earlier reasoning.
636
+
637
+ ### Build and run
638
+
639
+ ```bash
640
+ cd packages/Grokky/dockerfiles/claude-runtime
641
+ docker build -t grokky-claude-runtime:<version> .
642
+ docker run --rm -p 5355:5355 grokky-claude-runtime:<version>
643
+ curl -s localhost:5355/health # {"status":"ok"}
644
+ ```
645
+
646
+ Hermes is pinned by `HERMES_COMMIT` in the Dockerfile's `hermes` stage and built with Hermes' own
647
+ package manager (CPython and uv sha-verified from `pm/lock.json`) with the `anthropic` and `mcp` extras.
648
+ The commit is recorded in the image label `ai.datagrok.hermes.commit` and in `/opt/hermes/COMMIT`. To
649
+ move the pin: change `HERMES_COMMIT`, rebuild, and run the BDD suite (see [Test](#test)) on a stand with
650
+ the new image.
651
+
652
+ ### Security model
653
+
654
+ - The server and every agent run as uid 1001. The image refuses to start as any user but root
655
+ (`entrypoint.sh`), because a server started as uid 1001 could not make itself non-dumpable.
656
+ - The server holds the provider credentials and every connected user's Datagrok key in its memory and
657
+ sockets. It starts as root and drops to uid 1001 (gid 2001, no supplementary groups) before anything
658
+ else runs (`src/privileges.ts`); a process whose uid changed after exec is not dumpable, so the agents'
659
+ tools cannot read the server's `/proc/<pid>/{environ,mem,fd}`. Provider credentials never enter
660
+ its environment (the entrypoint passes none): a child it runs (git, for the workspace sync) is dumpable again
661
+ after its exec, and would inherit them.
662
+ - An agent gets the provider credentials only in its `init` line, never in its environment or a file,
663
+ and keeps the key in memory. Before it imports the rest of the driver or reads stdin, it makes itself
664
+ non-dumpable (`prctl(PR_SET_DUMPABLE, 0)` in `__main__.py`), so other agents cannot read its memory,
665
+ environment or fds. The
666
+ agent's stdin/stdout/stderr are socketpairs (Node `pipe` stdio), which cannot be reopened through
667
+ `/proc/<pid>/fd`.
668
+ - The user's Datagrok key reaches the agent in each `turn` command as the MCP headers (`x-user-api-key`,
669
+ and `Authorization` for the datlas container proxy).
670
+ - Hermes never borrows a Claude Code login (`auth.adopt_external_logins: false`), and logs at `WARNING`:
671
+ `INFO` would write the start of every prompt into `agent.log`, which other agents can read.
672
+ - The access guard (`agent/grokky_agent/guard.py`) refuses tool calls that name another user's
673
+ `/users/<id>`, a `..` segment, an absolute `/workspace` (a user's session works in its own
674
+ `workspace/`), the agent homes (except the session's own `cache/spillover/`, where Hermes leaves a large
675
+ tool result for `read_file`), a `state.db`, a `~` path in a file tool, or `/proc` beyond `/proc/self`
676
+ and a few system files, and it refuses `skill_manage`. It is a pattern check on tool arguments: defence
677
+ in depth, not isolation.
678
+ - Residual risks, all from the shared uid:
679
+ - Agents of different users can read and write each other's files: user directories, live agent homes
680
+ and parked session stores. A reload keeps only `state.db*` from the stored home and the agent writes
681
+ its config fresh, so a planted `config.yaml`, `.env` or login never reaches a reloaded agent; a write
682
+ into a live agent's home, or into a stored `state.db`, is not prevented.
683
+ - The provider key is protected by the non-dumpable flag, not by a uid boundary.
684
+ - An agent is dumpable between its exec and the `prctl` call. It has not read the credentials yet, but a
685
+ same-uid process that attaches with `ptrace` in that window (the container has no Yama restriction)
686
+ stays attached and can read them later.
687
+ - `/workspace`, which every session reads (the help index the grounding gate sends the model to
688
+ included), is writable by every agent.
689
+ - A tool process that detaches into a new session of its own and its parent exits is no longer under the
690
+ agent, so the cleanup after a stopped turn does not reach it; it lives until the container stops.
691
+ - Any agent can signal the server and the other agents (same uid), so a hostile one can end every session
692
+ in the container until it restarts.
693
+
694
+ ### Test
695
+
696
+ ```bash
697
+ npm ci
698
+ npm test # tsc, then the unit tests
699
+ npm run lint
700
+ npm run lint:agent # ruff, then mypy (strict; pyproject.toml), on the agent driver
701
+ ```
702
+
703
+ `lint:agent` needs `python3` 3.11+ with the image's `jsonschema` and `ruamel.yaml`, plus `ruff`, `mypy` and
704
+ `types-jsonschema`. The AI panel's acceptance suite is the BDD feature set in `packages/Grokky/bdd`
705
+ (`GROKKY_BDD_LIVE=1 DATAGROK_SERVER=<alias> npx grok-bdd run --workers 1`), run against a stand with this
706
+ package and its runtime image deployed.
707
+
708
+ ### Debug
709
+
710
+ - Runtime log lines: `agent[<home8>]: dispose (<reason>)`, `agent: evicting session <sid> (LRU|idle …|turn …
711
+ went silent)`, `agent: reloaded session <sid> in N ms`, `agent: dropped the stored state of session …`,
712
+ `agent[…]: exited unexpectedly (<code>); last stderr:`, `agent: warm spare failed to start: <reason>`,
713
+ `agent[…]: a stdout line is not an event` (something printed on the event channel),
714
+ `watchdog[<sid>]: no agent event for 90s — killing turn`, `reaper: SIGKILL orphaned …`,
715
+ `task[<sid>]: no claim for … — failing open`, and per turn `verify[<sid>]: {…}` / `grounding[<sid>]: …`.
716
+ - Agent stderr: the last 40 lines of each process are kept for error messages; `HERMES_LOG_STDERR=1`
717
+ forwards every line as `agent[<home8>] …`. Key-shaped text (`sk-…`) is masked. Hermes' own logs
718
+ (`logs/agent.log`, `logs/errors.log`, `WARNING` and up) are in the agent's home while the process lives;
719
+ the home is deleted when the process ends.
720
+ - Processes in the container (the image has no `ps`):
721
+ `docker exec <c> sh -c 'for p in /proc/[0-9]*; do printf "%s %s\n" ${p#/proc/} "$(tr "\0" " " <$p/cmdline)"; done'`.
722
+ Expect `tini` (pid 1, root), then `node /app/dist/server.js` and one `python -m grokky_agent` per live
723
+ session plus the spares, all as uid 1001. A non-dumpable process's `environ`, `mem` and `fd` need
724
+ `CAP_SYS_PTRACE`, even for root: `docker exec --privileged -u 0`.
725
+ - What the model receives: the middleware sets the mode's prompt and, for `outputSchema` turns, the output
726
+ format where the request's format has them (`formats.py`); the model id and thinking come from `AIAgent`.
727
+ - A model request with `model: grokky-refused` means the middleware could not vouch for it (no turn in
728
+ progress, or the patch failed); the API rejects it and nothing of the conversation went out.
729
+ - Structured output errors: "The output schema cannot be used: …" (before any model call) means the
730
+ schema is not a JSON object or not a valid schema of its draft (draft-07 when it declares none). Anthropic's
731
+ format gets the schema reduced to its strict grammar, OpenAI's as sent; the reply is validated against the original with
732
+ `jsonschema`, and a mismatch is sent back to the model, up to 5 attempts: "… after 5 attempts" means
733
+ every reply failed. The check runs in the session's own process, so a backtracking `pattern` stalls only
734
+ that session, which the idle watchdog ends.
735
+ - Known limitation: Hermes' `search_files` with `target: "files"` matches file names only (a directory in
736
+ the pattern is dropped) and also returns every hidden directory under `path` (`.git`, `.vscode`, …). The
737
+ full-mode prompt tells the model; `none` mode shows it as is.
738
+
739
+ ### Roll back
740
+
741
+ Redeploy the last SDK runtime image (the registry tag live before the migration) by pointing
742
+ `container.json` or the package version back at it and republishing. Roll back the Grokky package with
743
+ it: the SDK runtime reported a missing or rejected key with `auth_required`, which the current browser
744
+ package no longer handles, so an SDK image behind the current package leaves the panel waiting. No data
745
+ migration is involved; neither runtime keeps sessions across a container restart, so a rollback costs one
746
+ `session_reset` per open chat.