UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

78 lines (77 loc) • 2.38 kB
import { AsyncLocalStorage } from "node:async_hooks"; const statusSinkStore = new AsyncLocalStorage(); export function runWithStatusSink(emit, fn) { return statusSinkStore.run({ emit }, fn); } export function bindBrainStatusEmitter() { const sink = statusSinkStore.getStore(); if (sink === undefined) return () => undefined; return (status) => deliverBrainStatus(sink, status); } function deliverBrainStatus(sink, status) { try { sink.emit(withRetryDeadline(status)); } catch { } } export function emitBrainStatus(status) { const sink = statusSinkStore.getStore(); if (sink === undefined) return; deliverBrainStatus(sink, status); } function withRetryDeadline(status) { if (status.retryAtMs !== undefined) return status; const { retryInMs } = status; if (retryInMs === undefined || !Number.isFinite(retryInMs)) return status; return { ...status, retryAtMs: Date.now() + retryInMs }; } const telemetrySinkStore = new AsyncLocalStorage(); export function runWithBrainTelemetry(emit, fn) { return telemetrySinkStore.run({ emit }, fn); } export function emitBrainTelemetry(t) { try { telemetrySinkStore.getStore()?.emit(t); } catch { } } const reasoningFactsSinkStore = new AsyncLocalStorage(); export function runWithReasoningWireFacts(observe, fn) { const scope = { observe, live: true }; return reasoningFactsSinkStore.run(scope, fn).finally(() => { scope.live = false; }); } export function reportReasoningWireFacts(facts) { try { const sink = reasoningFactsSinkStore.getStore(); if (sink?.live === true) sink.observe(facts); } catch { } } const extraBodyDroppedSinkStore = new AsyncLocalStorage(); export function runWithExtraBodyDropped(observe, fn) { return extraBodyDroppedSinkStore.run({ observe }, fn); } export function reportExtraBodyDropped(report) { try { extraBodyDroppedSinkStore.getStore()?.observe(report); } catch { } } const credentialOriginRefusalSinkStore = new AsyncLocalStorage(); export function runWithCredentialOriginRefusals(observe, fn) { return credentialOriginRefusalSinkStore.run({ observe }, fn); } export function reportCredentialOriginRefusal(report) { credentialOriginRefusalSinkStore.getStore()?.observe(report); }