@sema-agent/core
Version:
Stateless, task-oriented AI agent core
832 lines • 80.4 kB
JavaScript
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 { refuseLateRosterChanges, snapshotCallerRoster } from "./caller-roster.js";
import { toolPolicyPathRules, toolPolicyWriteGuardRows } from "../tool-policy.js";
import { dataRootSpellings } from "../sensitive-path-policy.js";
import { bindPathRules, createHeadLeads } from "../path-rule-binding.js";
import { whereItsAnsweredPrefixLeads } from "../../tools/fs/read-deny-home.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 { personPathRowsOfTask, ruleRowsDroppedNotice, ruleStoreUnreadableNotice } from "./person-path-rows.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 { compileSkillGrant, skillGateWiring } from "../skill-grant.js";
import { legCallTargetStamp, validatePath } from "../effective-path-target.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 { chainAnchorRecords, chainPolicyOnLeg, chainTopAnchors, deploymentCanRerootChild } from "./child-tree.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 { checkpointScopeOf, 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 { compileToolSelector, valveLeaves } from "../../agents/tool-filter.js";
import { boundOwnToolLists, boundToolListsJudgment, judgeRunToolLists } from "./sub-agent-deny-lists.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 { mountedMcpOf } from "../mounted-mcp.js";
import { McpConnectionPool } from "../mcp-connection-pool.js";
import { rosterCanPersistMemory } 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 { toolResultMediaRefusedSeat } from "./tool-result-media-seat.js";
import { asThrownError, thrownText } from "../thrown-value.js";
import { createAttachmentDelivery, refuseUserAttachmentPathsWithoutWorkspace, screenUserAttachments } from "../user-attachment.js";
import { admitLegMods, legFacadeSeats } from "../mods/stations.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(request, deps, sessions, resume, internals, runnerSelf, runIdSink, holdSessionLock) {
const runId = uuidv7();
if (runIdSink !== undefined)
runIdSink.runId = runId;
const callerRoster = snapshotCallerRoster(request);
const mountsCallerTool = callerToolMembership(callerRoster.roster.handed);
let spec = callerRoster.spec;
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 userAttachmentsSeat = screenUserAttachments(spec.userAttachments, { resumeLeg: resume !== undefined });
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 { toolFaceLists, promptProfile, promptHost, promptBinding, 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);
const ownToolLists = boundOwnToolLists(internals?.ownToolLists ?? resume?.seed.ownToolLists, toolFaceLists);
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 toolLegs = [
...(delegation.isDelegatedChild ? ["delegated"] : []),
...(internals?.explicitAgentName !== undefined ? ["teammate"] : []),
...(internals?.goalMode === true ? ["goal"] : []),
...(internals?.observerLeg === true ? ["observer"] : []),
...(spec.outputSchema !== undefined ? ["structured"] : []),
];
const toolCeiling = internals?.toolCeiling ?? resume?.seed.toolCeiling;
const toolListsJudged = boundToolListsJudgment(internals?.toolListsJudged ?? resume?.seed.toolListsJudged, toolFaceLists);
const toolFaceSnapshot = Object.freeze({
selector: compileToolSelector([...(toolCeiling ?? []), Object.freeze({ ...(toolFaceLists.allow !== undefined ? { allow: toolFaceLists.allow } : {}), deny: toolFaceLists.exclude ?? [] })], toolLegs),
defer: toolFaceLists.defer,
alwaysLoad: toolFaceLists.alwaysLoad,
restoreGated: toolFaceLists.restoreGated,
});
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";
const checkpointScope = checkpointScopeOf(spec, internals?.checkpointScope || resume?.seed.legScope);
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 && valveLeaves(spec, toolFaceSnapshot.selector)({ name: 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 { nestedStats, reportUsage, offloadStore, offloadReachableToolsRef, maybeOffload, firstPartyOffload, remoteToolOffload } = prepareOffloadWrappers({ spec, deps, resume, offloadScope, sessionId, selector: toolFaceSnapshot.selector });
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, placement } = await prepareExecutionEnv({ deps, spec, internals, resume, placementRootResolved, sessionId, forgetOnThrow, rollback });
if (!handsEnabled)
refuseUserAttachmentPathsWithoutWorkspace(userAttachmentsSeat);
const externalContentTargetActive = executionEnv.externalContentTarget === true || resume?.seed.externalContentTarget === true;
const abortController = new AbortController();
if (spec.signal?.aborted)
abortController.abort();
try {
const legMods = resume?.legMods ?? (await admitLegMods({ spec, deps, sessionId }));
const ownModChain = legMods.chain;
const notifyOwnHookCrash = (err) => {
try {
deps.onError?.(asThrownError(err), { phase: "hook", sessionId });
}
catch {
}
};
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 (!deploymentCanRerootChild(deps)) {
failIsolation("no executionEnvFactory is configured (a static/shared execution env cannot mint a per-agent worktree)");
}
else if (ownedEnvSeat.current === undefined) {
failIsolation("the executionEnvFactory returned no env instead of a worktree-rooted env");
}
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, placement, abortController, sessionId });
const { canonical: taskRootCanonical } = await resolveTaskRootCanonical({ env: executionEnv, given: taskRootFinal, onNotice: deps.onNotice, sessionId, runId });
const legHome = validatePath(executionEnv.homeDir, { intent: "validate-coordinate" });
const legAnchors = { root: taskRootCanonical, ...(legHome !== undefined ? { home: legHome } : {}) };
const chainTop = chainTopAnchors({ leg: legAnchors, live: internals?.inheritedGate?.pathRuleAnchors, seed: resume?.seed.inheritedGate?.pathRuleAnchors, placement, rebase: rebaseRestoredPath });
const onLeg = chainPolicyOnLeg({ leg: legAnchors, chainTop, placement, chain: (internals?.inheritedGate?.parentConstraints ?? []).map((c) => c.policy), installations: { live: internals?.inheritedGate?.pathRuleInstallations, seed: resume?.seed.inheritedGate?.pathRuleInstallations }, rebase: rebaseRestoredPath });
const [installedToolPolicy, installedBaseEdit] = [lockedPreflight.toolPolicy, lockedPreflight.basePolicyForResumeEdit].map(onLeg.own);
const installedPreflight = { ...lockedPreflight, toolPolicy: installedToolPolicy, basePolicyForResumeEdit: installedBaseEdit };
const headLeads = createHeadLeads((part) => whereItsAnsweredPrefixLeads(executionEnv, part));
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, toolOccurrences, 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 mcpPool = installedPreflight.mcp?.length ? { pool: internals?.mcpPool ?? new McpConnectionPool(), owned: internals?.mcpPool === undefined } : undefined;
const mountedMcpNow = mcpPool !== undefined ? () => mountedMcpOf({ declared: installedPreflight.mcp, roster: roster.tools, aggregateNames: new Set(mcp.tools.filter((t) => t.mcpRemoteName === undefined).map((t) => t.name)), pool: mcpPool.pool }) : undefined;
const { liveInheritedGate, seedInheritedGate, inheritedAncestorRules, inheritedShellGate, inheritedParentConstraints, permissionMode, commitModeSeats, endModeCeiling, inheritedAdmittedOrgScopes, priorOwnOrgVerdict, orgGovernedProvenance, effectiveShellGate, ownSessionRulesRef, ancestorSessionRulesRef, ancestorRulesNow, memoryAdmittedOrgScopesRef, ownOrgVerdictRef, runClampSource, faceCheckpointSection, writeFaceCheckpointSection, skillGrantCheckpointSection, frozenOnAsk, hookEnvSource, frozenOnQuestion, parentSpecSeat, provenanceForChildrenRef, delegationSettlementRef, inheritedGateForChildren, carrierReadFace, carrierWriteFace, fullShellReachable, gateStopRef, stopForDenialLimit, enrichSpecToolCtx } = prepareInheritedGate({ spec, deps, askSeat: doors.askSeat, internals, resume, sessions, sessionId, runId, hostTaskId, taskRootFinal, executionEnv, ownedEnv, lockedPreflight: installedPreflight, pathRuleAnchors: { chainTop, onLeg: onLeg.chained }, checkpointSeat, checkpointScope, toolFaceSnapshot, mountsCallerTool, ...(mountedMcpNow !== undefined ? { mountedMcp: mountedMcpNow } : {}), 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, modBus: legMods.bus, ownModChain, 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 personRowNotices = { onUnread: ruleStoreUnreadableNotice(deps.onNotice, { sessionId, runId }), onRowsDropped: ruleRowsDroppedNotice(deps.onNotice, { sessionId, runId }) };
const readerOf = (signals) => personPathRowsOfTask({ deps, notices: personRowNotices, principal: spec.principal, ids: { sessionId, runId, taskId: hostTaskId }, root: taskRootFinal, rootCanonical: taskRootCanonical, leads: headLeads, chainTop, occurrences: toolOccurrences, signals });
const personRows = readerOf([abortController.signal, ...(spec.signal !== undefined ? [spec.signal] : [])]);
const personRowsBeyondRun = readerOf([]);
const primed = handsEnabled ? personRows.prime() : undefined;
if (primed !== undefined)
await primed;
const policyDenyRows = toolPolicyPathRules([installedToolPolicy, ...(inheritedParentConstraints ?? []).map((c) => c.policy)], legAnchors).filter((r) => r.faces.length > 0 && r.behavior === "deny");
for (const r of policyDenyRows)
if (r.unanchored !== undefined)
emitTrace(deps.tracer, () => ({ kind: "permission.rule_store_unreadable", version: 1, taskId: hostTaskId, message: `the deny rule ${r.rule} needs a ${r.unanchored.join(" / ")} base this task does not declare — the shell's file commands and the search tools do not judge it on this leg (the gate asks)`, ts: Date.now() }));
const effectivePathDenyRules = policyDenyRows.filter((r) => r.unanchored === undefined);
const writeTargetJudgeRef = {};
const legExemptRoots = Object.freeze(dataRootSpellings(deps.memoryEngineDir));
const legWriteGuard = { exemptRoots: legExemptRoots, rows: toolPolicyWriteGuardRows([installedToolPolicy, ...(inheritedParentConstraints ?? []).map((c) => c.policy)]) };
const sideCallBookRef = {};
const { roster, blockedRef, runtimeCaps, runtimeCapsFaulted, complianceDenies, complianceDegraded, agentForkDenial, observersActive, autoModeArmReason, autoModeDeciderRef, autoModeDenialTrackingRef, autoModeArmingRef, armAutoMode, selfOrchestrationActive, workflowToolsActive, workflowSizeGuideline } = await prepareCapsAndWorkflow({ spec, deps, askSeat: doors.askSeat, internals, session, sessionId, runId, hostTaskId, taskScope, taskRootFinal, model, thinking, lockedPreflight, checkpointSeat, toolEffects, toolFaceSnapshot, promptProfile, resolvedInteractionPosture, harnessRef, parentSpecSeat, runClampSource, forwardEvent, inheritedGateForChildren, enrichSpecToolCtx, maybeOffload, requestReview, enterPlanMode, permissionMode, readDenyEntries: () => personRows.tablesReady().then(() => ({ entries: readDenyMatcher?.entries ?? [], ruleRows: pathTables?.ruleRows() ?? effectivePathDenyRules })), peerLaneActive, peerSendMessageBuiltIn, runnerSelf, memoryEngineSession: () => memoryEngineSession, centerAdoption: () => centerAdoptionRef.current, delegated: delegation.isDelegatedChild, sideCallBookRef });
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, modBus: legMods.bus, ...(mcpPool !== undefined ? { mcpPool } : {}), 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) => !valveLeaves(spec, toolFaceSnapshot.selector)({ name: n }));
const memoryPairOccupiedName = MEMORY_ENGINE_TOOL_NAMES.find((n) => memoryPairNameDomain.has(n));
const memorySearchToolsPlanned = memoryPairExcludedName === undefined && memoryPairOccupiedName === undefined;
const captureLineage = await (async () => {
try {
const { forkedFrom: ff, forkedFromIncarnation: copied, incarnation: own } = await session.getMetadata();
return { ...(ff !== undefined ? { origin: ff, ...(copied !== undefined ? { originIncarnation: copied } : {}) } : {}), ...(own !== undefined ? { own } : {}), fault: false };
}
catch {
return { fault: true };
}
})();
const { memoryEngineSession, memoryTools, memoryWriteGate, composeInjection: composeMemoryInjection, admittedOrgScopes: memoryAdmittedOrgScopes, ownOrgVerdict: memoryOwnOrgVerdict, effectiveMemoryScopes: memoryEffectiveScopes, } = await prepareMemory({
spec,
deps,
sessionId,
...(captureLineage.own !== undefined ? { sessionIncarnation: captureLineage.own } : {}),
taskRootPath: taskRootFinal,
reminderMark,
writeToolsMounted: (handsWriteHalfPlanned || tools.some((t) => t.name === "Write")) &&
valveLeaves(spec, toolFaceSnapshot.selector)({ name: "Write" }) &&
!(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.originIncarnation !== undefined ? { captureForkOriginIncarnation: captureLineage.originIncarnation } : {}),
...(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 modelFileReaderSeat = {};
const handsReadFaceInput = { permissionMode, denyRuleRows: effectivePathDenyRules, headLeads, writeTargetJudge: () => writeTargetJudgeRef.current, personRows, 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, modelFileReaderSeat, ...(trackFileEdit !== undefined ? { trackFileEdit } : {}), onFileEdited: noteFileEdited, harnessRef, toolProgressRef, toolOccurrences, ...(restoredFilePaths.length > 0 ? { restoredFilePaths } : {}) };
const handsReadFace = handsEnabled ? await prepareHandsMount(handsReadFaceInput) : resolveHandsLessReadFace(handsReadFaceInput);
const { readFileStateForCheckpoint, seedContextFiles, handsCwdRef, workspaceStateSettle, wsSnapshot, rebaseWsPath, backgroundTaskToolsActive, shellReadCheck, shellReadAdmission, additionalRootsCanonical, attachmentRootCanonical, readDenyMatcher, readRoots, pathTables, 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, toolFaceSnapshot, 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, withheldDiagnosticsOf, lspRunIdent, managerWired: lspManagerWired } = prepareLsp({ spec, deps, executionEnv, taskRootFinal, readFace: attachmentRootCanonical !== undefined ? { rootCanonical: attachmentRootCanonical, roots: readRoots, ready: personRows.tablesReady, ...(handsCwdRef !== undefined ? { cwdRef: handsCwdRef } : {}), ...(readDenyMatcher !== undefined ? { readDeny: readDenyMatcher } : {}), ...(resolvedReadFace !== undefined ? { face: resolvedReadFace } : {}), ...(handsReadFace.readAdmission !== undefined ? { admitted: handsReadFace.readAdmission } : {}) } : undefined, sessionId, roster, envHandToolNames });
prepareArtifact({ deps, runId, taskId: hostTaskId, sessionId, agentName: internals?.explicitAgentName, onAsk: frozenOnAsk, toolOccurrences, permissionMode, executionEnv, rootCanonical: attachmentRootCanonical, additionalRootsCanonical: readRoots, 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 = rosterCanPersistMemory(tools.filter(valveLeaves(spec, toolFaceSnapshot.selector)), { effects: toolEffects, remoteHands: handsEnabled && isRemoteExecutionEnv(executionEnv) }, spec.memoryPersistenceCapable);
const { memoryBlock: memoryBlockFromEngine, recallDisciplineSegment: memoryRecallSegment, seedFiles: memorySeedFiles } = composeMemoryInjection({ rosterCanPersist, isSubagent: delegation.isNonForkChild });
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, runId, 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 { featureFlags, sugar, mcpInstructionsBlock, envFacts, tzValid, userTz, dateAnchor, gitStatusRef } = await preparePromptInputs({ modBus: legMods.bus, 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, roster, model, externalContentTargetActive, resume, handsEnabled, taskRootFinal, additionalRootsCanonical, additionalReadRootsCanonical: (await readRoots.ready().then(readRoots)).filter((r) => !additionalRootsCanonical.includes(r)), sessionId, session, ...(advertisedWritableDirs !== undefined ? { advertisedWritableDirs } : {}) });
judgeRunToolLists({ spec, tools: roster.tools, declaredPeers: { mcp: lockedPreflight.mcp, a2a: a2a.statuses }, own: { allow: toolFaceLists.allow, exclude: toolFaceLists.exclude }, layers: toolFaceSnapshot.selector.layers, legs: toolLegs, judgedUpstream: toolListsJudged !== undefined, toldUpstream: internals?.ownToolLists !== undefined && ownToolLists !== undefined && toolCeiling !== undefined, ownBy: ownToolLists, onceLedger, sessionId });
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, ...(mountedMcpNow !== undefined ? { mountedMcp: mountedMcpNow } : {}), sessionId, runId, deps, provenanceForChildrenRef, delegationSettlementRef, spec, envHandToolNames, roster, contentOriginWrapRef });
const { systemPromptSeat, renderWithDate, systemBlocks, promptManifest, promptIdentity, buildAssembleInputs, identityFor, adoptsCandidates, centerAdoptionRef } = await preparePromptAssembly({ session, deps, internals, resume, sugar, host: promptHost, binding: promptBinding, modBus: legMods.bus, signal: abortController.signal, featureFlags, mcpInstructionsBlock, memoryBlock, envFacts, promptProfile, fableMitigations, tools, model, sessionId, 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, onceLedger, sessionId, toolFaceSnapshot, activeTools, deferred, 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),
onToolMediaRefused: toolResultMediaRefusedSeat(deps.onNotice, { sessionId, runId }),
...(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 { basePolicyForResumeEdit, denyNarrowingPolicy, skillGrantLane, allowEntryLanes, policyLayers, effectivePolicy, inheritedUnavailableAsks, inheritedAskGrants, askSourceIdentity, riskAxesOf, ruleOffersOf, grantBindingOf, permissionRuleLane, ruleLaneFacts, permissionRuleOrgLane, sandboxAdmissionArmed, sandboxBoundaryCapable, emitSandboxAdmitted, foldAskClasses, ancestorSandboxAdmissions, ancestorArbitrations, inheritedToolChecks } = await preparePolicyChain({ spec, deps, internals, sessionId, runId, hostTaskId, taskRootFinal, additionalRootsCanonical, executionEnv, lockedPreflight: installedPreflight, pathRuleAnchors: { leg: legAnchors, chainTop }, headLeads, tools, harnessTools, selector: toolFaceSnapshot.selector, toolEffects, egressTools, irreversibilityTier, axisExplicitNegatives, shellGatedTools, toolMarkSources, envHandToolNames, handsCwdRef, readDenyMatcher, personRows, questionToolMounted, runtimeCaps, inheritedAncestorRules, ancestorSessionRulesRef, inheritedParentConstraints, seedInheritedGate, skillGrants, skillSpecs, allowedToolTables, frozenOnAsk, hookEnvSource, notifyOwnHookCrash, modBus: legMods.bus, ownModChain, autoModeDecider: () => autoModeDeciderRef.current, readFace: () => resolvedReadFace, permissionMode, scratchpadDir: spec.envFacts?.scratchpadDir, toolRosterDeltas: rosterSeat, stopForDenialLimit, delegation, abortController, now, ownSessionRulesRef });
const { onAsk, preToolContexts, blockedToolCalls, batchHaltRef, blockedTracked, incompleteSuspendAdapter, durableSuspendInfraReady, resourceSuspendEligible, usageGovernance, durableApproval, wiringManifest, writeProtection, parkLaneArmed, gateMachineryActive, hookIdentity, hookEnvFace, sessionBoxBound } = prepareWiringManifest({ spec, deps, askSeat: doors.askSeat, internals, resume, sessionId, runId, hostTaskId, taskScope, modBus: legMods.bus, policyLayers, effectivePolicy, handsEnabled, taskRootFinal, legWriteGuard, 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, liveInheritedGate, delegation, toolRoster, readDenyBuiltinTiersActive: handsReadFace.readDenyBuiltinTiersActive, lspManagerWired, lspDiagnosticsLive: lspDiagnostics !== undefined, fileHistoryFact, sessionBox, checkpointScope, memoryPollution: () => memoryEngineSession?.pollution });
const writeProtectionCheck = writeProtection.mount?.check;
writeTargetJudgeRef.current = writeProtection.judgeWriteTarget;
if (fileHistoryBoundary !== undefined) {
harness.on("tool_call", async () => {
await fileHistoryBoundary.settle();
return undefined;
});
}
const listPathRows = () => skillSpecs.flatMap((s) => compileSkillGrant(s, "model").rows).flatMap((r) => (r.behavior === "deny" && r.compiled.kind === "path" ? [r.compiled.rule] : []));
const stampCallTarget = attachmentRootCanonical === undefined ? undefined : legCallTargetStamp({ env: executionEnv, root: attachmentRootCanonical, cwd: () => handsCwdRef?.current, judgesPaths: () => effectivePolicy?.pathRules !== undefined || basePolicyForResumeEdit?.pathRules !== undefined || permissionRuleLane !== undefined || skillSpecs.some((s) => compileSkillGrant(s, "model").rows.some((r) => r.compiled.kind === "path")) || allowedToolTables.request.holdsPathRows() || allowedToolTables.deployment.holdsPathRows(), leads: () => headLeads.resolve([...toolPolicyPathRules([effectivePolicy, basePolicyForResumeEdit, ...(inheritedParentConstraints ?? []).map((c) => c.policy)], legAnchors), ...bindPathRules(listPathRows().map((rule) => ({ parsed: rule, ruleText: rule.rule })), legAnchors)]) });
const { askLane } = prepareAskLane({ gateMachineryActive, abortController, effectivePolicy, budgetSnapshot, handsCwdRef, handsRoot: attachmentRootCanonical, stampCallTarget, advertisedWritableDirs, exemptRoots: legExemptRoots, tools, inheritedUnavailableAsks, inheritedAskGrants, onAsk, humanReviewRef, now, ruleOffersOf, grantBindingOf, askSourceIdentity, riskAxesOf, autoModeDenialTracking: autoModeDenialTrackingRef, spec, deps, sessionId, runId, modBus: legMods.bus, notifyOwnHookCrash, grantReadRoot: handsReadFace.grantReadRoot });
const inheritedAnchorRecords = chainAnchorRecords(chainTop, inheritedParentConstraints ?? []);
const { saga } = prepareSuspendSaga({ gateMachineryActive, abortController, harness, checkpointStore, deps, sessionId, hostTaskId, taskScope, liveSpendRef, resume, nestedStats, internals, activeTools, outputRef, readFileStateForCheckpoint, faceCheckpointSection, writeFaceCheckpointSection, skillGrantCheckpointSection, reminderMark, handsCwdRef, handsRoot: attachmentRootCanonical, handsHome: attachmentRootCanonical !== undefined ? legAnchors.home : undefined, worktreeSessionRef, undeliveredContinuationRef, inheritedParentConstraints, seedInheritedGate, ancestorRulesNow, inheritedShellGate, permissionMode, inheritedAdmittedOrgScopes, inheritedPathRuleAnchors: chainTop !== legAnchors ? inheritedAnchorRecords.pathRuleAnchors : undefined, inheritedPathRuleInstallations: inheritedAnchorRecords.pathRuleInstallations, ownOrgVerdictRef, orgGovernedProvenance, announcedListingsRef, gitStatusRef, hookIdentity, placementRootResolved, checkpointScope, toolCeiling, toolListsJudged, ownToolLists, externalContentTargetActive, remoteEnvFailures, memoryEngineSession, suspendLoopRef, ownedEnv, incompleteSuspendAdapter });
const { suspendForResource, suspendForPlatformLimit, suspendForReview } = prepareBoundaryParks({ saga, spec, checkpointStore, checkpointScope, abortController, harness, session, sessions, sessionId, deps, priorLedger, maxSlices, maxSuspends, resourceTotal, priorSuspendCount, suspendChainBase, humanReviewRef, liveSpendRef, now, pausedRef, remoteEnvFailures, resourceSuspendEligible, durableSuspendInfraReady, incompleteSuspendAdapter });
const { parkAsk } = prepareParkAsk({ askLane, saga, spec, deps, sessionId, checkpointStore, checkpointScope, toolRosterDeltas: rosterSeat, parkLaneArmed, contentAskRoutable, liveQuestionFace, mountedQuestionTool, contentAskBindings, lateStrandedAnswers, discloseStrandedAnswers, onAsk, runtimeCaps, inheritedUnavailableAsks, basePolicyForResumeEdit, budgetSnapshot, handsCwdRef, handsRoot: attachmentRootCanonical, stampCallTarget, advertisedWritableDirs, exemptRoots: legExemptRoots, offloadStore, ownedEnv, incompleteSuspendAdapter, session, sessions, suspendChainBase, maxSuspends, remoteEnvFailures, shellGatedTools, irreversibilityTier, toolMarkSources, effectiveShellGate, durableApproval, priorLedger, liveSpendRef, resourceTotal, ruleOffersOf, grantBindingOf, 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, modBus: legMods.bus, inheritedToolChecks, egressTools, irreversibleTools, spec, complianceDenies, harness, blockedToolCalls, inheritedAskGrants, inheritedUnavailableAsks, foldAskClasses, ancestorSandboxAdmissions, preToolContexts, toolOccurrences, batchHaltRef, blockedTracked, hookIdentity, reminderMark, hostTaskId, sessionId, handsCwdRef, stampCallTarget, readDenyInForce: (toolCallId) => ({ tiers: handsReadFace.readDenyBuiltinTiersActive, rows: [...readDenyAdditionsNormalized.map((e) => e.pattern), ...(pathTables?.forCall(toolCallId).ruleRows ?? handsReadFaceInput.denyRuleRows).filter((r) => r.faces.includes("read")).map((r) => r.rule)] }), hookEnvFace, writeProtectionCheck, shellReadCheck, readFace: () => resolvedReadFace, 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, 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, syntheticReadVerdict, consolidationWriteJudge, listBackgroundTasks, centerCompactionCandidate, effectiveReadFaceObserved, effectiveWriteFaceObserved, effectiveReadDenyObserved } = prepareTurnWiring({ deps, systemPromptSeat, harnessTools, fpRef, model, promptIdentityDigest: promptManifest.identity.artifact, promptProfile, fableMitigations, systemBlocks, thinking, spec, sessionId, turnSnapshotRef, promptManifest, charsPerToken, handsEnabled, executionEnv, attachmentRootCanonical, readRoots, readDenyMatcher, resolvedReadFace, handsCwdRef, readFileStateForCheckpoint, denyNarrowingPolicy, skillGrants: skillGrantLane, callerPolicy: installedToolPolicy, inheritedPolicies: (inheritedParentConstraints ?? []).map((c) => c.policy), persistedRuleLane: permissionRuleLane, ruleLaneFacts, personRowsBeyondRun, orgRuleLane: permissionRuleOrgLane, stampCallTarget, abortController, hostTaskId, taskScope, buildAssembleInputs, identityFor, adoptsCandidates, centerAdoptionRef, harnessRef, 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, toolOccurrences, batchHaltRef, nestedStats, ...(rewindNotes.length > 0 ? { rewindNotes } : {}), ...(fileHistoryBoundary !== undefined ? { fileHistoryBoundary } : {}), ...(effectiveReadFaceObserved !== undefined ? { effectiveReadFace: effectiveReadFaceObserved, effectiveWriteFace: effectiveWriteFaceObserved } : {}), ...(effectiveReadDenyObserved !== undefined ? { effectiveReadDenyPatterns: effectiveReadDenyObserved } : {}), effectiveMemoryScopes: memoryEffectiveScopes, cwdRef: handsCwdRef, ...(attachmentRootCanonical !== undefined ? { handsRoot: attachmentRootCanonical } : {}), ...(stampCallTarget !== undefined ? { stampCallTarget } : {}), toolProgressRef, ...(advertisedWritableDirs !== undefined ? { advertisedWritableDirs } : {}), exemptRoots: legExemptRoots, ...(worktreeSessionRef !== undefined ? { worktreeSessionRef } : {}), ...(workspaceStateSettle !== undefined ? { workspaceStateSettle } : {}), ...(sealReadStateSeat !== undefined ? { sealReadStateSeat } : {}), denyNarrowingPolicy, skillGrants: skillGrantLane, skillSpecs, ...(permissionRuleLane !== undefined ? { persistedRuleLane: permissionRuleLane } : {}), ...(basePolicyForResumeEdit !== undefined ? { basePolicyForResumeEdit } : {}), consolidationWriteJudge, ...(permissionRuleOrgLane !== undefined ? { permissionRuleOrg: permissionRuleOrgLane } : {}), releaseSignal, endModeCeiling, settleContentAskBindings, cacheBreakDetector, cacheFingerprint, wiringManifest, promptManifest, promptIdentity, 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 && withheldDiagnosticsOf ? { lspDiagnostics: { registry: lspDiagnostics, nudge: nudgeLspOnEdit, runIdent: lspRunIdent, withheldOf: withheldDiagnosticsOf } } : {}), 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, ...(userAttachmentsSeat !== undefined ? { userAttachments: userAttachmentsSeat } : {}), attachmentDelivery: createAttachmentDelivery(), ...(modelFileReaderSeat.current !== undefined ? { modelFileReader: modelFileReaderSeat.current } : {}), syntheticReadVerdict, ...(peerLaneRefs.boundaryRound !== undefined ? { peerBoundaryRound: peerLaneRefs.boundaryRound } : {}), gitStatusRef, postureFrameRef, listBackgroundTasks, hookIdentity, modBus: legMods.bus, sideCallBookRef, ...(sessionBoxBound !== undefined ? { sessionBox: sessionBoxBound } : {}), ...(turnSnapshotRef.current !== undefined ? { turnSnapshot: turnSnapshotRef.current } : {}), ...(centerCompactionCandidate !== undefined ? { centerCompactionCandidate } : {}), ...(shellReadCheck !== undefined ? { shellReadCheck } : {}), ...(toolDisclosureSeat !== undefined ? { toolDisclosure: toolDisclosureSeat } : {}), ...(approvedCallScreen !== undefined ? { approvedCallScreen } : {}) });
refuseLateRosterChanges(callerRoster.roster);
rollback.commit();
commitModeSeats(abortController.signal);
const prepared = buildPrepared();
preparedHolder.current = prepared;
legMods.bindFacade(legFacadeSeats({ deps, spec, sessionId, model, executionEnv, taskRoot: taskRootFinal, cwdRef: handsCwdRef, lastBrainContext: prepared.lastBrainContext, activeTools, agentListing, book: (answeredBy, reply) => {
const book = prepared.sideCallBookRef.book;
if (book === undefined)
throw new Error("a mod's $.model.complete was answered before the run body bound the leg's usage account, which it does before any tool call");
book("mod", answeredBy, reply);
} }));
return prepared;
}
catch (prepareErr) {
await rollback.unwindAll();
await settleTeardownLeg(() => forgetOnThrow(), "forgetOnThrow (prepare-throw leg)", (e) => deps.onError?.(e, { phase: "config", sessionId }));
throw prepareErr;
}
}