bookclerk_plugin_host

Development These docs follow the development version and change with every merge.

Last updated View as Markdown

External plugin host for Bookclerk (bookclerk-plugin-host).

Discovers staged guests under $BOOKCLERK_FILES_DIR/plugins/ and spawns them over the Workers RPC ABI through the mandatory bookclerk-workerd front door (api_version = 3 Cap'n Proto on stdio).

Production hosts never link ordinary plugin implementation crates. First-party storefronts (Audible, Libro.fm, …) are staged guests, the same path third-party plugins use. Database adapters own physical lowering behind the typed databaseAdapter capability (openSession, dropUnit); production hosts do not link bookclerk-plugin-database-* crates to perform product behavior.

External plugins are untrusted relative to the host: the host never passes library.db / master.key / the files-dir root, clears secret-bearing env on spawn, and mediates credentials + library upserts. Operators must bookclerk plugins approve domains/bindings before enable; the same covering grant is required again at every external spawn and at privileged delivery points (config / secrets / work_fs / oauth). Durable identity is provenance-qualified PluginKey; the manifest id is a display / CLI alias.

Host binaries should depend on this crate for registration — not on individual store crates.

Guest SDK

Third-party Rust plugins should depend on bookclerk_plugin_sdk, not this crate. This host crate re-exports the protocol types for in-tree convenience.

See docs/plugins/README.md, docs/adr/plugin-workers-rpc-workerd.md, and docs/plugins/registry.md.

Item Kind Summary
OnDemandStatus trait What the deployment reconciler reads from, and does to, any on-demand proxy.
DeploymentRuntime trait Install health and spawn for one deployment row.
RefreshedCredentialSink trait Receives the credentials a guest refreshed while it used credentials an library handed with a job (ScanPage.refreshedCredentials, PlainFetch.refreshedCredentials), already checked against the ABI bounds. The daemon writes them back to the owner under the job's fence.
IngressHost trait What the daemon supplies to run the library's ingress.
SocketSink trait Where a plugin instance's socket events go: its guest's socketHandler.
CallbackProxy struct Active host callback proxy for one OAuth session.
GrantedEventConsumer struct One approved event-consumer subscription (structural authority).
PendingStructural struct Newly requested capabilities awaiting operator consent: structural ones, and network destinations wider than the stored grant.
PluginGrant struct One approved grant snapshot for a provenance-qualified plugin.
PluginGrantStore struct On-disk grant store.
SettingNetworkOverlay struct Network destinations one spawn adds from approved network settings.
AuthorizedLocalPackages struct Operator-placed archives keyed by canonical plugin key.
DeploymentSpawn struct Spawn request after config resolution.
LiveDeploymentRuntime struct Production runtime: spawn through the existing host adapters and register the session on the live registry.
LocalPackage struct Local archive the reconciler may install when the ledger has no row.
DiscoveredPlugin struct A discovered plugin ready to spawn.
LinkStateDir struct The directory leaf that holds one joined library's plugin state: link- and 32 lowercase hex digits (128 bits of the SHA-256 of the library's id, as PluginKey::fs_id keeps). An owner picks its own library id, so the digest must be long enough that no library can search for an id that lands in another library's directory.
EnrolledPlugin struct One plugin after enrollment on this node.
EventOutbox struct Host-owned facts a session needs before it can hand a guest an EVENTS binding: the outbox store, the producer allowlist and what it may read.
EventReaders struct What an EVENTS binding may read back from the outbox.
OutboxEventPublisher struct EventPublisher server for one invocation: validates a guest PluginEvent and appends it to the library outbox.
DatabaseRegistry struct Long-lived external database plugin for the active [database].plugin.
DeployedDestination struct One deployed destination as acquire sees it.
DeployedIntake struct One deployed drop folder as the intake runner sees it.
DestinationRegistry struct Long-lived external output plugins loaded at host startup.
DestinationSettings struct Key layout settings the host reads from a deployed destination's instance document: a storage plugin declares prefix and the naming overrides as [[settings]], and acquire needs them to plan storage keys.
ExternalDatabase struct External database backend spawned for [database].plugin.
ExternalIntegration struct External integration backed by a discovered plugin binary.
ExternalSource struct External content source backed by a discovered plugin binary.
HandedPass struct How one account's pass of a handed scan ended.
HandedScan struct What a scan with handed credentials found (ExternalSource::scan_handed).
HostControlPlane struct Open control plane for this process.
NodeEnrollment struct Result of enroll_node: the bootstrap half of a host control plane.
PresentDeployment struct A deployment the database wants present on this node, joined with the instance row and the local install it will run.
AddedVersion struct What add_package_version recorded.
InstallRequest struct An operator's install: what bookclerk plugins install and POST /api/config/plugin-versions both install.
InstalledVersion struct What install_version did.
VersionRequest struct One package to install.
PreparedOpen struct Bindings passed to PluginWorker.open, plus the spawn config table.
KvNamespaces struct Host-owned facts a session needs before it can hand a guest its KV bindings: the library store plus the granted rows.
LibraryKvNamespace struct KvNamespace server for one (plugin_key, namespace) on the library.
OnDemandIntegration struct Integration registry entry that starts its guest on the first call and stops it after the idle timeout without calls.
OnDemandSource struct Source registry entry that starts its storefront guest on the first call and stops it after the idle timeout without calls.
HeldSession struct A guest session lent to a caller, with the hold that keeps an on-demand guest up.
OnDemandStorage struct Destination registry entry that starts its storage guest on a call and stops it after the idle timeout without calls.
OutboxQueueProducer struct QueueProducer server for one binding of one invocation: validates a guest QueueSendMessage and appends it to the library outbox.
QueueOutbox struct Host-owned facts a session needs before it can hand a guest its queue producer bindings: the outbox store plus the granted (binding, queue) pairs.
BookclerkPackageMetadata struct [package.metadata.bookclerk] published on crates.io.
PluginCatalogEntry struct One catalog hit from crates.io (or a curated index).
PluginCrateName struct Parsed crates.io crate name for a Bookclerk plugin.
RemoteNarrowing struct What a host operator takes out of an owner plugin's request.
ExecutorIdentity struct Expanded executor identity. Pooling is an optimization; correctness must not depend on a PID surviving.
PluginSession struct Host-side plugin session (one jailed child + one vat thread).
PluginStorage struct StorageBackend over a plugin destination capability (streams, fail-closed scalars).
RpcBackupOps struct Send-safe backup primitives over a vat-held adapter session (or its open txn).
SessionServices struct Host services a session hands its guest as Bindings on every PluginWorker.open.
InstanceSettingStatuses struct The network-setting statuses of one plugin instance.
SettingGrantStatus struct One network setting, the destination its value names, and its state.
BrokerSockets struct The SOCKETS binding a guest session hands out: the instance's broker.
SocketBroker struct The host's handle on one plugin instance's socket broker.
SpawnPlan struct Everything the spawn path needs to start one guest.
WorkerdFrontDoor struct Resolved bookclerk-workerd launcher and the pinned workerd beside it.
HostWebhooks struct The WEBHOOKS hook of one session: the library, the deployed instance and the declared rows.
WebhookEndpoint struct What the public route needs to check a request for one webhook of an instance this node runs.
SpawnHealth enum Result of spawn plus the health RPC.
StateScope enum Whose library a guest works for, which keeps one library's plugin state apart from another's on the same install.
PluginError enum Failures from discovery, RPC, consent, or plugin adapters.
DestinationSession enum A deployed destination's guest, as handed to a job that calls the guest's entrypoints directly.
StorageRole enum What the host does with a deployed storage instance.
Activate enum When installing moves the active pointer.
RemoteApprovalError enum Why approve_remote_request refused, by cause, so a caller (the operator API) can tell "review again" from "fix the input" from "retry later".
RemoteConsentState enum How this host stands on one owner plugin's request.
SocketEvent enum What a socket delivered: a message, or its close.
GuestRuntimeKind enum Process tree the jail will contain, as reported in crate::ExecutorIdentity.
SpawnTransport enum Which transport a spawn uses to reach the guest.
apply_grant_store function Reconcile every live session against a loaded persisted grant store.
authority_revision function Canonical SHA-256 of security-relevant effective authority.
fence_plugin_key function Fences every live session for plugin_key (grant/authority change).
fence_stale_grant_revisions function Fences live sessions whose persisted crate::grant_revision is not current.
fence_stale_sessions function Fences live sessions for plugin_key whose revision is not current_revision.
is_fenced function True when this cancel flag has been fenced.
live_session_count function Sessions currently registered with the process-wide authority table.
notify_grants_changed function Wake the grant watcher in this process (same-process save / tests).
reconcile_grants_from_disk function Load plugin-grants.json and fence sessions that no longer match.
register_session function Registers a live session and returns its cancel flag.
register_session_revisions function Registers a live session with distinct persisted vs effective revisions.
register_session_with_shutdown function Registers a live session whose shutdown hook runs the instant it is fenced.
spawn_grant_watcher function Spawn the daemon grant watcher (fire-and-forget).
unregister_session function Drops a previously registered cancel flag from the live set.
watch_grants_loop function Watch plugin-grants.json until the process exits.
install_bundled_platform_plugins function Installs bundled platform plugins from beside the running executable into files_dir.
active_processes_for function Absolute Spec active_processes from runtime overhead + extra budget.
ai_task_grant function Grant token for running models of task through the AI binding.
canonical_event_filter function Minified JSON for an event filter; null / missing → None.
consent_request function Build the consent request surface from a manifest and its PluginKey.
consent_request_alias function Build the consent request surface from a manifest (alias only; tests).
consent_summary function Human-readable consent lines for CLI/UI.
consumers_cover function True when every requested consumer is covered by some approved consumer.
cores_to_percent function Convert cores to Spec/config percent-of-one-core, rounded to 0.01 core.
cron_grant function Grant token for firing the normalized cron schedule cron.
database_binding_name function The binding name when a grant entry is a named database binding.
effective_cpu_cores function Clamp operator/manifest cores into 0.01..=``host_cpu_cores_max.
effective_cpu_rate_percent function Resolved jail Spec CPU rate as percent of one logical CPU.
effective_disk_budget_bytes function Resolved disk budget in bytes for data/ and tmp/ checks.
effective_disk_mib function Resolved disk budget in MiB (default + host clamp).
effective_extra_processes function Clamp an operator/manifest extra-process budget (0..=``PLUGIN_JAIL_EXTRA_PROCESSES_MAX).
effective_grant function Spawn/delivery grant: stored approval is authoritative, host-normalized.
effective_memory_mib function Resolved jail Spec memory ceiling in MiB.
format_cpu_cores function Format cores for operator-facing text (0.80).
grant_covers function True when a stored grant is usable for enable/spawn of this PluginKey.
grant_has_binding function True when grant.bindings contains name (case-insensitive).
grant_revision function Canonical SHA-256 of a grant's security-relevant fields (not presentation).
grant_within_ceiling function True when an existing grant stays within the manifest request surface.
granted_consumers_from_manifest function Consumers declared by plugin.toml as structural grant entries.
granted_database_bindings function Consented database binding names on a grant, in manifest-set order.
granted_jobs_from_manifest function Job trigger types declared by [triggers].jobs.
granted_queue_consumers function Consented queue consumer names on a grant.
host_cpu_cores_max function Host max jail CPU in cores (logical_cpus as a 2 d.p. float).
host_cpu_rate_max function Host CPU rate ceiling in one-core percent units (logical_cpus × 100).
host_overlay_config_digest function SHA-256 of host config that participates in implied network overlays.
inject_workerd_grant_env function Injects effective-grant overrides for bookclerk-workerd into a guest command.
is_platform_envelope function True when grant stays inside the platform installer envelope (deny network, only config / work_fs bindings): the request a Bookclerk platform plugin may receive without the operator being asked.
jail_process_overhead function Fixed payload occupancy for the launcher / primary guest tree.
network_compatible function Returns true when a stored network mode can satisfy a requested network mode.
node_logical_cpus function Logical CPUs visible to this process (at least 1).
overlay_host_implied_network function Overlay TCP + CIDR implied by host configuration (not persisted).
pending_structural function Structural capabilities the current manifest requests that the stored grant does not yet authorize.
percent_to_cores function Convert Spec/config percent-of-one-core (100 = 1.00 core) to cores (2 d.p.).
queue_consumer_grant function Grant token for consuming queue.
queue_producer_grant function Grant token for sending through the [[queues.producers]] binding binding.
reapprove_grant function Re-approves the current request on top of a stored grant, keeping the operator's earlier answers.
reconcile_host_overlay_authority function Recomputes effective overlay authority and fences sessions that no longer match.
require_binding function Fail closed when a delivery site needs a binding the covering grant lacks.
require_grant function Require an operator grant before enable or every external spawn.
spawn_config_for_grant function Spawn config payload: non-empty settings only when the grant includes config.
spawn_grant function Resolve the covering grant for spawn: verified platform auto-grant, else require_grant.
validate_approved_grant function Validates and normalizes an operator-supplied grant against host hard caps.
validate_described_capabilities function Reject describe() capability claims that exceed the manifest and the covering grant.
validate_described_config_options function Validates describe().configOptions against the manifest [[settings]].
validate_described_media function Checks the media a guest's describe() returns against its manifest.
windows_session_active_processes function Windows outer session Job active-process cap: baseline 5 plus extra.
search_crates_io function Search crates.io for Bookclerk plugins.
load_authorized_local_packages function Loads operator-placed archives under $FILES_DIR/plugin-packages/<name>/.
reconcile_local_deployments function Reconciles every present deployment for node_id.
build_acquire_destinations function Build destination backends for acquire from the deployed output plugins.
build_storage_backend function Build listing/storage backends from the deployed output plugins.
discover_plugins function Discover plugins under the configured search directories.
first_party_database_kind function First-party database adapter kind when provenance + PluginKey match.
identity_matches_occupancy function True when plugin_key / alias is the occupant named by spec.
is_first_party_local_output function True when this install is the verified Bookclerk local-filesystem destination.
is_first_party_local_output_key function True when key names the Bookclerk local-filesystem destination.
is_first_party_s3_output function True when this install is the verified Bookclerk S3 destination.
occupancy_matches_alias function True when occupancy spec names the display alias (or kind token) alias.
occupancy_names_alias function True when occupancy spec names alias among discovered installs.
occupancy_spec function Config occupancy selector (plugin = "…"), or alias when the field is empty.
plugin_matches_occupancy function True when plugin is the occupant named by spec (PluginKey or alias).
plugin_search_dirs function Resolve search roots: BOOKCLERK_PLUGIN_DIRS then $FILES_DIR/plugins.
resolve_plugin_ref function Resolves spec to a discovered plugin.
resolve_plugin_slot function Resolves spec among plugins without treating a vacant slot as an error.
settings_table function Bootstrap connection settings for a database adapter from config.toml.
settings_table_for function settings_table for one explicit handler family.
stamp_occupancy_plugin_key function Records plugin as the [database].plugin occupant.
upgrade_unique_alias_occupancy function Rewrites a unique [database].plugin alias to the canonical PluginKey.
enroll_local_plugins function Enrolls every discovered plugin on node_id.
enroll_one function Enrolls one discovered plugin. See the module docs for the steps.
has_covering_grant function True when the operator already consented to this plugin, or it is a verified platform guest that grants itself on first spawn.
is_bootstrap_only function True when the plugin is a database adapter and nothing else: those stay bootstrap ([database] in config.toml) in this phase.
granted_event_subscriptions function Keeps the catalog rows an operator grant admits.
manifest_event_subscriptions function Catalog rows for a manifest's [[events.consumers]] declarations, before consent narrows them.
backup_adapter_id function Adapter id recorded on a backup (diagnostic; restore is capability-driven).
database_connect_bindings function Builds the bookclerk_plugin_sdk::BindingValues for the adapter's PluginWorker.open (then databaseAdapter.openSession).
export_registered_plugin_units function Exports every registered plugin-owned database binding as SeaORM sessions.
load_external_database function Discover and spawn the external database plugin matching [database].plugin.
migrate_database_plugin function Copy library data from one database plugin backend to another.
migrate_library_schema function Opens the active database guest without auto-apply and migrates to target.
open_library_store function Open bookclerk_library::LibraryStore via the external database guest (required).
open_library_store_for_plugin function Open the library for a specific [database].plugin id (ignoring the active config value).
restore_plugin_backup_units function Restores plugin binding units onto the current adapter.
storage_role function Reads the role of the storage instance plugin_instance_id.
allow_credential_login function allow_credential_login from the resolved CONFIG; absent means allowed.
enroll_node function Bootstraps the control plane on an open library and enrolls every local plugin, without loading any guest.
open_host_control_plane function Opens the library database and the control plane for config.
open_host_control_plane_with_store function open_host_control_plane on a library that is already open.
refresh_present function Loads an already-open host control plane's deployments again, for callers that changed desired state and want a fresh view without re-enrolling.
add_package_version function Verifies package, records a PluginVersion, and moves the active pointer per VersionRequest::activate.
enroll_version function Creates the default instance of a installed plugin with its schema defaults, as enrollment does for a host-local plugin. Idempotent.
grant_covers_version function True when grant still covers everything version requests, so an update may carry an earlier approval forward. A widened request needs a fresh plugins approve.
host_artifact function The version artifact this node runs.
install_plugin_key function The plugin key an install installs under.
install_version function Installs an operator's package as a version, carries an earlier approval forward when it still covers the new version (or approves when asked), and enrolls the plugin's default instance.
is_sha256_hex function True for a canonical SHA-256 digest: exactly 64 lowercase hex digits.
materialize_owner_version function materialize_version for a version a library deploys to this host: a blob: archive is read from the library as usual (the caller fetched it over the owner link and checked its digest), and any other URL is fetched only as an owner https: URL (bookclerk_plugin_catalog::fetch_owner_artifact: no file:, no local or private hosts, every redirect hop checked the same way).
materialize_version function Makes the active version's tree available under plugins/.versions/<payload digest> and returns that path.
open_installed_plugin function Opens a materialized version tree as a spawnable plugin carrying the version's identity and consent grant.
sweep_version_cache function Removes cached digests not in keep and older than grace, plus stale version staging directories. Returns how many entries were removed.
version_cache_path function Cached tree of one payload-root digest.
version_cache_root function Cache root: <files_dir>/plugins/.versions.
version_consent_request function Consent the version's manifest requests (what plugins approve shows).
version_grant function The consent grant recorded on version.
configured_alias_occupants function Occupancy (PluginKey, alias, path) under every configured discovery root.
install_from_manifest_with_configured_aliases function Catalog install after reject_configured_alias_collision.
install_local_archive_with_configured_aliases function Local-archive install after reject_configured_alias_collision.
reject_configured_alias_collision function Rejects installing incoming_alias when a different PluginKey already owns it anywhere in the configured discovery universe.
binding_grant_flags function config / secrets flags of the plugin's covering grant.
prepare_open_for_instance function Resolves open bindings for instance_id of plugin.
prepared_open_from_resolved function Builds open bindings from a deployment's already resolved payloads.
guest_reservation function CPU and memory one guest may use at most on this host: its grant's ceilings after [plugins.jail], the numbers its jail enforces. The library scheduler accounts host budgets against these.
plugin_data_dir function The private directory a plugin keeps state in.
activates_on_demand function True when a deployment of manifest may sleep while idle and start on the next call.
storefront_activates_on_demand function True when a storefront deployment of manifest may sleep while idle.
storage_activates_on_demand function True when a storage deployment of manifest may sleep while idle.
family_keyword function Family-specific crates.io keyword (bookclerk-source, …).
host_target_triple function Host target triple used when selecting release assets.
validate_plugin_id function Validate plugin id segment used in crate names and plugin.toml.
approve_remote_request function Approves the request recorded from library_id for plugin_key, exactly as it was reviewed: reviewed_digest must be the recorded request's digest (bookclerk_library::control_plane::RemotePluginConsent::request_digest, shown with the request), and the consent is that request minus narrowing (remote_consent). The write is a compare-and-swap on the recorded request, so a request that changed after it was read is refused rather than approved unseen.
narrow_remote_grant function The grant a guest runs with: requested ∩ consent.
remote_consent function The consent an operator gives to requested with narrowing applied.
remote_consent_state function Evaluates a stored consent row's grants: the current request (requested_json), the request as reviewed and the consent (both None while unapproved).
remote_consent_view function The one JSON view of a consent row, shared by the operator API and the CLI so both answer the same fields: the request (version, grant, the archive this host would fetch, and its request_digest), the approval (approved_version, grant, approved_at, approved_by), revoked_at, updated_at, the state (remote_row_consent_state), and pending, what the request asks for beyond the approval (remote_row_changes). A stored grant that does not parse shows as null.
remote_platform_auto_approval function True when a platform plugin's request may be approved without asking: the key is a Bookclerk platform key, this host's own install of that key is platform-bundled with the same payload digest as the owner's artifact (local_bundled_payload, from this host's provenance check), and the request stays inside the platform envelope (deny network, only config / work_fs).
remote_request_changes function Operator-facing lines naming what requested asks for beyond reviewed.
remote_request_within function True when requested asks for nothing outside reviewed: the same plugin, every capability set a subset, network no wider (outbound only if reviewed outbound), undeclared redirects only if reviewed, and no larger budget.
remote_row_changes function remote_request_changes for a stored consent row: what the owner's current request asks for beyond the request the operator approved.
remote_row_consent_state function Evaluates a stored consent row: remote_consent_state over its grants, except that an approval of another archive (the owner changed the artifact URL or digest since the operator approved) needs approval again, whatever the grant.
plugin_instance_key function Isolation key: different accounts never share a plugin isolate.
apply_setting_destinations function Adds every approved destination the instance's settings name to grant.
approve_setting_destinations function The approved setting destinations after the operator answers the form.
destinations_in_use function The destinations rows name, per setting key, for approve_setting_destinations's in_use.
library_setting_statuses function Judges the network settings of every instance of a plugin in the library.
network_grant_binding function The NETWORK binding a guest receives at open: the grant in effect (after apply_setting_destinations filled its setting overlay) and each network setting's destination and state.
network_settings function The settings of manifest that declare network, in declaration order.
setting_grant_statuses function Derives the destination each network setting names in settings.
note_spawn_stage function Record one secret-free startup line.
purge_link_plugin_state function Deletes the plugin state this install kept for a library it no longer belongs to: plugin-state/<link dir>/, every plugin's data, tmp and session directories in it.
recent_spawn_diagnostics function Bounded startup log for the current process.
retry_abandoned_acl_journals function Retry abandoned journals for every plugin under files_dir/plugin-state.
revoke_plugin_state_before_purge function Revoke this plugin's journal before --purge-state deletes the directory.
set_webhook_public_origin function Sets the origin webhook URLs are built on.
webhook_public_origin function The origin webhook URLs are built on, when one is set.
SessionShutdown type alias Shutdown hook invoked the moment a live session is fenced.
Result type alias Result alias for PluginError.
GuestDatabaseFactory type alias Send-safe constructor for a per-binding bookclerk_plugin_sdk::GuestDatabase.
SettingDestinationMap type alias Per setting key, the destinations a plugin's instances name now.
AI_BINDING_RUN_TIMEOUT constant Longest one run through the AI binding may take.
AI_ITEMS_PER_MINUTE constant Input items (texts, for text embeddings) one plugin session may send through AI per minute. The budget refills continuously and allows a burst of the whole minute. Work over many items belongs in a job that the host runs against the model plugin itself.
GRANT_WATCH_INTERVAL constant How often the daemon re-reads plugin-grants.json when no in-process notify fires.
AI_TASK_BINDING_PREFIX constant Grant bindings entry prefix for one [ai].calls task (ai:<task>, such as ai:textEmbeddings): the plugin may run models of that task through its AI binding.
GRANTS_FILE constant Filename under $BOOKCLERK_FILES_DIR for persisted grants.
GRANT_SCHEMA_VERSION constant Current persisted PluginGrant document version.
KNOWN_HOST_BINDINGS constant Host binding names operators may grant (widen or narrow).
PENDING_HEADER constant First line of PendingStructural::summary_lines and crate::remote_request_changes.
PLUGIN_JAIL_ACTIVE_PROCESSES_MAX constant Absolute OS jail PID ceiling (overhead + extra, inclusive).
PLUGIN_JAIL_CPU_CORES_DEFAULT constant Default jail CPU as cores (PLUGIN_JAIL_CPU_RATE_DEFAULT / 100).
PLUGIN_JAIL_CPU_RATE_DEFAULT constant Default jail Spec CPU rate percent for confined guests (one-core units).
PLUGIN_JAIL_CPU_RATE_MAX constant Absolute ceiling used only when host CPU detection is unavailable in docs.
PLUGIN_JAIL_EXTRA_PROCESSES_DEFAULT constant Default extra processes/threads beyond launcher overhead.
PLUGIN_JAIL_EXTRA_PROCESSES_MAX constant Host hard cap for per-plugin extra process budget.
PLUGIN_JAIL_MEMORY_MIB_DEFAULT constant Default jail Spec memory ceiling (MiB) for confined guests.
PLUGIN_JAIL_MEMORY_MIB_MAX constant Host hard cap for per-plugin jail memory overrides (MiB).
PLUGIN_STATE_BUDGET_MIB_DEFAULT constant Default per-plugin data/ and tmp/ disk budget (MiB each).
PLUGIN_STATE_BUDGET_MIB_MAX constant Host hard cap for per-plugin disk budget overrides (MiB).
QUEUE_CONSUMER_BINDING_PREFIX constant Grant bindings entry prefix for one [[queues.consumers]] row (queue_consumer:<queue>): the host may deliver that queue to the plugin.
QUEUE_PRODUCER_BINDING_PREFIX constant Grant bindings entry prefix for one [[queues.producers]] binding (queue:<BINDING>): the plugin may send through that env binding.
WINDOWS_SESSION_PROCESS_BASELINE constant Windows outer session Job processes before the granted extra budget.
WORKERD_GRANT_CPU_MS_ENV constant Grant CPU budget (ms) for workerd logging / limit narrowing.
WORKERD_GRANT_DOMAINS_ENV constant Comma-separated grant domain allowlist for workerd egress.
WORKERD_GRANT_NETWORK_MODE_ENV constant Env keys consumed by bookclerk-workerd (grant.rs) at isolate start.
WORKERD_GRANT_POLICY_ENV constant Canonical JSON EgressPolicy (preferred over piecemeal domain env vars).
WORKERD_GRANT_SUBREQUESTS_ENV constant Grant subrequest budget injected into workerd EGRESS_POLICY.
AUTHORIZED_PACKAGE_DIR constant Directory under the files dir that holds operator-placed package archives.
INGRESS_HEALTH_INTERVAL constant How often a running ingress is asked whether it is serving.
VERSION_CACHE_DIR constant Directory under plugins/ holding materialized version trees.
VERSION_CACHE_GRACE constant How long an unreferenced cached digest survives before the sweep.
KV_GRANT_BINDING constant Grant token that authorizes every [[kv_namespaces]] row of a plugin.
TRIGGER_IDLE_TIMEOUT constant How long a trigger-driven guest stays up after its last call returns.
STOREFRONT_IDLE_TIMEOUT constant How long a storefront stays up after its last call returns.
STORAGE_IDLE_TIMEOUT constant How long a storage destination stays up after its last call returns.
CRATE_NAME_PREFIX constant Required crates.io name prefix: bookclerk-plugin-{family}-{id}.
PRODUCT_KEYWORD constant Shared crates.io keyword (bookclerk) expected on published plugin crates.
REGISTRY_KEYWORD constant Keyword every published plugin crate should include.
HOST_SHARED_ACCOUNT constant Registry-loaded source/integration guests (not a user account).
OPERATOR_ACCOUNT constant Isolation key: different accounts never share a plugin isolate.
WORKERD_BIN_ENV constant Override for the pinned Cloudflare workerd binary, honoured by bookclerk-workerd and forwarded to it by the host.
WORKERD_LAUNCHER_ENV constant Override for the bookclerk-workerd launcher path (tests / packaging).
TEST_CHANNEL_IDENT_ENV constant Set to 1 or true in the host process to give each proxy a channel tag.
TEST_CHANNEL_TAG_FILE constant Session-directory file holding the tag when TEST_CHANNEL_IDENT_ENV is set.
TEST_INJECT_EXTRA_ENDPOINT_ENV constant Host-process description of one extra endpoint to add to the guest handoff.
TEST_OBSERVE_EXTRA_ENDPOINT_ENV constant Host-process request to publish candidate-endpoint observation metadata.
ON_DEMAND_USER_POLL_INTERVAL constant How often the host polls a sleeping remote library for new users.
RESIDENT_USER_POLL_INTERVAL constant How often the host polls a resident remote library for new users.
WEBHOOKS_GRANT_BINDING constant Grant token that authorizes every [[webhooks]] row of a plugin.

