diff --git a/src/infra/exec-events-context.ts b/src/infra/exec-events-context.ts new file mode 100644 index 000000000..fe228e7cb --- /dev/null +++ b/src/infra/exec-events-context.ts @@ -0,0 +1,23 @@ +import { AsyncLocalStorage } from "node:async_hooks"; +import type { ExecEventContext } from "./exec-events.js"; + +const execEventContextStorage = new AsyncLocalStorage(); + +function hasContextValues(context: ExecEventContext | undefined): boolean { + if (!context) return false; + return Boolean(context.runId || context.toolCallId || context.sessionKey); +} + +export function runWithExecEventContext(context: ExecEventContext, fn: () => T): T { + const existing = execEventContextStorage.getStore(); + const shouldBypass = !hasContextValues(context) && !hasContextValues(existing); + if (shouldBypass) return fn(); + + const merged = existing ? { ...existing, ...context } : { ...context }; + return execEventContextStorage.run(merged, fn); +} + +export function getExecEventContext(): ExecEventContext | undefined { + const store = execEventContextStorage.getStore(); + return store ? { ...store } : undefined; +}