fix(hermes): patch --query-file support and surface provider errors

- Add idempotent Hermes CLI patch for --query-file (E2BIG fix) and wire it into setup_hermes.sh
- Mark runs failed when Hermes exits 0 after a terminal provider error (e.g. HTTP 429)
- Prefer MiniMax as default OPENAI_* provider in service.pre_start
- Replace dead OpenRouter model IDs with models that currently exist
- Ignore Playwright MCP artifacts
This commit is contained in:
Jannik committed 2026-11-15 20:23:17 +01:00
1 parent ee101b4a73
commit 8a492afa00
6 files changed
+187 -2

No files matched your search

+3
View File
@@ -31,3 +31,6 @@ services/caddy/fragments/
# Local docker save backups (don't accidentally commit these — too big)
paperclip-image.tar
paperclip-image.tar.gz
# Playwright MCP artifacts
.playwright-mcp/
+128
View File
@@ -0,0 +1,128 @@
#!/usr/bin/env python3
"""Add --query-file support to the installed hermes_cli.
PaperClip's hermes adapter passes the (potentially large) prompt via
`hermes chat --query-file <path>`. Upstream hermes-agent 0.19.0 (latest on
PyPI at the time of writing) only supports `-q/--query`, and passing a prompt
larger than ~128 KB as a single argv string fails with E2BIG (MAX_ARG_STRLEN).
This patch teaches the CLI to read the query from a file, which removes the
argv size limit and keeps the PaperClip adapter patch working.
Idempotent: safe to run multiple times, and safe if hermes is not installed.
"""
from __future__ import annotations
import sys
from pathlib import Path
MARKER = "# [paperclip-patch] --query-file support"
def find_site_packages() -> Path | None:
"""Locate the site-packages dir that contains hermes_cli."""
candidates: list[Path] = []
# 1) Ask the venv interpreter that owns the hermes entrypoint.
try:
import subprocess
out = subprocess.run(
[
"/opt/hermes-venv/bin/python3",
"-c",
"import hermes_cli, os; print(os.path.dirname(os.path.dirname(hermes_cli.__file__)))",
],
capture_output=True,
text=True,
timeout=30,
)
if out.returncode == 0 and out.stdout.strip():
candidates.append(Path(out.stdout.strip()))
except Exception:
pass
# 2) Fall back to the current interpreter's site-packages.
try:
import hermes_cli # type: ignore
candidates.append(Path(hermes_cli.__file__).resolve().parent.parent)
except Exception:
pass
for candidate in candidates:
if (candidate / "hermes_cli" / "_parser.py").is_file():
return candidate
return None
def patch_parser(site_packages: Path) -> str:
parser_path = site_packages / "hermes_cli" / "_parser.py"
src = parser_path.read_text(encoding="utf-8")
if "--query-file" in src:
return "parser: already patched"
needle = ''' chat_parser.add_argument(
"-q", "--query", help="Single query (non-interactive mode)"
)'''
if needle not in src:
return "parser: ANCHOR NOT FOUND (skipped)"
addition = needle + '''
chat_parser.add_argument(
"--query-file",
dest="query_file",
default=None,
help="Read the single query from a file (non-interactive mode).",
)'''
parser_path.write_text(src.replace(needle, addition, 1), encoding="utf-8")
return "parser: patched"
def patch_main(site_packages: Path) -> str:
main_path = site_packages / "hermes_cli" / "main.py"
src = main_path.read_text(encoding="utf-8")
if MARKER in src:
return "main: already patched"
needle = "def cmd_chat(args):\n"
count = src.count(needle)
if count != 1:
return f"main: ANCHOR COUNT={count} (expected 1, skipped)"
injection = (
"def cmd_chat(args):\n"
f" {MARKER}\n"
' _qf = getattr(args, "query_file", None)\n'
' if _qf and not getattr(args, "query", None):\n'
" try:\n"
' with open(_qf, "r", encoding="utf-8", errors="replace") as _fh:\n'
" args.query = _fh.read()\n"
" except OSError as _exc:\n"
' print(f"Error: could not read --query-file {_qf}: {_exc}")\n'
" sys.exit(1)\n"
)
main_path.write_text(src.replace(needle, injection, 1), encoding="utf-8")
return "main: patched"
def main() -> int:
site_packages = find_site_packages()
if site_packages is None:
print("hermes_cli not found (skipped)")
return 0
parser_status = patch_parser(site_packages)
main_status = patch_main(site_packages)
print(f"site-packages: {site_packages}")
print(parser_status)
print(main_status)
if "ANCHOR" in parser_status or "ANCHOR" in main_status:
return 2
return 0
if __name__ == "__main__":
sys.exit(main())
+14
View File
@@ -130,6 +130,20 @@ else
docker exec -u node "${PAPERCLIP_CONTAINER}" hermes config set model.provider auto 2>/dev/null || true
fi
# Hermes unterstützt upstream kein --query-file, der PaperClip-Adapter
# übergibt große Prompts aber genau so (vermeidet spawn E2BIG, da ein
# einzelnes argv-Argument max. ~128 KB groß sein darf). Patch anwenden.
HERMES_QF_PATCH="${SCRIPT_DIR}/patch_hermes_queryfile.py"
if [[ -f "${HERMES_QF_PATCH}" ]]; then
log "Patche Hermes CLI für --query-file Support (E2BIG-Fix)..."
docker cp "${HERMES_QF_PATCH}" "${PAPERCLIP_CONTAINER}:/tmp/patch_hermes_queryfile.py"
docker exec -u root "${PAPERCLIP_CONTAINER}" /opt/hermes-venv/bin/python3 /tmp/patch_hermes_queryfile.py \
|| warn "Hermes --query-file Patch meldete ein Problem."
if ! docker exec -u node "${PAPERCLIP_CONTAINER}" hermes chat --help 2>&1 | grep -q -- "--query-file"; then
warn "Hermes --query-file ist nach dem Patch nicht verfügbar!"
fi
fi
# PaperClip Runtime-Patches anwenden (spawn E2BIG Fix für Hermes)
PATCH_SCRIPT="${SERVICES_DIR}/paperclip/patch_paperclip.js"
if [[ -f "${PATCH_SCRIPT}" ]]; then
+1 -1
View File
@@ -35,7 +35,7 @@ services:
PAPERCLIP_AUTH_BASE_URL_MODE: "explicit"
PAPERCLIP_PUBLIC_URL: "https://paperclip.orfel.de"
HERMES_GATEWAY_ALLOW_INSECURE_HTTP: "1"
PAPERCLIP_OPENCODE_PROVIDERS: '{"openrouter":{"npm":"@ai-sdk/openai-compatible","options":{"baseURL":"https://openrouter.ai/api/v1","apiKey":"{env:OPENROUTER_API_KEY}"},"models":{"anthropic/claude-sonnet-4-5":{},"anthropic/claude-3.5-sonnet":{},"google/gemini-2.5-pro":{},"deepseek/deepseek-r1":{},"openai/gpt-4o":{}}},"mistral":{"npm":"@ai-sdk/openai-compatible","options":{"apiKey":"{env:MISTRAL_API_KEY}"},"models":{"mistral/mistral-large":{}}},"minimax":{"npm":"@ai-sdk/openai-compatible","options":{"baseURL":"https://api.minimax.io/v1","apiKey":"{env:MINIMAX_API_KEY}"},"models":{"minimax/abab6.5s":{},"minimax/MiniMax-Text-01":{},"minimax/MiniMax-M3":{}}},"poe":{"npm":"@ai-sdk/openai-compatible","options":{"apiKey":"{env:POE_API_KEY}"},"models":{"poe/claude-3-opus":{}}}}'
PAPERCLIP_OPENCODE_PROVIDERS: '{"openrouter":{"npm":"@ai-sdk/openai-compatible","options":{"baseURL":"https://openrouter.ai/api/v1","apiKey":"{env:OPENROUTER_API_KEY}"},"models":{"nvidia/nemotron-3.5-lightning:free":{},"nvidia/nemotron-3-ultra-550b-a55b:free":{},"cohere/north-mini-code:free":{},"google/gemma-4-31b-it:free":{},"dots-studio/dots-3-note-preview:free":{}}},"mistral":{"npm":"@ai-sdk/openai-compatible","options":{"apiKey":"{env:MISTRAL_API_KEY}"},"models":{"mistral/mistral-large":{}}},"minimax":{"npm":"@ai-sdk/openai-compatible","options":{"baseURL":"https://api.minimax.io/v1","apiKey":"{env:MINIMAX_API_KEY}"},"models":{"minimax/MiniMax-M3":{}}},"poe":{"npm":"@ai-sdk/openai-compatible","options":{"apiKey":"{env:POE_API_KEY}"},"models":{"poe/claude-3-opus":{}}}}'
volumes:
- /opt/PaperClip-Data/paperclip:/paperclip
- /opt/PaperClip-Data/paperclip-hermes-venv:/opt/hermes-venv
+35
View File
@@ -91,4 +91,39 @@ if (fs.existsSync(aiConnPath)) {
}
}
// ---------------------------------------------------------------------------
// 4. Mark runs as failed when Hermes reports a terminal provider error
// (Hermes exits 0 even when the final LLM call failed, e.g. HTTP 429)
// ---------------------------------------------------------------------------
if (fs.existsSync(hermesExecutePath)) {
let content = fs.readFileSync(hermesExecutePath, 'utf8');
const marker = '[paperclip-patch] terminal provider error detection';
const anchor = ' const parsed = parseHermesOutput(result.stdout || "", result.stderr || "");';
if (!content.includes(marker) && content.includes(anchor)) {
const injection = anchor + `
// ${marker}
if (!parsed.errorMessage) {
const fatalPatterns = [
/API call failed after \\d+ retries?:\\s*([^\\n]+)/,
/Final error:\\s*([^\\n]+)/,
/insufficient_balance_error[^\\n]*/,
];
const haystack = \`\${result.stdout || ""}\\n\${result.stderr || ""}\`;
for (const pattern of fatalPatterns) {
const match = haystack.match(pattern);
if (match) {
parsed.errorMessage = (\`Hermes provider error: \${match[0]}\`).slice(0, 500);
break;
}
}
}`;
content = content.replace(anchor, injection);
fs.writeFileSync(hermesExecutePath, content, 'utf8');
console.log('[Patch PaperClip] Patched hermes execute.ts to surface terminal provider errors.');
} else {
console.log('[Patch PaperClip] hermes terminal-error detection already patched or anchor not found.');
}
}
console.log('[Patch PaperClip] All patches completed.');
+6 -1
View File
@@ -18,7 +18,12 @@ if [[ -f "${ENV_FILE}" ]]; then
# Auto-configure default LLM (OPENAI_* Overrides) aus shared.env lesen
if ! grep -q "OPENAI_API_KEY=" "${ENV_FILE}" && ! grep -q "ANTHROPIC_API_KEY=" "${ENV_FILE}"; then
if [[ -f "${SHARED_ENV}" ]] && grep -q "OPENROUTER_API_KEY=" "${SHARED_ENV}"; then
if [[ -f "${SHARED_ENV}" ]] && grep -q "MINIMAX_API_KEY=" "${SHARED_ENV}"; then
echo "[PaperClip Pre-Start] Auto-configuring MiniMax as default LLM..."
echo "" >> "${ENV_FILE}"
echo "OPENAI_BASE_URL=https://api.minimax.io/v1" >> "${ENV_FILE}"
grep "MINIMAX_API_KEY=" "${SHARED_ENV}" | sed 's/MINIMAX_API_KEY=/OPENAI_API_KEY=/' >> "${ENV_FILE}"
elif [[ -f "${SHARED_ENV}" ]] && grep -q "OPENROUTER_API_KEY=" "${SHARED_ENV}"; then
echo "[PaperClip Pre-Start] Auto-configuring OpenRouter as default LLM..."
echo "" >> "${ENV_FILE}"
echo "OPENAI_BASE_URL=https://openrouter.ai/api/v1" >> "${ENV_FILE}"