@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
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
{
|
|
2
|
+
"root": true,
|
|
2
3
|
"env": {
|
|
3
|
-
"
|
|
4
|
-
"
|
|
4
|
+
"node": true,
|
|
5
|
+
"es2022": true
|
|
5
6
|
},
|
|
6
7
|
"extends": [
|
|
7
8
|
"google"
|
|
@@ -9,35 +10,25 @@
|
|
|
9
10
|
"parser": "@typescript-eslint/parser",
|
|
10
11
|
"parserOptions": {
|
|
11
12
|
"ecmaVersion": 2022,
|
|
12
|
-
"project": "./packages/Grokky/tsconfig.json",
|
|
13
13
|
"sourceType": "module"
|
|
14
14
|
},
|
|
15
15
|
"plugins": [
|
|
16
16
|
"@typescript-eslint"
|
|
17
17
|
],
|
|
18
18
|
"rules": {
|
|
19
|
-
"indent": ["error", 2, {"SwitchCase":
|
|
19
|
+
"indent": ["error", 2, {"SwitchCase": 1}],
|
|
20
20
|
"max-len": ["error", 120],
|
|
21
21
|
"max-params": ["warn", 7],
|
|
22
22
|
"no-throw-literal": "error",
|
|
23
23
|
"no-unused-vars": "off",
|
|
24
|
-
"@typescript-eslint/no-unused-vars": ["warn", {
|
|
24
|
+
"@typescript-eslint/no-unused-vars": ["warn", {"varsIgnorePattern": "^_", "argsIgnorePattern": "^_"}],
|
|
25
25
|
"require-jsdoc": "off",
|
|
26
26
|
"valid-jsdoc": "off",
|
|
27
27
|
"spaced-comment": "off",
|
|
28
28
|
"linebreak-style": "off",
|
|
29
29
|
"quote-props": "off",
|
|
30
|
-
"curly": [
|
|
31
|
-
|
|
32
|
-
"multi-or-nest"
|
|
33
|
-
],
|
|
34
|
-
"brace-style": [
|
|
35
|
-
"error",
|
|
36
|
-
"1tbs",
|
|
37
|
-
{
|
|
38
|
-
"allowSingleLine": true
|
|
39
|
-
}
|
|
40
|
-
],
|
|
30
|
+
"curly": ["error", "multi-or-nest"],
|
|
31
|
+
"brace-style": ["error", "1tbs", {"allowSingleLine": true}],
|
|
41
32
|
"block-spacing": [2, "always"],
|
|
42
33
|
"comma-dangle": "off",
|
|
43
34
|
"comma-spacing": "error",
|
|
@@ -1,27 +1,87 @@
|
|
|
1
|
-
|
|
1
|
+
ARG HERMES_COMMIT=1f6c02c07c697026888f1c66e634534fa2aae358
|
|
2
|
+
ARG NODE_IMAGE=node:22.23.4-trixie-slim@sha256:8eb619e402eaede1748a3c8173bffab391592812e85136452f781741c7242ddf
|
|
2
3
|
|
|
3
|
-
|
|
4
|
-
|
|
4
|
+
# Hermes' own package manager builds the venv, as Hermes' Dockerfile does: CPython and uv come from
|
|
5
|
+
# pm/lock.json (sha256-verified) into HERMES_RUNTIME_DIR, which the venv links to, so the path is kept.
|
|
6
|
+
# uv is needed for the build only: it first lifts the venv's libraries Hermes pins below their CVE fixes.
|
|
7
|
+
# Of the unstripped CPython the lock pins, only libpython is stripped: GNU strip
|
|
8
|
+
# breaks the x86-64 python executable, whose .dynstr lies outside any segment.
|
|
9
|
+
# The sealed venv records Hermes' editable install but not its .pth; hermes_project.pth puts /opt/hermes on
|
|
10
|
+
# the path so the agent imports Hermes from any cwd.
|
|
11
|
+
FROM ${NODE_IMAGE} AS hermes
|
|
12
|
+
ARG HERMES_COMMIT
|
|
13
|
+
ENV HERMES_RUNTIME_DIR=/opt/hermes/tools
|
|
14
|
+
RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates python3 binutils && \
|
|
15
|
+
git clone --filter=blob:none https://github.com/NousResearch/hermes-agent.git /opt/hermes && \
|
|
16
|
+
git -C /opt/hermes checkout "$HERMES_COMMIT" && \
|
|
17
|
+
cd /opt/hermes && \
|
|
18
|
+
python3 -c 'from pm import ensure; ensure("python", explicit=True)' && \
|
|
19
|
+
python3 -m pm.build_env --source /opt/hermes \
|
|
20
|
+
--python "$(python3 -c 'from pm import installed_package; print(installed_package("python").binary)')" \
|
|
21
|
+
--out /opt/hermes/.venv --sealed --extra anthropic --extra mcp --extra bedrock && \
|
|
22
|
+
echo /opt/hermes > "$(/opt/hermes/.venv/bin/python -c 'import site; print(site.getsitepackages()[0])')/hermes_project.pth" && \
|
|
23
|
+
uv="$(find "$HERMES_RUNTIME_DIR" -type f -name uv | head -n 1)" && [ -x "$uv" ] && \
|
|
24
|
+
"$uv" pip install --python /opt/hermes/.venv/bin/python --upgrade \
|
|
25
|
+
"pillow>=13.0.0" "pyjwt>=2.14.0" "certifi>=2026.10.18" "urllib3>=2.8.0" "mcp>=2.2.0" \
|
|
26
|
+
$("$uv" pip list --python /opt/hermes/.venv/bin/python --format freeze | grep -io '^opentelemetry-[a-z-]*') && \
|
|
27
|
+
rm -rf "$HERMES_RUNTIME_DIR"/uv-* \
|
|
28
|
+
"$HERMES_RUNTIME_DIR"/python-*/lib/python3*/ensurepip \
|
|
29
|
+
"$HERMES_RUNTIME_DIR"/python-*/lib/python3*/site-packages/pip \
|
|
30
|
+
"$HERMES_RUNTIME_DIR"/python-*/lib/python3*/site-packages/pip-* && \
|
|
31
|
+
strip --strip-debug "$HERMES_RUNTIME_DIR"/python-*/lib/libpython3.*.so.1.0 && \
|
|
32
|
+
git rev-parse HEAD > COMMIT && \
|
|
33
|
+
rm -rf .git tests website apps web ui-tui optional-skills && \
|
|
34
|
+
/opt/hermes/.venv/bin/python -c "import run_agent, anthropic, mcp, jsonschema, ruamel.yaml, PIL.Image, jwt"
|
|
35
|
+
|
|
36
|
+
FROM ${NODE_IMAGE} AS app
|
|
37
|
+
WORKDIR /app
|
|
38
|
+
COPY package.json package-lock.json* tsconfig.json ./
|
|
39
|
+
COPY src ./src
|
|
40
|
+
RUN npm ci && npx tsc && rm -rf src tsconfig.json && npm prune --omit=dev
|
|
41
|
+
|
|
42
|
+
# Wolfi (glibc) carries no unfixed distro CVEs. The userland is what the agent's terminal and `!cmd` use;
|
|
43
|
+
# node is the official build from the Node image. npm and virtualenv are not shipped: nothing here runs them.
|
|
44
|
+
FROM cgr.dev/chainguard/wolfi-base
|
|
45
|
+
ARG HERMES_COMMIT
|
|
46
|
+
LABEL ai.datagrok.hermes.commit=$HERMES_COMMIT
|
|
47
|
+
|
|
48
|
+
RUN apk upgrade --no-cache && \
|
|
49
|
+
apk add --no-cache bash coreutils findutils grep sed diffutils gzip git ca-certificates-bundle \
|
|
50
|
+
python-3.13 py3.13-pip ripgrep tini libstdc++ libgcc && \
|
|
51
|
+
test -x /usr/bin/tini
|
|
52
|
+
COPY --from=app /usr/local/bin/node /usr/local/bin/node
|
|
5
53
|
|
|
6
54
|
WORKDIR /app
|
|
7
55
|
|
|
8
56
|
ARG HOME_DIR=/home/grok
|
|
9
|
-
RUN
|
|
10
|
-
|
|
11
|
-
git clone --depth 1 https://github.com/datagrok-ai/public.git /workspace && \
|
|
12
|
-
|
|
57
|
+
RUN addgroup -g 2001 grok && \
|
|
58
|
+
adduser -D -h ${HOME_DIR} -G grok -u 1001 -s /bin/bash grok && \
|
|
59
|
+
git clone --depth 1 --filter=blob:none --sparse https://github.com/datagrok-ai/public.git /workspace && \
|
|
60
|
+
git -C /workspace sparse-checkout set --no-cone '/*' '!/docusaurus/' \
|
|
61
|
+
'!*.gif' '!*.png' '!*.PNG' '!*.jpg' '!*.jpeg' '!*.bmp' '!*.mp4' '!*.jar' && \
|
|
62
|
+
git clone --depth 1 --filter=blob:none --sparse https://github.com/datagrok-ai/help.git /workspace/help && \
|
|
63
|
+
git -C /workspace/help sparse-checkout set --no-cone '/*' '!/uploads/' \
|
|
64
|
+
'!*.gif' '!*.png' '!*.PNG' '!*.jpg' '!*.jpeg' '!*.bmp' '!*.mp4' && \
|
|
65
|
+
mkdir -p /users /var/lib/grokky && \
|
|
66
|
+
chown -R grok:grok ${HOME_DIR} /workspace /users /var/lib/grokky
|
|
13
67
|
|
|
14
|
-
COPY --
|
|
15
|
-
COPY --
|
|
16
|
-
RUN npm ci && npx tsc && rm -rf src tsconfig.json && npm prune --production
|
|
68
|
+
COPY --from=app /app /app
|
|
69
|
+
COPY --from=hermes /opt/hermes /opt/hermes
|
|
17
70
|
|
|
18
|
-
|
|
71
|
+
COPY plugin /app/plugin
|
|
72
|
+
COPY agent /app/agent
|
|
73
|
+
COPY entrypoint.sh /app/entrypoint.sh
|
|
74
|
+
RUN sed -i 's/\r$//' /app/entrypoint.sh && chmod 0755 /app/entrypoint.sh && \
|
|
75
|
+
node --version && python3 --version && pip3 --version && rg --version && git --version && \
|
|
76
|
+
PYTHONPATH=/app/agent /opt/hermes/.venv/bin/python -c \
|
|
77
|
+
"import run_agent, anthropic, mcp, jsonschema, ruamel.yaml, PIL.Image, jwt, grokky_agent.session"
|
|
19
78
|
|
|
20
|
-
|
|
79
|
+
ENV CLAUDE_WORKSPACE=/workspace
|
|
21
80
|
|
|
22
81
|
EXPOSE 5355
|
|
23
82
|
|
|
24
83
|
HEALTHCHECK --interval=5s --timeout=3s --start-period=10s --retries=3 \
|
|
25
84
|
CMD node -e "fetch('http://127.0.0.1:5355/health').then(r=>r.ok?process.exit(0):process.exit(1)).catch(()=>process.exit(1))"
|
|
26
85
|
|
|
27
|
-
|
|
86
|
+
# tini is PID 1 so orphaned tool processes (agents start them in sessions of their own) are reaped.
|
|
87
|
+
ENTRYPOINT ["/usr/bin/tini", "--", "/app/entrypoint.sh"]
|
|
File without changes
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""python -m grokky_agent: one chat session. The first stdin line is the init command (credentials and settings, so no
|
|
2
|
+
secret is in this process's environment); every later line is a command, every stdout line an event."""
|
|
3
|
+
import ctypes
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import queue
|
|
7
|
+
import sys
|
|
8
|
+
import threading
|
|
9
|
+
|
|
10
|
+
PR_SET_DUMPABLE = 4
|
|
11
|
+
# Before anything else: the other agents run as the same uid and must not read this process's memory or fds.
|
|
12
|
+
ctypes.CDLL(None).prctl(PR_SET_DUMPABLE, 0, 0, 0, 0)
|
|
13
|
+
|
|
14
|
+
from pathlib import Path # noqa: E402
|
|
15
|
+
|
|
16
|
+
from . import config, hermes, providers, session, skills # noqa: E402
|
|
17
|
+
from .protocol import Command, ContinueCommand, Event, InitCommand, TurnCommand # noqa: E402
|
|
18
|
+
|
|
19
|
+
TurnQueue = queue.Queue[tuple[TurnCommand | ContinueCommand, session.Turn]]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def run_turns(s: session.Session, turns: TurnQueue) -> None:
|
|
23
|
+
while True:
|
|
24
|
+
cmd, turn = turns.get()
|
|
25
|
+
try:
|
|
26
|
+
if cmd['type'] == 'turn':
|
|
27
|
+
s.start_turn(cmd, turn)
|
|
28
|
+
else:
|
|
29
|
+
s.continue_turn(cmd, turn)
|
|
30
|
+
except Exception as e:
|
|
31
|
+
s.emit({'type': 'error', 'message': f'{type(e).__name__}: {e}'})
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def main() -> int:
|
|
35
|
+
out = os.fdopen(os.dup(1), 'w', buffering=1)
|
|
36
|
+
os.dup2(2, 1) # anything Hermes prints goes to stderr; stdout carries only events
|
|
37
|
+
lock = threading.Lock()
|
|
38
|
+
|
|
39
|
+
def emit(event: Event) -> None:
|
|
40
|
+
with lock:
|
|
41
|
+
out.write(json.dumps(event, default=str) + '\n')
|
|
42
|
+
|
|
43
|
+
init: InitCommand = json.loads(sys.stdin.readline())
|
|
44
|
+
try:
|
|
45
|
+
provider = providers.from_credentials(init['credentials'])
|
|
46
|
+
except providers.ProviderError as e:
|
|
47
|
+
emit({'type': 'fatal', 'message': str(e)})
|
|
48
|
+
return 1
|
|
49
|
+
settings = init['settings']
|
|
50
|
+
config.write_home(Path(os.environ['HERMES_HOME']), settings)
|
|
51
|
+
session.current = s = session.Session(emit, provider, settings['homes'], hermes.open_store(),
|
|
52
|
+
hermes.tool_registry(), hermes.spillover_dir())
|
|
53
|
+
hermes.load_plugins()
|
|
54
|
+
if not s.hooks_registered:
|
|
55
|
+
emit({'type': 'fatal', 'message': 'the Grokky plugin did not load'})
|
|
56
|
+
return 1
|
|
57
|
+
hermes.send_keys_by_type()
|
|
58
|
+
s.skills = skills.index(settings['skillsDir'])
|
|
59
|
+
hermes.describe_skills(s.skills)
|
|
60
|
+
if provider.format.mode == 'bedrock_converse':
|
|
61
|
+
hermes.use_bedrock_key(provider.key)
|
|
62
|
+
if settings['warm']:
|
|
63
|
+
s.build_agent()
|
|
64
|
+
emit({'type': 'ready'})
|
|
65
|
+
|
|
66
|
+
# Turns run on one worker: a cancel and the browser's answers must reach a turn while it runs.
|
|
67
|
+
turns: TurnQueue = queue.Queue()
|
|
68
|
+
threading.Thread(target=run_turns, args=(s, turns), daemon=True).start()
|
|
69
|
+
for line in sys.stdin:
|
|
70
|
+
cmd: Command = json.loads(line)
|
|
71
|
+
if cmd['type'] == 'cancel':
|
|
72
|
+
s.cancel(cmd.get('reason'))
|
|
73
|
+
elif cmd['type'] == 'browser_result':
|
|
74
|
+
s.browser_answer(cmd)
|
|
75
|
+
else:
|
|
76
|
+
turns.put((cmd, s.receive(cmd)))
|
|
77
|
+
return 0
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
sys.exit(main())
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""Tools that run in the user's Datagrok tab. Each call goes to Node, which forwards it to the browser and returns its
|
|
2
|
+
answer. They are native Hermes tools, so their results reach the model as they are."""
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from jsonschema import Draft7Validator
|
|
9
|
+
|
|
10
|
+
from .hermes import ToolHandler, ToolRegistry, ToolSpec
|
|
11
|
+
from .protocol import ClientTool, JsonObject
|
|
12
|
+
|
|
13
|
+
TOOLSET = 'grokky-browser'
|
|
14
|
+
VIEW_TOOLSET = 'grokky-view'
|
|
15
|
+
|
|
16
|
+
# Seconds. An unanswered question must not hold the turn (and the workspace sync behind it) open.
|
|
17
|
+
EXEC_TIMEOUT, VERIFY_TIMEOUT, ENTITIES_TIMEOUT, VIEW_TIMEOUT = 300, 60, 30, 120
|
|
18
|
+
|
|
19
|
+
ENTITY_TYPES = {'dataquery': 'query', 'dataconnection': 'connection', 'usergroup': 'group', 'fileinfo': 'file'}
|
|
20
|
+
|
|
21
|
+
CallBrowser = Callable[[str, JsonObject, int], Any]
|
|
22
|
+
ShowInBrowser = Callable[[str, JsonObject], None]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _string(description: str) -> JsonObject:
|
|
26
|
+
return {'type': 'string', 'description': description}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
EXEC: ToolSpec = {
|
|
30
|
+
'name': 'datagrok_exec',
|
|
31
|
+
'description': (
|
|
32
|
+
'Run JavaScript in the Datagrok tab to perform an action (add viewer, filter, open file, upload data, …). '
|
|
33
|
+
'Returns {success, returnValue?, verified?, error?}. ALWAYS provide `verify` with state-changing code — it '
|
|
34
|
+
'runs right after your code in the same round-trip and its {passed, observed} comes back as `verified`, so '
|
|
35
|
+
'no separate datagrok_verify call is needed when it passes. For informational questions ("how do I…", '
|
|
36
|
+
'"what is…") answer in plain text — do NOT call this tool.'),
|
|
37
|
+
'parameters': {'type': 'object', 'required': ['code'], 'properties': {
|
|
38
|
+
'code': _string('Async JS (await works). Globals: grok, ui, DG, view, t. Return a plain object confirming the '
|
|
39
|
+
'action (shape per the datagrok-exec skill), or an HTMLElement only to render output in chat.'),
|
|
40
|
+
'verify': {'type': 'object', 'required': ['assertion', 'description'],
|
|
41
|
+
'description': 'Required for any state-changing code; omit only when the code is a pure '
|
|
42
|
+
'read/render.',
|
|
43
|
+
'properties': {
|
|
44
|
+
'assertion': _string(
|
|
45
|
+
'Async JS that re-reads the state your code changed and MUST `return` the values it '
|
|
46
|
+
'read (truthy = verified; a bare `true` is rejected). Runs in a fresh scope (globals grok, '
|
|
47
|
+
"ui, DG, view, t) — it cannot see your code's variables, so re-derive everything from live "
|
|
48
|
+
'state.'),
|
|
49
|
+
'description': _string('Short human-readable statement of what is being verified.')}}}},
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
VERIFY: ToolSpec = {
|
|
53
|
+
'name': 'datagrok_verify',
|
|
54
|
+
'description': (
|
|
55
|
+
'Confirm a previous datagrok_exec / MCP action actually took effect, by re-reading LIVE state. Runs in a fresh '
|
|
56
|
+
'scope (globals: grok, ui, DG, view, t) — it CANNOT see variables from your action code, so it must re-derive '
|
|
57
|
+
'from t/view/grok. Returns {passed, observed?, error?}. After any action you MUST call this before reporting '
|
|
58
|
+
'success; passed:false means it did NOT work — fix it, do not report done.'),
|
|
59
|
+
'parameters': {'type': 'object', 'required': ['assertion', 'description'], 'properties': {
|
|
60
|
+
'assertion': _string('Async JS (await works) that MUST `return` the values it read; truthy = verified. '
|
|
61
|
+
'Re-read whatever you changed from t/view/grok. A bare `true` or any literal is '
|
|
62
|
+
'rejected.'),
|
|
63
|
+
'description': _string('Short human-readable statement of what is being verified.')}},
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
SHOW_ENTITIES: ToolSpec = {
|
|
67
|
+
'name': 'datagrok_show_entities',
|
|
68
|
+
'description': (
|
|
69
|
+
'Display Datagrok entities (files, scripts, queries, connections, projects, spaces, groups, users) as '
|
|
70
|
+
'interactive cards in the chat. ALWAYS call this tool when you have entity data from an MCP result — never '
|
|
71
|
+
'list entities as plain text, markdown links, or a fenced block.'),
|
|
72
|
+
'parameters': {'type': 'object', 'required': ['entities'], 'properties': {'entities': {
|
|
73
|
+
'type': 'array',
|
|
74
|
+
'description': (
|
|
75
|
+
'Array of entity refs. Each entry: type (file|script|query|connection|project|space|group|user) or the raw '
|
|
76
|
+
'#type string from the MCP result — the tool normalizes it; name (for users, use friendlyName); id '
|
|
77
|
+
'(required for all types except file); connector + path (required for files; connector is the connection '
|
|
78
|
+
'name, e.g. "System:DemoFiles"); isDirectory (optional, files only). Pass all values from the MCP result '
|
|
79
|
+
'exactly — never invent.'),
|
|
80
|
+
'items': {'type': 'object', 'required': ['name'], 'properties': {
|
|
81
|
+
'#type': {'type': 'string'}, 'type': {'type': 'string'}, 'name': {'type': 'string'},
|
|
82
|
+
'id': {'type': 'string'}, 'connector': {'type': 'string'}, 'path': {'type': 'string'},
|
|
83
|
+
'isDirectory': {'type': 'boolean'}}}}}},
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
ASK_USER: ToolSpec = {
|
|
87
|
+
'name': 'AskUserQuestion',
|
|
88
|
+
'description': ('Ask the user a multiple-choice question when the intent of their request is genuinely unclear. '
|
|
89
|
+
'End your turn after asking: the answer, if any, comes as the next message.'),
|
|
90
|
+
'parameters': {'type': 'object', 'required': ['questions'], 'properties': {'questions': {
|
|
91
|
+
'type': 'array', 'description': '1-4 questions to ask.',
|
|
92
|
+
'items': {'type': 'object', 'required': ['question', 'options'], 'properties': {
|
|
93
|
+
'question': _string('The complete question to ask the user.'),
|
|
94
|
+
'header': _string('A very short label for the question (at most 12 characters).'),
|
|
95
|
+
'options': {'type': 'array', 'description': '2-4 distinct choices.', 'items': {
|
|
96
|
+
'type': 'object', 'required': ['label'], 'properties': {
|
|
97
|
+
'label': _string('The choice as shown to the user (1-5 words).'),
|
|
98
|
+
'description': _string('What this choice means.')}}},
|
|
99
|
+
'multiSelect': {'type': 'boolean', 'description': 'Allow the user to pick more than one option.'}}}}}},
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
# What the model API accepts as a tool name.
|
|
103
|
+
TOOL_NAME = re.compile(r'[A-Za-z0-9_-]{1,64}')
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _entity(e: JsonObject) -> JsonObject:
|
|
107
|
+
raw = str(e.get('#type') or e.get('type') or '').lower()
|
|
108
|
+
out: JsonObject = {'type': ENTITY_TYPES.get(raw, raw), 'name': e.get('name')}
|
|
109
|
+
out.update({k: e[k] for k in ('id', 'connector', 'path') if e.get(k)})
|
|
110
|
+
if 'isDirectory' in e:
|
|
111
|
+
out['isDirectory'] = e['isDirectory']
|
|
112
|
+
return out
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _entities(args: JsonObject) -> JsonObject:
|
|
116
|
+
return {'entities': [_entity(e) for e in args.get('entities') or []]}
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _invalid(spec: ToolSpec, args: JsonObject) -> str | None:
|
|
120
|
+
errors = list(Draft7Validator(spec['parameters']).iter_errors(args))
|
|
121
|
+
return f"Input validation error: Invalid arguments for tool {spec['name']}: {errors[0].message}" if errors else None
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _relay(spec: ToolSpec, call: CallBrowser, timeout: int, failure_key: str,
|
|
125
|
+
prepare: Callable[[JsonObject], JsonObject] = lambda args: args) -> ToolHandler:
|
|
126
|
+
def handler(args: JsonObject, **_: Any) -> str:
|
|
127
|
+
try:
|
|
128
|
+
invalid = _invalid(spec, args)
|
|
129
|
+
if invalid:
|
|
130
|
+
return json.dumps({failure_key: False, 'error': invalid})
|
|
131
|
+
return json.dumps(call(spec['name'], prepare(args), timeout))
|
|
132
|
+
except Exception as e:
|
|
133
|
+
return json.dumps({failure_key: False, 'error': str(e)})
|
|
134
|
+
return handler
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _ask_user(show: ShowInBrowser) -> ToolHandler:
|
|
138
|
+
def handler(args: JsonObject, **_: Any) -> str:
|
|
139
|
+
invalid = _invalid(ASK_USER, args)
|
|
140
|
+
if invalid:
|
|
141
|
+
return invalid
|
|
142
|
+
show(ASK_USER['name'], args)
|
|
143
|
+
return 'The question is shown. End your turn now; the answer, if any, comes as the next message.'
|
|
144
|
+
return handler
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def register(registry: ToolRegistry, call: CallBrowser, show: ShowInBrowser) -> None:
|
|
148
|
+
"""The browser tools every session has."""
|
|
149
|
+
tools = [(EXEC, _relay(EXEC, call, EXEC_TIMEOUT, 'success')),
|
|
150
|
+
(VERIFY, _relay(VERIFY, call, VERIFY_TIMEOUT, 'passed')),
|
|
151
|
+
(SHOW_ENTITIES, _relay(SHOW_ENTITIES, call, ENTITIES_TIMEOUT, 'success', _entities)),
|
|
152
|
+
(ASK_USER, _ask_user(show))]
|
|
153
|
+
for spec, handler in tools:
|
|
154
|
+
registry.register(name=spec['name'], toolset=TOOLSET, schema=spec, handler=handler)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def view_tool_specs(client_tools: list[ClientTool] | None) -> list[ToolSpec]:
|
|
158
|
+
"""The browser's view tools that can be offered: well-named and described."""
|
|
159
|
+
specs: list[ToolSpec] = []
|
|
160
|
+
for t in client_tools or []:
|
|
161
|
+
name = t.get('name') if isinstance(t, dict) else None
|
|
162
|
+
if isinstance(name, str) and TOOL_NAME.fullmatch(name) and t.get('description'):
|
|
163
|
+
specs.append({'name': name, 'description': t['description'],
|
|
164
|
+
'parameters': {'type': 'object', 'properties': {}, **(t.get('inputSchema') or {})}})
|
|
165
|
+
return specs
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def register_view_tools(registry: ToolRegistry, call: CallBrowser, specs: list[ToolSpec], previous: list[str]) \
|
|
169
|
+
-> list[str]:
|
|
170
|
+
"""Replaces the previous turn's view tools with these; returns the names it registered. A name another tool has
|
|
171
|
+
is skipped: Hermes refuses it, and deregistering it next turn would remove that tool."""
|
|
172
|
+
for name in previous:
|
|
173
|
+
registry.deregister(name)
|
|
174
|
+
registered = []
|
|
175
|
+
for spec in specs:
|
|
176
|
+
if registry.get_entry(spec['name']) is None:
|
|
177
|
+
registry.register(name=spec['name'], toolset=VIEW_TOOLSET, schema=spec,
|
|
178
|
+
handler=_relay(spec, call, VIEW_TIMEOUT, 'success'))
|
|
179
|
+
registered.append(spec['name'])
|
|
180
|
+
return registered
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from ruamel.yaml import YAML
|
|
6
|
+
|
|
7
|
+
from .protocol import Settings
|
|
8
|
+
|
|
9
|
+
HERE = Path(__file__).parent
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def load_yaml(name: str) -> Any:
|
|
13
|
+
return YAML(typ='safe').load(HERE / name)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def write_home(home: Path, settings: Settings) -> None:
|
|
17
|
+
config = load_yaml('hermes.yaml')
|
|
18
|
+
config['skills']['external_dirs'] = [settings['skillsDir']]
|
|
19
|
+
config['compression']['threshold_tokens'] = settings['compressionThresholdTokens']
|
|
20
|
+
# As JSON, which is YAML, a string such as "off" reaches Hermes as a string whatever YAML version it reads.
|
|
21
|
+
(home / 'config.yaml').write_text(json.dumps(config))
|
|
22
|
+
plugins = home / 'plugins'
|
|
23
|
+
plugins.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
24
|
+
link = plugins / 'grokky'
|
|
25
|
+
link.unlink(missing_ok=True)
|
|
26
|
+
link.symlink_to(HERE / 'hermes_plugin')
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""The wire formats a model is called in, one class each, named by the api_mode Hermes uses for them: where a turn's
|
|
2
|
+
system prompt and output schema go on a request, and the request sent instead of one the session cannot vouch for."""
|
|
3
|
+
import copy
|
|
4
|
+
from abc import ABC, abstractmethod
|
|
5
|
+
from typing import Any, ClassVar, Literal
|
|
6
|
+
|
|
7
|
+
from .protocol import JsonObject
|
|
8
|
+
|
|
9
|
+
ApiMode = Literal['anthropic_messages', 'codex_responses', 'chat_completions', 'bedrock_converse']
|
|
10
|
+
SCHEMA_NAME = 'output'
|
|
11
|
+
# Hermes sends no Responses call without instructions, and puts its own identity into empty ones.
|
|
12
|
+
NO_INSTRUCTIONS = 'You are a helpful assistant.'
|
|
13
|
+
|
|
14
|
+
# Keywords the strict structured-output grammar rejects; minLength and maxLength pass.
|
|
15
|
+
UNSUPPORTED = {
|
|
16
|
+
'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf',
|
|
17
|
+
'maxItems', 'uniqueItems', 'contains', 'minContains', 'maxContains',
|
|
18
|
+
'minProperties', 'maxProperties', 'patternProperties', 'propertyNames', 'dependentRequired',
|
|
19
|
+
'dependentSchemas', 'unevaluatedProperties', 'unevaluatedItems', 'not', 'if', 'then', 'else',
|
|
20
|
+
}
|
|
21
|
+
STRING_FORMATS = {'date-time', 'time', 'date', 'duration', 'email', 'hostname', 'uri', 'ipv4', 'ipv6', 'uuid'}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def strict_schema(schema: Any) -> Any:
|
|
25
|
+
"""The schema in the strict grammar's subset: objects closed, `oneOf` as `anyOf`, unsupported keywords and
|
|
26
|
+
formats dropped, `minItems` only 0 or 1. The reply is still checked against the original."""
|
|
27
|
+
if isinstance(schema, list):
|
|
28
|
+
return [strict_schema(s) for s in schema]
|
|
29
|
+
if not isinstance(schema, dict):
|
|
30
|
+
return schema
|
|
31
|
+
out: JsonObject = {}
|
|
32
|
+
for k, v in schema.items():
|
|
33
|
+
if k in UNSUPPORTED or k == 'additionalProperties' or (k == 'format' and v not in STRING_FORMATS) or \
|
|
34
|
+
(k == 'minItems' and isinstance(v, int) and v > 1):
|
|
35
|
+
continue
|
|
36
|
+
if k in ('properties', '$defs', 'definitions') and isinstance(v, dict):
|
|
37
|
+
out[k] = {name: strict_schema(s) for name, s in v.items()}
|
|
38
|
+
elif k in ('anyOf', 'allOf', 'prefixItems', 'items', 'oneOf'):
|
|
39
|
+
out['anyOf' if k == 'oneOf' else k] = strict_schema(v)
|
|
40
|
+
else:
|
|
41
|
+
out[k] = v
|
|
42
|
+
t = out.get('type')
|
|
43
|
+
if t == 'object' or (isinstance(t, list) and 'object' in t) or (t is None and 'properties' in out):
|
|
44
|
+
out['additionalProperties'] = False
|
|
45
|
+
return out
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _openai_schema(output_schema: JsonObject) -> JsonObject:
|
|
49
|
+
# Not strict: OpenAI's strict mode needs every property required; the reply is validated and retried instead.
|
|
50
|
+
return {'name': SCHEMA_NAME, 'schema': output_schema, 'strict': False}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class ApiFormat(ABC):
|
|
54
|
+
mode: ClassVar[ApiMode]
|
|
55
|
+
# The value of the apiFormat Grokky credential that picks this format for a custom endpoint.
|
|
56
|
+
credential: ClassVar[str]
|
|
57
|
+
refusal: ClassVar[JsonObject]
|
|
58
|
+
|
|
59
|
+
@abstractmethod
|
|
60
|
+
def patch(self, request: JsonObject, system_prompt: str, output_schema: JsonObject | None) -> JsonObject:
|
|
61
|
+
"""The outgoing request with the turn's system prompt, if any, and output format."""
|
|
62
|
+
|
|
63
|
+
def refused(self) -> JsonObject:
|
|
64
|
+
"""Sent instead of a request the session cannot vouch for: the API rejects it, and nothing of the
|
|
65
|
+
conversation leaves the process."""
|
|
66
|
+
return copy.deepcopy(self.refusal)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
_REFUSED_MESSAGES: JsonObject = {'model': 'grokky-refused', 'max_tokens': 1,
|
|
70
|
+
'messages': [{'role': 'user', 'content': 'refused'}]}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class AnthropicMessages(ApiFormat):
|
|
74
|
+
mode = 'anthropic_messages'
|
|
75
|
+
credential = 'anthropic-messages'
|
|
76
|
+
refusal: ClassVar[JsonObject] = _REFUSED_MESSAGES
|
|
77
|
+
|
|
78
|
+
def patch(self, request: JsonObject, system_prompt: str, output_schema: JsonObject | None) -> JsonObject:
|
|
79
|
+
out = dict(request)
|
|
80
|
+
if system_prompt:
|
|
81
|
+
out['system'] = [{'type': 'text', 'text': system_prompt, 'cache_control': {'type': 'ephemeral'}}]
|
|
82
|
+
else:
|
|
83
|
+
out.pop('system', None)
|
|
84
|
+
if output_schema is not None:
|
|
85
|
+
out['output_config'] = {**(out.get('output_config') or {}),
|
|
86
|
+
'format': {'type': 'json_schema', 'schema': strict_schema(output_schema)}}
|
|
87
|
+
return out
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class OpenAIResponses(ApiFormat):
|
|
91
|
+
mode = 'codex_responses'
|
|
92
|
+
credential = 'openai-responses'
|
|
93
|
+
refusal: ClassVar[JsonObject] = {'model': 'grokky-refused', 'instructions': 'refused', 'max_output_tokens': 16,
|
|
94
|
+
'store': False, 'input': [{'role': 'user', 'content': 'refused'}]}
|
|
95
|
+
|
|
96
|
+
def patch(self, request: JsonObject, system_prompt: str, output_schema: JsonObject | None) -> JsonObject:
|
|
97
|
+
# Nothing is stored: every call carries the whole history, its reasoning included.
|
|
98
|
+
out = {**request, 'store': False, 'instructions': system_prompt or NO_INSTRUCTIONS}
|
|
99
|
+
if output_schema is not None:
|
|
100
|
+
out['text'] = {**(out.get('text') or {}),
|
|
101
|
+
'format': {'type': 'json_schema', **_openai_schema(output_schema)}}
|
|
102
|
+
# Grokky shows no reasoning summary, and summaries may need a verified organization. Some models always reason
|
|
103
|
+
# and reject `none`, which Hermes asks for when a turn wants no thinking; every reasoning model takes `low`.
|
|
104
|
+
reasoning = {k: v for k, v in (out.pop('reasoning', None) or {}).items() if k != 'summary'}
|
|
105
|
+
if reasoning.get('effort') == 'none':
|
|
106
|
+
reasoning['effort'] = 'low'
|
|
107
|
+
if reasoning:
|
|
108
|
+
out['reasoning'] = reasoning
|
|
109
|
+
return out
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class ChatCompletions(ApiFormat):
|
|
113
|
+
mode = 'chat_completions'
|
|
114
|
+
credential = 'openai-chat-completions'
|
|
115
|
+
refusal: ClassVar[JsonObject] = _REFUSED_MESSAGES
|
|
116
|
+
|
|
117
|
+
def patch(self, request: JsonObject, system_prompt: str, output_schema: JsonObject | None) -> JsonObject:
|
|
118
|
+
out = dict(request)
|
|
119
|
+
messages = list(out.get('messages') or [])
|
|
120
|
+
# Hermes leads with a system message, or a developer one for the models that take that role.
|
|
121
|
+
lead = messages.pop(0) if messages and messages[0].get('role') in ('system', 'developer') \
|
|
122
|
+
else {'role': 'system'}
|
|
123
|
+
out['messages'] = ([{'role': lead['role'], 'content': system_prompt}] if system_prompt else []) + messages
|
|
124
|
+
if output_schema is not None:
|
|
125
|
+
out['response_format'] = {'type': 'json_schema', 'json_schema': _openai_schema(output_schema)}
|
|
126
|
+
return out
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class BedrockConverse(ApiFormat):
|
|
130
|
+
"""Amazon Bedrock's Converse API, for the models Bedrock serves neither on the Messages nor on the Responses API
|
|
131
|
+
(Qwen, Kimi). Hermes calls it through boto3 with Converse's own request shape."""
|
|
132
|
+
mode = 'bedrock_converse'
|
|
133
|
+
credential = ''
|
|
134
|
+
refusal: ClassVar[JsonObject] = {'modelId': 'grokky-refused', 'inferenceConfig': {'maxTokens': 1},
|
|
135
|
+
'messages': [{'role': 'user', 'content': [{'text': 'refused'}]}]}
|
|
136
|
+
|
|
137
|
+
def patch(self, request: JsonObject, system_prompt: str, output_schema: JsonObject | None) -> JsonObject:
|
|
138
|
+
out = dict(request)
|
|
139
|
+
if system_prompt:
|
|
140
|
+
out['system'] = [{'text': system_prompt}]
|
|
141
|
+
else:
|
|
142
|
+
out.pop('system', None)
|
|
143
|
+
return out
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
FORMATS: dict[str, ApiFormat] = {f.mode: f for f in (AnthropicMessages(), OpenAIResponses(), ChatCompletions(),
|
|
147
|
+
BedrockConverse())}
|
|
148
|
+
# The apiFormat Grokky credential's values.
|
|
149
|
+
BY_CREDENTIAL: dict[str, ApiFormat] = {f.credential: f for f in FORMATS.values() if f.credential}
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def refused(api_mode: str) -> JsonObject:
|
|
153
|
+
"""The refusal in the request's format; middleware that raises lets Hermes send its own request, so an unknown
|
|
154
|
+
format gets one too."""
|
|
155
|
+
return FORMATS.get(api_mode, FORMATS['anthropic_messages']).refused()
|