@sema-agent/core
Version:
Stateless, task-oriented AI agent core
51 lines (50 loc) • 1.73 kB
JavaScript
import { asThrownError } from "../thrown-value.js";
export const TEARDOWN_LEG_MAX_MS = 15_000;
let teardownLegBudgetMs = TEARDOWN_LEG_MAX_MS;
export function setTeardownLegBudgetForTests(ms) {
teardownLegBudgetMs = ms ?? TEARDOWN_LEG_MAX_MS;
}
export const teardownLegBudget = () => teardownLegBudgetMs;
export class TeardownLegTimeoutError extends Error {
leg;
constructor(leg, budgetMs) {
super(`teardown leg "${leg}" did not settle within ${budgetMs}ms — proceeding without it. ` +
`The leg keeps running detached; whatever it owns (process/env/store row) may be leaked until it settles on its own.`);
this.name = "TeardownLegTimeoutError";
this.leg = leg;
}
}
export async function settleTeardownLeg(leg, label, report, boundMs = teardownLegBudgetMs) {
try {
await raceTeardownLeg(leg, label, boundMs);
}
catch (e) {
try {
report?.(asThrownError(e));
}
catch {
}
}
}
export async function raceTeardownLeg(leg, label, boundMs = teardownLegBudgetMs) {
let timer;
try {
return await Promise.race([
Promise.resolve().then(leg),
new Promise((_, reject) => {
timer = setTimeout(() => reject(new TeardownLegTimeoutError(label, boundMs)), boundMs);
}),
]);
}
finally {
if (timer !== undefined)
clearTimeout(timer);
}
}
export function raceTeardownLegOr(leg, label, onTimeout, boundMs = teardownLegBudgetMs) {
return raceTeardownLeg(leg, label, boundMs).catch((e) => {
if (e instanceof TeardownLegTimeoutError && e.leg === label)
return onTimeout(e);
throw e;
});
}