@sema-agent/core
Version:
Stateless, task-oriented AI agent core
166 lines (165 loc) • 10.9 kB
JavaScript
import { openSystemReminder } from "../reminder-mint.js";
import { formatHookFeedback } from "../hooks.js";
import { deliverEngineNotice } from "../engine-notice.js";
import { foreignLine } from "../protocol-http-auth.js";
import { classicEventBase, legEventsOf } from "../mods/stations.js";
import { judgeStopFamily, stopFamilyBlockText, stopFamilyContextText, stopFamilyWord, teammateStopPass } from "../mods/teammate-stations.js";
import { heldInProgress } from "../../tools/task-list.js";
import { steeringPreview } from "./steering-preview.js";
import { ceilingTurnNote, stopTailWaitedFor } from "./stop-tail-notice.js";
import { taskAxisCrossed } from "./clock-and-limits.js";
import { oneShotEndingBook, oneShotWaitCeilingOf } from "../task-notification.js";
import { FINAL_VERIFICATION_MARK } from "./clock-and-limits.js";
export function finalVerificationFrame(which, prepared) {
const body = prepared.engineText(which === "nudge" ? "core/event.final-verification" : "core/event.final-verification.reentry");
return `${openSystemReminder(prepared.reminderMark)}${FINAL_VERIFICATION_MARK} ${body}</system-reminder>`;
}
const STOP_HOOK_BLOCK_CAP = 8;
export function runStopAndFinalVerify(input) {
const { spec, prepared, queue, rs, stats, ident, walltimeMonotonicDeadline, deliveryObligations, callerStop, runner } = input;
const stopEvent = legEventsOf(prepared.hookIdentity).stop;
const stopArmed = prepared.modBus.hasHandlers(stopEvent);
const teammateArmed = prepared.hookIdentity.isDelegatedChild && prepared.hookIdentity.spawnName !== undefined && (prepared.modBus.hasHandlers("classic.TaskCompleted") || prepared.modBus.hasHandlers("classic.TeammateIdle"));
const reportFault = (err) => void runner.deps.onError?.(err, { phase: "hook", sessionId: prepared.sessionId });
const finalVerificationOn = spec.finalVerification === true;
const finalVerifyBudgetFill = () => {
let worst = 0;
if (rs.budget.maxTokensWindow !== undefined && rs.budget.maxTokensWindow > 0)
worst = Math.max(worst, stats.tokens / rs.budget.maxTokensWindow);
if (rs.budget.maxCostMicroUsd !== undefined && rs.budget.maxCostMicroUsd > 0)
worst = Math.max(worst, stats.costMicroUsd / rs.budget.maxCostMicroUsd);
if (walltimeMonotonicDeadline !== undefined && prepared.suspendForResource === undefined) {
const windowMs = walltimeMonotonicDeadline - rs.telemetry.taskStartMonotonic;
if (windowMs > 0)
worst = Math.max(worst, (performance.now() - rs.telemetry.taskStartMonotonic) / windowMs);
}
return worst;
};
const emitFinalVerifyEcho = (body) => {
queue.push({ type: "steering_injected", source: "final_verification", preview: steeringPreview(body), ...ident() });
};
const owed = oneShotEndingBook(spec.oneShot, deliveryObligations);
if (stopArmed || teammateArmed || finalVerificationOn || owed !== undefined) {
let consecutiveBlocks = 0;
let ceilingTurnGiven = false;
const ending = () => prepared.abortController.signal.aborted || prepared.pausedRef.current !== undefined || prepared.batchHaltRef.current !== undefined || taskAxisCrossed(rs.limits, walltimeMonotonicDeadline);
prepared.harness.setStopGate(async () => {
if (ending())
return [];
const pushedBack = stopArmed || teammateArmed || finalVerificationOn ? await pushBack() : [];
const waitEnd = pushedBack.length === 0 ? await owed?.waitOut(AbortSignal.any([prepared.abortController.signal, callerStop.signal]), () => !ending() && prepared.harness.pendingInjectionCount() === 0, (wake) => prepared.harness.subscribe((e) => void (e.type === "queue_update" && wake())), oneShotWaitCeilingOf(spec.limits)) : undefined;
if (waitEnd === "signal")
prepared.harness.consumeStopAtEnding();
if (waitEnd === "ceiling" && prepared.runLedgerBook !== undefined && !ceilingTurnGiven && owed !== undefined) {
ceilingTurnGiven = true;
return [{ role: "user", engineMinted: true, content: ceilingTurnNote(stopTailWaitedFor(owed, { read: { ...prepared.registryAccess, sessionId: prepared.sessionId }, owner: prepared.registryAccess }), oneShotWaitCeilingOf(spec.limits)), timestamp: Date.now() }];
}
return pushedBack;
});
async function pushBack() {
if (finalVerificationOn &&
(rs.counters.finalVerifyInjections === 0 || (rs.counters.finalVerifyInjections === 1 && rs.counters.groundingSignalPreR9 && !rs.counters.groundingSignalPostR9)) &&
rs.counters.wroteThisRun &&
prepared.outputRef.set !== true &&
!(rs.limits.effectiveMaxTurns !== undefined && rs.limits.effectiveMaxTurns > 0 && stats.turns >= rs.limits.effectiveMaxTurns - 1) &&
finalVerifyBudgetFill() < 0.9) {
rs.counters.finalVerifyInjections += 1;
if (rs.counters.finalVerifyInjections === 2) {
const reentryBody = finalVerificationFrame("reentry", prepared);
emitFinalVerifyEcho(reentryBody);
return [
{
role: "user",
engineMinted: true,
content: reentryBody,
timestamp: Date.now(),
},
];
}
const nudgeBody = finalVerificationFrame("nudge", prepared);
emitFinalVerifyEcho(nudgeBody);
return [
{
role: "user",
engineMinted: true,
content: nudgeBody,
timestamp: Date.now(),
},
];
}
if (stopArmed) {
const e = {
...classicEventBase(prepared.hookIdentity, prepared.permissionMode.observed),
stopHookActive: consecutiveBlocks > 0,
consecutiveBlocks,
getBranch: () => prepared.session.getBranch(),
backgroundTasks: () => prepared.listBackgroundTasks(),
};
const verdict = await judgeStopFamily(prepared.modBus, stopEvent, e, prepared.abortController.signal, reportFault);
if (verdict === "aborted" || prepared.abortController.signal.aborted)
return [];
if (verdict.answer.end !== undefined)
return endStopPoint(stopEvent, verdict, verdict.answer.end);
const messages = fedBack(stopEvent, verdict.answer);
if (messages.length > 0)
return pushedBackWith(stopEvent, messages);
}
const raises = teammateArmed
? await teammateStopPass({ bus: prepared.modBus, identity: prepared.hookIdentity, permissionMode: () => prepared.permissionMode.observed, report: reportFault, signal: prepared.abortController.signal, held: (owner) => heldInProgress(spec.tools, (name) => prepared.tools.some((t) => t.name === name), owner) })
: undefined;
if (raises === "aborted" || prepared.abortController.signal.aborted)
return [];
if (raises !== undefined) {
const ended = raises.find((r) => r.verdict.answer.end !== undefined);
if (ended !== undefined)
return endStopPoint(ended.event, ended.verdict, ended.verdict.answer.end ?? "");
const pushing = raises.filter((r) => fedBack(r.event, r.verdict.answer).length > 0);
if (pushing.length > 0)
return pushedBackWith(pushing[0].event, pushing.flatMap((r) => fedBack(r.event, r.verdict.answer)));
}
consecutiveBlocks = 0;
return [];
}
function endStopPoint(event, verdict, reason) {
announceStopEnded(event, verdict.ended?.seat ?? "task", verdict.ended?.registration, reason, verdict.ended?.taskContinueDropped === true);
consecutiveBlocks = 0;
return [];
}
function fedBack(event, result) {
const reminder = (text) => ({
role: "user",
engineMinted: true,
content: formatHookFeedback(text, prepared.reminderMark),
timestamp: Date.now(),
});
return [
...(result.additionalContext ? [reminder(stopFamilyContextText(event, result.additionalContext))] : []),
...(result.block ? [reminder(stopFamilyBlockText(event, result.block))] : []),
];
}
function pushedBackWith(event, messages) {
consecutiveBlocks++;
const cap = STOP_HOOK_BLOCK_CAP;
if (consecutiveBlocks > cap) {
runner.deps.onError?.(new Error(`a ${stopFamilyWord(event)} hook kept the turn from ending ${consecutiveBlocks} consecutive times — overriding and ending the run. ` +
`Both a block and an additionalContext-only push-back count (CC 2.1.220). ` +
`Check ctx.stopHookActive in the hook and return success while it's true.`), { phase: "hook", sessionId: prepared.sessionId });
return [];
}
return messages;
}
function announceStopEnded(event, seat, registration, reason, taskContinueDropped) {
const said = reason.trim().length > 0 ? foreignLine(reason) : undefined;
const who = registration !== undefined ? `extension "${registration}"` : "an extension";
const where = stopEvent === "classic.SubagentStop" ? "the sub-agent's" : "the run's";
const tail = `the run is not pushed back to continue from this stop point${said !== undefined ? ` — ${said}` : ""}`;
const detail = { event, ...(registration !== undefined ? { registration } : {}), seat, ...(said !== undefined ? { reason: said } : {}), ...prepared.legNotice.route.address, runId: prepared.runId };
if (taskContinueDropped) {
deliverEngineNotice(runner.deps.onNotice, { code: "mods.stop_continue_dropped", message: `${who} on the deployment seat answered end at ${where} stop point, and the task seat's own request to continue (its block or additional context) was dropped: ${tail}`, detail }, prepared.legNotice.admission);
return;
}
deliverEngineNotice(runner.deps.onNotice, { code: "mods.stop_ended", message: `${who} on the ${seat} seat answered end at ${where} stop point: ${tail}`, detail }, prepared.legNotice.admission);
}
}
return {};
}