UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

774 lines • 51.5 kB
import { compactionKindOf } from "../task-notification.js";
import { mintSystemReminder } from "../reminder-mint.js";
import { eventDefaultOn } from "../../prompt-assembly/event-registry.js";
import { compactionFailureCause, compactionFailureReason, compactionPassReport, compactionCutOf, DEFAULT_COMPACTION_INSTRUCTIONS, manualCompactOutcomeOf, turnCutWhileLegRuns, maybeCompact, measureContext, mintCompactedEvent, nextTrimForceBackoff, recordCompactionAndCheckRapidRefill } from "../auto-compaction.js";
import { emitTrace } from "../trace.js";
import { compactionEnabled } from "../context-settings.js";
import { steeringPreview } from "./steering-preview.js";
import { answerSettled } from "./assemble-result.js";
import { composeBundle } from "../attachment-source.js";
import { instructionEchoTo } from "./nested-memory-lane.js";
import { ATTACHMENT_BYTE_CAP, TOTAL_TOKENS_REMINDER_DEFAULT_MODE, attachmentEnvelopeTags, changedFilesNoticeIn, clipToBytes, collectDateChange, collectDueAttachments, commitAgentListing, commitSkillsListing, isIntactSource, rebaseCadenceWindows, renderAgentListingFrame, renderMcpInstructionsDelta, selectMcpDroppedBatch, renderSkillsListingFrame } from "./turn-attachments.js";
import { boundaryReminderInputs } from "./boundary-reminders.js";
import { announceWhenCarried, scanChangedFiles } from "./changed-files-scan.js";
import { announceListingTruncation } from "../skill-listing-budget.js";
import { buildWorkingFileAttachments, centerAdoptionOption, emitInputTruncated, forkContextOption, legCompactionSettings, legContextOverlayOption } from "./compaction-call-options.js";
import { classicEventBase, dispatchClassic, seatHears, stringMembersAnswer, stringMembersOf } from "../mods/stations.js";
import { offeredAgentListing } from "../mods/agent-stations.js";
import { measureSession, raiseCompletedTurn } from "../mods/lifecycle-stations.js";
import { sanitizeUntrustedText, SHELLED_BODY_ENVELOPE_TAGS } from "../untrusted-text.js";
import { droppedToolDigest, withAnnounceDigests } from "./announce-once-ledger.js";
import { formatDiagnosticsBlock, withholdListedDiagnostics } from "../lsp-diagnostics.js";
import { workflowSizeGuidelineChangeNotice } from "../../orchestration/workflow-size-guideline.js";
import { requesterOf } from "../mods/session-compact.js";
import { costFigureOf } from "./side-call-account.js";
import { awaitChargeWithSlowDisclosure, discloseUnevaluableWindow, discloseWindowBelowOverhead, ENV_DUE_GOVERNANCE_READ_BUDGET_MS, GOVERNANCE_READ_STALLED, LIMIT_APPROACH_DEFAULT_THRESHOLDS, LIMIT_APPROACH_MIN_TURNS, limitApproachFrames, platformLimitTerminal, raceUntilDeadline, taskAxisCrossed } from "./clock-and-limits.js";
import { appendBoundaryFrames, compactionRestateOptions, frameCarried } from "./compaction-restate.js";
import { COMPACTION_FREED_EPSILON, COMPACTION_REGROWTH_FACTOR, MAX_CONSECUTIVE_COMPACTION_FAILURES } from "./compaction-knobs.js";
import { compactionHookOptions, recordCompactionReuse, seamCCompactionOptions } from "./compaction-seams.js";
import { contextUsageSections } from "../../prompt-assembly/section-usage.js";
import { asThrownError } from "../thrown-value.js";
import { boundaryYield } from "./boundary-yield.js";
const BATCH_CONTEXT_MIN_KEEP_BYTES = 160;
const BATCH_TRUNCATION_MARKER = "\n…[truncated]";
function consumeDelivered(pending, delivered) {
    for (const d of delivered) {
        const at = pending.indexOf(d);
        if (at !== -1)
            pending.splice(at, 1);
    }
}
export function createTurnBoundary(input) {
    const { prepared, stats, rs, deps } = input;
    const { spec, legYield, queue, loopLatch: { callerStop }, manualCompactRef, todoToolMounted, taskToolsMounted, walltimeMonotonicDeadline, timeout, ident, postToolBatchArmed, batchArgs, compactionBrain, withinTaskCompaction, compactionBreaker, rapidRefill, drainManualCompact, runnerHooks, runner, display } = deps;
    let finalVerifySeenAtLastBoundary = 0;
    let legContinues = true;
    const yieldAsk = boundaryYield({ spec, legYield, prepared, rs, stats, onError: () => runnerHooks.onError });
    const boundaryPass = async (event) => {
        const shown = display?.settled();
        if (shown !== undefined)
            await shown;
        if (rs.turn.completed !== undefined)
            await prepared.compactStation.window((request) => compactInPlace(event.model, request), () => raiseCompletedTurn(prepared.modBus, rs.turn, prepared.hookIdentity, prepared.abortController.signal));
        if (rs.limits.platformTerminal !== undefined)
            return void (legContinues = false);
        const turnOwesRequest = event.continues;
        const legOwesTurn = () => turnOwesRequest || !answerSettled(event.message, prepared.harness.pendingInjectionCount() > 0);
        let boundarySteered = false;
        const noNextRequest = () => prepared.stopRequestedRef.current || deps.loopLatch.userHalted;
        const firstTry = yieldAsk.first();
        const firstAsk = firstTry === undefined || typeof firstTry === "string" ? firstTry : await firstTry;
        if (firstAsk === "ended")
            return void (legContinues = false);
        let platformCause;
        let platformRetryAfterMs;
        if (prepared.pausedRef.current === undefined && !prepared.abortController.signal.aborted) {
            const ledgerReadDeadline = prepared.envLifetimeSuspendAt !== undefined ? prepared.envLifetimeSuspendAt + ENV_DUE_GOVERNANCE_READ_BUDGET_MS : undefined;
            if (prepared.usageGovernance !== undefined) {
                const governance = prepared.usageGovernance;
                try {
                    const at = Date.now();
                    await awaitChargeWithSlowDisclosure(governance.commit(stats.tokens, costFigureOf(rs.telemetry, stats.costMicroUsd), at), () => runnerHooks.onError?.(new Error("the usage ledger CHARGE has not settled after 10s — still waiting (a charge is never abandoned: walking away would double-charge on the end-of-task flush). A wedged ledger store wedges this boundary, now visibly."), { phase: "config", sessionId: prepared.sessionId }));
                    const windowRead = governance.check(at);
                    let answer;
                    if (ledgerReadDeadline !== undefined) {
                        answer = await raceUntilDeadline(windowRead, ledgerReadDeadline);
                        if (answer === GOVERNANCE_READ_STALLED) {
                            void windowRead.catch((lateErr) => {
                                try {
                                    runnerHooks.onError?.(asThrownError(lateErr), { phase: "config", sessionId: prepared.sessionId });
                                }
                                catch {
                                }
                            });
                            try {
                                runnerHooks.onError?.(new Error("the usage ledger did not answer before the execution environment's suspend deadline — stopping for the environment, the cause this run can still prove. The window state for this boundary is UNKNOWN and was not enforced."), { phase: "config", sessionId: prepared.sessionId });
                            }
                            catch {
                            }
                        }
                    }
                    else {
                        answer = await windowRead;
                    }
                    if (answer !== GOVERNANCE_READ_STALLED) {
                        platformRetryAfterMs = answer;
                        if (platformRetryAfterMs !== undefined)
                            platformCause = "usage_window";
                    }
                }
                catch (govErr) {
                    rs.limits.turnsExceeded = false;
                    rs.limits.platformTerminal = asThrownError(govErr);
                    void prepared.harness.abort();
                    prepared.abortController.abort();
                    legContinues = false;
                    return undefined;
                }
            }
            if (platformCause === undefined && prepared.envLifetimeSuspendAt !== undefined && Date.now() >= prepared.envLifetimeSuspendAt) {
                platformCause = "env_lifetime";
            }
        }
        if (platformCause !== undefined) {
            const platformSpend = { costMicroUsd: stats.costMicroUsd, tokens: stats.tokens, turns: stats.turns, walltimeMs: Math.round(performance.now() - rs.telemetry.taskStartMonotonic) };
            const committed = prepared.suspendForPlatformLimit !== undefined &&
                (await prepared.suspendForPlatformLimit(platformCause, platformSpend, platformRetryAfterMs !== undefined ? { resumeAfterMs: platformRetryAfterMs } : undefined)).tag === "committed";
            if (committed) {
                rs.limits.turnsExceeded = false;
                rs.limits.budgetHit = undefined;
                legContinues = false;
                return undefined;
            }
            const terminal = platformLimitTerminal(platformCause, platformRetryAfterMs);
            rs.limits.platformTerminal = terminal;
            try {
                runnerHooks.onError?.(terminal, { phase: "config", sessionId: prepared.sessionId });
            }
            catch {
            }
            void prepared.harness.abort();
            prepared.abortController.abort();
            legContinues = false;
            return undefined;
        }
        const axisCrossed = taskAxisCrossed(rs.limits, walltimeMonotonicDeadline);
        if (rs.limits.walltimeCrossedMs === undefined && walltimeMonotonicDeadline !== undefined && performance.now() >= walltimeMonotonicDeadline)
            rs.limits.walltimeCrossedMs = Math.ceil(performance.now() - rs.telemetry.taskStartMonotonic);
        const taskAxisHit = axisCrossed && legOwesTurn();
        if (axisCrossed)
            legContinues = false;
        if (prepared.suspendForResource && taskAxisHit && prepared.pausedRef.current === undefined) {
            const reason = rs.limits.budgetHit !== undefined
                ? rs.limits.budgetAxis === "tokens"
                    ? "budget_tokens"
                    : "budget_cost"
                : rs.limits.turnsExceeded
                    ? "turns"
                    : "walltime";
            const sliceSpend = { costMicroUsd: stats.costMicroUsd, tokens: stats.tokens, turns: stats.turns, walltimeMs: Math.round(performance.now() - rs.telemetry.taskStartMonotonic) };
            if ((await prepared.suspendForResource(reason, sliceSpend)).tag === "committed") {
                rs.limits.turnsExceeded = false;
                rs.limits.budgetHit = undefined;
            }
            else {
                void prepared.harness.abort();
                prepared.abortController.abort();
            }
            legContinues = false;
            return undefined;
        }
        if (walltimeMonotonicDeadline !== undefined &&
            prepared.suspendForResource === undefined &&
            performance.now() >= walltimeMonotonicDeadline) {
            if (!timeout.fired) {
                timeout.fired = true;
                timeout.clear();
                timeout.latenessMs = Math.max(timeout.latenessMs ?? 0, performance.now() - walltimeMonotonicDeadline);
                rs.counters.walltimeSyncBackstopFired = true;
                void prepared.harness.abort();
                prepared.abortController.abort();
            }
            legContinues = false;
            return undefined;
        }
        const approachCfg = spec.limits?.approachNotice;
        const approachRef = prepared.limitApproachRef;
        if (approachCfg !== false && prepared.suspendForResource === undefined) {
            const thresholds = approachCfg?.at ?? LIMIT_APPROACH_DEFAULT_THRESHOLDS;
            const ratios = [];
            const spendFill = prepared.spend.fill();
            if (spendFill !== undefined)
                ratios.push({ axis: spendFill.axis, ratio: spendFill.ratio });
            const declaredMaxTurns = spec.limits?.maxTurns;
            if (declaredMaxTurns !== undefined && declaredMaxTurns >= LIMIT_APPROACH_MIN_TURNS) {
                ratios.push({ axis: "turns", ratio: (stats.turns + 1) / declaredMaxTurns });
            }
            if (walltimeMonotonicDeadline !== undefined) {
                const walltimeWindowMs = walltimeMonotonicDeadline - rs.telemetry.taskStartMonotonic;
                if (walltimeWindowMs > 0) {
                    ratios.push({ axis: "walltime", ratio: (performance.now() - rs.telemetry.taskStartMonotonic) / walltimeWindowMs });
                }
            }
            let tightest;
            for (const r of ratios)
                if (tightest === undefined || r.ratio > tightest.ratio)
                    tightest = r;
            const index = tightest === undefined ? undefined : tightest.ratio >= thresholds[1] ? 1 : tightest.ratio >= thresholds[0] ? 0 : undefined;
            if (tightest !== undefined && index !== undefined && index > (approachRef.crossed?.index ?? -1)) {
                const percent = Math.min(100, Math.round(tightest.ratio * 100));
                const text = limitApproachFrames(index, tightest.axis, percent, prepared.reminderMark, prepared.engineText);
                const preview = steeringPreview(text);
                approachRef.crossed = {
                    index,
                    text,
                    announce: () => {
                        rs.counters.approachNoticesSent += 1;
                        queue.push({ type: "steering_injected", source: "limit_approach", preview, ...ident() });
                    },
                };
            }
        }
        const pendingReview = prepared.reviewRequestRef.pending;
        if (pendingReview !== undefined) {
            prepared.reviewRequestRef.pending = undefined;
            prepared.reviewRequestRef.later = undefined;
            const honorable = prepared.suspendForReview !== undefined &&
                !prepared.abortController.signal.aborted &&
                prepared.pausedRef.current === undefined;
            if (honorable && prepared.suspendForReview) {
                await prepared.suspendForReview(pendingReview);
                legContinues &&= !prepared.abortController.signal.aborted && prepared.pausedRef.current === undefined;
                return undefined;
            }
            emitTrace(rs.telemetry.tracer, () => ({ kind: "review.dropped", version: 1, taskId: rs.telemetry.taskId, ts: Date.now() }));
        }
        const againTry = firstTry === undefined ? yieldAsk.again(turnOwesRequest && legContinues && !noNextRequest() && prepared.batchHaltRef.current === undefined) : undefined;
        if (againTry !== undefined && (await againTry) === "ended")
            return void (legContinues = false);
        if (!noNextRequest() && !prepared.abortController.signal.aborted)
            await appendBoundaryFrames(prepared, turnOwesRequest);
        if (prepared.lspDiagnostics &&
            !prepared.lspDiagnostics.registry.isEmpty() &&
            turnOwesRequest &&
            !prepared.abortController.signal.aborted &&
            prepared.batchHaltRef.current === undefined) {
            const files = await withholdListedDiagnostics(prepared.lspDiagnostics.registry.drain(prepared.lspDiagnostics.runIdent), prepared.lspDiagnostics.withheldOf);
            if (files.length > 0) {
                queue.push({ type: "diagnostics", files, isNew: true, ...ident() });
                const block = mintSystemReminder(formatDiagnosticsBlock(files), prepared.reminderMark);
                void prepared.harness.steer(block, { provenance: "engine-note" }).catch(() => undefined);
                boundarySteered = true;
            }
        }
        let boundaryAttachmentBytes = 0;
        let attachmentsBundle;
        let changedNotice;
        let nestedLoad;
        const recordSteps = new Map();
        const bundleReceipts = [];
        const carried = (source) => frameCarried(prepared.frameReceipts, source);
        if ((rs.attach.dateState !== undefined ||
            rs.attach.sizeGuidelineState !== undefined ||
            rs.attach.attachState !== undefined ||
            prepared.nestedMemory !== undefined) &&
            turnOwesRequest &&
            !boundarySteered &&
            prepared.batchHaltRef.current === undefined &&
            !noNextRequest() &&
            rs.counters.finalVerifyInjections === 0 &&
            !prepared.abortController.signal.aborted) {
            const due = [];
            if (rs.attach.attachState !== undefined) {
                const attachState = rs.attach.attachState;
                const changedScan = scanChangedFiles({ cfg: rs.attach.attachmentsCfg, detect: prepared.detectExternalChanges, ledger: prepared.frameReceipts });
                const changed = changedScan === undefined ? undefined : await changedScan;
                const backgroundTasksOn = (rs.attach.attachmentsCfg?.backgroundTasks ?? eventDefaultOn("background_tasks")) === true && !carried("background_tasks");
                const bgTasks = backgroundTasksOn && rs.attach.attachState.postCompactPending ? prepared.listBackgroundTasks() : undefined;
                const toolsDeltaOn = rs.attach.attachmentsCfg?.toolsDelta === true && !carried("tools_delta");
                const tdRef = toolsDeltaOn ? prepared.toolsDeltaRef : undefined;
                const pendingTools = tdRef !== undefined && tdRef.pending.length > 0 ? [...tdRef.pending] : undefined;
                const pendingRemovedTools = tdRef !== undefined && tdRef.pendingRemoved.length > 0 ? [...tdRef.pendingRemoved] : undefined;
                const pendingReaddedTools = tdRef !== undefined && tdRef.pendingReadded.length > 0 ? [...tdRef.pendingReadded] : undefined;
                const mcpToolsDelta = pendingRemovedTools !== undefined || pendingReaddedTools !== undefined
                    ? {
                        ...(pendingRemovedTools !== undefined ? { removed: pendingRemovedTools } : {}),
                        ...(pendingReaddedTools !== undefined ? { readded: pendingReaddedTools } : {}),
                    }
                    : undefined;
                const mcpInstructionsOn = rs.attach.attachmentsCfg?.mcpInstructions === true;
                const mcpDelta = prepared.mcp.instructionsDelta;
                const mcpAdds = mcpInstructionsOn && mcpDelta.pendingAdds.length > 0 ? [...mcpDelta.pendingAdds] : undefined;
                const mcpRemovals = mcpInstructionsOn && mcpDelta.pendingRemovals.length > 0 ? [...mcpDelta.pendingRemovals] : undefined;
                const mcpDropped = mcpInstructionsOn && !carried("mcp_dropped_tools") && prepared.mcp.droppedTools.length > 0 ? selectMcpDroppedBatch(prepared.mcp.droppedTools, prepared.engineText) : undefined;
                const budgetUsdOn = rs.attach.attachmentsCfg?.budgetUsd === true && rs.budget.maxCostMicroUsd !== undefined;
                const totalTokensDeclared = rs.attach.attachmentsCfg?.totalTokensReminder;
                const totalTokensMode = rs.attach.attachmentsCfg?.totalTokensReminderMode ?? TOTAL_TOKENS_REMINDER_DEFAULT_MODE;
                const totalTokensArmedByDefault = totalTokensDeclared === undefined &&
                    eventDefaultOn("total_tokens_reminder") &&
                    totalTokensMode !== "fixed" &&
                    totalTokensMode !== "infinite";
                const totalTokensOn = totalTokensDeclared === true || totalTokensArmedByDefault;
                const toolSearchReminderOn = rs.attach.attachmentsCfg?.toolSearchReminder === true && prepared.deferredToolNames !== undefined && !carried("tool_search_usage_reminder");
                const undiscoveredTools = toolSearchReminderOn
                    ? [...prepared.deferredToolNames].filter((n) => !prepared.activeTools.has(n)).sort()
                    : undefined;
                const agentListingOwed = rs.attach.agentListingOn && prepared.agentListing !== undefined && !frameCarried(prepared.frameReceipts, "agent_listing");
                const offeredListing = !agentListingOwed ? undefined : seatHears({ bus: prepared.modBus }, "agent.offer") ? await offeredAgentListing({ bus: prepared.modBus }, prepared.agentListing, prepared.abortController.signal) : prepared.agentListing;
                const skillsListingDue = rs.attach.skillsListingOn && prepared.skillsListing !== undefined && !frameCarried(prepared.frameReceipts, "skills_listing");
                const listingBudget = prepared.skillsListing?.budget ?? prepared.agentListing?.budget;
                const reminderLane = prepared.runTimeReminders.lane;
                const { silentTurn, elapsedMs } = await boundaryReminderInputs({ ...prepared.runTimeReminders, carried, rows: async () => (await prepared.session.buildContext()).messages });
                due.push(...collectDueAttachments(rs.attach.attachState, {
                    engineText: prepared.engineText,
                    turn: stats.turns,
                    cadenceTurn: rs.counters.cadenceTurns,
                    todoMounted: todoToolMounted,
                    taskListMounted: taskToolsMounted,
                    config: {
                        todoReminder: rs.attach.attachmentsCfg?.todoReminder === true && !carried("todo_reminder") && !carried("task_reminder"),
                        ...(rs.attach.attachmentsCfg?.todoReminderMode !== undefined ? { todoReminderMode: rs.attach.attachmentsCfg.todoReminderMode } : {}),
                        toolSearchReminder: toolSearchReminderOn,
                        changedFiles: changed !== undefined,
                        budgetUsd: budgetUsdOn,
                        totalTokensReminder: totalTokensOn,
                        ...(rs.attach.attachmentsCfg?.totalTokensReminderMode !== undefined
                            ? { totalTokensReminderMode: rs.attach.attachmentsCfg.totalTokensReminderMode }
                            : {}),
                        silentTurnReminder: reminderLane.silentTurn,
                        elapsedTimeReminder: elapsedMs !== undefined,
                        backgroundTasks: backgroundTasksOn,
                        toolsDelta: toolsDeltaOn,
                        agentListing: rs.attach.agentListingOn,
                        skillsListing: rs.attach.skillsListingOn,
                        mcpInstructions: mcpInstructionsOn,
                    },
                    ...(prepared.outputStyleFrame !== undefined && !frameCarried(prepared.frameReceipts, "output_style") ? { outputStyle: prepared.outputStyleFrame } : {}),
                    ...(silentTurn !== undefined ? { silentTurn } : {}),
                    ...(elapsedMs !== undefined ? { elapsedMs } : {}),
                    ...(undiscoveredTools !== undefined && undiscoveredTools.length > 0
                        ? { undiscoveredTools, deferDirectCall: prepared.deferDirectCall }
                        : {}),
                    ...(changed !== undefined ? { changedFiles: changed } : {}),
                    ...(budgetUsdOn && rs.budget.maxCostMicroUsd !== undefined
                        ? { budgetUsd: { used: stats.costMicroUsd / 1e6, total: rs.budget.maxCostMicroUsd / 1e6 } }
                        : {}),
                    ...(totalTokensOn && rs.budget.maxTokensWindow !== undefined
                        ? { totalTokens: { used: stats.tokens, total: rs.budget.maxTokensWindow } }
                        : {}),
                    ...(bgTasks !== undefined ? { backgroundTasks: bgTasks } : {}),
                    ...(pendingTools !== undefined ? { newTools: pendingTools } : {}),
                    ...(prepared.toolMaterializeStatic ? { newToolsStaticFace: true } : {}),
                    ...(prepared.toolMaterializeStatic && pendingTools !== undefined
                        ? { newToolsSwappedUnderStatic: pendingTools.filter((n) => prepared.staticFaceFor?.(n) !== true) }
                        : {}),
                    ...(prepared.toolMaterializeStatic && pendingReaddedTools !== undefined
                        ? { readdedToolsSwappedUnderStatic: pendingReaddedTools.filter((n) => prepared.staticFaceFor?.(n) !== true) }
                        : {}),
                    ...(mcpToolsDelta !== undefined ? { mcpToolsDelta } : {}),
                    ...(offeredListing !== undefined
                        ? {
                            agentListing: offeredListing.entries,
                            agentToolName: offeredListing.toolName,
                            ...(offeredListing.models !== undefined ? { agentModels: offeredListing.models } : {}),
                        }
                        : {}),
                    ...(skillsListingDue ? { skillsListing: prepared.skillsListing.entries } : {}),
                    ...(listingBudget !== undefined ? { listingBudget } : {}),
                    ...(mcpAdds !== undefined || mcpRemovals !== undefined
                        ? { mcpInstructions: { added: mcpAdds ?? [], removed: mcpRemovals ?? [] } }
                        : {}),
                    ...(mcpDropped !== undefined ? { mcpDroppedTools: mcpDropped } : {}),
                }));
                if ((pendingTools !== undefined || mcpToolsDelta !== undefined) && due.some((a) => a.source === "tools_delta")) {
                    const ref = prepared.toolsDeltaRef;
                    recordSteps.set("tools_delta", () => {
                        if (pendingTools !== undefined)
                            consumeDelivered(ref.pending, pendingTools);
                        if (pendingRemovedTools !== undefined)
                            consumeDelivered(ref.pendingRemoved, pendingRemovedTools);
                        if (pendingReaddedTools !== undefined)
                            consumeDelivered(ref.pendingReadded, pendingReaddedTools);
                    });
                }
                if ((mcpAdds !== undefined || mcpRemovals !== undefined) &&
                    due.some((a) => a.source === "mcp_instructions" && a.body === renderMcpInstructionsDelta(mcpAdds ?? [], mcpRemovals ?? [], prepared.engineText))) {
                    if (mcpAdds !== undefined)
                        mcpDelta.pendingAdds.splice(0, mcpAdds.length);
                    if (mcpRemovals !== undefined)
                        mcpDelta.pendingRemovals.splice(0, mcpRemovals.length);
                }
                if (mcpDropped !== undefined && due.some((a) => a.source === "mcp_dropped_tools")) {
                    recordSteps.set("mcp_dropped_tools", () => {
                        consumeDelivered(prepared.mcp.droppedTools, mcpDropped);
                        prepared.announcedListingsRef.advisories = withAnnounceDigests(prepared.announcedListingsRef.advisories, mcpDropped.map(droppedToolDigest));
                        prepared.frameReceipts.listingSnapshotOwed = true;
                    });
                }
                if (offeredListing !== undefined && due.some((a) => a.source === "agent_listing")) {
                    const listing = offeredListing;
                    const frame = renderAgentListingFrame(attachState, listing.entries, listing.toolName, listing.models, listing.budget, prepared.engineText);
                    recordSteps.set("agent_listing", () => {
                        commitAgentListing(attachState, listing.entries, listing.models);
                        prepared.announcedListingsRef.agents = listing.entries.map((e) => e.name);
                        if (listing.models !== undefined)
                            prepared.announcedListingsRef.models = [...listing.models];
                        prepared.frameReceipts.listingSnapshotOwed = true;
                        announceListingTruncation(deps.runner.deps.onNotice, { listing: "agents", total: frame.listed, nameOnly: frame.nameOnly, dropped: frame.dropped, budget: listing.budget, sessionId: prepared.sessionId });
                    });
                }
                if (skillsListingDue && due.some((a) => a.source === "skills_listing")) {
                    const listing = prepared.skillsListing;
                    const frame = renderSkillsListingFrame(attachState, listing.entries, listing.budget, prepared.engineText);
                    recordSteps.set("skills_listing", () => {
                        commitSkillsListing(attachState, listing.entries);
                        prepared.announcedListingsRef.skills = listing.entries.map((e) => e.name);
                        prepared.frameReceipts.listingSnapshotOwed = true;
                        announceListingTruncation(deps.runner.deps.onNotice, { listing: "skills", total: frame.listed, nameOnly: frame.nameOnly, dropped: frame.dropped, budget: listing.budget, sessionId: prepared.sessionId });
                    });
                }
            }
            if (rs.attach.dateState !== undefined && !frameCarried(prepared.frameReceipts, "date_change")) {
                const today = prepared.dateChange.today();
                const cand = collectDateChange(rs.attach.dateState, today, prepared.engineText);
                if (cand !== undefined) {
                    due.unshift(cand);
                    recordSteps.set("date_change", () => void (rs.attach.dateState.announcedDate = today));
                }
            }
            if (rs.attach.sizeGuidelineState !== undefined && !carried("workflow_size_guideline_change")) {
                const sizeState = rs.attach.sizeGuidelineState;
                const guideline = sizeState.current();
                if (guideline !== sizeState.announcedGuideline) {
                    due.splice(due.length > 0 && due[0].source === "date_change" ? 1 : 0, 0, {
                        source: "workflow_size_guideline_change",
                        body: workflowSizeGuidelineChangeNotice(guideline, prepared.engineText),
                    });
                    recordSteps.set("workflow_size_guideline_change", () => void (sizeState.announcedGuideline = guideline));
                }
            }
            if (prepared.nestedMemory !== undefined)
                nestedLoad = await prepared.nestedMemory.load({ echo: instructionEchoTo(queue, ident, rs.attach) });
            if (due.length > 0) {
                const minted = due.map((a) => ({ source: a.source, block: mintSystemReminder(sanitizeUntrustedText(a.body, attachmentEnvelopeTags(a.source)), prepared.reminderMark) }));
                attachmentsBundle = composeBundle(minted);
                const noticeAt = due.findIndex((a) => a.source === "changed_files");
                if (noticeAt >= 0)
                    changedNotice = { block: minted[noticeAt].block, frame: due[noticeAt] };
                for (const a of due)
                    if (!isIntactSource(a.source))
                        boundaryAttachmentBytes += Buffer.byteLength(a.body, "utf8");
                for (const a of due) {
                    const record = a.commit ?? recordSteps.get(a.source);
                    const announce = () => {
                        queue.push({ type: "steering_injected", source: a.source, preview: steeringPreview(a.body, a.echoBound), ...ident() });
                        rs.attach.attachmentsInjected += 1;
                    };
                    bundleReceipts.push({
                        source: a.source,
                        commit: a.source === "changed_files"
                            ? announceWhenCarried(prepared, announce)
                            : () => {
                                announce();
                                record?.();
                            },
                    });
                }
            }
        }
        let batchContextBlock;
        const finalVerifyInjectedThisTurn = rs.counters.finalVerifyInjections !== finalVerifySeenAtLastBoundary;
        finalVerifySeenAtLastBoundary = rs.counters.finalVerifyInjections;
        if (postToolBatchArmed && rs.turn.toolBatch.length > 0) {
            const batch = rs.turn.toolBatch;
            rs.turn.toolBatch = [];
            batchArgs?.clear();
            const injectedThisTurn = finalVerifyInjectedThisTurn ? "final_verification" : undefined;
            if (!boundarySteered && !prepared.abortController.signal.aborted) {
                const outcome = await dispatchClassic(prepared.modBus, "classic.PostToolBatch", { ...classicEventBase(prepared.hookIdentity, prepared.permissionMode.observed), batch, ...(injectedThisTurn !== undefined ? { injectedThisTurn } : {}) }, { signal: prepared.abortController.signal, checkAnswer: stringMembersAnswer("classic.PostToolBatch", ["additionalContext"]) }).catch((err) => {
                    try {
                        runnerHooks.onError?.(asThrownError(err), { phase: "hook", sessionId: prepared.sessionId });
                    }
                    catch {
                    }
                    return undefined;
                });
                const r = outcome?.kind === "answered" ? stringMembersOf(outcome.answer, ["additionalContext"]) : undefined;
                if (r?.additionalContext && injectedThisTurn === undefined) {
                    const body = sanitizeUntrustedText(r.additionalContext, SHELLED_BODY_ENVELOPE_TAGS);
                    const budget = ATTACHMENT_BYTE_CAP - boundaryAttachmentBytes;
                    if (budget >= BATCH_CONTEXT_MIN_KEEP_BYTES) {
                        const clipped = clipToBytes(body, budget) === body
                            ? body
                            : `${clipToBytes(body, budget - Buffer.byteLength(BATCH_TRUNCATION_MARKER, "utf8"))}${BATCH_TRUNCATION_MARKER}`;
                        batchContextBlock = mintSystemReminder(clipped, prepared.reminderMark);
                    }
                }
            }
        }
        if ((attachmentsBundle !== undefined || batchContextBlock !== undefined) && prepared.batchHaltRef.current === undefined) {
            const payload = attachmentsBundle !== undefined && batchContextBlock !== undefined ? `${attachmentsBundle.text}\n${batchContextBlock}` : (attachmentsBundle?.text ?? batchContextBlock);
            for (const c of bundleReceipts)
                prepared.frameReceipts.pending.push({ source: c.source, text: payload, commit: c.commit });
            const notice = changedNotice === undefined ? undefined : changedFilesNoticeIn(payload, changedNotice.block, changedNotice.frame);
            void prepared.harness.steer(payload, { engineMinted: true, ...(attachmentsBundle !== undefined ? { attachments: attachmentsBundle.attachments } : {}), ...(notice !== undefined ? { changedFilesNotices: [notice] } : {}) }).catch(() => {
                prepared.frameReceipts.pending = prepared.frameReceipts.pending.filter((r) => r.text !== payload);
            });
        }
        if (nestedLoad !== undefined) {
            const load = nestedLoad;
            if (prepared.batchHaltRef.current !== undefined)
                load.release();
            else {
                prepared.attachmentDelivery.stage(load.inputId, load.frames);
                for (const f of load.frames)
                    void prepared.harness.steerFrame(f.seed).catch(() => load.release());
            }
        }
        await compactionPass(event.model);
        return undefined;
    };
    const compactInPlace = async (model, request) => {
        let outcome = "mooted";
        manualCompactRef.waiters.push({ resolve: (o) => (outcome = o), ...(request.instructions !== undefined ? { instructions: request.instructions } : {}), requestedBy: request.requestedBy });
        manualCompactRef.requested = true;
        await compactionPass(model, request.call);
        return outcome;
    };
    const reportUsage = async (contextUsage) => {
        const sections = contextUsageSections(prepared.promptManifest.sections);
        queue.push({ type: "context_usage", ...contextUsage, ...(sections !== undefined ? { sections } : {}), ...ident() });
        const measured = measureSession(prepared.modBus, prepared.sessionMeasure, contextUsage, prepared.hookIdentity, prepared.abortController.signal);
        if (measured !== undefined)
            await measured;
    };
    const compactionPass = async (model, call, turnStart) => {
        if (turnStart === undefined && manualCompactRef.requested && !compactionEnabled("manualCompact", spec.compaction, legContextOverlayOption(prepared, runner).contextOverlay)) {
            emitTrace(rs.telemetry.tracer, () => ({ kind: "compaction.disabled", version: 1, taskId: rs.telemetry.taskId, ts: Date.now() }));
            queue.push({ type: "compaction_outcome", outcome: "disabled", trigger: "manual", ...requesterOf(manualCompactRef.waiters), ...ident() });
            drainManualCompact("disabled");
        }
        const forceManual = turnStart === undefined && manualCompactRef.requested;
        const automaticOn = turnStart?.owed === "leg-start" ? compactionEnabled("autoCompact", spec.compaction, legContextOverlayOption(prepared, runner).contextOverlay) : withinTaskCompaction();
        if ((!automaticOn && !forceManual) ||
            prepared.abortController.signal.aborted ||
            callerStop.signal.aborted ||
            prepared.pausedRef.current !== undefined) {
            if (forceManual) {
                emitTrace(rs.telemetry.tracer, () => ({ kind: "compaction.mooted", version: 1, taskId: rs.telemetry.taskId, reason: "task_ending", ts: Date.now() }));
                queue.push({ type: "compaction_outcome", outcome: "mooted", trigger: "manual", reason: "task_ending", ...requesterOf(manualCompactRef.waiters), ...ident() });
                drainManualCompact("mooted");
            }
            if (turnStart === undefined)
                legContinues &&= !prepared.abortController.signal.aborted && prepared.pausedRef.current === undefined;
            return false;
        }
        if (turnStart?.signal?.aborted === true)
            return false;
        if (compactionBreaker.failures >= MAX_CONSECUTIVE_COMPACTION_FAILURES) {
            if (forceManual) {
                emitTrace(rs.telemetry.tracer, () => ({
                    kind: "compaction.failed",
                    version: 1,
                    taskId: rs.telemetry.taskId,
                    trigger: "manual",
                    reason: "compaction circuit breaker open (3 consecutive failures this task) — manual request drained without an attempt",
                    ts: Date.now(),
                }));
                queue.push({ type: "compaction_outcome", outcome: "failed", trigger: "manual", reason: "compaction circuit breaker open (3 consecutive failures this task) — manual request drained without an attempt", ...requesterOf(manualCompactRef.waiters), ...ident() });
                drainManualCompact("failed");
            }
            return false;
        }
        const claimedManual = forceManual
            ? (() => {
                const waiters = manualCompactRef.waiters.splice(0);
                let instructions;
                for (let i = waiters.length - 1; i >= 0; i--) {
                    if (waiters[i].instructions !== undefined) {
                        instructions = waiters[i].instructions;
                        break;
                    }
                }
                return { instructions, waiters };
            })()
            : undefined;
        if (forceManual) {
            manualCompactRef.requested = false;
        }
        const requester = requesterOf(claimedManual?.waiters ?? []);
        const resolveClaimedWaiters = (outcome) => {
            if (claimedManual !== undefined)
                for (const w of claimedManual.waiters.splice(0))
                    w.resolve(outcome);
        };
        const claimedCancelSignals = claimedManual?.waiters.flatMap((w) => (w.signal !== undefined ? [w.signal] : [])) ?? [];
        const withdrawals = [...claimedCancelSignals, ...(turnStart?.signal !== undefined ? [turnCutWhileLegRuns(turnStart.signal, prepared.abortController.signal)] : [])];
        const manualCancelSignal = withdrawals.length === 0 ? callerStop.signal : AbortSignal.any([callerStop.signal, ...withdrawals]);
        const compactionPassSignal = AbortSignal.any([prepared.abortController.signal, manualCancelSignal, ...(turnStart?.signal !== undefined ? [turnStart.signal] : [])]);
        const trimPressureArmed = turnStart === undefined && prepared.trimPressureRef.droppedMessages;
        if (trimPressureArmed)
            prepared.trimPressureRef.droppedMessages = false;
        const trimPressure = trimPressureArmed && !rs.counters.trimForceBackoff && withinTaskCompaction();
        if (turnStart === undefined && !forceManual && !trimPressure) {
            prepared.microCompact.turnStartCompactionRef.owed = "boundary";
            try {
                const ctx = await prepared.session.buildContext();
                const overlay = legContextOverlayOption(prepared, runner).contextOverlay;
                const measured = measureContext({
                    messages: ctx.messages,
                    model,
                    ...(overlay !== undefined ? { contextOverlay: overlay } : {}),
                    settings: legCompactionSettings(spec, overlay, "autoCompact"),
                    ...(prepared.promptOverheadTokens !== undefined ? { overheadTokens: prepared.promptOverheadTokens } : {}),
                });
                if (measured.contextUsage !== undefined)
                    await reportUsage(measured.contextUsage);
            }
            catch (err) {
                runnerHooks.onError?.(err, { phase: "degraded", sessionId: prepared.sessionId, classification: "context-measurement" });
            }
            return false;
        }
        const passTrigger = trimPressure ? "forced" : forceManual ? "manual" : "auto";
        let manualOutcome = "failed";
        const manualInstructions = claimedManual?.instructions;
        const passReport = compactionPassReport(queue, ident);
        let landed = false;
        try {
            const comp = await prepared.compactStation.compact({
                session: prepared.session,
                admitRows: prepared.admitRows,
                promptIdentity: prepared.promptIdentity,
                ...centerAdoptionOption(prepared),
                model,
                ...legContextOverlayOption(prepared, runner),
                ...(turnStart !== undefined ? { forkContext: turnStart.fork } : forkContextOption(prepared, false)),
                brain: compactionBrain,
                getApiKeyAndHeaders: spec.getApiKeyAndHeaders,
                thinking: prepared.thinking,
                settings: legCompactionSettings(spec, legContextOverlayOption(prepared, runner).contextOverlay, forceManual ? "manualCompact" : "autoCompact"),
                customInstructions: manualInstructions ?? spec.compaction?.instructions ?? DEFAULT_COMPACTION_INSTRUCTIONS,
                signal: compactionPassSignal,
                manualCancelSignal,
                minTokens: forceManual ? 0 : rs.counters.compactionFloor,
                force: forceManual,
                onInputTruncated: emitInputTruncated(rs.telemetry.tracer, rs.telemetry.taskId),
                forceUnderThreshold: trimPressure,
                overheadTokens: prepared.promptOverheadTokens,
                ...(prepared.activeTools.size > 0 ? { activeTools: [...prepared.activeTools] } : {}),
                workingFileAttachments: buildWorkingFileAttachments(spec, prepared),
                ...(prepared.onCompactionApplied ? { onApplied: prepared.onCompactionApplied } : {}),
                ...seamCCompactionOptions(runner, prepared),
                ...compactionRestateOptions(prepared, instructionEchoTo(queue, ident, rs.attach)),
                ...compactionHookOptions(runner, prepared, passTrigger, compactionPassSignal),
                onStarted: passReport.onStarted,
            }, maybeCompact, { ...(manualInstructions !== undefined ? { instructions: manualInstructions } : {}), ...(call !== undefined ? { call } : {}) });
            if (comp.blocked) {
                emitTrace(rs.telemetry.tracer, () => ({
                    kind: "compaction.blocked",
                    version: 1,
                    taskId: rs.telemetry.taskId,
                    trigger: forceManual ? "manual" : "auto",
                    ts: Date.now(),
                }));
            }
            else if (comp.windowBelowOverhead === undefined) {
                compactionBreaker.failures = 0;
            }
            rs.counters.trimForceBackoff = nextTrimForceBackoff(rs.counters.trimForceBackoff, comp, trimPressure);
            if (comp.contextUsage && turnStart === undefined)
                await reportUsage(comp.contextUsage);
            if (comp.unevaluableWindow) {
                discloseUnevaluableWindow(comp.unevaluableWindow, prepared, rs.telemetry.tracer, rs.telemetry.taskId, runnerHooks.onError);
            }
            if (comp.windowBelowOverhead) {
                discloseWindowBelowOverhead(comp.windowBelowOverhead, prepared, runnerHooks.onError, (reason) => queue.push({ type: "compaction_outcome", outcome: "disabled", trigger: passTrigger, reason, ...ident() }));
            }
            if (comp.suppressedByFloor) {
                const s = comp.suppressedByFloor;
                emitTrace(rs.telemetry.tracer, () => ({
                    kind: "compaction.suppressed",
                    version: 1,
                    taskId: rs.telemetry.taskId,
                    estTokens: s.estTokens,
                    floor: s.floor,
                    ts: Date.now(),
                }));
            }
            manualOutcome = manualCompactOutcomeOf(comp);
            if (forceManual && !comp.compacted && !comp.blocked) {
                emitTrace(rs.telemetry.tracer, () => ({ kind: "compaction.noop", version: 1, taskId: rs.telemetry.taskId, ts: Date.now() }));
            }
            if (!comp.compacted) {
                const outcome = comp.blocked
                    ? "blocked"
                    : comp.suppressedByFloor
                        ? "suppressed"
                        : comp.noop || forceManual
                            ? "noop"
                            : undefined;
                if (outcome !== undefined) {
                    queue.push({ type: "compaction_outcome", outcome, trigger: passTrigger, ...requester, ...ident() });
                }
            }
            recordCompactionReuse(runner, prepared, comp);
            if (comp.compacted) {
                landed = true;
                queue.push({ ...mintCompactedEvent(comp, passTrigger, ident()), ...requester });
                rs.counters.compactionPasses += 1;
                rs.counters.compactionKind = compactionKindOf(passTrigger);
                if (!forceManual && recordCompactionAndCheckRapidRefill(rapidRefill, stats.turns)) {
                    compactionBreaker.failures = MAX_CONSECUTIVE_COMPACTION_FAILURES;
                    queue.push({ type: "compaction_outcome", outcome: "disabled", trigger: passTrigger, reason: "rapid_refill: compaction disabled for the rest of this task", ...ident() });
                    runnerHooks.onError?.(new Error("compaction.rapid_refill: the context refilled within <3 turns of compaction 3 times in a row — compaction disabled for the rest of this task (thrash spiral; the transcript is dominated by incompressible content)"), { phase: "compaction", sessionId: prepared.sessionId });
                }
                if (comp.phaseDurations !== undefined && comp.durationMs !== undefined) {
                    const pd = comp.phaseDurations;
                    const pdDur = comp.durationMs;
                    emitTrace(rs.telemetry.tracer, () => ({ kind: "compaction.phase_timings", version: 1, taskId: rs.telemetry.taskId, ...pd, durationMs: pdDur, ts: Date.now() }));
                }
                prepared.turnSnapshot?.declare({ cause: "compaction" });
                if (rs.attach.attachState !== undefined) {
                    rs.attach.attachState.postCompactPending = true;
                    rebaseCadenceWindows(rs.attach.attachState, rs.counters.cadenceTurns);
                }
                if ((comp.freedTokens ?? 0) >= COMPACTION_FREED_EPSILON && comp.postTriggerTokens !== undefined) {
                    rs.counters.compactionFloor = Math.ceil(comp.postTriggerTokens * COMPACTION_REGROWTH_FACTOR);
                }
            }
        }
        catch (err) {
            const cut = compactionCutOf(err);
            if (cut === "cancelled") {
                emitTrace(rs.telemetry.tracer, () => ({ kind: "compaction.mooted", version: 1, taskId: rs.telemetry.taskId, reason: "cancelled", ts: Date.now() }));
                queue.push({ type: "compaction_outcome", outcome: "mooted", trigger: passTrigger, reason: "cancelled", ...passReport.end, ...requester, ...ident() });
                manualOutcome = "mooted";
            }
            else if (cut === "failed") {
                compactionBreaker.failures += 1;
                runnerHooks.onError?.(err, { phase: "compaction", sessionId: prepared.sessionId });
                const failReason = compactionFailureReason(err), failCause = compactionFailureCause(err);
                emitTrace(rs.telemetry.tracer, () => ({
                    kind: "compaction.failed",
                    version: 1,
                    taskId: rs.telemetry.taskId,
                    trigger: passTrigger,
                    reason: failReason,
                    ts: Date.now(),
                }));
                queue.push({ type: "compaction_outcome", outcome: "failed", trigger: passTrigger, reason: failReason, ...(failCause !== undefined ? { cause: failCause } : {}), ...passReport.end, ...requester, ...ident() });
                manualOutcome = "failed";
            }
            else {
                manualOutcome = "mooted";
                if (passReport.pass !== undefined) {
                    emitTrace(rs.telemetry.tracer, () => ({ kind: "compaction.mooted", version: 1, taskId: rs.telemetry.taskId, reason: "task_ending", ts: Date.now() }));
                    queue.push({ type: "compaction_outcome", outcome: "mooted", trigger: passTrigger, reason: "task_ending", ...passReport.end, ...requester, ...ident() });
                }
            }
        }
        if (forceManual)
            resolveClaimedWaiters(manualOutcome);
        return landed;
    };
    prepared.microCompact.turnStartCompactionRef.current = async (owed, signal, fork) => await compactionPass(prepared.harness.getModel(), undefined, { owed, ...(signal !== undefined ? { signal } : {}), fork });
    const onTurnBoundary = async (event) => {
        legContinues = true;
        try {
            return await boundaryPass(event);
        }
        finally {
            const round = prepared.peerBoundaryRound;
            if (round !== undefined) {
                try {
                    await round({ continues: legContinues });
                }
                catch {
                }
            }
        }
    };
    return onTurnBoundary;
}