@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,87 @@
1
+ """Rules on tool calls: per-user paths, and the user's approval of a destructive MCP op. Every agent runs as the same
2
+ uid, so the path rules are a pattern check over the arguments: defence in depth, not isolation."""
3
+ import json
4
+ import os
5
+ import re
6
+ from typing import Any
7
+
8
+ from .protocol import JsonObject
9
+
10
+ # The /users root, not a `users` segment inside another path.
11
+ USER_DIR = re.compile(r'(?<![\w.-])/users(?![\w.-])(?:/[\w.-]+)?')
12
+ PARENT_DIR = re.compile(r'(?<![\w.])\.\.(?![\w.])')
13
+ WORKSPACE = re.compile(r'/workspace(?![\w.-])')
14
+ PROC = re.compile(r'/proc(?![\w.-])(/(?:self|thread-self|cpuinfo|meminfo|loadavg|uptime|version)(?![\w.-]))?')
15
+ STATE_DB = r'(?<![\w.-])state\.db(?![\w.-])'
16
+ # Hermes' file tools expand a leading `~` to the agent's own home, which is runtime state.
17
+ FILE_TOOLS = {'read_file', 'write_file', 'patch', 'search_files'}
18
+ EDIT_TOOLS = {'write_file', 'patch'}
19
+ # The token of a destructive MCP op's dry run, in its result text whether or not Hermes re-encoded it.
20
+ CONFIRM_TOKEN = re.compile(r'confirmToken\\?"\s*:\s*\\?"(\w+)')
21
+ CONFIRM_TOOL = 'datagrok_confirm'
22
+ NOT_APPROVED = ('The user has not approved this in the current turn. Repeat the call without `confirm` for a new dry '
23
+ 'run, ask with datagrok_confirm, and use the new token only if they approve; without that tool, it '
24
+ 'cannot be done here.')
25
+
26
+
27
+ class Approvals:
28
+ """The MCP server's confirm token is a hash of the op's arguments that never expires, so the model could reuse
29
+ one the user declined. A token is spendable once, and only after the user approved the confirmation card that
30
+ followed the dry run issuing it, in the same turn; a card approves the latest dry run only."""
31
+
32
+ def __init__(self) -> None:
33
+ self.issued: str | None = None
34
+ self.approved: set[str] = set()
35
+
36
+ def check(self, tool: str, args: JsonObject) -> str | None:
37
+ op_args = args.get('args')
38
+ token = op_args.get('confirm') if isinstance(op_args, dict) else None
39
+ if not tool.startswith('mcp__') or not token:
40
+ return None
41
+ if token not in self.approved:
42
+ return NOT_APPROVED
43
+ self.approved.discard(token)
44
+ return None
45
+
46
+ def record(self, tool: str, result: Any) -> None:
47
+ text = result if isinstance(result, str) else json.dumps(result, default=str)
48
+ if tool.startswith('mcp__'):
49
+ self.issued = (CONFIRM_TOKEN.findall(text) or [self.issued])[-1]
50
+ elif tool == CONFIRM_TOOL:
51
+ if self.issued and re.search(r'"confirmed"\s*:\s*true', text):
52
+ self.approved.add(self.issued)
53
+ self.issued = None
54
+
55
+
56
+ def violation(tool: str, args: JsonObject, user_dir: str | None, homes: str, spillover: str | None = None) \
57
+ -> str | None:
58
+ if tool == 'skill_manage':
59
+ return "Editing the assistant's skills is not allowed."
60
+ text = json.dumps(args, ensure_ascii=False)
61
+ foreign = next((m.group(0) for m in USER_DIR.finditer(text) if m.group(0) != user_dir), None)
62
+ if foreign:
63
+ own = f' ({user_dir})' if user_dir else ''
64
+ return f'Access to {foreign} is blocked — you may only access your own directory{own}.'
65
+ if PARENT_DIR.search(text):
66
+ return 'Parent-directory (`..`) path segments are blocked — use paths inside the current directory.'
67
+ # A user's session has no workspace but its own <user dir>/workspace.
68
+ if user_dir and WORKSPACE.search(text.replace(f'{user_dir}/workspace', '')):
69
+ return 'Direct access to /workspace is blocked — use cwd-relative `workspace/...` paths instead.'
70
+ path = args.get('path')
71
+ # Hermes leaves a large tool result in the session's own spillover directory and points the model at it.
72
+ outside_spillover = re.sub(re.escape(spillover) + r'(?![\w.-])', '', text) if spillover else text
73
+ if re.search(re.escape(homes) + r'(?![\w.-])|' + STATE_DB, outside_spillover) or \
74
+ (tool in FILE_TOOLS and isinstance(path, str) and re.match(r'^~(/|$)', path)):
75
+ return "The assistant runtime's own state is off limits."
76
+ if any(not m.group(1) for m in PROC.finditer(text)):
77
+ return 'Access to /proc is blocked except /proc/self.'
78
+ return None
79
+
80
+
81
+ def absolute_edit_path(tool: str, args: JsonObject, cwd: str) -> str | None:
82
+ """The absolute form of a relative write_file/patch path. Hermes resolves it against the session directory
83
+ everywhere except when it prepares the edit for approval, which uses the process cwd and fails."""
84
+ path = args.get('path')
85
+ if tool in EDIT_TOOLS and isinstance(path, str) and path and not os.path.isabs(path):
86
+ return os.path.normpath(os.path.join(cwd, path))
87
+ return None
@@ -0,0 +1,212 @@
1
+ """Every Hermes API the driver uses, typed as the driver uses it. Hermes is imported on first use, so the unit
2
+ tests run without it."""
3
+ from collections.abc import Callable
4
+ from typing import Any, Literal, NotRequired, Protocol, TypedDict
5
+
6
+ from .protocol import JsonObject
7
+
8
+ ToolHandler = Callable[..., str]
9
+ Hook = Callable[..., Any]
10
+
11
+
12
+ class ToolSpec(TypedDict):
13
+ name: str
14
+ description: str
15
+ parameters: JsonObject
16
+
17
+
18
+ class Connection(TypedDict):
19
+ provider: str
20
+ api_mode: str
21
+ base_url: str
22
+ # On the Anthropic Messages API Hermes sends a string key as x-api-key (send_keys_by_type) and a callable's as
23
+ # Bearer, except to api.anthropic.com, which gets a Console key as x-api-key either way.
24
+ api_key: str | Callable[[], str]
25
+
26
+
27
+ class ConversationResult(TypedDict, total=False):
28
+ messages: list[JsonObject]
29
+ final_response: str | None
30
+ failed: bool
31
+ error: str | None
32
+ turn_exit_reason: str | None
33
+
34
+
35
+ class ApiError(TypedDict):
36
+ type: str
37
+ message: str
38
+
39
+
40
+ class Usage(TypedDict, total=False):
41
+ input_tokens: int | None
42
+ output_tokens: int | None
43
+ cache_read_tokens: int | None
44
+ cache_write_tokens: int | None
45
+
46
+
47
+ class Activity(TypedDict, total=False):
48
+ last_activity_at: float | None
49
+ last_activity_description: str
50
+
51
+
52
+ class ToolVerdict(TypedDict):
53
+ action: Literal['block', 'modify']
54
+ message: NotRequired[str]
55
+ args: NotRequired[JsonObject]
56
+
57
+
58
+ class RequestOverride(TypedDict):
59
+ request: JsonObject
60
+ source: str
61
+
62
+
63
+ class Agent(Protocol):
64
+ session_id: str
65
+ max_iterations: int
66
+ reasoning_config: JsonObject
67
+ enabled_toolsets: list[str]
68
+ tools: list[JsonObject]
69
+ valid_tool_names: set[str]
70
+
71
+ def run_conversation(self, user_message: str | list[JsonObject], conversation_history: list[JsonObject],
72
+ task_id: str) -> ConversationResult: ...
73
+
74
+ def interrupt(self, message: str | None = None, *, hard_cancel: bool = False) -> bool: ...
75
+
76
+ def clear_interrupt(self) -> bool: ...
77
+
78
+ def get_activity_summary(self) -> Activity: ...
79
+
80
+
81
+ class SessionStore(Protocol):
82
+ def get_messages_as_conversation(self, session_id: str, *, repair_alternation: bool = False) \
83
+ -> list[JsonObject]: ...
84
+
85
+
86
+ class ToolRegistry(Protocol):
87
+ def register(self, name: str, toolset: str, schema: ToolSpec, handler: ToolHandler) -> None: ...
88
+
89
+ def deregister(self, name: str) -> None: ...
90
+
91
+ def get_entry(self, name: str) -> object | None: ...
92
+
93
+
94
+ class PluginContext(Protocol):
95
+ def register_hook(self, hook_name: str, callback: Hook) -> object: ...
96
+
97
+ def register_middleware(self, kind: str, callback: Hook) -> object: ...
98
+
99
+
100
+ def send_keys_by_type() -> None:
101
+ """Hermes would send a string key as Bearer to the hosts on its list, Azure's among them, which documents keys in
102
+ x-api-key or api-key and Bearer for Entra ID: without the list the key's type decides (Connection), on every
103
+ Anthropic client of the process."""
104
+ import agent.anthropic_adapter as anthropic_adapter
105
+ anthropic_adapter._requires_bearer_auth = lambda base_url: False
106
+
107
+
108
+ def use_bedrock_key(key: str) -> None:
109
+ """Hermes reaches Bedrock's Converse API through boto3, which takes a Bedrock API key only from the process
110
+ environment, where the session's tools could read it from /proc. The clients are built here instead: unsigned,
111
+ with the key added as a Bearer header, so boto3 never walks its credential chain either."""
112
+ import agent.bedrock_adapter as bedrock_adapter
113
+ import boto3
114
+ import botocore
115
+ from botocore.config import Config
116
+
117
+ clients: dict[tuple[str, str], Any] = {}
118
+
119
+ def add_key(request: Any, **_: Any) -> None:
120
+ request.headers['Authorization'] = f'Bearer {key}'
121
+
122
+ def client(service: str, region: str) -> Any:
123
+ if (service, region) not in clients:
124
+ # boto3 stops reading after 60 s, under Kimi's long replies; Hermes retries and spots stale streams.
125
+ c = boto3.client(service, region_name=region, config=Config(
126
+ signature_version=botocore.UNSIGNED, read_timeout=600, retries={'max_attempts': 1}))
127
+ c.meta.events.register(f'before-send.{service}.*', add_key)
128
+ clients[service, region] = c
129
+ return clients[service, region]
130
+
131
+ bedrock_adapter._get_bedrock_runtime_client = lambda region: client('bedrock-runtime', region)
132
+ bedrock_adapter._get_bedrock_control_client = lambda region: client('bedrock', region)
133
+ bedrock_adapter.resolve_bedrock_bearer_token = lambda env=None: key
134
+ # Hermes learns a window by sending ~1.3M tokens to provoke a length error: over 30 s for some models (Kimi,
135
+ # Qwen), and a billed call for any that accepts it. Its table, or 128k, serves instead.
136
+ bedrock_adapter.probe_bedrock_context_length = lambda model_id, region: None
137
+
138
+
139
+ def usage_cost(model: str, usage: Usage, billing: str, base_url: str) -> float | None:
140
+ """USD for one call from Hermes' price list for the provider `billing` names, or None when it has no price."""
141
+ from agent.usage_pricing import CanonicalUsage, estimate_usage_cost
142
+ canonical = CanonicalUsage(input_tokens=usage.get('input_tokens') or 0,
143
+ output_tokens=usage.get('output_tokens') or 0,
144
+ cache_read_tokens=usage.get('cache_read_tokens') or 0,
145
+ cache_write_tokens=usage.get('cache_write_tokens') or 0)
146
+ amount = estimate_usage_cost(model, canonical, provider=billing, base_url=base_url).amount_usd
147
+ return None if amount is None else float(amount)
148
+
149
+
150
+ def new_agent(model: str, connection: Connection, session_id: str, store: SessionStore, toolsets: list[str],
151
+ on_delta: Callable[[str | None], None]) -> Agent:
152
+ from run_agent import AIAgent
153
+ agent: Agent = AIAgent(model=model, **connection, quiet_mode=True, session_id=session_id, session_db=store,
154
+ enabled_toolsets=toolsets, skip_context_files=True, skip_memory=True,
155
+ skip_background_review=True, stream_delta_callback=on_delta)
156
+ return agent
157
+
158
+
159
+ def open_store() -> SessionStore:
160
+ from hermes_constants import get_hermes_home
161
+ from hermes_state_registry import acquire
162
+ store: SessionStore = acquire(get_hermes_home() / 'state.db')
163
+ return store
164
+
165
+
166
+ def tool_registry() -> ToolRegistry:
167
+ from tools.registry import registry
168
+ tools: ToolRegistry = registry
169
+ return tools
170
+
171
+
172
+ def describe_skills(skills: list[tuple[str, str]]) -> None:
173
+ """Puts the index of Grokky's skills into the skill_view tool's own description: models that weigh tool
174
+ definitions over a long system prompt (Qwen) otherwise act without loading the skill the request matches."""
175
+ from tools.skills_tool import SKILL_VIEW_SCHEMA
176
+ SKILL_VIEW_SCHEMA['description'] = (
177
+ 'Load the Datagrok skill whose description matches the request BEFORE acting: it gives the exact API calls '
178
+ 'and conventions for the task. Skills:\n' + '\n'.join(f'- {name}: {desc}' for name, desc in skills))
179
+
180
+
181
+
182
+ def tool_definitions(toolsets: list[str]) -> list[JsonObject]:
183
+ from model_tools import get_tool_definitions
184
+ definitions: list[JsonObject] = get_tool_definitions(enabled_toolsets=toolsets, quiet_mode=True)
185
+ return definitions
186
+
187
+
188
+ def spillover_dir() -> str:
189
+ from tools.tool_result_storage import get_spillover_dir
190
+ return str(get_spillover_dir())
191
+
192
+
193
+ def set_terminal_cwd(task_id: str, cwd: str) -> None:
194
+ from tools.terminal_tool import register_task_env_overrides
195
+ register_task_env_overrides(task_id, {'cwd': cwd})
196
+
197
+
198
+ def connect_mcp(name: str, config: JsonObject) -> list[str]:
199
+ """Every MCP tool Hermes now has: the server's are missing when it could not connect."""
200
+ from tools.mcp_tool_discovery import register_mcp_servers
201
+ names: list[str] = register_mcp_servers({name: config})
202
+ return names
203
+
204
+
205
+ def disconnect_mcp(name: str) -> None:
206
+ from tools.mcp_tool_lifecycle import shutdown_mcp_servers
207
+ shutdown_mcp_servers(names={name})
208
+
209
+
210
+ def load_plugins() -> None:
211
+ from hermes_cli.plugins import discover_plugins
212
+ discover_plugins()
@@ -0,0 +1,45 @@
1
+ # Hermes' config.yaml for every session; config.py adds the skills directory and the compression threshold. Hermes'
2
+ # own additions to the prompt and the loop are off: the runtime owns both.
3
+ agent:
4
+ image_input_mode: native # an image goes to the model as is; one without image input answers with an error
5
+ verify_on_stop: false
6
+ intent_ack_continuation: false
7
+ stall_guards: false
8
+ task_completion_guidance: false
9
+ parallel_tool_call_guidance: false
10
+ environment_probe: false
11
+ bot_mode_protocol: false
12
+ coding_context: "off"
13
+ auto_recovery_cycles: 0
14
+ api_max_retries: 4 # attempts per model call
15
+ tools:
16
+ tool_search:
17
+ enabled: "off"
18
+ connectors:
19
+ enabled: false
20
+ tool_loop_guardrails:
21
+ warnings_enabled: false
22
+ hard_stop_enabled: false
23
+ non_interactive_hard_stop_enabled: false
24
+ plugins:
25
+ enabled: [grokky]
26
+ auto_update_check_hours: 0
27
+ load_timeout_seconds: 0 # loaded inline: a session whose plugin did not load refuses to start
28
+ skills:
29
+ project_discovery: false
30
+ auxiliary:
31
+ title_generation:
32
+ enabled: false
33
+ compression:
34
+ enabled: true
35
+ tail_mode: legacy # keeps the recent messages verbatim
36
+ approvals:
37
+ mode: "off"
38
+ auth:
39
+ adopt_external_logins: false # never a Claude Code login found on the host (~/.claude, the macOS Keychain)
40
+ logging:
41
+ level: WARNING # INFO logs the start of every prompt where the other sessions (same uid) can read it
42
+ model_catalog:
43
+ enabled: false
44
+ openrouter:
45
+ response_cache: false # it would answer a repeated request with the stored reply
@@ -0,0 +1,8 @@
1
+ """Hermes takes hooks only from plugins: this one registers the hooks of the session running in this process."""
2
+ from grokky_agent import session
3
+ from grokky_agent.hermes import PluginContext
4
+
5
+
6
+ def register(ctx: PluginContext) -> None:
7
+ assert session.current is not None, 'the session is created before Hermes loads its plugins'
8
+ session.current.register_hooks(ctx)
@@ -0,0 +1,3 @@
1
+ name: grokky
2
+ version: "1.0.0"
3
+ description: "The Grokky session's tool guard, usage accounting and request patch."
@@ -0,0 +1,174 @@
1
+ """The JSON lines the runtime server and an agent process exchange (`AgentCommand` and `AgentProcessEvent` in
2
+ src/types.ts)."""
3
+ from collections.abc import Callable
4
+ from typing import Any, Literal, NotRequired, TypedDict
5
+
6
+ JsonObject = dict[str, Any]
7
+
8
+
9
+ class Image(TypedDict):
10
+ mediaType: str
11
+ data: str
12
+
13
+
14
+ class ClientTool(TypedDict):
15
+ name: str
16
+ description: str
17
+ inputSchema: NotRequired[JsonObject]
18
+
19
+
20
+ class McpServer(TypedDict):
21
+ url: str
22
+ headers: dict[str, str]
23
+
24
+
25
+ class Limits(TypedDict):
26
+ maxTurns: int
27
+ maxBudgetUsd: float
28
+
29
+
30
+ class Settings(TypedDict):
31
+ homes: str
32
+ skillsDir: str
33
+ compressionThresholdTokens: int
34
+ warm: bool
35
+
36
+
37
+ class InitCommand(TypedDict):
38
+ type: Literal['init']
39
+ credentials: dict[str, str]
40
+ settings: Settings
41
+
42
+
43
+ class TurnCommand(TypedDict):
44
+ type: Literal['turn']
45
+ text: str
46
+ images: NotRequired[list[Image]]
47
+ systemPrompt: str
48
+ effort: NotRequired[str]
49
+ cwd: str
50
+ userDir: NotRequired[str]
51
+ outputSchema: NotRequired[JsonObject]
52
+ clientTools: NotRequired[list[ClientTool]]
53
+ browserTools: bool
54
+ datagrokMcp: NotRequired[McpServer]
55
+ limits: Limits
56
+ restore: NotRequired[str]
57
+
58
+
59
+ class ContinueCommand(TypedDict):
60
+ type: Literal['continue']
61
+ text: str
62
+
63
+
64
+ class CancelCommand(TypedDict):
65
+ type: Literal['cancel']
66
+ reason: NotRequired[str]
67
+
68
+
69
+ class BrowserResultCommand(TypedDict):
70
+ type: Literal['browser_result']
71
+ id: str
72
+ value: NotRequired[Any]
73
+ error: NotRequired[str]
74
+
75
+
76
+ Command = TurnCommand | ContinueCommand | CancelCommand | BrowserResultCommand
77
+
78
+
79
+ class Metrics(TypedDict):
80
+ model: str
81
+ inputTokens: int
82
+ outputTokens: int
83
+ cacheReadTokens: int
84
+ cacheCreationTokens: int
85
+ costUsd: float | None
86
+ numTurns: int
87
+ durationMs: int
88
+ durationApiMs: int
89
+
90
+
91
+ class ReadyEvent(TypedDict):
92
+ type: Literal['ready']
93
+
94
+
95
+ class FatalEvent(TypedDict):
96
+ type: Literal['fatal']
97
+ message: str
98
+
99
+
100
+ class SessionEvent(TypedDict):
101
+ type: Literal['session']
102
+ id: str
103
+
104
+
105
+ class TextEvent(TypedDict):
106
+ type: Literal['text']
107
+ text: str
108
+
109
+
110
+ class ActivityEvent(TypedDict):
111
+ type: Literal['activity']
112
+
113
+
114
+ class ToolStartEvent(TypedDict):
115
+ type: Literal['tool_start']
116
+ name: str
117
+ args: JsonObject
118
+
119
+
120
+ class ToolEndEvent(TypedDict):
121
+ type: Literal['tool_end']
122
+ name: str
123
+ args: JsonObject
124
+ result: str
125
+
126
+
127
+ class BrowserCallEvent(TypedDict):
128
+ type: Literal['browser_call']
129
+ id: str
130
+ name: str
131
+ input: JsonObject
132
+ timeoutMs: int
133
+
134
+
135
+ class BrowserShowEvent(TypedDict):
136
+ type: Literal['browser_show']
137
+ name: str
138
+ input: JsonObject
139
+
140
+
141
+ class UsageEvent(TypedDict):
142
+ type: Literal['usage']
143
+ metrics: Metrics
144
+
145
+
146
+ class StoppedEvent(TypedDict):
147
+ type: Literal['stopped']
148
+ text: str
149
+ structuredOutput: NotRequired[Any]
150
+ metrics: Metrics
151
+
152
+
153
+ class LimitEvent(TypedDict):
154
+ type: Literal['limit']
155
+ kind: Literal['turns', 'budget']
156
+
157
+
158
+ class ErrorEvent(TypedDict):
159
+ type: Literal['error']
160
+ message: str
161
+
162
+
163
+ class CancelledEvent(TypedDict):
164
+ type: Literal['cancelled']
165
+
166
+
167
+ class SessionLostEvent(TypedDict):
168
+ type: Literal['session_lost']
169
+
170
+
171
+ Event = (ReadyEvent | FatalEvent | SessionEvent | TextEvent | ActivityEvent | ToolStartEvent |
172
+ ToolEndEvent | BrowserCallEvent | BrowserShowEvent | UsageEvent | StoppedEvent | LimitEvent | ErrorEvent |
173
+ CancelledEvent | SessionLostEvent)
174
+ Emit = Callable[[Event], None]
@@ -0,0 +1,21 @@
1
+ """The providers the Grokky credentials can name: each module of this package defines one Provider subclass, which
2
+ registers it under its `name`."""
3
+ import importlib
4
+ import pkgutil
5
+
6
+ from .base import Credentials, Provider, ProviderError
7
+
8
+ for _module in pkgutil.iter_modules(__path__):
9
+ importlib.import_module(f'{__name__}.{_module.name}')
10
+
11
+ PROVIDERS: dict[str, type[Provider]] = {p.name: p for p in Provider.__subclasses__()}
12
+
13
+
14
+ def from_credentials(credentials: Credentials) -> Provider:
15
+ name = credentials.get('provider') or 'Anthropic'
16
+ if name not in PROVIDERS:
17
+ raise ProviderError(f'The provider Grokky credential must be one of {", ".join(PROVIDERS)}')
18
+ return PROVIDERS[name](credentials)
19
+
20
+
21
+ __all__ = ['PROVIDERS', 'Provider', 'ProviderError', 'from_credentials']
@@ -0,0 +1,21 @@
1
+ from ..formats import ApiMode
2
+ from .base import Credentials, Provider, Route
3
+
4
+ API = 'https://api.anthropic.com'
5
+
6
+
7
+ class AnthropicProvider(Provider):
8
+ """Claude on the Anthropic Messages API with a Console API key."""
9
+
10
+ name = 'Anthropic'
11
+ key_kind = 'an Anthropic Console API key'
12
+ model_example = 'claude-sonnet-5-5'
13
+ billing = 'anthropic'
14
+
15
+ def routes(self, credentials: Credentials) -> dict[ApiMode, Route]:
16
+ url = self.endpoint(API)
17
+ self.refuse_subscription_token(credentials.get('apiKey') or '', url)
18
+ return {'anthropic_messages': Route(url)}
19
+
20
+ def error_hint(self, status: int | None) -> str:
21
+ return ' (check the apiKey Grokky credential: an Anthropic Console API key)' if status == 401 else ''
@@ -0,0 +1,46 @@
1
+ import re
2
+
3
+ from ..formats import ApiMode
4
+ from .base import CLAUDE, Credentials, Provider, ProviderError, Route
5
+
6
+ # A Microsoft Foundry resource serves Claude and GPT, an Azure OpenAI resource GPT only. Claude speaks the Messages API
7
+ # under /anthropic, GPT the v1 API under /openai/v1, which takes no api-version:
8
+ # https://learn.microsoft.com/en-us/azure/foundry/foundry-models/how-to/use-foundry-models-claude
9
+ # https://learn.microsoft.com/en-us/azure/foundry/openai/api-version-lifecycle
10
+ RESOURCE = re.compile(r'https://[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.(services\.ai|openai)\.azure\.com')
11
+ # Azure answers an unknown deployment with 404.
12
+ HINTS: dict[int | None, str] = {
13
+ 401: ' (check the apiKey Grokky credential: a key of the Azure resource in baseUrl)',
14
+ 404: ' (check that baseUrl is the Azure resource and that model names one of its deployments)'}
15
+
16
+
17
+ class AzureProvider(Provider):
18
+ """Claude on Microsoft Foundry and GPT on Azure OpenAI, called by deployment name with the resource's key."""
19
+
20
+ name = 'Azure'
21
+ key_kind = 'a key of the Azure resource'
22
+ model_example = 'claude-sonnet-5-5 (a deployment name)'
23
+
24
+ def routes(self, credentials: Credentials) -> dict[ApiMode, Route]:
25
+ resource = RESOURCE.fullmatch((credentials.get('baseUrl') or '').strip().rstrip('/').lower())
26
+ if not resource:
27
+ raise ProviderError('The baseUrl Grokky credential must be the Azure resource: '
28
+ 'https://<resource>.services.ai.azure.com, or https://<resource>.openai.azure.com '
29
+ 'for GPT only')
30
+ if CLAUDE.search(self.model):
31
+ if resource[1] == 'openai':
32
+ raise ProviderError('The model Grokky credential names a Claude deployment, which needs a '
33
+ 'Microsoft Foundry resource, https://<resource>.services.ai.azure.com: an Azure '
34
+ 'OpenAI resource serves GPT only')
35
+ # Hermes picks a Claude request's thinking and sampling settings by the model name, and turns the dots
36
+ # of a claude-* name into hyphens.
37
+ if '.' in self.model:
38
+ raise ProviderError('The model Grokky credential names a Claude deployment with a dot in its '
39
+ 'name: name the deployment after its model id, as Azure does by default')
40
+ routes: dict[ApiMode, Route] = {'codex_responses': Route(self.endpoint(resource[0] + '/openai/v1'))}
41
+ if resource[1] == 'services.ai':
42
+ routes['anthropic_messages'] = Route(self.endpoint(resource[0] + '/anthropic'))
43
+ return routes
44
+
45
+ def error_hint(self, status: int | None) -> str:
46
+ return HINTS.get(status, '')