A higher-order function that ensures a provided function executes outside of existing method and execution contexts.
Wraps the input function to isolate its execution from any active MethodContextService or ExecutionContextService contexts,
using AsyncResource to create a new, untracked async scope when necessary.
Throws
Propagates any errors thrown by the wrapped run function during execution.
Example
// Basic usage with a simple logging function constlogMessage = (message: string) =>console.log(message); constsafeLog = beginContext(logMessage); safeLog("Hello, world!"); // Logs "Hello, world!" outside any existing contexts
Example
// Usage with an async function constfetchData = async (id: number) => { constresponse = awaitfetch(`https://api.example.com/data/${id}`); returnresponse.json(); }; constsafeFetch = beginContext(fetchData); safeFetch(42).then(data=>console.log(data)); // Fetches data in a clean context
Remarks
This utility leverages AsyncResource from Node.js’s async_hooks to create a new async scope when either
MethodContextService.hasContext() or ExecutionContextService.hasContext() returns true. This ensures the
wrapped function runs in an isolated environment, free from inherited context state, which is critical for operations
requiring a clean slate (e.g., resetting tracking in the agent swarm system). If no contexts are active, the function
executes directly without overhead. The resource.emitDestroy() call ensures proper cleanup of the async resource.
The type of the function to be wrapped, extending any function with arbitrary arguments and return type.
and executes it outside of any existing contexts if detected, otherwise runs it directly.
A higher-order function that ensures a provided function executes outside of existing method and execution contexts. Wraps the input function to isolate its execution from any active
MethodContextServiceorExecutionContextServicecontexts, usingAsyncResourceto create a new, untracked async scope when necessary.Throws
Propagates any errors thrown by the wrapped
runfunction during execution.Example
Example
Remarks
This utility leverages
AsyncResourcefrom Node.js’sasync_hooksto create a new async scope when eitherMethodContextService.hasContext()orExecutionContextService.hasContext()returns true. This ensures the wrapped function runs in an isolated environment, free from inherited context state, which is critical for operations requiring a clean slate (e.g., resetting tracking in the agent swarm system). If no contexts are active, the function executes directly without overhead. Theresource.emitDestroy()call ensures proper cleanup of the async resource.See