grok-to-hermes
Installation
Review the source and dependencies with a prompt. A package is available to download.
Install with an AI assistant
Copy the prompt so your assistant can review the pinned revision and dependencies first.
View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "grok-to-hermes" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-fc928b43b3036c4c23413847ec64600d3fa32a481fa2329f266330a61a5a9aa4. Verify the upstream source and version against https://skillhub.cn/skills/user_97acf6d1/grok-to-hermes before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.
Source and setup
skillhub.cn
Setup guidance pending
See the original source for supported tools, dependencies, and permissions.
Installation test pending
Five independent Python modules ported after deep reading of the 1.25M-line grok-build Rust codebase: context compression engine, inference retry/backoff, crash recovery, hooks runtime, and extension registry. Each module can be imported independently or invoked via CLI.
Introduction source: third_party · user_97acf6d1 · 2.0.0 Reference
SkillPi interpretation
- Tasks
- Translation pending; see source documentation.
- Testing
- Not tested
Browse files
Frontmatter
name: grok-to-hermes
slug: grok-to-hermes
displayName: "Grok Build 源码精华:压缩/重试/崩溃恢复/钩子/扩展注册表"
description: "从 grok-build 125万行 Rust 源码深读后移植的 5 个独立 Python 模块:上下文压缩引擎、推理重试退避、崩溃恢复、钩子运行时、扩展注册表。每个模块可独立 import 或 CLI 调用。"
version: 2.0.0
category: autonomous-ai-agentsGrok Build → Hermes 源码精华移植
从 xai-org/grok-build 仓库(74 crates, 1,252,142 行 Rust)深读后,将 5 个关键 crate 的算法移植为独立 Python 模块。每个模块精确匹配 grok-build 的算法逻辑和默认值。
工作流原则:Codex 依赖 FreeLLMAPI 模型可用性。当 Codex 因模型不可用无法启动时,不要无限调试——直接用本技能的模块自行构建。
架构全景
| 开源(全部 74 crate) | 闭源(仅 3 样) |
|---|---|
| agent 引擎、shell TUI、工具层、推理调度 | 模型权重 |
| 上下文压缩、沙箱、MCP、Markdown 渲染 | 推理 API 后端 |
| 崩溃处理、钩子、注册表、熔断器 | 系统提示词正文 |
| 1,252,142 行 — 整个 agent 基础设施 | 模型调用是唯一外部依赖 |
本 skill 深读了其中 5 个关键 crate,并将算法移植为 Python:
模块清单
| # | 模块 | 脚本 | 来源 crate | 源码行数 | 状态 |
|---|---|---|---|---|---|
| 1 | 上下文压缩引擎 | scripts/compaction_engine.py |
xai-grok-compaction |
6,790 | ✅ 已实现 |
| 2 | 推理重试/退避 | scripts/retry_backoff.py |
xai-grok-sampler/retry.rs |
856 | ✅ 已实现 |
| 3 | 崩溃恢复 | scripts/crash_recovery.py |
xai-crash-handler |
1,592 | ✅ 已实现 |
| 4 | 钩子运行时 | scripts/hook_runtime.py |
xai-grok-hooks |
7,488 | ✅ 已实现 |
| 5 | 扩展注册表 | scripts/extension_registry.py |
xai-agent-lifecycle |
608 | ✅ 已实现 |
| 6 | Codex Bridge Adapter | scripts/codex_bridge_adapter.py |
— | — | ✅ 已实现 |
| 7 | Codex Bridge Adapter (JS) | scripts/codex_bridge_adapter.js |
— | — | ✅ 已实现 |
快速开始
# 每个模块都可独立 import
from compaction_engine import should_compact, compact, CompactionConfig
from retry_backoff import classify_error, retry_backoff_with_jitter, retry_with_backoff
from crash_recovery import check_previous_crash, CrashHandler
from hook_runtime import load_hooks_from_directory, dispatch_pre_tool_use
from extension_registry import ExtensionRegistryBuilder, CommandContributor, CommandAction
# 每个模块都有 CLI
python scripts/compaction_engine.py check '<json_messages>' 128000 85
python scripts/retry_backoff.py classify 502 2
python scripts/crash_recovery.py check /tmp/crashes
python scripts/hook_runtime.py load ~/.hermes/hooks
python scripts/extension_registry.py list
模块详解
1. 上下文压缩引擎 ★★★
scripts/compaction_engine.py — 移植自 xai-grok-compaction (6,790 LOC)
三种策略:
| 策略 | 行为 | 触发条件 |
|---|---|---|
FullReplace |
整个对话 → 单个摘要消息 | token > 85% 窗口 |
TailKeep |
保留尾部 50% tokens,压缩旧内容 | token > 85% 窗口 + step >= 3 |
Chunked |
分 8K token 块各自摘要再合并 | 手动调用 |
核心算法:
select → sample → guard → commit
should_compact()— 4 层门控:enabled ∧ context_window>0 ∧ (FullReplace ∨ step≥3) ∧ tokens>85%select_turns_to_compact()— 从尾部向前走,预算内保留,找到 split_idxsnap_to_safe_boundary()— 工具对安全:绝不切断 assistant-tool_requests 和 tool_results- Guard: tokens_before < 5000 → 跳过;tokens_after > tokens_before × 0.8 → 丢弃
- 重试 3 次(FullReplace)/ 2 次(TailKeep),3s 间隔
所有默认值精确匹配 grok-build:
| 参数 | 默认值 | 说明 |
|---|---|---|
trigger_threshold_percent |
85 | 触发压缩的 token 占比 |
target_threshold_percent |
50 | 压缩后目标 token 占比 |
min_compactable_tokens |
5000 | 低于此值不压缩 |
max_reduction_ratio |
0.8 | 摘要必须 ≤ 原文 80% |
max_attempts |
3 (FullReplace) / 2 (TailKeep) | 最大重试次数 |
retry_delay_secs |
3 | 重试间隔 |
sampling_timeout_secs |
120 | LLM 调用超时 |
chunk_token_limit |
8000 | Chunked 策略每块预算 |
min_summary_seed_chars |
500 | 拒绝退化摘要 |
from compaction_engine import compact, CompactionConfig, CompactionStrategy
cfg = CompactionConfig(
strategy=CompactionStrategy.TAIL_KEEP,
trigger_threshold_percent=85,
target_threshold_percent=50,
)
def my_llm(messages, prompt):
return openai.chat(prompt["system"], prompt["user"])
result = compact(messages, my_llm, context_window=128000, config=cfg)
if result:
messages = result["messages"] # compacted conversation
2. 推理重试/退避 ★★★
scripts/retry_backoff.py — 移植自 xai-grok-sampler/src/retry.rs (856 LOC)
9 步错误分类管道(求值顺序不可变):
| 步骤 | 条件 | 决策 |
|---|---|---|
| 1 | 401/403 / 加密内容错误 | EmitToSession(不重试) |
| 2 | 413 Payload Too Large | RetryWithImageStrip |
| 3 | 图片处理错误(400/500) | RetryWithImageStrip(拦截 5xx!) |
| 4 | x-should-retry: false |
Fatal |
| 5 | 上下文溢出 | Fatal |
| 6 | DoomLoopDetected | Retry(~0-250ms) |
| 7 | 429 Rate Limited | RetryWithBackoff(cap=2,用 Retry-After) |
| 8 | 5xx / 传输错误 | Retry(首次重建 HTTP/1.1 client) |
| 9 | 其他一切 | Fatal |
退避曲线: 2000ms → 4000ms → 8000ms → 16000ms → 30000ms(cap),±20% 抖动
from retry_backoff import classify_error, retry_with_backoff
# 独立使用分类器
decision = classify_error(status_code=502, retry_count=1)
# → RetryDecision(decision=RETRY, backoff_ms=3200, reason="server_error")
# 完整重试循环
result = retry_with_backoff(
lambda: api.chat(messages),
max_retries=5,
rate_limit_threshold=2,
)
3. 崩溃恢复 ★★
scripts/crash_recovery.py — 移植自 xai-crash-handler (1,592 LOC)
GCRX 二进制格式(576 字节最大):
Offset Size Field
0 4 Magic "GCRX"
4 1 Version (1)
5 1 Signal number
6 4 si_code (i32)
10 8 si_addr (u64)
18 4 PID (u32)
22 8 Unix timestamp (u64)
30 2 n_frames (u16)
32 32 App version (null-padded UTF-8)
64 n*8 Frame addresses (u64 each)
关键设计: 先写 crash PC(1 帧),再做 best-effort frame walk。Frame walk 可能再次 fault,SA_RESETHAND 会杀死进程——所以 PC 必须先落盘。
from crash_recovery import check_previous_crash, CrashHandler
# 启动时检测上次崩溃
report = check_previous_crash("/tmp/crashes")
if report:
print(f"Previous crash: {report['signal_name']} at {report['faulting_address']}")
# 安装信号处理器
handler = CrashHandler(crash_dir="/tmp/crashes", app_version="1.0.0")
handler.install()
4. 钩子运行时 ★★
scripts/hook_runtime.py — 移植自 xai-grok-hooks (7,488 LOC)
15 种生命周期事件:
- Session: SessionStart, SessionEnd, Stop, StopFailure
- Tool: PreToolUse(唯一可阻断的), PostToolUse, PostToolUseFailure, PermissionDenied
- User: UserPromptSubmit, Notification
- Subagent: SubagentStart, SubagentStop
- Compaction: PreCompact, PostCompact
关键安全属性:FAIL-OPEN。 只有显式 {"decision":"deny"} 才阻断工具调用。超时/崩溃/格式错误全部放行。
两层决策: JSON 返回值优先于 exit code(0=allow, 2=deny, 其他=fail-open)
from hook_runtime import load_hooks_from_directory, dispatch_pre_tool_use
hooks = load_hooks_from_directory("~/.hermes/hooks")
result = dispatch_pre_tool_use(hooks, "Bash", {"command": "rm file.txt"}, {})
if result["decision"] == "deny":
print(f"Blocked by {result['hook_name']}: {result['reason']}")
5. 扩展注册表 ★
scripts/extension_registry.py — 移植自 xai-agent-lifecycle (608 LOC)
Builder → Registry 模式:
Builder (可变) → build() → Registry (不可变)
↓ ↓
注册 contributors 按类型查询
重复检测(先到先得) 生命周期分发
O(1) 命令查找
4 种 contributor:TurnLifecycle / SessionLifecycle / TurnInput / Command
from extension_registry import ExtensionRegistryBuilder, CommandContributor, CommandAction
class MyCommands(CommandContributor):
def advertised_commands(self):
return [CommandSpec(name="deploy", description="Deploy to staging")]
def handle_command(self, inv):
return CommandAction.rewrite("Run the deployment pipeline...")
builder = ExtensionRegistryBuilder()
builder.register_command(MyCommands())
registry = builder.build()
result = registry.handle_command("deploy") # O(1) lookup
Codex Bridge 集成
scripts/codex_bridge_adapter.py 和 scripts/codex_bridge_adapter.js 将 compaction + retry 嵌入 bridge-443.mjs(Codex → FreeLLMAPI 的中间层):
Codex CLI → bridge-443.mjs
↓ 拦截请求
[Adapter: shouldCompact? → compactWithLLM]
[Adapter: proxyFn with retry → 5xx/429 自动退避]
↓
FreeLLMAPI :3001
CLI 命令:
python codex_bridge_adapter.py check '<json_messages>' 128000 85
python codex_bridge_adapter.py retry 502 2
python codex_bridge_adapter.py backoff 3
深读过的源文件
| Grok 文件 | 行数 | 关键内容 |
|---|---|---|
xai-grok-compaction/src/intra_compaction/compact.rs |
1,550 | FullReplace/TailKeep 编排 |
xai-grok-compaction/src/intra_compaction/trigger.rs |
247 | should_compact() 4 层门控 |
xai-grok-compaction/src/intra_compaction/config.rs |
366 | 全部默认值 |
xai-grok-compaction/src/intra_compaction/select.rs |
279 | 尾部分割 + 工具对安全 |
xai-grok-compaction/src/code_compaction/sample.rs |
181 | 共享摘要采样 + 退化检测 |
xai-grok-compaction/src/code_compaction/summary.rs |
82 | 摘要清洗(XML 标签剥离) |
xai-grok-sampler/src/retry.rs |
856 | 9 步错误分类 + 指数退避 |
xai-crash-handler/src/handler.rs |
923 | 信号处理 + 帧遍历 |
xai-crash-handler/src/format.rs |
82 | GCRX 二进制格式 |
xai-grok-hooks/src/dispatcher.rs |
— | 阻塞分发 + fail-open |
xai-grok-hooks/src/matcher.rs |
— | All/Exact/Regex 三模式 |
xai-agent-lifecycle/src/lib.rs |
— | Builder → Registry 模式 |
参考文件
references/grok-source-guide.md— Grok Build 源码获取技巧 + 必读清单references/grok-bridge-pattern.md— Grok Build → FreeLLMAPI WSS 桥接方案references/codex-model-debugging.md— Codex + FreeLLMAPI 模型故障速查references/BRIDGE_INTEGRATION.md— Codex bridge-443 集成步骤references/windows-disk-cleanup.md— Windows C 盘清理 playbook
与 FreeLLMAPI / Codex 的关系
- compaction_engine 可在 FreeLLMAPI 请求前后介入,预防 token 超限
- retry_backoff 可直接套在 Codex/FreeLLMAPI 的 HTTP 调用外层
- crash_recovery 在 Hermes 启动时检测 FreeLLMAPI 异常退出
- hook_runtime 的 pre_tool_use 可在危险命令前拦截
- extension_registry 可用于构建 Hermes 的插件系统
- codex_bridge_adapter 是 compaction + retry 的 Codex 特化版
Current listing version
2.0.0
Safety and assessment details
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Highlights
- 提供 5 个独立可复用的 Python 模块,解决上下文压缩、API 重试、崩溃恢复等工程刚需
- 每个模块支持独立 import 和 CLI 调用,集成灵活度高
Areas to improve
-
触发词不全 Reported severity: Minor
description 描述了功能但未提供具体触发关键词或命令示例,用户难以通过自然语言精准触发
Recommendation: 补充典型触发词如 'compress context'、'retry api'、'handle crash' 等,并在 description 中明确列出
Areas to improve
-
缺少 When to Use 章节 Reported severity: Minor
文档结构完整但缺少明确的 When to Use 使用场景说明
Recommendation: 增加 When to Use 章节,说明何时应使用本 Skill(如 Codex 模型不可用时、需要自定义压缩策略等)
-
缺少端到端示例 Reported severity: Minor
虽有模块示例但缺少从安装到完整使用的端到端流程示例
Recommendation: 补充一个完整示例:从导入模块 -> 配置参数 -> 调用 LLM -> 处理结果的完整流程
Highlights
- 架构清晰,模块划分明确,含详细的算法说明和默认值匹配
Highlights
- 工具来源明确(grok-build 源码),参数与默认值精确匹配,覆盖主要异常场景
- 重试退避、崩溃恢复等模块具备完善的错误处理机制
The arithmetic mean of the first four original scores, rounded to a whole number.
Static text checks
100 / 100 · skillpi-20261123-no-r3-v1
No current rules matched the text.
This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.
Permissions and checks before use
Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.
These common operations were not identified in the main document. This does not mean no permissions or risks exist.
Security rating and access scope
safe · Static evidence review; not a runtime safety guarantee.
Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.
User discussion
No verified reviews yet.