@sema-agent/core
Version:
Stateless, task-oriented AI agent core
89 lines (88 loc) • 4.12 kB
JavaScript
import { hookSeatExpiredError, resolveHookTimeoutMs, runHookSeat } from "../hooks.js";
import { asThrownError } from "../thrown-value.js";
export function seamCCompactionOptions(runner, prepared) {
return {
...(runner.deps.summaryProvider
? {
summaryProvider: runner.deps.summaryProvider,
onCompaction: runner.deps.onCompaction,
maxConsecutiveProviderReuse: runner.deps.maxConsecutiveProviderReuse,
consecutiveProviderReuse: prepared.compactionReuseRef.consecutive,
}
: {}),
onCommitted: (effect) => {
if (prepared.frameSettlement.wantsEffects?.() !== true)
return;
prepared.frameSettlement.compactions.push(effect);
},
};
}
export function compactionHookOptions(runner, spec, sessionId, trigger, identity, seatBound) {
const hooks = spec.hooks ?? runner.deps.hooks;
const pre = hooks?.preCompact;
const post = hooks?.postCompact;
const seatMs = seatBound?.timeoutMs ?? resolveHookTimeoutMs(hooks?.timeoutMs);
const seatSignal = seatBound?.signal;
const withIdentity = (ctx) => identity !== undefined ? { ...ctx, identity } : ctx;
return {
trigger,
...(pre
? {
preCompact: async (rawCtx) => {
const ctx = withIdentity(rawCtx);
const report = (err) => {
try {
runner.deps.onError?.(err, { phase: "hook", sessionId });
}
catch {
}
};
try {
const seat = await runHookSeat("preCompact", { timeoutMs: seatMs, ...(seatSignal !== undefined ? { signal: seatSignal } : {}) }, (sig) => pre.call(hooks, { ...ctx, signal: sig }));
if (seat.expired) {
report(hookSeatExpiredError("preCompact", seatMs, seat.cause, `the "${ctx.trigger}" compaction PROCEEDED unblocked and with no additional instructions`));
return undefined;
}
const r = seat.value;
if (r?.block && ctx.trigger === "forced") {
report(new Error(`a preCompact callback blocked a "forced" compaction — ignored (PTL/trim-pressure compaction is not optional): ${r.block}`));
}
return r;
}
catch (err) {
report(asThrownError(err));
return undefined;
}
},
}
: {}),
...(post
? {
postCompact: async (rawCtx) => {
try {
const seat = await runHookSeat("postCompact", { timeoutMs: seatMs, ...(seatSignal !== undefined ? { signal: seatSignal } : {}) }, (sig) => post.call(hooks, { ...withIdentity(rawCtx), signal: sig }));
if (seat.expired) {
try {
runner.deps.onError?.(hookSeatExpiredError("postCompact", seatMs, seat.cause, "the observation was abandoned; the compaction that already landed is unchanged"), { phase: "hook", sessionId });
}
catch {
}
}
}
catch (err) {
try {
runner.deps.onError?.(asThrownError(err), { phase: "hook", sessionId });
}
catch {
}
}
},
}
: {}),
};
}
export function recordCompactionReuse(runner, prepared, comp) {
if (!runner.deps.summaryProvider || !comp.compacted)
return;
prepared.compactionReuseRef.consecutive = comp.reused ? prepared.compactionReuseRef.consecutive + 1 : 0;
}