meinKontextDocs
Navigation & Suche

Plugin SDK

API-Referenz

Öffentliche SDK-Exporte, Host-Schnittstellen, Berechtigungen und Abfragen.

SDK 0.1 · ExperimentalMarkdown

Diese technische Anleitung wird derzeit auf Englisch gepflegt. Navigation und Nutzer-Anleitungen sind auf Deutsch verfügbar.

Start with AUTHORING.md. This reference describes the implemented public interfaces, not the broader plugin roadmap. Type declarations in the package exports are the exact signature contract.

Exports

ImportContents
@meinkontext/plugin-sdkBrowser-safe schema/reference primitives, codecs, runtime/host types, query vocabulary, context and tool definitions, execution-grant types, fail(code) for public workflow error codes.
/contractsManifest, reference and JSON Schema primitives; no domain schemas.
/contracts/*.jsonDistributable generic schemas. Domain schemas ship in their owning plugin.
/declarativeExperimental declarative definition parser and exact installed-release resolver over trusted metadata. No execution, persistence or authorization. See contract guide.
/serverReviewed catalog compilation, compatibility and policy helpers. This does not create a durable host or authenticate a caller.
/proceduresv2, browser-safe. The API procedure descriptor (definePluginProcedures), its wire envelopes, the generic host procedures of a namespace (hostProcedures) and the overview declaration (definePluginOverview). See SDK v2.
/context-file-answersv2, browser-safe. The answer shapes of a plugin's file procedures over a ContextFilesApi (contextFileEntrySchema, contextFilePageSchema, contextFileContentSchema, contextFileReviewSchema): one definition for every file-serving plugin (the Explorer, the Wiki's Files tab), so one browser file component reads them.
/plugin-serverv2, server only. The server contribution (definePluginServer): procedure handlers, refuse(code), the action-item resolver, the overview and background jobs (PluginJob, pluginJobQueue). Re-exports /procedures.
/browser-registrationv2, browser. The browser entry (defineBrowserPlugin): a route subtree, navigation entries, lazily loaded views and the data port (BrowserDataPort, including useIntent(target), the durable idempotency intent of a write that must land at most once), plus the shell's matcher (matchBrowserRoute, browserRouteParameters, browserRouteHref).
/intentsv2, browser. The state machine behind BrowserDataPort.useIntent (createIntentStore, useIntentFrom, payloadDigest) and memoryIntents() for a test double of the port. Rules: V2-PLUGIN-UI "Durable intents".
/commandsv2, browser. A plugin view's commands and action items, once for every plugin: useCommand (one write intent with its idempotency key; createIntent is its lifetime without React), failureText (what a refused or lost write tells the person, extended by the plugin's own codes) and the action-item strip (actionItemStripLoader, useActionItemStrip, the paint rule actionItemStripState; the organism that draws it is the plugin's to pass in). React and the SDK's own browser types only.
/evalsPluginEvalSuite, PluginEvalCase, AgentResult, EvalCheck, evalPassed, parsedRow (a stored row through the plugin's own schema, or undefined — evals read typed fields instead of casting). No inference runtime.
/context-filesContextFilesApi and file/list/content types for the optional trusted web file capability.
/execution-clientTrusted external-client grant lifecycle. Keep outside the model tool surface.
/datasetsReport datasets (PLUGIN-REPORTS RP-01): PluginDatasetHandler/datasetHandler, DatasetResult, datasetRangeSchema (a period of at most 366 days), and the shared export cells csvCell (formula neutralization), markdownCell, datasetCsv, datasetMarkdown, datasetFile, and answerDatasetFixture for fixtures pages. See Report datasets.
/dataset-perioddatasetPeriodBounds(range, zone) and datasetDayStart(date, zone): a period of the person's local days as instants, with Temporal (@js-temporal/polyfill), in its own subpath so a browser bundle that imports /datasets does not carry the polyfill.
/report, /report-uiThe generic report procedure hostDataset (reportProcedures) and the report page datasetReportView (PLUGIN-REPORTS RP-05), kept out of /procedures so the shell's validation chunk does not carry them. See Report datasets.

Views use /browser-registration, server code /plugin-server.

ActionItem.readAction has three shapes: an MCP read tool ({ tool, arguments }), a plugin record ({ resource }), and since AV05-S05d { href } — settled by a person in the browser at that account page, with no reader for an agent. href must pass actionItemHrefSchema (exported from the package root): a same-origin relative path under /account/; absolute, protocol-relative or backslash URLs, other schemes and paths outside the account are refused. Only platform entries carry it, never a plugin's own: a resolver that narrows with "resource" in must also skip "href" in (TypeScript then asks for it), as the in-repo resolvers do. list_action_items adds the agent-facing sentence "A person settles this in the browser at <href> …" to such entries.

ActionItem.workspace is required (ActionItemHome, the shape of CollectionHome): { own: true, id, name } for one of the reading person's workspaces, { own: false, id } for the workspace of another account that shares the record's root (its name is never given). A plugin entry carries its record's root's home; a platform entry carries the person's Standard workspace. No entry is without a workspace, and none names "all".

Imports from /src/* are unsupported. The SDK depends on no meinKontext application/domain package: pnpm plugin:verify-external installs the packed SDK in a clean directory, finds no other @meinkontext/* package there and no type declaration naming one, and compiles the example plus a module using every v2 entrypoint with skipLibCheck: false.

SDK v2: procedures, jobs and browser entry

The v2 platform has no server-side rendering: a plugin contributes typed API procedures to the api fleet, MCP tools to the mcp fleet, background jobs to the worker fleet and a lazily loaded browser entry to the web build. The platform composes them from the reviewed catalog; a plugin still imports only the SDK (and, in the repository, @meinkontext/ui). The domain runtime (definition, codec, project, plan, policy, tools, context) is the same object on both stacks and is unchanged by v2. The binding contract of the platform side is the repository's docs/architecture/V2-PLUGINS.md; this section is what an author writes.

PartModule of the pluginSDK importComposed into
Procedures (descriptors)src/procedures.ts, browser-safe/proceduresthe api contract and its OpenAPI document; the browser data port
Server contributionsrc/server.ts, export ./server (export const server)/plugin-serverapi (procedures), worker (jobs), the account overview
MCP toolsthe runtime's tools, dynamicTools, contextrootmcp, unchanged (PluginTool, PluginToolContext)
Browser entrysrc/browser.ts, export ./browser (export const browser)/browser-registrationthe web build, one lazy chunk per plugin

A tool (PluginTool, and a derived DynamicPluginTool) may set recoveryHints: its own recovery text per refusal code, which the client reads after the code in place of the platform's generic text. Only the codes of pluginRecoverableCodes take one (UNAVAILABLE, INVALID_INPUT, INVALID_QUERY, UNKNOWN_ACTION, REVISION_CONFLICT, IDEMPOTENCY_CONFLICT, CONTEXT_TARGET_UNAVAILABLE): codes a caller fixes by naming another record, owner or input. The platform's safety texts (APPROVAL_REQUIRED, HOST_BUSY, EXECUTION_DENIED, credential, quarantine and release codes) cannot be replaced: definePluginTool refuses any other key, and both MCP registrations drop it. One text answers every refusal of its code, so it must not depend on why the call was refused (a wrong owner and an unreadable record read alike).

Procedures

definePluginProcedures(pluginId, specs) turns each spec into a PluginProcedure. The path is /api/v2/<namespace><segment>; the namespace is the last dot segment of the manifest id (acme.notes → /api/v2/notes), and the platform refuses a namespace it reserves (session, workspaces, events, auth, mcp, objects, memory, buckets, plugins, account, public) or one two composed plugins share.

FieldRule
methodGET (read) or POST (mutation)
segment"" or /word and /:param segments; every parameter is an input field; /host is reserved
input, outputzod object schemas; the input is strict, the output is checked on every answer
consistencyfresh (default). recent is refused until host reads without row locks admit replica reads
callers["session"]: the human browser session only. OAuth clients and managed, execution-grant and context-read credentials are refused with 401 and use MCP tools
mutation keya POST input carries idempotencyKey (procedureIdempotencyKeySchema, 1–128 characters); pass it to host.execute, so a retry applies once
downloadGET only: { filename }, sent as an attachment
notFoundGET only: "record" for a read of one record. Its refuse("NOT_FOUND") and the host's UNAVAILABLE/ARCHIVED answer 404 RESOURCE_MISSING once the platform re-read the caller's plugin scope, and the browser drops only that query (a record deleted while its detail is shown); without it, and for workspace or plugin refusals, every 404 ends the page's data scope (V2-PLUGINS.md, "Errors")
confidential, authorizationCallbackPOST only: an input that carries a credential-like value (an OAuth code), or a procedure that uses a protected host function; the answer gets Referrer-Policy: no-referrer, a request whose Sec-Fetch-Site is not same-origin is refused, a callback's owner comes from the stored one-use state
bodyLimitPOST only: the request body limit in bytes, 1 to PROCEDURE_BODY_LIMIT_MAX (8 MiB); unset, the API's 256 KiB. The input schema still bounds every field
keyedPOST only, and only for a plugin whose manifest declares context.files: the platform runs the procedure in its keyed idempotency transaction, and context.files' Core and memory reads and writes run in it, so the write commits with the answer, which must be a receipt (id, replayed); a retry with the same key replays it, the same key with another body is IDEMPOTENCY_CONFLICT, a refusal rolls back and frees the key. The request's owner must be the person's own organization (404 otherwise). Writes to a mounted file (fileMounts), through context.host or executeReviewed keep their own transactions and are not rolled back with the receipt. A plugin without context.files may key a host write too (Messages' createChannel): it validates everything first and keys its first host write with the request's key (createCollection({ initialCommand })), because a receipt lost after the host writes committed makes a resend run the handler again, which the host then refuses with IDEMPOTENCY_CONFLICT instead of writing twice. While its host writes run, the keyed transaction holds a second pooled connection (docs/ENGINE-KNOWLEDGE.md)

The envelopes procedurePageRequestSchema, procedurePageSchema(item, size), procedureMutationSchema and procedureReceiptSchema equal the platform's wire shapes. Descriptors grant nothing: the binder checks every rule again and the host authorizes every read and command.

Server contribution

ts
export const server = definePluginServer({
  runtime,                  // the plugin's DomainRuntime, unchanged
  procedures,               // from definePluginProcedures
  handlers: { list: async (input, { host, identity, ownerOrganizationId, requestId }) => … },
                            // mutations also get executeReviewed
  errors: ["NOTE_LOCKED"],  // the domain codes refuse() may use
  actionItems,              // optional: the same resolver loadActionItemViews takes
  overview,                 // optional: definePluginOverview(...)
  jobs: [],                 // optional: PluginJob[]
});

parallelGets names POST procedures whose preliminary host.get calls may overlap because their own state machine, such as an external-effect lease, already coordinates callers. Every other mutation keeps the bounded per-owner queue. This declaration is server-contribution metadata, not a browser procedure-descriptor field; an unknown name or a GET is rejected when the server contribution is defined.

Every procedure has exactly one handler. A handler calls the plugin's own commands and queries through context.host (the selected owner organization and workspace) and adds no rule the runtime does not have. context.workspace is the request's explicit workspace scope, never absent: { kind: "workspace", workspaceId }, or { kind: "all" } for every workspace the person is admitted to, as the old pages without ?workspace=. Under all the host lists the union, every root with its own workspace, and host.root() names the Standard workspace's root, where a new record lands. Read it only where the old page decided by its workspace. The host serves the plugin plus the target plugins of its manifest's optionalIntegrations (servedPluginIds in the platform's binder): the host derives active integration features and resolves another plugin's public contract from the runtimes it serves, and a target the composition does not serve stays absent. Serving a target grants nothing: the host authorizes every record read and command, and an integration feature stays required where the manifest requires it.

A read (GET) procedure's handler gets a ReadProcedureContext: its context.host and every context.owners.host(owner) are read-only views (readOnlyPluginHost). A GET skips the API's CSRF and Origin checks, so a write from it would be reachable cross-site. The write methods (execute, root, archive, acknowledge, external.invoke, the access and collection setters and the rest) are typed so that a direct call does not compile, and at runtime each refuses FORBIDDEN, also when the view is passed to a helper typed with the full PluginHostApi. Use findRoot instead of root in a read. A helper that both reads and mutations call takes ReadProcedureContext; a mutation's ProcedureContext satisfies it. PluginServer.downloadFiles gets the same read-only context.

Mutation (POST) procedures also receive context.executeReviewed(command) (APPROVED-COMMANDS.md): the browser session's explicit submission approves exactly the submitted command, which the host mints and consumes in one call (fixed audience, live access, expected revisions, policy epoch). It is passed only for an action of the procedure's own plugin that the manifest marks requiresApproval; any other action is refused FORBIDDEN before the host, and neither a GET procedure nor an authorizationCallback procedure receives it. The procedure must still show a real review step before the submission. executeReviewed(command, { replayOnly: true }) runs the same approval and every authorization, then answers only the receipt this caller stored under this key for the identical command; without one the host refuses REPLAY_UNAVAILABLE and runs nothing (for a retry a plugin may answer but must not execute again, as Messages' release from an already retired draft); a procedure that lets it through answers a final 409 REPLAY_UNAVAILABLE. The host looks up a command's stored receipt before it compares the expected revisions, so a retry under the same key answers its receipt even after a dependency moved on, while a fresh command with a stale revision is refused REVISION_CONFLICT. Every procedure also receives context.reportUnexpected(error, fields) for a failure it does not answer with, such as a best-effort step after a successful write: the API writes its error line with the plugin and request id and, where configured, reports it to the error tracker. The platform keeps only allowlisted fields: <name>Id with a UUID, and procedure, step or code with a short code (letters, digits, _.:-, at most 64 characters); every other field or value is dropped.

servedPluginIds, ProcedureContext.executeReviewed and the generic action-item read's prefetch of records named through a notice rule's tool arguments are platform amendments the operator accepted on 2026-10-31 (.ytstack/DECISIONS.md; AV05-S03e, #867). The SEC delta review of plugin routes (X19) covers all three amendments. It refuses with refuse("NOT_FOUND") (404), refuse("FORBIDDEN") (403) or a declared domain code (422). Host conflicts answer 409, an unavailable or disabled plugin 404, anything undeclared 503 UNAVAILABLE. A readable record of another plugin answers 404 like an unreadable one.

A procedure's path and body arrive as the typed input, strings are rendered by the browser in DE/EN, collections and the derived root are on context.host (root()), files, buckets and plugin management belong to the platform rather than to the procedure context, and the control plane is the protected host functions below. Where a page lists its own and its bucket-shared roots together, context.owners gives host(owner) and collections(pluginId) across the person's owners (the Wiki index); every read through it is still authorized by that owner's host. A plugin that streams files declares definePluginServer({ downloadFiles: (scope, context) => files }), which the platform serves at GET /api/v2/files/plugin/<namespace>/<scope>.

Protected host functions

ProcedureContext carries the control plane as optional members (AV05-S01k; contract and limits in the repository's docs/architecture/V2-PLUGINS.md). A member is absent at runtime wherever it does not qualify, so check it and refuse when it is missing. Only the verified browser session reaches a handler, and every call serves the request's one owner: the members take no owner argument.

MemberNeedsOn
confidentialStorage.configuredprotected-payloads.v1 or external-effects.v1every procedure. A configuration hint, not a health check or a grant
confidential (commit, reveal, exportEncrypted, exportEncryptedMany)protected-payloads.v1a confidential POST. commit takes the plugin's own actions, the others only its own records
external.reviewexternal-effects.v1every procedure, for the plugin's own record
external.bind, bindFrom, unbind, unbindShared, rejectReview, approveReview, reviewAndInvokeexternal-effects.v1a confidential POST, for the plugin's own record; unbindShared then removes every binding of that credential by this person, on any plugin's resources
authorization.startexternal-effects.v1 and a callback patha confidential POST, for the plugin's own record
authorization.completeexternal-effects.v1 and a callback paththe authorizationCallback procedure only, for exactly the state the platform resolved
executeConfiguredexternal-effects.v1 and controlPlaneActionsa confidential POST, for those actions
authorizedClientsexternal-effects.v1every procedure: the session's current consents, never credentials
directory (canModerate, search, get, submissions)a runtime directoryevery procedure, for the plugin's own id
directory.submit, directory.moderatea runtime directorya confidential POST, for the plugin's own id

An action, state or directory id that is not the plugin's rejects with FORBIDDEN before the host; a record of another plugin answers 404 like an unreadable one. Any other failure rejects with an Error whose message is the host's code (EXECUTOR_UNAVAILABLE, REVIEW_NOT_PENDING, …): catch the codes you expect and refuse a declared domain code, or it answers 503. An authorizationCallback procedure gets complete and no other change. CONFIDENTIAL-EXTERNAL.md describes the semantics.

Generic host procedures. Every composed plugin's namespace also serves hostProcedures(pluginId): hostActionItems (the reader's action items with the plugin's resolver, counts per view, actionItemBadgeCount), hostExport (the plugin-wide export, also for a disabled plugin) and hostReferenceOptions (pickers over another plugin's public contract the plugin declares as an optional integration). A browser chunk calls only its own namespace, so it reads these descriptors from /procedures like its own.

Overview. definePluginOverview(pluginId, { navigation, counts, examples }) declares the navigation entry (/account/ href), the counted formats and the overview examples once; the contribution reads that value.

Jobs. A PluginJob is background work: name ([a-z][a-z0-9-]*, queue pluginJobQueue(pluginId, name) = plugin.<id>.<name>), execution ("worker", the default, on the keyless worker fleet; "api-read" on the api fleet, which holds the executor, for a job that reads an external provider through a credential), recurring (the platform's trigger, below), retryLimit 0–10 (5), leaseSeconds 30–900 (300), concurrency 1–4 (1) and run(payload, { host, signal, attempt }). The payload holds opaque ids only and names organizationId and actorId (and workspaceId, which becomes the host's workspace); the attempt runs on that owner's host for that actor on the controller surface, so live rights apply to every call, and every host call checks that the attempt still holds its lease: after a lost lease nothing commits. Commands carry idempotency keys derived from the payload, because a crash after a commit retries the attempt; stop between units of work when signal aborts. An api-read job's host admits external reads only (write tools are not even listed) and offers no control plane: configure, collection, archive, access, sharing and bucket-link members, selectEdition and acknowledge refuse with FORBIDDEN, and root and execute serve only the plugin's own root (in the job's workspace) and actions. No plugin enqueues a job directly. recurring: { formatId, enabledField, dueField, actorField, includeArchived? } names a format of the plugin whose records are the schedule; the format projects the three fields at the top level as boolean, timestamp and string (projectionFields). Every minute the platform scans, per live member and through that member's own host, the records directly under the member's own roots that are enabled, due (dueField <= now) and name the member in actorField, and enqueues one job per record and revision with organizationId, actorId, workspaceId and recordId; the job moves dueField forward to run again later. Declared as { name, execution: "api-read", recurring: { … }, run } in the plugin's v2 server jobs.

Browser entry

ts
export const browser = defineBrowserPlugin({
  id: "acme.notes",
  basePath: "/account/notes",                       // the plugin's old /account URL
  views: [{ id: "list", load: () => import("./list.js") }, { id: "detail", load: () => import("./detail.js") }],
  routes: [{ view: "list", path: "" }, { view: "detail", path: "$id" }],
  navigation: [{ label: { de: "Notizen", en: "Notes" }, iconPath: "M4 4h16v16H4z", view: "list" }],
});

The entry imports the SDK only and reaches its views through import(). A view gets BrowserViewProps: language, parameters (search, then decoded path parameters), the data port and the navigation. The data port (fetch, useQuery, mutate, prefetch) is a chunk's only network path and calls only the plugin's own procedures; it declares optimistic updates only for deterministic outcomes. Links come from navigation.href(viewId, parameters); never write a URL by hand. Base paths never share or nest. BrowserRouteParams<"$id/files/$file"> types parameter names.

Catalog flags and the OpenAPI document

In plugins/catalog.json, every entry names its plugin id (the id its runtime declares); "v2": true composes a package's ./server into api and worker, a package without it is composed there runtime-only (its records resolve for other plugins' references, no procedures or jobs), and "v2Browser": true composes its ./browser into the web build; mcp composes every reviewed package's tools. A v2Browser package may export ./fixtures (export const fixtures = defineBrowserFixtures({ answer, path?, parameters?, search? }), synthetic answers per procedure; in parameters, a value the answers know for every $name segment of the plugin's routes; in search, by route path, the search a route that takes its subject from the search needs) and gets a fixtures-mode page in the technical harness; no app build contains it. A v2 process loads only the plugins its PLUGINS selection names. The OpenAPI 3.1 document of the v2 API is a build artifact of the composition: @meinkontext/plugin-runtime/openapi.json documents the default selection (every non-example v2 plugin plus the platform namespaces); a selection's own document is generateOpenApiDocument(await composeV2Contract(ids)). An author outside the repository gets that document and the external client (packages/plugin-client); code runs inside the fleets only through the reviewed in-repo path.

Surface and versions

SDK v2 is additive: it needs no host API bump and no upgrade click, because v2 contributions are build-time and not part of the installed manifest or policy. The host API stays at 0.1.x until the operator approves a bump; the SDK package stays private at 0.0.1, and public distribution and licensing stay release gates.

Definition and runtime

PluginDefinition = { manifest, schemas }. The manifest declares namespace/release, compatible host API, reviewed entrypoints, capabilities, required dependencies, optional integrations, public contracts, formats, actions, views, datasets, policy vocabulary and optional import profiles.

Runtime memberContract
definitionThe validated plugin definition.
upgradeFromVersions?Explicit reviewed installation versions eligible for a metadata-only upgrade; host policy/format checks still apply.
reviewedRoleGrants?Permissions roles already in use gain, one entry per policy version that introduced them ([].policyVersion, [].roles[].roleId, [].roles[].permissions), kept for every later release; never a read, draft or format gate. See "Reviewed installation upgrades" below.
refreshDerivedOnUpgrade?Opt in to rebuilding stored revision projections and tightening current read ceilings from canonical data during an explicit reviewed upgrade; content and revisions stay unchanged. true rebuilds on every upgrade; { skipFrom, verifiedFor } rebuilds too, except for the one verified step it names.
embeddingFormats?Formats whose projected searchText gets a semantic search vector; see "Semantic search vectors". Absent means none.
collectionType, creatorRole, createPermissionGeneric host bootstrap vocabulary for this plugin.
label, descriptionCatalog metadata.
decode(formatId, formatVersion, files)Strict canonical-file validation to record data. Reject unsupported versions/files.
encode(formatId, formatVersion, data)Validated record data to canonical text files.
project(formatId, data){data, searchText} derived from the canonical record. data.actionItem (projectedActionItemFieldSchema: one item or a list of up to eight, each category, for user ids, optional dueAt/until; a list when the record waits for different people or in different windows at once) marks the record as an action item for those people; the host lists it under their live read access, scoped to the connection's workspace (an entry carries the home workspace of the record's root among the person's own workspaces; a connection on /mcp?workspace= sees only that workspace's entries, roots shared from another account appear everywhere), and strips it from the data your query rows return, so your strict record schemas keep parsing (the field was attention until 2026-10-29; the legacy name is stripped too). Set it from the record's state alone and leave it out as soon as nobody waits — the entry then disappears by itself, nothing is acknowledged. The state may mirror another system (a pull request waiting for the person's review) as an ordinary record; such an entry is only as fresh as your plugin's last sync, because the platform has no scheduler and no webhook ingress for plugins today — external reads run when a person opens a view or an agent calls one of your tools (timed runs are planned, not commissioned: .ytstack/plans/2026-10-29-plugin-schedules.md).
plan(actionId, input, context)Deterministic DomainPlan from authorized documents and host-provided identity/time/IDs. context.operationKey is the host-attributed idempotency key of this operation, never caller-authored action input; a plugin may persist it to bind later recovery to the originating operation.
planAsync(actionId, input, context)?Asynchronous planning for actions (event handlers keep plan): the host calls it instead of plan, and context.readDocuments({formatId, where?, whereAny?, orderBy?, offset?, limit?}) pages canonical, live-authorized documents of the command's own plugin and root, at most 32 per call (the default), archived records left out, inside the command's locked snapshot and transaction. The reads run one at a time and end when the plan settles; a read kept past that is refused with UNAVAILABLE, and a refused read fails the command even when the plan caught it. No writes and no other I/O. An invalid read is INVALID_QUERY.
readScope(actionId, input, actorId)?{ids?, formats?, requiredFormats?, queries?, restoreIds?, maintainArchivedIds?} selecting canonical documents; maintainArchivedIds is the archived maintenance of "Lifecycle gates"; actorId is the host-authenticated actor, the same value as context.actorId in plan. Missing means full scope. requiredFormats requires capability documents.required-formats; every existing record of these formats in the collection must be readable before admission/replay, or the command fails without revealing hidden data.
requirements(actionId, input)?Feature IDs and exact reference/contract/version preconditions, checked before execute and replay.
publicProjection(contractId, version, document, reference)?Provider validates and returns its published projection; the host supplies current access and the trusted reference.
canArchive(document, actor)?, canRestore(document, actor)?Owning workflow's archive and restore gates; see "Lifecycle gates".
canPurge, canMaintainArchived, expiration, expirationDependenciesOpt-ins to erasure, archived maintenance and automatic expiry; see "Lifecycle gates" and "Irreversible record erasure".
context?, tools?Deferred client guidance and plugin-owned MCP tools.

DomainDocument contains id, revision, formatId, formatVersion and readonly data. Files and authorization metadata are host-controlled. DomainPlan returns changes and result, optionally requiresCompleteScope (with completeScopeFormats, the formats the command depends on; absent means every format) and host outbox notification intents. Each DomainChange names its ID/format/version/data, optional narrower permission and optional inheritProtectionFrom. This is not arbitrary filesystem or network execution.

The host serializes operations per owner organization. Do not infer high-volume throughput from correctness tests; large-scale load gates are still open.

Authenticated host methods

Managed service identities use the experimental actor/session contract v1, initially adopted by Tasks 0.0.7. Runtime and tool adoption must be explicit; unsupported plugins remain user-only and fail closed. The host supplies authenticated identity and enforces live bindings and credential ceilings; never supply actor IDs from request input.

Web/tool handlers receive an already scoped PluginHostApi. They do not construct it from caller-provided identity or access the database.

Web handlers can call context.collections(companionPluginId) to discover an optional companion’s readable roots across the caller’s own and shared owners in the selected workspace. Omitting the ID retains the current plugin. Bridged exact-scope pages retain their scope restriction. Discovery grants no read or write authority; commands and public projections still authorize independently.

MethodReturns / effect
catalog()Available plugin metadata, activation state and visible collections.
describe(pluginId)Published definition; not a grant to content.
isInstalled(pluginId)Whether an installation row exists; this can remain true while disabled. Use catalog().enabled for activation.
integrationFeatures(pluginId)Eligible enabled features based on manifest versions/contracts; still no content authorization.
configure(pluginId, enabled, upgradeFromVersion?)Administration-gated activation through the UI or unrestricted user-OAuth MCP plugin_configure. Restricted execution credentials cannot call it.
root({pluginId,workspaceId?,audienceUserIds?,derivedOnly?})The plugin's derived root in one workspace (the request's, else the caller's Standard), created on first use; its id is the collectionId of commands, queries and links. Fixed-audience plugins get one root per audience set. Among legacy duplicates the oldest root answers; derivedOnly: true never answers with a titled legacy root (its sharing was given for what it held) and creates the untitled root instead; without derivedOnly, the runtime's derivedRootOnly: true makes that the default for every root resolution of the plugin (generic plugin_command, workspace moves).
findRoot({pluginId,workspaceId?,audienceUserIds?,derivedOnly?})What root() would answer for the same input, read-only: the same selection, null where it finds no root, and the same refusals except root()'s write gate: a disabled installation (PLUGIN_DISABLED), a quarantined plugin (PLUGIN_QUARANTINED) and a declarative plugin without writes or execution (PLUGIN_DISABLED) are no refusal here. An installation behind the release still answers PLUGIN_UNAVAILABLE. Writes nothing, so a page load may ask.
createCollection({pluginId,title,securityParentId?,audienceUserIds?})Transitional: a titled root, refused with ROOT_DERIVED from a public surface unless the manifest declares collectionAudience: "fixed" or legacyContainerRoots.
collections(pluginId?, { includeArchived? })Visible roots, each with its one home (CollectionHome: { own: true, id, name } for the caller's own workspace, { own: false, id } for a root another account shares, the sharer's workspace by id alone; never absent, a root without a home is left out), canCreate, canManageAccess, archived, protection and enabled flags, oldest first (creation time, then id). Archived roots appear only on request.
collectionHomes?(collectionIds)The one home of each named root the caller may read, as a record read: [{ id, home }]. A context-read grant may make it, where collections() (a discovery) is refused. A root the caller cannot read, or one without a home, is absent from the answer.
renameCollection({collectionId,title})Retitles a top-level collection. Custodian only (the authority canManageAccess reports). Audited as plugin.collection.renamed.
archiveCollection({collectionId,archived})Archives or restores a top-level collection. Custodian only. Archived: hidden from collections() by default, commands refuse with ARCHIVED, records stay readable, searchable and exportable, grants and bucket links untouched.
get(id)Canonical data, revision, format, collection, archive/protection and current editability.
getMany(ids)Up to 100 distinct ids in one host transaction: {records, unavailable}. Each record carries exactly what get returns and is authorized exactly like get; records keep the order of the distinct ids. An unreadable id and an id that does not exist both land in unavailable, indistinguishably; any other refusal (for example PLUGIN_UNAVAILABLE) fails the whole call, as get would fail for that id. Use it instead of one get per query row: every host call pays the transaction prelude and an access snapshot. Added to the experimental 0.1 API without changing any existing method.
resolve(id, contractId, version)Provider's validated public projection under current access.
query(query)Authorized rows, total, and optional groups. Row IDs/revisions bind derived data to versions.
readBatch?(fn)Optional. Runs several query() reads of one owner in ONE read transaction: fn receives { query } and its result is returned. Each read is authorized exactly like the separate call; a refused read (for example UNAVAILABLE for a collection the caller cannot read) fails the whole batch, so a caller that must tolerate one refusal checks access first or falls back to separate calls. The reads end with the batch: a query kept past fn is refused with UNAVAILABLE, a read started but not awaited is finished before the transaction commits (and fails the batch if it fails), and at most 200 reads share one batch (the 201st is refused). Use it instead of several queries in a row: every host call pays the transaction prelude. Added to the experimental 0.1 API without changing any existing method.
execute(request)Committed plugin result plus replayed. Requires action, collection, input, revisions and key.
archive(id, archived, expectedRevision)Archive/restore with current rights and workflow gate. Increments revision.
purgeArchived?(id, expectedRevision)Irreversibly erases an archived record with what it protects or files: {id, records}. A person on the browser surface who is the record's custodian; see "Irreversible record erasure".
expireRecord?(id, expectedRevision), expireChildren?(id, expectedRevision, signal?)The same erasure for records whose runtime expiration deadline has passed, for the trusted controller (a plugin job): {id, records}, and {deletedIds, hasMore} for at most 32 protected children per call.
exportCollection(collectionId, filter?)Authorized documents and canonical files, including a disabled plugin's readable data. filter.includeContext adds caller-owned workspace assignments and custodian-only access metadata from the same transaction; these describe the source and never grant access on import. filter.containerId exports only that readable declared container and what is filed under it, also when the root is not readable (title null, includeContext refused).
accessList(scopeId), setAccess(input)Current domain roles/bindings/exclusions and bounded access administration. accessList also returns bucketOptions (the caller's own and joined buckets, at most 200) and each bucket link's targetKind.
linkBucket({collectionId,bucketId,roleId})Live container sharing; roleId: null removes the link.
linkRecordBucket({recordId,bucketId,roleId})Exact-record sharing for reviewed formats declaring recordTraversalRoles. Requires custody and a role containing only permissions for that record type. Reads retain live contributor rights and mandatory protected parents; no sibling or ordinary parent discovery. The contributor or bucket owner can remove a link after content access is lost.
linkContainerBucket?({recordId,bucketId,roleId})Container sharing for a record whose format the runtime declares in containers (AV02-S04-P5): one link of kind container; the container and everything filed under it now or later resolve at read time, each record only while the container stays live and readable. Requires the container's custody, bucket ownership or membership and a read-only role (reads of the root, the container and its filed formats, transitively through nested containers as containedFormatIds(containers, formatId) lists them, the container's read included); delivered formats declare recordTraversalRoles. roleId: null removes the link, also for the bucket owner or contributor without content access. See AUTHORING.md, "Sharing record containers through buckets".
bucketOptions?()Optional. The caller's own and joined buckets by id and name, at most 200, for a share or audience picker (the old page context's buckets()). Interactive people only; buckets live outside the organization, their membership is the boundary. Added to the experimental 0.1 API without changing any existing method (AV05-S03m).
bucketMembers?(bucketId)Optional. The members of one bucket the caller owns or has joined, by id and display name only (no address), at most 500 (the old page context's bucketMembers()). Any other bucket, one the caller has left included, refuses UNAVAILABLE; the membership check and the list read one repeatable-read snapshot. Interactive people only. Added to the experimental 0.1 API without changing any existing method (AV05-S03m).
participants(collectionId)Eligible named participants under current rights.
notifications(pluginId?), acknowledge(id)Authorized host outbox/inbox records, not email/push delivery or a general Messages plugin.

Generic MCP administration

An independent agent account can administer its own plugins over authenticated MCP. The host stays domain-neutral: plugin IDs, role IDs and schemas come from discovery, never from host-owned domain constants.

MCP toolHost method / authority
plugin_configureconfigure; current organization owner/admin only. Optional owner_organization_id still checks that caller's membership there.
plugin_accessaccessList; current readable scope and custodian required. Returns role IDs, members, bindings, exclusions and bucket links.
plugin_set_accesssetAccess; replaces a direct organization member's role/exclusion. role_id: null removes the direct role; excluded: true adds a deny; omitted/false clears the exclusion. Optional expires_at bounds the binding.
plugin_link_bucketlinkBucket, linkContainerBucket or linkRecordBucket; supply exactly one of collection_id, container_id or record_id. Custodian-controlled links are bounded by effective rights. role_id: null unlinks; the bucket owner may also revoke without content access. Use buckets for separate accounts/organizations.
plugin_create_collectionOnly for plugins with a fixed audience or legacy container roots; everyone else writes into the workspace's derived collection (plugin_command with plugin_id, the plugin tools without collection_id). Optional security_parent_id adds mandatory inherited protection.

All four administration tools are absent from restricted import connections, even if that credential's underlying user is an owner. They do not issue credentials, widen execution grants, transfer custody, or turn installation rights into content rights. Authenticated calls still run the same host transactions, live policy checks and audit as the dashboard. Reconnect clients after changing activation if they cache the tool catalog or initialization instructions.

get().editable is a live capability, not canonical data. Disabling a plugin can change it to false without changing the stored record or revision. Keep state comparisons and capability assertions separate in tests.

Typical mutation request:

ts
await host.execute({
  collectionId,
  actionId: "example.hello-world.save",
  input: { id: record.id, message: "Updated greeting" },
  expectedRevisions: { [record.id]: record.revision },
  idempotencyKey: requestKey,
});

Reviewed installation upgrades

catalog() exposes installedVersion and upgradeAvailable. Every worker start (its plugin.release-upgrade job) moves the installations of reviewed plugins to the deployed version under the checks below, as actor system:plugin-release, enabled or not (upgradeReleasedInstallations). An upgrade those checks refuse stays on its version and is logged as an error: that is a defect of the release, not a task for the organization. Declarative plugins are not part of this and keep the organization's decision. With a version mismatch, collections advertise enabled: false / canCreate: false until an explicit supported upgrade. Organization owner/admin can call configure(id, enabled, installedVersion) or MCP plugin_configure with upgrade_from_version; installation administration grants no content read rights.

Release checks must cover every previously shipped installation version, including users who skip releases. Pin historical authorization policies in fixtures instead of deriving all old policies from the current manifest. Exercise the account update button as well as configure; metadata discovery alone is not proof of a usable upgrade.

The reviewed runtime must allow the exact source version in upgradeFromVersions. Under the normal organization transaction, the host checks that all currently stored formats remain supported and that policy changes preserve every existing resource/read gate, permission and role entitlement. Additional permissions may address only new resource types. Removing/changing old permissions, widening existing roles’ access to existing content or rolling policy versions back fails closed. A reviewed runtime may introduce roles only when neither direct bindings nor bucket links already use their IDs; the policy version must increase. Declarative metadata upgrades retain the strict no-new-roles rule. A policy version must increase when policy changes.

One reviewed exception exists (reviewedRoleGrants, since Calendar 0.0.6 was refused on every installed 0.0.5): a reviewed runtime may declare permissions that roles already in use gain, including a new permission on an existing resource type, as one entry per policy version that introduced them. The host accepts exactly the grants of every entry whose policy version the step crosses (installed policy older, target at that version or later) and only those the target role still carries; everything else it refuses as before. An entry therefore stays in the runtime for good: an installation still on an older policy crosses it on every later release. A grant never names a resource's read or draft gate or a format's read, write, draft or history permission. That does not make a grant harmless: a command's plan() can gate a write with any permission through effect.permission (Calendar's event.respond writes the organizer's event), so declare one only when every plan() that checks the permission proves that it changes nothing on existing content until a person with write access acts, pin that with a test, and pin the upgrade from the shipped policy in a store test (packages/core/src/plugins/release-upgrades.test.ts). The security review reads every such plan() whenever an entry or one of those plan()s changes (.github/reviewers/security.md). The administrator's preview lists the grants as extended roles.

Every policy a catalog plugin has carried while registered is kept in packages/plugin-runtime/src/shipped-policies.json, and shipped-policies.test.ts checks that each upgradeFromVersions source's policies upgrade to the current one with the declared grants. A release that changes a policy adds the new policy there under its version, keyed by the sha256 of its canonical JSON (the test prints the key); a policy the host would refuse fails the pull request instead of locking the plugin after the release. The file is append-only: a changed policy no longer matches its key, every upgrade source must be recorded (or listed under unregistered, a version no installation can hold), every recorded version stays an upgrade source, and every reviewedRoleGrants entry must name a policy version a recorded step introduces and whose recorded policies give the declared roles the declared permissions.

A release upgrade the checks refuse is an error of the release: the worker logs one error per refused step (plugin, versions, refusal and the policy entries that differ; a GlitchTip event) and puts one job per release into the release queue's dead letter, which is the platform admins' action item platform.dead-letter-operator until an admin deletes it once a corrected release runs. A redrive would return the job to the refused release's own queue, so the admin view and the api refuse one for plugin.release-upgrade.* dead letters.

The upgrade updates installation/policy metadata and corresponding resource, binding and live bucket-link policy versions atomically, audits plugin.upgraded, and invalidates access epochs. It retains resource IDs, revisions, custody, protection, exclusions, expiry and content bytes. Disabled remains disabled if requested. Repeat requests do not migrate data again. There is no arbitrary migration script execution or automatic downgrade. Content migrations and unsupported policy changes require a separate reviewed design. Reconnect MCP clients to refresh discovery.

A reviewed runtime that changes derived search fields or adds mandatory read ceilings can opt into refreshDerivedOnUpgrade: true. The same upgrade transaction decodes every stored projected revision through the supported codecs and rebuilds record_projection without rewriting canonical bytes, revision numbers or pointers. Current read constraints may only stay equal or become narrower: existing author/contributor limits and every protected parent remain mandatory. Custody is the one exception to "retains custody" above: a record of a format the runtime's creationRole names that has no custodian yet gets its root's custodian and the creation role's binding in the same transaction, because a read constraint that names the author ({ kind: "user", userId: ownership.custodianId }) needs one; the report and the plugin.upgraded audit count those records and how many sit in roots shared with someone else, who stops reading them. A record that already has a custodian keeps it. Unsupported historical formats, missing current projections or a weaker constraint abort the whole upgrade. The administrator receives no record data; this internal rebuild does not grant them content access.

The rebuild reads and rewrites every stored revision of every record in one transaction, and until it commits the installation is behind the deployed version, so the plugin answers PLUGIN_UNAVAILABLE for that organization. A release that changes no derived data can therefore name the one step that moves without the rebuild. What each form of refreshDerivedOnUpgrade does:

FormUpgrade of an installation
absentNever rebuilds: the runtime did not opt in.
trueAlways rebuilds.
{ skipFrom: ["0.0.2"], verifiedFor: "0.0.3" }Rebuilds, except while the manifest version is 0.0.3 and the installation is at 0.0.2: that step is the metadata update alone. From any other source it rebuilds, and under any other manifest version it rebuilds from every source.
{ skipFrom: [], verifiedFor: … }Always rebuilds, like true.

The skip is bound to the release it was verified for. A version bump without a new declaration falls back to rebuilding from every source, so a skip is never inherited by a release nobody checked; the author of the next release verifies its step and writes the new pair, or leaves the declaration and gets the rebuild. Write verifiedFor as a literal, never derived from the manifest. Every version in skipFrom must be in upgradeFromVersions.

A step may be named only when, for every record an installation at the source version can hold, the release produces the same output of project(), readConstraint() and creationRole() as the source version did. That is about their output, including everything they call (decode, the record schemas, SDK helpers), not about whether their own text changed: a changed parser of an old format version changes the projection of every record stored in it. Verify it with a run over records written by the source version, comparing the projection rows, read ceilings and bindings before and after a rebuild. A skipped rebuild also skips its checks of historical formats and current projections; the checks of the upgrade itself (source version, policy, stored formats) always run.

Report datasets

A plugin declares a dataset in its manifest (datasets: id, version, rowSchemaId, optional inputSchemaId, permission; both schema ids name owned schemas, and plugin_describe serves the parameter schema through its schema_id read, so an agent learns the parameters before it asks) and answers it in its runtime: DomainRuntime.datasets[id] is a PluginDatasetHandler, declared with datasetHandler({ input, formats, columns, participants?, query }): its own parameter schema (input: measures, dimensions, filters, a bounded period through datasetRangeSchema), the formats it reads (formats), the typed columns of its rows (columns, labels in German and English) and a deterministic query(input, documents, { now, userId, participants }) that receives the parameters parsed and typed by input. A handler that sets participants: true gets each read root's current participants (the host's participants, one read per root), for example to tell an assignee who lost access; otherwise the map is empty. collectionTitles names every root the host read (null when untitled), so a plugin whose records are named by their root (a Messages channel) names its rows instead of showing an id. A dataset over a period of the person's days takes range plus zone (timeZoneSchema, a default of "UTC" keeps older callers valid) and compares instants against datasetPeriodBounds(range, zone) from /dataset-period, the instants of those local midnights (datasetDayStart for one day; Temporal's start of day, so a day whose midnight a clock change skips begins after the gap), never UTC midnight; the report view sends the browser's zone for a dataset registered with period: { zone: true }. Ship a parameter schema with toSchema(schema, id, "input"), so a field with a default stays optional for the caller. The handler never reads the clock, storage or another plugin.

The host answers queryDataset({ datasetId, input?, collectionIds? }) (capability datasets.query) generically: the plugin must be enabled at its installed version; it reads the caller's readable roots of the host's scope (a request workspace narrows them, collectionIds narrows further, a root the caller cannot read answers UNAVAILABLE) and, per root in one read, only the live records of the named formats the export path's access admits, without attachment bytes, archived ones left out. Datasets are a person's own reports: the host refuses a restricted execution grant (EXECUTION_DENIED), a managed agent and a context-read controller (UNAVAILABLE) itself, not only through the MCP surface. The declared permission must be the read permission of one of the handler's formats, so that record access is the dataset's permission check; otherwise the dataset answers UNAVAILABLE. Invalid parameters answer INVALID_INPUT, rows that break the columns DATASET_FAILED. The answer is { schemaVersion: 1, datasetId, version, rowSchemaId, asOf, scope, columns, rows }; nothing is stored. MCP exposes it to a person's connection as the read-only plugin_dataset; a v2 read procedure calls host.queryDataset (a host read). datasetCsv/datasetMarkdown are the shared export.

A column may carry two display hints, both domain-blind: values maps a coded column's values to labels in German and English (a status, a kind; the report view shows the label, the export keeps the value) and identifier: true marks the row's own record id beside its title, or the root (collectionId): the view leaves it out, the export keeps it. A column that is a row's only key is never an identifier.

Report view (RP-05). Every namespace carries the generic procedure hostDataset (/report: reportProcedures(pluginId), GET <namespace>/host/dataset with datasetId, parameters as JSON, format rows/csv/md, lang), which answers only the plugin's own datasets and adds the export file for csv and md. /report-ui exports datasetReportView(pluginId, datasets), the one report page: register it in the browser entry as view REPORT_VIEW ("reports") with the route { view: "reports", path: "reports" } before a $id route, loaded with import(), and list each dataset with its labels and period: {} (or period: { zone: true } for a dataset that takes the browser's time zone). The page keeps the dataset and the period in the route's search, renders the first 500 rows and offers both exports. Declare the page in the manifest as views: [{ id: "<plugin>.reports", kind: "report" }]. In a fixtures page, answerDatasetFixture(declarations, handlers, input, documents, context) (/datasets) answers the procedure with the plugin's own handlers.

Query language

ProjectionQuery requires pluginId; optionally use collectionId or collectionIds (at most 200 candidate roots, mutually exclusive), formatId, full-text query, where, groupBy (one property path), groupByCollection (count matches per collection; value is the collection ID, exclusive with groupBy), offset, limit, includeArchived or archivedOnly. Predicates are combined; property paths and values are parameterized, never SQL fragments. For runtimes declaring typed projection fields, a single format is inferred. Multi-format runtimes require formatId for field filters, sorting or grouping. exportCollection accepts the same typed predicates and an optional filter.formatId; multi-format field filtering requires that selection. Unfiltered queries and exports may span formats.

collectionIds selects direct children of exactly those roots, preserving their complete scope/security dependency closure. It is a candidate filter on the ordinary query: unreadable or revoked records are omitted and archived roots remain hidden unless the existing archive flags request them. A stale root list therefore does not make a still-readable sibling disappear. An empty array returns no rows or counts. In contrast, singular collectionId is an explicit root read: it requires access to that root and permits reading an archived root. Grouped counts retain the ordinary query's selected-edition rules. Do not broaden a sparse selection to an owner's entire corpus.

includeWorkspaces: false omits optional browser-row workspace labels and their lookup. It defaults to true; it never changes workspace scoping or any access check. Use it for metadata views that do not display or navigate by those labels.

PredicateFields / semantics
eqpath, string value.
inpath, string values; the value is one of them. An empty list matches nothing.
notInpath, string values.
isNullpath.
comparepath, `comparison: "lt"
dateTodaypath, zonePath, `comparison: "before"

query({ ..., limit: 0 }) returns total and requested groups with an empty rows array. Use it for counters rather than loading a record that the view discards. Filters, selected editions, archives and live authorization are identical to a paged query; offset does not change the total.

Normalize sortable values in the owning plugin. Apply authorization before observable counts/groups. A cross-plugin query must use a provider's published record contract for any fields it relies on; never query undocumented internals. Pages are not a frozen transactional snapshot.

References and public contracts

ts
type EntityRef = {
  installationId: string;
  entityType: string;
  objectId: string;
  selector: { kind: "live" } | { kind: "version"; versionId: string };
};

The generic schema permits these reference shapes; individual workflows can support a narrower subset. Runtime command reference requirements currently support live references in the same owner organization. Do not infer cross-owner or historical linking support from the generic schema alone. Prefer trusted provider-returned references, and resolve under the viewer's current rights. References do not contain grants or authorize access.

A provider builds the references it hands out with liveReference({ ownerOrganizationId, pluginId, entityType, objectId }) and returns them with its read results, so a consumer, a model included, passes them on unchanged instead of composing one. The host resolves installationId as the plugin installed in that owner; a plugin does not spell that form itself. Tasks returns one as ref on every task_query task row (DECISIONS 2026-11-07, "Tasks rows return ready references").

Client setup guides

A plugin may add context.clientSetup (pluginClientSetupSchema, PluginClientSetup): a guide a person's own client follows to set itself up for the plugin, for example to capture its sessions. It is static reviewed text like the guide: no record content, no data per caller, and it never asks for or carries a credential. Fields: version (change it whenever the guide or a template changes), summary (≤ 200, the line setup_client lists under plugin_setups), instructions keyed by client kind (generic required, each ≤ 6,000), optional templates (≤ 8, each {name, purpose, clients?, text ≤ 8,000}; a starting point, never an installer), and the required check and remove (≤ 1,200 each). For every client key, instructions plus its templates plus check plus remove stay within 16,000 characters. selectClientSetup(setup, client) is the one selection rule: the client's own key, else generic. The host serves the guide only through setup_client with plugin_id, behind its own domain-neutral rules; plugin_context answers without it. A new plugin version invalidates managed credentials pinned to the old one, so a guide whose setup issues one says what happens then.

Context fields on facts, objects and records

A plugin contributes a metadata field to memory facts, Core objects and the plugin records the base views show by declaring DomainRuntime.contextFields and naming targets in the reserved projection field contextFields; writers resolve natural references through host.contextTargets.resolve. Contract, write checks and read rules: CONTEXT-FIELDS.md.

Known platform accounts and account presentation

A command that records a platform account (a user id) declares it in requirements(actionId, input).knownAccounts. The host admits it only when every id is a visible known account of the human actor — someone they share or shared a bucket with, invited or were invited by (user_contact, not hidden) — before execution; a replay returns the stored result and writes nothing. Service actors, organization credentials and execution grants are refused. Recording an account grants it nothing.

A reviewed plugin may present the accounts a page shows, for the current viewer only, through its own ./account-presentation export (catalog flag accountPresentation): presentAccounts(context, userIds) returns AccountPresentation[] (types AccountPresentation and AccountPresentationContext from @meinkontext/plugin-sdk/plugin-server): an optional label that replaces the account name for this viewer and up to four link-only actions. The v2 composition (packages/plugin-runtime/src/account-presentation.ts) asks every installed and enabled plugin of the viewer's own organization once per request, keeps the first valid label per account, and renders the plain account when the plugin errs or exceeds one second. It never shows a presentation to anyone but the viewer. Procedures read the result through ProcedureContext.accountPresentations(userIds) (or viewerPresentations(context, userIds), which yields the { presentation } to spread beside each person's name) and return it only in the answer of that request. Every view that shows a person, rather than offering them in a picker, renders AccountName from @meinkontext/ui/components with that presentation (a reviewed in-repo plugin; external plugins render the same data themselves), so the presenting plugin's actions, for example Contacts' "Als Kontakt anlegen …", appear in one ⋮ menu wherever a person is shown; the page's own actions for that person go in as AccountName children, never a second menu, and a name inside a sentence uses compact. context.knownAccount(id) and context.knownAccounts(query) read the viewer's own known accounts (name and email) and nothing else. This is a data contract, not UI slot injection: the host owns every pixel. Reference implementation: Contacts (packages/plugin-contacts/src/server/accounts.server.ts).

Errors and safe recovery

The host deliberately avoids distinguishing absent from unreadable resources. Render an unavailable state without probing to disclose existence. REVISION_CONFLICT requires a fresh read and a user-intent check. INTEGRATION_UNAVAILABLE disables the dependent feature; the independent workflow should remain usable. Do not retry schema, policy, unsupported-version or changed-idempotency-request errors indefinitely.

Catch expected domain validation failures in your own UI and preserve input. Never swallow host denials into success or use a remembered private title as the unavailable fallback. Exact domain error vocabulary belongs in the plugin.

Raise a public code from a workflow with fail(code) (root export, never): the host forwards an Error whose message matches /^[A-Z_]+$/ to the caller verbatim as the tool-error code — your plugin context explains those codes — and collapses any other message to COMMAND_FAILED, so an exception never carries SQL, content or input to a model.

See optional integration contracts and verification. Source signatures are in src/runtime.ts, src/host-api.ts, src/contracts.ts, src/query.ts, src/tools.ts and src/plugin-server.ts in this package.

Public documentation contributions

DomainRuntime.documentation?: readonly PluginDocumentationPage[] adds static, public guides to the online documentation catalog. It receives no session, actor, request or host capability. Documentation is public before sign-in and independent of organization activation. Never include record data, secrets or private operational evidence.

Each page declares a unique lowercase slug, localized title and description, an absolute HTTPS source URL for relative link resolution, and load(language) returning { markdown, language }. The returned language identifies an explicit fallback. The host owns /docs/plugins/{pluginId}/{slug}, navigation, full-text search, sanitized Markdown, tables, anchors and Markdown delivery. A package omitted from the reviewed catalog contributes no routes or navigation.

Load the canonical guide from your own shipped package assets, for example with readFile(new URL('../GUIDE.md', import.meta.url), 'utf8') in the server runtime. Include the guide in package.json → files and preserve its location relative to dist/. Do not import server filesystem code into browser exports. The SDK's own maintained guides are exported separately through @meinkontext/plugin-sdk/documentation-server; its root remains browser-safe.

Reviewed release actions

See fixed audiences and reviewed commands for requiresApproval, immutable collection ceilings, live revision dependencies, web review and the trusted MCP command-grant client. These generic primitives never put domain semantics in the host.

A format upgrade must update persisted format metadata and canonical files together. Keep each supported strict decoder; do not widen a v1 contract in place. A public summary may remain compatible while its provider writes a new private format. Older binaries need an explicit rollout/rollback plan.

Collection change feed

PluginHostApi.changes({collectionId, since?, limit?}) and the corresponding MCP tool plugin_changes({collection_id, owner_organization_id?, since?, limit?}) provide current-state invalidations for any installed plugin. Hosts advertise collections.changes for plugin admission. The method returns no domain fields, authored text or historical payloads. Restricted execution credentials and core-read credentials cannot use it. Disabled plugins retain authorized reads.

ts
type Page =
  | { status: "ok"; phase: "snapshot" | "changes";
      changes: { id: string; revision: number; archived: boolean }[];
      cursor: string; hasMore: boolean }
  | { status: "resync_required"; phase: "snapshot";
      changes: []; cursor: null; hasMore: false };

Start without since and with an empty/staging cache. Snapshot pages enumerate currently readable document IDs, including archived records. Use plugin_get (or host.get) for current content. Follow each returned cursor until hasMore is false, then retain it for the next poll. A snapshot captures a collection sequence before paging; writes during paging are picked up after the snapshot. A delta drain has a fixed upper sequence, so a continuously writing producer cannot indefinitely extend that drain. A later poll picks up subsequent commits. An empty page can still have hasMore: true.

Persist the cache update and its cursor atomically. Apply repeated IDs/revisions idempotently; several events may coalesce to a newer current revision. get may return a still newer revision and must recheck authorization. If a record read fails, do not label stale cached content current; discard that record and reconcile the feed. The feed is not a journal or a transaction replay API, and snapshots do not promise a historical point-in-time payload view.

Cursors are opaque non-authorizing checkpoints bound to owner organization, caller and collection. They expire after seven days; malformed or wrong-scope cursors yield INVALID_CURSOR. Reset your own cache rather than constructing or modifying a cursor. Internal cursor values are not a confidentiality boundary for aggregate collection activity. Transport them only through authenticated MCP and store them with the matching cache. Pages default to 50 and allow 1–100 scanned events/records; a filtered delta can contain fewer items.

On resync_required, discard the whole collection cache before restarting without since. On UNAVAILABLE, discard it and rediscover authorized scopes; do not interpret denial as permission to retain a last-known live view. Changes to policy, active bindings (including expiry), sharing, protection, installation state or record deletion can require a full resync. Policy checkpoints cover the requested collection, its records (including hidden ones) and transitive scope/protection parents, including parents owned by another plugin. Creating or sharing an unrelated collection, or changing an unrelated plugin installation, does not reset this feed. Changes within that dependency set remain conservative; adding a newly protected record can require a resync. An older checkpoint may require a one-time resync after this policy-scoping correction. It never exposes a list of IDs made inaccessible by revocation. Offline consumers cannot receive revocation until they reconnect; cache age, offline lifetime and purge behavior are consumer responsibilities.

The DB trigger records document effects and increments a transactional row counter in the same transaction. It does not use a nontransactional SQL sequence as a committed high-water mark. Rollback advances neither counter nor feed, and idempotent command replay has no new effect. Archive/restore advances the revision and feed. Initial snapshots discover pre-migration records without inventing history. Hard deletion increments a reset epoch and returns no historical tombstone ID. Collection deletion removes its feed metadata.

Events contain only resource IDs/revisions. At least seven days are retained; older rows are pruned lazily when that collection is polled, so inactive collections can retain metadata longer. A retained sequence floor detects stale checkpoints even if their timestamps were modified. Host-only organization RLS protects both tables. The host evaluates current authorization on every page before returning any resource ID, including for cross-account bucket readers.

This reduces client/network polling and avoids loading unchanged documents. The existing host still loads organization policy/resource metadata to evaluate access; this release makes no indexed-at-scale or end-to-end latency claim. Feed reads still take the existing organization lock and prune expired feed metadata; readOnlyHint describes domain content, which is unchanged. This is not a lock-free polling implementation. Cursors currently have no integrity signature: a client that edits its checkpoint can corrupt its own cache but cannot bypass live authorization. Integrity protection and reducing read contention remain follow-ups, not delivered features. Clients must reconnect/re-sync if they cache MCP tool definitions.

Trusted web context files

A reviewed plugin may declare capabilities: ["context.files"]. The v2 composition supplies ProcedureContext.files (/plugin-server) only when the plugin is installed and declares this admitted capability. Treat an absent capability as unavailable. It is separate from ordinary domain collection authority: installation never grants access to a file. The host binds it to the signed-in account and resolves own and shared content under current rights; paths and IDs are not credentials.

The public PluginHostApi, MCP tool context, restricted execution context and managed-service context do not expose this capability. Do not forward it to a model or synthesize it from a collection grant. Authentication, database/blob handles, headers and cookies remain inside the host.

MethodBehavior
list({ path?, query?, page? })Authorized file/folder metadata with page/total counts and per-entry write/publication flags.
read(id, published?)Current authorized content and revision; content: null denotes non-text bytes. Reading the published version is explicit.
save({ id, revision, content })Revision-checked save. Registry objects get a draft; memory uses its immediate historical update.
review(id)The full object's draft-versus-published changes and both revision identifiers.
publish({ id, revision, publishedRevision })Explicit publication bound to the reviewed draft and published revisions.
export({ id?, path?, published?, originalsOnly? })Authorized file entries as an async stream. originalsOnly selects original source files where available.
files.download(input)Web-only wrapper returning a single file or recursive ZIP response with private/no-store headers.

Every underlying file operation applies its content access checks. Save and publish additionally require a same-origin POST and recheck that the plugin is still installed and enabled. Disabling it retains authorized reads/exports but blocks edits and clears writable/publishable flags. A missing installation does not admit a new plugin route request. Reader/export access is not an installation administration right.

Domain-plugin files are read-only in this surface: edit them through their owning plugin's commands. Protected credential payloads are never ordinary context files; confidential export remains a separate trusted capability. Wiki-scoped native pages use a host-scoped file API independently of the Explorer installation.

File procedures answer the shapes of /context-file-answers.

Atomic command archival

A command change may request archive: true. The host requires the format's full write permission in addition to any narrower command permission, asks canArchive about the resulting document, and rejects incoming references after applying the whole plan. Rejection rolls back every change, including references created by another effect in the same command. An archive and restore cannot coexist on one change. Installation migrations cannot request this command disposition.

canRestore(document) optionally restricts restoration to valid domain states; the generic restore API evaluates the stored document, while a command's explicit restore evaluates its resulting document. A plugin can thereby require its own command to update domain state together with restoring the resource. Archived records remain available through authorized recovery metadata/history surfaces; ordinary query and file delivery omit them.

Lifecycle gates

The runtime's lifecycle gates are domain opt-ins, asked only after the host has checked live read and write authority; a gate never grants anything. The host always passes the trusted actor (TrustedActor: person or service, with the caller surface), so a gate may answer differently for a person, a service or the controller. A one-argument implementation stays valid.

GateAsked byAbsent means
canArchive(document, actor)archive(id, true, …) and a command change with archive: trueRefused (ACTIVE_RECORD).
canRestore(document, actor)archive(id, false, …), a command change with restore, restoreIds/restoreQueriesAllowed.
canPurge(document, actor)purgeArchived for every erased record; expireRecord/expireChildren for erased records without their own deadlineRefused (ACTIVE_RECORD).
canMaintainArchived(document, actor)readScope().maintainArchivedIds; expireChildren under an archived parentRefused (ACTIVE_RECORD).
expiration(document, actor, dependencies)expireRecord, expireChildren: an ISO instant from which the record may be erased, null for neverNever expires.
expirationDependencies(document)Before expiration: at most 32 ids of the same plugin and root, each live-readable, read and passed as dependencies (more is INVALID_PLAN)No dependencies.

Archived maintenance. A controller command (the host a plugin job runs on names the controller surface; a host without a surface is no controller) may rewrite archived records without restoring them: readScope().maintainArchivedIds names at most 32 archived records of the command's root (more is INVALID_PLAN). Each needs live write authority and canMaintainArchived; each change on one must keep it archived (archive: true, replayArchived: true, no restore, else INVALID_PLAN); canArchive is not asked again for it. Browser and MCP callers, services and execution grants are refused with UNAVAILABLE. A non-archived id is ignored.

Irreversible record erasure

purgeArchived(id, expectedRevision) erases an archived record for good, the plugin-host form of v1's archived-object purge: a person on the browser surface who is the record's custodian (its own custodian, else its root's) decides, references never block, and the bytes nothing else needs go in the same transaction. Refusals: an active record ACTIVE_RECORD, a stale revision REVISION_CONFLICT, any other caller (MCP, controller, service, grant) or a non-custodian UNAVAILABLE.

expireRecord(id, expectedRevision) runs the same erasure for the trusted controller once the runtime's expiration deadline has passed (ACTIVE_RECORD before), archived or not. expireChildren(id, expectedRevision, signal?) expires the due protected children of id (records whose security parent or resource read constraint names it): it finds at most 32 per call, erases each in its own transaction with every check repeated, and answers {deletedIds, hasMore}; call again while hasMore. The parent needs live write authority and, when archived, canMaintainArchived. An aborted signal throws its reason between records; the records erased until then stay erased.

The erasure set is the target, every record it protects (security parent or resource read constraint, transitively) and, when its format is a declared container (containers), every record filed under it, transitively in both relations. Every member must belong to the same plugin and root and be live-writable for the caller, judged with only this set virtually restored, and an explicit custodian of a member must be the caller when a person purges; every member must be admitted by canPurge (or, when expiring, by its own passed deadline). One refusal refuses the whole call and changes nothing.

Under the owner lock and the organization's blob-gc lock, one transaction then deletes the records with their bindings, projections, workspace items and bucket links (all of them, a link to a single erased record included), the reference edges from and to them, the record objects with every revision, file, search, pin, subscription, grant, alias and channel row, and every binary asset no surviving row references. The deletion advances the root's change epoch, so a change-feed consumer resynchronizes. Command receipts that named an erased record stay as tombstones with an empty result: the idempotency key stays used and a replay is refused. The audit log records plugin.record.purged or plugin.record.expired with the erased ids.

Records that survive keep the ids they cite in their own data; those resolve as unavailable from then on (get, resolve and a command that keeps the reference answer UNAVAILABLE), so a plugin drops such a reference on its next write. A plugin uses erasure by implementing the gates on its runtime and calling host.purgeArchived from a browser procedure, or host.expireRecord and host.expireChildren from a job.

Published record editions

A format may opt into editionSelection: "subscription". New records retain a canonical write pointer and publish accepted changes to stable in the same host transaction. Read surfaces resolve explicit pins before channel follows, then stable, with current permissions. Shared contributor projections never inherit draft-review rights; incompatible contributor selections are unavailable. Current selection remains the default for other formats.

Derived edition projections retain their format version. Historical decoding uses that version, never the newest record format by assumption; an unknown historical format blocks decoded selection while authorized raw historical files remain recoverable. The write revision still protects the canonical record.

Trusted migration maintenance can retain a distinct canonical write channel and collection defaults for new-record organization read/history bindings. Neither is accepted from a command or a plugin plan. Defaults apply only on creation, never change existing grants, and may contain only a declared format's read/history permissions. Native collections have no organization defaults. This does not grant installation administrators access to content.

Trusted authorization snapshots may contain a traverseFor binding for an exact record share. Such a binding grants only the declared scope parent's read permission while evaluating that specific descendant. It never grants a direct parent read, never inherits to a sibling, and never satisfies a security-parent check. Its role must contain exactly the scope parent's read permission. The host constructs these bindings from live record-share and bucket membership rows; plugins and command payloads cannot create them. Exclusions, audience ceilings, contributor authority and all security parents are still evaluated. Record links use read-only roles without history or draft authority and do not appear as collection links.

Draft command editions

A command change may set publication: "draft" for an existing subscription-selected record whose format declares a draft permission. The caller must currently hold that permission and the write permission; replay rechecks both. The private write channel/revision advances while published readers remain on their selected stable edition. Stable-as-write-channel records and other formats refuse this disposition. Omitting the field (or "publish") retains normal publication, including publishing an unchanged private edition when skipUnchanged applies. Installation migrations do not accept command publication dispositions. This does not itself expose a model-callable grant or bypass the caller's current scope.

A command change may set versionMessage to preserve an immutable version note. The note passes the same secret-value gate as file content before persistence. An explicit note forces a new version even with skipUnchanged; it cannot accompany publishWorkingEdition or an installation migration plan.

A publication plan may additionally set publishWorkingEdition: true with publication: "publish", skipUnchanged: true and an explicit expectedPublishedVersionId. After ordinary command, revision, effect-permission, reference and secret checks, the host verifies unchanged decoded data, format and read constraint, and rejects attachment writes, archive/restore, or a non-subscription record. It then publishes the existing immutable version without re-encoding it. This preserves historical storage layouts and exact bytes; installation migrations cannot use this disposition.

A publication plan may set expectedPublishedVersionId to the version observed by its review UI (null means never published). The host rejects a changed published pointer with REVISION_CONFLICT, including publication without a new working revision. This field is invalid for draft writes and format migrations.

Optional search presentation

query() accepts textSearch: { syntax: "web", rank: true, snippet: true, matchPaths: [["title"]] }. The default remains plain full-text search with the existing ordering. Web syntax supports phrases/OR; matchPaths adds literal, escaped substring matches over declared string projection fields. Rank precedes explicit tie-break ordering. Rank is PostgreSQL ts_rank normalized by document length (normalization 1, the same scale as the platform's own knowledge search), so a short record about the term outranks a long one that mentions it as often; a substring-only match ranks 0. Requested snippets are returned as optional row snippet text; render them as untrusted text, never HTML. Counts, rank and snippets all use the same authorized, selected-version projection set.

Semantic search vectors

A runtime lists in embeddingFormats the formats whose records a person should find by meaning, not only by words. For each record of such a format the platform's worker embeds the first 16,000 characters of the current revision's projected searchText with the embedding model that runs inside the worker (nothing is sent outside the platform) and stores the vector beside that revision's projection row. The vector inherits the row's access rules and workspace, is replaced when the search text changes, and is removed with an older revision, the record and the account. The plugin writes nothing for it and is never asked: the host and the worker decide only by the format id. Nothing else of the record is read for it.

Opt in only prose a person wrote to be read and found. Never opt in a format whose search text carries credentials, contact details, messages or session transcripts: a vector of such text would make it findable by meaning beside the plugin's own access model. Today only Wiki articles opt in. The vectors have no reader in the SDK yet; query() and its text search are unchanged.

File metadata

files.list returns bounded metadata pages for one collection/format without reading file bodies. Selected editions are the default. A human can request working: true; only records with current write and explicit draft permission use their working edition. Other records retain their selected edition. Returned version IDs and paths never confer authority for subsequent reads.

files.index is the optional complete metadata counterpart for consumers that need the entire catalog. It uses the same live selected/working-edition decisions in one transaction and additionally returns each selected projection as data. It never downloads file bodies. Do not rebuild this catalog by repeatedly calling files.list: that repeats authorization and edition resolution on every page. This is not a bounded first-page API or a cross-request authorization cache. recordIndex also accepts an optional collectionId; explicit collection scope requires current read access to that collection and excludes sibling collections. Metadata-only consumers may pass { includeFilePaths: false } as a second argument: the index retains the same authorized records, selected revisions and fields, but returns files: [] without querying file paths. Omission keeps the full file-path contract. Older hosts ignore this extra argument and safely return the complete file paths.

files.readMany?({ recordId, paths, versionId? }) is the optional batch counterpart of files.read for several files of ONE record version. It decides access and the version once, reads the bodies together (a single path alone, as read does) and answers { path, revision, bytes }[] in the order of paths, each verified against its sha256. It refuses the whole call (UNAVAILABLE) when one path is missing or the record or version is not readable, exactly as read would for that file; missing bytes raise the same error as read. Where reads are audited one by one (a context-read grant), it writes one audit row per path, the rows read writes. An empty paths answers [] without reading, authorizing or auditing anything. A consumer still checks each answer's path and revision against the manifest it asked for. A host without it leaves the consumer to call read per file.

File-area contributions

A reviewed definePluginServer({ fileMounts }) (/plugin-server) may return PluginFileMount providers for accessible collections. The host supplies the same bounded public host used by account routes, plus collection discovery and caller identity. Each provider owns its path and file-ID resolution; every content operation must recheck live permissions. mountContextFiles preserves IDs, prefixes displayed paths and combines folder/search results. Overlapping mounts and ambiguous ID ownership fail closed. Mount discovery is request-local and grants no content access.

ContextFilesApi.listBatch(run, hints?) optionally groups the directory listings for one page traversal. The callback receives only a listing function; its lifetime ends with the callback. This callback scope is transaction-neutral: providers must complete owner transactions before invoking it, because the traversal may enter mounts owned by other organizations. A provider may reuse its authorized filename metadata within that traversal, but must reload it for the next traversal and must reject escaped listing functions. A page traversal uses this capability when available and retains the ordinary list fallback for other providers. Open branches and their page limits remain unchanged. This does not authorize file reads, downloads, exports or mutations: those still perform their own live permission/version checks.

The optional listBatch path hints describe the selected and expanded folders. They are planning hints only: providers may reuse the same authorized inventory for root and descendant listings; hints never grant access or skip the visible branch/pagination checks. A root-only traversal retains bounded discovery.

Collections with a custom provider are omitted from the generic domain-file listing/export, while exact-record shares without a visible custom collection retain the generic fallback. Old domain-file links still recheck live access. Legacy storage adapters must separately fence migrated records: filtering a composed export does not prevent an underlying adapter from reading stale data.

The server contribution's resolveFile(context, id) optionally resolves a retained opaque file identity without adding a discoverable collection mount. It must authorize the record through the bound host and return a provider that reauthorizes every operation. The host tries ordinary mounts first and rejects multiple fallback claims. This supports exact-record shares whose parent metadata is deliberately inaccessible; it never grants sibling discovery or collection writes.

Named server operations

A reviewed definePluginServer({ operations }) may declare named operations (PluginOperation): (input: unknown, context: PluginOperationContext), where the context carries the caller's identity, a public host per owner organization and the plugin's enabled collections. A trusted host module dispatches them by name; they are never registered as MCP tools or API procedures and never receive credentials or database access. Each operation validates its own input and acts only through the host it is given. Today only the Wiki declares any: they serve its public identifiers (create_wiki, write_article, get_wiki, wiki-source:// and the Wiki's part of objects, search and buckets). This is a by-name seam between host adapters and one reviewed plugin, not an extension point for external plugins: prefer procedures and tools.

Exact-record scope traversal

Reviewed runtimes may declare recordTraversalRoles: [{ formatId, roleId }] to allow a directly shared record to be read without exposing its collection. The named role must contain exactly one permission: read on the scope-parent resource type. Every scope ancestor must match that type and the record's plugin and policy version; malformed declarations fail closed. Use this only for formats whose explicit human record grants are intended to stand alone.

The host derives traversal bindings from current direct user, organization and team bindings carrying that format's read permission. It preserves the principal, start/expiry times and live membership checks. Each synthetic binding is scoped to the exact requested record through traverseFor; it cannot read the parent, list siblings, export the book, bypass exclusions or satisfy a protected parent. Service credentials and bucket-derived bindings do not enter this path. Exact bucket sharing retains its separate contributor-aware traversal contract.

This does not issue grants or confer management rights. A reviewed format can use creationRole to give its author custody for the existing human setAccess flow. Collection inheritance remains independent; manage the collection's role separately from the exact record grant. Personal workspace selection still limits returned records. Declaring traversal does not adopt managed-agent access.

Custodian bindings on records with a scope or security parent also work for a foreign author admitted through sharing. Both parents remain mandatory live read gates; losing the bucket share withdraws access to the authored record as well. This does not relax organization membership for root or non-custodian grants, or expose author-only content to the root custodian.

Shallow logical directory discovery

files.rootDirectories?({ collectionId, sourceFormatId, fileFormatId, boundRecordField, fileNameField, fallbackDirectory }) is an optional root-only existence query for a declared path tree plus its bound file records. It returns root directory names, or undefined when the complete provider must be used. Every returned directory has a fully decoded, live authorized exact-version witness. Candidate paths alone never establish access.

This is progressive disclosure, not a full catalog validation pass: an unrelated malformed nonrepresentative payload or leaf policy assignment need not prevent discovering another directory. Unknown metadata, unproved groups, direct root entries, unsupported edition choices and ambiguous cases retain the full provider. Opening records, deeper listings, search, export and writes retain their complete validation and authorization. Older hosts without this optional method keep the existing provider.

Nested source-directory discovery

files.directoryEntries?({ collectionId, sourceFormatId, path }) returns a bounded complete set of immediate source-tree children: directories contains full paths of implicit child folders, while records contains { id, path, directory } for actual immediate source records. Every direct record is live-authorized and canonically decoded; each implicit folder needs an exact-version authorized canonical descendant. The capability never grants access to children when they are subsequently opened.

A nonempty proven source subtree can be rendered using the existing file-tree sorting and pagination. Unsupported cases return undefined for the complete provider: more than 100 raw direct records or 50 child groups, unknown path metadata, unproved groups, direct/implicit or duplicate-path collisions, and distinct locale-equivalent paths whose stable ordering belongs to the original provider. Search and exports remain on their existing complete paths. An older host simply omits this optional method.

Root directory discovery likewise uses bounded article/file candidates only for positive legacy-folder existence. Each selected file witness must have its exact protected projection and live canonical revision. It does not infer absence from an unproved bounded sample. Unrelated article inventory errors are outside the shallow request; full content and inventory operations retain their validation.

Root and prefix from one owner snapshot

files.directoryPages?({ collectionId, sourceFormatId, fileFormatId, boundRecordField, fileNameField, fallbackDirectory, path, paths? }) is an optional bounded pair: it returns { root, directory } using the same result types and fallback rules as rootDirectories and directoryEntries. It shares protected source candidates/projections in one short owner transaction; both original live canonical witness checks still run. With paths (at most 32 further prefixes of the same root, an expanded tree's other branches) it also returns directories, one directoryEntries answer per prefix in order, read in the same transaction; a host that does not return directories leaves each of those prefixes to its own directoryEntries call. The transaction completes before any consumer callback or other-owner operation. Undefined results require the existing full provider, never an empty page.

Mounted ContextFilesApi.listBatch providers receive relative requested-path hints. Wiki may reuse this completed pair only during that traversal; it does not reuse authority to open files, perform writes, authorize another request or authorize independent reads. Extra branches, search and export keep their existing paths. A speculative pair failure declines batching, and only actually requested pages execute their original checks/errors. Unrequested hints never expose a result or a new error. Listing callbacks expire on return, including fallback paths; hosts without this optional capability behave as before.