@sema-agent/core
Version:
Stateless, task-oriented AI agent core
329 lines (328 loc) • 27 kB
JavaScript
import { admitUndrainedPeerSeats, bindPeerLaneDrain, peerDrainLanesOf } from "../../agents/peer-session-drain.js";
import { teamRoleOf } from "../../agents/team-role.js";
import { resolveCheckpointStore } from "../checkpoint-store.js";
import { createHookEnvCapabilities, mintHookInvocationIdentity } from "../hooks.js";
import { hookRootSessionIdOf } from "../leg-identity.js";
import { chainJudges } from "../mods/stations.js";
import { MOD_EVENTS_HANDING_ENV } from "../mods/kernel/events.js";
import { suspendTargetGapRowOf } from "../remote-env.js";
import { isVolatileOffloadStore } from "../tool-result-store.js";
import { durableMandateSourceOf, effectiveDurableApprovalOf, isAnsweringSeat } from "../tool-policy.js";
import { notResumableClause, notResumableWayOut } from "../park-resumability.js";
import { deliverEngineNotice } from "../types.js";
import { mountWriteProtection } from "./write-protection-station.js";
import { autoRunOnRecommendationEffective } from "./memory-consolidation-driver.js";
import { GLOBAL_USAGE_KEY, usageRetryAfterMs, windowsGovernCost } from "../usage-window-store.js";
import { rosterEntryNamed, toolCallFaceOf } from "../tool-roster.js";
import { isShellFaceToolName } from "../tool-registry.js";
import { LSP_CONTRACT_ID, mcpManifestEntries, askAnsweredClassesOf, askSeatEffective, approvalParkWithheldOf, countElicitOptIns, deriveHandsSeam, executionEnvSeatOf, interactionSeatsOf, deriveLspSeam, deriveWiringManifest, resolveDeclaredDurability, resolveElicitSeam, resolveQuestionSeam, resolveSubagentTranscriptTier, wiringLegKindOf } from "../wiring-manifest.js";
import { modePolicyOf, modeQuestionReaches } from "../mode-policy.js";
import { deploymentBagOf } from "./model-lane-seat.js";
import { projectMarkerUnreadableOf } from "../memory-engine/scope-contract.js";
function buildUsageGovernance(windows, deps, principal, sessionId) {
if (windows === undefined || windows.length === 0)
return undefined;
const store = deps.usageWindowStore;
if (store === undefined) {
deps.onError?.(new Error("RunnerDeps.usageWindows is set but INACTIVE: no `usageWindowStore` is wired, so cross-task usage cannot be counted and no window can be enforced. Wire InMemoryUsageWindowStore (process-local) or FileUsageWindowStore (restart-surviving)."), { phase: "config", sessionId });
return undefined;
}
const key = principal || GLOBAL_USAGE_KEY;
const governsCost = windowsGovernCost(windows);
let chargedTokens = 0;
let chargedCostMicroUsd = 0;
let announcedCostGap = false;
let recordedUnpricedGap = false;
return {
key,
governsCost,
async check(now) {
const readings = await store.read(key, windows, now);
if (!announcedCostGap && readings.some((r) => r.costUnknown === true)) {
announcedCostGap = true;
deps.onError?.(new Error(`the usage window for ledger key ${JSON.stringify(key)} holds spend that nothing could price, so its maxCostUsd ceiling is being evaluated against a LOWER BOUND until that charge ages out of the window. Price every model this deployment can reach (including degrade targets and the compaction model).`), { phase: "config", sessionId });
}
return usageRetryAfterMs(readings, windows);
},
async commit(cumulativeTokens, cumulativeCost, now) {
if (!governsCost) {
const delta = cumulativeTokens - chargedTokens;
if (delta <= 0)
return;
await store.charge(key, delta, now, windows);
chargedTokens = cumulativeTokens;
return;
}
if (typeof cumulativeCost !== "number") {
const tokenDelta = cumulativeTokens - chargedTokens;
if (tokenDelta > 0 || !recordedUnpricedGap) {
await store.charge(key, Math.max(0, tokenDelta), now, windows, null);
chargedTokens = Math.max(chargedTokens, cumulativeTokens);
recordedUnpricedGap = true;
}
const e = new Error(`a deployment usage window declares maxCostUsd, but this run's spend has NO cost figure: ${cumulativeCost.unpricedBecause}. Refused rather than charged a fabricated 0 — the money ceiling would have silently stopped applying. Fix that, or drop maxCostUsd from the window.`);
e.code = "config.usage_window_unpriced";
throw e;
}
const tokenDelta = cumulativeTokens - chargedTokens;
const costDelta = cumulativeCost - chargedCostMicroUsd;
if (tokenDelta <= 0 && costDelta <= 0)
return;
await store.charge(key, Math.max(0, tokenDelta), now, windows, Math.max(0, costDelta));
chargedTokens = cumulativeTokens;
chargedCostMicroUsd = cumulativeCost;
},
};
}
const ungatedWarnedShapes = new WeakMap();
function liveChainSeatClause(form) {
switch (form) {
case "callback":
return "a live approver answers permission asks in-stream";
case "policy_callback":
return "the deployment's approval policy answers permission asks in-stream (it cannot approve an ask that requires a person)";
case "allow":
return 'a blanket "allow" posture answers ordinary permission asks without judgment (a mandated ask is refused)';
case "deny":
case "absent":
case "declared_none":
return "permission asks are denied fail-closed — nobody in this run can be asked to approve them";
default: {
const _exhaustive = form;
void _exhaustive;
throw new Error(`unreachable ask seat form ${String(form)}`);
}
}
}
function legNotResumableSentence(source) {
return `Durable approval gate mandated but unavailable: the deployment requires durable approvals for this principal, but this leg cannot be resumed — ${notResumableClause(source)} — so no ask of it can be parked for a durable answer, and none is answered in its place: every permission ask is refused without asking anyone and AskUserQuestion is refused (not shown). NO durable approval record is written. To go on: ${notResumableWayOut(source, true)}; or withdraw the entitlement.`;
}
function announceDurableGateUnavailable(args) {
if (args.mandate === undefined || (args.storeWired && !args.notResumable))
return;
const source = args.mandate;
const notResumable = args.notResumable !== false ? args.notResumable : undefined;
const cause = notResumable !== undefined ? "leg_not_resumable" : args.taskStoreDisabled ? "task_store_disabled" : "no_deployment_store";
const inheritedContentMandate = (args.parentConstraints ?? []).some((pc) => pc.contentMandate === true);
const answersLive = notResumable === undefined;
const liveQuestionFace = args.liveQuestionFace && !inheritedContentMandate && answersLive;
deliverEngineNotice(args.onNotice, {
code: "config.durable_gate_unavailable",
message: notResumable !== undefined ? legNotResumableSentence(notResumable) :
`Durable approval gate mandated but unavailable: ${source === "force_durable_gate" ? "the deployment requires durable approvals for this principal" : "this task opted into durable approval with no live approver seat"}, ` +
`but ${cause === "task_store_disabled" ? "this task runs with the checkpoint store switched off (set by the host on the task, or by the engine on a fork child and every leg under it, since nothing resumes a fork)" : "this deployment wired no checkpoint store"}, ` +
`so no interactive ask of this task can be parked for a durable answer. Asks resolve on the live chain instead ` +
`(${liveChainSeatClause(args.seatForm)}; ` +
`${liveQuestionFace ? "a live question face answers AskUserQuestion in-stream" : args.liveQuestionFace ? "AskUserQuestion is withheld from the live face by an inherited durable mandate and refused" : "AskUserQuestion has no live face and is refused"}) ` +
`and NO durable approval record is written. ${cause === "task_store_disabled" ? 'Run the task with its store (a fork child cannot have one: delegate work that must wait for a person without subagent_type "fork")' : "Wire a checkpoint store on this deployment"}, or ${source === "force_durable_gate" ? "withdraw the entitlement for principals served here" : args.declaredNone ? "run the task where a person can be asked, or drop its durable-approval request" : "give the task a live approver seat (or drop its durable-approval request)"}.`,
detail: {
sessionId: args.sessionId,
runId: args.runId,
...(args.principal ? { principal: args.principal } : {}),
cause,
source,
...(notResumable !== undefined ? { notResumableSource: notResumable } : {}),
liveApprover: args.liveApprover && answersLive,
liveQuestionFace,
},
});
}
export function durableSuspendInfraGaps(facts) {
const gaps = [];
if (!facts.storeWired)
gaps.push({ code: "no_checkpoint_store", why: "no CheckpointStore is wired" });
if (facts.laneHoldsNoPark)
gaps.push({ code: "leg_not_resumable", why: notResumableClause("lane") });
if (facts.volatileToolResults)
gaps.push({ code: "volatile_tool_results", why: "tool-result offload uses the in-memory store (a resume needs durable results)" });
if (facts.envGap !== undefined)
gaps.push({ code: facts.envGap.code, why: `the per-task execution env ${facts.envGap.clause}` });
return gaps;
}
export function prepareWiringManifest(input) {
const { spec, deps, internals, resume, sessionId, runId, legStartedAt, hostTaskId, taskScope, modBus, standingModBus, checkpointScope, policyLayers, effectivePolicy, handsEnabled, skippedFactory, taskRootFinal, legWriteGuard, mcp, a2a, irreversibleTools, egressTools, toolEffects, ownedEnv, executionEnv, offloadStore, onceLedger, usageWindows, envLifetimeSuspendAt, runtimeCaps, resolvedInteractionPosture, durableQuestionFace, liveQuestionFace, checkpointStore, sessions, modelGateManifest, autoModeArmReason, permissionMode, fastMode, lockedPreflight, peerLaneRefs, frameSettlement, receiveSeat, sessionBox, sessionAddress, runEnd, harness, pausedRef, askSeat, liveInheritedGate, delegation, approvalParkNotResumable, forcedGateNotResumable, toolRoster, toolPlan, readDenyBuiltinTiersActive, readFloorUnkept, lspManagerWired, shellReadStationArmed, crossBoundaryStationEngaged, lspDiagnosticsLive, fileHistoryFact, projectMemoryFact, sessionRulesChildrenReadLive, memoryPollution, advisorFact, hostFloorPosture, sessionProject, runOrigin, commandSandboxFact, callerPlaces } = input;
const onAsk = askSeat.value;
const handWriteTools = toolRoster.entries.filter((e) => e.mountedBy === "hands" && (e.effect === "write" || e.effect === "idempotent")).map((e) => e.name);
const hasEffectAwareGate = policyLayers.length > 0 || chainJudges(standingModBus);
const rosterHolds = new Set(toolRoster.entries.map((e) => e.name));
const modeAsksUnstated = modePolicyOf(permissionMode.current).unstated === "ask";
const peerWriteUngated = modeAsksUnstated
? []
: mcp.tools.filter((t) => rosterHolds.has(t.name) && t.permissionSeat === "passthrough" && !irreversibleTools.has(t.name) && !egressTools.has(t.name) && (toolEffects.get(t.name) ?? "write") !== "read").map((t) => t.name);
const requestWriteTools = (spec.tools ?? [])
.map((t) => t.name)
.filter((name) => !irreversibleTools.has(name) && !egressTools.has(name))
.filter((name) => toolEffects.get(name) === "write" || (toolCallFaceOf(toolRoster, name)?.names ?? []).some(isShellFaceToolName));
const callerAnsweredByMode = (name) => modeAsksUnstated && rosterEntryNamed(toolRoster, name)?.source === "caller";
const callerWriteUnasked = requestWriteTools.filter((name) => callerAnsweredByMode(name) && !modeQuestionReaches(permissionMode.current, toolRoster, name, (spec.tools ?? []).findLast((t) => t.name === name)?.permissionSeat));
const firstPartyWriteUngated = hasEffectAwareGate ? [] : requestWriteTools.filter((name) => !callerAnsweredByMode(name));
if ((!hasEffectAwareGate && handWriteTools.length > 0) || callerWriteUnasked.length > 0 || firstPartyWriteUngated.length > 0 || peerWriteUngated.length > 0) {
const what = [
!hasEffectAwareGate && handWriteTools.length > 0 ? `hand tools [${handWriteTools.join(", ")}]` : undefined,
peerWriteUngated.length > 0 ? `server write tools under ${permissionMode.current} [${peerWriteUngated.join(", ")}]` : undefined,
firstPartyWriteUngated.length > 0 ? `write tools [${firstPartyWriteUngated.join(", ")}]` : undefined,
callerWriteUnasked.length > 0 ? `write tools under ${permissionMode.current} [${callerWriteUnasked.join(", ")}]` : undefined,
]
.filter(Boolean)
.join(" + ");
const deployment = deploymentBagOf(deps);
if (!ungatedWarnedShapes.get(deployment)?.has(what)) {
let shapes = ungatedWarnedShapes.get(deployment);
if (!shapes) {
shapes = new Set();
ungatedWarnedShapes.set(deployment, shapes);
}
shapes.add(what);
deps.onError?.(new Error((hasEffectAwareGate
? `write-capable ${what} are present and no question of the ${permissionMode.current} mode reaches their calls — a tool policy the deployment wired may still ask about a call; this warning does not see what it decides. `
: `write-capable ${what} are present but UNGATED — wire an effect-aware tool policy (or a PreToolUse hook). bash/MCP irreversible actions are otherwise unadjudicated; the deployment sandbox/egress boundary is the only protection. `) +
(peerWriteUngated.length > 0 ? `Under ${permissionMode.current} a server's tools run with nobody stating them; a deny or ask rule naming them still gates them. ` : "") +
(callerWriteUnasked.length > 0
? `Under ${permissionMode.current} a caller's tool that declares no permission seat answers for itself: the mode's question never reaches its calls (in auto, the classifier rules only on what a rule or a policy asks); declare permissionSeat: "passthrough" on it to put each call to the mode's question. A deny or ask rule naming it still gates it, and a read target it declares (pathTarget access "read") is judged by the read station whatever its seat. `
: "") +
`(This warning fires once per deployment per tool-set shape.)`), { phase: "config", sessionId });
}
}
const preToolContexts = new Map();
const blockedToolCalls = new Set();
const batchHaltRef = {};
const blockedTracked = ["classic.PostToolUse", "classic.PreToolUse", "classic.PostToolUseFailure", "classic.PostToolBatch"].some((ev) => modBus.hasHandlers(ev));
const suspendTargetGapRow = suspendTargetGapRowOf(ownedEnv);
const suspendTargetGap = suspendTargetGapRow?.clause;
const suspendInfraGaps = durableSuspendInfraGaps({
storeWired: resolveCheckpointStore(spec, deps) !== undefined,
laneHoldsNoPark: approvalParkNotResumable === "lane",
volatileToolResults: offloadStore !== undefined && isVolatileOffloadStore(offloadStore),
envGap: suspendTargetGapRow,
});
const durableSuspendInfraReady = suspendInfraGaps.length === 0;
const suspendLaneGap = durableSuspendInfraReady ? undefined : suspendInfraGaps.map((g) => g.why).join("; ");
const resourceSuspendEligible = spec.resourceSuspend !== undefined && durableSuspendInfraReady;
if (spec.resourceSuspend !== undefined && !resourceSuspendEligible) {
onceLedger.onError(new Error(`resourceSuspend is set but INACTIVE: ${suspendLaneGap}; resource limits will hard-fail, not suspend`), {
phase: "config",
sessionId,
});
}
const usageGovernance = buildUsageGovernance(usageWindows, deps, spec.principal, sessionId);
const platformSuspendArmed = durableSuspendInfraReady && (spec.preemptSignal !== undefined || envLifetimeSuspendAt !== undefined || usageGovernance !== undefined);
const durableApproval = effectiveDurableApprovalOf({ declared: spec.durableApproval, forceDurableGate: runtimeCaps?.forceDurableGate === true, approvalParkNotResumable, scope: checkpointScope });
const writeProtection = mountWriteProtection({ deps, configRoots: callerPlaces.configRoots.dirs, guard: legWriteGuard, spec, env: handsEnabled ? executionEnv : undefined, rootPath: taskRootFinal, roster: toolRoster, sessionId, runId });
const wiringQuestionSeam = resolveQuestionSeam(spec, deps);
const wiringQuestionStripped = internals?.questionFaceStripped === true;
const wiringFacts = {
half: "effective",
leg: wiringLegKindOf(resume !== undefined, internals), legInstance: { runId, startedAt: legStartedAt }, ...(runOrigin !== undefined ? { runOrigin } : {}), ...(deps.host !== undefined ? { host: deps.host } : {}),
teamRole: teamRoleOf({ isDelegatedChild: delegation.isDelegatedChild, ...(internals?.explicitAgentName !== undefined ? { spawnName: internals.explicitAgentName } : {}) }),
...(spec.peerPresence !== undefined ? { peerPresence: spec.peerPresence } : {}),
askForm: askSeat.form,
...(askSeat.provenance !== undefined ? { askProvenance: askSeat.provenance } : {}),
...((answered) => (answered !== undefined ? { askAnsweredClasses: answered } : {}))(askAnsweredClassesOf(askSeat)),
questionWired: wiringQuestionSeam.wired,
...(wiringQuestionSeam.provenance !== undefined ? { questionProvenance: wiringQuestionSeam.provenance } : {}),
...(wiringQuestionStripped ? { questionStrippedByEngine: true } : {}),
...(resolvedInteractionPosture !== undefined ? { interactionPosture: resolvedInteractionPosture } : {}),
...(spec.interactiveTools === true && !wiringQuestionSeam.wired && !durableQuestionFace && !wiringQuestionStripped
? { interactiveToolsWithoutDeliveryFace: true }
: {}),
elicitSeamWired: resolveElicitSeam(deps),
elicitServersOptedIn: countElicitOptIns(spec),
parkCapable: checkpointStore !== undefined,
parkLegNotResumable: approvalParkNotResumable !== undefined,
parkDurableApprovalOptIn: spec.durableApproval !== undefined,
parkForceDurableGate: runtimeCaps?.forceDurableGate === true && durableApproval !== undefined,
forcedGateNotResumable: forcedGateNotResumable !== undefined && forcedGateNotResumable !== false,
parkSafetyVocabularyArmed: irreversibleTools.size > 0 || egressTools.size > 0 || shellReadStationArmed, ...(approvalParkWithheldOf({ member: internals?.workflowMember !== undefined, form: askSeat.form }) ? { approvalParkWithheld: true } : {}),
...(checkpointStore !== undefined ? { checkpointDurability: resolveDeclaredDurability(checkpointStore, "checkpointStore") } : {}),
sessionDurability: resolveDeclaredDurability(sessions, "sessionStore"), checkpointStoreWired: deps.checkpointStore !== undefined, interactionSeats: interactionSeatsOf(deps),
suspendLaneReasons: suspendInfraGaps.map((g) => g.code),
backgroundAgentStoreWired: deps.backgroundAgentStore !== undefined,
subagentTranscriptTier: resolveSubagentTranscriptTier(deps.backgroundAgentStore !== undefined, sessions),
permissionRuleStoreWired: deps.permissionRuleStore?.partitions.durable === true,
permissionRuleSyncWired: deps.permissionRuleSyncWired === true,
permissionRuleOrgGoverned: deps.permissionRuleStore?.partitions.org === true,
hostChildEventSinkWired: deps.onBackgroundChildEvent !== undefined,
lockedConfigWired: deps.lockedConfig !== undefined,
complianceWired: deps.compliancePostureResolver !== undefined,
memoryAdmissionWired: deps.memoryScopeAdmission !== undefined,
retentionPolicyWired: deps.retentionPolicy !== undefined,
...(modelGateManifest !== undefined ? { modelGate: modelGateManifest } : {}),
autoMode: { ...autoModeArmReason() },
permissionMode: permissionMode.receipt(),
...(fastMode?.engaged === true ? { fastMode: fastMode.readingOf() } : {}),
mcp: mcpManifestEntries(lockedPreflight.mcp, mcp.statuses, toolRoster.entries.map((e) => e.name)),
a2a: a2a.statuses.map((s) => ({ name: s.name, status: s.status, ...(s.boundary !== undefined ? { boundary: s.boundary } : {}), ...(s.fingerprint !== undefined ? { fingerprint: s.fingerprint } : {}), ...(s.errorCode !== undefined ? { errorCode: s.errorCode } : {}), ...(s.code !== undefined ? { code: s.code } : {}) })),
...(writeProtection.mount !== undefined ? { writeProtectionTargetView: writeProtection.mount.targetView } : {}),
readDenyBuiltinTiersActive, readDenyFloorUnkept: readFloorUnkept !== false,
declaredPlaces: { agentConfigDirs: callerPlaces.configRoots.sources, agentHomeDirs: callerPlaces.homes.sources },
autoConsolidationOnRecommendation: autoRunOnRecommendationEffective(deps),
tools: toolRoster,
toolPlan,
mods: modBus.records,
...(lspManagerWired ? { lsp: deriveLspSeam(toolRoster.entries.some((e) => e.contract.contractId === LSP_CONTRACT_ID), lspDiagnosticsLive) } : {}),
hands: deriveHandsSeam(handsEnabled, skippedFactory), executionEnvSeat: executionEnvSeatOf(deps),
fileHistory: fileHistoryFact, commandSandbox: commandSandboxFact, projectMemory: projectMemoryFact, sessionRulesChildrenReadLive, ...(advisorFact !== undefined ? { advisor: advisorFact } : {}), ...(hostFloorPosture !== undefined ? { hostFloor: hostFloorPosture } : {}), ...(sessionProject?.project !== undefined ? { project: sessionProject.project } : {}), ...((u) => (u !== undefined ? { projectMarkerUnreadable: u } : {}))(projectMarkerUnreadableOf(sessionProject?.markerFault)),
};
const wiringManifest = deriveWiringManifest(wiringFacts);
const askSeatWord = askSeatEffective(wiringFacts);
peerLaneRefs.askEffective = askSeatWord;
peerLaneRefs.permissionMode = () => permissionMode.current;
const drainLanes = internals?.onTaskNotification !== undefined ? peerDrainLanesOf(deps, { sessionBox, assistantSeat: internals.principalInboxAssistant, address: sessionAddress }) : undefined;
const sessionBoxBound = drainLanes?.sessionBox;
if (internals?.onTaskNotification !== undefined && sessionBox !== undefined && sessionBoxBound === undefined)
admitUndrainedPeerSeats(taskScope, sessionAddress);
if (drainLanes !== undefined && internals?.onTaskNotification !== undefined) {
bindPeerLaneDrain(harness, {
deps, lanes: drainLanes, assistantSeat: internals.principalInboxAssistant,
address: sessionAddress,
sessions,
runId, ...(runEnd !== undefined ? { runEnd } : {}),
scope: taskScope,
inject: internals.onTaskNotification,
ownTokens: () => internals?.peerSelfRef?.current.ownTokens ?? [],
refs: peerLaneRefs,
settlement: frameSettlement,
receive: receiveSeat,
selfName: () => internals?.explicitAgentName,
parked: () => pausedRef.current !== undefined,
markExternalContent: async (reason) => {
const face = memoryPollution?.();
if (face === undefined)
return;
if ((await face.markPolluted(reason, "observed")) === "unpersisted") {
const e = new Error("a letter from another principal was not injected: this session's exposure to it could not be recorded durably (the memory control plane refused the pollution marker) — it stays in the box and is delivered once the record can be made");
e.code = "memory.pollution_mark_failed";
throw e;
}
},
});
frameSettlement.boxBacked = (payload) => peerLaneRefs.isBoxBacked?.(payload) ?? false;
}
const parkLaneArmed = wiringManifest.parkLane.effective === true;
const gateMachineryActive = effectivePolicy !== undefined ||
modBus.hasHandlers("classic.PreToolUse") ||
egressTools.size > 0 ||
irreversibleTools.size > 0 ||
shellReadStationArmed || crossBoundaryStationEngaged ||
resourceSuspendEligible ||
platformSuspendArmed ||
spec.enablePlanMode === true ||
commandSandboxFact.state === "armed";
announceDurableGateUnavailable({ onNotice: deps.onNotice, mandate: durableMandateSourceOf({ forceDurableGate: runtimeCaps?.forceDurableGate === true, durableApprovalDeclared: spec.durableApproval !== undefined, onAsk }), storeWired: checkpointStore !== undefined, taskStoreDisabled: spec.checkpointStore === "disabled", notResumable: forcedGateNotResumable, liveApprover: isAnsweringSeat(onAsk), seatForm: askSeat.form, declaredNone: askSeat.reach === "none", liveQuestionFace: liveQuestionFace !== undefined, parentConstraints: liveInheritedGate?.parentConstraints, sessionId, runId, principal: spec.principal });
const rootSessionId = hookRootSessionIdOf(internals, sessionId, delegation.isDelegatedChild);
const hookIdentity = mintHookInvocationIdentity({
sessionId,
...(rootSessionId !== undefined ? { rootSessionId } : {}),
taskId: hostTaskId,
legKind: wiringManifest.leg.kind,
isDelegatedChild: delegation.isDelegatedChild,
...(internals?.insideFork === true ? { insideFork: true } : {}),
...(internals?.agentName !== undefined ? { agentName: internals.agentName } : {}),
...(internals?.explicitAgentName !== undefined ? { spawnName: internals.explicitAgentName } : {}),
...(internals?.spawnAgentType !== undefined ? { agentType: internals.spawnAgentType } : {}),
...(internals?.parentToolCallId !== undefined ? { parentToolCallId: internals.parentToolCallId } : {}),
});
const hookContextConsumerWired = MOD_EVENTS_HANDING_ENV.some((ev) => modBus.hasHandlers(ev));
const hookEnvFace = hookContextConsumerWired && (ownedEnv ?? deps.executionEnv) != null ? createHookEnvCapabilities(executionEnv) : undefined;
return { onAsk, preToolContexts, blockedToolCalls, batchHaltRef, blockedTracked, suspendTargetGap, durableSuspendInfraReady, suspendLaneGap, resourceSuspendEligible, usageGovernance, platformSuspendArmed, durableApproval, wiringManifest, askSeatWord, writeProtection, parkLaneArmed, gateMachineryActive, hookIdentity, hookEnvFace, sessionBoxBound };
}