UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

833 lines • 58.7 kB
import { snapshotActorAssertion } from "../../internal/llm.js";
import { redactThenCut } from "../../agents/subagent-steps.js";
import { ASK_USER_QUESTION_TOOL_NAME } from "../ask-question.js";
import { CheckpointError, readPendingSteerQueue, realApprovalOrgFact, remainingBudgetMicroUsd } from "../checkpoint-store.js";
import { normalizePersistedRuleHit } from "../rule-lane-reads.js";
import { decidersNote, SETTLEMENT_NOBODY_JUDGED } from "../gate-outcome.js";
import { formatHookFeedback } from "../hooks.js";
import { classicEventBase, failedHandlerClause, screenUserPrompt } from "../mods/stations.js";
import { buildAppliedHumanInputEvent, buildHumanInputEvent, projectHumanInput } from "../human-input-projection.js";
import { humanInputAttachmentsOf, readObjectiveAttachments, userAttachmentDeclarations } from "../user-attachment.js";
import { readToolCallArguments, uuidv7 } from "../../internal/harness.js";
import { ORG_ADJUDICATION_TIMEOUT_MS, settleOrgVerdictWithin } from "../permission-rule-org.js";
import { applyPersistedTightening, disclosedRuleSet } from "../persisted-rule-arms.js";
import { argsReadBy, stampArgsReading } from "../effective-path-target.js";
import { parkedSkillApprovalRefusal, skillRowRefusal } from "../skill-grant.js";
import { SKILL_TOOL_NAME } from "./synthetic-tools.js";
import { computeCostMicroUsd } from "../pricing.js";
import { mintSystemReminder } from "../reminder-mint.js";
import { hasDestroy } from "../remote-env.js";
import { advertisedWritableRootsSeat, attestationOf, exemptRootsSeat, humanRefusalSentence, ownedReading, policyCannotAnswer, policyRefusalMessage, refuseOutOfContractDecision } from "../tool-policy.js";
import { failedJudgmentDeny } from "./policy-throw.js";
import { pathDenialCardOf } from "../../tools/fs/safety.js";
import { callFaceSeat, judgeParkedToolIdentity, parkedRowLiveFace, rosterEntryNamed } from "../tool-roster.js";
import { deliverEngineNotice } from "../types.js";
import { delimitUntrusted, inlineUntrusted, REVIEWER_NOTE_MAX_BODY, sanitizeUntrustedText } from "../untrusted-text.js";
import { errorCodeOf } from "./terminal-account.js";
import { DEFAULT_PRECALL_OUTPUT_TOKENS, platformLimitTerminal } from "./clock-and-limits.js";
import { legContextOverlayOption } from "./compaction-call-options.js";
import { mintOutputStyleReminder, owedPostureText } from "./compaction-restate.js";
import { deepJsonEqual, resumeContinuation } from "./decide-continuation.js";
import { chainCannotJudge } from "./call-hook-stations.js";
import { settleExecutionRecord } from "./execution-record.js";
import { holdPrompt } from "./prompt-block.js";
import { frozenInputSnapshot } from "./gate-exit.js";
import { withGateTimeout } from "../gate-bounded-await.js";
import { readStationAnswer } from "../shell-read-silence.js";
import { resolveGitLegDelivery, wrapGitFrame } from "./git-leg-delivery.js";
import { GIT_STATUS_ECHO_PREVIEW } from "./git-status-frame.js";
import { toImageContent } from "./image.js";
import { maybeHumanRejectionHalt } from "./prepare-gate-stations.js";
import { nextHumanInputSeq } from "./steer-admission.js";
import { settleTeardownLeg } from "./teardown-bounded.js";
import { announceToolCall, emitSettled, toolResultMsg } from "./tool-end-body.js";
import { rowDetailsOf, withRowNotExecuted } from "./tool-not-executed.js";
import { announceListingTruncation } from "../skill-listing-budget.js";
import { attachmentEnvelopeTags, collectDateChange, commitAgentListing, commitSkillsListing, reduceToolEnd, renderAgentListingFrame, renderOrphanedBackgroundTasks, renderSkillsListingFrame, stampWriteAnchor } from "./turn-attachments.js";
import { flushOwedAnnouncedSnapshot } from "./announce-once-ledger.js";
import { thrownMarksOf } from "../thrown-value.js";
import { egressThrownText, egressValue } from "../untrusted-egress.js";
import { ruleSourcePhrase } from "../rule-denial-sentence.js";
import { wireOf } from "../tool-name-readings.js";
export async function runLeg(input) {
    const { spec, queue, prepared, resume, rs, entryActor, effectiveTimeoutMs, timeout, pushContent, ident, emitCommitted, writeFamilyOf, startedToolCallIds, announceWorkspaceMove, withBrainSinks, flushGitMirror, loopLatch, notificationLane, unsubscribeTaskNotifications, unsubGitRetry, unsubBoundary, unsub, runner, next } = input;
    let final;
    let threw;
    let abortedLive = false;
    let userInterruptedLive = false;
    let strandedHumanAnswers = [];
    try {
        if (prepared.abortController.signal.aborted) {
            const e = new Error("run aborted");
            e.name = "AbortError";
            throw e;
        }
        if (resume) {
            const walltimeExhaustedResume = effectiveTimeoutMs !== undefined && effectiveTimeoutMs <= 0;
            const resumeWindowRetryAfterMs = !walltimeExhaustedResume && prepared.usageGovernance !== undefined ? await prepared.usageGovernance.check(Date.now()) : undefined;
            if (resumeWindowRetryAfterMs !== undefined) {
                const owesNothing = resume.outcome.gate === "resource_limit" &&
                    readPendingSteerQueue(resume.cp.state).length === 0 &&
                    (resume.cp.state.runningBackgroundTasks?.length ?? 0) === 0;
                const committed = owesNothing &&
                    prepared.suspendForPlatformLimit !== undefined &&
                    (await prepared.suspendForPlatformLimit("usage_window", { costMicroUsd: 0, tokens: 0, turns: 0, walltimeMs: Math.round(performance.now() - rs.telemetry.taskStartMonotonic) }, { resumeAfterMs: resumeWindowRetryAfterMs }));
                if (committed) {
                    rs.limits.turnsExceeded = false;
                    rs.limits.budgetHit = undefined;
                }
                else {
                    const terminal = platformLimitTerminal("usage_window", resumeWindowRetryAfterMs, "resume");
                    rs.limits.platformTerminal = terminal;
                    try {
                        runner.deps.onError?.(terminal, { phase: "config", sessionId: prepared.sessionId });
                    }
                    catch {
                    }
                }
            }
            if (resumeWindowRetryAfterMs === undefined && !walltimeExhaustedResume && resume.outcome.gate !== "wake") {
                await applyResumeDecision(runner, prepared, resume, (e) => pushContent({ ...e, ...ident() }), emitCommitted, (toolName, details) => {
                    if (rs.attach.attachState === undefined)
                        return;
                    const family = writeFamilyOf(toolName);
                    if (family !== undefined)
                        stampWriteAnchor(rs.attach.attachState, family, rs.counters.cadenceTurns);
                    if (details !== undefined)
                        reduceToolEnd(rs.attach.attachState, details);
                }, (toolCallId) => {
                    startedToolCallIds.add(toolCallId);
                    if (resume !== undefined && resume.cp.pendingAction.kind === "tool_approval" && toolCallId === resume.cp.pendingAction.toolCallId) {
                        resume.pendingActionStarted = true;
                    }
                });
                if (resume.outcome.gate === "policy_ask")
                    resume.decisionDelivered = true;
                announceWorkspaceMove();
            }
            if (resumeWindowRetryAfterMs !== undefined) {
            }
            else if (walltimeExhaustedResume) {
                timeout.fired = true;
                timeout.clear();
                void prepared.harness.abort();
                prepared.abortController.abort();
            }
            else if (rs.budget.maxTokensWindow !== undefined && rs.budget.maxTokensWindow <= 0) {
                rs.limits.budgetHit = "exceeded";
                rs.limits.budgetAxis = "tokens";
            }
            else if (rs.budget.maxCostMicroUsd !== undefined && rs.budget.maxCostMicroUsd <= 0) {
                rs.limits.budgetHit = "exceeded";
                rs.limits.budgetAxis = "cost";
            }
            else {
                let continuation = resumeContinuation(resume, prepared.reminderMark, prepared.fullShellReachable, prepared.hookIdentity.isDelegatedChild);
                const bgSnapshot = resume.cp.state.runningBackgroundTasks;
                let orphanTasks = [];
                if (bgSnapshot !== undefined && bgSnapshot.length > 0) {
                    const alive = new Set(prepared.listBackgroundTasks().map((t) => t.id));
                    orphanTasks = bgSnapshot.filter((t) => !alive.has(t.id));
                    if (orphanTasks.length > 0) {
                        continuation += "\n\n" + formatHookFeedback(renderOrphanedBackgroundTasks(orphanTasks), prepared.reminderMark);
                    }
                }
                let gitResumeDelivered;
                {
                    const gitBody = await resolveGitLegDelivery(prepared, resume.cp.state.gitAnnouncement, (err) => {
                        try {
                            runner.deps.onError?.(new Error(`git announcement ladder unreadable (conservative re-announce): ${err.message}`), { phase: "degraded", sessionId: prepared.sessionId });
                        }
                        catch {
                        }
                    });
                    const gitFrame = prepared.gitStatusRef.frame;
                    if (gitBody !== undefined && gitFrame !== undefined) {
                        const wrappedGit = wrapGitFrame(gitBody, prepared.reminderMark);
                        continuation += "\n\n" + wrappedGit;
                        gitResumeDelivered = { kind: gitFrame.kind, hash: gitFrame.hash, wrapped: wrappedGit };
                        if (gitFrame.kind === "full" && gitFrame.shrunk !== undefined) {
                            prepared.gitStatusRef.wrappedShrink = { find: wrappedGit, replace: wrapGitFrame(gitFrame.shrunk.body, prepared.reminderMark) };
                        }
                    }
                }
                const postureText = await owedPostureText(prepared, "always");
                if (postureText !== undefined)
                    continuation += "\n\n" + postureText;
                const outputStyleWrapped = mintOutputStyleReminder(prepared);
                if (outputStyleWrapped !== undefined)
                    continuation += "\n\n" + outputStyleWrapped;
                const engineSegments = continuation.length > 0 ? [{ start: 0, end: continuation.length }] : [];
                const parkedSteers = readPendingSteerQueue(resume.cp.state);
                const resumeFrames = [
                    ...parkedSteers.map((entry) => ({ entry, source: "steer" })),
                    ...(resume.wakeMessage !== undefined ? [{ entry: resume.wakeMessage, source: "wake" }] : []),
                ];
                const appliedEvents = [];
                const withheldSteerIds = new Set();
                for (const { entry: steer, source } of resumeFrames) {
                    if (source === "wake" && resume.wakeMessageHookContext !== undefined) {
                        const hookStart = continuation.length;
                        continuation += "\n\n" + formatHookFeedback(resume.wakeMessageHookContext, prepared.reminderMark);
                        engineSegments.push({ start: hookStart, end: continuation.length });
                    }
                    if (source === "steer") {
                        const screen = await screenUserPrompt(prepared.modBus, {
                            ...classicEventBase(prepared.hookIdentity, prepared.permissionMode.observed),
                            prompt: steer.text,
                            source: "parked_redelivery",
                            ...(steer.inputId !== undefined ? { inputId: steer.inputId } : {}),
                            ...(steer.actor !== undefined ? { actor: snapshotActorAssertion(steer.actor) } : {}),
                        }, prepared.abortController.signal);
                        if (screen !== undefined) {
                            const outcome = screen.kind === "aborted"
                                ? { blocked: "the run was cancelled while the screen was still deciding (fail-closed)" }
                                : screen.kind === "failed"
                                    ? { blocked: `the screen ${failedHandlerClause(screen)} (fail-closed)` }
                                    : screen.block !== undefined && screen.block !== ""
                                        ? { blocked: inlineUntrusted(screen.block) }
                                        : { ...(screen.additionalContext !== undefined && screen.additionalContext !== "" ? { context: screen.additionalContext } : {}) };
                            if ("blocked" in outcome) {
                                if (steer.inputId !== undefined)
                                    withheldSteerIds.add(steer.inputId);
                                deliverEngineNotice(runner.deps.onNotice, {
                                    code: "steering.parked_input_blocked",
                                    message: "a parked steering input was withheld by the deployment's userPromptSubmit screen when this resume redelivered it: " +
                                        `${outcome.blocked}. The parked row was consumed with the checkpoint; the instruction never reached the model — ` +
                                        "re-issue it if it still applies.",
                                    detail: {
                                        ...(steer.inputId !== undefined ? { inputId: steer.inputId } : {}),
                                        sessionId: prepared.sessionId,
                                        runId: prepared.runId,
                                        ...(spec.taskId !== undefined ? { taskId: spec.taskId } : {}),
                                    },
                                });
                                queue.push({
                                    ...buildHumanInputEvent({
                                        carrier: source,
                                        source,
                                        delivery: "blocked",
                                        sessionSeq: nextHumanInputSeq(prepared.harness),
                                        ...(steer.inputId !== undefined ? { inputId: steer.inputId } : {}),
                                        ...(steer.actor !== undefined ? { actor: steer.actor } : {}),
                                        ...(steer.actor?.issuer !== undefined ? { issuer: steer.actor.issuer } : {}),
                                        ...(spec.principal !== undefined ? { principal: spec.principal } : {}),
                                    }),
                                    ...ident(),
                                });
                                continue;
                            }
                            if ("context" in outcome && outcome.context !== undefined) {
                                const hookStart = continuation.length;
                                continuation += "\n\n" + formatHookFeedback(outcome.context, prepared.reminderMark);
                                engineSegments.push({ start: hookStart, end: continuation.length });
                            }
                        }
                    }
                    const start = continuation.length;
                    const projected = projectHumanInput({ text: steer.text, actor: steer.actor, source });
                    continuation +=
                        "\n\n" +
                            (steer.trusted ? formatHookFeedback(projected, prepared.reminderMark) : delimitUntrusted("supervisor steering message", projected));
                    if (steer.trusted)
                        engineSegments.push({ start, end: continuation.length });
                    appliedEvents.push({
                        ...buildAppliedHumanInputEvent({ carrier: source, source, sessionSeq: nextHumanInputSeq(prepared.harness), inputId: steer.inputId, actor: steer.actor, principal: spec.principal }),
                        ...ident(),
                    });
                }
                const pending = resume.cp.pendingAction;
                const rejectionHalt = pending.kind === "tool_approval" && resume.outcome.gate === "policy_ask"
                    ? maybeHumanRejectionHalt({ gate: resume.outcome.gateOutcome, isDelegatedChild: prepared.hookIdentity.isDelegatedChild, toolName: pending.toolName, toolCallId: pending.toolCallId })
                    : undefined;
                if (rejectionHalt !== undefined && pending.kind === "tool_approval")
                    prepared.batchHaltRef.current = { rejectedToolCallId: pending.toolCallId };
                prepared.undeliveredContinuationRef.current = { parkedSteers: resumeFrames.map(({ entry }) => entry).filter((e) => !withheldSteerIds.has(e.inputId)), orphanTasks };
                if (!prepared.abortController.signal.aborted) {
                    if (resume !== undefined)
                        resume.decisionDelivered = true;
                    if (gitResumeDelivered !== undefined) {
                        const delivered = gitResumeDelivered;
                        prepared.gitStatusRef.protectedText = delivered.wrapped;
                        prepared.frameReceipts.pending.push({
                            source: "git_status",
                            text: continuation,
                            commit: (entryId) => {
                                prepared.gitStatusRef.announced = { kind: delivered.kind, hash: delivered.hash, entryId };
                                queue.push({ type: "steering_injected", source: "git_status", preview: GIT_STATUS_ECHO_PREVIEW[delivered.kind], ...ident() });
                                rs.attach.attachmentsInjected += 1;
                                prepared.gitStatusRef.mirrorOwed = { kind: delivered.kind, hash: delivered.hash, entryId };
                            },
                        });
                    }
                    if (outputStyleWrapped !== undefined) {
                        const preview = redactThenCut(prepared.outputStyleFrame, 220);
                        prepared.frameReceipts.pending.push({ source: "output_style", text: continuation, commit: () => void (queue.push({ type: "steering_injected", source: "output_style", preview, ...ident() }), (rs.attach.attachmentsInjected += 1)) });
                    }
                    final = await withBrainSinks(() => prepared.harness.prompt(continuation, {
                        engineSegments,
                        settleUnansweredToolCalls: rejectionHalt !== undefined ? { halt: rejectionHalt } : {},
                        onDelivered: () => {
                            prepared.undeliveredContinuationRef.current = { parkedSteers: [], orphanTasks: [] };
                            for (const e of appliedEvents)
                                queue.push(e);
                        },
                    }));
                    await flushGitMirror();
                    if (prepared.gitStatusRef.announced?.pending === true)
                        await prepared.gitStatusRef.reassert?.();
                }
            }
        }
        else {
            const objectiveActor = entryActor;
            const projectedObjective = projectHumanInput({ text: spec.objective, actor: objectiveActor, source: "objective" });
            let effectiveObjective = projectedObjective;
            let promptBlocked = false;
            const screen = await screenUserPrompt(prepared.modBus, {
                ...classicEventBase(prepared.hookIdentity, prepared.permissionMode.observed),
                prompt: spec.objective,
                source: "objective",
                ...(objectiveActor !== undefined ? { actor: snapshotActorAssertion(objectiveActor) } : {}),
                ...(prepared.userAttachments !== undefined ? { userAttachments: userAttachmentDeclarations(prepared.userAttachments) } : {}),
            }, prepared.abortController.signal);
            if (screen?.kind === "aborted") {
                holdPrompt(prepared.blockedRef, prepared.reminderMark, "cancelled", `the task was cancelled while the deployment's userPromptSubmit hook was still screening this prompt; ` +
                    `the prompt was NOT submitted (fail-closed)`);
                promptBlocked = true;
            }
            else if (screen?.kind === "failed") {
                holdPrompt(prepared.blockedRef, prepared.reminderMark, screen.cause === "timeout" ? "timeout" : "crashed", `the deployment's userPromptSubmit hook ${failedHandlerClause(screen)} while screening this prompt; the prompt was NOT submitted (fail-closed)`);
                promptBlocked = true;
            }
            else if (screen?.block) {
                holdPrompt(prepared.blockedRef, prepared.reminderMark, "block", screen.block);
                promptBlocked = true;
            }
            else if (screen?.additionalContext) {
                effectiveObjective = `${formatHookFeedback(screen.additionalContext, prepared.reminderMark)}\n\n${projectedObjective}`;
            }
            const objectiveInputId = uuidv7();
            const { frames: attachmentFrames, chars: attachmentChars } = await readObjectiveAttachments(prepared, objectiveInputId, promptBlocked, { overlay: () => legContextOverlayOption(prepared, runner).contextOverlay, objectiveChars: effectiveObjective.length });
            let gitLegDelivered;
            if (!promptBlocked) {
                const gitBody = await resolveGitLegDelivery(prepared, undefined, (err) => {
                    try {
                        runner.deps.onError?.(new Error(`git announcement ladder unreadable (conservative re-announce): ${err.message}`), { phase: "degraded", sessionId: prepared.sessionId });
                    }
                    catch {
                    }
                });
                const gitFrame = prepared.gitStatusRef.frame;
                if (gitBody !== undefined && gitFrame !== undefined) {
                    const wrappedGit = wrapGitFrame(gitBody, prepared.reminderMark);
                    const standalone = spec.images !== undefined && spec.images.length > 0;
                    if (!standalone)
                        effectiveObjective = `${wrappedGit}\n${effectiveObjective}`;
                    gitLegDelivered = { kind: gitFrame.kind, hash: gitFrame.hash, standalone, wrapped: wrappedGit };
                    if (gitFrame.kind === "full" && gitFrame.shrunk !== undefined) {
                        prepared.gitStatusRef.wrappedShrink = { find: wrappedGit, replace: wrapGitFrame(gitFrame.shrunk.body, prepared.reminderMark) };
                    }
                }
            }
            const firstFrames = [];
            const legToday = rs.attach.dateState !== undefined ? prepared.dateChange.today() : undefined;
            const dateFrame = legToday !== undefined ? collectDateChange(rs.attach.dateState, legToday) : undefined;
            if (dateFrame !== undefined)
                firstFrames.push({ source: "date_change", body: dateFrame.body, commit: () => void (rs.attach.dateState.announcedDate = legToday), disclose: () => undefined });
            if (rs.attach.attachState !== undefined) {
                const attach = rs.attach.attachState;
                if (rs.attach.agentListingOn && prepared.agentListing !== undefined) {
                    const listing = prepared.agentListing;
                    const frame = renderAgentListingFrame(attach, listing.entries, listing.toolName, listing.models, listing.budget);
                    if (frame !== undefined) {
                        firstFrames.push({
                            source: "agent_listing",
                            body: frame.text,
                            commit: () => {
                                commitAgentListing(attach, listing.entries, listing.models);
                                prepared.frameReceipts.listingSnapshotOwed = true;
                                prepared.announcedListingsRef.agents = listing.entries.map((e) => e.name);
                                if (listing.models !== undefined)
                                    prepared.announcedListingsRef.models = [...listing.models];
                            },
                            disclose: () => announceListingTruncation(runner.deps.onNotice, { listing: "agents", total: frame.listed, nameOnly: frame.nameOnly, dropped: frame.dropped, budget: listing.budget, sessionId: prepared.sessionId }),
                        });
                    }
                }
                if (rs.attach.skillsListingOn && prepared.skillsListing !== undefined) {
                    const listing = prepared.skillsListing;
                    const frame = renderSkillsListingFrame(attach, listing.entries, listing.budget);
                    if (frame !== undefined) {
                        firstFrames.push({
                            source: "skills_listing",
                            body: frame.text,
                            commit: () => {
                                commitSkillsListing(attach, listing.entries);
                                prepared.frameReceipts.listingSnapshotOwed = true;
                                prepared.announcedListingsRef.skills = listing.entries.map((e) => e.name);
                            },
                            disclose: () => announceListingTruncation(runner.deps.onNotice, { listing: "skills", total: frame.listed, nameOnly: frame.nameOnly, dropped: frame.dropped, budget: listing.budget, sessionId: prepared.sessionId }),
                        });
                    }
                }
            }
            if (prepared.outputStyleFrame !== undefined)
                firstFrames.push({ source: "output_style", body: prepared.outputStyleFrame, commit: () => undefined, disclose: () => undefined });
            if (firstFrames.length > 0) {
                effectiveObjective = `${firstFrames.map((f) => mintSystemReminder(sanitizeUntrustedText(f.body, attachmentEnvelopeTags(f.source)), prepared.reminderMark)).join("\n")}\n${effectiveObjective}`;
            }
            const postureText = await owedPostureText(prepared, "always");
            if (postureText !== undefined)
                effectiveObjective = `${postureText}\n${effectiveObjective}`;
            const gitQueuedChars = gitLegDelivered !== undefined && gitLegDelivered.standalone ? gitLegDelivered.wrapped.length : 0;
            const precallMicroUsd = rs.budget.maxCostMicroUsd === undefined
                ? 0
                : computeCostMicroUsd({
                    totalInputTokens: Math.ceil((effectiveObjective.length + gitQueuedChars + attachmentChars) / 4),
                    cacheReadTokens: 0,
                    cacheWriteTokens: 0,
                    cacheWriteTokensLong: 0,
                    outputTokens: prepared.model.maxTokens ?? DEFAULT_PRECALL_OUTPUT_TOKENS,
                }, rs.telemetry.pricing);
            const precallCeilingMicroUsd = prepared.suspendForResource !== undefined ? rs.budget.remainingMicroUsd : rs.budget.maxCostMicroUsd;
            const precallTokens = Math.ceil((effectiveObjective.length + gitQueuedChars + attachmentChars) / 4) + (prepared.model.maxTokens ?? DEFAULT_PRECALL_OUTPUT_TOKENS);
            const precallCeilingTokens = prepared.suspendForResource !== undefined ? rs.budget.remainingTokens : rs.budget.maxTokensWindow;
            const entryUsageRetryAfterMs = prepared.usageGovernance !== undefined ? await prepared.usageGovernance.check(Date.now()) : undefined;
            if (promptBlocked) {
            }
            else if (entryUsageRetryAfterMs !== undefined) {
                const terminal = platformLimitTerminal("usage_window", entryUsageRetryAfterMs, "entry");
                rs.limits.platformTerminal = terminal;
                try {
                    runner.deps.onError?.(terminal, { phase: "config", sessionId: prepared.sessionId });
                }
                catch {
                }
            }
            else if (precallCeilingTokens !== undefined && precallTokens > precallCeilingTokens) {
                rs.limits.budgetHit = "precall";
                rs.limits.budgetAxis = "tokens";
            }
            else if (precallCeilingMicroUsd !== undefined && precallMicroUsd > precallCeilingMicroUsd) {
                rs.limits.budgetHit = "precall";
                rs.limits.budgetAxis = "cost";
            }
            else if (effectiveTimeoutMs !== undefined && effectiveTimeoutMs <= 0) {
                timeout.fired = true;
                timeout.clear();
                void prepared.harness.abort();
                prepared.abortController.abort();
            }
            else {
                const images = spec.images
                    ? await Promise.all(spec.images.map((img) => toImageContent(img, runner.deps.allowImageUrl)))
                    : undefined;
                if (gitLegDelivered !== undefined) {
                    const delivered = gitLegDelivered;
                    if (delivered.standalone)
                        await prepared.harness.nextTurn(delivered.wrapped, { engineMinted: true });
                    prepared.gitStatusRef.protectedText = delivered.wrapped;
                    prepared.frameReceipts.pending.push({
                        source: "git_status",
                        text: delivered.standalone ? delivered.wrapped : effectiveObjective,
                        commit: (entryId) => {
                            prepared.gitStatusRef.announced = { kind: delivered.kind, hash: delivered.hash, entryId };
                            queue.push({ type: "steering_injected", source: "git_status", preview: GIT_STATUS_ECHO_PREVIEW[delivered.kind], ...ident() });
                            rs.attach.attachmentsInjected += 1;
                            prepared.gitStatusRef.mirrorOwed = { kind: delivered.kind, hash: delivered.hash, entryId };
                        },
                    });
                }
                for (const f of firstFrames) {
                    prepared.frameReceipts.pending.push({
                        source: f.source,
                        text: effectiveObjective,
                        commit: () => {
                            f.commit();
                            queue.push({ type: "steering_injected", source: f.source, preview: redactThenCut(f.body, 220), ...ident() });
                            rs.attach.attachmentsInjected += 1;
                            f.disclose();
                        },
                    });
                }
                const enginePrefixChars = effectiveObjective.length - projectedObjective.length;
                if (!prepared.abortController.signal.aborted) {
                    prepared.attachmentDelivery.stage(objectiveInputId, attachmentFrames);
                    queue.push({
                        ...buildHumanInputEvent({
                            carrier: "objective",
                            source: "objective",
                            delivery: "applied",
                            inputId: objectiveInputId,
                            sessionSeq: nextHumanInputSeq(prepared.harness),
                            ...(objectiveActor !== undefined ? { actor: objectiveActor } : {}),
                            ...(objectiveActor?.issuer !== undefined ? { issuer: objectiveActor.issuer } : {}),
                            ...(spec.principal !== undefined ? { principal: spec.principal } : {}),
                            ...(attachmentFrames.length > 0 ? { attachments: humanInputAttachmentsOf(attachmentFrames) } : {}),
                        }),
                        ...ident(),
                    });
                    final = await withBrainSinks(() => prepared.harness.prompt(effectiveObjective, {
                        ...(images && images.length > 0 ? { images } : {}),
                        ...(enginePrefixChars > 0 ? { enginePrefixChars } : {}),
                        ...(attachmentFrames.length > 0 ? { trailing: attachmentFrames.map((f) => f.seed) } : {}),
                        ...(objectiveActor !== undefined ? { actor: objectiveActor } : {}),
                    }));
                    await flushGitMirror();
                    if (prepared.gitStatusRef.announced?.pending === true)
                        await prepared.gitStatusRef.reassert?.();
                }
            }
        }
        loopLatch.ended = true;
        abortedLive = prepared.abortController.signal.aborted;
        userInterruptedLive = loopLatch.userInterrupted;
    }
    catch (err) {
        loopLatch.ended = true;
        if (errorCodeOf(err) === "resume.tool_unavailable" || errorCodeOf(err) === "resume.tool_contract_mismatch") {
            await settleTeardownLeg(() => prepared.mcp.dispose(), "mcp.dispose (tool_unavailable leg)", (e) => runner.deps.onError?.(e, { phase: "config", sessionId: prepared.sessionId }));
            await settleTeardownLeg(() => prepared.a2a?.dispose(), "a2a.dispose (tool_unavailable leg)", (e) => runner.deps.onError?.(e, { phase: "config", sessionId: prepared.sessionId }));
            await settleTeardownLeg(() => (prepared.ownedEnv && hasDestroy(prepared.ownedEnv) ? prepared.ownedEnv.destroy() : undefined), "ownedEnv.destroy (tool_unavailable leg)", (e) => runner.deps.onError?.(e, { phase: "config", sessionId: prepared.sessionId }));
            throw err;
        }
        threw = err;
        abortedLive = prepared.abortController.signal.aborted;
        userInterruptedLive = loopLatch.userInterrupted;
    }
    finally {
        timeout.clear();
        prepared.lspDiagnostics?.registry.releaseRun(prepared.lspDiagnostics.runIdent);
        prepared.toolProgressRef.current?.clear();
        if (prepared.frameReceipts.listingSnapshotOwed) {
            await settleTeardownLeg(() => flushOwedAnnouncedSnapshot(prepared), "announced-listing snapshot (leg exit)", (e) => runner.deps.onError?.(e, { phase: "degraded", sessionId: prepared.sessionId }));
        }
        prepared.abortController.abort();
        prepared.releaseSignal();
        prepared.endModeCeiling();
        strandedHumanAnswers = prepared.settleContentAskBindings();
        try {
            prepared.harness.recoverUndrainedEngineNotes();
        }
        catch {
        }
        notificationLane.live = false;
        unsubscribeTaskNotifications();
        prepared.toolRosterDeltas.unsubscribe();
        prepared.toolDisclosure?.unsubscribe();
        unsubGitRetry();
        unsubBoundary();
        unsub();
    }
    return await next({ final, threw, abortedLive, userInterruptedLive, strandedHumanAnswers });
}
const ORG_DISCLOSURE_MAX_CHARS = 600;
async function applyResumeDecision(runner, prepared, resume, emit, emitCommitted, onResolvedToolSuccess, onExecuteStart) {
    const { pendingAction } = resume.cp;
    if (resume.outcome.gate === "dry_run_review")
        return;
    if (resume.outcome.gate === "plan_review")
        return;
    if (pendingAction.kind !== "tool_approval")
        return;
    if (resume.outcome.gate === "policy_ask" &&
        resume.outcome.decision === "allow" &&
        !prepared.tools.some((t) => t.name === pendingAction.toolName)) {
        const e = new Error(`the approved tool "${pendingAction.toolName}" is no longer available on resume — refusing to continue as if it ran; the checkpoint is reopened for a retry with the tool present`);
        e.code = "resume.tool_unavailable";
        throw e;
    }
    const liveRoster = prepared.toolRosterDeltas.current;
    if (pendingAction.kind === "tool_approval" && liveRoster !== undefined && judgeParkedToolIdentity(pendingAction, rosterEntryNamed(liveRoster, pendingAction.toolName)) === "mismatch") {
        const e = new Error(`the approved tool "${pendingAction.toolName}" on this leg is not the tool the approval was minted against (its contract / shape / revision differ) — refusing to execute a replacement wearing the name; the checkpoint is reopened for a retry with the original tool present`);
        e.code = "resume.tool_contract_mismatch";
        throw e;
    }
    await resolvePendingCall(runner, prepared, resume, emit, emitCommitted, onResolvedToolSuccess, onExecuteStart);
}
async function resolvePendingCall(runner, prepared, resume, emit, emitCommitted, onResolvedToolSuccess, onExecuteStart) {
    const { pendingAction } = resume.cp;
    const { outcome } = resume;
    if (pendingAction.kind !== "tool_approval" || outcome.gate !== "policy_ask")
        return;
    const decidedGate = outcome.gateOutcome;
    if (decidedGate === undefined) {
        throw new CheckpointError("checkpoint.invalid_outcome", "pending action reached the resolver with no settlement record on its decision (gateOutcome) — refusing to execute or settle a decision that carries no record");
    }
    const humanRewrite = wireOf("resume.questionArgsShown", pendingAction) === ASK_USER_QUESTION_TOOL_NAME ? undefined : outcome.updatedInput;
    const liveTool = prepared.tools.find((x) => x.name === pendingAction.toolName);
    const reading = liveTool === undefined ? undefined : ownedReading((a) => readToolCallArguments(liveTool, { type: "toolCall", id: pendingAction.toolCallId, name: pendingAction.toolName, arguments: {} }, a));
    const beltFace = () => { const f = parkedRowLiveFace(prepared.toolRosterDeltas.current, pendingAction); if (f !== undefined && reading !== undefined)
        stampArgsReading(f, reading); return f; };
    const tryRead = (v) => { try {
        return { args: reading === undefined ? v : argsReadBy(reading, v) };
    }
    catch (error) {
        return { args: v, unread: { error } };
    } };
    const decided = outcome.decision === "allow" ? tryRead(humanRewrite !== undefined ? humanRewrite : pendingAction.args) : { args: humanRewrite !== undefined ? humanRewrite : pendingAction.args };
    const resolvedArgs = decided.args;
    const pendingLabel = (() => { const l = prepared.tools.find((t) => t.name === pendingAction.toolName)?.label; return l !== undefined && l !== pendingAction.toolName ? { label: l } : {}; })();
    const spelledName = pendingAction.names?.[0] ?? pendingAction.toolName;
    const occurrences = prepared.toolOccurrences;
    const callStart = { toolCallId: pendingAction.toolCallId, spelledName, wireName: pendingAction.toolName, ...pendingLabel, args: resolvedArgs };
    announceToolCall(occurrences, callStart, { push: emit });
    occurrences.gateRound(pendingAction.toolCallId, decidedGate, frozenInputSnapshot(resolvedArgs));
    let notExecuted = false;
    const resultRow = (text, isError) => withRowNotExecuted(toolResultMsg(pendingAction.toolCallId, pendingAction.toolName, text, isError), notExecuted);
    const settleEnd = async (isError, result, refusedBy, neverRan) => {
        if (refusedBy !== undefined)
            occurrences.refuse(pendingAction.toolCallId, refusedBy);
        const settled = emitSettled(occurrences, callStart, { result, isError, ...(neverRan ? { notExecuted: true } : {}) }, { push: emit, structured: prepared.structuredProjector, mediaByteCapBytes: runner.deps.mediaByteCapBytes });
        notExecuted = settled.notExecuted === true;
        const gate = settled.gate ?? decidedGate;
        const word = await resume.recordExecutionOutcome(gate);
        settleExecutionRecord(runner.deps.onNotice, word, { toolName: pendingAction.toolName, gate, sessionId: prepared.sessionId, runId: prepared.runId, scope: resume.cp.scope, ...(resume.cp.checkpointId !== undefined ? { checkpointId: resume.cp.checkpointId } : {}) });
    };
    const settleUnreadable = async (error, which) => {
        const marks = egressValue("same-principal", thrownMarksOf(error));
        const text = formatHookFeedback(`The approved tool call "${pendingAction.toolName}" was not executed: the tool could not read ${which} — its argument preparation failed (${egressThrownText("same-principal", error)}). This approval is spent — the call has to be re-issued.`, prepared.reminderMark);
        await settleEnd(true, { content: text, ...(marks !== undefined ? { details: marks } : {}) }, undefined, true);
        emitCommitted(await prepared.session.appendMessage(resultRow(text, true)), "toolResult", pendingAction.toolCallId);
    };
    if (outcome.decision === "deny") {
        const settlementKind = outcome.gateOutcome?.settlement?.kind;
        const reason = settlementKind === "policy_refused"
            ? policyRefusalMessage(pendingAction.toolName, undefined, decidersNote(outcome.reason))
            : settlementKind === "park_sla_expired"
                ? outcome.reason
                    ? delimitUntrusted("reviewer note", outcome.reason, REVIEWER_NOTE_MAX_BODY)
                    : `No one answered the approval request for the pending tool call "${pendingAction.toolName}" — the approval window elapsed with no answer, so it was not executed.`
                : humanRefusalSentence("tool use", outcome.reason, prepared.hookIdentity.isDelegatedChild);
        await settleEnd(true, { content: formatHookFeedback(reason, prepared.reminderMark) });
        const eid = await prepared.session.appendMessage(resultRow(formatHookFeedback(reason, prepared.reminderMark), true));
        emitCommitted(eid, "toolResult", pendingAction.toolCallId);
        const parkedFallback = pendingAction.denialLimitFallback;
        if (parkedFallback !== undefined && settlementKind !== undefined && SETTLEMENT_NOBODY_JUDGED[settlementKind]) {
            prepared.stopForDenialLimit({ toolName: pendingAction.toolName, toolCallId: pendingAction.toolCallId, fallback: parkedFallback, settlement: settlementKind });
        }
        return;
    }
    if (outcome.decision !== "allow") {
        throw new CheckpointError("checkpoint.invalid_outcome", `pending action reached the resolver with decision "${String(outcome.decision)}" — only "allow" executes and only "deny" injects a denial; refusing to execute`);
    }
    if (decided.unread !== undefined)
        return settleUnreadable(decided.unread.error, humanRewrite !== undefined ? "the arguments the decision edited it to" : "its arguments");
    const screened = await prepared.approvedCallScreen?.({ toolCallId: pendingAction.toolCallId, toolName: pendingAction.toolName, args: structuredClone(resolvedArgs), decidedBy: outcome.hostDecision.decidedBy });
    if (screened !== undefined && "refused" in screened) {
        const hookDenial = formatHookFeedback(screened.refused, prepared.reminderMark);
        await settleEnd(true, { content: hookDenial }, "hook");
        emitCommitted(await prepared.session.appendMessage(resultRow(hookDenial, true)), "toolResult", pendingAction.toolCallId);
        return;
    }
    const rescreened = humanRewrite === undefined && screened !== undefined ? tryRead(screened.args) : undefined;
    if (rescreened?.unread !== undefined)
        return settleUnreadable(rescreened.unread.error, "the arguments a PreToolUse hook rewrote it to");
    const executedArgs = rescreened !== undefined ? rescreened.args : resolvedArgs;
    const unseen = !deepJsonEqual(executedArgs, pendingAction.args);
    let beltReading;
    const beltReq = () => ({ toolName: pendingAction.toolName, args: executedArgs, toolCallId: pendingAction.toolCallId, ...callFaceSeat(beltFace()), budget: beltBudget, ...(prepared.cwdRef !== undefined ? { cwd: prepared.cwdRef.current } : {}), ...(prepared.handsRoot !== undefined ? { root: prepared.handsRoot } : {}), ...advertisedWritableRootsSeat(prepared.advertisedWritableDirs), ...exemptRootsSeat(prepared.exemptRoots), ...(beltReading !== undefined ? { targetReading: beltReading } : {}) });
    const unjudgeable = unseen ? chainCannotJudge(resume.cp.state.inheritedGate) : undefined;
    if (unjudgeable !== undefined) {
        const chainDenial = formatHookFeedback(`The approved tool call "${pendingAction.toolName}" was not executed: its input changed after the approval and the inherited ancestor chain cannot judge the changed input (${unjudgeable}). This approval is spent — the call has to be re-issued.`, prepared.reminderMark);
        await settleEnd(true, { content: chainDenial }, "policy");
        emitCommitted(await prepared.session.appendMessage(resultRow(chainDenial, true)), "toolResult", pendingAction.toolCallId);
        return;
    }
    const beltBudget = {
        resourceRemainingMicroUsd: remainingBudgetMicroUsd(prepared.resourceLedger),
        resourceSpentMicroUsd: prepared.resourceLedger?.spentMicroUsd ?? 0,
        suspendCount: resume.cp.suspendCount ?? 0,
    };
    const denialCard = (d) => {
        const card = pathDenialCardOf(attestationOf(d, { toolCallId: pendingAction.toolCallId, toolName: pendingAction.toolName })?.pathDenial);
        return card !== undefined ? { details: card } : {};
    };
    const beltCheck = async (judge, seat) => { const signal = prepared.abortController.signal; try {
        return await judge(signal);
    }
    catch (err) {
        return failedJudgmentDeny(err, signal, (e) => runner.deps.onError?.(e, { phase: "hook", sessionId: prepared.sessionId }), seat, pendingAction);
    } };
    const beltStamped = prepared.stampCallTarget?.(beltReq(), prepared.abortController.signal);
    if (beltStamped !== undefined)
        beltReading = (await beltStamped).targetReading;
    if (unseen && prepared.basePolicyForResumeEdit) {
        const rechecked = refuseOutOfContractDecision(await beltCheck((signal) => prepared.basePolicyForResumeEdit.check(beltReq(), signal), "the deployment's tool policy re-checking a resumed call"));
        const personUnanswered = policyCannotAnswer(rechecked, outcome.hostDecision.decidedBy);
        const beltUnsafe = rechecked.action === "deny" ||
            (rechecked.updatedInput !== undefined && ((read) => read.unread !== undefined || !deepJsonEqual(read.args, executedArgs))(tryRead(rechecked.updatedInput))) ||
            personUnanswered;
        if (beltUnsafe) {
            const why = rechecked.action === "deny"
                ? (rechecked.message ? `: ${rechecked.message}` : "")
                : personUnanswered
                    ? " (the call as it would run requires a person's approval, and this decision was the deployment's policy)"
                    : " (the policy rewrote these bytes to a value that was not approved)";
            const editedDenial = formatHookFeedback(`${outcome.updatedInput !== undefined ? "The approver EDITED this call's input; the edited call" : "A PreToolUse hook REWROTE this approved call's input; the rewritten call"} is refused by the deployment's tool policy and was not executed${why}.`, prepared.reminderMark);
            await settleEnd(true, { content: editedDenial, ...denialCard(rechecked) }, "policy");
            const eid = await prepared.session.appendMessage(resultRow(editedDenial, true));
            emitCommitted(eid, "toolResult", pendingAction.toolCallId);
            return;
        }
    }
    const gateRealApproval = resume.cp.gate.kind === "irreversible_ask" ? resume.cp.gate.realApproval : undefined;
    const gateOrgGoverned = realApprovalOrgFact(gateRealApproval) !== undefined;
    if (gateOrgGoverned && prepared.permissionRuleOrg === undefined) {
        const unwiredDenial = formatHookFeedback(`The approved tool call "${pendingAction.toolName}" was not executed: its approval was minted under organization governance (${gateRealApproval.origin}), and this worker has no org adjudication wiring — a governed approval may only be redeemed where governance can be enforced. This approval is spent; re-issue the call on an org-wired worker.`, prepared.reminderMark);
        await settleEnd(true, { content: unwiredDenial }, "org");
        const eid = await prepared.session.appendMessage(resultRow(unwiredDenial, true));
        emitCommitted(eid, "toolResult", pendingAction.toolCallId);
        return;
    }
    if (prepared.permissionRuleOrg !== undefined) {
        const orgVerdict = prepared.permissionRuleOrg
            .adjudicate({ toolName: pendingAction.toolName, args: executedArgs, toolCallId: pendingAction.toolCallId, ...callFaceSeat(beltFace()) })
            .catch(() => ({ status: "unavailable", disclosures: ["the org adjudication face threw on resume"] }));
        let orgWaitCancelled = false;
        const org = await settleOrgVerdictWithin(orgVerdict, { status: "unavailable", disclosures: [`the org adjudication face did not answer within ${ORG_ADJUDICATION_TIMEOUT_MS}ms (or the task ended first)`] }, {
            signal: prepared.abortController.signal,
            timeoutMs: ORG_ADJUDICATION_TIMEOUT_MS,
            onFallback: (cause) => {
                orgWaitCancelled = cause === "aborted";
            },
        });
        const unanswered = policyCannotAnswer(org, outcome.hostDecision.decidedBy);
        const blocked = org.status === "unavailable"
            ? realApprovalOrgFact(gateRealApproval) === "unavailable"
                ? undefined
                : orgWaitCancelled
                    ? "this deployment is org-governed and the task was cancelled before the organization policy snapshot could be adjudicated"
                    : "this deployment is org-governed and cannot currently adjudicate against an organization policy snapshot"
            : org.verdict?.behavior === "deny"
                ? `an organization policy rule (${org.verdict.rule}) denies it`
                : unanswered
                    ? `an organization policy rule (${org.verdict?.rule})${org.verdict?.unreadable !== undefined ? ` may reach this call, which could not be read against it (${org.verdict.unreadable}), so it` : ""} requires a person's approval for this call, and the decision recorded for it was the deployment's policy, not a person's`
                    : undefined;
        if (blocked !== undefined) {
            const orgDisclosures = org.status === "unavailable" && org.disclosures.length > 0
                ? ` Governance disclosures: ${inlineUntrusted(org.disclosures.join("; "), ORG_DISCLOSURE_MAX_CHARS)}.`
                : "";
            const orgDenial = formatHookFeedback(`The approved tool call "${pendingAction.toolName}" was not executed: ${blocked}.${orgDisclosures} This approval is spent — the call has to be re-issued and ${unanswered ? "decided by a person" : "approved again once organization policy permits it"}.`, prepared.reminderMark);
            await settleEnd(true, { content: orgDenial }, "org");
            const eid = await prepared.session.appendMessage(resultRow(orgDenial, true));
            emitCommitted(eid, "toolResult", pendingAction.toolCallId);
            return;
        }
    }
    if (prepared.denyNarrowingPolicy) {
        const narrowed = refuseOutOfContractDecision(await beltCheck((signal) => prepared.denyNarrowingPolicy.check(beltReq(), signal), "the narrowing rules re-checking a resumed call"));
        if (narrowed.action === "deny") {
            const narrowedDenial = formatHookFeedback(`The approved tool call "${pendingAction.toolName}" is now denied by ${ruleSourcePhrase("narrowing")} and was not executed${narrowed.message ? `: ${narrowed.message}` : ""}.`, prepared.reminderMark);
            await settleEnd(true, { content: narrowedDenial, ...denialCard(narrowed) }, "policy");
            const eid = await prepared.session.appendMessage(resultRow(narrowedDenial, true));
            emitCommitted(eid, "toolResult", pendingAction.toolCallId);
            return;
        }
    }
    const skillRefusal = skillRowRefusal(prepared.skillGrants, beltReq());
    if (skillRefusal !== undefined) {
        const skillDenial = formatHookFeedback(`The approved tool call "${pendingAction.toolName}" was not executed: ${skillRefusal.message}. This approval is spent — the call has to be re-issued.`, prepared.reminderMark);
        await settleEnd(true, { content: skillDenial }, "policy");
        emitCommitted(await prepared.session.appendMessage(resultRow(skillDenial, true)), "toolResult", pendingAction.toolCallId);
        return;
    }
    if (prepared.persistedRuleLane !== undefined) {
        const unreadable = { unreadable: true };
        let laneWaitCancelled = false;
        let laneRead;
        try {
            laneRead = Promise.resolve(prepared.persistedRuleLane.adjudicate(beltReq())).then((answer) => normalizePersistedRuleHit(answer));
        }
        catch {
            laneRead = Promise.resolve(unreadable);
        }
        const read = await settleOrgVerdictWithin(laneRead, unreadable, { signal: prepared.abortController.signal, timeoutMs: ORG_ADJUDICATION_TIMEOUT_MS, onFallback: (cause) => void (laneWaitCancelled = cause === "aborted") });
        const tightened = applyPersistedTightening({ action: "allow" }, read, beltReq());
        if (laneWaitCancelled || tightened.tightened === "deny" || tightened.tightened === "unreadable") {
            const why = laneWaitCancelled
                ? "the task was cancelled before your persisted permission rules could be read"
                : tightened.tightened === "deny"
                    ? `a standing deny rule of yours (${disclosedRuleSet(read.hit?.rules ?? [])}) now refuses it`
                    : `it could not be read against your standing deny/ask rules (${read.reason})`;
            const ruleDenial = formatHookFeedback(`The approved tool call "${pendingAction.toolName}" was not executed: ${why}. This approval is spent — the call has to be re-issued and approved again.`, prepared.reminderMark);
            await settleEnd(true, { content: ruleDenial, ...denialCard(tightened.decision) }, "persisted_rule");
            const eid = await prepared.session.appendMessage(resultRow(ruleDenial, true));
            emitCommitted(eid, "toolResult", pendingAction.toolCallId);
            return;
        }
    }
    if (prepared.shellReadCheck !== undefined) {
        const readCall = { toolName: pendingAction.toolName, ...callFaceSeat(beltFace()) };
        const judged = prepared.shellReadCheck.judge(readCall, executedArgs, prepared.cwdRef?.current, prepared.abortController.signal, {
            toolCallId: pendingAction.toolCallId,
            ...(unseen ? { seat: "rejudge" } : {}),
        });
        if (judged !== null) {
            let verdict;
            try {
                verdict = await withGateTimeout(judged, ORG_ADJUDICATION_TIMEOUT_MS, prepared.abortController.signal, "shellReadStation");
            }
            catch {
                verdict = prepared.shellReadCheck.unanswered(readCall, "the read station could not answer on the resumed leg");
            }
            const reading = readStationAnswer(verdict, { toolName: pendingAction.toolName, toolCallId: pendingAction.toolCallId });
            if (reading.kind === "refuse" || reading.kind === "silence" || (unseen && reading.kind !== "vouch")) {
                const readDenial = formatHookFeedback(`The approved tool call "${pendingAction.toolName}" was not executed: ${reading.verdict.sentence ?? "the read boundary does not vouch for what it reads on this leg"} This approval is spent — the call has to be re-issued and approved again.`, prepared.reminderMark);
                await settleEnd(true, { content: readDenial, ...(reading.verdict.details !== undefined ? { details: reading.verdict.details } : {}) }, "read_boundary");
                const eid = await prepared.session.appendMessage(resultRow(readDenial, true));
                emitCommitted(eid, "toolResult", pendingAction.toolCallId);
                return;
            }
            reading.verdict.admit?.();
        }
    }
    const grantRefusal = parkedSkillApprovalRefusal(pendingAction, executedArgs, prepared.skillSpecs, SKILL_TOOL_NAME, "execution");
    if (grantRefusal !== undefined) {
        const grantDenial = formatHookFeedback(grantRefusal, prepared.reminderMark);
        await settleEnd(true, { content: grantDenial }, "policy");
        emitCommitted(await prepared.session.appendMessage(resultRow(grantDenial, true)), "toolResult", pendingAction.toolCallId);
        return;
    }
    const tool = prepared.tools.find((t) => t.name === pendingAction.toolName);
    if (!tool) {
        const e = new Error(`the approved tool "${pendingAction.toolName}" is no longer available on resume`);
        e.code = "resume.tool_unavailable";
        throw e;
    }
    const args = executedArgs;
    screened?.admit();
    onExecuteStart?.(pendingAction.toolCallId);
    occurrences.release(pendingAction.toolCallId);
    prepared.suspendProgressRef.executedApproved = true;
    const finalize = (executed) => prepared.harness.finalizeToolCall({ type: "toolCall", id: pendingAction.toolCallId, name: spelledName, arguments: executedArgs }, executedArgs, executed);
    let res;
    try {
        res = await tool.execute(pendingAction.toolCallId, args, prepared.abortController.signal);
    }
    catch (err) {
        const execError = `Error: ${egressThrownText("same-principal", err)}`;
        const marks = egressValue("same-principal", thrownMarksOf(err));
        const failed = await finalize({ result: { content: [{ type: "text", text: execError }], details: marks ?? {} }, isError: true });
        const failedText = failed.result.content.flatMap((c) => (c.type === "text" ? [c.text] : [])).join("\n");
        await settleEnd(true, { content: failedText, ...(marks !== undefined ? { details: marks } : {}) });
        const eid = await prepared.session.appendMessage(resultRow(failedText, true));
        emitCommitted(eid, "toolResult", pendingAction.toolCallId);
        return;
    }
    const ran = await finalize({ result: res, isError: res.isError === true });
    await settleEnd(ran.isError, ran.result);
    onResolvedToolSuccess?.(pendingAction.toolName, ran.isError ? undefined : ran.result.details);
    const eid = await prepared.session.appendMessage({
        role: "toolResult",
        toolCallId: pendingAction.toolCallId,
        toolName: pendingAction.toolName,
        content: ran.result.content,
        details: rowDetailsOf(ran.result.details, notExecuted),
        isError: ran.isError,
        timestamp: Date.now(),
    });
    emitCommitted(eid, "toolResult", pendingAction.toolCallId);
}