Re-exports

Traits

OnDemandStatus

pub trait OnDemandStatus: Send + Sync {
    fn is_retired(&self) -> bool;
    fn retire<'life0, 'async_trait>(
        &'life0 self,
    ) -> Pin<Box<dyn Future<Output = ()> + Send + 'async_trait>>
    where
        Self: 'async_trait,
        'life0: 'async_trait,;
    fn is_awake(&self) -> bool;
    fn guest_pid(&self) -> Option<u32>;
    fn wakes(&self) -> u64;
    fn idle_timeout(&self) -> Duration;
}

What the deployment reconciler reads from, and does to, any on-demand proxy.

OnDemandStatus::is_retired

fn is_retired(&self) -> bool

True once the deployment stopped the proxy; it does not wake again unless a rollback revives it.

OnDemandStatus::retire

fn retire<'life0, 'async_trait>(
    &'life0 self,
) -> Pin<Box<dyn Future<Output = ()> + Send + 'async_trait>>
where
    Self: 'async_trait,
    'life0: 'async_trait,

Stops the proxy for good: a running guest stops and later calls fail, including calls through a registry snapshot a job still holds.

OnDemandStatus::is_awake

fn is_awake(&self) -> bool

True while a guest is running. False while a wake or a sleep holds the guest slot.

OnDemandStatus::guest_pid

fn guest_pid(&self) -> Option<u32>

Native pid of the running guest, if awake.

OnDemandStatus::wakes

fn wakes(&self) -> u64

Guests started on demand since the proxy was created.

OnDemandStatus::idle_timeout

fn idle_timeout(&self) -> Duration

Idle time after which the guest is stopped.

Implemented by: OnDemandIntegration, OnDemandSource, OnDemandStorage

DeploymentRuntime

pub trait DeploymentRuntime: Send + Sync {
    fn spawn_and_health<'life0, 'life1, 'async_trait>(
        &'life0 self,
        request: &'life1 DeploymentSpawn,
    ) -> Pin<Box<dyn Future<Output = SpawnHealth> + Send + 'async_trait>>
    where
        Self: 'async_trait,
        'life0: 'async_trait,
        'life1: 'async_trait,;
    fn guest_still_running<'life0, 'life1, 'async_trait>(
        &'life0 self,
        plugin_instance_id: &'life1 str,
    ) -> Pin<Box<dyn Future<Output = bool> + Send + 'async_trait>>
    where
        Self: 'async_trait,
        'life0: 'async_trait,
        'life1: 'async_trait,;
    fn guest_root<'life0, 'life1, 'async_trait>(
        &'life0 self,
        plugin_instance_id: &'life1 str,
    ) -> Pin<Box<dyn Future<Output = Option<PathBuf>> + Send + 'async_trait>>
    where
        Self: 'async_trait,
        'life0: 'async_trait,
        'life1: 'async_trait,;
    fn retire_instance<'life0, 'life1, 'async_trait>(
        &'life0 self,
        plugin_instance_id: &'life1 str,
    ) -> Pin<Box<dyn Future<Output = ()> + Send + 'async_trait>>
    where
        Self: 'async_trait,
        'life0: 'async_trait,
        'life1: 'async_trait,;
    fn tracked_instance_ids<'life0, 'async_trait>(
        &'life0 self,
    ) -> Pin<Box<dyn Future<Output = Vec<String>> + Send + 'async_trait>>
    where
        Self: 'async_trait,
        'life0: 'async_trait,;
}

Install health and spawn for one deployment row.

DeploymentRuntime::spawn_and_health

fn spawn_and_health<'life0, 'life1, 'async_trait>(
    &'life0 self,
    request: &'life1 DeploymentSpawn,
) -> Pin<Box<dyn Future<Output = SpawnHealth> + Send + 'async_trait>>
where
    Self: 'async_trait,
    'life0: 'async_trait,
    'life1: 'async_trait,

Spawn the guest and run health. Health is the deployment observation; there is no pre-commit gate and nothing to roll back.

DeploymentRuntime::guest_still_running

fn guest_still_running<'life0, 'life1, 'async_trait>(
    &'life0 self,
    plugin_instance_id: &'life1 str,
) -> Pin<Box<dyn Future<Output = bool> + Send + 'async_trait>>
where
    Self: 'async_trait,
    'life0: 'async_trait,
    'life1: 'async_trait,

True when the guest spawned for plugin_instance_id is still running.

The default is true so a runtime that does not track processes keeps the healthy-observation skip. LiveDeploymentRuntime checks the session.

DeploymentRuntime::guest_root

fn guest_root<'life0, 'life1, 'async_trait>(
    &'life0 self,
    plugin_instance_id: &'life1 str,
) -> Pin<Box<dyn Future<Output = Option<PathBuf>> + Send + 'async_trait>>
where
    Self: 'async_trait,
    'life0: 'async_trait,
    'life1: 'async_trait,

Tree the running guest for plugin_instance_id was spawned from.

None (the default) means unknown and never forces a respawn.

DeploymentRuntime::retire_instance

fn retire_instance<'life0, 'life1, 'async_trait>(
    &'life0 self,
    plugin_instance_id: &'life1 str,
) -> Pin<Box<dyn Future<Output = ()> + Send + 'async_trait>>
where
    Self: 'async_trait,
    'life0: 'async_trait,
    'life1: 'async_trait,

Stops a guest this process is running for plugin_instance_id.

Used when a storefront is disabled. The default does nothing so a runtime that does not track processes still compiles. The deployment row is left in place so a later enable can start it again.

DeploymentRuntime::tracked_instance_ids

fn tracked_instance_ids<'life0, 'async_trait>(
    &'life0 self,
) -> Pin<Box<dyn Future<Output = Vec<String>> + Send + 'async_trait>>
where
    Self: 'async_trait,
    'life0: 'async_trait,

Instance ids this process is still tracking.

The default is empty. LiveDeploymentRuntime returns the guest map so a deployment row that disappeared can be retired.

Implemented by: LiveDeploymentRuntime

RefreshedCredentialSink

pub trait RefreshedCredentialSink: Send + Sync {
    fn refreshed<'life0, 'life1, 'async_trait>(
        &'life0 self,
        account_id: &'life1 str,
        credentials: Vec<u8>,
    ) -> Pin<Box<dyn Future<Output = ()> + Send + 'async_trait>>
    where
        Self: 'async_trait,
        'life0: 'async_trait,
        'life1: 'async_trait,;
    fn latest(&self, account_id: &str) -> Option<Vec<u8>>;
}

Receives the credentials a guest refreshed while it used credentials an library handed with a job (ScanPage.refreshedCredentials, PlainFetch.refreshedCredentials), already checked against the ABI bounds. The daemon writes them back to the owner under the job's fence.

One sink serves a whole job, so the job's later guest calls (the next title of an acquire, a fetch after a scan) are sent the refreshed credentials (Self::latest) rather than the stale handed ones.

RefreshedCredentialSink::refreshed

fn refreshed<'life0, 'life1, 'async_trait>(
    &'life0 self,
    account_id: &'life1 str,
    credentials: Vec<u8>,
) -> Pin<Box<dyn Future<Output = ()> + Send + 'async_trait>>
where
    Self: 'async_trait,
    'life0: 'async_trait,
    'life1: 'async_trait,

Hands back credentials, the guest's refreshed credentials for account_id. Failures are the sink's to log; the job goes on.

RefreshedCredentialSink::latest

fn latest(&self, account_id: &str) -> Option<Vec<u8>>

The newest credentials handed to Self::refreshed for account_id during this job, if any; they replace the handed ones.

IngressHost

pub trait IngressHost: Send + Sync {
    fn admit<'life0, 'life1, 'async_trait>(
        &'life0 self,
        plugin_instance_id: &'life1 str,
    ) -> Pin<Box<dyn Future<Output = Result<(), String>> + Send + 'async_trait>>
    where
        Self: 'async_trait,
        'life0: 'async_trait,
        'life1: 'async_trait,;
    fn origin(&self) -> Arc<dyn Origin + Send + Sync>;
    fn started<'life0, 'life1, 'async_trait>(
        &'life0 self,
        plugin_instance_id: &'life1 str,
        started: IngressStarted,
    ) -> Pin<Box<dyn Future<Output = Result<(), String>> + Send + 'async_trait>>
    where
        Self: 'async_trait,
        'life0: 'async_trait,
        'life1: 'async_trait,;
    fn stopped<'life0, 'life1, 'async_trait>(
        &'life0 self,
        plugin_instance_id: &'life1 str,
    ) -> Pin<Box<dyn Future<Output = ()> + Send + 'async_trait>>
    where
        Self: 'async_trait,
        'life0: 'async_trait,
        'life1: 'async_trait,;
}

What the daemon supplies to run the library's ingress.

IngressHost::admit

fn admit<'life0, 'life1, 'async_trait>(
    &'life0 self,
    plugin_instance_id: &'life1 str,
) -> Pin<Box<dyn Future<Output = Result<(), String>> + Send + 'async_trait>>
where
    Self: 'async_trait,
    'life0: 'async_trait,
    'life1: 'async_trait,

Whether plugin_instance_id may serve the library's public address now.

Errors

Returns why not, for the deployment observation: not the active ingress, no Owner yet, or the settings could not be read.

IngressHost::origin

fn origin(&self) -> Arc<dyn Origin + Send + Sync>

The library as relay plugins reach it (ORIGIN).

IngressHost::started

fn started<'life0, 'life1, 'async_trait>(
    &'life0 self,
    plugin_instance_id: &'life1 str,
    started: IngressStarted,
) -> Pin<Box<dyn Future<Output = Result<(), String>> + Send + 'async_trait>>
where
    Self: 'async_trait,
    'life0: 'async_trait,
    'life1: 'async_trait,

plugin_instance_id started and reported started.

Errors

Returns why the report was refused (an origin that is not https:// and a DNS name); the instance is then stopped.

IngressHost::stopped

fn stopped<'life0, 'life1, 'async_trait>(
    &'life0 self,
    plugin_instance_id: &'life1 str,
) -> Pin<Box<dyn Future<Output = ()> + Send + 'async_trait>>
where
    Self: 'async_trait,
    'life0: 'async_trait,
    'life1: 'async_trait,

plugin_instance_id stopped serving: retired, replaced, or refused.

SocketSink

pub trait SocketSink: Send + Sync {
    fn deliver_socket_event<'life0, 'async_trait>(
        &'life0 self,
        event: SocketEvent,
    ) -> Pin<Box<dyn Future<Output = Result<SocketMessageOk, String>> + Send + 'async_trait>>
    where
        Self: 'async_trait,
        'life0: 'async_trait,;
}

Where a plugin instance's socket events go: its guest's socketHandler.

SocketSink::deliver_socket_event

fn deliver_socket_event<'life0, 'async_trait>(
    &'life0 self,
    event: SocketEvent,
) -> Pin<Box<dyn Future<Output = Result<SocketMessageOk, String>> + Send + 'async_trait>>
where
    Self: 'async_trait,
    'life0: 'async_trait,

Hands one event to the guest, starting it if it sleeps.

A sink that schedules the guest's event poll acts on the guest's SocketMessageOk::poll_events itself, polling at once.

Returns

The guest's reply to a message; the default for a close.

Errors

Returns the wake or delivery failure as text. The broker logs it and carries on: a socket is not closed because one delivery failed.

Implemented by: ExternalIntegration, OnDemandIntegration

Structs

CallbackProxy

pub struct CallbackProxy {
    pub public_base: String,
    pub ipc_endpoint: String,
    /* private fields */
}

Active host callback proxy for one OAuth session.

