Navigation
ELOWEN · Documentation

Last updated: October 27, 2026

Browse documentation · Browser and plugin ownership
Developer reference

Browser and plugin ownership

Owning code:

  • src/plugins/loader.ts, src/plugins/registry.ts and src/plugins/pluginsProvider.ts: the plugin loader and the current registry. PluginRegistry.contextFor delegates accessor assembly to src/plugins/pluginContext.ts; src/plugins/pluginContextTypes.ts owns PluginContextOptions and host wiring declarations.
  • src/plugins/capabilities.ts:15: the public PluginCapabilities type, inferred from the manifest schema.
  • src/plugins/contributionReport.ts:47: buildContributionReport.
  • src/plugins/manifest.ts:48: PLUGIN_API_VERSION, currently '2'.
  • src/brain/toolOutput.ts:26: makeToolOutputPolicy. src/brain/messageView.ts:379: toolOutputView.
  • packages/plugin-shared/duration.mjs:2 and web/lib/format.ts:24: the duration formatter and its web mirror, pinned by tests/contract/webMirrorContracts.test.ts.
  • packages/plugin-shared/projectChoice.mjs:14, packages/plugin-shared/projectExecution.mjs, packages/plugin-shared/subagentName.mjs (five words and 40 characters, lines 5-8) and packages/plugin-shared/toolLists.mjs.
  • packages/plugin-shared/index.mjs:20: PLUGIN_SHARED_API_VERSION, currently 15.
  • packages/plugin-ui-kit/index.d.ts: the plugin UI kit types and PLUGIN_UI_API_VERSION (line 28, currently 73), mirrored by web/lib/pluginUi.tsx. useNow is at line 1558.
  • web/lib/pluginUi.tsx: the host plugin UI runtime a bundle receives — PLUGIN_UI_API_VERSION (line 147), the components and utils helpers that ensurePluginUiRuntime installs once on window.ElowenUiRuntime.
  • web/app/layout.tsx:152: the fixed dark data-theme.
  • web/lib/queries.ts:384 (useSystemUpdateStatus) and web/lib/operationDockUpdates.ts:27 (updateDockOperations).
  • web/modules/advisor/ConversationListPanel.tsx:146: the conversation register's filter options, where project, model, type and status entries carry their icons; the status dot is ConversationStateDot, exported by web/components/ui/ConversationIcon.tsx:54. The English strings come from web/lib/i18n/dictionaries/en.ts.

