@datagrok/grokky 1.0.4 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/skills/deploy-grokky/SKILL.md +193 -0
- package/.grokignore +2 -0
- package/.turbo/turbo-build.log +24 -0
- package/.vscode/settings.json +16 -0
- package/CHANGELOG.md +151 -8
- package/CLAUDE.md +284 -0
- package/CREDITS.md +173 -0
- package/LICENSE.md +16 -0
- package/README.md +24 -0
- package/bdd/bdd.config.json +1 -0
- package/bdd/bindings/elements.ts +9 -0
- package/bdd/bindings/steps.ts +787 -0
- package/bdd/features/ai-panel/platform-work.feature +63 -0
- package/bdd/features/ai-panel/session.feature +69 -0
- package/bdd/features/ai-panel/table-work.feature +99 -0
- package/bdd/generated/ai-panel/platform-work.test.ts +103 -0
- package/bdd/generated/ai-panel/session.test.ts +100 -0
- package/bdd/generated/ai-panel/table-work.test.ts +150 -0
- package/bdd/package.json +1 -0
- package/bdd/tsconfig.json +13 -0
- package/css/ai.css +637 -49
- package/dist/package-test.js +4 -1707
- package/dist/package-test.js.map +1 -1
- package/dist/package.js +742 -92317
- package/dist/package.js.map +1 -1
- package/dockerfiles/claude-runtime/.dockerignore +1 -0
- package/{.eslintrc.json → dockerfiles/claude-runtime/.eslintrc.json} +7 -16
- package/dockerfiles/claude-runtime/Dockerfile +73 -13
- package/dockerfiles/claude-runtime/agent/grokky_agent/__init__.py +0 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/__main__.py +80 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/browser_tools.py +180 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/config.py +26 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/formats.py +155 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/guard.py +87 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/hermes.py +212 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/hermes.yaml +45 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/hermes_plugin/__init__.py +8 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/hermes_plugin/plugin.yaml +3 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/protocol.py +174 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/__init__.py +21 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/anthropic.py +21 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/azure.py +46 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/base.py +127 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/bedrock.py +46 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/custom.py +40 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/databricks.py +54 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/openai_platform.py +41 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/providers/openrouter.py +46 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/session.py +471 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/skills.py +44 -0
- package/dockerfiles/claude-runtime/agent/grokky_agent/structured.py +40 -0
- package/dockerfiles/claude-runtime/container.json +2 -2
- package/dockerfiles/claude-runtime/entrypoint.sh +20 -0
- package/dockerfiles/claude-runtime/package-lock.json +1721 -306
- package/dockerfiles/claude-runtime/package.json +20 -5
- package/dockerfiles/claude-runtime/plugin/.claude-plugin/plugin.json +5 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-calc-column/SKILL.md +92 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-chem-data/SKILL.md +250 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-chem-toolkit/SKILL.md +395 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-df-and-columns/SKILL.md +454 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-entities/SKILL.md +38 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-exec/SKILL.md +209 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-filtering/SKILL.md +185 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-grid-customization/SKILL.md +270 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-projects/SKILL.md +100 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-selection/SKILL.md +344 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-undo/SKILL.md +78 -0
- package/dockerfiles/claude-runtime/plugin/skills/datagrok-viewers/SKILL.md +303 -0
- package/dockerfiles/claude-runtime/pyproject.toml +18 -0
- package/dockerfiles/claude-runtime/src/agent/pool.ts +411 -0
- package/dockerfiles/claude-runtime/src/agent/turn.ts +153 -0
- package/dockerfiles/claude-runtime/src/constants.ts +20 -0
- package/dockerfiles/claude-runtime/src/credentials.ts +45 -0
- package/dockerfiles/claude-runtime/src/grounding.ts +104 -0
- package/dockerfiles/claude-runtime/src/help-index.ts +118 -0
- package/dockerfiles/claude-runtime/src/privileges.ts +8 -0
- package/dockerfiles/claude-runtime/src/prompts.ts +211 -0
- package/dockerfiles/claude-runtime/src/server.ts +134 -234
- package/dockerfiles/claude-runtime/src/session.ts +328 -0
- package/dockerfiles/claude-runtime/src/shared-api-client.ts +112 -0
- package/dockerfiles/claude-runtime/src/stream-filter.ts +80 -0
- package/dockerfiles/claude-runtime/src/sync/home-files.ts +80 -0
- package/dockerfiles/claude-runtime/src/sync/orchestrator.ts +214 -0
- package/dockerfiles/claude-runtime/src/sync/packages.ts +145 -0
- package/dockerfiles/claude-runtime/src/sync/shared-connections.ts +87 -0
- package/dockerfiles/claude-runtime/src/sync/workspace.ts +68 -0
- package/dockerfiles/claude-runtime/src/tasks.ts +124 -0
- package/dockerfiles/claude-runtime/src/tool-summary.ts +66 -0
- package/dockerfiles/claude-runtime/src/types.ts +142 -23
- package/dockerfiles/claude-runtime/src/user/installed-packages.ts +17 -0
- package/dockerfiles/claude-runtime/src/user/staged-workspace.ts +80 -0
- package/dockerfiles/claude-runtime/src/user/user-dir.ts +108 -0
- package/dockerfiles/claude-runtime/src/verify.ts +136 -0
- package/dockerfiles/claude-runtime/src/watchdog.ts +115 -0
- package/dockerfiles/claude-runtime/test/credentials.test.js +43 -0
- package/dockerfiles/claude-runtime/test/grounding.test.js +191 -0
- package/dockerfiles/claude-runtime/test/help-index.test.js +115 -0
- package/dockerfiles/claude-runtime/test/plugin-skills.test.js +57 -0
- package/dockerfiles/claude-runtime/test/prompts.test.js +62 -0
- package/dockerfiles/claude-runtime/test/reaper.test.js +60 -0
- package/dockerfiles/claude-runtime/test/stream-filter.test.js +132 -0
- package/dockerfiles/claude-runtime/test/tasks.test.js +74 -0
- package/dockerfiles/claude-runtime/test/user-dir.test.js +71 -0
- package/dockerfiles/claude-runtime/test/verify.test.js +187 -0
- package/dockerfiles/claude-runtime/test/watchdog.test.js +43 -0
- package/dockerfiles/mcp-server/.eslintrc.json +39 -0
- package/dockerfiles/mcp-server/Dockerfile +10 -2
- package/dockerfiles/mcp-server/package-lock.json +1743 -98
- package/dockerfiles/mcp-server/package.json +27 -5
- package/dockerfiles/mcp-server/src/api-client.ts +123 -66
- package/dockerfiles/mcp-server/src/format.ts +51 -0
- package/dockerfiles/mcp-server/src/index.ts +44 -113
- package/dockerfiles/mcp-server/src/ops.ts +325 -0
- package/dockerfiles/mcp-server/src/shared-api-client.ts +81 -0
- package/dockerfiles/mcp-server/test/format.test.js +62 -0
- package/dockerfiles/mcp-server/test/ops.test.js +84 -0
- package/dockerfiles/mcp-server/test/shared-api-client.test.js +35 -0
- package/dockerfiles/queue/Dockerfile +2 -0
- package/dockerfiles/queue/container.json +7 -0
- package/docs/AUDIT-2026-08-03.md +1064 -0
- package/docs/BENCHMARK.md +292 -0
- package/docs/CLAUDE_CODE_FLOW.md +746 -0
- package/docs/EXAMPLES.md +82 -0
- package/docs/FEATURES.md +71 -0
- package/docs/IMPLEMENTATION.md +128 -0
- package/docs/LATENCY.md +170 -0
- package/docs/VISION.md +36 -0
- package/files/benchmark/suite.yaml +404 -0
- package/files/scripts/process-cro-results.md +14 -0
- package/files/suggestions.yaml +344 -0
- package/package.json +39 -97
- package/src/ai/ai-window.ts +157 -0
- package/src/ai/benchmark/benchmark.ts +737 -0
- package/src/ai/db-view-functions.ts +56 -0
- package/src/ai/engine.ts +98 -0
- package/src/ai/gemma-engine.ts +81 -0
- package/src/ai/panel.ts +1385 -0
- package/src/ai/prompt-suggestions.ts +209 -0
- package/src/ai/search/combined-search.ts +244 -0
- package/src/{llm-utils → ai/search}/query-matching.ts +46 -167
- package/src/{llm-utils → ai}/storage.ts +0 -1
- package/src/ai/table-tools.ts +145 -0
- package/src/ai/ui.ts +720 -0
- package/src/ai/usage-limiter.ts +105 -0
- package/src/ai/view-tools.ts +352 -0
- package/src/claude/ai-feature.ts +16 -0
- package/src/claude/exec-blocks.ts +176 -0
- package/src/claude/queue-task.ts +84 -0
- package/src/claude/runtime-client.ts +310 -0
- package/src/claude/turn-log.ts +114 -0
- package/src/claude/undoable.ts +105 -0
- package/src/{llm-utils → db}/db-index-tools.ts +24 -32
- package/src/db/sql-tools.ts +336 -0
- package/src/depr/LLM-client.ts +251 -0
- package/src/depr/ai-panel.ts +174 -0
- package/src/depr/chatgpt-assistant.ts +257 -0
- package/src/depr/creds.ts +30 -0
- package/src/depr/deepwikiclient.ts +118 -0
- package/src/depr/indexes/dg-repository-index.ts +266 -0
- package/src/depr/interfaces.ts +170 -0
- package/src/depr/is-help-request.ts +39 -0
- package/src/depr/prompt-engine.ts +52 -0
- package/src/depr/rendering-tools.ts +103 -0
- package/src/depr/script-tools.ts +785 -0
- package/src/depr/tableview-tools.ts +746 -0
- package/src/depr/viewers-ai.ts +67 -0
- package/src/package-api.ts +87 -28
- package/src/package-test.ts +1 -0
- package/src/package.g.ts +98 -48
- package/src/package.ts +211 -157
- package/src/polyfills.ts +12 -0
- package/src/utils.ts +128 -0
- package/tsconfig.json +8 -70
- package/webpack.config.js +3 -49
- package/.eslintignore +0 -2
- package/src/ai-panel.ts +0 -174
- package/src/claude-code/claude-panel.ts +0 -34
- package/src/claude-code/claude-runtime-client.ts +0 -148
- package/src/llm-utils/LLM-client.ts +0 -251
- package/src/llm-utils/combined-search.ts +0 -162
- package/src/llm-utils/creds.ts +0 -30
- package/src/llm-utils/deepwikiclient.ts +0 -118
- package/src/llm-utils/indexes/dg-repository-index.ts +0 -266
- package/src/llm-utils/panel.ts +0 -866
- package/src/llm-utils/script-tools.ts +0 -784
- package/src/llm-utils/sql-tools.ts +0 -840
- package/src/llm-utils/tableview-tools.ts +0 -704
- package/src/llm-utils/ui.ts +0 -315
- package/src/prompt-engine/chatgpt-assistant.ts +0 -257
- package/src/prompt-engine/interfaces.ts +0 -170
- package/src/prompt-engine/prompt-engine.ts +0 -52
- package/src/prompt-engine/rendering-tools.ts +0 -103
- package/src/prompts/is-help-request.ts +0 -26
- package/src/viewers-ai.ts +0 -67
- /package/src/{llm-utils → db}/indexes/biologics-index.ts +0 -0
- /package/src/{llm-utils → db}/indexes/chembl-index.ts +0 -0
- /package/src/{llm-utils → db}/query-meta-utils.ts +0 -0
- /package/src/{llm-utils/depr → depr}/AI-API-providers/openai-chat-completions-provider.ts +0 -0
- /package/src/{llm-utils/depr → depr}/AI-API-providers/openai-responses-provider.ts +0 -0
- /package/src/{llm-utils/depr → depr}/AI-API-providers/types.ts +0 -0
- /package/src/{llm-utils/depr → depr}/depr.ts +0 -0
- /package/src/{llm-utils/depr → depr}/embeddings.ts +0 -0
- /package/src/{llm-utils/depr → depr}/sql-utils.ts +0 -0
|
@@ -0,0 +1,471 @@
|
|
|
1
|
+
"""One Grokky chat on Hermes' AIAgent: the turns Node sends, and the Hermes hooks of this process."""
|
|
2
|
+
import json
|
|
3
|
+
import re
|
|
4
|
+
import threading
|
|
5
|
+
import time
|
|
6
|
+
import uuid
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from typing import Any, Literal
|
|
9
|
+
|
|
10
|
+
from . import browser_tools, formats, guard, hermes, skills, structured
|
|
11
|
+
from .hermes import Usage
|
|
12
|
+
from .protocol import BrowserResultCommand, ContinueCommand, Emit, JsonObject, McpServer, Metrics, TurnCommand
|
|
13
|
+
from .providers import Provider
|
|
14
|
+
|
|
15
|
+
MAX_STRUCTURED_ATTEMPTS = 5
|
|
16
|
+
HEARTBEAT_SECONDS = 30
|
|
17
|
+
# A model call that writes a long tool call without streaming it is busy, not hung, for this long; Hermes' own
|
|
18
|
+
# stale-stream detector waits 180 s.
|
|
19
|
+
MODEL_CALL_BUSY_SECONDS = 240
|
|
20
|
+
# Node answers every browser call within its own timeout; this only frees a thread whose call Node dropped.
|
|
21
|
+
BROWSER_GRACE_SECONDS = 30
|
|
22
|
+
# Hermes stamps its activity clock with this for every stream event (`_count_chunk`, agent/chat_completion_helpers.py).
|
|
23
|
+
STREAM_EVENT = 'receiving stream response'
|
|
24
|
+
# Bounds the connect, the MCP handshake and the tool listing: Node's idle watchdog ends a silent turn after 90 s.
|
|
25
|
+
MCP_CONNECT_TIMEOUT = 30
|
|
26
|
+
MCP_SERVER = 'datagrok'
|
|
27
|
+
# Hermes reports a failed call as "Error code: 400 - {...'message': '<provider text>'}" (a text with an apostrophe in
|
|
28
|
+
# double quotes, JSON in double quotes), or with the HTML page a proxy or gateway answered instead; the user sees the
|
|
29
|
+
# text, or the page's title. The title is trimmed in code: trimming it in the pattern backtracks on an unclosed one.
|
|
30
|
+
PROVIDER_MESSAGE = re.compile(r"""['"]message['"]: (?:'((?:[^'\\]|\\.)*)'|"((?:[^"\\]|\\.)*)")|"""
|
|
31
|
+
r'(?i:<title>([^<]*)</title>)')
|
|
32
|
+
# api_request_error's reason when the provider's safety filter stops an answer; its message is the cut-off answer.
|
|
33
|
+
SAFETY_FILTER = 'content_policy_blocked'
|
|
34
|
+
SAFETY_FILTER_MESSAGE = "The model provider's safety filter stopped this answer. Try rewording the request."
|
|
35
|
+
BASE_TOOLSETS = ['file', 'terminal', 'skills', 'web']
|
|
36
|
+
# The connection test's call: no system prompt, no tools, a reply of a word or two. Hermes may call again after an
|
|
37
|
+
# empty reply, which a limit of one would refuse and report as the provider's error.
|
|
38
|
+
RETRY_STRUCTURED = ('Your reply did not match the required JSON schema: {}. '
|
|
39
|
+
'Reply again with only the corrected JSON object.')
|
|
40
|
+
|
|
41
|
+
current: 'Session | None' = None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass
|
|
45
|
+
class Tokens:
|
|
46
|
+
input: int = 0
|
|
47
|
+
output: int = 0
|
|
48
|
+
cache_read: int = 0
|
|
49
|
+
cache_write: int = 0
|
|
50
|
+
|
|
51
|
+
def add(self, usage: Usage) -> None:
|
|
52
|
+
self.input += usage.get('input_tokens') or 0
|
|
53
|
+
self.output += usage.get('output_tokens') or 0
|
|
54
|
+
self.cache_read += usage.get('cache_read_tokens') or 0
|
|
55
|
+
self.cache_write += usage.get('cache_write_tokens') or 0
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class Turn:
|
|
59
|
+
"""One browser message, with its gate follow-ups and structured-output retries."""
|
|
60
|
+
|
|
61
|
+
def __init__(self, cmd: TurnCommand, model: str) -> None:
|
|
62
|
+
self.model = model
|
|
63
|
+
self.system_prompt = cmd['systemPrompt']
|
|
64
|
+
self.schema = cmd.get('outputSchema')
|
|
65
|
+
self.cwd = cmd['cwd']
|
|
66
|
+
self.user_dir = cmd.get('userDir')
|
|
67
|
+
self.max_calls = cmd['limits']['maxTurns']
|
|
68
|
+
self.max_cost = cmd['limits']['maxBudgetUsd']
|
|
69
|
+
self.started = time.time()
|
|
70
|
+
self.api_calls = 0
|
|
71
|
+
self.api_seconds = 0.0
|
|
72
|
+
# None once a call had no price: then only the call limit bounds the turn.
|
|
73
|
+
self.cost: float | None = 0.0
|
|
74
|
+
self.tokens = Tokens()
|
|
75
|
+
self.limit: Literal['turns', 'budget'] | None = None
|
|
76
|
+
self.api_error: str | None = None
|
|
77
|
+
self.cancelled = False
|
|
78
|
+
self.segment_start = True
|
|
79
|
+
self.in_flight: set[str] = set()
|
|
80
|
+
self.model_call_since: float | None = None
|
|
81
|
+
self.approvals = guard.Approvals()
|
|
82
|
+
self.redirected = False
|
|
83
|
+
|
|
84
|
+
def metrics(self) -> Metrics:
|
|
85
|
+
return {'model': self.model, 'inputTokens': self.tokens.input, 'outputTokens': self.tokens.output,
|
|
86
|
+
'cacheReadTokens': self.tokens.cache_read, 'cacheCreationTokens': self.tokens.cache_write,
|
|
87
|
+
'costUsd': self.cost, 'numTurns': self.api_calls,
|
|
88
|
+
'durationMs': round((time.time() - self.started) * 1000),
|
|
89
|
+
'durationApiMs': round(self.api_seconds * 1000)}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@dataclass
|
|
93
|
+
class BrowserCall:
|
|
94
|
+
answered: threading.Event = field(default_factory=threading.Event)
|
|
95
|
+
value: Any = None
|
|
96
|
+
error: str | None = None
|
|
97
|
+
|
|
98
|
+
def answer(self, value: Any = None, error: str | None = None) -> None:
|
|
99
|
+
self.value, self.error = value, error
|
|
100
|
+
self.answered.set()
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class Heartbeat:
|
|
104
|
+
"""Tells Node a turn is busy, at most every 30 s, while a tool or auxiliary call runs or the model streams; Hermes'
|
|
105
|
+
other stamps on its activity clock are silence and must still trip Node's idle watchdog."""
|
|
106
|
+
|
|
107
|
+
def __init__(self, emit: Emit) -> None:
|
|
108
|
+
self._emit = emit
|
|
109
|
+
self._last_at: float | None = None
|
|
110
|
+
self._busy = False
|
|
111
|
+
self._sent = float('-inf')
|
|
112
|
+
|
|
113
|
+
@staticmethod
|
|
114
|
+
def streamed(last_at: float | None, activity: hermes.Activity) -> bool:
|
|
115
|
+
return activity.get('last_activity_at') != last_at and activity.get('last_activity_description') == STREAM_EVENT
|
|
116
|
+
|
|
117
|
+
def beat(self, now: float, turn: Turn | None, agent: hermes.Agent | None) -> None:
|
|
118
|
+
if turn is None or agent is None:
|
|
119
|
+
self._busy = False
|
|
120
|
+
return
|
|
121
|
+
activity = agent.get_activity_summary()
|
|
122
|
+
calling = turn.model_call_since is not None and now - turn.model_call_since < MODEL_CALL_BUSY_SECONDS
|
|
123
|
+
self._busy = self._busy or bool(turn.in_flight) or calling or self.streamed(self._last_at, activity)
|
|
124
|
+
self._last_at = activity.get('last_activity_at')
|
|
125
|
+
if self._busy and now - self._sent >= HEARTBEAT_SECONDS:
|
|
126
|
+
self._emit({'type': 'activity'})
|
|
127
|
+
self._busy, self._sent = False, now
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class Session:
|
|
131
|
+
def __init__(self, emit: Emit, provider: Provider, homes: str, store: hermes.SessionStore,
|
|
132
|
+
registry: hermes.ToolRegistry, spillover: str) -> None:
|
|
133
|
+
self.emit = emit
|
|
134
|
+
self.provider = provider
|
|
135
|
+
self.homes = homes
|
|
136
|
+
self.store = store
|
|
137
|
+
self.registry = registry
|
|
138
|
+
self.spillover = spillover
|
|
139
|
+
self.key = uuid.uuid4().hex
|
|
140
|
+
self.agent: hermes.Agent | None = None
|
|
141
|
+
self.history: list[JsonObject] = []
|
|
142
|
+
self.hermes_session: str | None = None
|
|
143
|
+
# The turn whose run is in progress (the hooks act for it), and the latest one received, which gate feedback
|
|
144
|
+
# continues and a cancel stops even before it runs.
|
|
145
|
+
self.turn: Turn | None = None
|
|
146
|
+
self.latest: Turn | None = None
|
|
147
|
+
self.view_tools: list[str] = []
|
|
148
|
+
self.view_specs: list[hermes.ToolSpec] = []
|
|
149
|
+
self.browser_tools = True
|
|
150
|
+
self.mcp: McpServer | None = None
|
|
151
|
+
# The stored session this process reloads, until a turn has restored it.
|
|
152
|
+
self.restore: str | None = None
|
|
153
|
+
self.calls: dict[str, BrowserCall] = {}
|
|
154
|
+
self.skills: list[skills.Skill] = []
|
|
155
|
+
self.hooks_registered = False
|
|
156
|
+
browser_tools.register(registry, self.call_browser, self.show_in_browser)
|
|
157
|
+
threading.Thread(target=self._beat_every_second, daemon=True).start()
|
|
158
|
+
|
|
159
|
+
def register_hooks(self, ctx: hermes.PluginContext) -> None:
|
|
160
|
+
hooks: dict[str, hermes.Hook] = {
|
|
161
|
+
'pre_tool_call': self.pre_tool_call, 'post_tool_call': self.post_tool_call,
|
|
162
|
+
'pre_api_request': self.pre_api_request, 'post_api_request': self.post_api_request,
|
|
163
|
+
'api_request_error': self.api_request_error, 'pre_auxiliary_call': self.pre_auxiliary_call,
|
|
164
|
+
'post_auxiliary_call': self.post_auxiliary_call}
|
|
165
|
+
for name, callback in hooks.items():
|
|
166
|
+
ctx.register_hook(name, callback)
|
|
167
|
+
ctx.register_middleware('llm_request', self.llm_request)
|
|
168
|
+
self.hooks_registered = True
|
|
169
|
+
|
|
170
|
+
def pre_tool_call(self, tool_name: str, args: JsonObject | None = None, tool_call_id: str = '',
|
|
171
|
+
**_: Any) -> hermes.ToolVerdict | None:
|
|
172
|
+
t = self.turn
|
|
173
|
+
if t is None or t.cancelled:
|
|
174
|
+
return {'action': 'block', 'message': 'No turn is in progress.'}
|
|
175
|
+
args = args or {}
|
|
176
|
+
self.emit({'type': 'tool_start', 'name': tool_name, 'args': args})
|
|
177
|
+
why = guard.violation(tool_name, args, t.user_dir, self.homes, self.spillover) or \
|
|
178
|
+
t.approvals.check(tool_name, args)
|
|
179
|
+
if why:
|
|
180
|
+
return {'action': 'block', 'message': why}
|
|
181
|
+
if not t.redirected and (why := skills.redirect(tool_name, args, self.skills)):
|
|
182
|
+
t.redirected = True
|
|
183
|
+
return {'action': 'block', 'message': why}
|
|
184
|
+
t.in_flight.add(tool_call_id or tool_name)
|
|
185
|
+
path = guard.absolute_edit_path(tool_name, args, t.cwd)
|
|
186
|
+
return {'action': 'modify', 'args': {'path': path}} if path else None
|
|
187
|
+
|
|
188
|
+
def post_tool_call(self, tool_name: str, args: JsonObject | None = None, result: Any = None,
|
|
189
|
+
status: str | None = None, tool_call_id: str = '', **_: Any) -> None:
|
|
190
|
+
t = self.turn
|
|
191
|
+
if t is None:
|
|
192
|
+
return
|
|
193
|
+
t.in_flight.discard(tool_call_id or tool_name)
|
|
194
|
+
t.segment_start = True
|
|
195
|
+
# Hermes reports a call the guard refused too; it never ran.
|
|
196
|
+
if status != 'blocked':
|
|
197
|
+
t.approvals.record(tool_name, result)
|
|
198
|
+
self.emit({'type': 'tool_end', 'name': tool_name, 'args': args or {},
|
|
199
|
+
'result': result if isinstance(result, str) else json.dumps(result, default=str)})
|
|
200
|
+
|
|
201
|
+
def pre_api_request(self, **_: Any) -> None:
|
|
202
|
+
# Every attempt, retries included: the error of the one before no longer stands.
|
|
203
|
+
if self.turn:
|
|
204
|
+
self.turn.api_error = None
|
|
205
|
+
self.turn.model_call_since = time.time()
|
|
206
|
+
|
|
207
|
+
def post_api_request(self, usage: Usage | None = None, api_duration: float | None = None,
|
|
208
|
+
finish_reason: str | None = None, **_: Any) -> None:
|
|
209
|
+
t = self.turn
|
|
210
|
+
if t is None:
|
|
211
|
+
return
|
|
212
|
+
t.model_call_since = None
|
|
213
|
+
t.api_calls += 1
|
|
214
|
+
self._account(t, usage or {}, api_duration)
|
|
215
|
+
# The reply's tools must not run when no call is left to answer them with.
|
|
216
|
+
if t.api_calls >= t.max_calls and finish_reason in ('tool_calls', 'length'):
|
|
217
|
+
self._stop(t, 'turns')
|
|
218
|
+
|
|
219
|
+
def api_request_error(self, status_code: int | None = None, error: hermes.ApiError | None = None,
|
|
220
|
+
reason: str | None = None, **_: Any) -> None:
|
|
221
|
+
t = self.turn
|
|
222
|
+
if t is None:
|
|
223
|
+
return
|
|
224
|
+
t.model_call_since = None
|
|
225
|
+
if reason == SAFETY_FILTER:
|
|
226
|
+
t.api_error = SAFETY_FILTER_MESSAGE
|
|
227
|
+
return
|
|
228
|
+
raw = (error and error['message']) or reason or 'The model request failed.'
|
|
229
|
+
m = PROVIDER_MESSAGE.search(raw)
|
|
230
|
+
message = (m.group(1) or m.group(2) or m.group(3) or '').strip() if m else ''
|
|
231
|
+
text = f'API Error: {status_code} {message}' if message and status_code else raw
|
|
232
|
+
t.api_error = text + self.provider.error_hint(status_code)
|
|
233
|
+
|
|
234
|
+
def pre_auxiliary_call(self, api_request_id: str = '', **_: Any) -> None:
|
|
235
|
+
if self.turn:
|
|
236
|
+
self.turn.in_flight.add(f'aux:{api_request_id}')
|
|
237
|
+
|
|
238
|
+
def post_auxiliary_call(self, usage: Usage | None = None, api_duration: float | None = None,
|
|
239
|
+
api_request_id: str = '', **_: Any) -> None:
|
|
240
|
+
t = self.turn
|
|
241
|
+
if t is None:
|
|
242
|
+
return
|
|
243
|
+
t.in_flight.discard(f'aux:{api_request_id}')
|
|
244
|
+
self._account(t, usage or {}, api_duration)
|
|
245
|
+
|
|
246
|
+
def llm_request(self, request: JsonObject | None = None, api_mode: str = '', **_: Any) -> hermes.RequestOverride:
|
|
247
|
+
t = self.turn
|
|
248
|
+
if t is None or request is None:
|
|
249
|
+
return {'request': formats.refused(api_mode), 'source': 'grokky'}
|
|
250
|
+
# Hermes also calls the model on its own: after an empty or thinking-only reply, for a summary at its own limit.
|
|
251
|
+
if t.api_calls >= t.max_calls:
|
|
252
|
+
self._stop(t, 'turns')
|
|
253
|
+
return {'request': formats.refused(api_mode), 'source': 'grokky'}
|
|
254
|
+
# Hermes sends its own request when this raises, so a patch that fails sends the refusal.
|
|
255
|
+
try:
|
|
256
|
+
patched = self.provider.patch_request(api_mode, request, t.system_prompt, t.schema)
|
|
257
|
+
except Exception:
|
|
258
|
+
patched = formats.refused(api_mode)
|
|
259
|
+
return {'request': patched, 'source': 'grokky'}
|
|
260
|
+
|
|
261
|
+
def receive(self, cmd: TurnCommand | ContinueCommand) -> Turn:
|
|
262
|
+
"""The turn a `turn` or `continue` command runs, taken when the command arrives."""
|
|
263
|
+
if cmd['type'] == 'turn':
|
|
264
|
+
self.latest = Turn(cmd, self.provider.model)
|
|
265
|
+
assert self.latest is not None, 'a continue follows its turn'
|
|
266
|
+
return self.latest
|
|
267
|
+
|
|
268
|
+
def start_turn(self, cmd: TurnCommand, t: Turn) -> None:
|
|
269
|
+
self.restore = cmd.get('restore') or self.restore
|
|
270
|
+
problem = structured.schema_error(t.schema) if t.schema is not None else None
|
|
271
|
+
if problem:
|
|
272
|
+
self.emit({'type': 'error', 'message': f'The output schema cannot be used: {problem}'})
|
|
273
|
+
return
|
|
274
|
+
agent = self._prepare(cmd)
|
|
275
|
+
if agent is None:
|
|
276
|
+
self.emit({'type': 'session_lost'})
|
|
277
|
+
return
|
|
278
|
+
effort = cmd.get('effort')
|
|
279
|
+
agent.reasoning_config = {'enabled': True, 'effort': effort} if effort else {'enabled': False}
|
|
280
|
+
self._run(agent, t, self._user_content(cmd))
|
|
281
|
+
|
|
282
|
+
def continue_turn(self, cmd: ContinueCommand, t: Turn) -> None:
|
|
283
|
+
assert self.agent is not None, 'a continue follows its turn'
|
|
284
|
+
self._run(self.agent, t, cmd['text'])
|
|
285
|
+
|
|
286
|
+
def cancel(self, reason: str | None = None) -> None:
|
|
287
|
+
t = self.latest
|
|
288
|
+
if t is None or t.cancelled:
|
|
289
|
+
return
|
|
290
|
+
t.cancelled = True
|
|
291
|
+
if self.turn is t and self.agent:
|
|
292
|
+
self.agent.interrupt('cancelled by the user', hard_cancel=True)
|
|
293
|
+
for call in list(self.calls.values()):
|
|
294
|
+
call.answer(error=reason or 'aborted')
|
|
295
|
+
|
|
296
|
+
def browser_answer(self, cmd: BrowserResultCommand) -> None:
|
|
297
|
+
call = self.calls.get(cmd['id'])
|
|
298
|
+
if call:
|
|
299
|
+
call.answer(cmd.get('value'), cmd.get('error'))
|
|
300
|
+
|
|
301
|
+
def call_browser(self, name: str, args: JsonObject, timeout_s: int) -> Any:
|
|
302
|
+
call_id = uuid.uuid4().hex
|
|
303
|
+
call = self.calls[call_id] = BrowserCall()
|
|
304
|
+
self.emit({'type': 'browser_call', 'id': call_id, 'name': name, 'input': args, 'timeoutMs': timeout_s * 1000})
|
|
305
|
+
answered = call.answered.wait(timeout_s + BROWSER_GRACE_SECONDS)
|
|
306
|
+
del self.calls[call_id]
|
|
307
|
+
if not answered:
|
|
308
|
+
raise RuntimeError('The browser did not answer in time.')
|
|
309
|
+
if call.error:
|
|
310
|
+
raise RuntimeError(call.error)
|
|
311
|
+
return call.value
|
|
312
|
+
|
|
313
|
+
def show_in_browser(self, name: str, args: JsonObject) -> None:
|
|
314
|
+
self.emit({'type': 'browser_show', 'name': name, 'input': args})
|
|
315
|
+
|
|
316
|
+
def build_agent(self, hermes_session: str | None = None) -> hermes.Agent:
|
|
317
|
+
self.hermes_session = hermes_session or uuid.uuid4().hex
|
|
318
|
+
self.agent = hermes.new_agent(self.provider.model, self.provider.connection(), self.hermes_session,
|
|
319
|
+
self.store, self._toolsets(), self._on_delta)
|
|
320
|
+
self.emit({'type': 'session', 'id': self.hermes_session})
|
|
321
|
+
return self.agent
|
|
322
|
+
|
|
323
|
+
def _prepare(self, cmd: TurnCommand) -> hermes.Agent | None:
|
|
324
|
+
"""The agent for this turn's stored session, with this turn's tools; None when the stored session to
|
|
325
|
+
continue is gone."""
|
|
326
|
+
if self.restore:
|
|
327
|
+
agent = self.build_agent(self.restore)
|
|
328
|
+
self.history = self.store.get_messages_as_conversation(self.restore, repair_alternation=True)
|
|
329
|
+
if not self.history:
|
|
330
|
+
return None
|
|
331
|
+
self.restore = None
|
|
332
|
+
elif self.agent is None:
|
|
333
|
+
agent = self.build_agent(self.hermes_session)
|
|
334
|
+
else:
|
|
335
|
+
agent = self.agent
|
|
336
|
+
hermes.set_terminal_cwd(self.key, cmd['cwd'])
|
|
337
|
+
changed = self._set_view_tools(browser_tools.view_tool_specs(cmd.get('clientTools')))
|
|
338
|
+
changed = cmd['browserTools'] != self.browser_tools or changed
|
|
339
|
+
self.browser_tools = cmd['browserTools']
|
|
340
|
+
changed = self._set_mcp(cmd.get('datagrokMcp')) or changed
|
|
341
|
+
if changed:
|
|
342
|
+
agent.enabled_toolsets = self._toolsets()
|
|
343
|
+
agent.tools = hermes.tool_definitions(agent.enabled_toolsets)
|
|
344
|
+
agent.valid_tool_names = {t['function']['name'] for t in agent.tools}
|
|
345
|
+
return agent
|
|
346
|
+
|
|
347
|
+
def _toolsets(self) -> list[str]:
|
|
348
|
+
return BASE_TOOLSETS + ([browser_tools.TOOLSET] if self.browser_tools else []) + \
|
|
349
|
+
([browser_tools.VIEW_TOOLSET] if self.view_tools else []) + \
|
|
350
|
+
([f'mcp-{MCP_SERVER}'] if self.mcp else [])
|
|
351
|
+
|
|
352
|
+
def _set_view_tools(self, specs: list[hermes.ToolSpec]) -> bool:
|
|
353
|
+
if specs == self.view_specs:
|
|
354
|
+
return False
|
|
355
|
+
self.view_tools = browser_tools.register_view_tools(self.registry, self.call_browser, specs, self.view_tools)
|
|
356
|
+
self.view_specs = specs
|
|
357
|
+
return True
|
|
358
|
+
|
|
359
|
+
def _set_mcp(self, server: McpServer | None) -> bool:
|
|
360
|
+
"""The Datagrok MCP server, reached with this user's key: Hermes keeps one connection per server name, so a
|
|
361
|
+
changed key or URL replaces the connection."""
|
|
362
|
+
if server == self.mcp:
|
|
363
|
+
return False
|
|
364
|
+
if self.mcp:
|
|
365
|
+
hermes.disconnect_mcp(MCP_SERVER)
|
|
366
|
+
self.mcp = None
|
|
367
|
+
if server:
|
|
368
|
+
names = hermes.connect_mcp(MCP_SERVER, {'url': server['url'], 'headers': server['headers'],
|
|
369
|
+
'connect_timeout': MCP_CONNECT_TIMEOUT})
|
|
370
|
+
if any(n.startswith(f'mcp__{MCP_SERVER}__') for n in names):
|
|
371
|
+
self.mcp = server
|
|
372
|
+
else:
|
|
373
|
+
# Hermes parks a server it could not reach and reconnects it only in the background when asked again,
|
|
374
|
+
# so the next turn would still start without its tools: dropped, it is connected afresh.
|
|
375
|
+
hermes.disconnect_mcp(MCP_SERVER)
|
|
376
|
+
return True
|
|
377
|
+
|
|
378
|
+
def _run(self, agent: hermes.Agent, t: Turn, content: str | list[JsonObject]) -> None:
|
|
379
|
+
# An interrupt that landed after the previous run ended is stale (Hermes clears its own in the finalizer).
|
|
380
|
+
agent.clear_interrupt()
|
|
381
|
+
self.turn = t
|
|
382
|
+
try:
|
|
383
|
+
if t.cancelled:
|
|
384
|
+
self.emit({'type': 'cancelled'})
|
|
385
|
+
else:
|
|
386
|
+
self._prompt(agent, t, content)
|
|
387
|
+
finally:
|
|
388
|
+
self.turn = None
|
|
389
|
+
|
|
390
|
+
def _prompt(self, agent: hermes.Agent, t: Turn, content: str | list[JsonObject]) -> None:
|
|
391
|
+
problem = ''
|
|
392
|
+
for _ in range(MAX_STRUCTURED_ATTEMPTS):
|
|
393
|
+
t.segment_start = True
|
|
394
|
+
# One above what is left, so the request patch, not Hermes' own limit, ends the turn at the limit.
|
|
395
|
+
agent.max_iterations = max(1, t.max_calls - t.api_calls) + 1
|
|
396
|
+
result = agent.run_conversation(user_message=content, conversation_history=self.history, task_id=self.key)
|
|
397
|
+
if isinstance(result.get('messages'), list):
|
|
398
|
+
self.history = result['messages']
|
|
399
|
+
if agent.session_id != self.hermes_session:
|
|
400
|
+
self.hermes_session = agent.session_id
|
|
401
|
+
self.emit({'type': 'session', 'id': agent.session_id})
|
|
402
|
+
if t.cancelled:
|
|
403
|
+
self.emit({'type': 'cancelled'})
|
|
404
|
+
return
|
|
405
|
+
if t.limit or str(result.get('turn_exit_reason') or '').startswith('max_iterations'):
|
|
406
|
+
self.emit({'type': 'limit', 'kind': t.limit or 'turns'})
|
|
407
|
+
return
|
|
408
|
+
if t.api_error or result.get('failed'):
|
|
409
|
+
self.emit({'type': 'error',
|
|
410
|
+
'message': t.api_error or result.get('error') or 'The model request failed.'})
|
|
411
|
+
return
|
|
412
|
+
text = result.get('final_response') or ''
|
|
413
|
+
if t.schema is None:
|
|
414
|
+
if text:
|
|
415
|
+
self.emit({'type': 'stopped', 'text': text, 'metrics': t.metrics()})
|
|
416
|
+
else:
|
|
417
|
+
self.emit({'type': 'error', 'message': 'The assistant stopped without an answer.'})
|
|
418
|
+
return
|
|
419
|
+
value, error = structured.check(t.schema, text)
|
|
420
|
+
if error is None:
|
|
421
|
+
self.emit({'type': 'stopped', 'text': text, 'structuredOutput': value, 'metrics': t.metrics()})
|
|
422
|
+
return
|
|
423
|
+
problem = error
|
|
424
|
+
content = RETRY_STRUCTURED.format(problem)
|
|
425
|
+
self.emit({'type': 'error', 'message': 'The model did not return valid structured output after '
|
|
426
|
+
f'{MAX_STRUCTURED_ATTEMPTS} attempts: {problem}'})
|
|
427
|
+
|
|
428
|
+
def _account(self, t: Turn, usage: Usage, api_duration: float | None) -> None:
|
|
429
|
+
t.tokens.add(usage)
|
|
430
|
+
t.api_seconds += api_duration or 0.0
|
|
431
|
+
cost = self.provider.cost(usage)
|
|
432
|
+
t.cost = None if cost is None or t.cost is None else t.cost + cost
|
|
433
|
+
self.emit({'type': 'usage', 'metrics': t.metrics()})
|
|
434
|
+
if t.cost is not None and t.cost > t.max_cost:
|
|
435
|
+
self._stop(t, 'budget')
|
|
436
|
+
|
|
437
|
+
def _stop(self, t: Turn, limit: Literal['turns', 'budget']) -> None:
|
|
438
|
+
if t.limit is None and self.agent:
|
|
439
|
+
t.limit = limit
|
|
440
|
+
self.agent.interrupt(f'{limit} limit', hard_cancel=True)
|
|
441
|
+
|
|
442
|
+
def _on_delta(self, text: str | None) -> None:
|
|
443
|
+
t = self.turn
|
|
444
|
+
if t is None or not text:
|
|
445
|
+
return
|
|
446
|
+
# Hermes opens the first text after a tool round with a paragraph break for its own display.
|
|
447
|
+
if t.segment_start:
|
|
448
|
+
text = text.lstrip('\n')
|
|
449
|
+
if not text:
|
|
450
|
+
return
|
|
451
|
+
t.segment_start = False
|
|
452
|
+
# A structured reply is checked whole, and a failed call's prose is not the answer.
|
|
453
|
+
if t.schema is not None or t.api_error:
|
|
454
|
+
self.emit({'type': 'activity'})
|
|
455
|
+
else:
|
|
456
|
+
self.emit({'type': 'text', 'text': text})
|
|
457
|
+
|
|
458
|
+
@staticmethod
|
|
459
|
+
def _user_content(cmd: TurnCommand) -> str | list[JsonObject]:
|
|
460
|
+
images = cmd.get('images')
|
|
461
|
+
if not images:
|
|
462
|
+
return cmd['text']
|
|
463
|
+
return [{'type': 'image_url', 'image_url': {'url': f"data:{i['mediaType']};base64,{i['data']}"}}
|
|
464
|
+
for i in images] + [{'type': 'text', 'text': cmd['text']}]
|
|
465
|
+
|
|
466
|
+
def _beat_every_second(self) -> None:
|
|
467
|
+
heartbeat = Heartbeat(self.emit)
|
|
468
|
+
# Hermes stamps its own waits on the clock the stream events use, every 30 s: sampling must be finer.
|
|
469
|
+
while True:
|
|
470
|
+
time.sleep(1)
|
|
471
|
+
heartbeat.beat(time.monotonic(), self.turn, self.agent)
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Grokky's skills as the models see them: the index in skill_view's description, and the one redirect a turn gets
|
|
2
|
+
from reading Datagrok's source to the skill or tool that already covers what it is looking for."""
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
Skill = tuple[str, str]
|
|
8
|
+
|
|
9
|
+
# The platform's source in the workspace; its documentation (workspace/help) stays open.
|
|
10
|
+
SOURCE = re.compile(r'(?<![\w.-])workspace/(?!help(?![\w.-]))')
|
|
11
|
+
SEARCH_TOOLS = {'read_file', 'search_files'}
|
|
12
|
+
WORD = re.compile(r'[A-Z]?[a-z]+|[A-Z]+(?![a-z])')
|
|
13
|
+
STOP = {'the', 'and', 'for', 'src', 'workspace', 'packages', 'api', 'get', 'set', 'with', 'from', 'datagrok'}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def index(skills_dir: str) -> list[Skill]:
|
|
17
|
+
skills = []
|
|
18
|
+
for path in sorted(Path(skills_dir).glob('*/SKILL.md')):
|
|
19
|
+
text = path.read_text()
|
|
20
|
+
head = text.split('---')[1] if text.startswith('---') else ''
|
|
21
|
+
name = re.search(r'^name:\s*(.+)$', head, re.M)
|
|
22
|
+
description = re.search(r'^description:\s*(.+)$', head, re.M)
|
|
23
|
+
if name and description:
|
|
24
|
+
skills.append((name.group(1).strip(), description.group(1).strip()))
|
|
25
|
+
return skills
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _words(text: str) -> set[str]:
|
|
29
|
+
return {w.lower() for w in WORD.findall(text) if len(w) > 2} - STOP
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def redirect(tool: str, args: dict[str, object], skills: list[Skill]) -> str | None:
|
|
33
|
+
"""The message refusing a turn's first look into the platform's source, naming the skills that match it best."""
|
|
34
|
+
text = json.dumps(args, ensure_ascii=False)
|
|
35
|
+
if tool not in SEARCH_TOOLS or not SOURCE.search(text):
|
|
36
|
+
return None
|
|
37
|
+
wanted = _words(text)
|
|
38
|
+
scored = sorted(((len(wanted & _words(f'{name} {desc}')), name) for name, desc in skills), reverse=True)
|
|
39
|
+
names = ', '.join(name for score, name in scored[:3] if score)
|
|
40
|
+
which = f'closest: {names}' if names else "the index is in skill_view's description"
|
|
41
|
+
return (f'Not run: use Datagrok\'s own tooling before its source code. Load the skill that covers this with '
|
|
42
|
+
f'skill_view ({which}); use the mcp__datagrok__* tools for server entities (files, functions, '
|
|
43
|
+
'scripts, queries, projects, spaces, sharing) and list_view_functions for what the current view can do. '
|
|
44
|
+
'If none of them covers it, repeat this call and it will run.')
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Client output schemas. The provider constrains the reply to what its grammar supports; the reply is then checked
|
|
2
|
+
here against the whole schema, in the session's own process, so a pattern that backtracks stalls only this session,
|
|
3
|
+
which the runtime's idle watchdog ends."""
|
|
4
|
+
import json
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from jsonschema import Draft7Validator
|
|
8
|
+
from jsonschema.exceptions import SchemaError
|
|
9
|
+
from jsonschema.protocols import Validator
|
|
10
|
+
from jsonschema.validators import validator_for
|
|
11
|
+
|
|
12
|
+
from .protocol import JsonObject
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _validator_class(schema: JsonObject) -> type[Validator]:
|
|
16
|
+
# Draft-07 when the schema declares no `$schema`: the draft most client schemas are written in.
|
|
17
|
+
validator: type[Validator] = validator_for(schema, default=Draft7Validator)
|
|
18
|
+
return validator
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def schema_error(schema: Any) -> str | None:
|
|
22
|
+
if not isinstance(schema, dict):
|
|
23
|
+
return 'it is not a JSON object'
|
|
24
|
+
try:
|
|
25
|
+
_validator_class(schema).check_schema(schema)
|
|
26
|
+
except SchemaError as e:
|
|
27
|
+
return e.message
|
|
28
|
+
return None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def check(schema: JsonObject, text: str) -> tuple[Any, str | None]:
|
|
32
|
+
"""(value, None) for a valid reply, else (None, what is wrong)."""
|
|
33
|
+
try:
|
|
34
|
+
value = json.loads(text)
|
|
35
|
+
except ValueError:
|
|
36
|
+
return None, 'the reply is not a JSON value'
|
|
37
|
+
errors = sorted(_validator_class(schema)(schema).iter_errors(value), key=lambda e: list(e.path))
|
|
38
|
+
if errors:
|
|
39
|
+
return None, '; '.join(f"{'/'.join(map(str, e.path)) or 'reply'}: {e.message}" for e in errors[:5])
|
|
40
|
+
return value, None
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
#!/bin/sh
|
|
2
|
+
set -e
|
|
3
|
+
|
|
4
|
+
# Started as anyone but root, the server could not drop to uid 1001 itself and would stay dumpable.
|
|
5
|
+
[ "$(id -u)" = 0 ] || { echo "Start the Grokky runtime as root: it drops to uid 1001 itself." >&2; exit 1; }
|
|
6
|
+
|
|
7
|
+
# Only this allowlist of the container's environment reaches the server, so no foreign or stale credential does.
|
|
8
|
+
exec env -i \
|
|
9
|
+
PATH="$PATH" \
|
|
10
|
+
HOME=/home/grok \
|
|
11
|
+
CLAUDE_WORKSPACE="${CLAUDE_WORKSPACE:-/workspace}" \
|
|
12
|
+
DATAGROK_API_URL="${DATAGROK_API_URL:-}" \
|
|
13
|
+
HERMES_MAX_PROCESSES="${HERMES_MAX_PROCESSES:-}" \
|
|
14
|
+
HERMES_IDLE_TTL_MS="${HERMES_IDLE_TTL_MS:-}" \
|
|
15
|
+
HERMES_WARM_SPARES="${HERMES_WARM_SPARES:-}" \
|
|
16
|
+
HERMES_READY_TIMEOUT_MS="${HERMES_READY_TIMEOUT_MS:-}" \
|
|
17
|
+
HERMES_MAX_SESSIONS="${HERMES_MAX_SESSIONS:-}" \
|
|
18
|
+
HERMES_COMPRESSION_THRESHOLD_TOKENS="${HERMES_COMPRESSION_THRESHOLD_TOKENS:-}" \
|
|
19
|
+
HERMES_LOG_STDERR="${HERMES_LOG_STDERR:-}" \
|
|
20
|
+
node /app/dist/server.js
|