Fields

  • public_base: Browser-facing origin (http://127.0.0.1:<port>) advertised to the guest.
  • ipc_endpoint: Unix socket path or Windows pipe name the guest LoginServer connects to.

CallbackProxy::start

pub async fn start(
    callback_bind: Option<&str>,
    scratch: &Path,
    package_sid: Option<&str>,
) -> Result<Self>

Bind the browser TCP listener and the guest IPC endpoint, then spawn the accept/forward loop.

Errors

Returns when callback_bind is not a socket address, the TCP listener cannot bind, the scratch directory cannot be created, or the platform IPC endpoint cannot be created.

CallbackProxy::bind_addr

pub fn bind_addr(&self) -> SocketAddr

Bound TCP address the browser (and guest) should use for the callback.

Implements: Drop

GrantedEventConsumer

pub struct GrantedEventConsumer {
    pub event_type: String,
    pub schema_versions: Vec<u32>,
    pub supports_suspend: bool,
    pub filter: Option<String>,
}

One approved event-consumer subscription (structural authority).

Identity includes the event type plus the security-relevant subscription properties that change what the plugin receives: schema versions, suspend support, and the host-owned payload filter. Operational knobs (resource_class, max_retries) are not part of authority.

Fields

  • event_type: Versioned event type (book_acquired, …).
  • schema_versions: Schema versions this grant may deliver (sorted, unique).
  • supports_suspend: Whether EventResult::Suspended is authorized for this type.
  • filter: Canonical JSON of the host-owned payload filter, when present.

GrantedEventConsumer::from_manifest

pub fn from_manifest(consumer: &EventConsumer) -> Self

Structural consumer snapshot from a [[events.consumers]] row.

GrantedEventConsumer::covers

pub fn covers(&self, requested: &Self) -> bool

True when requested is the same type with equal-or-narrower schemas, equal-or-narrower suspend, and the same filter.

GrantedEventConsumer::intersect

pub fn intersect(&self, requested: &Self) -> Option<Self>

Intersection used when a stored grant already covers the current manifest.

Implements: Clone, Debug, Deserialize<'de>, Eq, Ord, PartialEq, PartialOrd, Serialize

PendingStructural

pub struct PendingStructural {
    pub entrypoints: BTreeSet<String>,
    pub producers: BTreeSet<String>,
    pub consumers: BTreeSet<GrantedEventConsumer>,
    pub jobs: BTreeSet<String>,
    pub bindings: BTreeSet<String>,
    pub compatibility_flags: BTreeSet<String>,
    pub own_user_agent_hosts: BTreeSet<String>,
    pub domains: BTreeSet<String>,
    pub tcp: BTreeSet<TcpGrant>,
    pub address_cidrs: BTreeSet<String>,
    pub undeclared_public_redirects: bool,
}

Newly requested capabilities awaiting operator consent: structural ones, and network destinations wider than the stored grant.

Fields

  • entrypoints: Entrypoints declared by the current manifest but not granted.
  • producers: Event producers declared by the current manifest but not granted.
  • consumers: Event consumers declared by the current manifest but not granted.
  • jobs: Job triggers declared by the current manifest but not granted.
  • bindings: Host / database bindings declared by the current manifest but not granted.
  • compatibility_flags: Compatibility flags declared by the current manifest but not granted.
  • own_user_agent_hosts: Hosts where the current manifest asks to keep its own User-Agent but the grant does not allow it yet.
  • domains: Fetch host patterns (normalized, * for any public host) the request asks for that the grant neither approved nor denied.
  • tcp: TCP host:ports the request asks for that the grant neither approved nor denied, narrowed to the new ports.
  • address_cidrs: CIDRs the request asks for that the grant neither approved nor denied.
  • undeclared_public_redirects: The request asks to follow undeclared public redirects, which the grant does not allow and the operator never answered.

PendingStructural::is_empty

pub fn is_empty(&self) -> bool

True when the current manifest introduces no unapproved structural caps.

PendingStructural::summary_lines

pub fn summary_lines(&self) -> Vec<String>

CLI/UI lines for capabilities waiting on consent.

Implements: Clone, Debug, Default, Eq, PartialEq

PluginGrant

pub struct PluginGrant {
    pub schema_version: u32,
    pub plugin_key: String,
    pub plugin_id: String,
    pub entrypoints: BTreeSet<String>,
    pub producers: BTreeSet<String>,
    pub consumers: BTreeSet<GrantedEventConsumer>,
    pub jobs: BTreeSet<String>,
    pub network_mode: String,
    pub domains: BTreeSet<String>,
    pub manifest_domains: BTreeSet<String>,
    pub operator_added_domains: BTreeSet<String>,
    pub operator_denied_domains: BTreeSet<String>,
    pub tcp: BTreeSet<TcpGrant>,
    pub manifest_tcp: BTreeSet<TcpGrant>,
    pub operator_added_tcp: BTreeSet<TcpGrant>,
    pub operator_denied_tcp: BTreeSet<TcpGrant>,
    pub address_cidrs: BTreeSet<String>,
    pub manifest_cidrs: BTreeSet<String>,
    pub operator_added_cidrs: BTreeSet<String>,
    pub operator_denied_cidrs: BTreeSet<String>,
    pub allow_undeclared_public_redirects: bool,
    pub operator_allow_undeclared_public_redirects: Option<bool>,
    pub own_user_agent_hosts: Option<BTreeSet<String>>,
    pub own_user_agent_reason: Option<String>,
    pub own_user_agent_refused_hosts: BTreeSet<String>,
    pub declared_own_user_agent_hosts: Option<BTreeSet<String>>,
    pub bindings: BTreeSet<String>,
    pub compatibility_flags: BTreeSet<String>,
    pub cpu_ms: Option<u32>,
    pub subrequests: Option<u32>,
    pub disk_mib: Option<u32>,
    pub memory_mib: Option<u32>,
    pub cpu_rate_percent: Option<u32>,
    pub extra_processes: Option<u32>,
    pub approved_at: String,
    pub setting_destinations: BTreeMap<String, BTreeSet<SettingDestination>>,
    pub setting_network: SettingNetworkOverlay,
}

One approved grant snapshot for a provenance-qualified plugin.

Fields

  • schema_version: Persisted grant document version.

    0 (or omitted JSON) is a legacy document. Empty structural sets approve nothing at every version; a newer manifest cannot acquire entrypoints, producers, consumers, jobs, or bindings by request alone.

  • plugin_key: Canonical bookclerk_plugin_catalog::PluginKey.

  • plugin_id: Display / CLI alias from plugin.toml (not security authoritative).

  • entrypoints: Approved named entrypoints (wire names: storefront, storage, databaseAdapter, remoteLibrary, cli, oidc, metadata, covers, metadataFiles, notifier, ai).

  • producers: Approved event types the plugin may publish through its events binding.

  • consumers: Approved event-consumer subscriptions (type + schema + suspend + filter).

  • jobs: Approved [triggers].jobs types the plugin may handle.

  • network_mode: Approved network mode: deny or outbound.

  • domains: Approved initial outbound domain patterns (workerd allowlist).

    Effective set: (manifest request covered by the approval) ∪ operator additions − operator denials. On a stored grant this is the approved set; a newer manifest can't add to it (effective_grant).

  • manifest_domains: Network destinations requested by the installed manifest (not operator-added).

  • operator_added_domains: Operator-added destinations beyond the current manifest request.

    Survive upgrades of the same Self::plugin_key. Do not transfer across provenance.

  • operator_denied_domains: Operator-denied destinations (even if the manifest still lists them).

  • tcp: Effective raw TCP grants: (manifest ports covered by the approval) ∪ operator additions − denials. On a stored grant these are the approved grants; a newer manifest can't add to them (effective_grant).

  • manifest_tcp: TCP grants requested by the installed manifest.

  • operator_added_tcp: Operator-added TCP grants; survive upgrades of the same PluginKey.

  • operator_denied_tcp: Operator-denied TCP grants (even if the current manifest still lists them).

    Same PluginKey upgrades must not silently restore a TCP host the operator removed. Host spawn overlays (postgres URL, D1, ABS, S3) may still add destinations from operator config after this set is applied.

  • address_cidrs: Effective CIDR grants beyond the public Internet. On a stored grant these are the approved ranges; a newer manifest can't add to them (effective_grant).

  • manifest_cidrs: CIDRs requested by the installed manifest.

  • operator_added_cidrs: Operator-added CIDRs; survive upgrades of the same PluginKey.

  • operator_denied_cidrs: Operator-denied CIDRs (even if the current manifest still lists them).

    Same PluginKey upgrades must not silently restore an address-space grant the operator removed. Host spawn overlays (loopback postgres/ABS) may still add CIDRs from operator config after this set is applied.

  • allow_undeclared_public_redirects: Effective undeclared-public-redirect permission.

  • operator_allow_undeclared_public_redirects: Explicit operator override for undeclared public redirects (None = follow manifest).

  • own_user_agent_hosts: Hosts (exact or *. wildcard) where the guest keeps its own User-Agent.

    Every other request carries the host's agent (bookclerk_plugin_manifest::host_user_agent). None marks a grant approved before this permission existed, when every guest sent its own agent everywhere; effective_grant then keeps the hosts the current manifest declares, which never widens what that grant allowed. Some is the operator's approval and narrows the manifest request.

  • own_user_agent_reason: The manifest's reason for Self::own_user_agent_hosts, shown on the consent form. Display only; it grants nothing.

  • own_user_agent_refused_hosts: Declared own-agent hosts the operator reviewed and left unticked.

    They are not pending (the operator answered), and they grant nothing. Not part of any revision.

  • declared_own_user_agent_hosts: Own-agent hosts the current manifest declares, once this grant has been resolved against it (consent_request, effective_grant).

    Never stored and not part of any revision. The run-time set is Self::own_user_agent_hosts narrowed to these (all of them for a legacy None grant), so an effective grant keeps the stored grant's own field and hashes to the same revisions: a grants write or a config reload doesn't fence its session when the manifest drops a host. None on a grant read from storage.

  • bindings: Approved host binding names (config, secrets, oauth, …).

  • compatibility_flags: Approved workerd compatibility flags from the consent snapshot.

  • cpu_ms: Optional workerd CPU budget override in milliseconds.

  • subrequests: Optional workerd outbound fetch / subrequest budget override.

  • disk_mib: Optional per-plugin disk budget for data/ and tmp/ (MiB each).

    Applies to native and workerd guests. Unset → PLUGIN_STATE_BUDGET_MIB_DEFAULT; clamped to PLUGIN_STATE_BUDGET_MIB_MAX.

  • memory_mib: Optional jail Spec memory ceiling (MiB) for native and workerd.

  • cpu_rate_percent: Optional jail Spec CPU rate as percent of one logical CPU for native guests (1..=host_cpu_rate_max; values above 100 request multi-core bandwidth). Workerd guests omit this and use cpu_ms plus the host jail CPU ceiling instead.

  • extra_processes: Optional extra process/thread budget beyond launcher overhead (native).

    Workerd guests omit this; the host applies default extra headroom only. Absolute Spec active_processes = overhead(runtime) + this value.

  • approved_at: RFC 3339 time when the operator approved this grant.

  • setting_destinations: Destinations derived from network settings ([[settings]] network = …) that the operator approved, by setting key.

    A destination is used only while an instance's value for that setting still derives it (crate::apply_setting_destinations), and approving a setting again withdraws destinations no instance names any more (crate::approve_setting_destinations).

  • setting_network: What approved setting destinations add for this spawn.

    Filled at spawn by crate::apply_setting_destinations from the instance's values; never stored. Self::egress_policy adds it to the stored network grant. It is kept apart from Self::domains and Self::tcp so the effective authority a session records stays the stored grant's: the approvals themselves are in Self::setting_destinations (part of the grant revision), and a changed value changes the instance's configuration revision.

PluginGrant::allows_event_consumer

pub fn allows_event_consumer(&self, event_type: &str, schema_version: u32) -> bool

True when this grant authorizes delivering event_type at schema_version.

PluginGrant::allows_queue_consumer

pub fn allows_queue_consumer(&self, queue: &str) -> bool

True when this grant authorizes delivering messages from queue.

PluginGrant::allows_cron

pub fn allows_cron(&self, cron: &str) -> bool

True when this grant authorizes firing the normalized cron cron.

PluginGrant::allows_queue_producer

pub fn allows_queue_producer(&self, binding: &str) -> bool

True when this grant authorizes sending through the queue producer binding.

PluginGrant::allows_ai_task

pub fn allows_ai_task(&self, task: AiTask) -> bool

True when this grant authorizes running models of task through the AI binding.

PluginGrant::allows_job

pub fn allows_job(&self, job_type: &str) -> bool

True when this grant authorizes handling job_type.

PluginGrant::empty

pub fn empty() -> Self

Empty grant used as a struct-update base for tests and new fields.

PluginGrant::egress_policy

pub fn egress_policy(&self) -> EgressPolicy

Canonical typed network policy for workerd and the native socket proxy.

PluginGrant::effective_domains

pub fn effective_domains(&self) -> BTreeSet<String>

The fetch allowlist this spawn uses: Self::domains plus what approved setting destinations add.

PluginGrant::approved_own_user_agent_hosts

pub fn approved_own_user_agent_hosts(&self) -> BTreeSet<String>

Approved own-agent hosts; a legacy None grant approves none here.

Revisions hash this set, so a legacy grant and its effective grant agree. Self::effective_own_user_agent_hosts is what a guest gets.

PluginGrant::effective_own_user_agent_hosts

pub fn effective_own_user_agent_hosts(&self) -> BTreeSet<String>

Hosts where the guest keeps its own agent at run time.

Returns

The approved hosts the current manifest still declares; for a legacy None grant, every declared host. Without a declared set (a grant read from storage) the approved set as is, or none.

Implements: Clone, Debug, Deserialize<'de>, Eq, PartialEq, Serialize

PluginGrantStore

pub struct PluginGrantStore {
    pub grants: Vec<PluginGrant>,
}

On-disk grant store.

Fields

  • grants: Persisted per-plugin grant snapshots.

PluginGrantStore::path

pub fn path(files_dir: &Path) -> PathBuf

Absolute path to plugin-grants.json under files_dir.

PluginGrantStore::load

pub fn load(files_dir: &Path) -> Result<Self>

Loads grants from disk, or an empty store when the file is missing.

Operator-selected files_dir may contain .. spelling (resolved via canonicalize). Escaping or dangling leaf symlinks at plugin-grants.json are hard errors; a true missing file yields an empty store.

Arguments
  • files_dir - Bookclerk files directory that owns plugin-grants.json.
Returns

Parsed PluginGrantStore, defaulting when the file does not exist.

Errors

Returns PluginError when the file cannot be read or parsed.

PluginGrantStore::save

pub fn save(&self, files_dir: &Path) -> Result<()>

Writes this grant store to plugin-grants.json under files_dir.

Uses unique same-dir create_new staging and Unix rename / Windows MoveFileExW so a leaf symlink at the final path is replaced as a directory entry (not followed). Cleanup removes only staging this call created.

Arguments
  • files_dir - Bookclerk files directory that owns plugin-grants.json.
Errors

Returns PluginError when serialization or the write fails.

PluginGrantStore::get_by_plugin_key

pub fn get_by_plugin_key(&self, plugin_key: &str) -> Option<&PluginGrant>

Returns the grant whose canonical PluginKey matches plugin_key.

Does not fall back to display aliases — spawn and privilege checks must not inherit another provenance's grant.

PluginGrantStore::get

pub fn get(&self, plugin_key: &str) -> Option<&PluginGrant>

Returns the grant for plugin_key (canonical), or an unambiguous alias.

Display / CLI helper only. Spawn, overlay, and other privilege checks must call Self::get_by_plugin_key so an alias cannot inherit another provenance's grant.

Arguments
  • plugin_key - Canonical PluginKey text, or a display alias.
Returns

A reference to the matching PluginGrant, or None.

PluginGrantStore::upsert

pub fn upsert(&mut self, grant: PluginGrant)

Inserts or replaces the grant for grant.plugin_key.

Incoming grants with a PluginKey match only that key: they never overwrite a different provenance, and never collapse onto a keyless same-alias legacy row. A keyless incoming grant (legacy files / tests) matches only other keyless rows by alias so it cannot replace a provenance-qualified grant.

Arguments
  • grant - Full consent snapshot to persist in memory (call Self::save to flush).

Implements: Clone, Debug, Default, Deserialize<'de>, Eq, PartialEq, Serialize

SettingNetworkOverlay

pub struct SettingNetworkOverlay {
    pub domains: BTreeSet<String>,
    pub tcp: BTreeSet<TcpGrant>,
    pub local_names: BTreeSet<String>,
    pub pending: BTreeSet<PendingSettingDestination>,
}

Network destinations one spawn adds from approved network settings.

Fields

  • domains: Fetch host:port entries (EgressPolicy::domains).
  • tcp: Raw TCP grants (EgressPolicy::tcp).
  • local_names: Names and local-network addresses bound to the local network (EgressPolicy::local_names).
  • pending: Destinations settings name that await approval; they grant nothing and only let a refusal name its setting (EgressPolicy::pending_settings).

Implements: Clone, Debug, Default, Eq, PartialEq

AuthorizedLocalPackages

pub struct AuthorizedLocalPackages {
    /* private fields */
}

Operator-placed archives keyed by canonical plugin key.

A key that two packages both resolve to is removed from the map and recorded in Self::is_conflicted. Neither package is installed.

AuthorizedLocalPackages::get

pub fn get(&self, key: &str) -> Option<&LocalPackage>

Package for key, when exactly one authorized archive resolved to it.

AuthorizedLocalPackages::is_conflicted

pub fn is_conflicted(&self, key: &str) -> bool

True when two archives resolved to key and neither was kept.

AuthorizedLocalPackages::is_empty

pub fn is_empty(&self) -> bool

True when no archive was loaded and no key collided.

AuthorizedLocalPackages::keys

pub fn keys(&self) -> Keys<'_, String, LocalPackage>

Canonical keys that have exactly one package.

AuthorizedLocalPackages::insert

pub fn insert(&mut self, key: String, package: LocalPackage)

Inserts package under key, clearing a previous conflict on that key.

Implements: Clone, Debug, Default

DeploymentSpawn

pub struct DeploymentSpawn {
    pub plugin_instance_id: String,
    pub plugin_key: String,
    pub plugin_root: Option<PathBuf>,
    pub config: ExtensibleConfig,
    pub secrets: ExtensibleConfig,
    pub config_revision: i64,
    pub installed: Option<Arc<PluginVersion>>,
}

Spawn request after config resolution.

Fields

  • plugin_instance_id: Instance this deployment runs. Not derived from the plugin key.
  • plugin_key: Canonical plugin key.
  • plugin_root: Installed tree, when discovery or install produced one.
  • config: Granted CONFIG payload.
  • secrets: Granted SECRETS payload.
  • config_revision: Document revision the spawn applies.
  • installed: Installed version the tree was materialized from; None for a host-local tree.

Implements: Clone, Debug

LiveDeploymentRuntime

pub struct LiveDeploymentRuntime {
    pub config: Arc<RwLock<Config>>,
    pub store: Arc<RwLock<LibraryStore>>,
    pub sources: Arc<RwLock<SourceRegistry>>,
    pub integrations: Arc<RwLock<IntegrationRegistry>>,
    pub destinations: Arc<RwLock<DestinationRegistry>>,
    pub ai: Arc<AiRouter>,
    /* private fields */
}

Production runtime: spawn through the existing host adapters and register the session on the live registry.

Fields

  • config: Live daemon config.
  • store: Open library, used for instance bindings.
  • sources: Storefront sessions the reconciler owns.
  • integrations: Integration sessions the reconciler owns.
  • destinations: Destination sessions the reconciler owns.
  • ai: The node's model router over [Self::integrations]: behind every granted AI binding, and what the host's own features run models through.

LiveDeploymentRuntime::new

pub fn new(
    config: Arc<RwLock<Config>>,
    store: Arc<RwLock<LibraryStore>>,
    sources: Arc<RwLock<SourceRegistry>>,
    integrations: Arc<RwLock<IntegrationRegistry>>,
    destinations: Arc<RwLock<DestinationRegistry>>,
) -> Self

Runtime bound to the daemon's live registries.

LiveDeploymentRuntime::set_ingress_host

pub fn set_ingress_host(&self, host: Arc<dyn IngressHost>)

Stores what the daemon supplies to run the library's ingress. Until it is set, ingress plugins are not spawned.

LiveDeploymentRuntime::on_demand

pub fn on_demand(&self, plugin_instance_id: &str) -> Option<Arc<dyn OnDemandStatus>>

The on-demand proxy registered for plugin_instance_id, if this process tracks one.

Only reads the map, so a poisoned lock still yields it.

LiveDeploymentRuntime::reconcile_lock

pub fn reconcile_lock(&self) -> &Mutex<()>

Lock a caller holds for the duration of one reconcile pass.

LiveDeploymentRuntime::set_integration_context

pub fn set_integration_context(&self, ctx: IntegrationContext)

Stores the daemon lifecycle context used when a deployment starts an integration.

Panics

Panics when the integration-context lock is poisoned.

LiveDeploymentRuntime::retire_plugin_instance

pub async fn retire_plugin_instance(&self, plugin_instance_id: &str)

Stops every registry entry for plugin_instance_id and drops the guest.

Sources, integrations, and storage slots all hold the session. Removing only the source leaves an integration claiming events or a destination still accepting writes. Other instances of the same plugin key stay.

LiveDeploymentRuntime::forget_guest

pub async fn forget_guest(&self, plugin_instance_id: &str)

Drops the tracked guest for plugin_instance_id without taking the source registry.

Config reload already holds that registry. Dropping this entry stops a resident process once the registry no longer keeps the session; an on-demand proxy is retired so no snapshot of it can wake it again.

Panics

Panics when the deployment guest lock is poisoned.

LiveDeploymentRuntime::opened_config_json

pub fn opened_config_json(&self, plugin_instance_id: &str) -> Option<Value>

CONFIG JSON the live open call delivered for plugin_instance_id.

Panics

Panics when the deployment guest lock is poisoned.

LiveDeploymentRuntime::tracked_guest_pid

pub fn tracked_guest_pid(&self, plugin_instance_id: &str) -> Option<u32>

Native guest pid for plugin_instance_id, when this process spawned it.

Panics

Panics when the deployment guest lock is poisoned.

LiveDeploymentRuntime::webhook_endpoint

pub fn webhook_endpoint(
    &self,
    plugin_instance_id: &str,
    name: &str,
) -> Option<WebhookEndpoint>

The [[webhooks]] row name of the instance this node runs, with the row's signing secret when it names one and the operator set it.

Returns

None when this node runs no guest for plugin_instance_id or its manifest declares no row name.

LiveDeploymentRuntime::wake_webhook

pub fn wake_webhook(&self, plugin_instance_id: &str, event: WebhookDelivered)

Tells the instance's resident guest that requests wait for webhook event.name, without waiting for its answer.

A sleeping on-demand guest is not started: it pulls on its next call, and a storage guest's feed is read on its next sync pass.

Implements: DeploymentRuntime

LocalPackage

pub struct LocalPackage {
    pub archive: PathBuf,
    pub manifest: BookclerkPackageManifest,
}

Local archive the reconciler may install when the ledger has no row.

Fields

  • archive: Archive path (tar.gz or zip).
  • manifest: Install-grade package manifest for archive.

Implements: Clone, Debug

DiscoveredPlugin

pub struct DiscoveredPlugin {
    pub manifest: PluginManifest,
    pub root: PathBuf,
    pub command: PathBuf,
    pub identity: PluginInstallIdentity,
    pub version_grant: Option<PluginGrant>,
    pub state_scope: StateScope,
}

A discovered plugin ready to spawn.

Fields

  • manifest: Parsed plugin.toml for this install directory.
  • root: Directory containing plugin.toml (cwd + relative command base).
  • command: Absolute path to the plugin executable.
  • identity: Host-evaluated provenance-qualified identity.
  • version_grant: Consent grant recorded on the library release this tree was materialized from; None for host-local trees, whose grant lives in plugin-grants.json.
  • state_scope: Whose library the guest works for, which decides where its host-managed data and tmp directories live.

DiscoveredPlugin::new

pub fn new(manifest: PluginManifest, root: PathBuf, command: PathBuf) -> Self

Builds a discovered plugin, evaluating content hashes and provenance.

Incomplete synthetic trees should use Self::for_test instead of weakening production evaluation.

Panics

Panics when the install tree cannot be evaluated. Prefer Self::try_new.

DiscoveredPlugin::try_new

pub fn try_new(
    manifest: PluginManifest,
    root: PathBuf,
    command: PathBuf,
    files_dir: Option<&Path>,
) -> Result<Self>

Production constructor: fail closed on malformed receipts, hash errors, and unrecognized install receipts.

Errors

Returns when identity evaluation fails closed.

DiscoveredPlugin::for_test

pub fn for_test(manifest: PluginManifest, root: PathBuf, command: PathBuf) -> Self

Explicit test/dev constructor for incomplete plugin trees.

Does not hash the tree or consult receipts. Never grants platform trust.

DiscoveredPlugin::from_release

pub fn from_release(
    manifest: PluginManifest,
    root: PathBuf,
    plugin_key: &str,
    version: &str,
    payload_root_sha256: &str,
    archive_sha256: &str,
    grant: PluginGrant,
) -> Result<Self>

Builds a plugin from a tree materialized from a library release.

The caller has already verified the tree's payload-root digest against the release row; identity, version, and the consent grant come from that row, not from a receipt or the host grant file.

Errors

Returns an error when the spawn command cannot be resolved, the manifest cannot be hashed, or plugin_key is malformed.

DiscoveredPlugin::alias

pub fn alias(&self) -> &str

Display / CLI alias (plugin.toml id).

DiscoveredPlugin::plugin_key

pub fn plugin_key(&self) -> &PluginKey

Provenance-qualified key.

Implements: Clone, Debug

LinkStateDir

pub struct LinkStateDir(/* private */);

The directory leaf that holds one joined library's plugin state: link- and 32 lowercase hex digits (128 bits of the SHA-256 of the library's id, as PluginKey::fs_id keeps). An owner picks its own library id, so the digest must be long enough that no library can search for an id that lands in another library's directory.

Derived from the library id rather than copying it, so the leaf is always filesystem-safe and fixed-length whatever the owner sent.

LinkStateDir::for_library

pub fn for_library(library_id: &str) -> Self

The state directory leaf of the library with library_id.

LinkStateDir::as_str

pub fn as_str(&self) -> &str

The directory leaf (link- + 32 hex digits).

LinkStateDir::is_leaf

pub fn is_leaf(leaf: &str) -> bool

True when leaf has the shape of a link state directory, so a sweep never mistakes a plugin's own state directory for one.

Implements: Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd

EnrolledPlugin

pub struct EnrolledPlugin {
    pub plugin: DiscoveredPlugin,
    pub instance: PluginInstance,
    pub deployment: PluginDeployment,
    pub schema: PinnedPluginSchema,
}

One plugin after enrollment on this node.

Fields

  • plugin: Discovered install.
  • instance: Default instance for the plugin key.
  • deployment: This node's deployment of the default instance.
  • schema: Pinned settings schema.

Implements: Clone, Debug

EventOutbox

pub struct EventOutbox {
    /* private fields */
}

Host-owned facts a session needs before it can hand a guest an EVENTS binding: the outbox store, the producer allowlist and what it may read.

EventOutbox::new

pub fn new(
    store: LibraryStore,
    plugin_id: &str,
    declared: impl IntoIterator<Item = String>,
    granted: &BTreeSet<String>,
    readers: EventReaders,
) -> Option<Self>

Builds the outbox hook for plugin_id, or None when the plugin neither publishes a consented producer nor consumes a consented subscription (the guest then sees no EVENTS binding).

EventOutbox::publisher

pub fn publisher(&self, invocation: &Invocation) -> OutboxEventPublisher

Publisher bound to one PluginWorker.open invocation (account scope and default correlation / causation come from invocation).

Implements: Clone

EventReaders

pub struct EventReaders {
    pub subscriptions: Vec<EventCatalogSubscription>,
    pub retention_days: u64,
    pub settle_secs: u64,
}

What an EVENTS binding may read back from the outbox.

Fields

  • subscriptions: Consented [[events.consumers]] subscriptions (manifest ∩ grant).
  • retention_days: [events].retention_days: reads never go further back.
  • settle_secs: Seconds an event must age before a read returns it (bookclerk_library::EVENT_STREAM_SETTLE_SECS in a session), so a late-committing publication is never behind a returned cursor.

Implements: Clone, Debug, Default

OutboxEventPublisher

pub struct OutboxEventPublisher {
    /* private fields */
}

EventPublisher server for one invocation: validates a guest PluginEvent and appends it to the library outbox.

OutboxEventPublisher::spec

pub fn spec(&self, event: PluginEvent) -> Result<PublishDomainEventSpec, PluginError>

Validates event and builds the outbox row the host will insert.

Errors
  • forbidden when eventType is not a consented producer.
  • payload_too_large when payload exceeds MAX_EVENT_PAYLOAD_BYTES.
  • invalid_params when payload is not UTF-8 JSON.

Implements: EventPublisher

DatabaseRegistry

pub struct DatabaseRegistry {
    /* private fields */
}

Long-lived external database plugin for the active [database].plugin.

DatabaseRegistry::active

pub fn active(&self) -> Option<Arc<ExternalDatabase>>

Currently active external database guest for [database].plugin.

Implements: Clone, Default

DeployedDestination

pub struct DeployedDestination {
    pub id: DestinationId,
    pub backend: Arc<dyn StorageBackend>,
    pub settings: DestinationSettings,
}

One deployed destination as acquire sees it.

Fields

  • id: The destination's id: its plugin instance id.
  • backend: Storage backend over the destination's guest.
  • settings: Key layout from the instance document.

Implements: Clone

DeployedIntake

pub struct DeployedIntake {
    pub id: DestinationId,
    pub backend: Arc<dyn StorageBackend>,
    pub settings: DestinationSettings,
}

One deployed drop folder as the intake runner sees it.

Fields

  • id: The drop folder's plugin instance id.
  • backend: Storage backend over the folder's guest.
  • settings: Key layout from the instance document (its prefix).

Implements: Clone

DestinationRegistry

pub struct DestinationRegistry {
    /* private fields */
}

Long-lived external output plugins loaded at host startup.

DestinationRegistry::destinations

pub fn destinations(&self) -> Vec<DeployedDestination>

Every deployed destination, one per plugin instance, by id. No kind of storage plugin comes first: each translates the host's keys itself.

Several instances of one plugin are separate destinations. Drop folders (StorageRole::Intake) are not destinations and are left out; see Self::intakes.

DestinationRegistry::intakes

pub fn intakes(&self) -> Vec<DeployedIntake>

Every deployed drop folder, sorted by id.

DestinationRegistry::plugin_session

pub fn plugin_session(
    &self,
    plugin_id: &str,
    account_id: &str,
) -> Option<DestinationSession>

Plugin session for plugin_id and account_id, when that guest was loaded.

plugin_id may be the canonical PluginKey (how sessions are stored) or a display alias. Aliases are installation-unique; two occupants sharing an alias is invalid state and fails closed rather than returning a twin.

DestinationRegistry::require_plugin_session

pub fn require_plugin_session(
    &self,
    plugin_id: &str,
    account_id: &str,
) -> Result<DestinationSession, String>

Self::plugin_session that reports same-key ambiguity.

Errors

Returns an error when no guest is loaded, or when more than one session matches plugin_id.

DestinationRegistry::reattach_owned

pub fn reattach_owned(&self, candidate: &mut Self, deployed_instances: &BTreeSet<String>)

Copies deployed sessions from this registry onto candidate.

deployed_instances is the set of present plugin instance ids. Reload builds candidate without those plugin keys. Only sessions the reconciler bound to one of those ids are copied, including the backend they own. A transitional session for the same key is left behind.

Implements: Clone, Default

DestinationSettings

pub struct DestinationSettings {
    pub prefix: String,
    pub naming: DestinationNaming,
}

Key layout settings the host reads from a deployed destination's instance document: a storage plugin declares prefix and the naming overrides as [[settings]], and acquire needs them to plan storage keys.

Fields

  • prefix: Key prefix under the destination root or bucket.
  • naming: Naming overrides; unset values inherit global [output].

DestinationSettings::from_granted_config

pub fn from_granted_config(granted: &Value) -> Self

Reads the layout settings from a resolved CONFIG object.

Implements: Clone, Debug, Default, Eq, PartialEq

ExternalDatabase

pub struct ExternalDatabase {
    /* private fields */
}

External database backend spawned for [database].plugin.

ExternalDatabase::spawn

pub async fn spawn(plugin: &DiscoveredPlugin, config: &Config) -> PluginResult<Self>

Spawn and describe a database plugin (connection happens later).

Errors

Returns an error when the operation fails.

ExternalDatabase::spawn_with

pub async fn spawn_with(
    plugin: &DiscoveredPlugin,
    config: &Config,
    services: SessionServices,
) -> PluginResult<Self>

Self::spawn with explicit session services (spawn transport, …).

Product callers use Self::spawn; this exists so transport diagnostics can compare the front door against direct native.

Errors

Returns an error when the guest cannot start or negotiate.

ExternalDatabase::connect

pub async fn connect(
    &self,
    config: &Config,
) -> Result<(DatabaseConnection, DbCapabilities), DbErr>

Open the library connection through the guest (database.openSession).

Errors

Returns an error when the operation fails.

ExternalDatabase::connect_without_migrate

pub async fn connect_without_migrate(
    &self,
    config: &Config,
) -> Result<(DatabaseConnection, DbCapabilities), DbErr>

Open the library connection without applying host schema (CLI migrate / version).

Errors

Returns an error when the guest cannot open a session.

ExternalDatabase::library_backup_ops

pub fn library_backup_ops(&self) -> SharedAdapterBackupOps

Adapter snapshot/identity/restore hooks for the library session.

ExternalDatabase::binding_backup_ops

pub fn binding_backup_ops(&self, key: impl Into<String>) -> SharedAdapterBackupOps

Adapter snapshot/identity/restore hooks for one named binding session.

ExternalDatabase::migrate_to

pub async fn migrate_to(
    &self,
    db: &DatabaseConnection,
    caps: &DbCapabilities,
    target: i64,
    opts: SchemaApplyOptions,
) -> Result<SchemaWalk, DbErr>

Migrates toward target using guest executeAtomic batches (CLI migrate / downgrade).

Errors

Returns when capability flags are unknown or a schema batch fails.

ExternalDatabase::open_binding_databases

pub async fn open_binding_databases(
    &self,
    config: &Config,
    store: &LibraryStore,
    owner_plugin_id: &str,
    bindings: &[String],
    owner: &PluginSession,
) -> PluginResult<Vec<(String, GuestDatabaseFactory)>>

Opens (provisioning on first use) isolated sessions for the named plugin database bindings of owner_plugin_id.

Backend-native units: SQLite gets a file per binding under <files_dir>/plugin-databases/<plugin-key-fs-id>/<BINDING>.db, PostgreSQL a dedicated database (pb_ + 32 hex of the (plugin, binding) digest), and D1 its own database (bookclerk-pb- + the same 32 hex). Third-party adapters advertising pluginDatabases receive binding plus a collision-resistant instanceId on the public bookclerk_plugin_abi::DatabaseAdapterConfig. Each provisioned unit is recorded in the plugin_databases registry (an existing row wins so a re-open never re-targets a binding).

Errors

Fails closed when the adapter does not advertise DbCapabilities::plugin_databases, when provisioning fails, or when the registry cannot be recorded.

ExternalDatabase::open_binding_seaorm

pub async fn open_binding_seaorm(
    &self,
    config: &Config,
    owner_plugin_id: &str,
    binding: &str,
    unit_ref: &str,
    provision: bool,
) -> PluginResult<(DatabaseConnection, DbCapabilities)>

Opens one plugin binding as a SeaORM connection through the guest session.

Physical provisioning is adapter-owned (provision). Logical identity is (plugin_id, binding). Does not switch on sqlite/postgres/d1 beyond building the adapter's own connect context.

Errors

Returns when the guest cannot open the binding or the proxy fails.

ExternalDatabase::drop_provisioned_unit

pub async fn drop_provisioned_unit(
    config: &Config,
    adapter_plugin_key: &str,
    unit_ref: &str,
) -> PluginResult<()>

Physically deletes a provisioned binding unit. The registry row is the caller's to remove after this returns success.

Spawns the original adapter PluginKey and calls Database.dropUnit. SQLite unlinks the file and journal sidecars. PostgreSQL issues DROP DATABASE. D1 deletes the Cloudflare database by name. Adapters that do not implement dropUnit fail closed so a registry row cannot outlive a unit the host cannot prove is gone.

Errors

Returns when the adapter is not installed, spawn fails, credentials are missing, or the guest refuses the delete.

ExternalDatabase::adapter_plugin_key

pub fn adapter_plugin_key(&self) -> &str

Canonical PluginKey of this adapter guest.

ExternalDatabase::first_party_kind

pub fn first_party_kind(&self) -> Option<DatabasePluginKind>

Verified first-party adapter kind, if any.

Implements: Clone

ExternalIntegration

pub struct ExternalIntegration {
    /* private fields */
}

External integration backed by a discovered plugin binary.

ExternalIntegration::spawn_prepared

pub async fn spawn_prepared(
    plugin: &DiscoveredPlugin,
    config: &Config,
    services: SessionServices,
    prepared: PreparedOpen,
    allow_credential_login: bool,
) -> Result<Self>

Spawn with bindings already resolved for one plugin instance.

Does not look up an instance by plugin key.

Errors

Returns an error when the guest cannot start or open fails.

ExternalIntegration::bind_plugin_instance

pub fn bind_plugin_instance(&mut self, plugin_instance_id: &str)

Records the plugin instance id used to recognize this guest on reload.

ExternalIntegration::check_health

pub async fn check_health(&self) -> Result<()>

Integration health RPC.

Calls health on each exported entrypoint that has one (remoteLibrary, metadata). Guests that export neither are ready once open has succeeded: event, job, OIDC, and CLI-only integrations use that describe/open check.

Errors

Returns an error when an entrypoint's health reports not ok.

Implements: Integration, SocketSink

ExternalSource

pub struct ExternalSource {
    /* private fields */
}

External content source backed by a discovered plugin binary.

ExternalSource::spawn_prepared

pub async fn spawn_prepared(
    plugin: &DiscoveredPlugin,
    config: &Config,
    services: SessionServices,
    prepared: PreparedOpen,
) -> Result<Self>

Spawn with bindings already resolved for one plugin instance.

Does not look up an instance by plugin key. See crate::prepare_open_for_instance for how the bindings are built.

Errors

Returns an error when the guest cannot start or open fails.

ExternalSource::with_refresh_sink

pub fn with_refresh_sink(self, sink: Arc<dyn RefreshedCredentialSink>) -> Self

Sends credentials the guest refreshes while using handed credentials to sink (see Self::with_handed_credentials).

ExternalSource::with_handed_credentials

pub fn with_handed_credentials(self, credentials: Vec<AccountCredential>) -> Self

Uses only credentials (a library handed them with a job) for every guest call: no library is read for credentials, and ContentSource::scan is refused in favour of Self::scan_handed.

ExternalSource::scan_handed

