Skip to content
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## 0.1.1 (Unreleased)

- Keep concurrent turns waiting for their current session start, consume its context once, and recover later turns after a failed start without deleting a newer pending start. Thanks @SebTardif.
- Read folded and literal YAML descriptions for generated commands, agents, and output styles, preserving header comments, indentation, blank lines, and clip/strip/keep chomping across LF and CRLF; retain copied skill bodies, metadata, assets, and regeneration rollback. Thanks @SebTardif.
- Isolate imported hook command expansion failures while retaining a blocking decision for PreToolUse, UserPromptSubmit, and Stop, preserving prior results and later hooks; observers warn and continue. Thanks @SebTardif.
- Let a Stop hook with `continue: false` finish the turn. `decision: "block"` still asks OpenClaw to revise, and `continue: false` outranks a block on the same hook. Thanks @SebTardif.
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ Installing an already installed name requires `--force`; a rejected duplicate le
| Prompt and terminal commands | User-invoked skills or top-level CLI commands when the source format supports them. Hermes MCP command tools accept optional `args`: omitted arguments, `{}`, or an empty `args` string pass `""`; explicit text is preserved. |
| Compatible hooks | Matching lifecycle, prompt, tool, compaction, and subagent hooks. Discovery permits 50 unique hook files and eight nested directories. Command-hook stdin is capped at 1 MiB; oversized decision events fail closed. String commands use a login shell; `args` or a `command` array spawn without a shell. |
| Compatible middleware | Matching prompt-build and tool-result middleware |
| Session-start context | Turn preparation waits for an in-flight session start. A failed start warns once instead of poisoning later turns; successful start context is consumed once. Concurrent prepares cannot bypass a pending start or remove a newer one. |
| Hook command expansion | An unresolved variable blocks PreToolUse, UserPromptSubmit, and Stop decisions while preserving earlier results and running later hooks. Observer expansion failures warn and continue. Execution-error handling is unchanged. |
| Stop hook decisions | On upgrade, installed Claude Code and Codex Stop hooks with `continue: false` finish the turn rather than request revision. This takes precedence over a block on the same hook only; a separate blocking hook still requests revision in either order. Pre-tool and prompt blocking is unchanged. |
| Unsupported behavior | Recorded during generation and reported at Gateway startup |
Expand Down
6 changes: 6 additions & 0 deletions docs/compatibility.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,12 @@ Codex app connector IDs are not MCP servers and have no equivalent Babelfish run

## Hermes Agent

Turn preparation waits for the current session-start operation. A rejected start
is reported once and removed only after settling, so later turns can retain
their own context. Concurrent prepares also wait; completion of an older start
cannot remove a newer pending start or publish stale start context. Successful
start context is consumed once per session and cleared at session end.

The selected Python environment must import each installed plugin and its dependencies. Plugins that import client internals also require the source client's Python package.

