UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

770 lines • 70.9 kB
import { resolve as resolveFsPath } from "node:path";
import { AgentHarness, DEFAULT_CLAMP_TOLERANCE, DEFAULT_COMPACTION_SETTINGS, summaryOutputBudgetTokens } from "../../internal/harness.js";
import { sanitizeCompactionSettings } from "../auto-compaction.js";
import { physicalPathOf } from "../physical-path.js";
import { projectStaleToolResults, resolveStaleToolResultOffload } from "./compaction-call-options.js";
import { uuidv7 } from "../../engine/session/uuid.js";
import { brainToRuntime } from "../runtime.js";
import { hasSessionFork } from "../session.js";
import { SEND_MESSAGE_TOOL_NAME } from "../../agents/send-message-tool.js";
import { callerToolMembership } from "../../agents/inherited-tool-pool.js";
import { toolPolicyPathDenyRules, toolPolicyWriteTargetGuard } from "../tool-policy.js";
import { loadAnnounceOnceLedger } from "./announce-once-ledger.js";
import { isValidReminderMark, mintReminderMark } from "../reminder-mint.js";
import { clampPermissionMode } from "../ask-origin.js";
import { modePolicyOf, modeRequestAfterResume, refusePermissionModeDoors } from "../mode-policy.js";
import { resolveOutputStyleFrame } from "../output-style.js";
import { recordedModeSeed } from "../checkpoint-store.js";
import { emitTrace } from "../trace.js";
import { persistedPathRowsOfTask, ruleStoreUnreadableNotice } from "./persisted-path-rows.js";
import { reservedCollisions, reservedFor } from "../../brain/request-params.js";
import { STALL_FIRST_BYTE_MS, STALL_FIRST_TOKEN_MS, STALL_IDLE_MS, withBrainCallGuardrail } from "../../brain/timeout.js";
import { OFFLOAD_TOOL_NAME } from "../tool-result-store.js";
import { OUTPUT_TOOL_NAME, SKILL_TOOL_NAME, createOutputTool } from "./synthetic-tools.js";
import { skillGateWiring } from "../skill-grant.js";
import { AllowEntryTable, screenAllowedToolsValue } from "../allow-entry.js";
import { compileOutputSchema } from "./strict-output-schema.js";
import { MEMORY_ENGINE_TOOL_NAMES } from "../memory-engine/tools.js";
import { foldAdmissionFreeze } from "../memory-admission.js";
import { prepareMemory } from "./prepare-memory.js";
import { prepareMemoryEngineSession } from "./prepare-memory-engine-session.js";
import { prepareDeferClassify } from "./prepare-defer-classify.js";
import { prepareListings } from "./prepare-listings.js";
import { preparePromptInputs } from "./prepare-prompt-inputs.js";
import { prepareProjectContext } from "./prepare-project-context.js";
import { preparePolicyChain } from "./prepare-policy-chain.js";
import { prepareContextLane } from "./prepare-context-lane.js";
import { prepareTurnWiring } from "./prepare-turn-wiring.js";
export { runGuardChain } from "./prepare-context-lane.js";
import { preparePromptAssembly } from "./prepare-prompt-assembly.js";
import { limitConfigError, prepareConfigDoors } from "./prepare-config-doors.js";
import { prepareSafetyScan } from "./prepare-safety-scan.js";
import { prepareAcquireReconcile } from "./prepare-acquire-reconcile.js";
import { settleBranchWriteBack } from "./branch-writeback.js";
import { prepareHandsMount, resolveHandsLessReadFace } from "./prepare-hands-readface.js";
import { prepareWorkspaceRestore } from "./prepare-workspace-restore.js";
import { parkContaminationMarker } from "./park-commit.js";
export { gatedCallIdOf, USAGE_WINDOW_REAP_MARGIN_MS } from "./park-commit.js";
import { prepareOffloadWrappers } from "./prepare-offload-wrappers.js";
import { prepareFileHistory } from "./prepare-file-history.js";
import { resolveFileHistoryRequest } from "./file-history-request.js";
import { prepareExecutionEnv } from "./prepare-execution-env.js";
import { prepareRunRefs } from "./prepare-run-refs.js";
import { prepareInheritedGate } from "./prepare-inherited-gate.js";
import { prepareCapsAndWorkflow } from "./prepare-caps-and-workflow.js";
import { prepareDelegationSurface } from "./prepare-delegation-surface.js";
import { prepareToolDisclosureMount } from "./prepare-tool-disclosure-mount.js";
import { prepareWiringManifest } from "./prepare-wiring-manifest.js";
import { prepareAskLane } from "./prepare-ask-lane.js";
import { prepareSuspendSaga } from "./prepare-suspend-saga.js";
import { prepareBoundaryParks } from "./prepare-boundary-parks.js";
import { prepareParkAsk } from "./prepare-park-ask.js";
import { prepareGateStations } from "./prepare-gate-stations.js";
export { batchContextAt } from "./prepare-park-ask.js";
export { compensateUnparkedPause } from "./prepare-suspend-saga.js";
import { placementValueOrAbsent } from "./checkpoint-scope.js";
export { DEFAULT_IRREVERSIBLE_SCOPE, checkpointScopeOf, placementValueOrAbsent } from "./checkpoint-scope.js";
export { mcpManifestEntries } from "./prepare-wiring-manifest.js";
import { derivedRouteFallsBack } from "./derived-route-fallback.js";
import { prepareProtocolTools } from "./prepare-protocol-tools.js";
import { prepareQuestionFace } from "./prepare-question-face.js";
import { prepareLsp } from "./prepare-lsp.js";
import { prepareArtifact } from "./prepare-artifact.js";
import { createRollbackStack } from "./rollback-stack.js";
export { __resetMaterializeEnvAnnouncements } from "./prepare-tool-disclosure-mount.js";
export { fileHistoryFilesystemIdentity, resolveFileHistoryScope } from "./prepare-file-history.js";
import { resolveTriggerWindow, } from "../context-edit.js";
import { isRemoteExecutionEnv } from "../remote-env.js";
import { settleTeardownLeg } from "./teardown-bounded.js";
import { defaultTaskRegistry } from "../task-registry.js";
import { announcePeerLaneMount, judgeSessionBoxDrain } from "../../agents/peer-session-drain.js";
import { createFrameSettlement } from "../frame-settlement.js";
import { createSchedulerTools } from "../../tools/scheduler-tools.js";
import { selfOrchestrationFailClosedReason } from "../../orchestration/workflow-script-runner.js";
import { remainingBudgetMicroUsd, resolveCheckpointStore } from "../checkpoint-store.js";
import { checkpointSeatOf } from "../checkpoint-seat.js";
import { handsWriteHalfMounts } from "../../tools/fs/index.js";
import { askSeatEffective } from "../wiring-manifest.js";
import { durableParkGapFor } from "../park-selfcheck.js";
import { deliverEngineNotice } from "../types.js";
import { ToolRosterDeltaSeat } from "../tool-roster.js";
import { faceOf } from "../tool-roster.js";
import { catalogEntriesNamed, pathTargetOf } from "../tool-registry.js";
import { AdvertisedWritableDirs } from "./advertised-writable-dirs.js";
import { resolveTaskRootCanonical } from "./task-root-canonical.js";
import { createStructuredProjector } from "./tool-output-projection.js";
import { asThrownError, thrownText } from "../thrown-value.js";
function warnCompactionWindowHazard(tracer, spec, model, compModel, hostTaskId, overlay) {
    if (compModel === undefined)
        return;
    const compWindow = compModel.contextTokens ?? compModel.contextWindow;
    const mainWindow = resolveTriggerWindow(model, overlay).window;
    if (compWindow > 0 && mainWindow > 0 && compWindow < mainWindow) {
        const merged = { ...DEFAULT_COMPACTION_SETTINGS, ...spec.compaction };
        const sanitized = sanitizeCompactionSettings(merged, mainWindow);
        const tolerance = sanitized.clampTolerance ?? DEFAULT_CLAMP_TOLERANCE;
        const headroom = Math.max(0, compWindow - Math.max(Math.floor(0.8 * summaryOutputBudgetTokens(compModel, sanitized)), 2048) - 512);
        emitTrace(tracer, () => ({
            kind: "compaction.window_config_warning",
            version: 1,
            taskId: hostTaskId,
            compactionModelWindow: compWindow,
            mainModelWindow: mainWindow,
            ...(tolerance < 1 ? { fallbackAt: Math.floor(headroom / (1 - tolerance)) } : {}),
            ts: Date.now(),
        }));
    }
}
let announcedToolModelGateBySink = new WeakMap();
const announcedToolModelGateConsole = new Set();
function toolModelGateLedger(onNotice) {
    if (typeof onNotice !== "function")
        return announcedToolModelGateConsole;
    let lines = announcedToolModelGateBySink.get(onNotice);
    if (lines === undefined) {
        lines = new Set();
        announcedToolModelGateBySink.set(onNotice, lines);
    }
    return lines;
}
export function __resetToolModelGateAnnouncements() {
    announcedToolModelGateBySink = new WeakMap();
    announcedToolModelGateConsole.clear();
}
function announceToolModelGate(onNotice, modelId, gate) {
    const ledger = toolModelGateLedger(onNotice);
    for (const [gateClass, removed] of gate.removedByClass) {
        const line = `Model gate: default-mounted tool(s) ${removed.map((n) => JSON.stringify(n)).join(", ")} (class ${JSON.stringify(gateClass)}) ` +
            `were not mounted for model ${JSON.stringify(modelId)} — the gate table marks this model as managing multi-step work without the scaffold. ` +
            `Explicitly composed tools are exempt; restore via TaskSpec.restoreGatedTools, SEMA_TOOL_MODEL_GATE=off, or RunnerDeps.toolModelGate: false.`;
        if (!ledger.has(line)) {
            ledger.add(line);
            deliverEngineNotice(onNotice, {
                code: "config.tool_model_gate_removed",
                message: line,
                detail: {
                    modelId,
                    gateClass,
                    removed: [...removed],
                    restore: { spec: "TaskSpec.restoreGatedTools", env: "SEMA_TOOL_MODEL_GATE=off", deps: "RunnerDeps.toolModelGate: false" },
                },
            });
        }
    }
    for (const gateClass of gate.unknownClasses) {
        const line = `ToolSpec.modelGate names gate class ${JSON.stringify(gateClass)}, which no row of the merged gate table defines — the tag is inert ` +
            `(fail-open: the tool stays mounted). Fix the tag, or define the class via RunnerDeps.toolModelGate.classes.`;
        if (!ledger.has(line)) {
            ledger.add(line);
            deliverEngineNotice(onNotice, { code: "config.tool_model_gate_unknown_class", message: line, detail: { gateClass } });
        }
    }
    if (gate.discardedEnvRaw !== undefined) {
        const line = `SEMA_TOOL_MODEL_GATE=${JSON.stringify(gate.discardedEnvRaw)} is not in the closed set (on|1|true|off|0|false, case-insensitive) — ` +
            `not in force on this task (nothing the model gate would remove), but a task where the gate WOULD trim a default-mounted tool ` +
            `will refuse to prepare under it (config.tool_model_gate_env_invalid). Fix or unset the flag.`;
        if (!ledger.has(line)) {
            ledger.add(line);
            deliverEngineNotice(onNotice, { code: "config.tool_model_gate_env_invalid", message: line, detail: { raw: gate.discardedEnvRaw } });
        }
    }
}
export const TOOL_MODEL_GATE_RESTORE_SENTENCE = "restore via TaskSpec.restoreGatedTools, SEMA_TOOL_MODEL_GATE=off, or RunnerDeps.toolModelGate: false";
function toolModelGateManifest(gate) {
    let firstClass;
    const removed = [];
    for (const [gateClass, names] of gate.removedByClass) {
        if (names.length === 0)
            continue;
        firstClass ??= gateClass;
        for (const n of names)
            if (!removed.includes(n))
                removed.push(n);
    }
    return firstClass === undefined ? undefined : { class: firstClass, removed, restore: TOOL_MODEL_GATE_RESTORE_SENTENCE };
}
export { __resetReadFaceClampAnnouncement } from "./prepare-hands-readface.js";
const DEFAULT_MAX_SUSPENDS = 5;
export const ENV_LIFETIME_SUSPEND_MARGIN_MS = 60_000;
export function resolveEnvLifetimeExpiry(env, observedAt) {
    const lifetimeMs = env.lifetimeMs;
    if (lifetimeMs === undefined)
        return undefined;
    if (typeof lifetimeMs !== "number" || !Number.isFinite(lifetimeMs) || lifetimeMs <= 0) {
        throw limitConfigError("config.env_lifetime_invalid", `ExecutionEnv.lifetimeMs must be a finite number of milliseconds > 0 (got ${String(lifetimeMs)}) — an unevaluable lifetime is not a lifetime, and treating it as absent would run the task with no protection against the platform reclaiming its environment.`);
    }
    const declaredStart = env.lifetimeStartedAt;
    if (declaredStart !== undefined && (typeof declaredStart !== "number" || !Number.isFinite(declaredStart))) {
        throw limitConfigError("config.env_lifetime_invalid", `ExecutionEnv.lifetimeStartedAt must be a finite epoch-ms timestamp (got ${String(declaredStart)}).`);
    }
    const anchor = declaredStart ?? observedAt;
    if (anchor === undefined)
        return { unanchored: true };
    return { expiresAt: anchor + lifetimeMs };
}
export { resolveCheckpointStore } from "../checkpoint-store.js";
export { isFableFamilyModelId, resolveAttachmentsConfig, resolveModelPromptTraits, resolveTaskLimits } from "./prepare-config-doors.js";
export { rebaseWorkspacePath, rebaseWorkspacePathAcross } from "./workspace-path.js";
export function effectiveDelegationFacts(internals, seedIsDelegatedChild) {
    const isDelegatedChild = internals?.isDelegatedChild !== undefined ? internals.isDelegatedChild === true : seedIsDelegatedChild === true;
    return { isDelegatedChild, isNonForkChild: isDelegatedChild && internals?.insideFork !== true };
}
async function forgetQuietly(sessions, sessionId) {
    try {
        if (sessions.forget)
            await sessions.forget(sessionId);
    }
    catch {
    }
}
async function adoptReminderMark(session, sessionId, seedMark, spawnMark, onError) {
    const sessionReminderMark = await (async () => {
        try {
            return await session.getReminderMark();
        }
        catch (err) {
            onError?.(asThrownError(err), { phase: "config", sessionId });
            return undefined;
        }
    })();
    const reminderMark = isValidReminderMark(seedMark)
        ? seedMark
        : isValidReminderMark(spawnMark)
            ? spawnMark
            : isValidReminderMark(sessionReminderMark)
                ? sessionReminderMark
                : mintReminderMark();
    if (reminderMark !== sessionReminderMark) {
        try {
            await session.appendReminderMark(reminderMark);
        }
        catch (err) {
            onError?.(asThrownError(err), { phase: "config", sessionId });
        }
    }
    return { reminderMark, reminderDisclosureCounts: {} };
}
function restorePlacementRoot(internals, seedPlacementRoot) {
    if (internals?.placementRoot !== undefined)
        return internals;
    const seed = placementValueOrAbsent(seedPlacementRoot);
    if (seed === undefined)
        return internals;
    return { ...(internals ?? {}), placementRoot: seed };
}
function refuseRequireExistingWithoutSession(spec) {
    if (spec.requireExistingSession && !spec.sessionId) {
        const e = new Error(`requireExistingSession requires a sessionId — cannot require an existing session without one (design/114 Phase3)`);
        e.code = "resume.session_not_found";
        throw e;
    }
}
function refuseRegistryScopeMismatch(spec, internals) {
    const registryScope = internals?.registryScope;
    if (registryScope === undefined || spec.principal === undefined || registryScope === spec.principal)
        return;
    const e = new Error(`registry scope mismatch: principal "${spec.principal}" vs RunInternals.registryScope "${registryScope}" — a delegated run's registry domain is its principal, so the two must be equal (or only one given)`);
    e.code = "config.registry_scope_mismatch";
    throw e;
}
function validateInputFaultNotice(onError, sessionId) {
    return ({ toolName, toolCallId, error }) => onError?.(new Error(`tool input pre-validation (validateInput) threw for ${toolName} (call ${toolCallId}) — read as no verdict; the call proceeded to the gate: ${thrownText(error)}`), { phase: "hook", sessionId });
}
export async function prepareTask(spec, deps, sessions, resume, internals, runnerSelf, runIdSink, holdSessionLock) {
    const runId = uuidv7();
    if (runIdSink !== undefined)
        runIdSink.runId = runId;
    const mountsCallerTool = callerToolMembership(spec.tools);
    const doors = prepareConfigDoors({ spec, deps, sessions, resume, internals });
    spec = doors.spec;
    const checkpointStore = resolveCheckpointStore(spec, deps), checkpointSeat = checkpointSeatOf(spec, checkpointStore);
    const permissionModeSeat = refusePermissionModeDoors(spec);
    const outputStyleFrame = resolveOutputStyleFrame(spec.outputStyle);
    const allowedTools = screenAllowedToolsValue(spec.allowedTools, "TaskSpec.allowedTools");
    const declaredModeAtDoor = (() => {
        const requested = modeRequestAfterResume(permissionModeSeat, recordedModeSeed(resume?.seed.inheritedGate), resume?.outcome);
        const ceiling = internals?.inheritedGate?.permissionModeCeiling?.current ?? internals?.inheritedGate?.permissionMode;
        return ceiling === undefined ? (requested ?? "default") : clampPermissionMode(requested, ceiling).effective;
    })();
    if (modePolicyOf(declaredModeAtDoor).enablePlanMode)
        spec = { ...spec, enablePlanMode: true };
    const { toolFaceSnapshot, promptProfile, lockedPreflight, resolvedInteractionPosture, microCompactKnob, resolvedRole, model, thinking, compModel, fableMitigations, memoryDelegationEvidence, memoryProvenance, memoryCapturePolicy, usageWindows, brainCallGuardrailRef, brainCallGuardrailMs } = doors;
    announceToolModelGate(deps.onNotice, model.id, doors.modelGate);
    const modelGateManifest = toolModelGateManifest(doors.modelGate);
    const { toolEffects, egressTools, irreversibleTools, irreversibilityTier, axisExplicitNegatives, reversibilityProbes, toolMarkSources } = prepareSafetyScan({ spec, deps });
    let shellGatedTools = new Set();
    refuseRequireExistingWithoutSession(spec);
    refuseRegistryScopeMismatch(spec, internals);
    if (model.extraBody !== undefined && Object.prototype.hasOwnProperty.call(model.extraBody, "max_completion_tokens")) {
        const e = new Error(`model.extraBody supplies "max_completion_tokens" — this spelling is engine-owned (the overflow retry ` +
            `adjusts the per-request output cap, and a constant extraBody value would override that adjustment on ` +
            `every retry). Set the cap via limits.maxOutputTokens (per request) or model.maxTokens instead.`);
        e.code = "config.extra_body_output_cap";
        throw e;
    }
    const fileHistoryRequest = resolveFileHistoryRequest(spec, deps);
    const { acquired, session, conflictRef, wakeRecovered, branch } = await prepareAcquireReconcile({ sessions, spec, resume, toolEffects, report: (e, id) => deps.onError?.(e, { phase: "config", sessionId: id }), ...(internals?.sessionPlacement !== undefined ? { placement: internals.sessionPlacement } : {}), ...(() => { const g = durableParkGapFor(deps, spec); return g !== undefined ? { durableParkGap: g } : {}; })() });
    const sessionId = acquired.sessionId;
    await holdSessionLock?.(sessionId);
    const onceLedger = await loadAnnounceOnceLedger(session, resume?.seed.announcedListings, deps.onError);
    const hostTaskId = spec.taskId ?? sessionId;
    const delegation = effectiveDelegationFacts(internals, resume?.seed.isDelegatedChild);
    const placementRootResolved = (internals = restorePlacementRoot(internals, resume?.seed.placementRootSessionId))?.placementRoot ?? internals?.rootSessionId ?? sessionId;
    let effectiveCompModel = compModel;
    if (spec.compactionModel === undefined &&
        compModel !== undefined &&
        (await derivedRouteFallsBack({ seat: "compaction-summary", derived: compModel, primary: model, brain: deps.brain, getApiKeyAndHeaders: spec.getApiKeyAndHeaders, onNotice: deps.onNotice, sessionId, runId }))) {
        effectiveCompModel = undefined;
    }
    warnCompactionWindowHazard(deps.tracer, spec, model, effectiveCompModel, hostTaskId, runnerSelf?.contextOverlayOf?.(resolvedRole.modelRef));
    const taskScope = internals?.registryScope ?? spec.principal ?? "default";
    internals?.peerSelfRef?.addAxis("s", sessionId);
    internals?.peerSelfRef?.addAxis("t", hostTaskId);
    const peerLaneActive = announcePeerLaneMount(deps, { sessionId, runId });
    const sessionBox = judgeSessionBoxDrain(deps, { sessionId, scope: taskScope, isDelegatedChild: delegation.isDelegatedChild });
    const peerLaneRefs = {};
    const frameSettlement = createFrameSettlement();
    const peerSendMessageBuiltIn = runnerSelf !== undefined && !(toolFaceSnapshot.exclude ?? []).includes(SEND_MESSAGE_TOOL_NAME) && !(spec.tools ?? []).some((t) => t.name === SEND_MESSAGE_TOOL_NAME);
    const { reminderMark, reminderDisclosureCounts } = await adoptReminderMark(session, sessionId, resume?.seed.reminderMark, internals?.reminderMark, deps.onError);
    const offloadScope = spec.principal ?? "default";
    if (internals?.registryScope !== undefined && internals.registryScope !== offloadScope) {
        deps.onError?.(new Error(`offload/tool-result namespace note: this run mounts in registry domain "${internals.registryScope}" but its offloaded tool results live under the TRUST identity "${offloadScope}" (principal${spec.principal === undefined ? " absent → default" : ""}). Before 2.13.0 the registry domain named this namespace too; if a deployment used registryScope as its ref-tenancy boundary, that boundary is now the principal — pass one, or read refs under "${offloadScope}".`), { phase: "config", sessionId });
    }
    defaultTaskRegistry.maybeGc();
    const forgetOnThrow = () => branch === undefined
        ? forgetQuietly(sessions, sessionId)
        : settleBranchWriteBack(branch, sessionId, "resumeAt branch write-back (prepare refusal)", (e) => deps.onError?.(e, { phase: "config", sessionId })).then(() => forgetQuietly(sessions, sessionId));
    const extraBodyCollisions = reservedCollisions(model.extraBody, reservedFor(model.api));
    if (extraBodyCollisions.length > 0) {
        deps.onError?.(new Error(`model.extraBody contains reserved key(s) [${extraBodyCollisions.join(", ")}] that core owns and sets itself — they are ignored. Remove them from extraBody.`), { phase: "config", sessionId });
    }
    const { nestedStats, reportUsage, offloadStore, offloadReachableToolsRef, maybeOffload, firstPartyOffload, remoteToolOffload } = prepareOffloadWrappers({ spec, deps, resume, offloadScope, sessionId });
    if (offloadStore && (spec.tools ?? []).some((t) => t.name === OFFLOAD_TOOL_NAME)) {
        const e = new Error(`Tool name "${OFFLOAD_TOOL_NAME}" is reserved when large-result offload is enabled.`);
        e.code = "config.reserved_tool_name";
        await settleTeardownLeg(() => forgetOnThrow(), "forgetOnThrow (reserved-name leg)", (err) => deps.onError?.(err, { phase: "config", sessionId }));
        throw e;
    }
    const rollback = createRollbackStack((e) => deps.onError?.(e, { phase: "config", sessionId }));
    const { executionEnv, ownedEnvSeat, ownedEnvObservedAt, handsEnabled, taskRootInitial } = await prepareExecutionEnv({ deps, spec, internals, resume, placementRootResolved, sessionId, forgetOnThrow, rollback });
    const externalContentTargetActive = executionEnv.externalContentTarget === true || resume?.seed.externalContentTarget === true;
    const abortController = new AbortController();
    if (spec.signal?.aborted)
        abortController.abort();
    try {
        const envLifetime = resolveEnvLifetimeExpiry(executionEnv, ownedEnvObservedAt);
        if (envLifetime !== undefined && "unanchored" in envLifetime) {
            deps.onError?.(new Error("ExecutionEnv.lifetimeMs is declared but NOT enforceable: this env was not minted by the run's executionEnvFactory and reports no `lifetimeStartedAt`, so the engine cannot tell how old it is. The run will NOT suspend before the platform reclaims the environment — have the adapter report `lifetimeStartedAt`."), { phase: "config", sessionId });
        }
        const envLifetimeSuspendAt = envLifetime !== undefined && "expiresAt" in envLifetime ? envLifetime.expiresAt - ENV_LIFETIME_SUSPEND_MARGIN_MS : undefined;
        if (internals?.isolation === "worktree") {
            const failIsolation = (reason) => {
                const e = new Error(`isolation "worktree" was requested but cannot be honored: ${reason}. The sub-agent was not started (fail-closed — no silent fallback to the shared working tree).`);
                e.code = "isolation.unavailable";
                throw e;
            };
            if (ownedEnvSeat.current === undefined) {
                failIsolation("no executionEnvFactory is configured (a static/shared execution env cannot mint a per-agent worktree)");
            }
            else if (ownedEnvSeat.current === deps.executionEnv) {
                ownedEnvSeat.current = undefined;
                failIsolation("the executionEnvFactory returned the shared static env instead of a worktree-rooted env");
            }
            else if (isRemoteExecutionEnv(ownedEnvSeat.current)) {
                if (ownedEnvSeat.current.capabilities.isolation !== true) {
                    failIsolation("the executionEnvFactory returned a remote env without capabilities.isolation — a non-isolated remote target is a shared remote checkout, not a per-agent worktree");
                }
            }
            else {
                const canonical = (p, what) => {
                    try {
                        return physicalPathOf(resolveFsPath(p));
                    }
                    catch (err) {
                        return failIsolation(`cannot canonicalize ${what} (${thrownText(err)}) — an unverifiable path is treated as not isolated`);
                    }
                };
                if (deps.rootPath !== undefined || internals.parentCwd !== undefined) {
                    const envCwd = canonical(ownedEnvSeat.current.cwd, "the factory env's cwd");
                    if (deps.rootPath !== undefined && envCwd === canonical(deps.rootPath, "the shared base root")) {
                        failIsolation("the executionEnvFactory rooted the env at the shared base root instead of a worktree");
                    }
                    if (internals.parentCwd !== undefined && envCwd === canonical(internals.parentCwd, "the parent's cwd")) {
                        failIsolation("the executionEnvFactory rooted the env at the parent's cwd instead of a worktree");
                    }
                }
            }
        }
        const ownedEnv = ownedEnvSeat.current;
        const { taskRootFinal, rebaseRestoredPath } = await prepareWorkspaceRestore({ ownedEnv, deps, spec, internals, resume, taskRootInitial, abortController, sessionId });
        const { canonical: taskRootCanonical } = await resolveTaskRootCanonical({ env: executionEnv, given: taskRootFinal, onNotice: deps.onNotice, sessionId, runId });
        const { trackFileEdit, fileHistoryBoundary, restoredFilePaths, rewindNotes, fileHistoryEnabled, fileHistoryFact, historyScope, historyRoot, historyFs } = await prepareFileHistory({ deps, spec, request: fileHistoryRequest, internals, executionEnv, taskRootFinal, handsEnabled, sessionId, session, abortController });
        const { noteFileEdited, editedFilesSnapshot, harnessRef, toolProgressRef, skillGrants, forwardEvent, reviewRequestRef, requestReview, stopRequestedRef, requestStopAfterTurn, bindPermissionModeSeat, enterPlanMode, subagentRetain, worktreeIsolation } = prepareRunRefs({ spec, internals, executionEnv, taskRootFinal });
        const allowedToolTables = { request: new AllowEntryTable(), deployment: new AllowEntryTable() };
        const legContextOverlay = () => runnerSelf?.contextOverlayOf?.(harnessRef.current?.getModelRef() ?? resolvedRole.modelRef);
        let resolvedReadFace;
        let resolvedWriteFace;
        let readDenyAdditionsNormalized = [];
        let handsLessResolvedFace;
        let handsLessResolvedWriteFace;
        const { liveInheritedGate, seedInheritedGate, inheritedAncestorRules, inheritedShellGate, inheritedParentConstraints, permissionMode, commitModeSeats, endModeCeiling, inheritedAdmittedOrgScopes, priorOwnOrgVerdict, orgGovernedProvenance, effectiveShellGate, ownSessionRulesRef, ancestorSessionRulesRef, ancestorRulesNow, memoryAdmittedOrgScopesRef, ownOrgVerdictRef, orgAdmissionCheckpointState, faceCheckpointSection, faceCheckpointState, writeFaceCheckpointSection, skillGrantCheckpointSection, f012CheckpointState, frozenOnAsk, hookEnvSource, notifyOwnHookCrash, frozenOnQuestion, parentSpecSeat, provenanceForChildrenRef, delegationSettlementRef, inheritedGateForChildren, carrierReadFace, carrierWriteFace, fullShellReachable, gateStopRef, stopForDenialLimit, enrichSpecToolCtx } = prepareInheritedGate({ spec, deps, internals, resume, sessions, sessionId, runId, hostTaskId, taskRootFinal, executionEnv, ownedEnv, lockedPreflight, checkpointSeat, toolFaceSnapshot, mountsCallerTool, promptProfile, resolvedInteractionPosture, permissionModeSeat, handsEnabled, reportUsage, harnessRef, skillGrants, requestAllowedTools: allowedToolTables.request, forwardEvent, subagentRetain, worktreeIsolation, requestReview, requestStopAfterTurn, enterPlanMode, reminderMark, reminderDisclosureCounts, fileHistoryEnabled, historyScope, historyRoot, historyFs, abortRun: () => { abortController.abort(); void harness.abort(); }, runtimeCaps: () => runtimeCaps, hooks: () => hooks, preToolUseObservational: () => preToolUseObservational, hookTimeoutMs: () => hookTimeoutMs, hookEnvFace: () => hookEnvFace, autoModeDecider: () => autoModeDeciderRef.current, autoModeDenialTracking: () => autoModeDenialTrackingRef.current, autoModeArming: () => autoModeArmingRef.current, agentForkDenial: () => agentForkDenial, observersActive: () => observersActive, resolvedReadFace: () => resolvedReadFace, resolvedWriteFace: () => resolvedWriteFace, readDenyAdditionsNormalized: () => readDenyAdditionsNormalized, handsLessResolvedFace: () => handsLessResolvedFace, handsLessResolvedWriteFace: () => handsLessResolvedWriteFace, centerAdoption: () => centerAdoptionRef.current, memoryEngineSession: () => memoryEngineSession });
        bindPermissionModeSeat(permissionMode);
        const announceRuleStoreSkipped = ruleStoreUnreadableNotice(deps.onNotice, { sessionId, runId });
        const persistedPathRowsRead = persistedPathRowsOfTask({ deps, principal: spec.principal, sessionId, root: taskRootFinal, home: executionEnv.homeDir, taskId: hostTaskId, handsEnabled, signals: [abortController.signal, ...(spec.signal !== undefined ? [spec.signal] : [])], onUnread: announceRuleStoreSkipped });
        const persistedPathRows = persistedPathRowsRead === undefined ? { readDirectories: [], denyRows: [] } : await persistedPathRowsRead;
        const effectivePathDenyRules = [...toolPolicyPathDenyRules([lockedPreflight.toolPolicy, ...(inheritedParentConstraints ?? []).map((c) => c.policy)]), ...persistedPathRows.denyRows];
        const writeProtectionJudgeRef = {};
        const writeGuards = { protection: () => writeProtectionJudgeRef.current, target: toolPolicyWriteTargetGuard([lockedPreflight.toolPolicy, ...(inheritedParentConstraints ?? []).map((c) => c.policy)]) };
        const { roster, blockedRef, runtimeCaps, runtimeCapsFaulted, complianceDenies, complianceDegraded, agentForkDenial, observersActive, autoModeArmReason, autoModeDeciderRef, autoModeDenialTrackingRef, autoModeArmingRef, armAutoMode, selfOrchestrationActive, workflowToolsActive, workflowSizeGuideline } = await prepareCapsAndWorkflow({ spec, deps, internals, session, sessionId, runId, hostTaskId, taskScope, taskRootFinal, model, thinking, lockedPreflight, checkpointSeat, toolEffects, toolFaceSnapshot, promptProfile, resolvedInteractionPosture, harnessRef, frozenOnAsk, parentSpecSeat, carrierReadFace, carrierWriteFace, forwardEvent, inheritedGateForChildren, enrichSpecToolCtx, maybeOffload, requestReview, enterPlanMode, permissionMode, readDenyEntries: () => ({ entries: readDenyMatcher?.entries ?? [], ruleRows: effectivePathDenyRules }), peerLaneActive, peerSendMessageBuiltIn, runnerSelf, memoryEngineSession: () => memoryEngineSession, centerAdoption: () => centerAdoptionRef.current, readDenyAdditionsNormalized: () => readDenyAdditionsNormalized });
        const tools = roster.tools;
        const pausedRef = {};
        const undeliveredContinuationRef = { current: { parkedSteers: [], orphanTasks: [] } };
        const remoteEnvFailures = [];
        const suspendLoopRef = { hit: false };
        const compactionReuseRef = { consecutive: 0 };
        const trimPressureRef = { droppedMessages: false };
        const liveSpendRef = {};
        const now = deps.now ?? Date.now;
        const humanReviewRef = {
            count: resume?.priorHumanReview?.count ?? 0,
            totalWaitMs: resume?.priorHumanReview?.totalWaitMs ?? 0,
            gates: resume?.priorHumanReview?.gates ? [...resume.priorHumanReview.gates] : [],
        };
        const priorSuspendCount = resume?.priorSuspendCount ?? 0;
        const suspendProgressRef = { executedApproved: false };
        const suspendChainBase = () => (suspendProgressRef.executedApproved ? 0 : priorSuspendCount);
        const maxSuspends = spec.maxSuspends ?? deps.maxSuspends ?? DEFAULT_MAX_SUSPENDS;
        const maxSlices = spec.resourceSuspend?.maxSlices;
        const priorLedger = resume?.priorLedger;
        const resourceTotal = spec.resourceSuspend
            ? {
                totalBudgetMicroUsd: spec.resourceSuspend.totalBudgetUsd !== undefined ? Math.round(spec.resourceSuspend.totalBudgetUsd * 1e6) : undefined,
                totalTokens: spec.resourceSuspend.totalTokens,
            }
            : undefined;
        const budgetSnapshot = {
            resourceRemainingMicroUsd: priorLedger
                ? remainingBudgetMicroUsd(priorLedger)
                : resourceTotal?.totalBudgetMicroUsd,
            resourceSpentMicroUsd: priorLedger?.spentMicroUsd ?? 0,
            suspendCount: priorSuspendCount,
        };
        const outputRef = {};
        if (resume?.seed.outputRef) {
            outputRef.value = resume.seed.outputRef.value;
            outputRef.set = resume.seed.outputRef.set;
        }
        if (spec.outputSchema) {
            if ((spec.tools ?? []).some((t) => t.name === OUTPUT_TOOL_NAME)) {
                const e = new Error(`Tool name "${OUTPUT_TOOL_NAME}" is reserved when TaskSpec.outputSchema is set.`);
                e.code = "config.reserved_tool_name";
                throw e;
            }
            const compiled = compileOutputSchema(spec.outputSchema);
            if ("error" in compiled) {
                const e = new Error(`TaskSpec.outputSchema is not a valid JSON Schema: ${compiled.error}`);
                e.code = "config.invalid_output_schema";
                throw e;
            }
            if (!compiled.strict) {
                try {
                    onceLedger.onError(new Error(`structured-output: strict schema derivation fell back to non-strict (${compiled.fallbackReason}) — the schema is served to the model as-is`), { phase: "config", sessionId });
                }
                catch {
                }
            }
            roster.mount(createOutputTool(outputRef, spec.outputSchema, compiled.strict ? compiled.modelSchema : undefined), { source: "synthetic", mountedBy: "optional" });
        }
        const rosterSeat = new ToolRosterDeltaSeat();
        const { mcp, a2a, rebuildHarnessToolsRef, contentOriginWrapRef, toolCallGateArmedRef, mcpRedial } = await prepareProtocolTools({ lockedPreflight, spec, deps, reminderMark, reminderDisclosureCounts, runId, sessionId, onceLedger, roster, rosterSeat, remoteToolOffload, toolFaceSnapshot, toolEffects, axisExplicitNegatives, irreversibilityTier, irreversibleTools, egressTools, toolMarkSources, abortController, rollback });
        const callIssuedAtRef = {};
        const workCutRef = { continuation: false, abortedBeforeTurnEnd: false };
        const advertisedWritableDirs = handsEnabled
            ? new AdvertisedWritableDirs(executionEnv, (dir, reason) => deps.onError?.(new Error(`${dir.advertiser} advertised writable directory skipped: ${dir.path} — ${reason}`), { phase: "config", sessionId }), taskRootCanonical, [...(spec.additionalDirectories ?? []), ...(spec.additionalReadDirectories ?? [])])
            : undefined;
        const handsWriteHalfPlanned = handsEnabled && handsWriteHalfMounts({ readOnly: spec.handsReadOnly === true });
        const memoryPairNameDomain = new Set();
        for (const t of tools) {
            memoryPairNameDomain.add(t.name);
            for (const alias of t.aliases ?? [])
                memoryPairNameDomain.add(alias);
        }
        const memoryPairExcludedName = MEMORY_ENGINE_TOOL_NAMES.find((n) => (toolFaceSnapshot.exclude ?? []).includes(n));
        const memoryPairOccupiedName = MEMORY_ENGINE_TOOL_NAMES.find((n) => memoryPairNameDomain.has(n));
        const memorySearchToolsPlanned = memoryPairExcludedName === undefined && memoryPairOccupiedName === undefined;
        const captureLineage = await (async () => {
            try {
                const ff = (await session.getMetadata()).forkedFrom;
                return { ...(ff !== undefined && ff !== sessionId ? { origin: ff } : {}), fault: false };
            }
            catch {
                return { fault: true };
            }
        })();
        const { memoryEngineSession, memoryTools, memoryWriteGate, composeInjection: composeMemoryInjection, admittedOrgScopes: memoryAdmittedOrgScopes, ownOrgVerdict: memoryOwnOrgVerdict, effectiveMemoryScopes: memoryEffectiveScopes, } = await prepareMemory({
            spec,
            deps,
            sessionId,
            taskRootPath: taskRootFinal,
            reminderMark,
            writeToolsMounted: (handsWriteHalfPlanned || tools.some((t) => t.name === "Write")) &&
                !(toolFaceSnapshot.exclude?.includes("Write") ?? false) &&
                !(handsEnabled && isRemoteExecutionEnv(executionEnv) && spec.memoryPersistenceCapable !== true),
            memoryProvenance,
            memoryCapturePolicy,
            memoryCapturePolicyDeclared: deps.memoryCapturePolicy !== undefined,
            captureEntitlement: {
                value: typeof runtimeCaps?.allowMemoryOptOut === "boolean" ? runtimeCaps.allowMemoryOptOut : undefined,
                faulted: runtimeCapsFaulted || (runtimeCaps?.allowMemoryOptOut !== undefined && typeof runtimeCaps.allowMemoryOptOut !== "boolean"),
            },
            captureCarrierUnsupported: isRemoteExecutionEnv(executionEnv) && deps.memoryCaptureRecordStore === undefined,
            ...(internals?.parentSessionId !== undefined ? { parentSessionId: internals.parentSessionId } : {}),
            captureFloor: internals?.memoryCaptureFloor === true,
            ...(internals?.memoryCaptureFloorIndeterminate === true ? { captureFloorIndeterminate: true } : {}),
            ...(captureLineage.origin !== undefined ? { captureForkOrigin: captureLineage.origin } : {}),
            ...(captureLineage.fault ? { captureLineageFault: true } : {}),
            ...(internals?.memoryCaptureQueryDir !== undefined ? { parentCaptureQueryDir: internals.memoryCaptureQueryDir } : {}),
            ...(internals?.memoryCaptureAncestors !== undefined ? { captureAncestors: internals.memoryCaptureAncestors } : {}),
            memoryPersistenceDeclared: spec.memoryPersistenceCapable,
            ...(advertisedWritableDirs !== undefined ? { advertisedWritableDirs } : {}),
            memorySearchToolsPlanned,
            admissionCtx: {
                orgMemoryDenied: complianceDenies.has("org_memory_mount"),
                complianceDegraded,
                parentAdmittedOrgScopes: foldAdmissionFreeze({
                    delegated: delegation.isDelegatedChild ||
                        internals?.inheritedGate !== undefined ||
                        (resume?.seed.inheritedGate !== undefined &&
                            (resume.seed.inheritedGate.ancestorRules !== undefined ||
                                resume.seed.inheritedGate.shellGate !== undefined ||
                                resume.seed.inheritedGate.admittedOrgScopes !== undefined ||
                                resume.seed.inheritedGate.requiresParentConstraint)),
                    inherited: inheritedAdmittedOrgScopes,
                }),
                priorOwnVerdict: priorOwnOrgVerdict,
                governedProvenance: orgGovernedProvenance,
            },
        });
        if (memoryEngineSession !== undefined)
            rollback.push(() => memoryEngineSession.release());
        memoryAdmittedOrgScopesRef.current = memoryAdmittedOrgScopes;
        ownOrgVerdictRef.current = memoryOwnOrgVerdict ?? priorOwnOrgVerdict;
        if (internals?.ownOrgAdmissionRef !== undefined && ownOrgVerdictRef.current !== undefined) {
            internals.ownOrgAdmissionRef.current = ownOrgVerdictRef.current;
        }
        const handsReadFaceInput = { permissionMode, pathDenyRules: effectivePathDenyRules, writeGuards, persistedReadDirectories: persistedPathRows.readDirectories, handsEnabled, executionEnv, taskRootFinal, taskRootCanonical, rebaseRestoredPath, resume, session, sessionId, hostTaskId, taskScope, fullShellReachable, effectiveShellGate, toolFaceSnapshot, model, spec, deps, internals, memoryWriteGate, ...(advertisedWritableDirs !== undefined ? { advertisedWritableDirs } : {}), firstPartyOffload, roster, egressTools, irreversibilityTier, irreversibleTools, reversibilityProbes, reminderMark, reminderDisclosureCounts, ...(trackFileEdit !== undefined ? { trackFileEdit } : {}), onFileEdited: noteFileEdited, harnessRef, toolProgressRef, ...(restoredFilePaths.length > 0 ? { restoredFilePaths } : {}) };
        const handsReadFace = handsEnabled ? await prepareHandsMount(handsReadFaceInput) : resolveHandsLessReadFace(handsReadFaceInput);
        const { readFileStateForCheckpoint, seedContextFiles, handsCwdRef, workspaceStateSettle, wsSnapshot, rebaseWsPath, backgroundTaskToolsActive, shellReadCheck, shellReadAdmission, additionalRootsCanonical, additionalReadRootsCanonical, attachmentRootCanonical, readDenyMatcher, envHandToolNames, sealReadStateSeat } = handsReadFace;
        resolvedReadFace = handsReadFace.resolvedReadFace;
        resolvedWriteFace = handsReadFace.resolvedWriteFace;
        readDenyAdditionsNormalized = handsReadFace.readDenyAdditionsNormalized;
        handsLessResolvedFace = handsReadFace.handsLessResolvedFace;
        handsLessResolvedWriteFace = handsReadFace.handsLessResolvedWriteFace;
        shellGatedTools = handsReadFace.shellGatedTools;
        await armAutoMode();
        const { worktreeSessionRef } = prepareDelegationSurface({ spec, deps, internals, resume, sessionId, hostTaskId, taskScope, taskRootFinal, taskRootCanonical, executionEnv, runnerSelf, backgroundTaskToolsActive, shellReadAdmission, workflowToolsActive, peerLaneActive, peerSendMessageBuiltIn, peerLaneRefs, sessionBox, roster, toolEffects, axisExplicitNegatives, envHandToolNames, toolFaceSnapshot, firstPartyOffload, offloadStore, subagentRetain, enrichSpecToolCtx, checkpointSeat, handsCwdRef, wsSnapshot, rebaseWsPath, rebaseRestoredPath, workspaceStateSettle });
        const { liveQuestionFace, contentAskBindings, contentAskRoutable, lateStrandedAnswers, discloseStrandedAnswers, settleContentAskBindings, durableQuestionFace, questionToolMounted, mountedQuestionTool } = prepareQuestionFace({ frozenOnQuestion, spec, deps, checkpointStore, runtimeCaps, resolvedInteractionPosture, resume, sessionId, roster, inheritedUnavailableAsks: () => inheritedUnavailableAsks });
        if (spec.handsReadOnly !== true) {
            const sessionScope = sessionId ?? spec.principal ?? spec.taskId ?? "default";
            roster.mountAll(createSchedulerTools(executionEnv, {
                scope: sessionScope,
                ...(spec.principal !== undefined ? { principal: spec.principal } : {}),
                ...(sessionId !== undefined ? { sessionId } : {}),
                requestStopAfterTurn,
            }).map((t) => (envHandToolNames.add(t.name), t)), { source: "builtin", mountedBy: "scheduler" });
        }
        if (internals?.insideFork !== true &&
            runnerSelf &&
            sessionId !== undefined &&
            hasSessionFork(runnerSelf.sessions) &&
            agentForkDenial === "principal") {
            deps.onError?.(new Error(`Fork DENIED for principal "${spec.principal ?? ""}" by runtimeCaps.allowFork=false ` +
                `(per-principal entitlement governance, not a misconfiguration — Agent(subagent_type:"fork") will refuse honestly)`), { phase: "config", sessionId });
        }
        const { lspDiagnostics, nudgeLspOnEdit, lspRunIdent, managerWired: lspManagerWired } = prepareLsp({ spec, deps, executionEnv, taskRootFinal, handsEnabled, sessionId, handsCwdRef, roster, envHandToolNames });
        prepareArtifact({ deps, runId, taskId: hostTaskId, sessionId, agentName: internals?.explicitAgentName, onAsk: frozenOnAsk, permissionMode, executionEnv, rootCanonical: attachmentRootCanonical, additionalRootsCanonical: () => [...additionalRootsCanonical, ...additionalReadRootsCanonical], readDenyMatcher, resolvedReadFace, handsCwdRef, roster, firstPartyOffload, envHandToolNames, ...(handsReadFace.artifactStoreRef !== undefined ? { artifactStoreRef: handsReadFace.artifactStoreRef } : {}) });
        if (internals?.delegationProvenance !== undefined && resume !== undefined) {
            const live = internals.delegationProvenance.ref.current;
            const seed = resume.seed.delegationProvenance;
            if (seed === undefined || seed.version !== 1 || seed.coverageStartTurn !== 0) {
                live.incomplete = true;
            }
            else {
                if (seed.sawExternal)
                    live.sawExternal = true;
                if (seed.incomplete)
                    live.incomplete = true;
            }
        }
        const rosterCanPersist = spec.memoryPersistenceCapable ??
            tools.some((t) => {
                if (toolFaceSnapshot.exclude?.includes(t.name) ?? false)
                    return false;
                const effect = (t.effect ?? toolEffects.get(t.name) ?? "write");
                if (effect === "read")
                    return false;
                const face = faceOf(t);
                const pt = face.pathTarget ?? pathTargetOf(t.name);
                const family = face.family ?? catalogEntriesNamed(t.name)[0]?.face.family;
                if (!((pt !== undefined && pt.access !== "read") || family === "shell"))
                    return false;
                return !(handsEnabled && isRemoteExecutionEnv(executionEnv));
            });
        const { memoryBlock: memoryBlockFromEngine, recallDisciplineSegment: memoryRecallSegment, seedFiles: memorySeedFiles } = composeMemoryInjection({ rosterCanPersist });
        if (memorySeedFiles?.length && seedContextFiles) {
            try {
                await seedContextFiles(memorySeedFiles);
            }
            catch (err) {
                deps.onError?.(asThrownError(err), { phase: "config", sessionId });
            }
        }
        const projectContext = await prepareProjectContext({ deps, spec, internals, session, sessionId, hostTaskId, taskRootFinal, handsEnabled, delegation, seedContextFiles, memoryBlockFromEngine, skillGrants, allowedTools, allowedToolTables, roster, toolFaceSnapshot, onceLedger, memoryTools, memoryEngineSession, memorySearchToolsPlanned, memoryPairExcludedName, memoryPairOccupiedName, resume, skillListingBudget: doors.skillListingBudget });
        const { memoryBlock: memoryBlockWithProject, instructionSources, projectInstructionContent, skillSpecs, skillSeatOf, skillsListing, sharedMemoryPairMounted, memoryEnginePairMounted } = projectContext;
        const { provider, featureFlags, userSystemPrompt, userAppendSystemPrompt, mcpInstructionsBlock, envFacts, tzValid, userTz, dateAnchor, gitStatusRef } = await preparePromptInputs({ spec, deps, contextOverlay: legContextOverlay(), failClosedReason: selfOrchestrationFailClosedReason(spec, deps), lockedPreflight, selfOrchestrationActive, executionEnv, reminderMark, resolvedReadFace, resolvedWriteFace: resolvedWriteFace?.inForce(), toolFaceSnapshot, promptProfile, fableMitigations, internals, thinking, ownedEnv, delegation, resolvedRole, mcp, model, externalContentTargetActive, resume, handsEnabled, taskRootFinal, additionalRootsCanonical, additionalReadRootsCanonical, sessionId, session, ...(advertisedWritableDirs !== undefined ? { advertisedWritableDirs } : {}) });
        const { deferred, memoryBlock, toolSearch: toolSearchPolicy } = prepareDeferClassify({ spec, deps, roster, toolFaceSnapshot, handsEnabled, fullShellReachable, promptProfile, model, mcp, a2a, sharedMemoryPairMounted, memoryEnginePairMounted, memoryBlock: memoryBlockWithProject, memoryRecallSegment, onceLedger, sessionId });
        prepareMemoryEngineSession({ memoryEngineSession, internals, memoryDelegationEvidence, externalContentTargetActive, lockedPreflight, mcp, sessionId, runId, deps, provenanceForChildrenRef, delegationSettlementRef, spec, envHandToolNames, roster, contentOriginWrapRef });
        const { systemPromptSeat, renderWithDate, systemBlocks, promptManifest, epochDeclaredSections, epochArtifactDigestForSnapshot, buildAssembleInputs, centerAdoptionRef } = await preparePromptAssembly({ session, deps, internals, resume, provider, userSystemPrompt, userAppendSystemPrompt, featureFlags, mcpInstructionsBlock, memoryBlock, envFacts, promptProfile, fableMitigations, tools, model, sessionId, reminderMark, onceLedger });
        const { activeTools, fpRef, turnSnapshotRef, harnessTools, toolsDeltaRef, toolMaterializeStatic, deferDirectCall, staticFaceForRef, listingRideRef, toolSearch, toolDisclosureSeat } = await prepareToolDisclosureMount({ spec, deps, session, resume, deferred, tools, onceLedger, mcp, promptManifest, toolSearchPolicy, offloadReachableToolsRef, contentOriginWrapRef, rebuildHarnessToolsRef, harnessRef });
        if (toolSearch !== undefined)
            roster.mountEngineLane(toolSearch, { source: "builtin", mountedBy: "optional" });
        const rosterFacts = { effects: toolEffects, egress: egressTools, irreversibilityTier, reversibilityProbes, deferred, trustedTools: new Set(spec.memory?.trustedTools ?? []) };
        const toolRoster = roster.snapshot(rosterFacts);
        rosterSeat.arm(toolRoster, () => roster.snapshot(rosterFacts));
        const structuredProjector = createStructuredProjector({
            declaredCards: toolRoster.entries.flatMap((e) => e.renderHints?.resultCards ?? []),
            onUndeclared: (type) => deliverEngineNotice(deps.onNotice, { code: "config.tool_card_undeclared", message: `a tool minted a \`details.type\` card ${JSON.stringify(type)} its definition never declared — dropped from tool_end.structured (declare it on the definition's catalog row or the caller's renderHints.resultCards)`, detail: { type, sessionId, runId } }),
        });
        const { agentListing, announcedListingsRef, dateChange } = prepareListings({ spec, tools, onceLedger, sessionId, toolFaceSnapshot, activeTools, resume, skillsListing, listingBudget: doors.skillListingBudget, listingRideRef, renderWithDate, envFacts, tzValid, userTz, dateAnchor });
        const lastBrainContextRef = {};
        const requestLossyRef = { current: false };
        const staleOffloadWrittenRefs = new Set();
        const lastBrainContext = () => lastBrainContextRef.current;
        const recordBrainContext = (servedModelId, c) => {
            if (requestLossyRef.current) {
                lastBrainContextRef.current = undefined;
                return;
            }
            lastBrainContextRef.current = {
                ...(c.systemPrompt !== undefined ? { systemPrompt: c.systemPrompt } : {}),
                ...(c.systemBlocks !== undefined ? { systemBlocks: [...c.systemBlocks] } : {}),
                messages: [...c.messages],
                ...(c.tools !== undefined ? { tools: [...c.tools] } : {}),
                modelId: servedModelId,
            };
        };
        const staleOffloadCfg = resolveStaleToolResultOffload(spec.compaction?.staleToolResultOffload);
        if (staleOffloadCfg !== undefined && offloadStore === undefined) {
            onceLedger.onError(new Error("compaction.staleToolResultOffload is set but the tool-result offload store is disabled (toolResultThresholdChars ≤ 0/∞) — the knob is inert this run; re-enable offloading or drop the knob"), { phase: "config", sessionId });
        }
        const staleOffload = staleOffloadCfg !== undefined && offloadStore !== undefined ? { cfg: staleOffloadCfg, store: offloadStore } : undefined;
        const guardedBrain = brainCallGuardrailMs === undefined
            ? deps.brain
            : {
                ...deps.brain,
                stream: withBrainCallGuardrail((m, c, o) => deps.brain.stream(m, c, o), brainCallGuardrailMs, brainCallGuardrailRef),
            };
        const harness = new AgentHarness({
            abortResultDetails: () => (gateStopRef.terminal !== undefined ? { code: gateStopRef.terminal.code } : parkContaminationMarker({ pausedRef })),
            onToolInputValidationFault: validateInputFaultNotice(deps.onError, sessionId),
            ...(spec.limits?.maxOutputTokens !== undefined && spec.limits.maxOutputTokens > 0
                ? { maxOutputTokens: spec.limits.maxOutputTokens }
                : {}),
            stallTimeoutsPerCall: () => {
                callIssuedAtRef.current = Date.now();
                return { firstByteMs: STALL_FIRST_BYTE_MS, firstTokenMs: STALL_FIRST_TOKEN_MS, idleMs: STALL_IDLE_MS };
            },
            ...(spec.resilience !== undefined ? { resilience: spec.resilience } : {}),
            loopTrace: (step) => {
                if (step.kind === "continue")
                    workCutRef.continuation = true;
                else
                    workCutRef.continuation = workCutRef.continuation && step.reason === "aborted_before_stream";
                if (step.kind !== "continue")
                    return;
                if (step.reason === "next_turn" || step.reason === "steer_injected" || step.reason === "follow_up_injected")
                    return;
                emitTrace(deps.tracer, () => ({
                    kind: "loop.recovery",
                    version: 1,
                    taskId: hostTaskId,
                    reason: step.reason,
                    ts: Date.now(),
                }));
            },
            ...(spec.streamingToolExecution === true ? { streamingToolExecution: true } : {}),
            env: executionEnv,
            session,
            tools: [...harnessTools],
            model,
            modelRef: resolvedRole.modelRef,
            thinkingLevel: thinking,
            systemPrompt: systemPromptSeat.current,
            ...(systemBlocks ? { systemBlocks } : {}),
            getApiKeyAndHeaders: spec.getApiKeyAndHeaders,
            runtime: brainToRuntime({
                ...guardedBrain,
                stream: (m, c, o) => {
                    if (staleOffload === undefined) {
                        recordBrainContext(m.id, c);
                        return guardedBrain.stream(m, c, o);
                    }
                    return (async () => {
                        const projected = await projectStaleToolResults(c, staleOffload.cfg, staleOffload.store, sessionId, staleOffloadWrittenRefs);
                        recordBrainContext(m.id, projected);
                        return await guardedBrain.stream(m, projected, o);
                    })();
                },
            }),
        });
        harnessRef.current = harness;
        let releaseSignal = () => undefined;
        if (spec.signal) {
            if (spec.signal.aborted) {
                abortController.abort();
            }
            else {
                const sig = spec.signal;
                const onExternalAbort = () => {
                    abortController.abort();
                    void harness.abort();
                };
                sig.addEventListener("abort", onExternalAbort, { once: true });
                releaseSignal = () => sig.removeEventListener("abort", onExternalAbort);
            }
        }
        const { hooks, hookTimeoutMs, preToolUseObservational, ownGatePreToolUse, basePolicyForResumeEdit, denyNarrowingPolicy, skillGrantLane, allowEntryLanes, policyLayers, effectivePolicy, inheritedUnavailableAsks, inheritedAskGrants, askSourceIdentity, riskAxesOf, ruleOffersOf, permissionRuleLane, permissionRuleOrgLane, sandboxAdmissionArmed, sandboxBoundaryCapable, emitSandboxAdmitted, foldAskClasses, ancestorSandboxAdmissions, ancestorArbitrations } = await preparePolicyChain({ spec, deps, internals, sessionId, runId, hostTaskId, taskRootFinal, additionalRootsCanonical, executionEnv, lockedPreflight, tools, harnessTools, toolEffects, egressTools, irreversibilityTier, axisExplicitNegatives, shellGatedTools, toolMarkSources, envHandToolNames, handsCwdRef, readDenyMatcher, announceRuleStoreSkipped, questionToolMounted, runtimeCaps, inheritedAncestorRules, ancestorSessionRulesRef, inheritedParentConstraints, seedInheritedGate, skillGrants, allowedToolTables, frozenOnAsk, hookEnvSource, notifyOwnHookCrash, autoModeDecider: () => autoModeDeciderRef.current, permissionMode, scratchpadDir: spec.envFacts?.scratchpadDir, toolRosterDeltas: rosterSeat, stopForDenialLimit, delegation, abortController, now, ownSessionRulesRef });
        const { onAsk, preToolContexts, blockedToolCalls, gateOutcomes, batchHaltRef, blockedTracked, incompleteSuspendAdapter, durableSuspendInfraReady, resourceSuspendEligible, usageGovernance, durableApproval, wiringManifest, writeProtection, parkLaneArmed, gateMachineryActive, hookIdentity, hookEnvFace, sessionBoxBound } = prepareWiringManifest({ spec, deps, internals, resume, sessionId, runId, hostTaskId, taskScope, hooks, preToolUseObservational, policyLayers, effectivePolicy, handsEnabled, taskRootFinal, mcp, irreversibleTools, egressTools, shellReadStationArmed: handsReadFace.shellReadStationArmed, toolEffects, ownedEnv, executionEnv, offloadStore, onceLedger, usageWindows, envLifetimeSuspendAt, runtimeCaps, resolvedInteractionPosture, durableQuestionFace, liveQuestionFace, checkpointStore, sessions, modelGateManifest, autoModeArmReason, permissionMode, lockedPreflight, peerLaneRefs, frameSettlement, harness, pausedRef, frozenOnAsk, liveInheritedGate, delegation, toolRoster, readDenyBuiltinTiersActive: handsReadFace.readDenyBuiltinTiersActive, lspManagerWired, lspDiagnosticsLive: lspDiagnostics !== undefined, fileHistoryFact, sessionBox });
        const writeProtectionCheck = writeProtection?.check;
        writeProtectionJudgeRef.current = writeProtection?.judgeTarget;
        if (fileHistoryBoundary !== undefined) {
            harness.on("tool_call", async () => {
                await fileHistoryBoundary.settle();
                return undefined;
            });
        }
        const { askLane } = prepareAskLane({ gateMachineryActive, abortController, effectivePolicy, budgetSnapshot, handsCwdRef, advertisedWritableDirs, tools, inheritedUnavailableAsks, inheritedAskGrants, onAsk, humanReviewRef, now, ruleOffersOf, askSourceIdentity, riskAxesOf, autoModeDenialTracking: autoModeDenialTrackingRef, spec, deps, sessionId, runId, hooks, hookTimeoutMs, notifyOwnHookCrash, grantReadRoot: handsReadFace.grantReadRoot });
        const { saga } = prepareSuspendSaga({ gateMachineryActive, abortController, harness, checkpointStore, deps, sessionId, hostTaskId, taskScope, liveSpendRef, resume, nestedStats, internals, activeTools, outputRef, readFileStateForCheckpoint, faceCheckpointSection, writeFaceCheckpointSection, skillGrantCheckpointSection, reminderMark, handsCwdRef, worktreeSessionRef, undeliveredContinuationRef, inheritedParentConstraints, seedInheritedGate, ancestorRulesNow, inheritedShellGate, permissionMode, inheritedAdmittedOrgScopes, ownOrgVerdictRef, orgGovernedProvenance, announcedListingsRef, gitStatusRef, hookIdentity, placementRootResolved, externalContentTargetActive, remoteEnvFailures, memoryEngineSession, suspendLoopRef, ownedEnv, incompleteSuspendAdapter });
        const { suspendForResource, suspendForPlatformLimit, suspendForReview } = prepareBoundaryParks({ saga, spec, checkpointStore, abortController, harness, session, sessions, sessionId, deps, priorLedger, maxSlices, maxSuspends, resourceTotal, priorSuspendCount, suspendChainBase, humanReviewRef, liveSpendRef, now, faceCheckpointState, f012CheckpointState, orgAdmissionCheckpointState, pausedRef, remoteEnvFailures, resourceSuspendEligible, durableSuspendInfraReady, incompleteSuspendAdapter });
        const { parkAsk } = prepareParkAsk({ askLane, saga, spec, deps, sessionId, checkpointStore, toolRosterDeltas: rosterSeat, parkLaneArmed, contentAskRoutable, liveQuestionFace, mountedQuestionTool, contentAskBindings, lateStrandedAnswers, discloseStrandedAnswers, onAsk, runtimeCaps, inheritedUnavailableAsks, basePolicyForResumeEdit, budgetSnapshot, handsCwdRef, advertisedWritableDirs, offloadStore, ownedEnv, incompleteSuspendAdapter, session, sessions, suspendChainBase, maxSuspends, remoteEnvFailures, shellGatedTools, irreversibilityTier, toolMarkSources, effectiveShellGate, durableApproval, priorLedger, liveSpendRef, resourceTotal, faceCheckpointState, f012CheckpointState, orgAdmissionCheckpointState, ruleOffersOf, skillSpecs, now, humanReviewRef, abortController, harness, pausedRef });
        const seatInputsFor = skillGateWiring({ tools, skillToolName: SKILL_TOOL_NAME, seatOf: skillSeatOf, mode: () => permissionMode.current, lane: skillGrantLane, onAllowed: (info) => emitTrace(deps.tracer, () => ({ kind: "permission.skill_allowed", version: 1, taskId: hostTaskId, ...info, entries: [...info.entries], ts: Date.now() })), allowEntries: { deploymentAllows: { ...allowEntryLanes.deployment, onAllowed: (info) => emitTrace(deps.tracer, () => ({ kind: "permission.allowed_tools_allowed", version: 1, taskId: hostTaskId, source: "deployment", ...info, entries: [...info.entries], ts: Date.now() })) }, requestAllows: { ...allowEntryLanes.request, onAllowed: (info) => emitTrace(deps.tracer, () => ({ kind: "permission.allowed_tools_allowed", version: 1, taskId: hostTaskId, source: "request", ...info, entries: [...info.entries], ts: Date.now() })) } } });
        const { approvedCallScreen } = prepareGateStations({ askLane, parkAsk, tools, toolRosterDeltas: rosterSeat, toolEffects, deps, toolCallGateArmedRef, effectivePolicy, hooks, egressTools, irreversibleTools, spec, complianceDenies, harness, blockedToolCalls, inheritedAskGrants, inheritedUnavailableAsks, foldAskClasses, ancestorSandboxAdmissions, preToolContexts, gateOutcomes, batchHaltRef, blockedTracked, hookIdentity, reminderMark, hostTaskId, sessionId, ownGatePreToolUse, hookTimeoutMs, handsCwdRef, readDenyInForce: () => ({ tiers: handsReadFace.readDenyBuiltinTiersActive, rows: [...readDenyAdditionsNormalized.map((e) => e.pattern), ...handsReadFaceInput.pathDenyRules.filter((r) => r.faces.includes("read")).map((r) => r.rule)] }), hookEnvFace, writeProtectionCheck, shellReadCheck, irreversibilityTier, reversibilityProbes, abortController, shellGatedTools, autoModeDecider: autoModeDeciderRef, autoModeDenialTracking: autoModeDenialTrackingRef, askRoute: { ...wiringManifest.ask, effective: askSeatEffective(wiringManifest) }, permissionMode, toolMarkSources, ...(deps.a2a?.isolatePeers === true ? { a2aIsolatePeers: true } : {}), ancestorArbitrations, runId, stopForDenialLimit, permissionRuleLane, seatInputsFor, permissionRuleOrgLane, questionToolMounted, sandboxAdmissionArmed, sandboxBoundaryCapable, emitSandboxAdmitted, delegation, notifyOwnHookCrash, frameSettlement });
        const postureFrameRef = { report: (err) => deps.onError?.(err, { phase: "degraded", sessionId }) };
        const { microCompact, charsPerToken } = prepareContextLane({ model, deps, sessionId, runId, hostTaskId, offloadStore, toolRosterDeltas: rosterSeat, microCompactKnob, harness, batchHaltRef, gitStatusRef, postureFrameRef, requestLossyRef, trimPressureRef, contextOverlay: legContextOverlay, ...(readFileStateForCheckpoint !== undefined ? { readFileState: readFileStateForCheckpoint } : {}) });
        const preparedHolder = {};
        const { cacheBreakDetector, cacheFingerprint, promptOverheadTokens, readTaskFile, normalizeAttachmentPath, isDedupStubResult, recentlyReadFiles, onCompactionApplied, detectExternalChanges, listBackgroundTasks, centerCompactionCandidate, effectiveReadFaceObserved, effectiveWriteFaceObserved, effectiveReadDenyObserved } = prepareTurnWiring({ deps, systemPromptSeat, harnessTools, fpRef, model, epochArtifactDigestForSnapshot, promptProfile, fableMitigations, systemBlocks, thinking, spec, sessionId, turnSnapshotRef, promptManifest, charsPerToken, handsEnabled, executionEnv, attachmentRootCanonical, additionalRootsCanonical, additionalReadRootsCanonical, readDenyMatcher, resolvedReadFace, handsCwdRef, readFileStateForCheckpoint, denyNarrowingPolicy, skillGrants: skillGrantLane, callerPolicy: lockedPreflight.toolPolicy, inheritedPolicies: (inheritedParentConstraints ?? []).map((c) => c.policy), persistedRuleLane: permissionRuleLane, orgRuleLane: permissionRuleOrgLane, abortController, hostTaskId, taskScope, buildAssembleInputs, centerAdoptionRef, harnessRef, epochDeclaredSections, carrierReadFace, carrierWriteFace, readDenyAdditionsNormalized, preparedHolder });
        await onceLedger.settle(session, announcedListingsRef);
        const buildPrepared = () => ({ harness, session, sessionId, runId, registryAccess: { owner: hostTaskId, scope: taskScope }, reminderMark, reminderDisclosureCounts, fullShellReachable, approvalPosture: { get mode() { return permissionMode.current; }, askEffective: askSeatEffective(wiringManifest) }, ...(outputStyleFrame !== undefined ? { outputStyleFrame } : {}), permissionMode, editedFilesSnapshot, taskRootPath: taskRootFinal, model, thinking, compModel: effectiveCompModel, mcp, ...(mcpRedial !== undefined ? { mcpRedial } : {}), ...(a2a.tools.length > 0 ? { a2a } : {}), blockedRef, outputRef, abortController, conflictRef, blockedToolCalls, gateOutcomes, batchHaltRef, nestedStats, ...(rewindNotes.length > 0 ? { rewindNotes } : {}), ...(fileHistoryBoundary !== undefined ? { fileHistoryBoundary } : {}), ...(effectiveReadFaceObserved !== undefined ? { effectiveReadFace: effectiveReadFaceObserved, effectiveWriteFace: effectiveWriteFaceObserved } : {}), ...(effectiveReadDenyObserved !== undefined ? { effectiveReadDenyPatterns: effectiveReadDenyObserved } : {}), effectiveMemoryScopes: memoryEffectiveScopes, cwdRef: handsCwdRef, toolProgressRef, ...(advertisedWritableDirs !== undefined ? { advertisedWritableDirs } : {}), ...(worktreeSessionRef !== undefined ? { worktreeSessionRef } : {}), ...(workspaceStateSettle !== undefined ? { workspaceStateSettle } : {}), ...(sealReadStateSeat !== undefined ? { sealReadStateSeat } : {}), denyNarrowingPolicy, skillGrants: skillGrantLane, skillSpecs, ...(permissionRuleLane !== undefined ? { persistedRuleLane: permissionRuleLane } : {}), ...(basePolicyForResumeEdit !== undefined ? { basePolicyForResumeEdit } : {}), ...(permissionRuleOrgLane !== undefined ? { permissionRuleOrg: permissionRuleOrgLane } : {}), releaseSignal, endModeCeiling, settleContentAskBindings, cacheBreakDetector, cacheFingerprint, wiringManifest, promptManifest, epochDeclaredSections, activeTools, ...(deferred.size > 0 ? { deferredToolNames: deferred } : {}), toolMaterializeStatic, deferDirectCall, ...(staticFaceForRef.current !== undefined ? { staticFaceFor: staticFaceForRef.current } : {}), ownedEnv, pausedRef, undeliveredContinuationRef, suspendProgressRef, remoteEnvFailures, reviewRequestRef, suspendLoopRef, suspendForResource, ...(suspendForPlatformLimit !== undefined ? { suspendForPlatformLimit } : {}), ...(envLifetimeSuspendAt !== undefined ? { envLifetimeSuspendAt } : {}), ...(usageGovernance !== undefined ? { usageGovernance } : {}), callIssuedAtRef, workCutRef, brainCallGuardrailRef, gateStopRef, stopForDenialLimit, suspendForReview, ...(readFileStateForCheckpoint !== undefined ? { readFileState: readFileStateForCheckpoint } : {}), resourceLedger: priorLedger, liveSpendRef, humanReviewRef, now, tools, toolRoster, toolRosterDeltas: rosterSeat, structuredProjector, toolEffects, wakeRecovered, promptOverheadTokens, lastBrainContext, readTaskFile, recentlyReadFiles, normalizeAttachmentPath, isDedupStubResult, ...(onCompactionApplied ? { onCompactionApplied } : {}), compactionReuseRef, trimPressureRef, microCompact, ...(memoryEngineSession ? { memoryEngineSession } : {}), ...(subagentRetain ? { subagentRetain } : {}), ...(lspDiagnostics && nudgeLspOnEdit ? { lspDiagnostics: { registry: lspDiagnostics, nudge: nudgeLspOnEdit, runIdent: lspRunIdent } } : {}), stopRequestedRef, announcedSnapshotRecovered: onceLedger.recovered, ...(dateChange ? { dateChange } : {}), ...(instructionSources ? { instructionSources } : {}), ...(projectInstructionContent !== undefined ? { projectInstructionContent } : {}), ...(workflowSizeGuideline ? { workflowSizeGuideline } : {}), ...(detectExternalChanges ? { detectExternalChanges } : {}), ...(toolsDeltaRef ? { toolsDeltaRef } : {}), ...(agentListing ? { agentListing } : {}), ...(skillsListing ? { skillsListing } : {}), announcedListingsRef, frameReceipts: { pending: [], listingSnapshotOwed: false }, frameSettlement, ...(peerLaneRefs.boundaryRound !== undefined ? { peerBoundaryRound: peerLaneRefs.boundaryRound } : {}), gitStatusRef, postureFrameRef, listBackgroundTasks, hookIdentity, ...(sessionBoxBound !== undefined ? { sessionBox: sessionBoxBound } : {}), hookTimeoutMs, ...(turnSnapshotRef.current !== undefined ? { turnSnapshot: turnSnapshotRef.current } : {}), ...(centerCompactionCandidate !== undefined ? { centerCompactionCandidate } : {}), ...(shellReadCheck !== undefined ? { shellReadCheck } : {}), ...(toolDisclosureSeat !== undefined ? { toolDisclosure: toolDisclosureSeat } : {}), ...(approvedCallScreen !== undefined ? { approvedCallScreen } : {}) });
        rollback.commit();
        commitModeSeats(abortController.signal);
        const prepared = buildPrepared();
        preparedHolder.current = prepared;
        return prepared;
    }
    catch (prepareErr) {
        await rollback.unwindAll();
        await settleTeardownLeg(() => forgetOnThrow(), "forgetOnThrow (prepare-throw leg)", (e) => deps.onError?.(e, { phase: "config", sessionId }));
        throw prepareErr;
    }
}