@sema-agent/core
Version:
Stateless, task-oriented AI agent core
38 lines (37 loc) • 1.22 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 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) {
let timer;
try {
await Promise.race([
Promise.resolve().then(leg),
new Promise((_, reject) => {
timer = setTimeout(() => reject(new TeardownLegTimeoutError(label, teardownLegBudgetMs)), teardownLegBudgetMs);
}),
]);
}
catch (e) {
try {
report?.(asThrownError(e));
}
catch {
}
}
finally {
if (timer !== undefined)
clearTimeout(timer);
}
}