@sema-agent/core
Version:
Stateless, task-oriented AI agent core
75 lines (74 loc) • 2.61 kB
JavaScript
import { gatePhaseOf, occurrenceClock } from "./tool-occurrence.js";
export const TOOL_HEARTBEAT_MS = 30_000;
export const TOOL_PROGRESS_MIN_INTERVAL_MS = 1_000;
export function createToolProgressLane(push, ident, occurrences, onWork) {
let timer;
const printed = new Map();
const arm = () => {
if (timer !== undefined)
return;
timer = setInterval(beat, TOOL_HEARTBEAT_MS);
timer.unref?.();
};
const disarm = () => {
if (timer === undefined)
return;
clearInterval(timer);
timer = undefined;
};
occurrences.onOpen(arm);
const noteWork = (toolCallId, attempt, bytes) => {
if (bytes === undefined || !Number.isFinite(bytes))
return;
const last = printed.get(toolCallId);
const before = last !== undefined && last.attempt === attempt ? last.bytes : 0;
printed.set(toolCallId, { attempt, bytes });
if (bytes <= before)
return;
try {
onWork?.();
}
catch {
}
};
const mint = (body, offeredByProducer) => {
const now = occurrenceClock();
const unseen = occurrences.get(body.toolCallId) === undefined;
const occ = occurrences.ensure({ toolCallId: body.toolCallId, spelledName: body.toolName, args: undefined });
if (unseen)
occurrences.release(occ.toolCallId);
if (!unseen && now - occ.lastHeardAt < TOOL_PROGRESS_MIN_INTERVAL_MS)
return;
occurrences.heard(occ.toolCallId);
const gate = gatePhaseOf(occ);
try {
push({ type: "tool_progress", ...body, elapsedTimeSeconds: Math.floor((now - (occ.releasedAt ?? now)) / 1000), ...(gate !== undefined ? { gate } : {}), ...ident() });
}
catch {
}
if (offeredByProducer)
noteWork(occ.toolCallId, occ.attempt, body.totalBytes);
};
const emit = (body) => mint(body, true);
function beat() {
const now = occurrenceClock();
const inFlight = occurrences.live().filter((o) => o.beating);
if (inFlight.length === 0)
return disarm();
if (inFlight.every((o) => o.holds.approval > 0))
return;
for (const o of inFlight) {
if (now - o.lastHeardAt < TOOL_HEARTBEAT_MS)
continue;
mint({ toolCallId: o.toolCallId, toolName: o.spelledName }, false);
}
}
return {
emit,
clear() {
occurrences.quiesce();
disarm();
printed.clear();
},
};
}