@sema-agent/core
Version:
Stateless, task-oriented AI agent core
75 lines (74 loc) • 2.48 kB
JavaScript
import { AsyncLocalStorage } from "node:async_hooks";
const statusSinkStore = new AsyncLocalStorage();
export function runWithStatusSink(emit, fn) {
return statusSinkStore.run({ emit }, fn);
}
export function withStatusSeat(seat, fn, toolCallId) {
const outer = statusSinkStore.getStore();
if (outer === undefined)
return fn();
return statusSinkStore.run({ emit: (s) => outer.emit(s.seat === undefined ? { ...s, seat, ...(toolCallId !== undefined ? { toolCallId } : {}) } : s) }, 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 extraBodyDroppedSinkStore = new AsyncLocalStorage();
export function runWithExtraBodyDropped(observe, fn) {
return extraBodyDroppedSinkStore.run({ observe }, fn);
}
export function reportExtraBodyDropped(report) {
try {
extraBodyDroppedSinkStore.getStore()?.observe(report);
}
catch {
}
}
const credentialRefusalSinkStore = new AsyncLocalStorage();
export function runWithCredentialRefusals(observe, fn) {
return credentialRefusalSinkStore.run({ observe }, fn);
}
export function reportCredentialRefusal(report) {
credentialRefusalSinkStore.getStore()?.observe(report);
}
const capabilityWithheldSinkStore = new AsyncLocalStorage();
export function runWithCapabilityWithheld(observe, fn) {
return capabilityWithheldSinkStore.run({ observe }, fn);
}
export function reportCapabilityWithheld(report) {
capabilityWithheldSinkStore.getStore()?.observe(report);
}