bookclerk_plugin_host
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.
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. |
bookclerk_workerd::webhook_requestbookclerk_plugin_sdk::protocolbookclerk_plugin_sdk::methodsbookclerk_plugin_sdk::CatalogHitbookclerk_plugin_sdk::CliArgbookclerk_plugin_sdk::CliArgKindbookclerk_plugin_sdk::CliArgSpecbookclerk_plugin_sdk::CliCommandSpecbookclerk_plugin_sdk::CliInvokeParamsbookclerk_plugin_sdk::CliInvokeResultbookclerk_plugin_sdk::CliSchemabookclerk_plugin_sdk::EventPollResultbookclerk_plugin_sdk::ExpandCandidatesParamsbookclerk_plugin_sdk::ExternalUserbookclerk_plugin_sdk::FetchTitleParamsbookclerk_plugin_sdk::FetchedFilebookclerk_plugin_sdk::FetchedFileRolebookclerk_plugin_sdk::ListeningProgressbookclerk_plugin_sdk::LoginCompleteParamsbookclerk_plugin_sdk::LoginParamsbookclerk_plugin_sdk::LoginResultbookclerk_plugin_sdk::LoginStartResultbookclerk_plugin_sdk::PlainFetchbookclerk_plugin_sdk::PluginDescribebookclerk_plugin_sdk::PurchaseHintbookclerk_plugin_sdk::PurchaseHintParamsbookclerk_plugin_sdk::ScanBookbookclerk_plugin_sdk::ScanPagebookclerk_plugin_sdk::ScanParamsbookclerk_plugin_sdk::SearchCatalogParamsbookclerk_plugin_sdk::SourceAccountbookclerk_plugin_sdk::SyncListeningResultbookclerk_plugin_sdk::PRODUCT_API_VERSIONbookclerk_plugin_sdk::PROTOCOL_NAMEbookclerk_plugin_catalog::host_bookclerk_targetbookclerk_plugin_manifest::derive_setting_destinationbookclerk_plugin_manifest::DestinationScopebookclerk_plugin_manifest::SettingDestinationbookclerk_plugin_manifest::TcpGrantbookclerk_plugin_sdk::JobCheckpointbookclerk_plugin_sdk::JobInvocationLeasebookclerk_plugin_sdk::JobOutcomemanifest::embedded_logo_api_pathmanifest::entrypoint_familymanifest::logo_content_typemanifest::validate_logomanifest::BindingCapabilitiesmanifest::CapabilitiesManifestmanifest::CredentialSharingmanifest::DatabaseBindingManifestmanifest::Entrypointmanifest::EventConsumermanifest::EventProducermanifest::EventsManifestmanifest::JailNetworkNeedmanifest::LogoKindmanifest::ModuleSpecmanifest::NamedBindingmanifest::NetworkCapabilitiesmanifest::NetworkModemanifest::PluginFamilymanifest::PluginManifestmanifest::PluginRuntimeKindmanifest::TriggersManifestmanifest::WorkerdLimitsmanifest::WorkerdRuntimeManifestmanifest::ALL_ENTRYPOINTSmanifest::MAX_EMBEDDED_LOGO_BYTESsetting_grants::SettingGrantState
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.
fn is_retired(&self) -> bool
True once the deployment stopped the proxy; it does not wake again unless a rollback revives it.
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.
fn is_awake(&self) -> bool
True while a guest is running. False while a wake or a sleep holds the guest slot.
fn guest_pid(&self) -> Option<u32>
Native pid of the running guest, if awake.
fn wakes(&self) -> u64
Guests started on demand since the proxy was created.
fn idle_timeout(&self) -> Duration
Idle time after which the guest is stopped.
Implemented by: OnDemandIntegration, OnDemandSource, OnDemandStorage
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.
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.
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.
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.
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.
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
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.
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.
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.
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.
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.
Returns why not, for the deployment observation: not the active ingress, no Owner yet, or the settings could not be read.
fn origin(&self) -> Arc<dyn Origin + Send + Sync>
The library as relay plugins reach it (ORIGIN).
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.
Returns why the report was refused (an origin that is not https://
and a DNS name); the instance is then 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.
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.
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.
The guest's reply to a message; the default for a close.
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
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.
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.
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.
pub fn bind_addr(&self) -> SocketAddr
Bound TCP address the browser (and guest) should use for the callback.
Implements: Drop
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: WhetherEventResult::Suspendedis authorized for this type.filter: Canonical JSON of the host-owned payload filter, when present.
pub fn from_manifest(consumer: &EventConsumer) -> Self
Structural consumer snapshot from a [[events.consumers]] row.
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.
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
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 ownUser-Agentbut 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: TCPhost:portsthe 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.
pub fn is_empty(&self) -> bool
True when the current manifest introduces no unapproved structural caps.
pub fn summary_lines(&self) -> Vec<String>
CLI/UI lines for capabilities waiting on consent.
Implements: Clone, Debug, Default, Eq, PartialEq
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: Canonicalbookclerk_plugin_catalog::PluginKey. -
plugin_id: Display / CLI alias fromplugin.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].jobstypes the plugin may handle. -
network_mode: Approved network mode:denyoroutbound. -
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 ownUser-Agent.Every other request carries the host's agent (
bookclerk_plugin_manifest::host_user_agent).Nonemarks a grant approved before this permission existed, when every guest sent its own agent everywhere;effective_grantthen keeps the hosts the current manifest declares, which never widens what that grant allowed.Someis the operator's approval and narrows the manifest request. -
own_user_agent_reason: The manifest's reason forSelf::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_hostsnarrowed to these (all of them for a legacyNonegrant), 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.Noneon 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 fordata/andtmp/(MiB each).Applies to native and workerd guests. Unset →
PLUGIN_STATE_BUDGET_MIB_DEFAULT; clamped toPLUGIN_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 usecpu_msplus 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_destinationsfrom the instance's values; never stored.Self::egress_policyadds it to the stored network grant. It is kept apart fromSelf::domainsandSelf::tcpso the effective authority a session records stays the stored grant's: the approvals themselves are inSelf::setting_destinations(part of the grant revision), and a changed value changes the instance's configuration revision.
pub fn allows_event_consumer(&self, event_type: &str, schema_version: u32) -> bool
True when this grant authorizes delivering event_type at schema_version.
pub fn allows_queue_consumer(&self, queue: &str) -> bool
True when this grant authorizes delivering messages from queue.
pub fn allows_cron(&self, cron: &str) -> bool
True when this grant authorizes firing the normalized cron cron.
pub fn allows_queue_producer(&self, binding: &str) -> bool
True when this grant authorizes sending through the queue producer
binding.
pub fn allows_ai_task(&self, task: AiTask) -> bool
True when this grant authorizes running models of task through
the AI binding.
pub fn allows_job(&self, job_type: &str) -> bool
True when this grant authorizes handling job_type.
pub fn empty() -> Self
Empty grant used as a struct-update base for tests and new fields.
pub fn egress_policy(&self) -> EgressPolicy
Canonical typed network policy for workerd and the native socket proxy.
pub fn effective_domains(&self) -> BTreeSet<String>
The fetch allowlist this spawn uses: Self::domains plus what
approved setting destinations add.
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.
pub fn effective_own_user_agent_hosts(&self) -> BTreeSet<String>
Hosts where the guest keeps its own agent at run time.
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
pub struct PluginGrantStore {
pub grants: Vec<PluginGrant>,
}
On-disk grant store.
Fields
grants: Persisted per-plugin grant snapshots.
pub fn path(files_dir: &Path) -> PathBuf
Absolute path to plugin-grants.json under files_dir.
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.
files_dir- Bookclerk files directory that ownsplugin-grants.json.
Parsed PluginGrantStore, defaulting when the file does not exist.
Returns PluginError when the file cannot be read or parsed.
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.
files_dir- Bookclerk files directory that ownsplugin-grants.json.
Returns PluginError when serialization or the write fails.
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.
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.
plugin_key- Canonical PluginKey text, or a display alias.
A reference to the matching PluginGrant, or None.
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.
grant- Full consent snapshot to persist in memory (callSelf::saveto flush).
Implements: Clone, Debug, Default, Deserialize<'de>, Eq, PartialEq, Serialize
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: Fetchhost:portentries (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
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.
pub fn get(&self, key: &str) -> Option<&LocalPackage>
Package for key, when exactly one authorized archive resolved to it.
pub fn is_conflicted(&self, key: &str) -> bool
True when two archives resolved to key and neither was kept.
pub fn is_empty(&self) -> bool
True when no archive was loaded and no key collided.
pub fn keys(&self) -> Keys<'_, String, LocalPackage>
Canonical keys that have exactly one package.
pub fn insert(&mut self, key: String, package: LocalPackage)
Inserts package under key, clearing a previous conflict on that key.
Implements: Clone, Debug, Default
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: GrantedCONFIGpayload.secrets: GrantedSECRETSpayload.config_revision: Document revision the spawn applies.installed: Installed version the tree was materialized from;Nonefor a host-local tree.
Implements: Clone, Debug
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 grantedAIbinding, and what the host's own features run models through.
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.
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.
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.
pub fn reconcile_lock(&self) -> &Mutex<()>
Lock a caller holds for the duration of one reconcile pass.
pub fn set_integration_context(&self, ctx: IntegrationContext)
Stores the daemon lifecycle context used when a deployment starts an integration.
Panics when the integration-context lock is poisoned.
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.
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 when the deployment guest lock is poisoned.
pub fn opened_config_json(&self, plugin_instance_id: &str) -> Option<Value>
CONFIG JSON the live open call delivered for plugin_instance_id.
Panics when the deployment guest lock is poisoned.
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 when the deployment guest lock is poisoned.
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.
None when this node runs no guest for plugin_instance_id or its
manifest declares no row name.
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
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.gzorzip).manifest: Install-grade package manifest forarchive.
Implements: Clone, Debug
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: Parsedplugin.tomlfor this install directory.root: Directory containingplugin.toml(cwd + relativecommandbase).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;Nonefor host-local trees, whose grant lives inplugin-grants.json.state_scope: Whose library the guest works for, which decides where its host-manageddataandtmpdirectories live.
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 when the install tree cannot be evaluated. Prefer Self::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.
Returns when identity evaluation fails closed.
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.
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.
Returns an error when the spawn command cannot be resolved, the
manifest cannot be hashed, or plugin_key is malformed.
pub fn alias(&self) -> &str
Display / CLI alias (plugin.toml id).
pub fn plugin_key(&self) -> &PluginKey
Provenance-qualified key.
Implements: Clone, Debug
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.
pub fn for_library(library_id: &str) -> Self
The state directory leaf of the library with library_id.
pub fn as_str(&self) -> &str
The directory leaf (link- + 32 hex digits).
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
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
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.
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).
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
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_SECSin a session), so a late-committing publication is never behind a returned cursor.
Implements: Clone, Debug, Default
pub struct OutboxEventPublisher {
/* private fields */
}
EventPublisher server for one invocation: validates a guest
PluginEvent and appends it to the library outbox.
pub fn spec(&self, event: PluginEvent) -> Result<PublishDomainEventSpec, PluginError>
Validates event and builds the outbox row the host will insert.
forbiddenwheneventTypeis not a consented producer.payload_too_largewhenpayloadexceedsMAX_EVENT_PAYLOAD_BYTES.invalid_paramswhenpayloadis not UTF-8 JSON.
Implements: EventPublisher
pub struct DatabaseRegistry {
/* private fields */
}
Long-lived external database plugin for the active [database].plugin.
pub fn active(&self) -> Option<Arc<ExternalDatabase>>
Currently active external database guest for [database].plugin.
Implements: Clone, Default
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
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 (itsprefix).
Implements: Clone
pub struct DestinationRegistry {
/* private fields */
}
Long-lived external output plugins loaded at host startup.
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.
pub fn intakes(&self) -> Vec<DeployedIntake>
Every deployed drop folder, sorted by id.
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.
pub fn require_plugin_session(
&self,
plugin_id: &str,
account_id: &str,
) -> Result<DestinationSession, String>
Self::plugin_session that reports same-key ambiguity.
Returns an error when no guest is loaded, or when more than one session
matches plugin_id.
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
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].
pub fn from_granted_config(granted: &Value) -> Self
Reads the layout settings from a resolved CONFIG object.
Implements: Clone, Debug, Default, Eq, PartialEq
pub struct ExternalDatabase {
/* private fields */
}
External database backend spawned for [database].plugin.
pub async fn spawn(plugin: &DiscoveredPlugin, config: &Config) -> PluginResult<Self>
Spawn and describe a database plugin (connection happens later).
Returns an error when the operation fails.
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.
Returns an error when the guest cannot start or negotiate.
pub async fn connect(
&self,
config: &Config,
) -> Result<(DatabaseConnection, DbCapabilities), DbErr>
Open the library connection through the guest (database.openSession).
Returns an error when the operation fails.
pub async fn connect_without_migrate(
&self,
config: &Config,
) -> Result<(DatabaseConnection, DbCapabilities), DbErr>
Open the library connection without applying host schema (CLI migrate / version).
Returns an error when the guest cannot open a session.
pub fn library_backup_ops(&self) -> SharedAdapterBackupOps
Adapter snapshot/identity/restore hooks for the library session.
pub fn binding_backup_ops(&self, key: impl Into<String>) -> SharedAdapterBackupOps
Adapter snapshot/identity/restore hooks for one named binding session.
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).
Returns when capability flags are unknown or a schema batch fails.
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).
Fails closed when the adapter does not advertise
DbCapabilities::plugin_databases, when provisioning fails, or when
the registry cannot be recorded.
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.
Returns when the guest cannot open the binding or the proxy fails.
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.
Returns when the adapter is not installed, spawn fails, credentials are missing, or the guest refuses the delete.
pub fn adapter_plugin_key(&self) -> &str
Canonical PluginKey of this adapter guest.
pub fn first_party_kind(&self) -> Option<DatabasePluginKind>
Verified first-party adapter kind, if any.
Implements: Clone
pub struct ExternalIntegration {
/* private fields */
}
External integration backed by a discovered plugin binary.
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.
Returns an error when the guest cannot start or open fails.
pub fn bind_plugin_instance(&mut self, plugin_instance_id: &str)
Records the plugin instance id used to recognize this guest on reload.
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.
Returns an error when an entrypoint's health reports not ok.
Implements: Integration, SocketSink
pub struct ExternalSource {
/* private fields */
}
External content source backed by a discovered plugin binary.
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.
Returns an error when the guest cannot start or open fails.
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).
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.
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.
Returns an error when this source has no handed credentials, the
grant lacks the secrets binding, or the guest fails.
pub fn bind_plugin_instance(&mut self, plugin_instance_id: &str)
Records the plugin instance id used as this source's registry address.
pub async fn check_health(&self) -> Result<()>
Storefront health RPC.
Returns an error when the guest has no storefront or health reports not ok.
pub fn guest_pid(&self) -> Option<u32>
Native guest pid, when the session recorded one.
Implements: ContentSource
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 withcompleteits rows are all the account holds.
Implements: Clone, Debug, Eq, PartialEq
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
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.
pub fn node_id(&self) -> &str
This node's id.
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.
Returns an error when the files directory is unavailable.
pub async fn load_integrations(
&self,
services: &SessionServices,
) -> Result<IntegrationRegistry>
Spawns every present integration deployment.
Returns an error when the files directory is unavailable.
pub async fn load_destinations(&self) -> Result<DestinationRegistry>
Spawns every present storage deployment.
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.
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.
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
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
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
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
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.Nonefetches 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 forupdate; 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
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 forPluginWorker.open. -
spawn_config_table: JSON object passed intocrate::PluginSession::spawn_with.The session still applies
crate::spawn_config_for_grant. -
granted_config: JSON object the guest receives when the grant includesconfig. -
config_revision: Document revision this open applies.
Implements: Clone, Debug
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.
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.
pub fn binding_names(&self) -> Vec<String>
Granted binding names in manifest order.
pub fn namespaces(&self) -> Vec<(String, String, Arc<dyn KvNamespace>)>
Namespaces shaped for HostBindings::kv as (binding, namespace, kv).
Implements: Clone
pub struct LibraryKvNamespace {
/* private fields */
}
KvNamespace server for one (plugin_key, namespace) on the library.
pub fn new(store: LibraryStore, plugin_key: &str, row: &KvNamespaceManifest) -> Self
Builds one namespace directly (tests and in-process hosts).
pub fn namespace(&self) -> &str
Namespace this binding is scoped to.
Implements: KvNamespace
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.
pub async fn sleep_if_idle(&self) -> bool
Stops the guest now if it has been idle for the timeout.
True when a running guest was stopped.
Implements: Integration, OnDemandStatus, SocketSink
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.
pub async fn sleep_if_idle(&self) -> bool
Stops the guest now if it has been idle for the timeout.
True when a running guest was stopped.
Implements: ContentSource, OnDemandStatus
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.
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.
pub async fn sleep_if_idle(&self) -> bool
Stops the guest now if it has been idle for the timeout.
True when a running guest was stopped.
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.
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
pub struct OutboxQueueProducer {
/* private fields */
}
QueueProducer server for one binding of one invocation: validates a
guest QueueSendMessage and appends it to the library outbox.
pub fn queue(&self) -> &str
Queue this producer sends to.
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.
payload_too_largewhenbodyexceedsMAX_EVENT_PAYLOAD_BYTES.invalid_paramswhencontentTypeis unknown, ajsonbody is not UTF-8 JSON, or atextbody is not UTF-8.
Implements: QueueProducer
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.
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).
pub fn binding_names(&self) -> Vec<String>
Granted binding names in manifest order.
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
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_urlis 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 whereplugin.tomllives. -
min_host: Optional minimum Bookclerk host version required to run this plugin.
pub fn validate_against_crate_name(&self, crate_name: &str) -> Result<()>
Ensure metadata matches the crate naming taxonomy.
Returns an error when the operation fails.
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
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
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.
pub fn crate_name(&self) -> String
Format as bookclerk-plugin-{family}-{id}.
pub fn parse(name: &str) -> Result<Self>
Parse bookclerk-plugin-{family}-{id}.
Returns an error when the operation fails.
Implements: Clone, Debug, Deserialize<'de>, Display, Eq, PartialEq, Serialize
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
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-qualifiedbookclerk_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 (installedplugin.tomlSHA-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.
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.
pub fn from_plugin_on(
plugin: &DiscoveredPlugin,
account_id: &str,
transport: SpawnTransport,
) -> Self
Builds an identity for plugin spawned over transport.
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.
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.
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.
pub fn with_persisted_and_effective(
self,
persisted: &PluginGrant,
effective: &PluginGrant,
) -> Self
Fills revisions from a persisted operator grant and the effective runtime grant.
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
pub struct PluginSession {
/* private fields */
}
Host-side plugin session (one jailed child + one vat thread).
pub async fn spawn(
plugin: &DiscoveredPlugin,
config: &Config,
config_table: Value,
) -> Result<Self>
Spawns a plugin guest and connects Cap'n Proto on stdio.
Fails when the child cannot start, describe fails, or apiVersion is not 2.
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.
Fails when the child cannot start, describe fails, or negotiation fails.
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.
Fails when the child cannot start, describe fails, or negotiation fails.
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.
Fails when the front door (bookclerk-workerd + pinned workerd) is
missing, the child cannot start, describe fails, or negotiation fails.
pub fn instance_key(&self) -> &str
Isolation instance key (plugin_id:account_id).
pub fn account_id(&self) -> &str
Account scope carried on every PluginWorker.open invocation.
pub fn session_key(&self) -> &str
Expanded executor session key (artifact, role, grant revision, …).
pub fn guest_pid(&self) -> Option<u32>
Native guest PID (sibling jail) or the single child when there is none.
pub fn gateway_pid(&self) -> Option<u32>
Gateway / Cap'n Proto child PID for native-behind-workerd, when known.
pub fn guest_running(&self) -> bool
True when the guest process, and the gateway when one was spawned, are still running.
pub fn session_dir(&self) -> Option<&Path>
Host-owned gateway session directory, when this session has a sibling.
pub fn limits(&self) -> ScalarLimits
Negotiated scalar limits.
pub fn supports_server_copy(&self) -> bool
True when the guest accepted storage.copy.
pub fn storage_capabilities(&self) -> StorageCapabilities
The optional storage operations the guest accepted (storage.*).
pub fn id(&self) -> &str
Provenance-qualified PluginKey (canonical text).
pub fn alias(&self) -> &str
Manifest display / CLI alias (plugin.toml id).
pub fn data_dir(&self) -> &Path
Guest data directory.
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.
Returns a plugin error when PluginWorker.open fails.
pub async fn describe(&self) -> Result<PluginDescribe>
Calls PluginWorker.describe.
Returns a plugin error when the RPC fails.
pub async fn stream_copy(&self, job_id: &str, from: &str, to: &str) -> Result<JobOutcome>
Runs the stream-copy job handler on the guest.
Returns a plugin error when the handler fails.
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.
Returns a plugin error when the handler fails or the fence is lost.
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.
Returns a plugin error when the handler fails or the fence is lost.
pub fn describe_snapshot(&self) -> &PluginDescribe
Snapshot from the guest describe() call at spawn.
pub fn grant(&self) -> &PluginGrant
Covering consent grant from spawn.
pub fn require_binding(&self, name: &str) -> Result<()>
Fail closed when a delivery site needs an ungranted binding.
Returns an error when the binding is missing from the grant.
pub fn scratch_dir(&self) -> &Path
Guest TMPDIR / scratch directory.
pub fn guest_ipc_dir(&self) -> Option<&Path>
Directory the guest may use for pathname sockets, when this session has one.
pub fn package_sid(&self) -> Option<&str>
AppContainer package SID when the guest is jailed on Windows.
pub fn spawn_config(&self) -> &Value
Spawn config JSON captured at spawn.
pub fn has_entrypoint(&self, entrypoint: Entrypoint) -> bool
True when the guest exported entrypoint in describe().
pub fn consumes_event(&self, event_type: &str) -> bool
True when the guest's default entrypoint consumes event_type.
pub fn consumes_events(&self) -> bool
True when the guest's default entrypoint consumes any event type.
pub fn consumes_queues(&self) -> bool
True when the guest's default entrypoint consumes at least one
[[queues.consumers]] queue.
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.
Returns a plugin error when the guest did not export storefront or
the method fails.
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.
Returns a plugin error when the guest did not export metadata or the
method fails.
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.
Returns a plugin error when the guest did not export covers or the
method fails.
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.
Returns a plugin error when the guest did not export metadataFiles
or the method fails.
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.
Returns a plugin error when the guest did not export notifier or
the method fails.
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.
Returns a plugin error when the guest did not export ai or the
method fails.
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.
Returns a plugin error when the guest did not export ingress or the
method fails.
pub async fn deliver_webhook_wake(&self, event: WebhookDelivered) -> Result<()>
Tells the guest's webhookHandler entrypoint that requests wait for
one of its webhooks.
Returns a plugin error when the guest did not export webhookHandler
or its handler failed.
pub async fn deliver_socket_event(&self, event: SocketEvent) -> Result<SocketMessageOk>
Hands one socket event to the guest's socketHandler entrypoint.
The guest's reply to a message (whether it asks for an events poll now); the default for a close.
Returns a plugin error when the guest did not export socketHandler
or its handler failed.
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.
Returns a plugin error when the guest did not export remoteLibrary
or the method fails.
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.
Returns a plugin error when the RPC fails or is cancelled.
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.
Returns a plugin error when the guest did not export an event consumer, the RPC fails, or the delivery is cancelled.
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.
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.
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.
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.
pub async fn cli_describe(&self) -> Result<CliSchema>
Guest CLI schema.
Returns a plugin error when the RPC fails.
pub async fn cli_invoke(&self, params: CliInvokeParams) -> Result<CliInvokeResult>
Guest CLI invoke.
Returns a plugin error when the RPC fails.
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.
Returns a plugin error when the RPC fails.
pub async fn oidc_authenticate_user(
&self,
params: AuthenticateUserParams,
) -> Result<ExternalUser>
Verifies remote credentials through the guest oidc entrypoint
(Oidc.authenticateUser).
Returns a plugin error when the guest exports no oidc entrypoint or
the RPC fails.
pub async fn database_migrations(&self, binding: &str) -> Result<Vec<PluginMigration>>
Complete ordered plugin-owned migration sequence for one named binding.
Returns a plugin error when the RPC fails.
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.
Returns a plugin error when open / openSession fails or the guest
exports no databaseAdapter.
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.
Returns a plugin error when open / dropUnit fails or the guest
exports no databaseAdapter.
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).
Returns a plugin error when the guest rejects the open or the binding session fails host capability minima.
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.
Returns a plugin error when the binding is not open or the guest rejects the call.
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.
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.
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.
Returns a plugin error when the binding is not open, the guest rejects
the call, or cancel is set.
pub async fn db_capabilities(&self) -> Result<DbCapabilities>
Typed AdapterDatabaseSession.capabilities.
Returns a plugin error when the guest rejects the call.
pub async fn db_bootstrap(&self) -> Result<DbBootstrap>
Typed AdapterDatabaseSession.bootstrap.
Returns a plugin error when the guest rejects the call or lacks bootstrap.
pub async fn db_execute_request(
&self,
request: AdapterExecuteRequest,
cancel: Arc<AtomicBool>,
) -> Result<ExecuteReply>
Typed AdapterDatabaseSession.execute.
Returns a plugin error when the guest rejects the call or cancel is set.
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.
Returns a plugin error when the adapter rejects the call or does not
implement streaming, the frames break the budget, or cancel is set.
pub async fn db_execute_envelope_request(
&self,
envelope: AdapterExecuteRequest,
cancel: Arc<AtomicBool>,
) -> Result<ExecuteReply>
Typed HostAdapterDatabaseSession.execute.
Returns a plugin error when the guest rejects the call or cancel is set.
pub async fn db_txn_execute_request(
&self,
request: AdapterExecuteRequest,
cancel: Arc<AtomicBool>,
) -> Result<ExecuteReply>
Typed AdapterTransaction.execute on the vat-held open transaction.
Returns a plugin error when no transaction is open, the guest rejects
the call, or cancel is set.
pub async fn db_begin(&self, isolation: IsolationReq) -> Result<()>
Begin a vat-held transaction.
Returns a plugin error when begin fails.
pub async fn db_commit(&self) -> Result<()>
Commit the vat-held transaction.
Returns a plugin error when commit fails.
pub async fn db_rollback(&self) -> Result<()>
Roll back the vat-held transaction.
Returns a plugin error when rollback fails.
pub async fn db_begin_binding(&self, name: &str, isolation: IsolationReq) -> Result<()>
Begin a transaction on a named plugin database binding.
Returns when the binding is not open or begin fails.
pub async fn db_commit_binding(&self, name: &str) -> Result<()>
Commit a named plugin database binding transaction.
Returns when no binding transaction is open or commit fails.
pub async fn db_rollback_binding(&self, name: &str) -> Result<()>
Roll back a named plugin database binding transaction.
Returns when no binding transaction is open or rollback fails.
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.
Returns when no binding transaction is open or the guest rejects the call.
pub async fn db_export_identity(
&self,
binding: Option<&str>,
) -> Result<Vec<DbIdentityHighWater>>
Identity high-water from the adapter (open txn if any).
Returns when the session is closed or the guest rejects the call.
pub async fn db_import_identity(
&self,
binding: Option<&str>,
rows: Vec<DbIdentityHighWater>,
) -> Result<()>
Restore identity high-water into the adapter.
Returns when the session is closed or the guest rejects the call.
pub async fn db_list_user_relations(&self, binding: Option<&str>) -> Result<Vec<String>>
User-visible relation names from the adapter.
Returns when the session is closed or the guest rejects the call.
pub async fn db_prepare_unit_restore(&self, binding: Option<&str>) -> Result<()>
Prepare the open restore transaction.
Returns when the session is closed or the guest rejects the call.
pub async fn db_drop_user_relations(
&self,
binding: Option<&str>,
names: Vec<String>,
) -> Result<()>
Drop named user relations.
Returns when the session is closed or the guest rejects the call.
pub async fn db_assert_restore_constraints(&self, binding: Option<&str>) -> Result<()>
Fail closed when restore FK checks still fail.
Returns when the session is closed or the guest rejects the call.
Implements: Drop
pub struct PluginStorage {
/* private fields */
}
StorageBackend over a plugin destination capability (streams, fail-closed scalars).
pub fn new(session: Arc<PluginSession>) -> Self
Wraps a connected session after PluginSession::open granted the
storage entrypoint.
Implements: Clone, StorageBackend
pub struct RpcBackupOps {
/* private fields */
}
Send-safe backup primitives over a vat-held adapter session (or its open txn).
pub fn library(session: Arc<PluginSession>) -> Self
Library adapter session (no named binding).
pub fn binding(session: Arc<PluginSession>, name: impl Into<String>) -> Self
Named plugin-database binding (plugin_id/binding).
pub fn shared(self) -> SharedAdapterBackupOps
Shared handle stored on backup/restore options.
Implements: AdapterBackupOps
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 theEVENTSbinding.None(the default) never exposesEVENTS, even to a granted producer. -
spawn_transport: How the guest is reached. The default fronts every guest withbookclerk-workerd;SpawnTransport::DirectNativeDiagnosticis for tests and diagnostics only and no product binary selects it. -
selected_instance_id: Plugin instance id selected by CLI scan or acquire.Noneuses 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.
Nonegrants no output directory. -
deployed_endpoint: Network authority from the deployed instance document: the S3endpoint.Some(Some(url))grants that host in addition to the manifest's fixed TCP list;Some(None)records that the document names none;Nonemeans this spawn is not a deployed instance of such a plugin. -
sockets: The instance's socket broker, behind theSOCKETSbinding.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 thesocketstoken;Nonenever exposesSOCKETS. -
ai: The node's model router, behind theAIbinding.The session hands it out only when the manifest lists tasks under
[ai].callsand the covering grant has the token of at least one;Nonenever exposesAI. -
origin: The library as a relay ingress plugin reaches it, behind theORIGINbinding.The deployment sets it only for the library's active ingress instance. The session hands it out only when the manifest also exports
ingresswith[ingress] kind = "relay";Nonenever exposesORIGIN. -
webhooks: The deployed instance whose inbound webhooks back theWEBHOOKSbinding. The session hands the binding out only when the manifest declares[[webhooks]], the covering grant has thewebhookstoken and the library store is attached;Nonenever exposesWEBHOOKS.
pub fn with_event_outbox(store: LibraryStore) -> Self
Services with the library outbox attached.
pub fn from_outbox(store: Option<&LibraryStore>) -> Self
Services with the library outbox attached when store is present.
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
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;Nonewhen 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
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, forSettingGrantState::Invalid.state: Where the grant stands.
Implements: Clone, Debug, Eq, PartialEq
pub struct BrokerSockets {
/* private fields */
}
The SOCKETS binding a guest session hands out: the instance's broker.
pub fn new(broker: SocketBroker) -> Self
The binding for broker.
Implements: Sockets
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.
pub fn new(plugin: DiscoveredPlugin, config: Config) -> Self
A broker handle for plugin; nothing starts until the first
connect.
plugin- The deployed plugin; it must declare[sockets].config- Host config for the broker's spawn.
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.
pub fn open_sockets(&self) -> Vec<String>
Ids of the sockets the host believes open, oldest id first.
pub async fn connect(&self, request: SocketConnectRequest) -> AbiResult<SocketInfo>
Opens a socket, starting the broker when none runs.
The broker's refusal or dial failure, or unavailable when the
broker cannot be started.
pub async fn send(&self, socket: String, frame: SocketFrame) -> AbiResult<()>
Sends one message on an open socket.
not_found when the socket is not open; the broker's refusal.
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.
The broker's refusal of the code or reason.
pub async fn set_attachment(&self, socket: String, attachment: Vec<u8>) -> AbiResult<()>
Replaces a socket's attachment.
not_found when the socket is not open; the broker's refusal.
pub async fn list(&self) -> AbiResult<Vec<SocketInfo>>
The instance's open sockets, oldest first.
The broker's failure to answer.
Implements: Clone
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 afterlauncher(manifestargs; diagnostic transport only).native_backend: Native executable the host spawns as the sibling guest.Nonefor author isolates and direct native.workerd_bin: Pinnedworkerdthe launcher will spawn (must stay readable in the jail).runtime: Process tree this plan produces.
pub fn resolve(plugin: &DiscoveredPlugin, transport: SpawnTransport) -> Result<Self>
Resolves the launch for plugin on transport using the host's front door.
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.
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).
Same as Self::resolve; locator failures are wrapped in the
front-door refusal message.
pub fn fronted_by_workerd(&self) -> bool
True when bookclerk-workerd is the program the jail execs.
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.
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.
pub fn guest_executable_reads(&self) -> Vec<PathBuf>
Executables the native sibling jail may read (the backend only).
Implements: Clone, Debug, Eq, PartialEq
pub struct WorkerdFrontDoor {
pub launcher: PathBuf,
pub workerd_bin: PathBuf,
}
Resolved bookclerk-workerd launcher and the pinned workerd beside it.
Fields
launcher:bookclerk-workerdexecutable the jail execs.workerd_bin: Pinned Cloudflareworkerdthe launcher spawns.
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.
Returns an error naming what was looked for and where when either binary is missing.
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.
Returns an error when dir lacks bookclerk-workerd or workerd.
Implements: Clone, Debug, Eq, PartialEq
pub struct HostWebhooks {
/* private fields */
}
The WEBHOOKS hook of one session: the library, the deployed instance
and the declared rows.
Implements: Clone, Webhooks
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
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
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
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 unsupportedplugin.toml/ package manifest. -
Other: Catch-all for otherwise unclassified failures. -
RateLimited: The guest's backend asked it to slow down (ABIrate_limited);retry_afteris 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 wirecode(includingunknown).code: Wire error code (not_found,unknown, …).message: Operator-facing explanation.
pub fn message(msg: impl Into<String>) -> Self
Builds a PluginError::Message from any displayable string.
msg- Operator-facing explanation; must not embed secrets.
A message-only PluginError.
pub fn conflict(msg: impl Into<String>) -> Self
Builds a PluginError::Conflict.
pub fn unavailable(msg: impl Into<String>) -> Self
Builds a structured unavailable error (lost RPC, timeout, incomplete reply).
pub fn instance_selection(msg: impl Into<String>) -> Self
Instance id, plugin key, or alias cannot select exactly one instance.
pub fn is_instance_selection(&self) -> bool
True when spawn must stop instead of skipping this guest.
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.
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>
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::lendstarts it.
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.
Returns an error when an on-demand guest was retired or cannot start.
Implements: Clone
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
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
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>
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.
pub fn grant(&self) -> Option<&PluginGrant>
The grant to run with, when consented.
pub fn as_str(&self) -> &'static str
Stable text for observations and listings.
Implements: Clone, Debug, Eq, PartialEq
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
pub enum GuestRuntimeKind {
Workerd,
NativeBehindWorkerd,
NativeDirect,
}
Process tree the jail will contain, as reported in crate::ExecutorIdentity.
Variants
Workerd:bookclerk-workerd+ the pinnedworkerdrunning author modules.NativeBehindWorkerd:bookclerk-workerd+workerd(control plane) + the native guest.NativeDirect: The native guest alone, spoken to directly (diagnostic transport).
pub fn label(self) -> &'static str
Stable label used in executor identities and logs.
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.
pub fn fronted_by_workerd(self) -> bool
True when bookclerk-workerd is the program the jail execs.
pub fn for_manifest(runtime: PluginRuntimeKind, transport: SpawnTransport) -> Self
Runtime kind a manifest resolves to under transport.
Implements: Clone, Copy, Debug, Eq, Hash, PartialEq
pub enum SpawnTransport {
WorkerdFrontDoor,
DirectNativeDiagnostic,
}
Which transport a spawn uses to reach the guest.
Variants
-
WorkerdFrontDoor: Product path:bookclerk-workerdfronts 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
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.
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.
pub fn fence_plugin_key(plugin_key: &str)
Fences every live session for plugin_key (grant/authority change).
pub fn fence_stale_grant_revisions(plugin_key: &str, current_grant_revision: &str)
Fences live sessions whose persisted crate::grant_revision is not current.
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.
pub fn is_fenced(flag: &Arc<AtomicBool>) -> bool
True when this cancel flag has been fenced.
pub fn live_session_count() -> usize
Sessions currently registered with the process-wide authority table.
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.
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.
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.
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.
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.
pub fn spawn_grant_watcher(files_dir: PathBuf) -> Arc<AtomicBool>
Spawn the daemon grant watcher (fire-and-forget).
Stop flag; set it to end the loop (tests). Production callers leak the task until process exit.
pub fn unregister_session(flag: &Arc<AtomicBool>)
Drops a previously registered cancel flag from the live set.
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.
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.
files_dir- Host$BOOKCLERK_FILES_DIRthat ownsplugins/and the install ledger.
pub fn active_processes_for(runtime: GuestRuntimeKind, extra: u32) -> u32
Absolute Spec active_processes from runtime overhead + extra budget.
pub fn ai_task_grant(task: AiTask) -> String
Grant token for running models of task through the AI binding.
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.
pub fn consumers_cover(
existing: &BTreeSet<GrantedEventConsumer>,
requested: &BTreeSet<GrantedEventConsumer>,
) -> bool
True when every requested consumer is covered by some approved consumer.
pub fn cores_to_percent(cores: f64) -> u32
Convert cores to Spec/config percent-of-one-core, rounded to 0.01 core.
pub fn cron_grant(cron: &str) -> String
Grant token for firing the normalized cron schedule cron.
pub fn database_binding_name(binding: &str) -> Option<&str>
The binding name when a grant entry is a named database binding.
pub fn effective_cpu_cores(value: Option<f64>) -> f64
Clamp operator/manifest cores into 0.01..=host_cpu_cores_max.
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).
pub fn effective_disk_budget_bytes(grant: Option<&PluginGrant>) -> u64
Resolved disk budget in bytes for data/ and tmp/ checks.
pub fn effective_disk_mib(value: Option<u32>) -> u32
Resolved disk budget in MiB (default + host clamp).
pub fn effective_extra_processes(value: Option<u32>) -> u32
Clamp an operator/manifest extra-process budget (0..=PLUGIN_JAIL_EXTRA_PROCESSES_MAX).
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.
pub fn effective_memory_mib(value: Option<u32>) -> u32
Resolved jail Spec memory ceiling in MiB.
pub fn format_cpu_cores(cores: f64) -> String
Format cores for operator-facing text (0.80).
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.
pub fn grant_has_binding(grant: &PluginGrant, name: &str) -> bool
True when grant.bindings contains name (case-insensitive).
pub fn grant_revision(grant: &PluginGrant) -> String
Canonical SHA-256 of a grant's security-relevant fields (not presentation).
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.
pub fn granted_consumers_from_manifest(
manifest: &PluginManifest,
) -> BTreeSet<GrantedEventConsumer>
Consumers declared by plugin.toml as structural grant entries.
pub fn granted_database_bindings(grant: &PluginGrant) -> Vec<String>
Consented database binding names on a grant, in manifest-set order.
pub fn granted_jobs_from_manifest(manifest: &PluginManifest) -> BTreeSet<String>
Job trigger types declared by [triggers].jobs.
pub fn granted_queue_consumers(grant: &PluginGrant) -> Vec<String>
Consented queue consumer names on a grant.
pub fn host_cpu_cores_max() -> f64
Host max jail CPU in cores (logical_cpus as a 2 d.p. float).
pub fn host_cpu_rate_max() -> u32
Host CPU rate ceiling in one-core percent units (logical_cpus × 100).
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.
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.
cmd- Guest process command being prepared for spawn.grant- Effective covering grant for this plugin.
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.
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.
pub fn network_compatible(existing: &str, requested: &str) -> bool
Returns true when a stored network mode can satisfy a requested network mode.
existing- Network mode already approved by the operator.requested- Network mode requested by the current plugin manifest.
true when the modes match, or when an existing deny grant is stricter
than a requested outbound grant.
pub fn node_logical_cpus() -> u32
Logical CPUs visible to this process (at least 1).
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.
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 includeplugin).
pub fn pending_structural(
existing: &PluginGrant,
requested: &PluginGrant,
) -> PendingStructural
Structural capabilities the current manifest requests that the stored grant does not yet authorize.
pub fn percent_to_cores(percent: u32) -> f64
Convert Spec/config percent-of-one-core (100 = 1.00 core) to cores (2 d.p.).
pub fn queue_consumer_grant(queue: &str) -> String
Grant token for consuming queue.
pub fn queue_producer_grant(binding: &str) -> String
Grant token for sending through the [[queues.producers]] binding binding.
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 aseffective_grantdoes). A TCP denial removes the denied ports of that host. - Network mode stays
denywhen 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-Agenthosts 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.
existing- The stored grant for this PluginKey.requested- Consent request generated from the current manifest.
The normalized grant to store.
Returns PluginError when the draft fails validate_approved_grant
(for example a stored addition is no longer a valid pattern).
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.
pub fn require_binding(grant: &PluginGrant, name: &str) -> Result<()>
Fail closed when a delivery site needs a binding the covering grant lacks.
Returns an error when the operation fails.
pub fn require_grant(files_dir: &Path, plugin: &DiscoveredPlugin) -> Result<PluginGrant>
Require an operator grant before enable or every external spawn.
files_dir- Bookclerk files directory containingplugin-grants.json.manifest- Plugin manifest whose id must have a stored grant.
Effective PluginGrant (operator approval, host-normalized).
Returns PluginError when no grant exists for the plugin id.
pub fn spawn_config_for_grant(grant: &PluginGrant, config_table: Value) -> Value
Spawn config payload: non-empty settings only when the grant includes config.
pub fn spawn_grant(files_dir: &Path, plugin: &DiscoveredPlugin) -> Result<PluginGrant>
Resolve the covering grant for spawn: verified platform auto-grant, else require_grant.
Returns an error when the operation fails.
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.
approved- Operator-supplied grant draft.baseline- Consent request generated from the current manifest.
A normalized grant with plugin identity and a fresh approved_at.
Returns PluginError when identity mismatches, network mode is invalid,
a binding is unknown, or a domain pattern cannot be normalized.
Panics when an internal invariant does not hold.
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.
manifest- Installed manifest for the plugin.grant- Effective covering grant.described- Capability block the guest returned fromdescribe().portal_auth_mode- Storefront connect mode fromdescribe().
Returns an error naming the first widening capability or missing grant.
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.
manifest- Installed manifest for the plugin.described-configOptionsthe guest returned fromdescribe().
Returns an error naming the first key or value that differs.
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.
manifest- Installed manifest for the plugin.described- The guest'sdescribe()reply.
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).
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.
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.
Returns an error when the operation fails.
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.
Returns an error when plugin-packages itself cannot be read. One bad
package is skipped and does not abort the rest of the directory.
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.
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.
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.
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.
Returns an error when no destination is deployed on this host.
pub fn build_storage_backend(
destinations: &DestinationRegistry,
) -> Result<Box<dyn StorageBackend>>
Build listing/storage backends from the deployed output plugins.
Returns an error when no destination is deployed.
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).
Returns PluginError on duplicate keys, duplicate aliases, missing binaries, or I/O failures.
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.
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).
plugin_key- CanonicalPluginKeytext.alias- Manifest display id.spec- Occupancy selector fromoccupancy_specor a job/CLI id.
pub fn is_first_party_local_output(plugin: &DiscoveredPlugin) -> bool
True when this install is the verified Bookclerk local-filesystem destination.
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.
key- Durable plugin identity to classify.
true for the first-party local destination package on a first-party
provenance scheme.
pub fn is_first_party_s3_output(plugin: &DiscoveredPlugin) -> bool
True when this install is the verified Bookclerk S3 destination.
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.
spec- Occupancy selector from config (plugin = "…").alias- Display alias or first-party kind token being compared.
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).
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.
plugin_field- Occupancy string from config (plugin = "…").alias- Display alias used whenplugin_fieldis empty.
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.
plugin- Candidate install.spec- Occupancy selector fromoccupancy_spec.
pub fn plugin_search_dirs(config: &Config) -> Vec<PathBuf>
Resolve search roots: BOOKCLERK_PLUGIN_DIRS then $FILES_DIR/plugins.
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.
Returns an error when spec matches nothing, or when corrupt disk state
contains duplicate keys or aliases.
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.
plugins- Already-filtered family candidates.spec- Occupancy selector fromoccupancy_spec.
Returns PluginError when two installs share the alias (or PluginKey).
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.
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.
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.
Returns an error when plugin is not a database adapter.
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.
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.
Returns an error when discovery or the grant store cannot be read.
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.
Returns an error when a schema, instance, document, or deployment write fails.
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.
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.
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.
pub fn manifest_event_subscriptions(
manifest: &PluginManifest,
) -> Vec<EventCatalogSubscription>
Catalog rows for a manifest's [[events.consumers]] declarations, before
consent narrows them.
pub fn backup_adapter_id(plugin_id: &str) -> String
Adapter id recorded on a backup (diagnostic; restore is capability-driven).
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.
Returns an error when plugin data paths, secrets, or context encoding fail.
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.
Returns when a binding is inaccessible.
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).
Returns an error when the operation fails.
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.
Returns an error when the operation fails.
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).
Returns when the guest cannot start, connect, or apply schema.
pub async fn open_library_store(
config: &Config,
registry: &DatabaseRegistry,
) -> Result<LibraryStore>
Open bookclerk_library::LibraryStore via the external database guest (required).
Returns an error when the operation fails.
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).
Returns an error when the operation fails.
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.
Returns when provisioning or canonical restore fails. Partial completion is reported in the error message.
pub async fn storage_role(
store: &LibraryStore,
plugin_instance_id: &str,
) -> Result<StorageRole>
Reads the role of the storage instance plugin_instance_id.
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.
pub fn allow_credential_login(granted_config: &Value) -> bool
allow_credential_login from the resolved CONFIG; absent means allowed.
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.
Returns an error when the secret root or node identity cannot be established, or enrollment fails as a whole.
pub async fn open_host_control_plane(config: &Config) -> Result<HostControlPlane>
Opens the library database and the control plane for config.
Returns an error when the database cannot be opened, the secret root or node identity cannot be established, or enrollment fails as a whole.
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.
Returns an error when bootstrap or enrollment fails.
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.
Returns an error when the deployment table cannot be read.
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.
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.
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.
Returns an error when an instance or document write fails.
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.
pub fn host_artifact(version: &PluginVersion) -> Result<&PluginArtifact>
The version artifact this node runs.
Returns an error naming the host target when the version has none for it, so placement can exclude this host.
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.
Returns an error when the coordinate yields no key or the alias is installed under several keys.
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.
Returns an error when the key cannot be derived, the alias belongs to another plugin, or installing, approval, or enrollment fails.
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.
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).
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.
As materialize_version, and when the owner's URL is refused.
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.
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.
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.
Returns an error when the tree's manifest is unreadable or names another plugin, or the version has no approved grant yet.
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.
Returns an error when the mutation lock cannot be taken.
pub fn version_cache_path(files_dir: &Path, payload_root_sha256: &str) -> Result<PathBuf>
Cached tree of one payload-root digest.
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.
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).
Returns an error when the recorded plugin.toml or plugin key no longer
parses.
pub fn version_grant(version: &PluginVersion) -> Result<PluginGrant>
The consent grant recorded on version.
Returns an error when no operator has approved the version yet or the recorded grant is malformed.
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.
Returns when a plugin.toml cannot be read or parsed, or a PluginKey
cannot be formed for an occupant.
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.
Returns a catalog error when the lock does not cover this plugins root, preflight rejects the alias, or install fails.
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.
Returns a catalog error when the lock does not cover this plugins root, preflight rejects the alias, or install fails.
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.
Returns PluginError when the alias is occupied by another PluginKey or
occupancy cannot be read.
pub fn binding_grant_flags(grant: &PluginGrant) -> InstanceBindingGrant
config / secrets flags of the plugin's covering grant.
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.
Returns an error when the grant cannot be loaded, the instance is not this plugin's, or its document cannot be 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.
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.
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.
Returns an error when the operation fails.
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.
manifest- the installed manifest the deployment spawns.
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.
manifest- the installed manifest the deployment spawns.
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.
manifest- the installed manifest the deployment spawns.
pub fn family_keyword(family: PluginFamily) -> &'static str
Family-specific crates.io keyword (bookclerk-source, …).
pub fn host_target_triple() -> &'static str
Host target triple used when selecting release assets.
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).
Returns an error when the operation fails.
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.
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).
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.
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.
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.
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).
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.
reviewed- The owner's request as this host's operator approved it.requested- The owner's current request.
A header line then one indented line per kind of widening, or nothing.
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.
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.
row- The consent row as stored.
pub fn plugin_instance_key(plugin_id: &str, account_id: &str) -> String
Isolation key: different accounts never share a plugin isolate.
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.
grant- The covering grant for this spawn (mutated in place).manifest- The plugin being spawned.settings- The instance's effective settings (the spawnCONFIG).
The status of each network setting, for the plugin's feedback.
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.
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.
The new PluginGrant::setting_destinations.
pub fn destinations_in_use(rows: &[InstanceSettingStatuses]) -> SettingDestinationMap
The destinations rows name, per setting key, for
approve_setting_destinations's in_use.
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.
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.
One entry per instance, oldest first.
Returns an error when the instances or a document cannot be read.
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.
grant- The effective spawn grant.statuses- Whatapply_setting_destinationsreturned for it.
The grant as the ABI carries it, within the schema's list bound.
pub fn network_settings(manifest: &PluginManifest) -> impl Iterator<Item = &SettingSpec>
The settings of manifest that declare network, in declaration order.
pub fn setting_grant_statuses(
manifest: &PluginManifest,
settings: &Value,
grant: Option<&PluginGrant>,
) -> Vec<SettingGrantStatus>
Derives the destination each network setting names in settings.
manifest- The plugin whose[[settings]]declare the networks.settings- One instance's effective settings (defaults applied), as the JSON object the guest'sCONFIGcarries.grant- The stored grant, which decides approved against pending.
One status per network setting, in declaration order.
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.
files_dir- This install's files directory.link- The joined library's state directory leaf.
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.
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.
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.
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.
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.
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.
pub fn webhook_public_origin() -> Option<String>
The origin webhook URLs are built on, when one is set.
pub type SessionShutdown = Arc<dyn Fn() + Send + Sync>;
Shutdown hook invoked the moment a live session is fenced.
pub type Result<T> = Result<T, PluginError>;
Result alias for PluginError.
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.
pub type SettingDestinationMap = BTreeMap<String, BTreeSet<SettingDestination>>;
Per setting key, the destinations a plugin's instances name now.
pub const AI_BINDING_RUN_TIMEOUT: Duration = _;
Longest one run through the AI binding may take.
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.
pub const GRANT_WATCH_INTERVAL: Duration = _;
How often the daemon re-reads plugin-grants.json when no in-process notify fires.
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.
pub const GRANTS_FILE: &str = "plugin-grants.json";
Filename under $BOOKCLERK_FILES_DIR for persisted grants.
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.
pub const KNOWN_HOST_BINDINGS: &[&str] = _;
Host binding names operators may grant (widen or narrow).
pub const PENDING_HEADER: &str = "Awaiting consent (not automatically approved):";
First line of PendingStructural::summary_lines and
crate::remote_request_changes.
pub const PLUGIN_JAIL_ACTIVE_PROCESSES_MAX: u32 = 64;
Absolute OS jail PID ceiling (overhead + extra, inclusive).
pub const PLUGIN_JAIL_CPU_CORES_DEFAULT: f64 = 0.80;
Default jail CPU as cores (PLUGIN_JAIL_CPU_RATE_DEFAULT / 100).
pub const PLUGIN_JAIL_CPU_RATE_DEFAULT: u32 = 80;
Default jail Spec CPU rate percent for confined guests (one-core units).
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).
pub const PLUGIN_JAIL_EXTRA_PROCESSES_DEFAULT: u32 = 2;
Default extra processes/threads beyond launcher overhead.
pub const PLUGIN_JAIL_EXTRA_PROCESSES_MAX: u32 = 62;
Host hard cap for per-plugin extra process budget.
pub const PLUGIN_JAIL_MEMORY_MIB_DEFAULT: u32 = 512;
Default jail Spec memory ceiling (MiB) for confined guests.
pub const PLUGIN_JAIL_MEMORY_MIB_MAX: u32 = 4096;
Host hard cap for per-plugin jail memory overrides (MiB).
pub const PLUGIN_STATE_BUDGET_MIB_DEFAULT: u32 = 512;
Default per-plugin data/ and tmp/ disk budget (MiB each).
pub const PLUGIN_STATE_BUDGET_MIB_MAX: u32 = 4096;
Host hard cap for per-plugin disk budget overrides (MiB).
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.
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.
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.
pub const WORKERD_GRANT_CPU_MS_ENV: &str = "BOOKCLERK_WORKERD_GRANT_CPU_MS";
Grant CPU budget (ms) for workerd logging / limit narrowing.
pub const WORKERD_GRANT_DOMAINS_ENV: &str = "BOOKCLERK_WORKERD_GRANT_DOMAINS";
Comma-separated grant domain allowlist for workerd egress.
pub const WORKERD_GRANT_NETWORK_MODE_ENV: &str = "BOOKCLERK_WORKERD_GRANT_NETWORK_MODE";
Env keys consumed by bookclerk-workerd (grant.rs) at isolate start.
pub const WORKERD_GRANT_POLICY_ENV: &str = "BOOKCLERK_WORKERD_GRANT_POLICY";
Canonical JSON EgressPolicy (preferred over piecemeal domain env vars).
pub const WORKERD_GRANT_SUBREQUESTS_ENV: &str = "BOOKCLERK_WORKERD_GRANT_SUBREQUESTS";
Grant subrequest budget injected into workerd EGRESS_POLICY.
pub const AUTHORIZED_PACKAGE_DIR: &str = "plugin-packages";
Directory under the files dir that holds operator-placed package archives.
pub const INGRESS_HEALTH_INTERVAL: Duration = _;
How often a running ingress is asked whether it is serving.
pub const VERSION_CACHE_DIR: &str = ".versions";
Directory under plugins/ holding materialized version trees.
pub const VERSION_CACHE_GRACE: Duration = _;
How long an unreferenced cached digest survives before the sweep.
pub const KV_GRANT_BINDING: &str = "plugin_kv";
Grant token that authorizes every [[kv_namespaces]] row of a plugin.
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.
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.
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.
pub const CRATE_NAME_PREFIX: &str = "bookclerk-plugin-";
Required crates.io name prefix: bookclerk-plugin-{family}-{id}.
pub const PRODUCT_KEYWORD: &str = "bookclerk";
Shared crates.io keyword (bookclerk) expected on published plugin crates.
pub const REGISTRY_KEYWORD: &str = "bookclerk-plugin";
Keyword every published plugin crate should include.
pub const HOST_SHARED_ACCOUNT: &str = "host";
Registry-loaded source/integration guests (not a user account).
pub const OPERATOR_ACCOUNT: &str = "operator";
Isolation key: different accounts never share a plugin isolate.
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.
pub const WORKERD_LAUNCHER_ENV: &str = "BOOKCLERK_PLUGIN_WORKERD";
Override for the bookclerk-workerd launcher path (tests / packaging).
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.
pub const TEST_CHANNEL_TAG_FILE: &str = "channel-tag";
Session-directory file holding the tag when TEST_CHANNEL_IDENT_ENV is set.
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.
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.
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.
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.
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