```bash
Expand Down
37 changes: 37 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,43 @@ async function copyFixture(target: string): Promise<void> {
}

describe("native OpenClaw hook entry", () => {
it("consumes session-start context once and clears it on session end after reset", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "babelfish-start-context-"));
const plugin = path.join(root, "codex", "start");
vi.stubEnv("OPENCLAW_BABELFISH_ROOT", root);
vi.stubEnv("OPENCLAW_BABELFISH_HERMES_PLUGIN_DIR", path.join(root, "hermes"));
try {
await fs.mkdir(path.join(plugin, ".codex-plugin"), { recursive: true });
await fs.writeFile(path.join(plugin, "start.mjs"),
'process.stdin.resume(); process.stdin.on("end", () => console.log(JSON.stringify({systemMessage:"start context"})));');
await fs.writeFile(path.join(plugin, ".codex-plugin", "plugin.json"), JSON.stringify({
hooks: { SessionStart: [{ hooks: [{ type: "command", command: [process.execPath, "start.mjs"] }] }] },
}));
vi.resetModules();
const entry = (await import("./index.js")).default;
const hooks = new Map<string, (event: unknown, ctx: unknown) => unknown>();
entry.register({
on: (name, handler) => { hooks.set(name, handler); },
registerTool: () => undefined, registerCommand: () => undefined,
registerCli: () => undefined, registerAgentToolResultMiddleware: () => undefined,
logger: { warn: () => undefined },
});
const first = { sessionId: "first" };
const second = { sessionId: "second" };
await hooks.get("session_start")!({}, first);
await hooks.get("session_start")!({}, second);
await expect(hooks.get("agent_turn_prepare")!({}, first)).resolves.toEqual({ prependContext: "start context" });
await expect(hooks.get("agent_turn_prepare")!({}, first)).resolves.toBeUndefined();
await hooks.get("before_reset")!({}, second);
await hooks.get("session_end")!({ reason: "reset" }, second);
await expect(hooks.get("agent_turn_prepare")!({}, second)).resolves.toBeUndefined();
await hooks.get("session_end")!({}, first);
} finally {
vi.unstubAllEnvs();
await fs.rm(root, { recursive: true, force: true });
}
}, 15_000);

it.each([
["PreToolUse", "before_tool_call", { block: true }],
["UserPromptSubmit", "before_agent_run", { outcome: "block" }],
Expand Down
50 changes: 40 additions & 10 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ const UNSUPPORTED_WARNING_MIDDLEWARE = new Set([
const config = resolveConfig(undefined);
const sessionStartContext = new Map<string, string[]>();
const sessionStartPending = new Map<string, Promise<void>>();
const sessionStartOwners = new Map<string, symbol>();
const sessionStartSources = new Map<string, string>();
const promptContextByRun = new Map<string, string[]>();
const outputStyleBySession = new Map<string, GeneratedOutputStyleEntry>();
Expand Down Expand Up @@ -572,8 +573,21 @@ function registerRunHooks(api: OpenClawApi): void {
.filter((value): value is string => typeof value === "string" && value.length > 0);
const key = sessionKey(event, ctx);
if (key) {
await sessionStartPending.get(key);
sessionStartPending.delete(key);
for (;;) {
const pendingStart = sessionStartPending.get(key);
if (!pendingStart) break;
try {
await pendingStart;
} catch (error) {
if (sessionStartPending.get(key) === pendingStart) {
const detail = error instanceof Error ? error.message : String(error);
api.logger?.warn(`Babelfish session start failed: ${detail}`);
}
} finally {
// Keep concurrent prepares waiting, and never remove a newer start.
if (sessionStartPending.get(key) === pendingStart) sessionStartPending.delete(key);
}
}
}
const promptRunKey = runKey(event, ctx);
if (promptRunKey) {
Expand Down Expand Up @@ -658,8 +672,15 @@ export function registerBabelfishCli(api: OpenClawApi): void {
function registerSessionHooks(api: OpenClawApi): void {
api.on("session_start", async (event, ctx) => {
const key = sessionKey(event, ctx);
const owner = Symbol();
if (key) {
sessionStartOwners.set(key, owner);
sessionStartContext.delete(key);
}
// Enqueue Hermes start synchronously, before a concurrent turn callback.
const pending = (async () => {
await invokeHook("on_session_start", event, ctx);
if (key && sessionStartOwners.get(key) !== owner) return;
const rawEvent = record(event);
const sessionId = typeof rawEvent.sessionId === "string" ? rawEvent.sessionId : undefined;
const transitionSource = sessionId ? sessionStartSources.get(sessionId) : undefined;
Expand All @@ -670,6 +691,7 @@ function registerSessionHooks(api: OpenClawApi): void {
sessionStartSources.delete(sessionId);
}
const imported = await bundleHooks("SessionStart", event, ctx, source);
if (key && sessionStartOwners.get(key) !== owner) return;
const additional = imported
.map(hookAdditionalContext)
.filter((value): value is string => Boolean(value));
Expand All @@ -691,6 +713,8 @@ function registerSessionHooks(api: OpenClawApi): void {
});
api.on("session_end", async (event, ctx) => {
const runtimeContext = context(ctx);
const key = sessionKey(event, ctx);
const owner = key ? sessionStartOwners.get(key) : undefined;
try {
await invokeHermesHook(config, {
hook: "on_session_finalize",
Expand All @@ -711,27 +735,33 @@ function registerSessionHooks(api: OpenClawApi): void {
}
await bundleHooks("SessionEnd", event, ctx, typeof reason === "string" ? reason : "");
} finally {
const key = sessionKey(event, ctx);
if (key) {
sessionStartContext.delete(key);
sessionStartPending.delete(key);
outputStyleBySession.delete(key);
stopMonitors(key);
if (!key || sessionStartOwners.get(key) === owner) {
if (key) {
sessionStartOwners.delete(key);
sessionStartContext.delete(key);
sessionStartPending.delete(key);
outputStyleBySession.delete(key);
stopMonitors(key);
}
releaseHermesBridge(config, runtimeContext);
}
releaseHermesBridge(config, runtimeContext);
}
}
});
api.on("before_reset", async (event, ctx) => {
const runtimeContext = context(ctx);
const key = sessionKey(event, ctx);
const owner = key ? sessionStartOwners.get(key) : undefined;
try {
await invokeHermesHook(config, {
hook: "on_session_reset",
kwargs: hermesKwargs(event),
context: runtimeContext,
});
} finally {
releaseHermesBridge(config, runtimeContext);
if (!key || sessionStartOwners.get(key) === owner) {
releaseHermesBridge(config, runtimeContext);
}
}
});
}
Expand Down
Loading
Loading