pub async fn scan_handed(
    &self,
    opts: ScanOptions,
    sync_tokens: &HashMap<String, String>,
) -> Result<HandedScan>

Scans with the handed credentials and answers the guest's rows unwritten, with how each account's pass ended (the owner validates and writes them, removes what a pass found gone, and keeps the sync tokens).

opts.accounts narrows the scan to those account ids; empty means every handed account. An account with a token in sync_tokens (the owner's, from its last complete pass) runs a delta pass from it; the others run full passes. A pass whose token the guest refuses restarts once as a full pass, and its report says so.

Errors

Returns an error when this source has no handed credentials, the grant lacks the secrets binding, or the guest fails.

ExternalSource::bind_plugin_instance

pub fn bind_plugin_instance(&mut self, plugin_instance_id: &str)

Records the plugin instance id used as this source's registry address.

ExternalSource::check_health

pub async fn check_health(&self) -> Result<()>

Storefront health RPC.

Errors

Returns an error when the guest has no storefront or health reports not ok.

ExternalSource::guest_pid

pub fn guest_pid(&self) -> Option<u32>

Native guest pid, when the session recorded one.

Implements: ContentSource

HandedPass

pub struct HandedPass {
    pub account_id: String,
    pub removed: Vec<String>,
    pub sync_token: String,
    pub complete: bool,
    pub full: bool,
}

How one account's pass of a handed scan ended.

Fields

  • account_id: The account.
  • removed: Product ids the pass reported gone from the account (a delta pass's removals).
  • sync_token: The plugin's token for the account's next pass; empty when it keeps none.
  • complete: The pass listed every title the account holds.
  • full: The pass was full (sent no token, or restarted after its token was refused), so with complete its rows are all the account holds.

Implements: Clone, Debug, Eq, PartialEq

HandedScan

pub struct HandedScan {
    pub rows: Vec<ScanBook>,
    pub passes: Vec<HandedPass>,
}

What a scan with handed credentials found (ExternalSource::scan_handed).

Fields

  • rows: Every account's rows, unwritten.
  • passes: How each account's pass ended, in the order the accounts ran.

Implements: Debug, Default

HostControlPlane

pub struct HostControlPlane {
    pub config: Config,
    pub database_registry: DatabaseRegistry,
    pub store: LibraryStore,
    pub session: ControlPlaneSession,
    pub enrolled: Vec<EnrolledPlugin>,
    pub present: Vec<PresentDeployment>,
    pub default_instances: HashMap<String, String>,
}

Open control plane for this process.

Fields

  • config: Bootstrap config with the database-backed domains overlaid.
  • database_registry: Database adapters discovered for bootstrap.
  • store: Open library.
  • session: Node identity, library id, and core documents.
  • enrolled: Plugins enrolled on this pass.
  • present: Deployments desired present on this node, in deployment-id order.
  • default_instances: Default instance id per plugin key, for routing a bare key.

HostControlPlane::node_id

pub fn node_id(&self) -> &str

This node's id.

HostControlPlane::load_sources

pub async fn load_sources(&self, services: &SessionServices) -> Result<SourceRegistry>

Spawns every present storefront deployment and registers it under its instance id, with the plugin's default instance recorded for routing.

A guest that fails to start is logged and skipped so the rest of the command still runs.

Errors

Returns an error when the files directory is unavailable.

HostControlPlane::load_integrations

pub async fn load_integrations(
    &self,
    services: &SessionServices,
) -> Result<IntegrationRegistry>

Spawns every present integration deployment.

Errors

Returns an error when the files directory is unavailable.

HostControlPlane::load_destinations

pub async fn load_destinations(&self) -> Result<DestinationRegistry>

Spawns every present storage deployment.

Errors

Returns an error when a present destination guest cannot start: a destination the database wants here that does not come up would otherwise silently drop acquire output.

NodeEnrollment

pub struct NodeEnrollment {
    pub config: Config,
    pub session: ControlPlaneSession,
    pub enrolled: Vec<EnrolledPlugin>,
}

Result of [enroll_node]: the bootstrap half of a host control plane.

Fields

  • config: Bootstrap config with the database-backed domains overlaid.
  • session: Node identity, library id, and core documents.
  • enrolled: Plugins enrolled on this pass.

PresentDeployment

pub struct PresentDeployment {
    pub deployment: PluginDeployment,
    pub instance: PluginInstance,
    pub plugin: Option<DiscoveredPlugin>,
}

A deployment the database wants present on this node, joined with the instance row and the local install it will run.

Fields

  • deployment: Desired row.
  • instance: Instance the row runs.
  • plugin: Install discovered on this node, when there is one.

Implements: Clone, Debug

AddedVersion

pub struct AddedVersion {
    pub version: PluginVersion,
    pub created: bool,
    pub pointer: Option<PluginInstall>,
}

What add_package_version recorded.

Fields

  • version: The version row.
  • created: True when this call wrote the row (false for an identical re-install).
  • pointer: Pointer after activation, when this call moved it.

Implements: Clone, Debug

InstallRequest

pub struct InstallRequest {
    pub package: BookclerkPackageManifest,
    pub coordinate: PackageCoordinate,
    pub archive: Option<PathBuf>,
    pub target: Option<String>,
    pub offline: bool,
    pub activate: bool,
    pub approve: bool,
}

An operator's install: what bookclerk plugins install and POST /api/config/plugin-versions both install.

Fields

  • package: Resolved package manifest.
  • coordinate: Where the package came from. A local archive's coordinate is path-derived and is not recorded on the version.
  • archive: Local archive to install instead of fetching the coordinate.
  • target: Install only this target instead of every target in the package.
  • offline: Refuse network fetches.
  • activate: Make the version active even when another version already is.
  • approve: Record the requested consent as approved when no earlier approval carries forward.

Implements: Clone, Debug

InstalledVersion

pub struct InstalledVersion {
    pub version: PluginVersion,
    pub created: bool,
    pub active: bool,
    pub instance: PluginInstance,
}

What install_version did.

Fields

  • version: The installed (and maybe approved) version.
  • created: False when this exact version was already installed.
  • active: True when the version is the plugin's active version afterwards.
  • instance: The plugin's default instance.

Implements: Clone, Debug

VersionRequest

pub struct VersionRequest {
    pub plugin_key: String,
    pub package: BookclerkPackageManifest,
    pub archive: Option<PathBuf>,
    pub target: Option<String>,
    pub coordinate: String,
    pub offline: bool,
    pub publisher_verified: bool,
    pub grant: Option<PluginGrant>,
    pub activate: Activate,
}

One package to install.

Fields

  • plugin_key: Canonical plugin key the version is recorded under.
  • package: Install-grade package manifest.
  • archive: Local archive. None fetches every target's artifact from its URL and verifies the manifest digests.
  • target: Target the local archive is built for (default: this host's).
  • coordinate: Package coordinate recorded for update; empty for a local archive.
  • offline: Refuse remote downloads (a local archive needs none).
  • publisher_verified: Publisher verification result (recorded on the version).
  • grant: Consent grant approved at install time, if any.
  • activate: When to move the active pointer.

Implements: Clone, Debug

PreparedOpen

pub struct PreparedOpen {
    pub bindings: BindingValues,
    pub spawn_config_table: Value,
    pub granted_config: Value,
    pub config_revision: i64,
}

Bindings passed to PluginWorker.open, plus the spawn config table.

Fields

  • bindings: Values for PluginWorker.open.

  • spawn_config_table: JSON object passed into crate::PluginSession::spawn_with.

    The session still applies crate::spawn_config_for_grant.

  • granted_config: JSON object the guest receives when the grant includes config.

  • config_revision: Document revision this open applies.

Implements: Clone, Debug

KvNamespaces

pub struct KvNamespaces {
    /* private fields */
}

Host-owned facts a session needs before it can hand a guest its KV bindings: the library store plus the granted rows.

KvNamespaces::new

pub fn new(
    store: LibraryStore,
    plugin_key: &str,
    manifest: &PluginManifest,
    grant: &PluginGrant,
) -> Option<Self>

Builds the KV hook for plugin_key, or None when the manifest declares no row or the grant lacks KV_GRANT_BINDING.

KvNamespaces::binding_names

pub fn binding_names(&self) -> Vec<String>

Granted binding names in manifest order.

KvNamespaces::namespaces

pub fn namespaces(&self) -> Vec<(String, String, Arc<dyn KvNamespace>)>

Namespaces shaped for HostBindings::kv as (binding, namespace, kv).

Implements: Clone

LibraryKvNamespace

pub struct LibraryKvNamespace {
    /* private fields */
}

KvNamespace server for one (plugin_key, namespace) on the library.

LibraryKvNamespace::new

pub fn new(store: LibraryStore, plugin_key: &str, row: &KvNamespaceManifest) -> Self

Builds one namespace directly (tests and in-process hosts).

LibraryKvNamespace::namespace

pub fn namespace(&self) -> &str

Namespace this binding is scoped to.

Implements: KvNamespace

OnDemandIntegration

pub struct OnDemandIntegration {
    /* private fields */
}

Integration registry entry that starts its guest on the first call and stops it after the idle timeout without calls.

OnDemandIntegration::sleep_if_idle

pub async fn sleep_if_idle(&self) -> bool

Stops the guest now if it has been idle for the timeout.

Returns

True when a running guest was stopped.

Implements: Integration, OnDemandStatus, SocketSink

OnDemandSource

pub struct OnDemandSource {
    /* private fields */
}

Source registry entry that starts its storefront guest on the first call and stops it after the idle timeout without calls.

OnDemandSource::sleep_if_idle

pub async fn sleep_if_idle(&self) -> bool

Stops the guest now if it has been idle for the timeout.

Returns

True when a running guest was stopped.

Implements: ContentSource, OnDemandStatus

HeldSession

pub struct HeldSession {
    pub session: Arc<PluginSession>,
    /* private fields */
}

A guest session lent to a caller, with the hold that keeps an on-demand guest up.

Fields

  • session: The running guest's session.

OnDemandStorage

pub struct OnDemandStorage {
    /* private fields */
}

Destination registry entry that starts its storage guest on a call and stops it after the idle timeout without calls.

Cloning shares the guest: every clone is the same destination.

OnDemandStorage::sleep_if_idle

pub async fn sleep_if_idle(&self) -> bool

Stops the guest now if it has been idle for the timeout.

Returns

True when a running guest was stopped.

OnDemandStorage::session

pub async fn session(&self) -> Result<HeldSession, String>

The running guest's session, starting the guest when asleep, held awake until the returned value is dropped.

Errors

Returns an error when the proxy is retired, the guest cannot start, or the guest has no session (a test double).

Implements: Clone, OnDemandStatus, StorageBackend

OutboxQueueProducer

pub struct OutboxQueueProducer {
    /* private fields */
}

QueueProducer server for one binding of one invocation: validates a guest QueueSendMessage and appends it to the library outbox.

OutboxQueueProducer::queue

pub fn queue(&self) -> &str

Queue this producer sends to.

OutboxQueueProducer::spec

pub fn spec(
    &self,
    message: QueueSendMessage,
    default_delay: u32,
) -> Result<PublishDomainEventSpec, PluginError>

Validates message and builds the outbox row the host will insert. default_delay applies when the message carries no delay of its own.

Errors
  • payload_too_large when body exceeds MAX_EVENT_PAYLOAD_BYTES.
  • invalid_params when contentType is unknown, a json body is not UTF-8 JSON, or a text body is not UTF-8.

Implements: QueueProducer

QueueOutbox

pub struct QueueOutbox {
    /* private fields */
}

Host-owned facts a session needs before it can hand a guest its queue producer bindings: the outbox store plus the granted (binding, queue) pairs.

QueueOutbox::new

pub fn new(
    store: LibraryStore,
    plugin_id: &str,
    manifest: &PluginManifest,
    grant: &PluginGrant,
) -> Option<Self>

Builds the outbox hook for plugin_id, or None when no producer row is both declared and granted (the guest then sees no queue bindings).

QueueOutbox::binding_names

pub fn binding_names(&self) -> Vec<String>

Granted binding names in manifest order.

QueueOutbox::producers

pub fn producers(
    &self,
    invocation: &Invocation,
) -> Vec<(String, String, Arc<dyn QueueProducer>)>

Producers bound to one PluginWorker.open invocation, shaped for HostBindings::queues as (binding, queue, producer).

Implements: Clone

BookclerkPackageMetadata

pub struct BookclerkPackageMetadata {
    pub api_version: u32,
    pub family: PluginFamily,
    pub id: String,
    pub display_name: Option<String>,
    pub artifact_base_url: Option<String>,
    pub artifact_url: Option<String>,
    pub archive_root: Option<String>,
    pub min_host: Option<String>,
}

[package.metadata.bookclerk] published on crates.io.

Fields

  • api_version: Plugin ABI / package metadata API version (must be >= 1).

  • family: Plugin family encoded in the crates.io name.

  • id: Plugin id ([a-z0-9_]{2,32}), unique across kinds in one host namespace.

  • display_name: Optional human-readable name for catalog UI.

  • artifact_base_url: Template with {tag}, {version}, {target}, {crate} placeholders.

    Any HTTPS host works (GitHub/GitLab/Codeberg releases, S3/R2, CDN, self-hosted). Combined with the conventional archive filename unless Self::artifact_url is set.

  • artifact_url: Full download URL template (overrides base + conventional filename).

    Placeholders: {tag}, {version}, {target}, {crate}, {ext}.

  • archive_root: Optional path inside the release archive where plugin.toml lives.

  • min_host: Optional minimum Bookclerk host version required to run this plugin.

BookclerkPackageMetadata::validate_against_crate_name

pub fn validate_against_crate_name(&self, crate_name: &str) -> Result<()>

Ensure metadata matches the crate naming taxonomy.

Errors

Returns an error when the operation fails.

BookclerkPackageMetadata::artifact_download_url

pub fn artifact_download_url(
    &self,
    crate_name: &str,
    version: &str,
    target: &str,
) -> Option<String>

Build a download URL for a release asset.

Prefers the artifact_url metadata field when set; otherwise {artifact_base_url}/{crate}-{version}-{target}.{ext} with {ext} = zip for Windows targets and tar.gz otherwise.

Implements: Clone, Debug, Deserialize<'de>, Eq, PartialEq, Serialize

PluginCatalogEntry

pub struct PluginCatalogEntry {
    pub crate_name: String,
    pub version: String,
    pub description: Option<String>,
    pub downloads: u64,
    pub documentation: Option<String>,
    pub repository: Option<String>,
    pub homepage: Option<String>,
    pub parsed: Option<PluginCrateName>,
    pub metadata: Option<BookclerkPackageMetadata>,
}

One catalog hit from crates.io (or a curated index).

Fields

  • crate_name: crates.io package name (bookclerk-plugin-{family}-{id}).
  • version: Published crate / release version string.
  • description: Short crates.io description when the index provides one.
  • downloads: Download count from the registry index, when known.
  • documentation: Documentation URL from crate metadata, when present.
  • repository: Source repository URL from crate metadata, when present.
  • homepage: Project homepage URL from crate metadata, when present.
  • parsed: Parsed from crate name when it matches the taxonomy.
  • metadata: Present when crates.io returned Cargo.toml metadata (install phase).

Implements: Clone, Debug, Deserialize<'de>, Eq, PartialEq, Serialize

PluginCrateName

pub struct PluginCrateName {
    pub family: PluginFamily,
    pub id: String,
}

Parsed crates.io crate name for a Bookclerk plugin.

Fields

  • family: Plugin family encoded in the crates.io name.
  • id: Plugin id ([a-z0-9_]{2,32}), unique across kinds in one host namespace.

PluginCrateName::crate_name

pub fn crate_name(&self) -> String

Format as bookclerk-plugin-{family}-{id}.

PluginCrateName::parse

pub fn parse(name: &str) -> Result<Self>

Parse bookclerk-plugin-{family}-{id}.

Errors

Returns an error when the operation fails.

Implements: Clone, Debug, Deserialize<'de>, Display, Eq, PartialEq, Serialize

RemoteNarrowing

pub struct RemoteNarrowing {
    pub deny_domains: BTreeSet<String>,
    pub deny_bindings: BTreeSet<String>,
    pub deny_own_user_agent_hosts: BTreeSet<String>,
    pub deny_network: bool,
}

What a host operator takes out of an owner plugin's request.

Fields

  • deny_domains: Outbound domain patterns to deny.
  • deny_bindings: Host bindings to deny (secrets, oauth, kv, ...).
  • deny_own_user_agent_hosts: Requested own-agent hosts to refuse: requests to them carry Bookclerk's agent. The hosts stay reachable.
  • deny_network: Turn outbound network off altogether.

Implements: Clone, Debug, Default, Eq, PartialEq

ExecutorIdentity

pub struct ExecutorIdentity {
    pub plugin_id: String,
    pub artifact_digest: String,
    pub version: String,
    pub role: String,
    pub account_id: String,
    pub configuration_revision: String,
    pub grant_revision: String,
    pub authority_revision: String,
    pub runtime_backend: String,
    pub compatibility_date: String,
}

Expanded executor identity. Pooling is an optimization; correctness must not depend on a PID surviving.

Fields

  • plugin_id: Provenance-qualified bookclerk_plugin_catalog::PluginKey (canonical text).
  • artifact_digest: Artifact payload-root digest (or install-path stand-in when unsigned/dev).
  • version: Manifest version.
  • role: Role (destination, source, database, integration).
  • account_id: Account / principal.
  • configuration_revision: Configuration revision (installed plugin.toml SHA-256).
  • grant_revision: Grant revision (persisted operator consent; revocation changes this).
  • authority_revision: Effective runtime authority (host overlays + clamped budgets).
  • runtime_backend: workerd / native-behind-workerd / native-direct (GuestRuntimeKind::label).
  • compatibility_date: Workerd compatibility date when applicable.

ExecutorIdentity::from_plugin

pub fn from_plugin(plugin: &DiscoveredPlugin, account_id: &str) -> Self

Builds an identity from a discovered plugin and account on the default (front-door) transport.

ExecutorIdentity::from_plugin_on

pub fn from_plugin_on(
    plugin: &DiscoveredPlugin,
    account_id: &str,
    transport: SpawnTransport,
) -> Self

Builds an identity for plugin spawned over transport.

ExecutorIdentity::from_plugin_with_runtime

pub fn from_plugin_with_runtime(
    plugin: &DiscoveredPlugin,
    account_id: &str,
    runtime: GuestRuntimeKind,
) -> Self

Builds an identity whose runtime_backend is the resolved launcher tree.

ExecutorIdentity::with_overlay_config

pub fn with_overlay_config(self, config: &Config) -> Self

Folds overlay-relevant host config into Self::configuration_revision.

Changing a Postgres URL / D1 API origin / S3 endpoint must not reuse a session that was spawned under the old overlay.

ExecutorIdentity::with_grant_revision

pub fn with_grant_revision(self, grant: &PluginGrant) -> Self

Fills persisted Self::grant_revision and effective Self::authority_revision from a grant snapshot.

When host overlays apply, pass the persisted grant to Self::with_persisted_and_effective.

ExecutorIdentity::with_persisted_and_effective

pub fn with_persisted_and_effective(
    self,
    persisted: &PluginGrant,
    effective: &PluginGrant,
) -> Self

Fills revisions from a persisted operator grant and the effective runtime grant.

ExecutorIdentity::session_key

pub fn session_key(&self) -> String

Stable session key. Distinct PIDs with the same key are the same logical instance; pooling must use this key, not a PID.

Implements: Clone, Debug, Eq, Hash, PartialEq

PluginSession

pub struct PluginSession {
    /* private fields */
}

Host-side plugin session (one jailed child + one vat thread).

PluginSession::spawn

pub async fn spawn(
    plugin: &DiscoveredPlugin,
    config: &Config,
    config_table: Value,
) -> Result<Self>

Spawns a plugin guest and connects Cap'n Proto on stdio.

Errors

Fails when the child cannot start, describe fails, or apiVersion is not 2.

PluginSession::spawn_for_account

pub async fn spawn_for_account(
    plugin: &DiscoveredPlugin,
    config: &Config,
    config_table: Value,
    account_id: &str,
) -> Result<Self>

Self::spawn keyed by (plugin_id, account_id) so different accounts never share a plugin isolate.

Errors

Fails when the child cannot start, describe fails, or negotiation fails.

PluginSession::spawn_for_account_with_env

pub async fn spawn_for_account_with_env(
    plugin: &DiscoveredPlugin,
    config: &Config,
    config_table: Value,
    account_id: &str,
    extra_env: &[(&str, OsString)],
) -> Result<Self>

Self::spawn_for_account with transport-private extra environment.

Errors

Fails when the child cannot start, describe fails, or negotiation fails.

PluginSession::spawn_with

pub async fn spawn_with(
    plugin: &DiscoveredPlugin,
    config: &Config,
    config_table: Value,
    account_id: &str,
    extra_env: &[(&str, OsString)],
    services: SessionServices,
) -> Result<Self>

Self::spawn_for_account_with_env plus the host services the guest may receive as bindings (EVENTS outbox, …) and the spawn transport.

This is the one place every product spawn passes through: the SpawnPlan resolved here decides that a runtime = "native" manifest is fronted by bookclerk-workerd (host-spawned sibling jails joined by inherited links) unless services.spawn_transport opted into the diagnostic direct transport.

Errors

Fails when the front door (bookclerk-workerd + pinned workerd) is missing, the child cannot start, describe fails, or negotiation fails.

PluginSession::instance_key

pub fn instance_key(&self) -> &str

Isolation instance key (plugin_id:account_id).

PluginSession::account_id

pub fn account_id(&self) -> &str

Account scope carried on every PluginWorker.open invocation.

PluginSession::session_key

pub fn session_key(&self) -> &str

Expanded executor session key (artifact, role, grant revision, …).

PluginSession::guest_pid

pub fn guest_pid(&self) -> Option<u32>

Native guest PID (sibling jail) or the single child when there is none.

PluginSession::gateway_pid

pub fn gateway_pid(&self) -> Option<u32>

Gateway / Cap'n Proto child PID for native-behind-workerd, when known.

PluginSession::guest_running

pub fn guest_running(&self) -> bool

True when the guest process, and the gateway when one was spawned, are still running.

PluginSession::session_dir

pub fn session_dir(&self) -> Option<&Path>

Host-owned gateway session directory, when this session has a sibling.

PluginSession::limits

pub fn limits(&self) -> ScalarLimits

Negotiated scalar limits.

PluginSession::supports_server_copy

pub fn supports_server_copy(&self) -> bool

True when the guest accepted storage.copy.

PluginSession::storage_capabilities

pub fn storage_capabilities(&self) -> StorageCapabilities

The optional storage operations the guest accepted (storage.*).

PluginSession::id

pub fn id(&self) -> &str

Provenance-qualified PluginKey (canonical text).

PluginSession::alias

pub fn alias(&self) -> &str

Manifest display / CLI alias (plugin.toml id).

PluginSession::data_dir

pub fn data_dir(&self) -> &Path

Guest data directory.

PluginSession::open

pub async fn open(&self, values: BindingValues) -> Result<()>

Opens the session's primary entrypoints with the granted binding values (CONFIG / SECRETS).

Idempotent for equal values; different values re-open. Entrypoint calls that run before open use empty bindings.

Errors

Returns a plugin error when PluginWorker.open fails.

PluginSession::describe

pub async fn describe(&self) -> Result<PluginDescribe>

Calls PluginWorker.describe.

Errors

Returns a plugin error when the RPC fails.

PluginSession::stream_copy

pub async fn stream_copy(&self, job_id: &str, from: &str, to: &str) -> Result<JobOutcome>

Runs the stream-copy job handler on the guest.

Errors

Returns a plugin error when the handler fails.

PluginSession::stream_copy_with_cancel

pub async fn stream_copy_with_cancel(
    &self,
    lease: JobInvocationLease,
    from: &str,
    to: &str,
    cancel: Arc<AtomicBool>,
    progress: Option<(LibraryStore, JobFence)>,
) -> Result<JobOutcome>

Self::stream_copy raced against a host cancel/fence flag.

When progress is set, reports are persisted with LibraryStore::set_job_progress; a lost fence surfaces as cancellation.

Errors

Returns a plugin error when the handler fails or the fence is lost.

PluginSession::stream_copy_with_databases

pub async fn stream_copy_with_databases(
    &self,
    lease: JobInvocationLease,
    from: &str,
    to: &str,
    cancel: Arc<AtomicBool>,
    progress: Option<(LibraryStore, JobFence)>,
    databases: Vec<(String, GuestDatabaseFactory)>,
) -> Result<JobOutcome>

Self::stream_copy_with_cancel with named plugin database bindings.

Each (name, factory) pair becomes an isolated GuestDatabase on the per-job PluginWorker.open bindings; factories run on the vat thread.

Errors

Returns a plugin error when the handler fails or the fence is lost.

PluginSession::describe_snapshot

pub fn describe_snapshot(&self) -> &PluginDescribe

Snapshot from the guest describe() call at spawn.

PluginSession::grant

pub fn grant(&self) -> &PluginGrant

Covering consent grant from spawn.

PluginSession::require_binding

pub fn require_binding(&self, name: &str) -> Result<()>

Fail closed when a delivery site needs an ungranted binding.

Errors

Returns an error when the binding is missing from the grant.

PluginSession::scratch_dir

pub fn scratch_dir(&self) -> &Path

Guest TMPDIR / scratch directory.

PluginSession::guest_ipc_dir

pub fn guest_ipc_dir(&self) -> Option<&Path>

Directory the guest may use for pathname sockets, when this session has one.

PluginSession::package_sid

pub fn package_sid(&self) -> Option<&str>

AppContainer package SID when the guest is jailed on Windows.

PluginSession::spawn_config

pub fn spawn_config(&self) -> &Value

Spawn config JSON captured at spawn.

PluginSession::has_entrypoint

pub fn has_entrypoint(&self, entrypoint: Entrypoint) -> bool

True when the guest exported entrypoint in describe().

PluginSession::consumes_event

pub fn consumes_event(&self, event_type: &str) -> bool

True when the guest's default entrypoint consumes event_type.

PluginSession::consumes_events

pub fn consumes_events(&self) -> bool

True when the guest's default entrypoint consumes any event type.

PluginSession::consumes_queues

pub fn consumes_queues(&self) -> bool

True when the guest's default entrypoint consumes at least one [[queues.consumers]] queue.

PluginSession::storefront

pub async fn storefront<T, F, Fut>(&self, call: F) -> Result<T>
where
    T: Send + 'static,
    F: FnOnce(Box<dyn ContentSource>) -> Fut + Send + 'static,
    Fut: Future<Output = Result<T, PluginError>> + 'static,

One typed storefront method on the opened primary entrypoints.

call runs on the vat thread; its output crosses back to the caller's runtime.

Errors

Returns a plugin error when the guest did not export storefront or the method fails.

PluginSession::metadata

pub async fn metadata<T, F, Fut>(&self, call: F) -> Result<T>
where
    T: Send + 'static,
    F: FnOnce(Box<dyn MetadataProvider>) -> Fut + Send + 'static,
    Fut: Future<Output = Result<T, PluginError>> + 'static,

One typed metadata method on the opened primary entrypoints.

call runs on the vat thread; its output crosses back to the caller's runtime.

Errors

Returns a plugin error when the guest did not export metadata or the method fails.

PluginSession::covers

pub async fn covers<T, F, Fut>(&self, call: F) -> Result<T>
where
    T: Send + 'static,
    F: FnOnce(Box<dyn CoverFetcher>) -> Fut + Send + 'static,
    Fut: Future<Output = Result<T, PluginError>> + 'static,

One typed covers method on the opened primary entrypoints.

call runs on the vat thread; its output crosses back to the caller's runtime.

Errors

Returns a plugin error when the guest did not export covers or the method fails.

PluginSession::metadata_files

pub async fn metadata_files<T, F, Fut>(&self, call: F) -> Result<T>
where
    T: Send + 'static,
    F: FnOnce(Box<dyn MetadataFiles>) -> Fut + Send + 'static,
    Fut: Future<Output = Result<T, PluginError>> + 'static,

One typed metadataFiles method on the opened primary entrypoints.

call runs on the vat thread; its output crosses back to the caller's runtime.

Errors

Returns a plugin error when the guest did not export metadataFiles or the method fails.

PluginSession::notifier

pub async fn notifier<T, F, Fut>(&self, call: F) -> Result<T>
where
    T: Send + 'static,
    F: FnOnce(Box<dyn Notifier>) -> Fut + Send + 'static,
    Fut: Future<Output = Result<T, PluginError>> + 'static,

One typed notifier method on the opened primary entrypoints.

call runs on the vat thread; its output crosses back to the caller's runtime.

Errors

Returns a plugin error when the guest did not export notifier or the method fails.

PluginSession::ai

pub async fn ai<T, F, Fut>(&self, call: F) -> Result<T>
where
    T: Send + 'static,
    F: FnOnce(Box<dyn AiModels>) -> Fut + Send + 'static,
    Fut: Future<Output = Result<T, PluginError>> + 'static,

One typed ai method on the opened primary entrypoints.

call runs on the vat thread; its output crosses back to the caller's runtime.

Errors

Returns a plugin error when the guest did not export ai or the method fails.

PluginSession::ingress

pub async fn ingress<T, F, Fut>(&self, call: F) -> Result<T>
where
    T: Send + 'static,
    F: FnOnce(Box<dyn Ingress>) -> Fut + Send + 'static,
    Fut: Future<Output = Result<T, PluginError>> + 'static,

One typed ingress method (start, health or stop) on the opened primary entrypoints.

call runs on the vat thread; its output crosses back to the caller's runtime.

Errors

Returns a plugin error when the guest did not export ingress or the method fails.

PluginSession::deliver_webhook_wake

pub async fn deliver_webhook_wake(&self, event: WebhookDelivered) -> Result<()>

Tells the guest's webhookHandler entrypoint that requests wait for one of its webhooks.

Errors

Returns a plugin error when the guest did not export webhookHandler or its handler failed.

PluginSession::deliver_socket_event

pub async fn deliver_socket_event(&self, event: SocketEvent) -> Result<SocketMessageOk>

Hands one socket event to the guest's socketHandler entrypoint.

Returns

The guest's reply to a message (whether it asks for an events poll now); the default for a close.

Errors

Returns a plugin error when the guest did not export socketHandler or its handler failed.

PluginSession::remote_library

pub async fn remote_library<T, F, Fut>(&self, call: F) -> Result<T>
where
    T: Send + 'static,
    F: FnOnce(Box<dyn RemoteLibrary>) -> Fut + Send + 'static,
    Fut: Future<Output = Result<T, PluginError>> + 'static,

One typed remoteLibrary method on the opened primary entrypoints.

Errors

Returns a plugin error when the guest did not export remoteLibrary or the method fails.

PluginSession::remote_library_cancelable

pub async fn remote_library_cancelable<T, F, Fut>(
    &self,
    cancel: Arc<AtomicBool>,
    call: F,
) -> Result<T>
where
    T: Send + 'static,
    F: FnOnce(Box<dyn RemoteLibrary>) -> Fut + Send + 'static,
    Fut: Future<Output = Result<T, PluginError>> + 'static,

Typed remoteLibrary method aborted when cancel is set.

Errors

Returns a plugin error when the RPC fails or is cancelled.

PluginSession::deliver_events

pub async fn deliver_events(
    &self,
    batch: Vec<DomainEvent>,
    cancel: Arc<AtomicBool>,
) -> Result<Vec<EventResult>>

Delivers one ordered event batch to the guest eventConsumer trigger (EventConsumer.event), aborted when cancel is set (fence loss).

Returns exactly one EventResult per input event.

Errors

Returns a plugin error when the guest did not export an event consumer, the RPC fails, or the delivery is cancelled.

PluginSession::deliver_queue

pub async fn deliver_queue(
    &self,
    batch: QueueBatch,
    cancel: Arc<AtomicBool>,
) -> Result<Vec<QueueResult>>

Delivers one ordered batch from a [[queues.consumers]] queue to the guest's queue(batch) trigger.

Returns exactly one bookclerk_plugin_abi::QueueResult per message.

Errors

Returns a plugin error when the grant does not cover the queue, the guest did not export a queue consumer, the RPC fails, or the delivery is cancelled.

PluginSession::run_scheduled

pub async fn run_scheduled(
    &self,
    controller: ScheduledController,
    cancel: Arc<AtomicBool>,
) -> Result<()>

Runs one cron fire through the guest's scheduled(controller) trigger, aborted when cancel is set.

Errors

Returns a plugin error when the grant does not cover the cron, the guest did not export a scheduled handler, the handler fails, or the fire is cancelled.

PluginSession::cli_describe

pub async fn cli_describe(&self) -> Result<CliSchema>

Guest CLI schema.

Errors

Returns a plugin error when the RPC fails.

PluginSession::cli_invoke

pub async fn cli_invoke(&self, params: CliInvokeParams) -> Result<CliInvokeResult>

Guest CLI invoke.

Errors

Returns a plugin error when the RPC fails.

PluginSession::oidc_clients

pub async fn oidc_clients(&self) -> Result<Vec<OidcClientTemplate>>

Plugin-provided OIDC authorization-server client templates (Oidc.clients); empty when the guest exports no oidc entrypoint.

Errors

Returns a plugin error when the RPC fails.

PluginSession::oidc_authenticate_user

pub async fn oidc_authenticate_user(
    &self,
    params: AuthenticateUserParams,
) -> Result<ExternalUser>

Verifies remote credentials through the guest oidc entrypoint (Oidc.authenticateUser).

Errors

Returns a plugin error when the guest exports no oidc entrypoint or the RPC fails.

PluginSession::database_migrations

pub async fn database_migrations(&self, binding: &str) -> Result<Vec<PluginMigration>>

Complete ordered plugin-owned migration sequence for one named binding.

Errors

Returns a plugin error when the RPC fails.

PluginSession::db_open

pub async fn db_open(&self, values: BindingValues) -> Result<()>

Opens the library adapter session (held on the vat until drop).

Performs a dedicated PluginWorker.open whose bindings carry the host-private connect params in values, then openSession on the returned databaseAdapter entrypoint.

Errors

Returns a plugin error when open / openSession fails or the guest exports no databaseAdapter.

PluginSession::db_drop_unit

pub async fn db_drop_unit(&self, values: BindingValues, unit_ref: &str) -> Result<()>

Physically drops one provisioned binding unit via Database.dropUnit.

Opens the adapter factory with values (library connect params) and does not retain a session. Used by plugins db drop.

Errors

Returns a plugin error when open / dropUnit fails or the guest exports no databaseAdapter.

PluginSession::db_open_binding

pub async fn db_open_binding(
    &self,
    name: &str,
    values: BindingValues,
) -> Result<DbCapabilities>

Opens an isolated adapter session for one named plugin database binding.

Negotiates bookclerk_plugin_sdk::DbCapabilities on the binding session itself (not the library session).

Errors

Returns a plugin error when the guest rejects the open or the binding session fails host capability minima.

PluginSession::db_execute_binding_request

pub async fn db_execute_binding_request(
    &self,
    name: &str,
    request: AdapterExecuteRequest,
    cancel: Arc<AtomicBool>,
) -> Result<ExecuteReply>

Typed execute on a named plugin database binding session.

Errors

Returns a plugin error when the binding is not open or the guest rejects the call.

PluginSession::db_execute_streamed_binding_request

pub async fn db_execute_streamed_binding_request(
    &self,
    name: &str,
    request: AdapterExecuteRequest,
    limits: ExecuteStreamLimits,
    cancel: Arc<AtomicBool>,
) -> Result<ExecuteReply>

Typed AdapterDatabaseSession.executeStreamed on a named plugin database binding, collected into one reply under limits.

Errors

Returns a plugin error when the binding is not open, the adapter rejects the call or does not implement streaming, the frames break the budget, or cancel is set.

PluginSession::db_execute_binding_envelope_request

pub async fn db_execute_binding_envelope_request(
    &self,
    name: &str,
    envelope: AdapterExecuteRequest,
    cancel: Arc<AtomicBool>,
) -> Result<ExecuteReply>

Host-private envelope execute on a named plugin database binding.

Forwards bookclerk_plugin_abi::AdapterExecuteRequest so the adapter persists guest receipt payloads before COMMIT.

Errors

Returns a plugin error when the binding is not open, the guest rejects the call, or cancel is set.

PluginSession::db_capabilities

pub async fn db_capabilities(&self) -> Result<DbCapabilities>

Typed AdapterDatabaseSession.capabilities.

Errors

Returns a plugin error when the guest rejects the call.

PluginSession::db_bootstrap

pub async fn db_bootstrap(&self) -> Result<DbBootstrap>

Typed AdapterDatabaseSession.bootstrap.

Errors

Returns a plugin error when the guest rejects the call or lacks bootstrap.

PluginSession::db_execute_request

pub async fn db_execute_request(
    &self,
    request: AdapterExecuteRequest,
    cancel: Arc<AtomicBool>,
) -> Result<ExecuteReply>

Typed AdapterDatabaseSession.execute.

Errors

Returns a plugin error when the guest rejects the call or cancel is set.

PluginSession::db_execute_streamed_request

pub async fn db_execute_streamed_request(
    &self,
    request: AdapterExecuteRequest,
    limits: ExecuteStreamLimits,
    cancel: Arc<AtomicBool>,
) -> Result<ExecuteReply>

Typed AdapterDatabaseSession.executeStreamed, collected into one reply.

The vat thread decodes the adapter's frames as they arrive and stops with limit_exceeded as soon as the collected rows or bytes pass limits, so a runaway result never fully lands in host memory.

Errors

Returns a plugin error when the adapter rejects the call or does not implement streaming, the frames break the budget, or cancel is set.

PluginSession::db_execute_envelope_request

pub async fn db_execute_envelope_request(
    &self,
    envelope: AdapterExecuteRequest,
    cancel: Arc<AtomicBool>,
) -> Result<ExecuteReply>

Typed HostAdapterDatabaseSession.execute.

Errors

Returns a plugin error when the guest rejects the call or cancel is set.

PluginSession::db_txn_execute_request

pub async fn db_txn_execute_request(
    &self,
    request: AdapterExecuteRequest,
    cancel: Arc<AtomicBool>,
) -> Result<ExecuteReply>

Typed AdapterTransaction.execute on the vat-held open transaction.

Errors

Returns a plugin error when no transaction is open, the guest rejects the call, or cancel is set.

PluginSession::db_begin

pub async fn db_begin(&self, isolation: IsolationReq) -> Result<()>

Begin a vat-held transaction.

Errors

Returns a plugin error when begin fails.

PluginSession::db_commit

pub async fn db_commit(&self) -> Result<()>

Commit the vat-held transaction.

Errors

Returns a plugin error when commit fails.

PluginSession::db_rollback

pub async fn db_rollback(&self) -> Result<()>

Roll back the vat-held transaction.

Errors

Returns a plugin error when rollback fails.

PluginSession::db_begin_binding

pub async fn db_begin_binding(&self, name: &str, isolation: IsolationReq) -> Result<()>

Begin a transaction on a named plugin database binding.

Errors

Returns when the binding is not open or begin fails.

PluginSession::db_commit_binding

pub async fn db_commit_binding(&self, name: &str) -> Result<()>

Commit a named plugin database binding transaction.

Errors

Returns when no binding transaction is open or commit fails.

PluginSession::db_rollback_binding

pub async fn db_rollback_binding(&self, name: &str) -> Result<()>

Roll back a named plugin database binding transaction.

Errors

Returns when no binding transaction is open or rollback fails.

PluginSession::db_txn_execute_binding_request

pub async fn db_txn_execute_binding_request(
    &self,
    name: &str,
    request: AdapterExecuteRequest,
    cancel: Arc<AtomicBool>,
) -> Result<ExecuteReply>

Typed execute on the vat-held binding transaction.

Errors

Returns when no binding transaction is open or the guest rejects the call.

PluginSession::db_export_identity

pub async fn db_export_identity(
    &self,
    binding: Option<&str>,
) -> Result<Vec<DbIdentityHighWater>>

Identity high-water from the adapter (open txn if any).

Errors

Returns when the session is closed or the guest rejects the call.

PluginSession::db_import_identity

pub async fn db_import_identity(
    &self,
    binding: Option<&str>,
    rows: Vec<DbIdentityHighWater>,
) -> Result<()>

Restore identity high-water into the adapter.

Errors

Returns when the session is closed or the guest rejects the call.

PluginSession::db_list_user_relations

pub async fn db_list_user_relations(&self, binding: Option<&str>) -> Result<Vec<String>>

User-visible relation names from the adapter.

Errors

Returns when the session is closed or the guest rejects the call.

PluginSession::db_prepare_unit_restore

pub async fn db_prepare_unit_restore(&self, binding: Option<&str>) -> Result<()>

Prepare the open restore transaction.

Errors

Returns when the session is closed or the guest rejects the call.

PluginSession::db_drop_user_relations

pub async fn db_drop_user_relations(
    &self,
    binding: Option<&str>,
    names: Vec<String>,
) -> Result<()>

Drop named user relations.

Errors

Returns when the session is closed or the guest rejects the call.

PluginSession::db_assert_restore_constraints

pub async fn db_assert_restore_constraints(&self, binding: Option<&str>) -> Result<()>

Fail closed when restore FK checks still fail.

Errors

Returns when the session is closed or the guest rejects the call.

Implements: Drop

PluginStorage

pub struct PluginStorage {
    /* private fields */
}

StorageBackend over a plugin destination capability (streams, fail-closed scalars).

PluginStorage::new

pub fn new(session: Arc<PluginSession>) -> Self

Wraps a connected session after PluginSession::open granted the storage entrypoint.

Implements: Clone, StorageBackend

RpcBackupOps

pub struct RpcBackupOps {
    /* private fields */
}

Send-safe backup primitives over a vat-held adapter session (or its open txn).

RpcBackupOps::library

pub fn library(session: Arc<PluginSession>) -> Self

Library adapter session (no named binding).

RpcBackupOps::binding

pub fn binding(session: Arc<PluginSession>, name: impl Into<String>) -> Self

Named plugin-database binding (plugin_id/binding).

RpcBackupOps::shared

pub fn shared(self) -> SharedAdapterBackupOps

Shared handle stored on backup/restore options.

Implements: AdapterBackupOps

SessionServices

pub struct SessionServices {
    pub event_outbox: Option<LibraryStore>,
    pub spawn_transport: SpawnTransport,
    pub selected_instance_id: Option<String>,
    pub local_output_root: Option<PathBuf>,
    pub deployed_endpoint: Option<Option<String>>,
    pub sockets: Option<SocketBroker>,
    pub ai: Option<Arc<AiRouter>>,
    pub origin: Option<Arc<dyn Origin + Send + Sync>>,
    pub webhooks: Option<PluginInstanceId>,
}

Host services a session hands its guest as Bindings on every PluginWorker.open.

Nothing here is guest-visible on its own: the session still gates each binding on the manifest declaration plus the covering consent grant.

Fields

  • event_outbox: Library store whose outbox backs the EVENTS binding. None (the default) never exposes EVENTS, even to a granted producer.

  • spawn_transport: How the guest is reached. The default fronts every guest with bookclerk-workerd; SpawnTransport::DirectNativeDiagnostic is for tests and diagnostics only and no product binary selects it.

  • selected_instance_id: Plugin instance id selected by CLI scan or acquire.

    None uses the only instance document for a plugin key, or transitional file settings when that key has no document. Several documents require this id. An id selects only the plugin key it belongs to.

  • local_output_root: Writable root for a deployed local destination.

    Set from the deployed local destination's instance document; it is the jail write grant. None grants no output directory.

  • deployed_endpoint: Network authority from the deployed instance document: the S3 endpoint.

    Some(Some(url)) grants that host in addition to the manifest's fixed TCP list; Some(None) records that the document names none; None means this spawn is not a deployed instance of such a plugin.

  • sockets: The instance's socket broker, behind the SOCKETS binding.

    Owned by the deployment so sockets outlive the guest process. The session hands it out only when the manifest declares [sockets] and the covering grant has the sockets token; None never exposes SOCKETS.

  • ai: The node's model router, behind the AI binding.

    The session hands it out only when the manifest lists tasks under [ai].calls and the covering grant has the token of at least one; None never exposes AI.

  • origin: The library as a relay ingress plugin reaches it, behind the ORIGIN binding.

    The deployment sets it only for the library's active ingress instance. The session hands it out only when the manifest also exports ingress with [ingress] kind = "relay"; None never exposes ORIGIN.

  • webhooks: The deployed instance whose inbound webhooks back the WEBHOOKS binding. The session hands the binding out only when the manifest declares [[webhooks]], the covering grant has the webhooks token and the library store is attached; None never exposes WEBHOOKS.

SessionServices::with_event_outbox

pub fn with_event_outbox(store: LibraryStore) -> Self

Services with the library outbox attached.

SessionServices::from_outbox

pub fn from_outbox(store: Option<&LibraryStore>) -> Self

Services with the library outbox attached when store is present.

SessionServices::direct_native_diagnostic

pub fn direct_native_diagnostic() -> Self

Default services on the direct native diagnostic transport.

For shell-probe jail tests and transport benchmarks: the host speaks Cap'n Proto to the native guest's stdio with no bookclerk-workerd.

Implements: Clone, Default

InstanceSettingStatuses

pub struct InstanceSettingStatuses {
    pub instance_id: Option<String>,
    pub statuses: Vec<SettingGrantStatus>,
}

The network-setting statuses of one plugin instance.

Fields

  • instance_id: The instance; None when the plugin has no instance yet and the statuses judge the settings' defaults.
  • statuses: One status per network setting, in declaration order.

Implements: Clone, Debug, Eq, PartialEq

SettingGrantStatus

pub struct SettingGrantStatus {
    pub key: String,
    pub label: String,
    pub network: SettingNetwork,
    pub destination: Option<SettingDestination>,
    pub error: Option<SettingDestinationError>,
    pub state: SettingGrantState,
}

One network setting, the destination its value names, and its state.

Fields

  • key: The setting key.
  • label: The setting's label, falling back to the key.
  • network: Whether the value is fetched or dialed.
  • destination: The derived destination, when the value names one.
  • error: Why the value names no destination, for SettingGrantState::Invalid.
  • state: Where the grant stands.

Implements: Clone, Debug, Eq, PartialEq

BrokerSockets

pub struct BrokerSockets {
    /* private fields */
}

The SOCKETS binding a guest session hands out: the instance's broker.

BrokerSockets::new

pub fn new(broker: SocketBroker) -> Self

The binding for broker.

Implements: Sockets

SocketBroker

pub struct SocketBroker {
    /* private fields */
}

The host's handle on one plugin instance's socket broker.

Cheap to clone; every clone shares the broker. Dropping the last clone stops the broker process and its sockets.

SocketBroker::new

pub fn new(plugin: DiscoveredPlugin, config: Config) -> Self

A broker handle for plugin; nothing starts until the first connect.

Arguments
  • plugin - The deployed plugin; it must declare [sockets].
  • config - Host config for the broker's spawn.

SocketBroker::set_sink

pub fn set_sink(&self, sink: Weak<dyn SocketSink>)

Sets where socket events go. Only the first call takes effect.

The broker keeps a weak reference, so it never keeps a retired instance's proxy alive.

SocketBroker::open_sockets

pub fn open_sockets(&self) -> Vec<String>

Ids of the sockets the host believes open, oldest id first.

SocketBroker::connect

pub async fn connect(&self, request: SocketConnectRequest) -> AbiResult<SocketInfo>

Opens a socket, starting the broker when none runs.

Errors

The broker's refusal or dial failure, or unavailable when the broker cannot be started.

SocketBroker::send

pub async fn send(&self, socket: String, frame: SocketFrame) -> AbiResult<()>

Sends one message on an open socket.

Errors

not_found when the socket is not open; the broker's refusal.

SocketBroker::close

pub async fn close(&self, socket: String, code: u16, reason: String) -> AbiResult<()>

Closes a socket; closing an unknown or closed socket is not an error.

Errors

The broker's refusal of the code or reason.

SocketBroker::set_attachment

pub async fn set_attachment(&self, socket: String, attachment: Vec<u8>) -> AbiResult<()>

Replaces a socket's attachment.

Errors

not_found when the socket is not open; the broker's refusal.

SocketBroker::list

pub async fn list(&self) -> AbiResult<Vec<SocketInfo>>

The instance's open sockets, oldest first.

Errors

The broker's failure to answer.

Implements: Clone

SpawnPlan

pub struct SpawnPlan {
    pub launcher: PathBuf,
    pub args: Vec<String>,
    pub native_backend: Option<PathBuf>,
    pub workerd_bin: Option<PathBuf>,
    pub runtime: GuestRuntimeKind,
}

Everything the spawn path needs to start one guest.

Fields

  • launcher: Program the jail execs: bookclerk-workerd, or the native command on the diagnostic transport.
  • args: Arguments after launcher (manifest args; diagnostic transport only).
  • native_backend: Native executable the host spawns as the sibling guest. None for author isolates and direct native.
  • workerd_bin: Pinned workerd the launcher will spawn (must stay readable in the jail).
  • runtime: Process tree this plan produces.

SpawnPlan::resolve

pub fn resolve(plugin: &DiscoveredPlugin, transport: SpawnTransport) -> Result<Self>

Resolves the launch for plugin on transport using the host's front door.

Errors

Fails when the front door is required but bookclerk-workerd or the pinned workerd cannot be found, when a native manifest declares args (the launcher spawns the backend with none), or when a workerd manifest asks for the diagnostic transport.

SpawnPlan::resolve_with

pub fn resolve_with(
    plugin: &DiscoveredPlugin,
    transport: SpawnTransport,
    locate: impl FnOnce() -> Result<WorkerdFrontDoor>,
) -> Result<Self>

Self::resolve with an injected front-door locator (called only when the plan needs bookclerk-workerd).

Errors

Same as Self::resolve; locator failures are wrapped in the front-door refusal message.

SpawnPlan::fronted_by_workerd

pub fn fronted_by_workerd(&self) -> bool

True when bookclerk-workerd is the program the jail execs.

SpawnPlan::executable_reads

pub fn executable_reads(&self) -> Vec<PathBuf>

Executable paths the jail must let the launcher tree read and exec.

For GuestRuntimeKind::NativeBehindWorkerd this is the union of Self::gateway_executable_reads and Self::guest_executable_reads.

SpawnPlan::gateway_executable_reads

pub fn gateway_executable_reads(&self) -> Vec<PathBuf>

Paths the gateway jail may read to run: bookclerk-workerd, workerd and, when present, the pinned Pyodide bundle directory beside workerd, which Python isolates load at start because workerd has no network of its own.

Direct native uses the guest command as the (only) launcher.

SpawnPlan::guest_executable_reads

pub fn guest_executable_reads(&self) -> Vec<PathBuf>

Executables the native sibling jail may read (the backend only).

Implements: Clone, Debug, Eq, PartialEq

WorkerdFrontDoor

pub struct WorkerdFrontDoor {
    pub launcher: PathBuf,
    pub workerd_bin: PathBuf,
}

Resolved bookclerk-workerd launcher and the pinned workerd beside it.

Fields

  • launcher: bookclerk-workerd executable the jail execs.
  • workerd_bin: Pinned Cloudflare workerd the launcher spawns.

WorkerdFrontDoor::locate

pub fn locate() -> Result<Self>

Locates the front door for this host process.

Launcher: WORKERD_LAUNCHER_ENV when set (must be a file), else beside the current executable (or its deps/ parent for cargo test binaries), else on PATH. workerd: WORKERD_BIN_ENV when set (must be a file), else beside the launcher.

Errors

Returns an error naming what was looked for and where when either binary is missing.

WorkerdFrontDoor::locate_in

pub fn locate_in(dir: &Path) -> Result<Self>

Locates the front door looking only in dir (no environment overrides, no PATH). A test seam for missing-launcher planning.

Errors

Returns an error when dir lacks bookclerk-workerd or workerd.

Implements: Clone, Debug, Eq, PartialEq

HostWebhooks

pub struct HostWebhooks {
    /* private fields */
}

The WEBHOOKS hook of one session: the library, the deployed instance and the declared rows.

Implements: Clone, Webhooks

WebhookEndpoint

pub struct WebhookEndpoint {
    pub row: WebhookManifest,
    pub secret: Option<Zeroizing<Vec<u8>>>,
}

What the public route needs to check a request for one webhook of an instance this node runs.

Fields

  • row: The manifest's [[webhooks]] row.
  • secret: The row's signing secret, when its rule names one and the operator set it.

Implements: Clone, Debug

Enums

SpawnHealth

pub enum SpawnHealth {
    Healthy,
    SpawnFailed { detail: String },
    HealthFailed { detail: String },
}

Result of spawn plus the health RPC.

Variants

  • Healthy: Health succeeded.
  • SpawnFailed: The guest did not start. No config revision was applied.
    • detail: Bounded later by the observation writer.
  • HealthFailed: The guest started and health failed. The install tree stays.
    • detail: Bounded later by the observation writer.

Implements: Clone, Debug, Eq, PartialEq

StateScope

pub enum StateScope {
    Local,
    Link(LinkStateDir),
}

Whose library a guest works for, which keeps one library's plugin state apart from another's on the same install.

A branch runs the plugins of every library it joined beside its own. Two libraries can deploy the same plugin key, so the key alone cannot name the guest's state: each joined library gets its own subtree under plugin-state/, and this install's own guests keep the top level.

Variants

  • Local: This install's own library: plugin-state/<PluginKey fs-id>/.
  • Link: A library this install is a branch of: plugin-state/<link dir>/<PluginKey fs-id>/.

Implements: Clone, Debug, Default, Eq, PartialEq

PluginError

pub enum PluginError {
    Message(String),
    InstanceSelection(String),
    Conflict(String),
    NotFound(String),
    Unavailable(String),
    Io(Error),
    Json(Error),
    Toml(Error),
    Manifest(Error),
    Other(Error),
    RateLimited { message: String, retry_after: Option<Duration> },
    Abi { code: String, message: String },
}

Failures from discovery, RPC, consent, or plugin adapters.

Variants

  • Message: Operator-facing error text with no structured code.

  • InstanceSelection: Instance selection failed closed: missing, wrong plugin key, or ambiguous.

    Callers match this variant instead of the message text.

  • Conflict: The request conflicts with library state (an alias owned by another plugin, a version installed with different content).

  • NotFound: A plugin, version, or row the request names does not exist.

  • Unavailable: Backend or plugin transport is temporarily unreachable; retry the same idempotency key when the caller still holds consume-once material.

  • Io: Filesystem or process I/O failure.

  • Json: JSON encode/decode failure on the RPC wire or grant file.

  • Toml: TOML decode failure (settings tables, legacy paths).

  • Manifest: Invalid or unsupported plugin.toml / package manifest.

  • Other: Catch-all for otherwise unclassified failures.

  • RateLimited: The guest's backend asked it to slow down (ABI rate_limited); retry_after is how long it said, when it did.

    • message: Operator-facing explanation (which backend, which call).
    • retry_after: How long the backend asked to be left alone, when it said.
  • Abi: Guest ABI error with a preserved wire code (including unknown).

    • code: Wire error code (not_found, unknown, …).
    • message: Operator-facing explanation.

PluginError::message

pub fn message(msg: impl Into<String>) -> Self

Builds a PluginError::Message from any displayable string.

Arguments
  • msg - Operator-facing explanation; must not embed secrets.
Returns

A message-only PluginError.

PluginError::conflict

pub fn conflict(msg: impl Into<String>) -> Self

Builds a PluginError::Conflict.

PluginError::unavailable

pub fn unavailable(msg: impl Into<String>) -> Self

Builds a structured unavailable error (lost RPC, timeout, incomplete reply).

PluginError::instance_selection

pub fn instance_selection(msg: impl Into<String>) -> Self

Instance id, plugin key, or alias cannot select exactly one instance.

PluginError::is_instance_selection

pub fn is_instance_selection(&self) -> bool

True when spawn must stop instead of skipping this guest.

PluginError::from_abi

pub fn from_abi(code: Option<&str>, message: impl Into<String>) -> Self

Maps a guest ABI error, preserving unavailable so atomic retries can classify without string matching.

PluginError::is_ambiguous_transport

pub fn is_ambiguous_transport(&self) -> bool

True when an atomic-execute caller should retry the same operation id.

Relies on the structured Self::Unavailable variant (guest ABI unavailable, RPC timeout, or a closed guest) rather than matching D1 HTTP strings: permanent 4xx from D1 is internal / invalid_params.

Implements: Debug, Display, Error, From<Error>, From<PluginError>

DestinationSession

pub enum DestinationSession {
    Resident(Arc<PluginSession>),
    OnDemand(Arc<OnDemandStorage>),
}

A deployed destination's guest, as handed to a job that calls the guest's entrypoints directly.

Variants

  • Resident: A guest that is always running.
  • OnDemand: A guest that sleeps while idle; Self::lend starts it.

DestinationSession::lend

pub async fn lend(&self) -> Result<HeldSession, String>

The guest's session, starting the guest when it sleeps; it stays awake until the returned value is dropped.

Errors

Returns an error when an on-demand guest was retired or cannot start.

Implements: Clone

StorageRole

pub enum StorageRole {
    Destination,
    Intake,
}

What the host does with a deployed storage instance.

The role comes from the instance's core.intake document, read when the guest starts; the library refuses to change it while the instance is deployed (bookclerk_library::control_plane::set_intake).

Variants

  • Destination: An acquire destination: acquired books are written to it.
  • Intake: A drop folder: the host lists it and ingests what lands there, and never writes acquired books to it.

Implements: Clone, Copy, Debug, Eq, PartialEq

Activate

pub enum Activate {
    Always,
    IfNone,
    Never,
}

When installing moves the active pointer.

Variants

  • Always: Always point at the new version (update, --activate).
  • IfNone: Only when the plugin has no active version yet (first install).
  • Never: Never; install only.

Implements: Clone, Copy, Debug, Eq, PartialEq

RemoteApprovalError

pub enum RemoteApprovalError {
    NotRequested(String),
    Conflict(String),
    Invalid(String),
    Store(String),
}

Why approve_remote_request refused, by cause, so a caller (the operator API) can tell "review again" from "fix the input" from "retry later".

Variants

  • NotRequested: No request is recorded for that library and plugin.
  • Conflict: The recorded request is not the reviewed one (its digest differs), or it changed between the read and the write (the store's compare-and-swap), or an automatic approval met a revoke: review it again.
  • Invalid: The recorded request does not parse, the narrowing names something the request does not ask for, or a field is malformed.
  • Store: The store failed (a fault that may pass).

Implements: Debug, Display, Error, From<LibraryError>

RemoteConsentState

pub enum RemoteConsentState {
    Consented(Box<PluginGrant>),
    Pending,
    NeedsReapproval,
    Invalid,
}

How this host stands on one owner plugin's request.

Variants

  • Consented: Approved and the request is within what was reviewed: the guest runs with this grant.
  • Pending: Never approved (or revoked): waiting for the host's operator.
  • NeedsReapproval: Approved once, but the request now asks for more than was reviewed or names another archive.
  • Invalid: The request or the stored approval does not parse; nothing runs.

RemoteConsentState::grant

pub fn grant(&self) -> Option<&PluginGrant>

The grant to run with, when consented.

RemoteConsentState::as_str

pub fn as_str(&self) -> &'static str

Stable text for observations and listings.

Implements: Clone, Debug, Eq, PartialEq

SocketEvent

pub enum SocketEvent {
    Message(SocketMessage),
    Closed(SocketClosed),
}

What a socket delivered: a message, or its close.

Variants

  • Message: One message on an open socket.
  • Closed: The socket ended; nothing more arrives on it.

Implements: Clone, Debug, Eq, PartialEq

GuestRuntimeKind

pub enum GuestRuntimeKind {
    Workerd,
    NativeBehindWorkerd,
    NativeDirect,
}

Process tree the jail will contain, as reported in crate::ExecutorIdentity.

Variants

  • Workerd: bookclerk-workerd + the pinned workerd running author modules.
  • NativeBehindWorkerd: bookclerk-workerd + workerd (control plane) + the native guest.
  • NativeDirect: The native guest alone, spoken to directly (diagnostic transport).

GuestRuntimeKind::label

pub fn label(self) -> &'static str

Stable label used in executor identities and logs.

GuestRuntimeKind::process_overhead

pub fn process_overhead(self) -> u32

Payload occupancy before guest-owned children.

NativeDirect: the guest (1). Workerd: bookclerk-workerd plus the pinned workerd (2). NativeBehindWorkerd: gateway payload (2) plus the native guest (1) = 3. This count does not include the two bookclerk-jail supervisors. The Windows outer session Job adds those supervisors (crate::consent::WINDOWS_SESSION_PROCESS_BASELINE); Linux pids.max stays on a thread budget and must not reuse the Windows process total.

GuestRuntimeKind::fronted_by_workerd

pub fn fronted_by_workerd(self) -> bool

True when bookclerk-workerd is the program the jail execs.

GuestRuntimeKind::for_manifest

pub fn for_manifest(runtime: PluginRuntimeKind, transport: SpawnTransport) -> Self

Runtime kind a manifest resolves to under transport.

Implements: Clone, Copy, Debug, Eq, Hash, PartialEq

SpawnTransport

pub enum SpawnTransport {
    WorkerdFrontDoor,
    DirectNativeDiagnostic,
}

Which transport a spawn uses to reach the guest.

Variants

  • WorkerdFrontDoor: Product path: bookclerk-workerd fronts every guest, native or isolate.

  • DirectNativeDiagnostic: Host ↔ native Cap'n Proto on the guest's own stdio, no isolate.

    Diagnostic only: shell-probe jail tests and transport benchmarks. A runtime = "workerd" manifest cannot use it (there is no native guest to talk to) and the product binaries never select it.

Implements: Clone, Copy, Debug, Default, Eq, PartialEq

Functions

apply_grant_store

pub fn apply_grant_store(store: &PluginGrantStore)

Reconcile every live session against a loaded persisted grant store.

Missing keys and crate::grant_revision mismatches are fenced. Effective authority_revision (host overlays, clamped budgets) is not compared to the persisted digest. Host-config overlay changes fence through crate::ExecutorIdentity::configuration_revision.

authority_revision

pub fn authority_revision(grant: &PluginGrant) -> String

Canonical SHA-256 of security-relevant effective authority.

Hash the grant after manifest ∩ operator ∩ host policy and host-controlled overlays (TCP/CIDR implied by configured destinations, clamped budgets). Omits approved_at and display aliases except the PluginKey. Distinct from crate::grant_revision and crate::ExecutorIdentity::configuration_revision.

fence_plugin_key

pub fn fence_plugin_key(plugin_key: &str)

Fences every live session for plugin_key (grant/authority change).

fence_stale_grant_revisions

pub fn fence_stale_grant_revisions(plugin_key: &str, current_grant_revision: &str)

Fences live sessions whose persisted crate::grant_revision is not current.

fence_stale_sessions

pub fn fence_stale_sessions(plugin_key: &str, current_revision: &str)

Fences live sessions for plugin_key whose revision is not current_revision.

Pass an empty current_revision to fence every session for the key. Each fenced session is cancelled and its shutdown hook is invoked immediately (vat Work::Shutdown, which kills the child and mediated sockets). Hooks run after the live-table lock is released.

is_fenced

pub fn is_fenced(flag: &Arc<AtomicBool>) -> bool

True when this cancel flag has been fenced.

live_session_count

pub fn live_session_count() -> usize

Sessions currently registered with the process-wide authority table.

notify_grants_changed

pub fn notify_grants_changed()

Wake the grant watcher in this process (same-process save / tests).

Cross-process CLI writes are observed by polling the grants file.

reconcile_grants_from_disk

pub fn reconcile_grants_from_disk(files_dir: &Path)

Load plugin-grants.json and fence sessions that no longer match.

Unreadable / malformed files are left untouched for this tick so a torn write cannot mass-fence. PluginGrantStore::save writes atomically.

register_session

pub fn register_session(plugin_key: &str, revision: &str) -> Arc<AtomicBool>

Registers a live session and returns its cancel flag.

Drop the session (or call unregister_session) when the vat exits. Sessions registered this way are still cancelled on grant change, but have no shutdown hook — prefer register_session_with_shutdown for product vats so fencing does not wait for the next RPC.

register_session_revisions

pub fn register_session_revisions(
    plugin_key: &str,
    grant_revision: &str,
    revision: &str,
    shutdown: SessionShutdown,
) -> Arc<AtomicBool>

Registers a live session with distinct persisted vs effective revisions.

grant_revision is the digest of the stored operator grant. revision is authority_revision of the effective runtime grant (after host overlays). The grant watcher compares grant revisions only.

register_session_with_shutdown

pub fn register_session_with_shutdown(
    plugin_key: &str,
    revision: &str,
    shutdown: SessionShutdown,
) -> Arc<AtomicBool>

Registers a live session whose shutdown hook runs the instant it is fenced.

Call this after the vat work channel exists so shutdown can send Work::Shutdown without racing spawn.

spawn_grant_watcher

pub fn spawn_grant_watcher(files_dir: PathBuf) -> Arc<AtomicBool>

Spawn the daemon grant watcher (fire-and-forget).

Returns

Stop flag; set it to end the loop (tests). Production callers leak the task until process exit.

unregister_session

pub fn unregister_session(flag: &Arc<AtomicBool>)

Drops a previously registered cancel flag from the live set.

watch_grants_loop

pub async fn watch_grants_loop(files_dir: PathBuf, stop: Arc<AtomicBool>)

Watch plugin-grants.json until the process exits.

In-process notify_grants_changed wakes immediately; CLI writes in another process are picked up within GRANT_WATCH_INTERVAL.

install_bundled_platform_plugins

pub async fn install_bundled_platform_plugins(files_dir: &Path)

Installs bundled platform plugins from beside the running executable into files_dir.

A no-op when no plugins/ directory sits beside the executable (development builds) or this process already tried files_dir. The hashing and copying run on the blocking pool. Failures are logged and do not stop startup: discovery then reports the missing or untrusted plugin the same way it would without a bundle.

When something has to be installed the sync takes the files directory's bookclerk_plugin_catalog::PluginMutationLock, so the first call for a files directory must not run while this process holds that lock.

Arguments

  • files_dir - Host $BOOKCLERK_FILES_DIR that owns plugins/ and the install ledger.

active_processes_for

pub fn active_processes_for(runtime: GuestRuntimeKind, extra: u32) -> u32

Absolute Spec active_processes from runtime overhead + extra budget.

ai_task_grant

pub fn ai_task_grant(task: AiTask) -> String

Grant token for running models of task through the AI binding.

canonical_event_filter

pub fn canonical_event_filter(filter: &Option<Value>) -> Option<String>

Minified JSON for an event filter; null / missing → None.

pub fn consent_request(manifest: &PluginManifest, plugin_key: &PluginKey) -> PluginGrant

Build the consent request surface from a manifest and its PluginKey.

pub fn consent_request_alias(manifest: &PluginManifest) -> PluginGrant

Build the consent request surface from a manifest (alias only; tests).

pub fn consent_summary(grant: &PluginGrant) -> Vec<String>

Human-readable consent lines for CLI/UI.

consumers_cover

pub fn consumers_cover(
    existing: &BTreeSet<GrantedEventConsumer>,
    requested: &BTreeSet<GrantedEventConsumer>,
) -> bool

True when every requested consumer is covered by some approved consumer.

cores_to_percent

pub fn cores_to_percent(cores: f64) -> u32

Convert cores to Spec/config percent-of-one-core, rounded to 0.01 core.

cron_grant

pub fn cron_grant(cron: &str) -> String

Grant token for firing the normalized cron schedule cron.

database_binding_name

pub fn database_binding_name(binding: &str) -> Option<&str>

The binding name when a grant entry is a named database binding.

effective_cpu_cores

pub fn effective_cpu_cores(value: Option<f64>) -> f64

Clamp operator/manifest cores into 0.01..=host_cpu_cores_max.

effective_cpu_rate_percent

pub fn effective_cpu_rate_percent(value: Option<u32>) -> u32

Resolved jail Spec CPU rate as percent of one logical CPU.

Clamped to 1..=host_cpu_rate_max (100 × logical CPUs).

effective_disk_budget_bytes

pub fn effective_disk_budget_bytes(grant: Option<&PluginGrant>) -> u64

Resolved disk budget in bytes for data/ and tmp/ checks.

effective_disk_mib

pub fn effective_disk_mib(value: Option<u32>) -> u32

Resolved disk budget in MiB (default + host clamp).

effective_extra_processes

pub fn effective_extra_processes(value: Option<u32>) -> u32

Clamp an operator/manifest extra-process budget (0..=PLUGIN_JAIL_EXTRA_PROCESSES_MAX).

effective_grant

pub fn effective_grant(existing: &PluginGrant, requested: &PluginGrant) -> PluginGrant

Spawn/delivery grant: stored approval is authoritative, host-normalized.

Structural capabilities stay at the stored operator snapshot (narrowed). Network destinations re-evaluate the current manifest against the stored approval plus persisted operator additions/denials: the manifest can drop a destination but never add one the operator did not approve, and undeclared public redirects follow the manifest only while the stored grant allows them.

effective_memory_mib

pub fn effective_memory_mib(value: Option<u32>) -> u32

Resolved jail Spec memory ceiling in MiB.

format_cpu_cores

pub fn format_cpu_cores(cores: f64) -> String

Format cores for operator-facing text (0.80).

grant_covers

pub fn grant_covers(existing: &PluginGrant, requested: &PluginGrant) -> bool

True when a stored grant is usable for enable/spawn of this PluginKey.

Identity match is enough. Extra capabilities on a newer manifest stay pending until the operator approves them; effective_grant intersects.

grant_has_binding

pub fn grant_has_binding(grant: &PluginGrant, name: &str) -> bool

True when grant.bindings contains name (case-insensitive).

grant_revision

pub fn grant_revision(grant: &PluginGrant) -> String

Canonical SHA-256 of a grant's security-relevant fields (not presentation).

grant_within_ceiling

pub fn grant_within_ceiling(existing: &PluginGrant, requested: &PluginGrant) -> bool

True when an existing grant stays within the manifest request surface.

Used for platform auto-grants (installer envelope). Operator approvals are not limited to this subset — see validate_approved_grant.

granted_consumers_from_manifest

pub fn granted_consumers_from_manifest(
    manifest: &PluginManifest,
) -> BTreeSet<GrantedEventConsumer>

Consumers declared by plugin.toml as structural grant entries.

granted_database_bindings

pub fn granted_database_bindings(grant: &PluginGrant) -> Vec<String>

Consented database binding names on a grant, in manifest-set order.

granted_jobs_from_manifest

pub fn granted_jobs_from_manifest(manifest: &PluginManifest) -> BTreeSet<String>

Job trigger types declared by [triggers].jobs.

granted_queue_consumers

pub fn granted_queue_consumers(grant: &PluginGrant) -> Vec<String>

Consented queue consumer names on a grant.

host_cpu_cores_max

pub fn host_cpu_cores_max() -> f64

Host max jail CPU in cores (logical_cpus as a 2 d.p. float).

host_cpu_rate_max

pub fn host_cpu_rate_max() -> u32

Host CPU rate ceiling in one-core percent units (logical_cpus × 100).

host_overlay_config_digest

pub fn host_overlay_config_digest(config: &Config) -> String

SHA-256 of host config that participates in implied network overlays.

Changing a Postgres URL or D1 API origin must mint a new executor configuration_revision and fence live sessions. Plugin endpoints (the S3 endpoint) come from instance documents, not config.toml.

inject_workerd_grant_env

pub fn inject_workerd_grant_env(cmd: &mut Command, grant: &PluginGrant)

Injects effective-grant overrides for bookclerk-workerd into a guest command.

Must be called after env_clear (explicit BOOKCLERK_* is blocked from inheritance). Domains are always set (possibly empty) so a subset approval cannot fall back to the full manifest allowlist.

Arguments

  • cmd - Guest process command being prepared for spawn.
  • grant - Effective covering grant for this plugin.

is_platform_envelope

pub fn is_platform_envelope(grant: &PluginGrant) -> bool

True when grant stays inside the platform installer envelope (deny network, only config / work_fs bindings): the request a Bookclerk platform plugin may receive without the operator being asked.

jail_process_overhead

pub fn jail_process_overhead(runtime: GuestRuntimeKind) -> u32

Fixed payload occupancy for the launcher / primary guest tree.

Workerd isolate: bookclerk-workerd plus the workerd child (2). Native behind workerd: those two plus the native guest (3). Direct native (diagnostic transport): the guest (1). The Windows outer Job adds the two jail supervisors on top of the native-behind payload; see WINDOWS_SESSION_PROCESS_BASELINE.

network_compatible

pub fn network_compatible(existing: &str, requested: &str) -> bool

Returns true when a stored network mode can satisfy a requested network mode.

Arguments

  • existing - Network mode already approved by the operator.
  • requested - Network mode requested by the current plugin manifest.

Returns

true when the modes match, or when an existing deny grant is stricter than a requested outbound grant.

node_logical_cpus

pub fn node_logical_cpus() -> u32

Logical CPUs visible to this process (at least 1).

overlay_host_implied_network

pub fn overlay_host_implied_network(
    grant: &mut PluginGrant,
    plugin: &DiscoveredPlugin,
    config: &Config,
    discovered: &[DiscoveredPlugin],
)

Overlay TCP + CIDR implied by host configuration (not persisted).

Not operator-invented structural authority. The operator already configured the destination URL; spawn injects matching EgressPolicy so the nested native guest can connect() it. Covers:

  • active Postgres [database.postgres].url
  • active D1 [database.d1].api_base
  • S3 [output.s3].endpoint (custom/MinIO)

Occupancy is uniquified with [crate::resolve_plugin_slot]: a bare alias overlays only the unique occupant, and a PluginKey never overlays a twin.

No-op unless the covering grant is outbound.

Arguments

  • grant - Effective covering grant (mutated in place).
  • plugin - Guest being spawned.
  • config - Host config (URL already env-applied).
  • discovered - Installs used to uniquify occupancy (must include plugin).

pending_structural

pub fn pending_structural(
    existing: &PluginGrant,
    requested: &PluginGrant,
) -> PendingStructural

Structural capabilities the current manifest requests that the stored grant does not yet authorize.

percent_to_cores

pub fn percent_to_cores(percent: u32) -> f64

Convert Spec/config percent-of-one-core (100 = 1.00 core) to cores (2 d.p.).

queue_consumer_grant

pub fn queue_consumer_grant(queue: &str) -> String

Grant token for consuming queue.

queue_producer_grant

pub fn queue_producer_grant(binding: &str) -> String

Grant token for sending through the [[queues.producers]] binding binding.

reapprove_grant

pub fn reapprove_grant(
    existing: &PluginGrant,
    requested: &PluginGrant,
) -> Result<PluginGrant>

Re-approves the current request on top of a stored grant, keeping the operator's earlier answers.

This is what accepting the web consent dialog unchanged does, for a caller with no dialog (bookclerk plugins approve):

  • Structural capabilities (entrypoints, producers, consumers, jobs, bindings, compatibility flags) are what the current version declares.
  • Network destinations are the request's, minus the destinations the operator denied, plus the ones they added (operator_denied_* / operator_added_*, rebuilt for legacy grants as effective_grant does). A TCP denial removes the denied ports of that host.
  • Network mode stays deny when the operator turned network off for a version that asked for destinations; otherwise it is the request's.
  • The operator's redirect answer and the own User-Agent hosts they refused stay answered; a host the request newly declares is approved.
  • Budgets are the request's: a grant cannot tell a budget the operator chose from one it inherited, and a new version may need more.

The draft then goes through validate_approved_grant, so the stored operator_* sets are recomputed against the current request.

Arguments

  • existing - The stored grant for this PluginKey.
  • requested - Consent request generated from the current manifest.

Returns

The normalized grant to store.

Errors

Returns PluginError when the draft fails validate_approved_grant (for example a stored addition is no longer a valid pattern).

reconcile_host_overlay_authority

pub fn reconcile_host_overlay_authority(config: &Config)

Recomputes effective overlay authority and fences sessions that no longer match.

Host-config destination changes do not touch plugin-grants.json, so the grant watcher cannot see them. Config reload must call this.

A deployed S3 session is recomputed with the document endpoint recorded at registration. That path does not read [output.s3].endpoint, so a settings reload cannot cancel an in-flight upload because the TOML endpoint differs or is unset. Transitional sessions still overlay the TOML endpoint.

A revision mismatch fences that session only. Several vats may share one PluginKey with different effective revisions, and cancelling the key would kill a deployed upload when a transitional session's TOML endpoint changes.

require_binding

pub fn require_binding(grant: &PluginGrant, name: &str) -> Result<()>

Fail closed when a delivery site needs a binding the covering grant lacks.

Errors

Returns an error when the operation fails.

require_grant

pub fn require_grant(files_dir: &Path, plugin: &DiscoveredPlugin) -> Result<PluginGrant>

Require an operator grant before enable or every external spawn.

Arguments

  • files_dir - Bookclerk files directory containing plugin-grants.json.
  • manifest - Plugin manifest whose id must have a stored grant.

Returns

Effective PluginGrant (operator approval, host-normalized).

Errors

Returns PluginError when no grant exists for the plugin id.

spawn_config_for_grant

pub fn spawn_config_for_grant(grant: &PluginGrant, config_table: Value) -> Value

Spawn config payload: non-empty settings only when the grant includes config.

spawn_grant

pub fn spawn_grant(files_dir: &Path, plugin: &DiscoveredPlugin) -> Result<PluginGrant>

Resolve the covering grant for spawn: verified platform auto-grant, else require_grant.

Errors

Returns an error when the operation fails.

validate_approved_grant

pub fn validate_approved_grant(
    approved: &PluginGrant,
    baseline: &PluginGrant,
) -> Result<PluginGrant>

Validates and normalizes an operator-supplied grant against host hard caps.

The manifest baseline supplies identity defaults and suggested values. Operators may narrow structural capabilities (entrypoints, producers, host bindings, flags) and widen or narrow network destinations. Inventing a structural capability the package did not declare is rejected. Workerd / disk limits clamp to host maximums.

Arguments

  • approved - Operator-supplied grant draft.
  • baseline - Consent request generated from the current manifest.

Returns

A normalized grant with plugin identity and a fresh approved_at.

Errors

Returns PluginError when identity mismatches, network mode is invalid, a binding is unknown, or a domain pattern cannot be normalized.

Panics

Panics when an internal invariant does not hold.

validate_described_capabilities

pub fn validate_described_capabilities(
    manifest: &PluginManifest,
    grant: &PluginGrant,
    described: &PluginCapabilities,
    portal_auth_mode: PortalAuthMode,
) -> Result<()>

Reject describe() capability claims that exceed the manifest and the covering grant.

The guest's typed PluginCapabilities must not widen what plugin.toml declares: no extra entrypoints, event consumers, producers, job types, database bindings, or named bindings. Every advertised entrypoint and producer must also be present in the operator grant, and OAuth storefronts need the oauth binding.

Arguments

  • manifest - Installed manifest for the plugin.
  • grant - Effective covering grant.
  • described - Capability block the guest returned from describe().
  • portal_auth_mode - Storefront connect mode from describe().

Errors

Returns an error naming the first widening capability or missing grant.

validate_described_config_options

pub fn validate_described_config_options(
    manifest: &PluginManifest,
    described: &[ConfigOption],
) -> Result<()>

Validates describe().configOptions against the manifest [[settings]].

The manifest is the authority for the settings a plugin takes. An empty list means the guest defers to the manifest. A non-empty list must name the same keys with the same enum value ids (labels may differ), so a guest cannot widen or narrow its own writable keys at runtime.

Arguments

  • manifest - Installed manifest for the plugin.
  • described - configOptions the guest returned from describe().

Errors

Returns an error naming the first key or value that differs.

validate_described_media

pub fn validate_described_media(
    manifest: &PluginManifest,
    described: &PluginDescribe,
) -> Result<()>

Checks the media a guest's describe() returns against its manifest.

The manifest's [media] table is the authority: the host routes work to sleeping plugins from it without spawning them, so a guest may neither widen nor narrow it at runtime. The described declaration must name the same kinds (order and repeats ignored) and pass the same rules the manifest does.

Arguments

  • manifest - Installed manifest for the plugin.
  • described - The guest's describe() reply.

Errors

Returns an error when the declaration differs from [media] or breaks a declaration rule (empty for a storefront or metadata provider, names unspecified, fetches a carrier it does not list).

windows_session_active_processes

pub fn windows_session_active_processes(extra: u32) -> u32

Windows outer session Job active-process cap: baseline 5 plus extra.

extra is clamped to PLUGIN_JAIL_EXTRA_PROCESSES_MAX. The sum is clamped to PLUGIN_JAIL_ACTIVE_PROCESSES_MAX. Inner jail caps are not inflated by this baseline: the gateway stays at 2 and the guest stays at 1 plus the same extra budget.

search_crates_io

pub fn search_crates_io(
    query: Option<&str>,
    per_page: u32,
) -> Result<Vec<PluginCatalogEntry>>

Search crates.io for Bookclerk plugins.

Uses keyword REGISTRY_KEYWORD plus optional free text, then keeps hits whose crate name starts with CRATE_NAME_PREFIX and parses cleanly.

Errors

Returns an error when the operation fails.

load_authorized_local_packages

pub fn load_authorized_local_packages(files_dir: &Path) -> Result<AuthorizedLocalPackages>

Loads operator-placed archives under $FILES_DIR/plugin-packages/<name>/.

Each directory holds package.json (a BookclerkPackageManifest) and archive.tar.gz. Artifact URLs must be file: paths inside that directory. The reconciler does not download plugins. A missing directory is an empty map.

Errors

Returns an error when plugin-packages itself cannot be read. One bad package is skipped and does not abort the rest of the directory.

reconcile_local_deployments

pub async fn reconcile_local_deployments(
    store: &LibraryStore,
    config: &Config,
    node_id: &str,
    packages: &AuthorizedLocalPackages,
    runtime: &dyn DeploymentRuntime,
) -> Result<()>

Reconciles every present deployment for node_id.

Errors

Returns an error when the deployment list cannot be read. A single row's install, spawn, or observation failure is stored on that row and does not stop the others.

build_acquire_destinations

pub fn build_acquire_destinations(
    config: &Config,
    destinations: &DestinationRegistry,
    filters: &BTreeMap<String, DestinationFilter>,
) -> Result<AcquireDestinations>

Build destination backends for acquire from the deployed output plugins.

Every deployed storage plugin instance is a destination, in id order, and the first destination is the primary.

Arguments

  • config - The host's configuration, for download options.
  • destinations - The deployed destinations.
  • filters - Stored destination filters by plugin instance id (bookclerk_library::control_plane::destination_filters), or an empty map when the caller sets them later; a destination without one takes every book.

Errors

Returns an error when no destination is deployed on this host.

build_storage_backend

pub fn build_storage_backend(
    destinations: &DestinationRegistry,
) -> Result<Box<dyn StorageBackend>>

Build listing/storage backends from the deployed output plugins.

Errors

Returns an error when no destination is deployed.

discover_plugins

pub fn discover_plugins(config: &Config) -> Result<Vec<DiscoveredPlugin>>

Discover plugins under the configured search directories.

Accepts either:

  • $dir/plugin.toml (single plugin at root), or
  • $dir/<name>/plugin.toml (one plugin per subdirectory).

Duplicate PluginKey values are a hard error. Duplicate aliases from different PluginKeys are also a hard error (invalid installation state).

Errors

Returns PluginError on duplicate keys, duplicate aliases, missing binaries, or I/O failures.

first_party_database_kind

pub fn first_party_database_kind(plugin: &DiscoveredPlugin) -> Option<DatabasePluginKind>

First-party database adapter kind when provenance + PluginKey match.

PlatformBundled (platform sqlite) and VerifiedStaged (crates.io / platform postgres and D1) both qualify. LocalDevelopment and Modified never do. Alias text (id = "sqlite") is not consulted.

identity_matches_occupancy

pub fn identity_matches_occupancy(plugin_key: &str, alias: &str, spec: &str) -> bool

True when plugin_key / alias is the occupant named by spec.

A parseable PluginKey never falls through to an alias comparison, so a miss cannot inherit another provenance's grant or session. Does not detect corrupt duplicate aliases — callers that load or privilege-check must require a unique match (resolve_plugin_slot).

Arguments

  • plugin_key - Canonical PluginKey text.
  • alias - Manifest display id.
  • spec - Occupancy selector from occupancy_spec or a job/CLI id.

is_first_party_local_output

pub fn is_first_party_local_output(plugin: &DiscoveredPlugin) -> bool

True when this install is the verified Bookclerk local-filesystem destination.

is_first_party_local_output_key

pub fn is_first_party_local_output_key(key: &PluginKey) -> bool

True when key names the Bookclerk local-filesystem destination.

This is the key half of [is_first_party_local_output]: it does not see an install, so it cannot check provenance. Use it only where matching more plugins than the verified one is safe, such as routing acquires to the nodes that hold their output disks when discovery is unavailable.

Arguments

  • key - Durable plugin identity to classify.

Returns

true for the first-party local destination package on a first-party provenance scheme.

is_first_party_s3_output

pub fn is_first_party_s3_output(plugin: &DiscoveredPlugin) -> bool

True when this install is the verified Bookclerk S3 destination.

occupancy_matches_alias

pub fn occupancy_matches_alias(spec: &str, alias: &str) -> bool

True when occupancy spec names the display alias (or kind token) alias.

Bare kind tokens (pg ↔ postgres) match without discovery. A PluginKey occupant matches only when it is a host-controlled first-party package whose package name maps to that alias — never via a #fragment. Third-party keys need occupancy_names_alias plus discovery.

A bare alias does not match a PluginKey string passed as alias.

Arguments

  • spec - Occupancy selector from config (plugin = "…").
  • alias - Display alias or first-party kind token being compared.

occupancy_names_alias

pub fn occupancy_names_alias(
    spec: &str,
    alias: &str,
    discovered: &[DiscoveredPlugin],
) -> bool

True when occupancy spec names alias among discovered installs.

Uses occupancy_matches_alias first, then resolves spec to exactly one PluginKey. Corrupt duplicate aliases fail closed (false).

occupancy_spec

pub fn occupancy_spec<'a>(plugin_field: &'a str, alias: &'a str) -> &'a str

Config occupancy selector (plugin = "…"), or alias when the field is empty.

Occupancy is how host config names the guest that may use a singleton slot ([database].plugin, [output.s3].plugin, [sources.<id>].plugin). An empty field still means the display alias, which resolve_plugin_slot accepts only when exactly one install uses it.

Arguments

  • plugin_field - Occupancy string from config (plugin = "…").
  • alias - Display alias used when plugin_field is empty.

plugin_matches_occupancy

pub fn plugin_matches_occupancy(plugin: &DiscoveredPlugin, spec: &str) -> bool

True when plugin is the occupant named by spec (PluginKey or alias).

Does not detect corrupt duplicate aliases — loaders must call resolve_plugin_slot.

Arguments

  • plugin - Candidate install.
  • spec - Occupancy selector from occupancy_spec.

plugin_search_dirs

pub fn plugin_search_dirs(config: &Config) -> Vec<PathBuf>

Resolve search roots: BOOKCLERK_PLUGIN_DIRS then $FILES_DIR/plugins.

resolve_plugin_ref

pub fn resolve_plugin_ref<'a>(
    plugins: &'a [DiscoveredPlugin],
    spec: &str,
) -> Result<&'a DiscoveredPlugin>

Resolves spec to a discovered plugin.

spec may be a canonical PluginKey or an alias unique in this host plugin namespace. In valid installed state an alias maps to exactly one PluginKey. Duplicate aliases fail closed rather than picking first or last.

Errors

Returns an error when spec matches nothing, or when corrupt disk state contains duplicate keys or aliases.

resolve_plugin_slot

pub fn resolve_plugin_slot<'a>(
    plugins: &'a [DiscoveredPlugin],
    spec: &str,
) -> Result<Option<&'a DiscoveredPlugin>>

Resolves spec among plugins without treating a vacant slot as an error.

None means nothing installed matches. An ambiguous alias is an error so callers fail closed instead of spawning every twin or last-write-wins.

Arguments

  • plugins - Already-filtered family candidates.
  • spec - Occupancy selector from occupancy_spec.

Errors

Returns PluginError when two installs share the alias (or PluginKey).

settings_table

pub fn settings_table(config: &Config, plugin: &DiscoveredPlugin) -> Table

Bootstrap connection settings for a database adapter from config.toml.

Database adapters are the one plugin family whose configuration stays in the bootstrap file: the process needs it to open the library before the database-backed control plane exists. Every other family receives its settings from the plugin instance document.

settings_table_for

pub fn settings_table_for(
    config: &Config,
    plugin: &DiscoveredPlugin,
    family: PluginFamily,
) -> Table

settings_table for one explicit handler family.

Only PluginFamily::Database has a config.toml table; every other family returns an empty table.

stamp_occupancy_plugin_key

pub fn stamp_occupancy_plugin_key(
    config: &mut Config,
    plugin: &DiscoveredPlugin,
) -> Result<()>

Records plugin as the [database].plugin occupant.

Database adapters are the bootstrap exception: they stay selected in config.toml because the connection is needed before the database can be read. Every other plugin is enabled by a plugin_deployments row.

Errors

Returns an error when plugin is not a database adapter.

upgrade_unique_alias_occupancy

pub fn upgrade_unique_alias_occupancy(
    config: &mut Config,
    discovered: &[DiscoveredPlugin],
)

Rewrites a unique [database].plugin alias to the canonical PluginKey.

An ambiguous alias or vacant slot is left unchanged so loaders still fail closed. An empty discovered slice is a no-op so a settings discovery timeout cannot wipe occupancy.

enroll_local_plugins

pub async fn enroll_local_plugins(
    store: &LibraryStore,
    config: &Config,
    node_id: &str,
) -> Result<Vec<EnrolledPlugin>>

Enrolls every discovered plugin on node_id.

A plugin that fails to enroll is logged and skipped so one bad install does not keep the others from starting.

Errors

Returns an error when discovery or the grant store cannot be read.

enroll_one

pub async fn enroll_one(
    store: &LibraryStore,
    node_id: &str,
    plugin: &DiscoveredPlugin,
    grants: &PluginGrantStore,
) -> Result<EnrolledPlugin>

Enrolls one discovered plugin. See the module docs for the steps.

Errors

Returns an error when a schema, instance, document, or deployment write fails.

has_covering_grant

pub fn has_covering_grant(plugin: &DiscoveredPlugin, grants: &PluginGrantStore) -> bool

True when the operator already consented to this plugin, or it is a verified platform guest that grants itself on first spawn.

is_bootstrap_only

pub fn is_bootstrap_only(plugin: &DiscoveredPlugin) -> bool

True when the plugin is a database adapter and nothing else: those stay bootstrap ([database] in config.toml) in this phase.

granted_event_subscriptions

pub fn granted_event_subscriptions(
    catalog: &[EventCatalogSubscription],
    admitted: &BTreeSet<GrantedEventConsumer>,
) -> Vec<EventCatalogSubscription>

Keeps the catalog rows an operator grant admits.

A row is admitted when a granted consumer has its type, covers all its schema versions, and carries the same canonical filter; suspend support is kept only when both sides allow it.

manifest_event_subscriptions

pub fn manifest_event_subscriptions(
    manifest: &PluginManifest,
) -> Vec<EventCatalogSubscription>

Catalog rows for a manifest's [[events.consumers]] declarations, before consent narrows them.

backup_adapter_id

pub fn backup_adapter_id(plugin_id: &str) -> String

Adapter id recorded on a backup (diagnostic; restore is capability-driven).

database_connect_bindings

pub fn database_connect_bindings(
    config: &Config,
    plugin: &DiscoveredPlugin,
    session: &PluginSession,
) -> Result<BindingValues>

Builds the bookclerk_plugin_sdk::BindingValues for the adapter's PluginWorker.open (then databaseAdapter.openSession).

Used by the CLI diagnose probe and mirrors ExternalDatabase::connect.

Errors

Returns an error when plugin data paths, secrets, or context encoding fail.

export_registered_plugin_units

pub async fn export_registered_plugin_units(
    ext: &ExternalDatabase,
    config: &Config,
    library: &DatabaseConnection,
) -> Result<Vec<PreparedPluginUnit>>

Exports every registered plugin-owned database binding as SeaORM sessions.

A missing plugin_databases table (uninitialized library) is treated as an empty registry. Fails closed if any registered binding cannot be opened.

Errors

Returns when a binding is inaccessible.

load_external_database

pub async fn load_external_database(config: &Config) -> Result<DatabaseRegistry>

Discover and spawn the external database plugin matching [database].plugin.

Platform plugins bundled beside the host executable are installed into the files directory first (crate::install_bundled_platform_plugins).

Guests are required: when the matching database plugin is missing or fails to start, open_library_store returns an error (no in-process engine).

Errors

Returns an error when the operation fails.

migrate_database_plugin

pub async fn migrate_database_plugin(
    config: &Config,
    from_plugin: &str,
    to_plugin: &str,
    opts: &BackendMigrateOptions,
) -> Result<BackendMigrateSummary>

Copy library data from one database plugin backend to another.

Errors

Returns an error when the operation fails.

migrate_library_schema

pub async fn migrate_library_schema(
    config: &Config,
    target: i64,
    opts: SchemaApplyOptions,
) -> Result<SchemaWalk>

Opens the active database guest without auto-apply and migrates to target.

Uses guest executeAtomic batches (the same path as daemon connect).

Errors

Returns when the guest cannot start, connect, or apply schema.

open_library_store

pub async fn open_library_store(
    config: &Config,
    registry: &DatabaseRegistry,
) -> Result<LibraryStore>

Open bookclerk_library::LibraryStore via the external database guest (required).

Errors

Returns an error when the operation fails.

open_library_store_for_plugin

pub async fn open_library_store_for_plugin(
    config: &Config,
    plugin_id: &str,
) -> Result<LibraryStore>

Open the library for a specific [database].plugin id (ignoring the active config value).

Errors

Returns an error when the operation fails.

restore_plugin_backup_units

pub async fn restore_plugin_backup_units(
    ext: &ExternalDatabase,
    config: &Config,
    library: &DatabaseConnection,
    repo: &BackupRepository,
    units: &[BackupUnit],
) -> Result<()>

Restores plugin binding units onto the current adapter.

Each unit is replaced independently. A later failure leaves earlier units already replaced (no cross-database atomicity). Plugin migrations are not run; version rows restore as captured data. Registry rows are rebound to the target adapter's physical placement.

Each open_binding_seaorm session must itself advertise atomicUnitRestore. Restore binds, payload, and request limits come from that session.

Errors

Returns when provisioning or canonical restore fails. Partial completion is reported in the error message.

storage_role

pub async fn storage_role(
    store: &LibraryStore,
    plugin_instance_id: &str,
) -> Result<StorageRole>

Reads the role of the storage instance plugin_instance_id.

Errors

Returns an error when the instance's core.intake document cannot be read or is invalid; the guest is then not published, rather than published as a destination a drop folder's settings may have meant to keep acquired books out of.

allow_credential_login

pub fn allow_credential_login(granted_config: &Value) -> bool

allow_credential_login from the resolved CONFIG; absent means allowed.

enroll_node

pub async fn enroll_node(config: &Config, store: &LibraryStore) -> Result<NodeEnrollment>

Bootstraps the control plane on an open library and enrolls every local plugin, without loading any guest.

The daemon's config reload uses this: guests stay with the deployment reconciler, which picks up the enrolled deployments on its next pass.

Errors

Returns an error when the secret root or node identity cannot be established, or enrollment fails as a whole.

open_host_control_plane

pub async fn open_host_control_plane(config: &Config) -> Result<HostControlPlane>

Opens the library database and the control plane for config.

Errors

Returns an error when the database cannot be opened, the secret root or node identity cannot be established, or enrollment fails as a whole.

open_host_control_plane_with_store

pub async fn open_host_control_plane_with_store(
    config: &Config,
    database_registry: DatabaseRegistry,
    store: LibraryStore,
) -> Result<HostControlPlane>

open_host_control_plane on a library that is already open.

The daemon's config reload uses this so it does not reopen the database.

Errors

Returns an error when bootstrap or enrollment fails.

refresh_present

pub async fn refresh_present(
    store: &LibraryStore,
    node_id: &str,
    enrolled: &[EnrolledPlugin],
) -> Result<(Vec<PresentDeployment>, HashMap<String, String>)>

Loads an already-open host control plane's deployments again, for callers that changed desired state and want a fresh view without re-enrolling.

Errors

Returns an error when the deployment table cannot be read.

add_package_version

pub async fn add_package_version(
    store: &LibraryStore,
    actor: &ConfigActor,
    files_dir: &Path,
    node_id: &str,
    request: VersionRequest,
) -> Result<AddedVersion>

Verifies package, records a PluginVersion, and moves the active pointer per VersionRequest::activate.

A local archive's digest is computed here (it is the operator's own file); a remote artifact must match the digest its package manifest declares. Archives up to the library blob cap are stored in the database when no shared URL exists, so every host can materialize them.

Errors

Returns an error for a platform key (platform guests ship with the host), a malformed or yanked package, a digest mismatch, a tree that disagrees with the package, or a library write failure.

enroll_version

pub async fn enroll_version(
    store: &LibraryStore,
    actor: &ConfigActor,
    version: &PluginVersion,
) -> Result<PluginInstance>

Creates the default instance of a installed plugin with its schema defaults, as enrollment does for a host-local plugin. Idempotent.

Errors

Returns an error when an instance or document write fails.

grant_covers_version

pub fn grant_covers_version(grant: &PluginGrant, version: &PluginVersion) -> bool

True when grant still covers everything version requests, so an update may carry an earlier approval forward. A widened request needs a fresh plugins approve.

host_artifact

pub fn host_artifact(version: &PluginVersion) -> Result<&PluginArtifact>

The version artifact this node runs.

Errors

Returns an error naming the host target when the version has none for it, so placement can exclude this host.

install_plugin_key

pub async fn install_plugin_key(
    store: &LibraryStore,
    files_dir: &Path,
    coordinate: &PackageCoordinate,
    package: &BookclerkPackageManifest,
) -> Result<String>

The plugin key an install installs under.

A registry coordinate names a stable key. A local archive's path does not: a new version of an already installed plugin arrives as another file, so its key is the key its alias is already installed under, and only a first install takes the path-derived key.

Errors

Returns an error when the coordinate yields no key or the alias is installed under several keys.

install_version

pub async fn install_version(
    store: &LibraryStore,
    actor: &ConfigActor,
    files_dir: &Path,
    node_id: &str,
    request: InstallRequest,
) -> Result<InstalledVersion>

Installs an operator's package as a version, carries an earlier approval forward when it still covers the new version (or approves when asked), and enrolls the plugin's default instance.

One alias names one plugin: a version may not take an alias another plugin's active version already answers to.

Errors

Returns an error when the key cannot be derived, the alias belongs to another plugin, or installing, approval, or enrollment fails.

is_sha256_hex

pub fn is_sha256_hex(raw: &str) -> bool

True for a canonical SHA-256 digest: exactly 64 lowercase hex digits.

Every digest that names a path (the version cache) or is compared against a computed digest is held to this form, so an owner- or registry-supplied value such as .., an absolute path, or one with a separator can never select a directory outside the cache.

materialize_owner_version

pub async fn materialize_owner_version(
    store: &LibraryStore,
    files_dir: &Path,
    version: &PluginVersion,
) -> Result<PathBuf>

materialize_version for a version a library deploys to this host: a blob: archive is read from the library as usual (the caller fetched it over the owner link and checked its digest), and any other URL is fetched only as an owner https: URL ([bookclerk_plugin_catalog::fetch_owner_artifact]: no file:, no local or private hosts, every redirect hop checked the same way).

A tree already cached under the artifact's payload digest is reused without a fetch or an archive check, so the caller must have checked the whole artifact (URL, archive digest and payload digest) against the host operator's approval first (RemotePluginConsent::approved_artifact_matches).

Arguments

  • store - This host's library.
  • files_dir - This host's files dir.
  • version - The owner's version, with the grant this host runs it with.

Errors

As materialize_version, and when the owner's URL is refused.

materialize_version

pub async fn materialize_version(
    store: &LibraryStore,
    files_dir: &Path,
    version: &PluginVersion,
) -> Result<PathBuf>

Makes the active version's tree available under plugins/.versions/<payload digest> and returns that path.

A cached digest is reused as is; otherwise the archive is fetched (from the library blob store, a file: path, or HTTPS), its digest checked, extracted under .staging, the payload-root digest checked against the version, and renamed into place under the plugin mutation lock.

Errors

Returns an error when the version has no artifact for this host, a digest is not 64 lowercase hex digits (is_sha256_hex; checked before any path is formed or a cached tree reused), the artifact cannot be fetched, or a digest does not match.

open_installed_plugin

pub fn open_installed_plugin(
    root: &Path,
    version: &PluginVersion,
) -> Result<DiscoveredPlugin>

Opens a materialized version tree as a spawnable plugin carrying the version's identity and consent grant.

Errors

Returns an error when the tree's manifest is unreadable or names another plugin, or the version has no approved grant yet.

sweep_version_cache

pub fn sweep_version_cache(
    files_dir: &Path,
    keep: &BTreeSet<String>,
    grace: Duration,
) -> Result<usize>

Removes cached digests not in keep and older than grace, plus stale version staging directories. Returns how many entries were removed.

Errors

Returns an error when the mutation lock cannot be taken.

version_cache_path

pub fn version_cache_path(files_dir: &Path, payload_root_sha256: &str) -> Result<PathBuf>

Cached tree of one payload-root digest.

Errors

Returns an error when payload_root_sha256 is not a canonical SHA-256 (is_sha256_hex): it is joined onto the cache root, so anything else could name a directory outside it.

version_cache_root

pub fn version_cache_root(files_dir: &Path) -> PathBuf

Cache root: <files_dir>/plugins/.versions.

pub fn version_consent_request(version: &PluginVersion) -> Result<PluginGrant>

Consent the version's manifest requests (what plugins approve shows).

Errors

Returns an error when the recorded plugin.toml or plugin key no longer parses.

version_grant

pub fn version_grant(version: &PluginVersion) -> Result<PluginGrant>

The consent grant recorded on version.

Errors

Returns an error when no operator has approved the version yet or the recorded grant is malformed.

configured_alias_occupants

pub fn configured_alias_occupants(
    config: &Config,
) -> Result<Vec<(PluginKey, String, PathBuf)>>

Occupancy (PluginKey, alias, path) under every configured discovery root.

Walks plugin_search_dirs without hashing payloads. A receipt PluginKey is preferred; otherwise PluginKey::from_install_path.

Errors

Returns when a plugin.toml cannot be read or parsed, or a PluginKey cannot be formed for an occupant.

install_from_manifest_with_configured_aliases

pub fn install_from_manifest_with_configured_aliases(
    config: &Config,
    lock: &PluginMutationLock,
    manifest: &BookclerkPackageManifest,
    coordinate: &PackageCoordinate,
    opts: &InstallOptions,
) -> Result<InstallOutcome>

Catalog install after reject_configured_alias_collision.

lock must already cover opts.plugins_root so alias preflight and the catalog transaction share one host-local mutation lock.

Errors

Returns a catalog error when the lock does not cover this plugins root, preflight rejects the alias, or install fails.

install_local_archive_with_configured_aliases

pub fn install_local_archive_with_configured_aliases(
    config: &Config,
    lock: &PluginMutationLock,
    archive: &Path,
    manifest: &BookclerkPackageManifest,
    opts: &InstallOptions,
) -> Result<InstallOutcome>

Local-archive install after reject_configured_alias_collision.

lock must already cover opts.plugins_root.

Errors

Returns a catalog error when the lock does not cover this plugins root, preflight rejects the alias, or install fails.

reject_configured_alias_collision

pub fn reject_configured_alias_collision(
    config: &Config,
    incoming_key: &PluginKey,
    incoming_alias: &str,
) -> Result<()>

Rejects installing incoming_alias when a different PluginKey already owns it anywhere in the configured discovery universe.

Same PluginKey remains eligible for update/replace at the same alias. --replace cannot seize a foreign alias or rename an installed alias.

Errors

Returns PluginError when the alias is occupied by another PluginKey or occupancy cannot be read.

binding_grant_flags

pub fn binding_grant_flags(grant: &PluginGrant) -> InstanceBindingGrant

config / secrets flags of the plugin's covering grant.

prepare_open_for_instance

pub async fn prepare_open_for_instance(
    store: &LibraryStore,
    files_dir: &Path,
    plugin: &DiscoveredPlugin,
    instance_id: &PluginInstanceId,
) -> Result<PreparedOpen>

Resolves open bindings for instance_id of plugin.

The covering grant comes from plugin-grants.json; the settings schema from the installed manifest. A missing document, a dangling secret ref, or a missing required setting is an error. Document keys the installed manifest no longer declares are dropped and logged.

Errors

Returns an error when the grant cannot be loaded, the instance is not this plugin's, or its document cannot be resolved.

prepared_open_from_resolved

pub fn prepared_open_from_resolved(
    config: ExtensibleConfig,
    secrets: ExtensibleConfig,
    config_revision: i64,
) -> PreparedOpen

Builds open bindings from a deployment's already resolved payloads.

Does not look up an instance by plugin key.

guest_reservation

pub fn guest_reservation(
    manifest: &PluginManifest,
    grant: Option<&PluginGrant>,
    jail: &PluginsJailConfig,
) -> GuestReservation

CPU and memory one guest may use at most on this host: its grant's ceilings after [plugins.jail], the numbers its jail enforces. The library scheduler accounts host budgets against these.

plugin_data_dir

pub fn plugin_data_dir(config: &Config, plugin: &DiscoveredPlugin) -> Result<PathBuf>

The private directory a plugin keeps state in.

State is keyed by bookclerk_plugin_catalog::PluginKey (plugin-state/<fs_id>/data), not the display alias. Invalid keys cannot be constructed.

Errors

Returns an error when the operation fails.

activates_on_demand

pub fn activates_on_demand(manifest: &PluginManifest) -> bool

True when a deployment of manifest may sleep while idle and start on the next call.

The plugin must belong only to the integration family. A Python guest sleeps too: it starts from its stored start-up snapshot in about a second. Every integration entrypoint works through a wake: a remoteLibrary guest keeps what must outlive a sleep in its plugin database, and its new-user poll is scheduled by the host; a sign-in (oidc) call starts the guest the way a lookup does. A cli entrypoint is fine: the CLI starts its own session for each command.

Arguments

  • manifest - the installed manifest the deployment spawns.

storefront_activates_on_demand

pub fn storefront_activates_on_demand(manifest: &PluginManifest) -> bool

True when a storefront deployment of manifest may sleep while idle.

The plugin must belong only to the source family. Python storefronts sleep too, since they start from a stored snapshot.

Arguments

  • manifest - the installed manifest the deployment spawns.

storage_activates_on_demand

pub fn storage_activates_on_demand(manifest: &PluginManifest) -> bool

True when a storage deployment of manifest may sleep while idle.

The plugin must belong only to the storage family. The deployment also requires a host-side backend (the first-party s3 or local package); other storage guests stay running.

Arguments

  • manifest - the installed manifest the deployment spawns.

family_keyword

pub fn family_keyword(family: PluginFamily) -> &'static str

Family-specific crates.io keyword (bookclerk-source, …).

host_target_triple

pub fn host_target_triple() -> &'static str

Host target triple used when selecting release assets.

validate_plugin_id

pub fn validate_plugin_id(id: &str) -> Result<()>

Validate plugin id segment used in crate names and plugin.toml.

Delegates to bookclerk_plugin_manifest::validate_plugin_id (strict [a-z0-9_]{2,32} grammar; unique across kinds in one host plugin namespace).

Errors

Returns an error when the operation fails.

approve_remote_request

pub async fn approve_remote_request(
    store: &LibraryStore,
    library_id: &str,
    plugin_key: &str,
    reviewed_digest: &str,
    narrowing: &RemoteNarrowing,
    approver: RemoteApprover<'_>,
) -> Result<RemotePluginConsent, RemoteApprovalError>

Approves the request recorded from library_id for plugin_key, exactly as it was reviewed: reviewed_digest must be the recorded request's digest (bookclerk_library::control_plane::RemotePluginConsent::request_digest, shown with the request), and the consent is that request minus narrowing (remote_consent). The write is a compare-and-swap on the recorded request, so a request that changed after it was read is refused rather than approved unseen.

Arguments

  • store - This host's library.
  • library_id - Library id.
  • plugin_key - Canonical plugin key.
  • reviewed_digest - Digest of the request as the approver reviewed it.
  • narrowing - What the approver takes out of the request.
  • approver - Who approves (an automatic approval never overrides an operator's revoke).

Errors

Returns RemoteApprovalError::NotRequested when nothing is recorded, RemoteApprovalError::Conflict when the recorded request is not the reviewed one (its digest differs) or the store refuses the write (a request that changed in between, or an automatic approval of a revoked one), RemoteApprovalError::Invalid when it does not parse or the narrowing names something it does not ask for, and RemoteApprovalError::Store when a read or write fails.

narrow_remote_grant

pub fn narrow_remote_grant(requested: &PluginGrant, consent: &PluginGrant) -> PluginGrant

The grant a guest runs with: requested ∩ consent.

Every structural set and network destination is intersected; network is outbound only when both are; undeclared redirects only when both allow; budgets take the smaller. Destinations the request asks for but the result lacks are recorded as operator denials, so the spawn path's manifest re-evaluation (crate::effective_grant) keeps them out.

pub fn remote_consent(
    requested: &PluginGrant,
    narrowing: &RemoteNarrowing,
) -> Result<PluginGrant>

The consent an operator gives to requested with narrowing applied.

Errors

Returns an error when the narrowing names a domain, binding or own-agent host the request does not ask for (it would deny nothing, and a typo must not read as a narrowing that did not happen).

pub fn remote_consent_state(
    plugin_key: &str,
    requested_json: &str,
    reviewed_json: Option<&str>,
    consent_json: Option<&str>,
) -> RemoteConsentState

Evaluates a stored consent row's grants: the current request (requested_json), the request as reviewed and the consent (both None while unapproved).

pub fn remote_consent_view(row: &RemotePluginConsent) -> Value

The one JSON view of a consent row, shared by the operator API and the CLI so both answer the same fields: the request (version, grant, the archive this host would fetch, and its request_digest), the approval (approved_version, grant, approved_at, approved_by), revoked_at, updated_at, the state (remote_row_consent_state), and pending, what the request asks for beyond the approval (remote_row_changes). A stored grant that does not parse shows as null.

remote_platform_auto_approval

pub fn remote_platform_auto_approval(
    requested: &PluginGrant,
    owner_payload_root_sha256: &str,
    local_bundled_payload: Option<&str>,
) -> bool

True when a platform plugin's request may be approved without asking: the key is a Bookclerk platform key, this host's own install of that key is platform-bundled with the same payload digest as the owner's artifact (local_bundled_payload, from this host's provenance check), and the request stays inside the platform envelope (deny network, only config / work_fs).

remote_request_changes

pub fn remote_request_changes(
    reviewed: &PluginGrant,
    requested: &PluginGrant,
) -> Vec<String>

Operator-facing lines naming what requested asks for beyond reviewed.

The same lines (and header) the local consent flow prints for a widened plugin (crate::PendingStructural::summary_lines), plus network turned on and larger budgets, which only an owner request can change. Network destinations are compared exactly as remote_request_within compares them (whole TCP grants, exact patterns and ranges), so the lines are empty exactly when that holds.

Arguments

  • reviewed - The owner's request as this host's operator approved it.
  • requested - The owner's current request.

Returns

A header line then one indented line per kind of widening, or nothing.

remote_request_within

pub fn remote_request_within(reviewed: &PluginGrant, requested: &PluginGrant) -> bool

True when requested asks for nothing outside reviewed: the same plugin, every capability set a subset, network no wider (outbound only if reviewed outbound), undeclared redirects only if reviewed, and no larger budget.

remote_row_changes

pub fn remote_row_changes(row: &RemotePluginConsent) -> Vec<String>

remote_request_changes for a stored consent row: what the owner's current request asks for beyond the request the operator approved.

Empty when nothing was approved yet (the whole request is new), when the request stays within the approval, or when either grant does not parse (the row's state already says invalid_grant).

pub fn remote_row_consent_state(row: &RemotePluginConsent) -> RemoteConsentState

Evaluates a stored consent row: remote_consent_state over its grants, except that an approval of another archive (the owner changed the artifact URL or digest since the operator approved) needs approval again, whatever the grant.

Arguments

  • row - The consent row as stored.

plugin_instance_key

pub fn plugin_instance_key(plugin_id: &str, account_id: &str) -> String

Isolation key: different accounts never share a plugin isolate.

apply_setting_destinations

pub fn apply_setting_destinations(
    grant: &mut PluginGrant,
    manifest: &PluginManifest,
    settings: &Value,
) -> Vec<SettingGrantStatus>

Adds every approved destination the instance's settings name to grant.

A fetch destination adds its host:port, a TCP destination its host and port, and a name or local-network address its local binding, all to PluginGrant::setting_network. A destination is added only when the current value derives exactly what the operator approved for that setting. Nothing is added unless the grant is outbound.

Arguments

  • grant - The covering grant for this spawn (mutated in place).
  • manifest - The plugin being spawned.
  • settings - The instance's effective settings (the spawn CONFIG).

Returns

The status of each network setting, for the plugin's feedback.

approve_setting_destinations

pub fn approve_setting_destinations(
    existing: &BTreeMap<String, BTreeSet<SettingDestination>>,
    manifest: &PluginManifest,
    in_use: &BTreeMap<String, BTreeSet<SettingDestination>>,
    approve: &BTreeMap<String, BTreeSet<SettingDestination>>,
) -> BTreeMap<String, BTreeSet<SettingDestination>>

The approved setting destinations after the operator answers the form.

For each network setting the result holds what is approved and still in use (in_use lists the destinations the instances' current values derive), plus each destination the operator approved now that is in use. Anything else is withdrawn: a value that changed no longer keeps its old destination, and a destination nobody named cannot be approved.

Arguments

  • existing - The stored grant's approvals.
  • manifest - The plugin; only its network settings are kept.
  • in_use - Per setting key, the destinations the instances name now.
  • approve - Per setting key, the destinations the operator approved now.

Returns

The new PluginGrant::setting_destinations.

destinations_in_use

pub fn destinations_in_use(rows: &[InstanceSettingStatuses]) -> SettingDestinationMap

The destinations rows name, per setting key, for approve_setting_destinations's in_use.

library_setting_statuses

pub async fn library_setting_statuses(
    library: &LibraryStore,
    manifest: &PluginManifest,
    plugin_key: &str,
    grant: Option<&PluginGrant>,
) -> Result<Vec<InstanceSettingStatuses>>

Judges the network settings of every instance of a plugin in the library.

Each instance's configuration document is read and its defaults applied as at spawn; an instance without a document runs on its defaults, and a plugin with no instance yet is judged on its defaults alone. Nothing is read when the plugin declares no network setting.

Arguments

  • library - The library holding the instances.
  • manifest - The plugin; its schema supplies the defaults.
  • plugin_key - The plugin's canonical key, which its instances carry.
  • grant - The stored grant, which decides approved against pending.

Returns

One entry per instance, oldest first.

Errors

Returns an error when the instances or a document cannot be read.

network_grant_binding

pub fn network_grant_binding(
    grant: &PluginGrant,
    statuses: &[SettingGrantStatus],
) -> NetworkGrant

The NETWORK binding a guest receives at open: the grant in effect (after apply_setting_destinations filled its setting overlay) and each network setting's destination and state.

Arguments

Returns

The grant as the ABI carries it, within the schema's list bound.

network_settings

pub fn network_settings(manifest: &PluginManifest) -> impl Iterator<Item = &SettingSpec>

The settings of manifest that declare network, in declaration order.

setting_grant_statuses

pub fn setting_grant_statuses(
    manifest: &PluginManifest,
    settings: &Value,
    grant: Option<&PluginGrant>,
) -> Vec<SettingGrantStatus>

Derives the destination each network setting names in settings.

Arguments

  • manifest - The plugin whose [[settings]] declare the networks.
  • settings - One instance's effective settings (defaults applied), as the JSON object the guest's CONFIG carries.
  • grant - The stored grant, which decides approved against pending.

Returns

One status per network setting, in declaration order.

note_spawn_stage

pub fn note_spawn_stage(message: &str)

Record one secret-free startup line.

The line is a bookclerk::spawn tracing event and a byte-capped ring entry. Raw stderr is written only when spawn_diag_stderr_enabled is set (BOOKCLERK_SPAWN_DIAG=1|true|stderr). Session challenges are stripped. Plugin stderr is not stored here; the per-session tail is separate.

pub fn purge_link_plugin_state(
    files_dir: &Path,
    link: &LinkStateDir,
) -> Result<(), String>

Deletes the plugin state this install kept for a library it no longer belongs to: plugin-state/<link dir>/, every plugin's data, tmp and session directories in it.

Each plugin's state root goes through revoke_plugin_state_before_purge first, so a Windows package-SID grant still journalled there is revoked (or the purge refused) rather than left behind. Rejected journals are not discarded. A missing subtree is not an error.

Call it only once no guest of that library is running.

Arguments

  • files_dir - This install's files directory.
  • link - The joined library's state directory leaf.

Errors

Returns a message naming every plugin whose journal refused the purge, or saying the subtree could not be deleted; whatever was not deleted stays in place, and a later call retries it.

recent_spawn_diagnostics

pub fn recent_spawn_diagnostics() -> String

Bounded startup log for the current process.

A deadline handler prints this before exiting. The snapshot is a second capped copy of the ring, not a join of unbounded strings.

retry_abandoned_acl_journals

pub fn retry_abandoned_acl_journals(files_dir: &Path)

Retry abandoned journals for every plugin under files_dir/plugin-state.

Host startup calls this so a crash does not wait for the next spawn of the same plugin. A live session's owner lock is left alone.

revoke_plugin_state_before_purge

pub fn revoke_plugin_state_before_purge(
    state_root: &Path,
    discard_rejected: bool,
) -> Result<(), String>

Revoke this plugin's journal before --purge-state deletes the directory.

discard_rejected deletes session-*.json.rejected with plugin state. A readable journal that is still present is never discarded that way.

Errors

Returns an error when a journal file is still present, when a live session holds one, or when a rejected record remains and discard_rejected is false. Purge then leaves plugin-state in place.

set_webhook_public_origin

pub fn set_webhook_public_origin(origin: Option<&str>)

Sets the origin webhook URLs are built on.

The daemon calls this once it knows its public origin and that webhooks are on (plugins.webhooks = "auto"), and with None to stop handing URLs out. A trailing / is dropped.

webhook_public_origin

pub fn webhook_public_origin() -> Option<String>

The origin webhook URLs are built on, when one is set.

Type aliases

SessionShutdown

pub type SessionShutdown = Arc<dyn Fn() + Send + Sync>;

Shutdown hook invoked the moment a live session is fenced.

Result

pub type Result<T> = Result<T, PluginError>;

Result alias for PluginError.

GuestDatabaseFactory

pub type GuestDatabaseFactory = Arc<dyn Fn(Arc<AtomicBool>, u64) -> Arc<dyn GuestDatabase> + Send + Sync>;

Send-safe constructor for a per-binding bookclerk_plugin_sdk::GuestDatabase.

GuestDatabase trait objects are ?Send, so named plugin database bindings cross into the vat task as factories and are constructed on the vat thread just before the per-job PluginWorker.open. The factory receives the job cancel flag and the host lease deadline so binding execute can abort and cap deadlineUnixMs.

SettingDestinationMap

pub type SettingDestinationMap = BTreeMap<String, BTreeSet<SettingDestination>>;

Per setting key, the destinations a plugin's instances name now.

Constants

AI_BINDING_RUN_TIMEOUT

pub const AI_BINDING_RUN_TIMEOUT: Duration = _;

Longest one run through the AI binding may take.

AI_ITEMS_PER_MINUTE

pub const AI_ITEMS_PER_MINUTE: u32 = 240;

Input items (texts, for text embeddings) one plugin session may send through AI per minute. The budget refills continuously and allows a burst of the whole minute. Work over many items belongs in a job that the host runs against the model plugin itself.

GRANT_WATCH_INTERVAL

pub const GRANT_WATCH_INTERVAL: Duration = _;

How often the daemon re-reads plugin-grants.json when no in-process notify fires.

AI_TASK_BINDING_PREFIX

pub const AI_TASK_BINDING_PREFIX: &str = "ai:";

Grant bindings entry prefix for one [ai].calls task (ai:<task>, such as ai:textEmbeddings): the plugin may run models of that task through its AI binding.

GRANTS_FILE

pub const GRANTS_FILE: &str = "plugin-grants.json";

Filename under $BOOKCLERK_FILES_DIR for persisted grants.

GRANT_SCHEMA_VERSION

pub const GRANT_SCHEMA_VERSION: u32 = 2;

Current persisted PluginGrant document version.

This constant versions the on-disk grant representation. Missing / 0 JSON is a legacy document. Empty structural sets are fail-closed at every schema version: they approve nothing and do not acquire capabilities merely because a newer manifest requests them.

KNOWN_HOST_BINDINGS

pub const KNOWN_HOST_BINDINGS: &[&str] = _;

Host binding names operators may grant (widen or narrow).

PENDING_HEADER

pub const PENDING_HEADER: &str = "Awaiting consent (not automatically approved):";

First line of PendingStructural::summary_lines and crate::remote_request_changes.

PLUGIN_JAIL_ACTIVE_PROCESSES_MAX

pub const PLUGIN_JAIL_ACTIVE_PROCESSES_MAX: u32 = 64;

Absolute OS jail PID ceiling (overhead + extra, inclusive).

PLUGIN_JAIL_CPU_CORES_DEFAULT

pub const PLUGIN_JAIL_CPU_CORES_DEFAULT: f64 = 0.80;

Default jail CPU as cores (PLUGIN_JAIL_CPU_RATE_DEFAULT / 100).

PLUGIN_JAIL_CPU_RATE_DEFAULT

pub const PLUGIN_JAIL_CPU_RATE_DEFAULT: u32 = 80;

Default jail Spec CPU rate percent for confined guests (one-core units).

PLUGIN_JAIL_CPU_RATE_MAX

pub const PLUGIN_JAIL_CPU_RATE_MAX: u32 = 100;

Absolute ceiling used only when host CPU detection is unavailable in docs.

Prefer host_cpu_rate_max at runtime (logical_cpus × 100).

PLUGIN_JAIL_EXTRA_PROCESSES_DEFAULT

pub const PLUGIN_JAIL_EXTRA_PROCESSES_DEFAULT: u32 = 2;

Default extra processes/threads beyond launcher overhead.

PLUGIN_JAIL_EXTRA_PROCESSES_MAX

pub const PLUGIN_JAIL_EXTRA_PROCESSES_MAX: u32 = 62;

Host hard cap for per-plugin extra process budget.

PLUGIN_JAIL_MEMORY_MIB_DEFAULT

pub const PLUGIN_JAIL_MEMORY_MIB_DEFAULT: u32 = 512;

Default jail Spec memory ceiling (MiB) for confined guests.

PLUGIN_JAIL_MEMORY_MIB_MAX

pub const PLUGIN_JAIL_MEMORY_MIB_MAX: u32 = 4096;

Host hard cap for per-plugin jail memory overrides (MiB).

PLUGIN_STATE_BUDGET_MIB_DEFAULT

pub const PLUGIN_STATE_BUDGET_MIB_DEFAULT: u32 = 512;

Default per-plugin data/ and tmp/ disk budget (MiB each).

PLUGIN_STATE_BUDGET_MIB_MAX

pub const PLUGIN_STATE_BUDGET_MIB_MAX: u32 = 4096;

Host hard cap for per-plugin disk budget overrides (MiB).

QUEUE_CONSUMER_BINDING_PREFIX

pub const QUEUE_CONSUMER_BINDING_PREFIX: &str = "queue_consumer:";

Grant bindings entry prefix for one [[queues.consumers]] row (queue_consumer:<queue>): the host may deliver that queue to the plugin.

QUEUE_PRODUCER_BINDING_PREFIX

pub const QUEUE_PRODUCER_BINDING_PREFIX: &str = "queue:";

Grant bindings entry prefix for one [[queues.producers]] binding (queue:<BINDING>): the plugin may send through that env binding.

WINDOWS_SESSION_PROCESS_BASELINE

pub const WINDOWS_SESSION_PROCESS_BASELINE: u32 = 5;

Windows outer session Job processes before the granted extra budget.

Both bookclerk-jail supervisors, bookclerk-workerd, the pinned workerd, and the native guest. Payload overhead stays 3 (GuestRuntimeKind::process_overhead); this baseline is only the outer Windows Job. Linux pids.max counts threads and must not use this number.

WORKERD_GRANT_CPU_MS_ENV

pub const WORKERD_GRANT_CPU_MS_ENV: &str = "BOOKCLERK_WORKERD_GRANT_CPU_MS";

Grant CPU budget (ms) for workerd logging / limit narrowing.

WORKERD_GRANT_DOMAINS_ENV

pub const WORKERD_GRANT_DOMAINS_ENV: &str = "BOOKCLERK_WORKERD_GRANT_DOMAINS";

Comma-separated grant domain allowlist for workerd egress.

WORKERD_GRANT_NETWORK_MODE_ENV

pub const WORKERD_GRANT_NETWORK_MODE_ENV: &str = "BOOKCLERK_WORKERD_GRANT_NETWORK_MODE";

Env keys consumed by bookclerk-workerd (grant.rs) at isolate start.

WORKERD_GRANT_POLICY_ENV

pub const WORKERD_GRANT_POLICY_ENV: &str = "BOOKCLERK_WORKERD_GRANT_POLICY";

Canonical JSON EgressPolicy (preferred over piecemeal domain env vars).

WORKERD_GRANT_SUBREQUESTS_ENV

pub const WORKERD_GRANT_SUBREQUESTS_ENV: &str = "BOOKCLERK_WORKERD_GRANT_SUBREQUESTS";

Grant subrequest budget injected into workerd EGRESS_POLICY.

AUTHORIZED_PACKAGE_DIR

pub const AUTHORIZED_PACKAGE_DIR: &str = "plugin-packages";

Directory under the files dir that holds operator-placed package archives.

INGRESS_HEALTH_INTERVAL

pub const INGRESS_HEALTH_INTERVAL: Duration = _;

How often a running ingress is asked whether it is serving.

VERSION_CACHE_DIR

pub const VERSION_CACHE_DIR: &str = ".versions";

Directory under plugins/ holding materialized version trees.

VERSION_CACHE_GRACE

pub const VERSION_CACHE_GRACE: Duration = _;

How long an unreferenced cached digest survives before the sweep.

KV_GRANT_BINDING

pub const KV_GRANT_BINDING: &str = "plugin_kv";

Grant token that authorizes every [[kv_namespaces]] row of a plugin.

TRIGGER_IDLE_TIMEOUT

pub const TRIGGER_IDLE_TIMEOUT: Duration = _;

How long a trigger-driven guest stays up after its last call returns.

One minute matches the event delivery lease, so a burst of deliveries reuses one process while a quiet plugin is gone within a minute.

STOREFRONT_IDLE_TIMEOUT

pub const STOREFRONT_IDLE_TIMEOUT: Duration = _;

How long a storefront stays up after its last call returns.

Storefront work comes in bursts (a scan pages through a library, an acquire fetches several parts, Discover asks for a page of hints), so the timeout is longer than for trigger-driven plugins.

STORAGE_IDLE_TIMEOUT

pub const STORAGE_IDLE_TIMEOUT: Duration = _;

How long a storage destination stays up after its last call returns.

Storage work comes in bursts (an acquire writes several parts and a cover, a library scan pages through the inventory), so the timeout matches storefronts.

CRATE_NAME_PREFIX

pub const CRATE_NAME_PREFIX: &str = "bookclerk-plugin-";

Required crates.io name prefix: bookclerk-plugin-{family}-{id}.

PRODUCT_KEYWORD

pub const PRODUCT_KEYWORD: &str = "bookclerk";

Shared crates.io keyword (bookclerk) expected on published plugin crates.

REGISTRY_KEYWORD

pub const REGISTRY_KEYWORD: &str = "bookclerk-plugin";

Keyword every published plugin crate should include.

HOST_SHARED_ACCOUNT

pub const HOST_SHARED_ACCOUNT: &str = "host";

Registry-loaded source/integration guests (not a user account).

OPERATOR_ACCOUNT

pub const OPERATOR_ACCOUNT: &str = "operator";

Isolation key: different accounts never share a plugin isolate.

WORKERD_BIN_ENV

pub const WORKERD_BIN_ENV: &str = "BOOKCLERK_WORKERD_BIN";

Override for the pinned Cloudflare workerd binary, honoured by bookclerk-workerd and forwarded to it by the host.

WORKERD_LAUNCHER_ENV

pub const WORKERD_LAUNCHER_ENV: &str = "BOOKCLERK_PLUGIN_WORKERD";

Override for the bookclerk-workerd launcher path (tests / packaging).

TEST_CHANNEL_IDENT_ENV

pub const TEST_CHANNEL_IDENT_ENV: &str = "BOOKCLERK_TEST_CHANNEL_IDENT";

Set to 1 or true in the host process to give each proxy a channel tag.

The variable is not copied into the guest. The tag is written under the gateway session directory as TEST_CHANNEL_TAG_FILE and answered only by that session's proxy. Production leaves it unset.

TEST_CHANNEL_TAG_FILE

pub const TEST_CHANNEL_TAG_FILE: &str = "channel-tag";

Session-directory file holding the tag when TEST_CHANNEL_IDENT_ENV is set.

TEST_INJECT_EXTRA_ENDPOINT_ENV

pub const TEST_INJECT_EXTRA_ENDPOINT_ENV: &str = "BOOKCLERK_TEST_INJECT_EXTRA_ENDPOINT";

Host-process description of one extra endpoint to add to the guest handoff.

Unix: fd:<n> of a socket in this process. Windows: handle:<read>,handle:<write> of the guest pipe ends in this process. The variable is not copied into the guest. Production leaves it unset, so the guest preserve list stays bookclerk_sandbox::GUEST_PROXY_FD only. Setting it transfers the endpoint. It does not, by itself, publish the candidate metadata the guest uses to observe that slot.

TEST_OBSERVE_EXTRA_ENDPOINT_ENV

pub const TEST_OBSERVE_EXTRA_ENDPOINT_ENV: &str = "BOOKCLERK_TEST_OBSERVE_EXTRA_ENDPOINT";

Host-process request to publish candidate-endpoint observation metadata.

1 or true names the fixed Unix slot, and on Windows the handles from TEST_INJECT_EXTRA_ENDPOINT_ENV. A Windows handle:<read>,handle:<write> value names that candidate without transferring it. The variable is not copied into the guest. Unset means the guest reports not-run, which is not proof the endpoint is absent.

ON_DEMAND_USER_POLL_INTERVAL

pub const ON_DEMAND_USER_POLL_INTERVAL: Duration = _;

How often the host polls a sleeping remote library for new users.

Each poll wakes the guest, which then stays up for the idle timeout, so the interval is several idle timeouts long: the guest sleeps most of the time, and a new user waits at most this long for a claim ticket.

RESIDENT_USER_POLL_INTERVAL

pub const RESIDENT_USER_POLL_INTERVAL: Duration = _;

How often the host polls a resident remote library for new users.

A resident guest is running anyway, so a short interval costs one RPC.

WEBHOOKS_GRANT_BINDING

pub const WEBHOOKS_GRANT_BINDING: &str = "webhooks";

Grant token that authorizes every [[webhooks]] row of a plugin.

Generated from crates/bookclerk-plugin-host at main · View as Markdown