Browser application and packages

  • web/app/ contains Next.js routes and page composition.
  • web/components/ contains the shell, navigation, command palette, UI primitives, and shared browser components.
  • web/modules/ contains feature surfaces such as advisor chat, dashboard, settings, Projects, and account pages.
  • web/lib/ contains browser-side API clients, data contracts, event handling, search, presentation helpers, and mirrors of selected shared contracts. The root layout owns the app's fixed dark data-theme; terminal auto mode separately uses the dark terminal palette, while custom terminal palettes are per-account settings.
  • web/tests/ and the web package scripts provide browser unit and end-to-end coverage.
  • plugins/*/web-src/ is the source location for plugin browser bundles when a plugin contributes browser UI.
  • packages/plugin-shared/ contains shared plugin contracts and utilities. The core tarball includes it as a local file: dependency, which npm installs into the core's node_modules without a registry lookup. Installed plugins link to that host node_modules and resolve the same shared contract; when a plugin does not import it, nothing is loaded. Do not bundle the core's node_modules: npm can prune unrelated transitive dependencies during a global install. For example, the Telegram plugin imports elowen-plugin-shared/format through the host link. The plugin registry's Discord, WhatsApp, Telegram, MS Teams and Cronjob plugins import it the same way, for example plugins/telegram/lib/format.mjs:6. The core package declares the file:packages/plugin-shared dependency in package.json:146. The pure elowen-plugin-shared/duration entry formats milliseconds as floored 8s, 12m 14s, or 1h 2m; the CLI and platform cards import this one implementation, and plugin bundles reach it through the web runtime utility utils.formatDuration (published by web/lib/pluginUi.tsx). The web app keeps a byte-identical mirror in web/lib/format.ts, because Turbopack resolves modules only inside the web root; tests/contract/webMirrorContracts.test.ts pins the two. A caller that does not display a duration imports nothing; compact single-unit relative timestamps remain a separate format. Likewise elowen-plugin-shared/projectChoice (resolveProjectArgument) is the one reading of a typed /project <slug|id> argument, imported by the adapters' shared picker core and by the CLI. The verified importers are packages/plugin-shared/chatCommands.mjs:36 and src/cli/chat/picker.ts:10.
  • packages/plugin-shared/projectExecution.mjs owns reserved guest roots, slug normalization, managed guest mount paths and the artifact root. Core retains the typed Project reference parser/facade; Sandbox imports the same runtime owner for mount validation and environment paths. Historical empty/reserved slugs keep their stable Project-id path, and container hash preimages stay unchanged. These pure helpers grant no authority and perform no I/O. The subagentName.mjs owner preserves the five-word/40-character delegated-child labels for the coordinated store/migration/Subagent cohort without rewriting names. Shared ask, display and modelIdentity own transport-neutral adapter parsing, vocabulary and catalog decisions; imageRuntime calls the existing image and authorized Project file seams once per render. Package imports register nothing; detailed use, absent behavior, bounds and costs live in the shared README and PLUGIN_DEV shared runtime helpers.
  • packages/plugin-shared/destinations.mjs owns the routed-notification envelope shared by core, Discord, Teams and Meeting Confirm. Core routes with decodeNotificationDestination(value, knownPlatforms); an adapter reads its own configuration with readNotificationDestination(value, platform), and Meeting Confirm mints its Teams notice target with encodeNotificationDestination('msteams', ownerEmail). Native provider ids and provider-specific generation handling stay with their adapters. The functions are pure: no I/O, no registration and no work without a call, and malformed or foreign routed values fail closed instead of falling back to broadcast. Consumers set requiresCore to the first core release shipping this subpath; the helper adds no version bump of its own and the coordinated release moves shared API to 15.
  • packages/plugin-ui-kit/ contains the reusable plugin UI kit used by the web application and plugin bundles. Its hooks.useNow signature publishes the existing host clock directly; enabled host and plugin consumers share one visible-tab heartbeat, documented in Shared clock.

The existing language producer check parses EnvironmentAction discriminants and Sandbox STEP_PLANS tuples with the TypeScript parser. Comments and unrelated string properties cannot keep an orphan translation alive; unresolved variants or dynamic plan entries fail as incomplete coverage. Action labels are checked both ways, while historical step labels remain supported. This is bounded producer coverage, not general translation liveness.

Shared helper subpaths are shipped inside the core artifact together with their adjacent .d.mts declarations. Import each helper from its explicit elowen-plugin-shared subpath; the package root does not re-export helper bodies. NodeNext resolves the adjacent declaration for the .mjs export. Each declaration has an exact analysis entry. The current package declares shared API 16, and consumers must require the first verified core release containing the helper and its export metadata. An older number alone does not establish availability. Unused helpers perform no work; a missing target or unsupported subpath fails module loading. Validate the packed artifact as well as the source tree.

/xml exposes sanitizeXmlText, xmlEscapeText and xmlEscape. Import xmlEscape from elowen-plugin-shared/xml for attribute values, or xmlEscapeText for text nodes. The canonical rules replace XML 1.0-forbidden C0 controls, escape ampersands and angle brackets, and additionally escape both quotes for attributes. The helper converts values with String before escaping. Core src/shared/xml.ts delegates to this module; Subagent delegation and the migrated Todo and Chatbot contexts are real consumers. No invocation means no transformation. These pure string operations scale with input size and do not parse or validate complete XML documents.

/configTokenList exports parseConfigTokenList(value) for messaging configuration. Arrays are already tokenized: stringify and trim elements, then remove empty entries while preserving embedded commas and newlines. String values split on commas and newlines. Missing values produce an empty list; order and duplicates remain intact. Discord threadIds, Telegram allowedChatIds and WhatsApp groupIds use it when reading adapter configuration. For example, parseConfigTokenList(['123', '456,789']) preserves two tokens. Work scales with input size. It does not validate configuration writes.

/operationInitiator exports operationInitiatorFromCredentialScope(scope). Call it with the host-verified req.auth.credentialScope at authenticated HTTP operation creation. full and impersonation map to ui, agent maps to agent, and api, advisor or an absent origin map to system. Sandbox environment operations, core Project routes and Cronjob manual runs share this classifier. It performs constant-time classification without authorization or persistence. Request bodies and account roles do not determine origin; non-HTTP callers retain their existing defaults.

/withTimeout exports withTimeout(work, ms, failure), where work is a Promise or a callback returning one and failure is a string or Error. For example, await withTimeout(() => cdp.send('Tracing.end'), 1000, new BrowserDeadlineError('Trace end timed out')). Callback work starts once after the timer is armed. Work results and failures, including synchronous throws, preserve identity. Expiry creates an Error from a string or rejects with the supplied Error unchanged. The timer is unref'd and cleared on settlement. This helper never cancels work: callers own late effects and cancellation. Each call uses one timer with Node event-loop timing; without a call it schedules nothing. Browser tracing after migration and core platform startup through src/shared/withTimeout.ts are real consumers. Resolve-on-expiry waits keep their own semantics.

Files uses shared imageSniff for bounded signature classification and keeps its own full-byte eligibility in plugins/files/lib/imageFormats.mjs: a PNG needs a valid IHDR and no acTL chunk, JPEG-LS is refused, and BMP headers are validated. Ordinary image Read and rendered PDF pages call prepareInlineImage(raw, mime, policy) from elowen-plugin-shared/inlineImage during result construction. Both keep a 3,750,000-byte raw fallback cap. Read does not fall back after unsupported resized MIME; PDF does. Omitted images do not grant mutation authorization. MCP result mapping calls the same helper with maxRawBytes: MAX_MCP_INLINE_IMAGE_BYTES (10 MiB, and a larger payload is refused before the call) and fallbackOnUnsupportedResize: true, resending the original rawData. Successful resizing remains bounded to 2000 pixels per edge. Notebook outputs iterate the shared PNG, JPEG, GIF, WebP set with local byte validation and limits.

Files seedReadStateFromHistory(sessionId, messages) restores authorization atomically from successful visible Read results carrying content hashes and returns no count. Without a session it does nothing; invalid or failed results grant nothing. Host and managed-project keys stay separate, and replay replaces prior session state. The Files brain.session.afterSpawn hook is its production consumer. Session and file bounds remain 64 and 512.

MCP serverPresentation owns reconnect classification and summarizeReconnectResults(settledResults). CLI and browser reconnect-all share connected, project-verified, sign-in-required and failed counts. Rejected requests count as failed; denied authorization retains explicit auth labels. Empty input yields zero counts. This helper performs no requests and changes no scheduling: CLI remains concurrent, browser sequential. reconnectFailure uses the same classifier.

plugins/mcp/serverPresentation.mjs keeps its internal status-label dictionary typed as Record<string, string | undefined>: missing dictionary keys and unknown server statuses remain absent rather than fabricating a label. CLI/browser presentation consumers retain their existing rendering policy; this lookup performs no IO or reconnect.

The Subagent plugin owns AGENT_NAME_RE in lib/agentTypes.mjs. Agent-file parsing and lib/agentCatalog.mjs save/delete validation share it: one to 64 lowercase alphanumeric characters with single interior dashes, no trailing or repeated dash. Invalid definitions are not loaded and invalid writes are rejected. Core plugin names deliberately use a different grammar requiring two characters and permitting repeated or trailing dashes. Sharing this constant adds no filesystem operation.

loadAgentTypes in plugins/subagent/lib/agentTypes.mjs requires PluginContext['normalizeBrainModelSpec'] and accepts optional PluginLogger, bundled directory override and user directory. The plugin's catalog initialization supplies the host normalizer; the bundled default remains in effect when its override is absent, and an absent user directory contributes no definitions. The type annotation does not change reads, invalid-file handling or user-over-builtin precedence, and does not introduce a replacement normalizer.

The terminal cleanup deadline remains private. Existing cleanup helpers use it by default and remain internal regression-test entry points; the deadline is not an exported consumer option. Cleanup still reports an overdue wait once and waits for confirmed process exit.

Conversation membership

ConversationLifecycle.memberUserSession(userId, sessionId) authorizes an ordinary owner or current participant through transcript.sessionAccess; channel and delegated child writes are excluded. ownedUserSession remains the owner-control boundary: participants receive ForbiddenSessionError, while strangers receive UnknownSessionError. The BrainService facade exposes the member predicate for queue and participant operations. These checks are request-time repository reads, not a new membership cache. Current participation also authorizes the conversation's Project for shared turns through the shared-turn writer authorization in turnRunner.ts (authorizeWriter), without granting Project membership or access outside this conversation. Implicit active pointers receive the same authorization as explicit ids, including branch/context/goal reads. SessionTeardownService.stopSession also authorizes its resolved active target with ownedUserSession before any pre-lock interrupt, elicitation cancellation or disposal: POST /brain/session/stop {} cannot tear down an owner's runtime merely because a guest selected it earlier. A current guest receives 403 and a removed guest 404. Owner implicit, explicit and generation-bound stops retain their release/idempotence behavior; an implicit first-use target with no stored conversation remains a no-op. No second membership authority is introduced. Goal-loop addressing keeps its owner-only boundary even after a guest selects a shared conversation; first-use empty-state reads retain their existing behavior. A queued writer already accepted before removal uses ParticipantRemovedError (an UnknownSessionError subtype with code participant_removed) at its native admission or recovery recheck; arbitrary strangers do not receive that historical-membership signal. A participant's explicit CLI resume may include the client's ordinary launch cwd; ConversationLifecycle.start ignores it and restores the owner's stored runtime and directory, cold or live. Explicit provider, model and execution-target changes remain owner-only. The CLI's existing /brain/start request uses this same boundary without changing its client identity or generation contract.

HTTP uploads without a running BrainService reuse the same memberSession predicate. The existing UploadProject.conversation snapshot binds a conversation upload to its id, owner, creation time, spill namespace and typed execution target; explicit Project/directory uploads have no conversation binding. brainUploads.ts rechecks current membership and that snapshot in the existing UploadSessions authorizer at begin, each part and commit, alongside the original Project grant, destination and local cwd checks. Removal or replacement yields 404 and disposes staging; changed targets yield 409. Managed and local providers always receive the uploading account, not the conversation owner. This adds bounded repository reads per request, no second upload/membership registry, and no background work.

readableSession in service/lifecycle.ts, exposed as BrainService.sessionForRead, is the shared history/attachment read boundary. Owners and current participants can read their conversation. Child history inherits access from its actual parent chain, without permitting writes; a retained child remains readable by its owner. Administrator oversight is an explicit read-only option, never membership. An absent membership conceals the session with 404. Reads cost one session/access lookup per visited ancestor; ordinary roots do not traverse ancestry. sessionForRead and readableSession accept typed columns for callers such as status that need only identity and authorization. The same ancestry check reads only parent links beyond those columns; it never materializes unrelated large session payloads. Status membership projection likewise selects only its identity/child fields inside the existing read-only repeatable-read snapshot.

Before the first conversation exists, implicit abort and compact retain the ConversationNotRunningError result; explicit unknown targets still remain concealed. answerView keeps its boolean match contract: unknown or foreign answers return false without consuming a wait, current members may answer, and repository failures propagate.

The daemon's existing onConversationActivityChanged callback calls conversationActivityEvents(bound.transcript, sessionId, removedUserId?, membershipChanged?) in one read-only repeatable-read transaction, then publishes the resulting content-free events after the transaction closes. A committed member removal adds that recipient's removed:true, unread:false invalidation at the same activity sequence; control deduplication never suppresses membership invalidation. The owner uses the existing web-participation baseline; each current guest uses their own cursor. Ordinary missing-session activity produces no event. Owner deletion captures current guests under the existing session lock before deleting the row and emits their removed invalidations only after deleteSessionWithArtifacts succeeds. A removed recipient whose session is gone receives a terminal tombstone (idle, sequence zero, empty detail, no unread), not reconstructed activity. Failed or abandoned deletion emits no tombstone. The live-session projection costs three repository reads per activity invalidation and adds no durable notification or listener registry.

BrainService.participants is the process-owned readonly ConversationParticipants instance consumed by participant HTTP routes. It uses the same lifecycle, registry locks, alerts and targeted detach owner, and sends committed membership changes through the existing activity callback. Its lifecycle dependency is resolved after BrainService initialization; routes create no second operation service. The daemon plugin conversation writer uses that same instance for setParticipants({ accountUserId, key, userIds, revision }), deriving the conversation from the host-bound plugin, account and key and refusing an absent row with not_found. Plugin-keyed roots are shareable; the owner is excluded, targets must be human, and the complete target list is validated before changes. Manual invitations and silent plugin synchronization share one add mutation; only invitations raise conversation.invited. Synchronization uses ordinary removals, targeted detaches, live invalidation and membership activity notifications. Kanban owns its board notice, not a second membership authority. A complete desired snapshot and monotonic revision are durable metadata, not immediate access while another turn runs. PostgreSQL native ownership defers application until the whole settlement finishes; no setter waits for another conversation's turn. Stale revisions cannot restore removed members. The runner's conversation.participantEffects RPC carries only a session ID; the daemon re-reads committed desired state, checks the active caller and publishes existing detach/invalidation/activity effects before acknowledgement. A failed publication remains pending for finalizer/setter/boot recovery. Admission compares applied revisions to retire stale cached prompt composition across processes. The writer's prepare persists the keyed root before the plugin binds its card and synchronizes members; conversations.turn.settled observes all writers only for the owning plugin, without granting access. Committed invite/remove/leave calls mark the existing activity callback with membershipChanged:true. Only the owner's projected conversation event carries the marker, once per mutation; recipient copies and ordinary activity do not. The existing /brain/stream EventBus subscription translates a matching snapshot stream's marker into a transient resync with reason membership-changed, never replayed into a snapshot. The subscription precedes snapshot capture, so the existing pending-frame buffer retains a membership mutation committed while an oversight snapshot is still opening. It closes a removed recipient before queued delivery and rechecks current read authority (including the administrator's current role) and browser security before writing. The existing read-only reconnect controller then reads the current snapshot; oversight still creates no runtime, attachment, client binding or additional reader. This adds one role/access recheck per matching membership invalidation, no polling or observer registry. Without an activity callback no bus bridge is installed by the brain itself.

For a user-initiated shared turn, the existing BrainService completion notifier reads current owner/participants, excludes the actual writer and calls the unchanged notifyTurnComplete(recipientId, title, preview) daemon transport only for recipients without a visible stream on that conversation. ClientAttachments.watchingCount(id, userId) derives this from its existing authenticated listener binding, including anonymous transports; another account's visible tab cannot suppress a recipient. The count without a user remains conversation-wide. Unshared sender-device suppression and owner recovery notifications retain their existing behavior. This adds bounded membership/history reads and one visibility scan per recipient, no persistent recipient registry or profile cache, and does nothing without a notifier.

BrainStatusService augments viewer-independent model identity with request-scoped BrainSessionSnapshot membership and capabilities, using the existing conversationProfiles projection for current safe account fields. Personal and managed listings consume the repository's aggregate owner/participant profiles without participant queries per row. Participant unread and acknowledgement use that participant's monotonic cursor, never the owner's web baseline. Status queue reads await queuedWithPending(live, store, viewerUserId) and expose per-item removal authority; live queue broadcasts use the viewer-independent overload instead.

Chat action routes preserve canonical typed authorization responses: known members denied owner-only actions receive 403, while unknown and removed users receive 404. Answer and view-answer share this mapping. Queue list, remove and recall authorize both explicit ids and implicit active pointers with memberUserSession. Members see all pending items, may delete only their own unless owner, and recall only their own last visible item; a foreign delete returns 403/not_queue_owner.

Owner-triggered interruptQueued preserves each native echo's original request account, client, origin, surface, token identity/clock, explicit human writer and mention ids. The echo omits an active token reservation, so the promoted turn opens fresh accounting through the existing runner; it never inherits the interrupt caller's token or origin. Native platform/automation echoes without request provenance retain owner execution authority without inventing a human writer. These transient host-only fields are neither persisted nor broadcast.

For example, GET /brain/messages/:id?session=... authorizes the session, validates a settled user/assistant target on its active journal branch, then uses the same async shapeBrainMessagesWithProfiles projection as history and stream snapshots, including conversation appends. Each distinct persisted Elowen author is resolved once per projection from current safe account fields, including former participants; raw pre-sharing rows stay unauthored. No profile cache is retained. Synchronous visible-slot counting keeps the pure projection and never performs account reads. Tool results and missing targets yield unknown_message; this lookup currently reads the active history to preserve native Address context. Paged history retains the preceding native call/result context through its real turn boundary but never returns context-only views or counts them in its cursor. Successful tool settlement, not call arguments, supplies Address metadata. Reaction metadata is folded from settled events on the current active branch, including changes newer than an older page cursor. Version 1 has no reaction index: this reads the branch once per shaped page, retains only reactions targeting fetched messages and removes duplicate context entries before the canonical projection. Context-only rows never affect the cursor or returned item count. Human reactions use the existing conversation lock (send, then session), recheck membership after waiting, flush native persistence, and call the canonical updateReaction recorder; no second reaction store or cache is introduced.

The conversation SSE coalescer preserves the viewer's unread projection when an administrator also receives another recipient's event. A removed event is private to its recipient, not an oversight broadcast. Transcript SSE attaches one existing bus listener and closes only that viewer/session stream on removal; its normal unsubscribe path releases both listeners. Other users' and other conversations' streams remain attached.

After a committed removal, participant routes call BrainService.detachConversationMember(userId, sessionId). It uses ClientAttachments.detachUserSession for the exact root, then checks durable ancestry of attached children. The existing listener bookkeeping now retains authenticated viewer identity for anonymous as well as stable transports; no second registry is introduced. Removal clears only that viewer's taps and claims, preserving generation tombstones against late reconnects. Remote child taps use the same read authority in the daemon and runner; disposing the daemon's control tap also disposes the remote tap, including an IPC attachment that completes after removal. Work is proportional to currently attached sessions and their ancestor chains, never stored history size.

The export worker invokes the same read predicate inside its existing read-only repeatable-read transaction. It still verifies owner, creation timestamp and spill namespace against the captured request identity, and rechecks administrator status before granting oversight. Member removal before the worker snapshot refuses the export; a snapshot already authorized remains internally consistent.

Plugins

The repository's plugins/ directory contains bundled plugins and their manifests. A plugin directory can include an entry module, manifest, plugin-owned library code, database migrations, browser source, and assets. The runtime also discovers enabled installed plugins from its configured plugin directories. The manifest declares the plugin's contributions and dependencies.

The core loads plugins through src/plugins/loader.ts and exposes the current registry through src/plugins/registry.ts and src/plugins/pluginsProvider.ts. Plugin controls are typed and resolved at call time, so a consumer does not retain a control from the generation that published it. Subagent owns its built-in definitions, editor, and one immutable per-generation type catalog; core grants only its fixed user-definition directory and validates model/tool names through generic host seams. The host still enforces the read-only tool policy. Cronjob owns browser job requests and schedule validation through its server preview; the browser runtime offers only generic query infrastructure and the conversation-link invalidation hook. The plugin UI API carries no cron-specific runtime hooks or parser. The API numbers in this paragraph follow the plugin UI kit series annotated in packages/plugin-ui-kit/index.d.ts, whose PLUGIN_UI_API_VERSION is 66; API 26 is the conversation-link invalidation hook. The series and its history are documented in Browser contract history. They are separate from the manifest contract version PLUGIN_API_VERSION (src/plugins/manifest.ts:48), currently '2'.

Internally, PluginRegistry.contextFor(name, options: PluginContextOptions) constructs a staged context with named loader wiring, for example contextFor('files', { config: {}, logger, capabilities }). Configuration and logger are required; optional callbacks preserve the existing absent-host refusal or empty projection for their respective public accessor. The loader's tool-name, command and sibling-control callbacks read the merged registry at call time, so staging order and live configuration remain authoritative. The public PluginCapabilities type comes from src/plugins/capabilities.ts, inferred from the same schema the manifest validates, rather than repeating its vocabulary. Context-local capability checks preserve synchronous throws, rejected promises, warning text and reporting metadata. Construction adds no I/O beyond the existing context preparation.

buildContributionReport(registry, owner?) is the single runtime contribution projection. Without an owner it reports the full registry; with one it selects raw ownership before projection, preserves registration order and duplicate hook names, and returns empty lists for a plugin with no contributions. The plugin detail API uses this same projection. Its work is linear in the registered contributions and performs no I/O. Manifest tool declarations and makeToolOutputPolicy reuse packages/plugin-shared/toolLists.mjs for exact names and trailing-star prefixes. Successful built-in output stays hidden by default; only plugin showOutput declarations supply patterns, while failure and hook-note visibility remains in toolOutputView.

Overlay isolation

useOverlayIsolation({ enabled, rootRef }) owns body-level overlay registration, inert and aria-hidden isolation and the shared body scroll lock. It returns restoreFocus only; there is no topmost-query callback. With enabled false or no mounted root, it registers nothing. Cleanup unregisters the captured registration id, while Radix continues to own keyboard dismissal and focus trapping. Modal and ConfirmDialog consume the same active isolation lifecycle; useReturnFocus also serves surfaces outside the body-level stack.