Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix(hooks): await session-end flush before pi/omp/openclaw teardown (#676)

AkitaOnRails195be4e59a22
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d5be5dcc..dbec8a60 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
time. A session end now costs what it wrote, not the size of the wiki,
and the git history no longer silently misses snapshots under
concurrent sessions (#674).
+- The generated pi/omp and OpenClaw TypeScript integrations registered their
+ session-end lifecycle event (`session_shutdown` for pi/omp, `session_end`
+ for OpenClaw) with a synchronous, fire-and-forget handler. The host tears
+ down the runtime as soon as a synchronous handler returns, killing the
+ in-flight `session-end` POST before it completes, so the server never
+ learned the session had ended: `sessions.ended_at` stayed `NULL`, and no
+ summary or handoff was produced. The handlers are now `async` and await a
+ bounded (2s) drain of the pending request(s) before returning, mirroring
+ the joinable dispose-drain already used by the OpenCode integration (#676).
## [2.1.1] - 2026-09-07
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index e9648a63..c8181482 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -4114,12 +4114,14 @@ const HOOK_FLUSH_INTERVAL_MS = 2000;
const HOOK_FLUSH_THRESHOLD = 20;
const HOOK_INTER_REQUEST_DELAY_MS = 50;
const HOOK_REQUEST_TIMEOUT_MS = 2000;
+const HOOK_DISPOSE_DRAIN_BUDGET_MS = 2000;
const HOOK_IMMEDIATE_EVENTS = new Set(["session-start", "stop", "session-end", "pre-compact"]);
type HookQueueItem = {{ event: string; url: URL; payload: Record<string, unknown> }};
const hookQueue: HookQueueItem[] = [];
let hookFlushTimer: ReturnType<typeof setTimeout> | undefined;
let hookDraining = false;
+let hookDrainPromise: Promise<void> | undefined;
function sleep(ms: number): Promise<void> {{
return new Promise((resolve) => setTimeout(resolve, ms));
@@ -4129,16 +4131,37 @@ function scheduleHookFlush(): void {{
if (hookFlushTimer) return;
hookFlushTimer = setTimeout(() => {{
hookFlushTimer = undefined;
- void drainHookQueue();
+ void requestHookDrain();
}}, HOOK_FLUSH_INTERVAL_MS);
hookFlushTimer.unref?.();
}}
+function requestHookDrain(): Promise<void> {{
+ if (!hookDrainPromise) {{
+ hookDrainPromise = drainHookQueue().finally(() => {{
+ hookDrainPromise = undefined;
+ if (hookQueue.length > 0) void requestHookDrain();
+ }});
+ }}
+ return hookDrainPromise;
+}}
+
+function disposeDrainTimeout(): Promise<void> {{
+ return new Promise((resolve) => {{
+ const timer = setTimeout(resolve, HOOK_DISPOSE_DRAIN_BUDGET_MS);
+ timer.unref?.();
+ }});
+}}
+
+async function drainHookQueueForDispose(): Promise<void> {{
+ await Promise.race([requestHookDrain(), disposeDrainTimeout()]);
+}}
+
function enqueueHook(event: string, url: URL, payload: Record<string, unknown>): void {{
if (hookQueue.length >= HOOK_QUEUE_MAX) hookQueue.shift();
hookQueue.push({{ event, url, payload }});
if (HOOK_IMMEDIATE_EVENTS.has(event) || hookQueue.length >= HOOK_FLUSH_THRESHOLD) {{
- void drainHookQueue();
+ void requestHookDrain();
}} else {{
scheduleHookFlush();
}}
@@ -4169,7 +4192,6 @@ async function drainHookQueue(): Promise<void> {{
}}
}} finally {{
hookDraining = false;
- if (hookQueue.length > 0) void drainHookQueue();
}}
}}
@@ -4402,9 +4424,10 @@ export default function AiMemoryExtension(api: any): void {{
postHook("stop", sessionPayload(ctx));
}});
- api.on("session_shutdown", (_event: any, ctx: any) => {{
+ api.on("session_shutdown", async (_event: any, ctx: any) => {{
startSession(ctx);
postHook("session-end", sessionPayload(ctx));
+ await drainHookQueueForDispose();
}});
}}
"#,
@@ -8362,6 +8385,22 @@ model = "gpt-5"
.contains("projectStrategy === \"repo-root\" || projectStrategy === \"repo_root\"")
);
assert!(extension.contains("url.searchParams.set(\"project\", repoProject)"));
+ // #676: pi/omp await session_shutdown's dispose flush instead of
+ // returning immediately, so the runtime teardown that follows a sync
+ // handler no longer kills the in-flight session-end fetch.
+ assert!(extension.contains("const HOOK_DISPOSE_DRAIN_BUDGET_MS = 2000;"));
+ assert!(extension.contains("let hookDrainPromise: Promise<void> | undefined;"));
+ assert!(extension.contains("function requestHookDrain(): Promise<void>"));
+ assert!(extension.contains("function disposeDrainTimeout(): Promise<void>"));
+ assert!(extension.contains("async function drainHookQueueForDispose(): Promise<void>"));
+ assert!(
+ extension.contains("api.on(\"session_shutdown\", async (_event: any, ctx: any) => {")
+ );
+ assert!(extension.contains("await drainHookQueueForDispose();"));
+ assert!(
+ !extension.contains("api.on(\"session_shutdown\", (_event: any, ctx: any) => {"),
+ "session_shutdown must not regress to the sync fire-and-forget form: {extension}"
+ );
}
#[test]
@@ -8793,6 +8832,20 @@ model = "gpt-5"
assert!(!extension.contains(".omp"));
assert!(!extension.contains("serve --transport stdio"));
assert!(!extension.contains("serve --stdio"));
+ // #676: the pi string-transform (api.on( -> pi.on() must still
+ // produce an async session_shutdown handler that awaits the bounded
+ // dispose flush, mirroring the omp source it derives from.
+ assert!(extension.contains("const HOOK_DISPOSE_DRAIN_BUDGET_MS = 2000;"));
+ assert!(extension.contains("function requestHookDrain(): Promise<void>"));
+ assert!(extension.contains("async function drainHookQueueForDispose(): Promise<void>"));
+ assert!(
+ extension.contains("pi.on(\"session_shutdown\", async (_event: any, ctx: any) => {")
+ );
+ assert!(extension.contains("await drainHookQueueForDispose();"));
+ assert!(
+ !extension.contains("pi.on(\"session_shutdown\", (_event: any, ctx: any) => {"),
+ "session_shutdown must not regress to the sync fire-and-forget form: {extension}"
+ );
}
// Windows 11 + Git Bash support matters for regulated enterprise setups
diff --git a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
index 8401c994..75564e6a 100644
--- a/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
+++ b/crates/ai-memory-cli/src/commands/openclaw_plugin.rs
@@ -450,6 +450,28 @@ const startedSessions = new Set<string>();
const handoffChecked = new Set<string>();
const preCompactLast = new Map<string, number>();
+const HOOK_DISPOSE_DRAIN_BUDGET_MS = 2000;
+const pendingHookRequests = new Set<Promise<void>>();
+
+function trackHookRequest(request: Promise<void>): void {{
+ pendingHookRequests.add(request);
+ void request.finally(() => pendingHookRequests.delete(request));
+}}
+
+function disposeDrainTimeout(): Promise<void> {{
+ return new Promise((resolve) => {{
+ const timer = setTimeout(resolve, HOOK_DISPOSE_DRAIN_BUDGET_MS);
+ timer.unref?.();
+ }});
+}}
+
+async function drainHookQueueForDispose(): Promise<void> {{
+ await Promise.race([
+ Promise.allSettled(Array.from(pendingHookRequests)),
+ disposeDrainTimeout(),
+ ]);
+}}
+
function rememberSession(event: any, ctx: any): void {{
const id = sessionID(event, ctx);
if (!id || startedSessions.has(id)) return;
@@ -478,7 +500,9 @@ function postPreCompact(event: any, ctx: any): void {{
// Fire-and-forget, but never silent loss: an unreachable server or
// 5xx spools the event in the CLI hook-spool format for a later
// drain (#580); a delivered post opportunistically drains backlog.
- void fetch(url, {{
+ // Tracked in pendingHookRequests so session_end can await a bounded
+ // flush instead of letting teardown kill the in-flight fetch (#676).
+ const request = fetch(url, {{
method: "POST",
headers: {{ "Content-Type": "application/json", ...authHeaders() }},
body: JSON.stringify(policy.payload),
@@ -490,6 +514,7 @@ function postPreCompact(event: any, ctx: any): void {{
else requestSpoolDrain();
}})
.catch(() => undefined);
+ trackHookRequest(request);
}} catch (_e) {{
try {{ spoolFailedHook(url, policy.payload); }} catch (_e2) {{}}
}}
@@ -523,9 +548,10 @@ export default definePluginEntry({{
rememberSession(event, ctx);
}});
- api.on("session_end", (event: any, ctx: any) => {{
+ api.on("session_end", async (event: any, ctx: any) => {{
rememberSession(event, ctx);
postHook("session-end", payload(event, ctx, {{ reason: event?.reason }}));
+ await drainHookQueueForDispose();
}});
api.on("before_prompt_build", async (event: any, ctx: any) => {{
@@ -627,6 +653,19 @@ mod tests {
assert!(plugin.contains("definePluginEntry"));
assert!(plugin.contains("api.on(\"session_start\""));
assert!(plugin.contains("api.on(\"session_end\""));
+ // #676: session_end must be async and await a bounded flush of the
+ // in-flight postHook fetch, otherwise the gateway tears the plugin
+ // down before the session-end request reaches the server.
+ assert!(plugin.contains("const HOOK_DISPOSE_DRAIN_BUDGET_MS = 2000;"));
+ assert!(plugin.contains("function disposeDrainTimeout(): Promise<void>"));
+ assert!(plugin.contains("async function drainHookQueueForDispose(): Promise<void>"));
+ assert!(plugin.contains("function trackHookRequest("));
+ assert!(plugin.contains("api.on(\"session_end\", async (event: any, ctx: any) => {"));
+ assert!(plugin.contains("await drainHookQueueForDispose();"));
+ assert!(
+ !plugin.contains("api.on(\"session_end\", (event: any, ctx: any) => {"),
+ "session_end must not regress to the sync fire-and-forget form: {plugin}"
+ );
assert!(plugin.contains("api.on(\"before_prompt_build\""));
assert!(plugin.contains("api.on(\"before_tool_call\""));
assert!(plugin.contains("api.on(\"after_tool_call\""));