UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

1,011 lines • 78 kB
import { snapshotActorAssertion } from "../../internal/llm.js";
import { spendRefusalOf } from "../../brain/spend-meter.js";
import { steeringPreview } from "./steering-preview.js";
import { instructionEchoTo } from "./nested-memory-lane.js";
import { isEngineQuestionFace } from "../ask-question.js";
import { CheckpointError, readPendingSteerQueue, realApprovalOrgFact, remainingBudgetMicroUsd } from "../checkpoint-store.js";
import { planReviewRequesterOf } from "../plan-review-facts.js";
import { readGateIdentity } from "../checkpoint-identity.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, legEventsOf, legNoticeTaskId, observePermissionDenied, openSubagent, screenUserPrompt, seatHears } from "../mods/stations.js";
import { raiseSessionEnd, raiseSessionStart } from "../mods/lifecycle-stations.js";
import { offeredAgentListing } from "../mods/agent-stations.js";
import { appendAdmittedRow } from "../row-admission.js";
import { buildAppliedHumanInputEvent, buildHumanInputEvent, personSteerFrame, projectHumanInput } from "../human-input-projection.js";
import { inputSourceOf } from "../steer-replay.js";
import { countsAsOperator, isScreened, judgedAuthorOf, objectiveAuthorOf } from "../input-author.js";
import { renderSkillMentionFrame, skillMentionsIn } from "./skill-mention.js";
import { humanInputAttachmentsOf, readObjectiveAttachments, userAttachmentDeclarations } from "../user-attachment.js";
import { findUnansweredToolBatch, NothingQueuedError, 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, carryArgsReadFrom, stampArgsReading } from "../effective-path-target.js";
import { skillGrantBindingMembers, skillRowRefusal } from "../skill-grant.js";
import { requestGrantBinding } from "../skill-grant-binding.js";
import { judgeApprovalObject } from "../approval-object.js";
import { SKILL_TOOL_NAME } from "./synthetic-tools.js";
import { mintSystemReminder } from "../reminder-mint.js";
import { truncateError } from "../tool-errors.js";
import { approvalMessageOf } from "../approval-display.js";
import { hasDestroy } from "../remote-env.js";
import { attestationOf, callFactsSeat, humanRefusalMessage, licenseCovers, ownArgs, ownedReading, policyRefusalMessage, refuseOutOfContractDecision } from "../tool-policy.js";
import { beltUnanswered, editRecheckUnanswered } from "../real-approval.js";
import { stationAskRowOf } from "../ask-origin.js";
import { failedJudgmentDeny } from "./policy-throw.js";
import { pathDenialCardOf } from "../../tools/fs/safety.js";
import { callFaceSeat, parkedRowLiveFace, rosterEntryNamed, rowMember } from "../tool-roster.js";
import { deliverEngineNotice, endNoticeFact } from "../types.js";
import { READ_DENY_FLOOR_UNKEPT } from "../../tools/fs/read-floor.js";
import { delimitUntrusted, inlineUntrusted, REVIEWER_NOTE_MAX_BODY, sanitizeUntrustedText } from "../untrusted-text.js";
import { errorCodeOf } from "./terminal-account.js";
import { platformLimitTerminal } from "./clock-and-limits.js";
import { legContextOverlayOption } from "./compaction-call-options.js";
import { mintOutputStyleReminder, owedPostureText } from "./compaction-restate.js";
import { announceWhenCarried, scanChangedFiles } from "./changed-files-scan.js";
import { advisorFrameText, registerAdvisorReceipt } from "./advisor-instructions.js";
import { languageFrameText, registerLanguageReceipt } from "./language-frame.js";
import { registerSandboxFrameReceipt, sandboxFrameText } from "./command-sandbox-frame.js";
import { resumeContinuation } from "./decide-continuation.js";
import { sameBytes } from "../rewrite-rejudge.js";
import { editOfAnswer, exactBoundInputHashOf } from "../canonical-json.js";
import { approvalWordsOf, owedApprovalWords, withApprovalWords } from "./approval-feedback.js";
import { chainCannotJudge } from "./call-hook-stations.js";
import { settleExecutionRecord } from "./execution-record.js";
import { holdPrompt } from "./prompt-block.js";
import { frozenInputSnapshot, permissionDeniedOf } from "./gate-exit.js";
import { withGateTimeout } from "../gate-bounded-await.js";
import { unestablishedDetails } from "../../tools/fs/shell-read-check.js";
import { readStationAnswer } from "../shell-read-silence.js";
import { resolveGitLegDelivery, wrapGitFrame } from "./git-leg-delivery.js";
import { GIT_STATUS_ECHO_PREVIEW, protectedGitFrameOf } from "./git-status-frame.js";
import { toImageContents } from "./image.js";
import { isBareHumanRefusal, maybeHumanRejectionHalt } from "./prepare-gate-stations.js";
import { nextHumanInputSeq } from "./steer-admission.js";
import { usableInputId } from "../user-row-origin.js";
import { settleTeardownLeg } from "./teardown-bounded.js";
import { runAbortedError } from "../terminal-cause.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, changedFilesNoticeIn, collectChangedFilesFirstRequestFrame, collectDateChange, commitAgentListing, commitSkillsListing, owedMcpUnavailable, reduceToolEnd, renderAgentListingFrame, renderOrphanedBackgroundTasks, renderSkillsListingFrame, stampWriteAnchor } from "./turn-attachments.js";
import { flushOwedAnnouncedSnapshot, settleMcpUnavailable } from "./announce-once-ledger.js";
import { intakeOfCommit } from "../task-intake.js";
import { thrownMarksOf } from "../thrown-value.js";
import { egressThrownText, egressValue } from "../untrusted-egress.js";
import { ruleSourcePhrase } from "../rule-denial-sentence.js";
import { runWithCommandSandboxPlan } from "../command-sandbox-dispatch.js";
export async function runLeg(input) {
    const { spec, queue, prepared, resume, rs, entryActor, objectiveAuthor, effectiveTimeoutMs, timeout, pushContent, ident, emitCommitted, taskIdRef, 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 = [];
    const legRunOrigin = prepared.wiringManifest.leg?.runOrigin;
    const recordIntake = (entryId) => {
        if (taskIdRef !== undefined)
            taskIdRef.intake = intakeOfCommit(prepared.sessionId, entryId);
    };
    try {
        const starting = raiseSessionStart(prepared.modBus, prepared.hookIdentity, { cwd: prepared.cwdRef?.current ?? prepared.taskRootPath, sessionId: prepared.sessionId }, prepared.abortController.signal);
        if (starting !== undefined)
            await starting;
        if (prepared.abortController.signal.aborted)
            throw runAbortedError();
        const adoption = await prepared.legAdoption.run();
        if (prepared.abortController.signal.aborted)
            throw runAbortedError();
        if (resume) {
            const walltimeExhaustedResume = effectiveTimeoutMs !== undefined && effectiveTimeoutMs <= 0;
            const approvalWords = approvalWordsOf(resume.outcome);
            const approvalFrames = owedApprovalWords(approvalWords, uuidv7());
            prepared.undeliveredContinuationRef.current.parkedSteers.push(...approvalFrames);
            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 })).tag === "committed";
                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.engineText), 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 unavailableResume = owedMcpUnavailable(prepared, rs.attach.attachmentsCfg);
                if (unavailableResume !== undefined)
                    continuation += "\n\n" + mintSystemReminder(sanitizeUntrustedText(unavailableResume.body, attachmentEnvelopeTags("mcp_unavailable")), prepared.reminderMark);
                const continuationResume = adoption.workflowContinuation;
                if (continuationResume !== undefined)
                    continuation += "\n\n" + mintSystemReminder(sanitizeUntrustedText(continuationResume, attachmentEnvelopeTags("workflow_continuation")), prepared.reminderMark);
                let changedResume;
                if (rs.attach.attachState !== undefined) {
                    const batchOpen = async () => findUnansweredToolBatch((await prepared.session.buildContext()).messages) !== undefined;
                    const changedResumeScan = scanChangedFiles({ cfg: rs.attach.attachmentsCfg, detect: prepared.detectExternalChanges, ledger: prepared.frameReceipts, settlesFirst: batchOpen });
                    if (changedResumeScan !== undefined)
                        changedResume = collectChangedFilesFirstRequestFrame(await changedResumeScan, prepared.engineText);
                }
                const changedResumeBlock = changedResume === undefined ? undefined : mintSystemReminder(sanitizeUntrustedText(changedResume.body, attachmentEnvelopeTags("changed_files")), prepared.reminderMark);
                if (changedResumeBlock !== undefined)
                    continuation += "\n\n" + changedResumeBlock;
                if (prepared.memoryNoticesFrame !== undefined)
                    continuation += "\n\n" + prepared.memoryNoticesFrame;
                const advisorResumeFrame = advisorFrameText(prepared);
                if (advisorResumeFrame !== undefined)
                    continuation += "\n\n" + advisorResumeFrame;
                const languageResumeFrame = languageFrameText(prepared);
                if (languageResumeFrame !== undefined)
                    continuation += "\n\n" + languageResumeFrame;
                const sandboxResumeFrame = sandboxFrameText(prepared);
                if (sandboxResumeFrame !== undefined)
                    continuation += "\n\n" + sandboxResumeFrame;
                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 = [];
                let personSpoke = false;
                const withheldSteerIds = new Set();
                const answeredInputs = [];
                for (const { entry: steer, source } of resumeFrames) {
                    const named = inputSourceOf(steer, source);
                    if (source === "steer" && steer.reply !== undefined) {
                        const { reply } = steer;
                        const { seq: _seq, ...record } = steer;
                        answeredInputs.push({
                            text: personSteerFrame(reply.entered ?? steer.text, steer.actor, steer.trusted, prepared.reminderMark, named),
                            provenance: {
                                provenance: "engine-note",
                                author: "operator",
                                parkRecord: record,
                                ...(steer.actor !== undefined ? { actor: steer.actor } : {}),
                                ...(steer.runOrigin !== undefined ? { runOrigin: steer.runOrigin } : {}),
                            },
                            answer: { text: reply.text, by: reply.by },
                        });
                        continue;
                    }
                    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 });
                    }
                    let delivered = { text: steer.text, rewrittenBy: source === "wake" ? resume.wakeMessageRewrittenBy : undefined };
                    if (source === "steer") {
                        const screen = await screenUserPrompt(prepared.modBus, {
                            ...classicEventBase(prepared.hookIdentity, prepared.permissionMode.observed),
                            prompt: steer.text,
                            source: inputSourceOf(steer, "parked_redelivery"),
                            ...(steer.inputId !== undefined ? { inputId: steer.inputId } : {}),
                            ...(steer.actor !== undefined ? { actor: snapshotActorAssertion(steer.actor) } : {}),
                        }, prepared.abortController.signal, { author: "operator", whileScreened: prepared.hookScreens.prompt });
                        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,
                                        ...legNoticeTaskId(prepared),
                                    },
                                });
                                queue.push({
                                    ...buildHumanInputEvent({
                                        carrier: source,
                                        source: named,
                                        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 } : {}),
                                        ...(steer.runOrigin !== undefined ? { runOrigin: steer.runOrigin } : {}),
                                    }),
                                    ...ident(),
                                });
                                continue;
                            }
                            if (screen.kind === "answered" && screen.rewrittenBy !== undefined)
                                delivered = { text: screen.text, rewrittenBy: screen.rewrittenBy };
                            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;
                    continuation += "\n\n" + personSteerFrame(delivered.text, steer.actor, steer.trusted, prepared.reminderMark, named);
                    if (steer.trusted)
                        engineSegments.push({ start, end: continuation.length });
                    if (named !== "system")
                        personSpoke = true;
                    appliedEvents.push(() => ({
                        ...buildAppliedHumanInputEvent({ carrier: source, source: named, sessionSeq: nextHumanInputSeq(prepared.harness), inputId: steer.inputId, actor: steer.actor, principal: spec.principal, runOrigin: steer.runOrigin, rewrittenBy: delivered.rewrittenBy }),
                        ...ident(),
                    }));
                }
                if (approvalWords !== undefined)
                    continuation = withApprovalWords(continuation, engineSegments, approvalWords);
                const pending = resume.cp.pendingAction;
                const decided = resume.outcome.gate === "policy_ask" || resume.outcome.gate === "plan_review" ? resume.outcome.gateOutcome : undefined;
                const refusalEndsTurn = isBareHumanRefusal(decided, prepared.hookIdentity.isDelegatedChild);
                const rejectionHalt = refusalEndsTurn && pending.kind === "tool_approval"
                    ? maybeHumanRejectionHalt({ gate: decided, isDelegatedChild: prepared.hookIdentity.isDelegatedChild, toolName: pending.toolName, toolCallId: pending.toolCallId })
                    : undefined;
                const refusedCallId = pending.kind === "tool_approval" ? pending.toolCallId : planReviewRequesterOf(pending);
                if (refusalEndsTurn)
                    prepared.batchHaltRef.current = { ...(refusedCallId !== undefined ? { rejectedToolCallId: refusedCallId } : {}) };
                prepared.undeliveredContinuationRef.current = { parkedSteers: [...resumeFrames.map(({ entry }) => entry).filter((e) => !withheldSteerIds.has(e.inputId)), ...approvalFrames], orphanTasks };
                if (!prepared.abortController.signal.aborted) {
                    registerAdvisorReceipt(prepared, continuation);
                    registerLanguageReceipt(prepared, continuation);
                    registerSandboxFrameReceipt(prepared, continuation);
                    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 = steeringPreview(prepared.outputStyleFrame);
                        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)) });
                    }
                    if (postureText !== undefined)
                        prepared.frameReceipts.pending.push({ source: "posture", text: continuation, commit: () => undefined });
                    if (changedResume !== undefined) {
                        const frame = changedResume;
                        prepared.frameReceipts.pending.push({ source: "changed_files", text: continuation, commit: announceWhenCarried(prepared, () => void (queue.push({ type: "steering_injected", source: "changed_files", preview: steeringPreview(frame.body), ...ident() }), (rs.attach.attachmentsInjected += 1))) });
                    }
                    if (unavailableResume !== undefined)
                        prepared.frameReceipts.pending.push({ source: "mcp_unavailable", text: continuation, commit: () => void (settleMcpUnavailable(prepared, unavailableResume.entries), queue.push({ type: "steering_injected", source: "mcp_unavailable", preview: steeringPreview(unavailableResume.body), ...ident() }), (rs.attach.attachmentsInjected += 1)) });
                    if (continuationResume !== undefined)
                        prepared.frameReceipts.pending.push({ source: "workflow_continuation", text: continuation, commit: () => void (queue.push({ type: "steering_injected", source: "workflow_continuation", preview: steeringPreview(continuationResume), ...ident() }), (rs.attach.attachmentsInjected += 1)) });
                    const laneFirst = prepared.nestedMemory === undefined ? undefined : await prepared.nestedMemory.load({ echo: instructionEchoTo(queue, ident, rs.attach) });
                    if (laneFirst !== undefined)
                        prepared.attachmentDelivery.stage(laneFirst.inputId, laneFirst.frames);
                    if (prepared.turnOpenRedelivery.current !== undefined)
                        await prepared.turnOpenRedelivery.current;
                    const resumeNotice = changedResume !== undefined && changedResumeBlock !== undefined ? changedFilesNoticeIn(continuation, changedResumeBlock, changedResume) : undefined;
                    prepared.runTimeReminders.opening.current = { byPerson: appliedEvents.length > 0, at: Date.now() };
                    final = await withBrainSinks(() => prepared.harness.prompt(continuation, {
                        engineSegments,
                        ...(resumeNotice !== undefined ? { changedFilesNotices: [resumeNotice] } : {}),
                        ...(laneFirst !== undefined ? { trailing: laneFirst.frames.map((f) => f.seed) } : {}),
                        settleUnansweredToolCalls: rejectionHalt !== undefined ? { halt: rejectionHalt } : {},
                        ...(refusalEndsTurn && appliedEvents.length === 0 ? { endsAwaitingUser: true } : {}),
                        ...(answeredInputs.length > 0 ? { answeredInputs } : {}),
                        ...(appliedEvents.length > 0 ? { input: usableInputId(resume.wakeMessage?.inputId) !== undefined ? { inputId: resume.wakeMessage.inputId } : {} } : {}),
                        onCommitted: (entryId) => {
                            recordIntake(entryId);
                            if (personSpoke)
                                prepared.runTimeReminders.elapsedClock.restart();
                            if (resume !== undefined)
                                resume.decisionDelivered = true;
                            prepared.undeliveredContinuationRef.current = { parkedSteers: [], orphanTasks: [] };
                            for (const applied of appliedEvents)
                                queue.push(applied());
                        },
                    }));
                    await flushGitMirror();
                    if (prepared.gitStatusRef.announced?.pending === true)
                        await prepared.gitStatusRef.reassert?.();
                }
            }
        }
        else {
            const objectiveActor = entryActor;
            let projectedObjective = projectHumanInput({ text: spec.objective ?? "", actor: objectiveActor, source: "objective" });
            let objectiveWords = spec.objective ?? "";
            let objectiveRewrittenBy;
            let effectiveObjective = projectedObjective;
            let promptBlocked = false;
            let objectiveReply;
            const author = objectiveAuthorOf(objectiveAuthor, (e) => runner.deps.onError?.(e, { phase: "config", sessionId: prepared.sessionId, classification: "input-author-unreadable" }));
            const objectiveEvents = legEventsOf(prepared.hookIdentity);
            const wakeLeg = spec.wake !== undefined;
            if (!wakeLeg && isScreened(author)) {
                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, { author: judgedAuthorOf(author), whileScreened: prepared.hookScreens.prompt });
                if (screen?.kind === "answered" && screen.rewrittenBy !== undefined) {
                    projectedObjective = projectHumanInput({ text: screen.text, actor: objectiveActor, source: "objective" });
                    objectiveWords = screen.text;
                    objectiveRewrittenBy = screen.rewrittenBy;
                    effectiveObjective = projectedObjective;
                }
                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?.reply !== undefined)
                        objectiveReply = screen.reply;
                    if (screen?.additionalContext)
                        effectiveObjective = `${formatHookFeedback(screen.additionalContext, prepared.reminderMark)}\n\n${projectedObjective}`;
                }
            }
            if (objectiveEvents.start !== undefined && !promptBlocked) {
                const start = await openSubagent(prepared.modBus, prepared.hookIdentity, prepared.permissionMode.observed, prepared.abortController.signal);
                if (start?.additionalContext)
                    effectiveObjective = `${formatHookFeedback(start.additionalContext, prepared.reminderMark)}\n\n${effectiveObjective}`;
            }
            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}`;
                    const substitute = gitFrame.kind === "full" && gitFrame.shrunk !== undefined ? { find: wrappedGit, replace: wrapGitFrame(gitFrame.shrunk.body, prepared.reminderMark) } : undefined;
                    gitLegDelivered = { kind: gitFrame.kind, hash: gitFrame.hash, standalone, wrapped: wrappedGit, ...(substitute !== undefined ? { substitute } : {}) };
                    if (substitute !== undefined)
                        prepared.gitStatusRef.wrappedShrink = substitute;
                }
            }
            const firstFrames = [];
            const legToday = rs.attach.dateState !== undefined ? prepared.dateChange.today() : undefined;
            const dateFrame = legToday !== undefined ? collectDateChange(rs.attach.dateState, legToday, prepared.engineText) : undefined;
            if (dateFrame !== undefined)
                firstFrames.push({ source: "date_change", body: dateFrame.body, commit: () => void (rs.attach.dateState.announcedDate = legToday), disclose: () => undefined });
            const unavailable = owedMcpUnavailable(prepared, rs.attach.attachmentsCfg);
            if (unavailable !== undefined)
                firstFrames.push({ source: "mcp_unavailable", body: unavailable.body, commit: () => settleMcpUnavailable(prepared, unavailable.entries), disclose: () => undefined });
            if (adoption.workflowContinuation !== undefined)
                firstFrames.push({ source: "workflow_continuation", body: adoption.workflowContinuation, commit: () => undefined, disclose: () => undefined });
            if (rs.attach.attachState !== undefined) {
                const attach = rs.attach.attachState;
                const offeredListing = !rs.attach.agentListingOn ? undefined : seatHears({ bus: prepared.modBus }, "agent.offer") ? await offeredAgentListing({ bus: prepared.modBus }, prepared.agentListing, prepared.abortController.signal) : prepared.agentListing;
                if (offeredListing !== undefined) {
                    const listing = offeredListing;
                    const frame = renderAgentListingFrame(attach, listing.entries, listing.toolName, listing.models, listing.budget, prepared.engineText);
                    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, prepared.engineText);
                    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 });
            let changedFirst;
            if (!promptBlocked && rs.attach.attachState !== undefined) {
                const changedScan = scanChangedFiles({ cfg: rs.attach.attachmentsCfg, detect: prepared.detectExternalChanges, ledger: prepared.frameReceipts });
                changedFirst = changedScan === undefined ? undefined : collectChangedFilesFirstRequestFrame(await changedScan, prepared.engineText);
                if (changedFirst !== undefined)
                    firstFrames.push({ source: "changed_files", body: changedFirst.body, commit: () => undefined, disclose: () => undefined });
            }
            if (!promptBlocked && !wakeLeg && countsAsOperator(author) && prepared.skillsListing !== undefined && prepared.promptManifest.selectors.host.role !== "coordinator") {
                const named = skillMentionsIn(objectiveWords, new Set(prepared.skillsListing.entries.map((e) => e.name)));
                const mentionBody = named.length > 0 ? renderSkillMentionFrame(named, prepared.engineText) : undefined;
                if (mentionBody !== undefined)
                    firstFrames.push({ source: "skill_mention", body: mentionBody, commit: () => undefined, disclose: () => undefined });
            }
            if (prepared.memoryNoticesFrame !== undefined)
                effectiveObjective = `${prepared.memoryNoticesFrame}\n${effectiveObjective}`;
            if (firstFrames.length > 0) {
                effectiveObjective = `${firstFrames.map((f) => mintSystemReminder(sanitizeUntrustedText(f.body, attachmentEnvelopeTags(f.source)), prepared.reminderMark)).join("\n")}\n${effectiveObjective}`;
            }
            const advisorFrame = advisorFrameText(prepared);
            if (advisorFrame !== undefined)
                effectiveObjective = `${advisorFrame}\n${effectiveObjective}`;
            const languageFrame = languageFrameText(prepared);
            if (languageFrame !== undefined)
                effectiveObjective = `${languageFrame}\n${effectiveObjective}`;
            const sandboxFrame = sandboxFrameText(prepared);
            if (sandboxFrame !== undefined)
                effectiveObjective = `${sandboxFrame}\n${effectiveObjective}`;
            const postureText = await owedPostureText(prepared, "always");
            if (postureText !== undefined)
                effectiveObjective = `${postureText}\n${effectiveObjective}`;
            const objectiveInputId = uuidv7();
            if (!wakeLeg && countsAsOperator(author))
                prepared.runTimeReminders.elapsedClock.admit(objectiveInputId);
            const enginePrefixChars = effectiveObjective.length - projectedObjective.length;
            const standingGit = gitLegDelivered === undefined ? protectedGitFrameOf(prepared.gitStatusRef) : undefined;
            const objectiveGit = gitLegDelivered ?? (standingGit !== undefined ? { wrapped: standingGit.protectedText, standalone: false, ...(standingGit.substitute !== undefined ? { substitute: standingGit.substitute } : {}) } : undefined);
            const { frames: attachmentFrames } = await readObjectiveAttachments(prepared, objectiveInputId, promptBlocked, { text: effectiveObjective, prefixChars: enginePrefixChars, images: spec.images?.length ?? 0, ...(objectiveGit !== undefined ? { git: objectiveGit } : {}), overlay: () => legContextOverlayOption(prepared, runner).contextOverlay }, runner.deps.imageProcessor);
            const nestedFirst = promptBlocked || prepared.nestedMemory === undefined ? undefined : await prepared.nestedMemory.load({ triggers: attachmentFrames.flatMap((f) => (f.seed.attachment.observation !== undefined ? [f.seed.attachment.observation.key] : [])), echo: instructionEchoTo(queue, ident, rs.attach) });
            const trailingFrames = nestedFirst === undefined ? attachmentFrames : [...attachmentFrames, ...nestedFirst.frames];
            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 (effectiveTimeoutMs !== undefined && effectiveTimeoutMs <= 0) {
                timeout.fired = true;
                timeout.clear();
                void prepared.harness.abort();
                prepared.abortController.abort();
            }
            else {
                const images = spec.images ? await toImageContents(spec.images, prepared.hostFloor, runner.deps.imageProcessor, prepared.imageUnprocessed) : 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) {
                    const announce = () => void (queue.push({ type: "steering_injected", source: f.source, preview: steeringPreview(f.body), ...ident() }), (rs.attach.attachmentsInjected += 1));
                    const commit = f.source === "changed_files" ? announceWhenCarried(prepared, announce) : () => void (f.commit(), announce(), f.disclose());
                    prepared.frameReceipts.pending.push({ source: f.source, text: effectiveObjective, commit });
                }
                if (postureText !== undefined)
                    prepared.frameReceipts.pending.push({ source: "posture", text: effectiveObjective, commit: () => undefined });
                registerAdvisorReceipt(prepared, effectiveObjective);
                registerLanguageReceipt(prepared, effectiveObjective);
                registerSandboxFrameReceipt(prepared, effectiveObjective);
                if (!prepared.abortController.signal.aborted) {
                    prepared.attachmentDelivery.stage(objectiveInputId, attachmentFrames);
                    if (nestedFirst !== undefined)
                        prepared.attachmentDelivery.stage(nestedFirst.inputId, nestedFirst.frames);
                    if (!wakeLeg)
                        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) } : {}),
                                ...(legRunOrigin !== undefined ? { runOrigin: legRunOrigin } : {}),
                                ...(objectiveRewrittenBy !== undefined ? { rewrittenBy: objectiveRewrittenBy } : {}),
                            }),
                            ...ident(),
                        });
                    if (prepared.turnOpenRedelivery.current !== undefined)
                        await prepared.turnOpenRedelivery.current;
                    prepared.runTimeReminders.opening.current = { byPerson: !wakeLeg, at: Date.now() };
                    const firstNotice = changedFirst === undefined ? undefined : changedFilesNoticeIn(effectiveObjective, mintSystemReminder(sanitizeUntrustedText(changedFirst.body, attachmentEnvelopeTags("changed_files")), prepared.reminderMark), changedFirst);
                    final = await withBrainSinks(() => wakeLeg
                        ?
                            prepared.harness.prompt(effectiveObjective, { engineMinted: true, opensOnQueuedInput: true }).catch((error) => {
                                if (!(error instanceof NothingQueuedError))
                                    throw error;
                                throw Object.assign(new Error("TaskSpec.wake: no notification is parked for this session's occupant — nothing to wake on (no model request was made)."), { code: "config.nothing_to_wake" });
                            })
                        : prepared.harness.prompt(effectiveObjective, {
                            ...(images && images.length > 0 ? { images } : {}),
                            ...(enginePrefixChars > 0 ? { enginePrefixChars } : {}),
                            ...(firstNotice !== undefined ? { changedFilesNotices: [firstNotice] } : {}),
                            input: { inputId: objectiveInputId },
                            ...(trailingFrames.length > 0 ? { trailing: trailingFrames.map((f) => f.seed) } : {}),
                            ...(objectiveActor !== undefined ? { actor: objectiveActor } : {}),
                            ...(legRunOrigin !== undefined ? { runOrigin: legRunOrigin } : {}),
                            ...(objectiveReply !== undefined ? { givenAnswer: objectiveReply } : {}),
                            onCommitted: recordIntake,
                        }));
                    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 }));
            if (prepared.ownedEnv !== undefined && taskIdRef !== undefined && resume?.cp.state.workspaceHandle !== undefined)
                taskIdRef.legEnvForRow = prepared.ownedEnv;
            else
                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 }));
            const ending = raiseSessionEnd(prepared, prepared.hookIdentity, { reason: "failed", sessionId: prepared.sessionId });
            if (ending !== undefined)
                await ending;
            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();
        prepared.hookProgress.close();
        if (prepared.readFloorUnkept.judged && !prepared.readFloorUnkept.current)
            endNoticeFact(prepared.legNotice.told, READ_DENY_FLOOR_UNKEPT, {});
        prepared.mcp.ended?.();
        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();
        prepared.prefixChanges.unsubscribe();
        prepared.endPrefixLeg();
        unsubGitRetry();
        unsubBoundary();
        unsub();
    }
    if (final !== undefined && spendRefusalOf(final)?.sent === false) {
        final = rs.turn.lastProduced;
        prepared.workCutRef.continuation = true;
    }
    return await next({ final, threw, abortedLive, userInterruptedLive, strandedHumanAnswers });
}
const ORG_DISCLOSURE_MAX_CHARS = 600;
const ORG_RULE_CLASSES = Object.freeze(["org_rule"]);
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;
    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 answered = outcome.hostDecision.decidedBy === "person" ? pendingAction.classes : undefined;
    const mounted = () => { const roster = prepared.toolRosterDeltas.current; const entry = roster === undefined ? undefined : rosterEntryNamed(roster, pendingAction.toolName); const tool = entry?.name === pendingAction.toolName ? rowMember(entry) : undefined; return tool === undefined ? {} : { tool, entry }; };
    const reopen = (miss) => { throw Object.assign(new Error(miss.message), { code: miss.code }); };
    if (outcome.decision === "allow" && prepared.mcp.pending !== undefined && (mounted().entry === undefined || mounted().entry?.source === "mcp")) {
        await prepared.mcp.pending.settled({ signal: prepared.abortController.signal });
        prepared.abortController.signal.throwIfAborted();
    }
    const liveTool = mounted().tool;
    const atSession = outcome.decision === "allow" ? judgeApprovalObject(pendingAction, { tool: mounted().entry }, "session") : "match";
    if (atSession !== "match" && atSession.disposition === "reopen")
        reopen(atSession);
    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 = isEngineQuestionFace(parkedRowLiveFace(prepared.toolRosterDeltas.current, pendingAction)) ? undefined : editOfAnswer(pendingAction.toolName, exactBoundInputHashOf(pendingAction.toolName, pendingAction.args), outcome.updatedInput);
    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 {
            const read = reading === undefined ? v : argsReadBy(reading, v);
            const owned = ownArgs(read);
            if (owned.ok && owned.value !== read)
                carryArgsReadFrom(read, owned.value);
            return { args: owned.ok ? owned.value : read };
        }
        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 = liveTool?.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, ...(resume.cp.checkpointId !== undefined ? { resumesCheckpoint: resume.cp.checkpointId } : {}) };
    announceToolCall(occurrences, callStart, { push: emit });
    const decidedInput = frozenInputSnapshot(resolvedArgs);
    occurrences.gateRound(pendingAction.toolCallId, decidedGate, decidedInput);
    let notExecuted;
    const resultRow = (text, isError) => withRowNotExecuted(toolResultMsg(pendingAction.toolCallId, pendingAction.toolName, text, isError), notExecuted);
    const settleEnd = async (isError, result, neverRan) => {
        const settled = emitSettled(occurrences, callStart, { result, isError, ...(neverRan ? { notExecuted: true } : {}) }, { push: emit, structured: prepared.structuredProjector, mediaBudgetBase64Chars: runner.deps.mediaBudgetBase64Chars, reviewRequest: prepared.reviewRequestRef, verdicts: prepared.verdictLedger });
        notExecuted = settled;
        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, identity: readGateIdentity(resume.cp.checkpointId, resume.cp.token) });
    };
    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 } : {}) }, true);
        emitCommitted(await appendAdmittedRow(prepared.admitRows, prepared.session, resultRow(text, true)), "toolResult", pendingAction.toolCallId);
    };
    const refuseCall = async (sentence, by, card = {}) => {
        const gate = by === undefined ? decidedGate : occurrences.refuse(pendingAction.toolCallId, by.layer, by.facts);
        await observePermissionDenied({ legBus: prepared.modBus, payload: permissionDeniedOf({ toolName: pendingAction.toolName, finalInput: decidedInput, toolCallId: pendingAction.toolCallId, reason: sentence, gate, identity: prepared.hookIdentity, permissionMode: prepared.permissionMode.observed }), signal: prepared.abortController.signal });
        const text = by === undefined ? truncateError(formatHookFeedback(sentence, prepared.reminderMark)) : formatHookFeedback(sentence, prepared.reminderMark);
        await settleEnd(true, { content: text, ...card });
        emitCommitted(await appendAdmittedRow(prepared.admitRows, prepared.session, resultRow(text, true)), "toolResult", pendingAction.toolCallId);
    };
    const vetoApproval = (miss) => refuseCall(miss.message, { layer: "policy" }, miss.code !== undefined ? { details: { code: miss.code } } : {});
    if (outcome.decision === "deny") {
        const settlementKind = outcome.gateOutcome?.settlement?.kind;
        const question = () => { try {
            return approvalMessageOf(pendingAction.cardMessage);
        }
        catch {
            return undefined;
        } };
        const windowNote = decidersNote(outcome.reason);
        const reason = settlementKind === "policy_refused"
            ? policyRefusalMessage(pendingAction.toolName, question(), decidersNote(outcome.reason), outcome.hostDecision.decidedVia, true)
            : settlementKind === "park_sla_expired"
                ? `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.${windowNote !== undefined ? `\nReviewer note:\n${delimitUntrusted("reviewer note", windowNote, REVIEWER_NOTE_MAX_BODY)}` : ""}`
                : humanRefusalMessage(pendingAction.toolName, question(), outcome.reason, prepared.hookIdentity.isDelegatedChild);
        await refuseCall(reason);
        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, decidedVia: outcome.hostDecision.decidedVia });
        }
        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 (atSession !== "match")
        return vetoApproval(atSession);
    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), answered });
    if (screened !== undefined && "refused" in screened)
        return refuseCall(screened.refused, { layer: "hook", facts: screened.extension !== undefined ? { extension: screened.extension } : undefined });
    const executedArgs = resolvedArgs;
    const unseen = !licenseCovers(pendingAction.boundInputHash, pendingAction.toolName, executedArgs);
    let beltReading;
    const beltReq = () => ({ toolName: pendingAction.toolName, args: executedArgs, toolCallId: pendingAction.toolCallId, ...callFactsSeat({ face: beltFace(), budget: beltBudget, cwd: prepared.cwdRef?.current, root: prepared.handsRoot, advertisedWritableDirs: prepared.advertisedWritableDirs, exemptRoots: prepared.exemptRoots }), ...(beltReading !== undefined ? { targetReading: beltReading } : {}), ...requestGrantBinding((call, args) => skillGrantBindingMembers(call, args, prepared.skillSpecs, SKILL_TOOL_NAME), pendingAction, executedArgs) });
    const unjudgeable = unseen ? chainCannotJudge(resume.cp.state.inheritedGate) : undefined;
    if (unjudgeable !== undefined)
        return refuseCall(`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.`, { layer: "policy" });
    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 = editRecheckUnanswered(rechecked, { toolCallId: pendingAction.toolCallId, toolName: pendingAction.toolName }, answered);
        const rewrite = rechecked.updatedInput !== undefined ? tryRead(rechecked.updatedInput) : undefined;
        const rewrote = rewrite !== undefined && (rewrite.unread !== undefined || !sameBytes({}, rewrite.args, executedArgs));
        if (rechecked.action === "deny" || rewrote || personUnanswered) {
            const why = rechecked.action === "deny"
                ? (rechecked.message ? `: ${rechecked.message}` : "")
                : personUnanswered
                    ? " (the call as it would run raises a question that requires a person's approval, and no person answered that question for this call; send the call again to have it asked)"
                    : " (the policy rewrote these bytes to a value that was not approved)";
            const outlet = rechecked.action !== "deny" && !personUnanswered && rewrite?.unread === undefined && rewrite !== undefined ? { details: { editRewritten: { acceptableForm: rewrite.args } } } : denialCard(rechecked);
            return refuseCall(`The approver EDITED this call's input; the edited call is refused by the deployment's tool policy and was not executed${why}.`, { layer: "policy" }, outlet);
        }
    }
    const gateRealApproval = resume.cp.gate.kind === "irreversible_ask" ? resume.cp.gate.realApproval : undefined;
    const gateOrgGoverned = realApprovalOrgFact(gateRealApproval) !== undefined;
    if (gateOrgGoverned && prepared.permissionRuleOrg === undefined) {
        return refuseCall(`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.`, { layer: "org" });
    }
    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 = beltUnanswered(org, ORG_RULE_CLASSES, answered);
        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 not a person's answer to a question that rule asked`
                    : undefined;
        if (blocked !== undefined) {
            const orgDisclosures = org.status === "unavailable" && org.disclosures.length > 0
                ? ` Governance disclosures: ${inlineUntrusted(org.disclosures.join("; "), ORG_DISCLOSURE_MAX_CHARS)}.`
                : "";
            return refuseCall(`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"}.`, { layer: "org" });
        }
    }
    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") {
            return refuseCall(`The approved tool call "${pendingAction.toolName}" is now denied by ${ruleSourcePhrase("narrowing")} and was not executed${narrowed.message ? `: ${narrowed.message}` : ""}.`, { layer: "policy" }, denialCard(narrowed));
        }
    }
    const skillRefusal = skillRowRefusal(prepared.skillGrants, beltReq());
    if (skillRefusal !== undefined)
        return refuseCall(`The approved tool call "${pendingAction.toolName}" was not executed: ${skillRefusal.message}. This approval is spent — the call has to be re-issued.`, { layer: "policy" });
    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})`;
            return refuseCall(`The approved tool call "${pendingAction.toolName}" was not executed: ${why}. This approval is spent — the call has to be re-issued and approved again.`, { layer: "persisted_rule" }, denialCard(tightened.decision));
        }
    }
    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, toolCallId: pendingAction.toolCallId }, "the read station could not answer on the resumed leg", executedArgs);
            }
            const reading = readStationAnswer(verdict, { toolName: pendingAction.toolName, toolCallId: pendingAction.toolCallId });
            const row = reading.kind === "refuse" ? undefined : stationAskRowOf(reading.verdict, reading.verdict.writeAskRule !== undefined ? prepared.permissionMode.current : undefined);
            if (reading.kind === "refuse" || reading.kind === "silence" || (unseen && (reading.kind !== "vouch" || row !== undefined))) {
                return refuseCall(`The approved tool call "${pendingAction.toolName}" was not executed: ${reading.verdict.sentence ?? (row?.face === "write" ? `an ask rule (${inlineUntrusted(row.rule, 200)}) asks about what the edited command writes on this leg` : "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.`, { layer: "read_boundary", facts: reading.verdict.echoed !== undefined ? { echoed: reading.verdict.echoed } : undefined }, reading.verdict.details !== undefined ? { details: reading.verdict.details } : {});
            }
            reading.verdict.admit?.();
        }
    }
    let tool;
    for (;;) {
        const { targetReading: _belts, ...unread } = beltReq();
        const targetReading = (await prepared.stampCallTarget?.(unread, prepared.abortController.signal))?.targetReading;
        const reads = prepared.shellReadLandings?.(pendingAction.toolCallId);
        const landings = prepared.declaredReadKeys?.(pendingAction.toolCallId, callFaceSeat(beltFace()));
        if (landings === "unjudged")
            return refuseCall(`The approved tool call "${pendingAction.toolName}" was not executed: no read station on this leg judged where it reads, so the approval cannot be checked against what it would read now. This approval is spent — the call has to be re-issued and approved again.`, { layer: "read_boundary" }, { details: unestablishedDetails() });
        const atExecution = judgeApprovalObject(pendingAction, { tool: mounted().entry, args: executedArgs, skills: prepared.skillSpecs, skillToolName: SKILL_TOOL_NAME, ...(humanRewrite !== undefined ? { decided: resolvedArgs } : {}), targetReading, reads, ...(landings !== undefined ? { landings } : {}) }, "execution");
        if (atExecution !== "match")
            return atExecution.disposition === "reopen" ? reopen(atExecution) : vetoApproval(atExecution);
        tool = mounted().tool;
        const waited = prepared.crossBoundary?.storeWaits() ?? 0;
        const crossBoundaryRefusal = await prepared.crossBoundary?.check?.exit({ toolName: pendingAction.toolName, args: executedArgs, toolCallId: pendingAction.toolCallId }, answered);
        if (crossBoundaryRefusal !== undefined)
            return refuseCall(crossBoundaryRefusal.message, { layer: "policy" });
        if ((prepared.crossBoundary?.storeWaits() ?? 0) === waited)
            break;
    }
    const args = structuredClone(executedArgs);
    screened?.admit();
    onExecuteStart?.(pendingAction.toolCallId);
    prepared.runLedgerBook?.callResumed(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 {
        const sandboxPlan = prepared.commandSandboxPlanOf({ toolName: tool.name, toolCallId: pendingAction.toolCallId, args: executedArgs, parkedClasses: pendingAction.classes ?? [] });
        res = await (prepared.toolCallStation ?? ((_c, run) => run()))({ toolCallId: pendingAction.toolCallId, toolName: tool.name, args }, () => runWithCommandSandboxPlan(sandboxPlan, () => tool.execute(pendingAction.toolCallId, args, prepared.abortController.signal)), 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 } : {}) });
        prepared.runLedgerBook?.callEnded(pendingAction.toolCallId, failed.result.details);
        const eid = await appendAdmittedRow(prepared.admitRows, prepared.session, 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);
    prepared.runLedgerBook?.callEnded(pendingAction.toolCallId, ran.result.details);
    onResolvedToolSuccess?.(pendingAction.toolName, ran.isError ? undefined : ran.result.details);
    const eid = await appendAdmittedRow(prepared.admitRows, prepared.session, {
        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);
}