@sema-agent/core
Version:
Stateless, task-oriented AI agent core
44 lines (43 loc) • 2.16 kB
JavaScript
import { deliverEngineNotice } from "../engine-notice.js";
import { createSafeNotifier, observeThenableRejection, safeErrorMessage } from "../safe-notify.js";
const FORWARD_SINK_SITE = "runtask.onForwardEvent";
const ORPHAN_SCOPES = new WeakMap();
const HOST_SINK_SENTENCE = {
run_internals: (at, cause) => `[@sema-agent/core] ${at}: run-internals sink threw (contained; further failures counted, not re-disclosed): ${cause}`,
delegation_lifecycle: (at, cause) => `[@sema-agent/core] ${at}: delegation-lifecycle observer threw (contained; further failures counted, not re-disclosed): ${cause}`,
forward: (_at, cause) => `The subagent display sink (RunInternals.onForwardEvent) failed and the frame was dropped: ${cause}. ` +
`The run is unaffected — forwarding is a render channel — and further failures of this run are counted, not repeated.`,
};
export function hostSinkNotifier(onNotice, site) {
return createSafeNotifier({
onError: (f) => {
const cause = safeErrorMessage(f.error);
deliverEngineNotice(onNotice, { code: "config.host_sink_failed", message: HOST_SINK_SENTENCE[site](f.site, cause), detail: { site, cause } });
},
});
}
export function createForwardSinkScope(onNotice) {
return { notifier: hostSinkNotifier(onNotice, "forward") };
}
function scopeOf(holder) {
if (holder.forwardScope !== undefined)
return holder.forwardScope;
const existing = ORPHAN_SCOPES.get(holder);
if (existing !== undefined)
return existing;
const scope = createForwardSinkScope(undefined);
ORPHAN_SCOPES.set(holder, scope);
return scope;
}
export function forwardSafely(holder, event) {
if (holder?.onForwardEvent === undefined)
return;
const { notifier } = scopeOf(holder);
notifier.notify(() => observeThenableRejection(holder.onForwardEvent?.(event), notifier, FORWARD_SINK_SITE), FORWARD_SINK_SITE);
}
export function forwardSinkFailures(holder) {
if (holder === undefined)
return 0;
const scope = holder.forwardScope ?? ORPHAN_SCOPES.get(holder);
return scope?.notifier.failuresAt(FORWARD_SINK_SITE) ?? 0;
}