Skip to content

perf(adapters): warm bridge pool, launcher-prefix cache and one-shot history for hermes opens - #638

Closed
zxd-666 wants to merge 3 commits into
BytePioneer-AI:mainfrom
zxd-666:perf/hermes-warm-bridge
Closed

zxd-666 wants to merge 3 commits into
BytePioneer-AI:mainfrom
zxd-666:perf/hermes-warm-bridge

Conversation

@zxd-666

@zxd-666 zxd-666 commented Oct 28, 2026

Copy link
Copy Markdown
Contributor

Stacked on #631 (canonical wire fixes) — merge that first; once it lands, this PR's diff collapses to just the performance changes. Based on perf/hermes-warm-bridge = fix/hermes-delegation-ws-bridge + one commit.

Problem

Hermes session opens paid ~3.3s where the ACP harnesses answer in well under a second. Cost breakdown per open, all against the same resident gateway:

  • every open spawns a fresh bridge: launcher probe (~0.3s) + interpreter start with heavy imports + WS attach (~0.7s)
  • every helper subprocess (resolveGatewayModel, the history pair) re-ran the launcher probe before its own interpreter start
  • the create-time history pair (ensure + identity reconciliation) spawned twice

Changes

  1. Warm bridge pool (gateway-transport-pool.ts, new). A bridge is a stateless pipe between the host and the resident gateway's canonical WebSocket — session state lives in the gateway process — so a settled session's bridge can serve the next open. The adapter acquires from the pool before spawning and releases on session settle; each bridge serves one session at a time (exclusive ownership, no event routing changes). Faulted or never-started bridges are discarded on acquire/release; capacity 2. Nothing is keyed per-thread on purpose: cwd is a session.create parameter (never read from the bridge process), and the delegation skill text is thread-independent — the same per-thread-identity mistake that broke the ACP warm pool (PR feat: 集成 Hermes ACP 并修复会话生命周期 #206) is not repeated here.
  2. Launcher-prefix cache (hermes-runtime.ts). --print-runtime-command answers embed the caller's script verbatim, but the interpreter prefix (python + -I + -c bootstrap) is script-independent. Cache the prefix keyed on the launcher's stat (mtime/size — a hermes update rewrites the launcher and invalidates) plus HERMES_HOME/PATH; re-append the passthrough timeit arguments per spawn. Cache only stores entries whose echo tail matches the request verbatim.
  3. Stable delegation skill directory (gateway-delegation.ts, was mkdtemp): the bootstrap script stays byte-identical across opens so the prefix cache always hits. The file is intentionally not deleted on dispose — warm bridges keep serving the registered skill path, and the next open overwrites it.
  4. One-shot history (gateway-history-script.ts, gateway-history.ts, gateway-open.ts): a new ensure_and_resolve operation persists the session row and reads the storage identity back in a single interpreter start; resume/fork paths keep resolve-only.

Measured

Against a live resident gateway (Telegram/Feishu connected), Desktop-identical conditions (delegation env, --print-runtime-command native chain, model + thinking selected), same machine before/after:

open before after
cold (first, cache fill) 3329 ms 2446 ms
warm (pooled bridge + cached prefix) — 1424 ms
full turn round-trip (open → submit → streamed reply → turn.completed → detach) — healthy, ~9.3s incl. model generation

Verification (SHA be506a79)

  • hermes verify on this branch: bootstrap / build (tsc full repo + plugins + renderer + rust) / typecheck / test:rust / lint / format:check all PASS. Full vitest 7111 passed; the single failure is the pre-existing baseline packages/adapters/workbuddy/test/discovery.test.ts > finds the macOS bundle — reproduced on the parent commits of fix(adapters): attach the hermes delegation gateway to the resident gateway and speak its canonical wire #631 (documented there): the branch base predates the workbuddy discovery update while the local WorkBuddy.app CLI moved on. Unrelated to this PR's files.
  • New unit tests for the pool (gateway-transport-pool.test.ts, 7 cases: idle acquire, fault/never-started discard, runtime mismatch, capacity eviction, teardown).
  • Live E2E per the table above, including a warm-path full turn.

The delegation transport spawns tui_gateway.entry as a standalone stdio
server. Upstream hermes-agent (9595c3f345) made that server refuse to
start when a gateway already owns HERMES_HOME - both are state.db
writers, so the reservation is correct - which means every delegation
spawn fails with '[gateway-exit] refused' whenever the messaging
gateway is running (Telegram/Feishu/etc. keep it resident).

Replace the stdio server launch with a thin WS bridge: ensure the
gateway runtime, mint a session ticket on the control socket, dial the
canonical WebSocket, and pipe stdin JSON-RPC lines to it. The WS
transport reuses the same tui_gateway.server.dispatch, so the RPC
surface is unchanged; attached clients (Ink TUI, Desktop, this bridge)
coexist with the resident gateway by design.

The bridge runs top-level code without a __main__ guard: the native
launcher executes the script via exec(script, {}) whose fresh globals
lack __name__.
The WS bridge attaches to the gateway's canonical hermes-gateway-v1
channel, whose method contracts differ from the stdio/TUI surface the
transport was written against. Session creation failed with 4001
invalid_params and turns never started:

- session.create: drop close_on_disconnect, rename reasoning_effort to
  reasoning (CanonicalCreateParams); canonical lazy sessions build the
  agent on the first prompt and never emit a non-lazy session.info, so
  stop waiting (the official TUI renders lazy info with placeholders);
  the persisted identity only rides the create response top level
- session.resume: drop eager_build
- config.set yolo: session-scoped switch must omit scope (the scoped
  variant is the global toggle and is refused); value on/off, reply 1/0
- config.set model: refused with use_session_mutation_model — switch via
  session.mutate (operation=model, revision/generation fenced), confirm
  from the mutation receipt (config.get key=provider does not exist)
- prompt.submit: requires a caller-chosen submission_id (idempotent
  admission identity); answers AdmissionStatus queued/started, never
  streaming
- session.interrupt: requires execution_generation; session.close does
  not exist — detach with the receipt's subscription_id
- delegation bootstrap: tui_gateway.server redirects sys.stdout to
  sys.stderr at import (stdio-entry protection), which hijacked the
  bridge's RPC channel to the host under delegation env; save and
  restore stdout around that import

Track revision/execution_generation/subscription_id from the create
receipt and session.info events. Test assertions updated to the new
wire contract.
…history for hermes opens

Hermes session opens paid ~3.3s where ACP harnesses answer in well under a
second: every open spawned a fresh bridge (launcher probe + interpreter +
WS attach), every helper subprocess re-ran the launcher probe, and the
history pair spawned twice.

- Warm bridge pool: a settled session's bridge is a stateless pipe to the
  resident gateway, so the adapter now hands it back on settle and the next
  open acquires it instead of spawning (exclusive ownership per session;
  cwd is a session.create parameter and the delegation skill text is
  thread-independent, so nothing is keyed per-thread)
- Launcher-prefix cache: --print-runtime-command answers embed the caller's
  script verbatim, but the interpreter prefix is script-independent; cache
  that prefix keyed on the launcher's stat so a hermes update invalidates
  it, and re-append the passthrough arguments per spawn
- Stable delegation skill directory (was mkdtemp): the bootstrap script
  stays byte-identical across opens so the prefix cache always hits
- One-shot history: ensure + identity reconciliation ride a single
  interpreter start via a new ensure_and_resolve operation

Measured against a live resident gateway under Desktop conditions
(delegation env, model + thinking selected): cold open 3329ms -> 2446ms,
warm open 1424ms; full turn round-trip unchanged and healthy.
@coderabbitai

coderabbitai Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Caution

Review failed

The pull request is closed.

📝 Summary

Summary by CodeRabbit

  • 新功能
    • Hermes 会话现支持复用连接,减少重复启动带来的等待。
    • 创建或恢复会话时可保留会话身份,并支持通过会话信息切换模型。
  • 问题修复
    • 改进会话提交、取消和结束处理,降低操作状态不一致及意外中断的可能。
    • 优化会话创建与恢复流程,提升连接异常时的稳定性。

此 PR 更新 Hermes Gateway 桥接和会话协议,新增 transport 池及运行时命令缓存,并调整会话创建和历史身份解析。

Changes: Hermes Gateway 接入

Layer / File(s) Summary
Gateway 桥接与启动准备
packages/adapters/hermes/src/hermes-runtime.ts, packages/adapters/hermes/src/gateway-delegation.ts, packages/adapters/hermes/src/gateway-transport.ts, packages/adapters/hermes/test/gateway-delegation.test.ts
桥接脚本连接常驻 Gateway,并在标准输入和标准输出之间转发 JSON-RPC 帧。委托文件写入固定临时目录。运行时命令前缀按启动器文件状态和环境变量缓存。
Transport 池与适配器生命周期
packages/adapters/hermes/src/gateway-transport-pool.ts, packages/adapters/hermes/src/hermes-adapter.ts, packages/adapters/hermes/test/gateway-transport-pool.test.ts
新增按运行时匹配的 transport 池。适配器打开会话时先尝试获取池内 transport;没有可用实例时启动新实例。会话结束时释放 transport,适配器关闭时关闭池。
会话打开与历史身份解析
packages/adapters/hermes/src/gateway-history-script.ts, packages/adapters/hermes/src/gateway-history.ts, packages/adapters/hermes/src/gateway-open.ts, packages/adapters/hermes/test/gateway-routing.test.ts
新增确保会话记录存在并解析物理会话 ID 的操作。创建请求使用 canonical 参数,并通过响应级 storedId 校验身份。恢复和派生路径解析现有物理会话 ID。
会话协议与状态管理
packages/adapters/hermes/src/gateway-session-transport.ts, packages/adapters/hermes/test/gateway-session.test.ts, packages/adapters/hermes/test/gateway-observability.test.ts
会话传输维护 revision、generation 和 subscription ID。模型更新改用带版本校验的 session.mutate;提示提交接受 queued 或 started;取消请求携带 generation,关闭会话时按 subscription ID detach。

Priority: Not assessed

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Refactor

Sequence Diagram(s)

sequenceDiagram
  participant HermesAdapter
  participant GatewayTransportPool
  participant startGatewayTransport
  participant HermesGatewayTransport
  participant openGatewaySession
  participant Gateway
  HermesAdapter->>GatewayTransportPool: acquire(runtime)
  alt 池中有可用 transport
    GatewayTransportPool-->>HermesAdapter: 返回 transport
  else 池中没有可用 transport
    HermesAdapter->>startGatewayTransport: 启动 transport
    startGatewayTransport->>HermesGatewayTransport: prepareSession() 和 start()
    HermesGatewayTransport->>Gateway: 建立 Gateway WebSocket 连接
    HermesGatewayTransport-->>HermesAdapter: 返回已启动 transport
  end
  HermesAdapter->>openGatewaySession: 打开会话
  openGatewaySession->>Gateway: 发送创建或恢复请求
  Gateway-->>openGatewaySession: 返回会话响应
  openGatewaySession-->>HermesAdapter: 返回会话
  HermesAdapter->>GatewayTransportPool: 会话结束时释放 transport
Loading

Possibly related PRs

  • BytePioneer-AI/codex-host#631:该 PR 涉及 Hermes 常驻 Gateway 桥接、wire contract 和会话生命周期,与本次改动处于同一实现链路。

Suggested labels: 范围:适配器

Suggested reviewers: bytepioneer-ai

Merge Risk: Moderate · up to be506

Opening Hermes sessions can fail persistently after a transient startup error, large prompts can break the bridge, and warm bridges can be reused with a stale working directory or environment. The shared temp directory for the delegation skill also needs hardening. Resolve these before merging.

Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant