API reference

Use @clank.run/framework/reviewed actions for durable previews, decisions, atomic commits and receipts. ReviewedAction.approvalQuorum opts into distinct human approvers, required roles, requester separation, native membership/security versi

38 min read8,307 wordsClank 0.24.0
On this page

Governance, lifecycle, and tooling

Use @clank.run/framework/reviewed-actions for durable previews, decisions, atomic commits and receipts. ReviewedAction.approvalQuorum opts into distinct human approvers, required roles, requester separation, native membership/security versions and expiring votes. ReviewedApprovalMembership, ReviewedApprovalQuorum and ReviewedApprovalProgress describe that contract; see approval quorum policies.

Use @clank.run/framework/governance for policy decisions, expiring agent approvals, entitlements, and feature flags. Use @clank.run/framework/lifecycle for revision replay, provenance, promotions, rollout guardrails, sanitized clones, portable exports, and capacity. Use @clank.run/framework/tooling for App Studio reviews, visual regression, parity, schema planning, contract tests, upgrades, and the agent playground. Provider adapters can call runDeploymentProviderConformance() from @clank.run/framework/provider.

This is a compact index of the primary public surfaces. The shipped .d.ts files are the exhaustive symbol contract; focused guides contain behavioral details and examples.

Core

  • signal(value, options?) → ReactiveSignal<T>: mutable tracked value.
  • ReactiveSignal: .value, .get(), .peek(), .set(), .update(), .subscribe(), .toJSON().
  • isSignal(value): detects signals and computed values.
  • computed(derive, options?) → Computed<T>: lazy cached derived value.
  • effect(callback, options?) → disposer: tracked synchronous side effect with cleanup.
  • batch(callback): coalesces dependent effects.
  • transaction(callback): batch with signal rollback on throw.
  • untrack(callback): disables dependency capture in the callback.
  • createRoot(callback): creates an ownership scope.
  • onCleanup(callback): registers owned cleanup.
  • getOwner() / runWithOwner(owner, callback): capture and restore ownership for advanced integrations.
  • store(object): creates a lazy deep reactive proxy.
  • isStore(value), toRaw(value), snapshot(value): store inspection and serialization.
  • resource(loader, options?): async state with abort and stale-result protection.
  • consumeStream(iterable, initial, reduce?): folds an async iterable into a signal.
  • SIGNAL, STORE: global protocol symbols for integrations.

Typed Task runtime

The opt-in runtime is available from the package root or @clank.run/framework/task. See Typed tasks, failures, and services for the complete execution, cleanup, cancellation, and security contract.

  • Task<A, E, R>: lazy computation with success A, typed failure E, and service requirements R. Composition includes map, flatMap, tap, as, mapError, catchAll, catchCause, ensuring, retry, timeout, provide, withSpan, and generator yielding.
  • Constructors: Task.succeed, Task.fail, Task.failCause, Task.sync, Task.suspend, Task.try, Task.tryPromise, Task.fromPromise, and Task.gen.
  • Execution: Task.runExit, Task.runPromise, TaskRuntime, and createTaskRuntime. runPromise rejects with inspectable TaskExecutionError; runExit returns every outcome as data.
  • Outcomes: Exit, Cause, and Result. Cause variants distinguish typed Failure, unexpected Defect, Interrupted, Sequential, and Parallel outcomes.
  • Services: service<T>(name), nominal Service<T>, and memoized Layer. Layer.succeed, Layer.effect, Layer.fromValue, merge, and task.provide compose requirements and scoped implementations.
  • Resources: Task.acquireRelease, Task.addFinalizer, Task.scoped, and TaskScope. Finalizers run exactly once in LIFO order and cleanup causes are retained.
  • Scheduling: Schedule.recurs, Schedule.spaced, Schedule.exponential, while, mapDelay, intersect, and union.
  • Concurrency: Task.all, Task.race, Task.fork, and Fiber. Children own scopes, propagate interruption, and cannot outlive an enclosing runtime scope.
  • Time: realClock, injectable Clock, and deterministic TestClock.
  • Diagnostics: TaskTracer, withSpan, TimeoutError, and MissingServiceError. Clank's observability tracer can be passed directly as the runtime tracer.

DOM

  • TSX: preferred component syntax; dynamic braces become fine-grained bindings automatically.
  • h(type, props?, ...children) / createElement: lower-level VNode construction.
  • jsx, jsxs, jsxDEV: compiler runtime entry points.
  • expression(read), isExpression(value): compiler/runtime reactive boundary.
  • Fragment: groups children without an element.
  • render(root, view) → disposer: mounts an application.
  • hydrate(root, view) → disposer: attaches to marker-compatible SSR DOM; warns and remounts on a structural mismatch.
  • observeHydration(listener) → disposer: opt-in immutable structural mismatch metadata; paths, patch/remount reason and optional source/component location exclude rendered values and attributes.
  • withHydrationSource(vnode, { file, line, column }): copy a VNode with bounded basename/source metadata without changing props or HTML.
  • createDevtools({ hydration: true, maxEvents? }), exportHydrationSnapshot(snapshot): bounded local inspection and deterministic redacted JSON; see development tools.
  • isVNode(value): VNode detection.
  • onMount(callback): post-mount lifecycle with optional cleanup.
  • createContext(defaultValue), provideContext(context, value), useContext(context).
  • useId(prefix?): render-root-scoped deterministic ID for matching SSR and hydration trees.
  • Portal({ target?, disabled?, children }): same-document portal that server-renders at its declaration markers and moves owned nodes after hydration.
  • Show, Match, Switch: reactive conditional control flow.
  • For: O(n) keyed reconciliation with row identity preservation; use by="id" or a key function.
  • lazy(loader): promise-backed component.
  • Types: Renderable, Component, VNode, ReactiveExpression, KeyedBlock, ElementType, ClankContext.

Element protocols include onClick/on:click, bind:value, classList, object style, callback/signal ref, directive use, dangerouslySetInnerHTML, and the agent* properties.

Forms

  • createForm(options) → typed headless form controller.
  • Controller state: values, dirty, valid, pending, submitted, submitCount, status, result, error, formErrors.
  • Controller methods: field, setValue, setValues, setErrors, validate, submit, reset, focusFirstError, props.
  • Field state: value, errors, touched, dirty, invalid, message.
  • Field helpers: input, textarea, select, checkbox, radio, error.
  • manifest: clank-form/1 schema and field contract without live values.
  • Types: FormController, FormField, FormManifest, FormErrorMap, FormStatus, CreateFormOptions.

Headless UI

The dependency-free headless library is available from the package root or @clank.run/framework/ui. Group entry points (/ui/controls, /ui/fields, and so on) and all 39 family entry points (/ui/dialog, /ui/number-field, and so on) are also exported. Family paths are typed aliases to their category modules rather than symbol-isolated bundles. See Headless UI for required markup, behavior, accessibility, forms, SSR, Tailwind, and the complete anatomy table.

  • Catalog: UI_COMPONENT_COUNT (39), UI_COMPONENT_CATALOG, UI_COMPONENT_FACTORIES, getUiCatalogEntry(), BASE_UI_REFERENCE_VERSION ("1.6.0"), and BASE_UI_REFERENCE_URL. Types: UiCatalogEntry, UiCatalogModule, UiComponentName, UiComponentSlug, UiComponentFactoryName, UiComponentNameForSlug, UiCatalogEntryFor, UiComponentContractMap, and UiComponentFactoryMap.
  • Themes: CLANK_THEME_PRESETS (ten immutable presets), CLANK_THEME_COUNT, CLANK_THEME_TOKEN_NAMES, defineClankTheme(), getClankTheme(), clankThemeVariables(), createClankThemeStylesheet(), and applyClankTheme() from @clank.run/framework/ui/theme. Types: ClankTheme, ClankThemeInput, ClankThemeTokens, ClankThemeTokenName, ClankThemeScheme, and ClankThemeStylesheetOptions. See Design system and component workshop.
  • State and composition: createChangeDetails(), createControllableState(), isEventCanceled(), composeEventHandlers(), mergeProps(), mergeRefs(), renderPart(), createInteractionState(), and createMediaQuery().
  • IDs and environment: createIdScope()/createUiIdScope(), createUiId(), UiProvider, DirectionProvider, CSPProvider, useUiEnvironment(), useDirection(), and useCspNonce().
  • Direction and DOM ownership: resolveDirection(), isRtl(), resolveLogicalSide(), getOwnerDocument(), getComposedPath(), and containsEventTarget().
  • Focus and collections: isFocusable(), focusableElements(), focusFirst(), getCollectionNavigationIntent(), findCollectionIndex(), findTypeaheadMatch(), and createTypeahead().
  • Agent contracts and data hooks: createUiManifest() and dataState().
  • Overlay foundations: createOverlay(), createFloating(), and createPresence().
  • Popup families: createAlertDialog(), createBottomSheet(), createCollapsible(), createDialog(), createDrawer(), createDrawerProvider(), createDrawerVirtualKeyboardProvider(), createPopover(), createPreviewCard(), createTooltip(), and createTooltipProvider().
  • Control families: createAvatar(), createButton(), createCheckbox(), createCheckboxGroup(), createMeter(), createProgress(), createRadioGroup(), createSeparator(), createSwitch(), createToggle(), and createToggleGroup().
  • Selection families: createAutocomplete(), createCombobox(), createSelect(), and filterSelectionItems().
  • Collection families: createAccordion(), createContextMenu(), createMenu(), createMenubar(), createNavigationMenu(), createTabs(), and createToolbar().
  • Field families: createField(), createFieldset(), createFormFacade(), createInput(), createNumberField(), createOtpField(), and createSlider(). createFormFacade() is distinct from the schema-oriented createForm() above.
  • Utility families: createScrollArea(), createToastManager(), and createToastProvider().
  • Navigation families: createPagination().
  • Compatibility helpers outside the 39-family catalog: createDisclosure(), clickOutside(), and autoFocus().

Common contracts include ChangeDetails, ControllableState, UiProps, UiRef, UiManifest, UiPartManifest, UiActionManifest, Direction, Orientation, OverlayController, FloatingController, PresenceController, and the family-specific *Options and *Controller types.

  • Responsive selection: SelectionPresentation = "popover" | "bottom-sheet" | "responsive" is available through AutocompleteOptions.presentation, ComboboxOptions.presentation, and SelectOptions.presentation. Responsive mode uses a positioned popup on desktop and sheet-ready attributes on narrow viewports without changing controller state or rendered content.
  • Bottom Sheet: BottomSheetOptions fixes the Drawer motion axis to the bottom edge while retaining modal behavior, snap points, swipe handling, and the BottomSheetController handle part.
  • Pagination: PaginationOptions and PaginationController expose bounded page state, page-size changes, first/previous/next/last actions, a status live region, and semantic page buttons.
  • Popup presence: PopupOptions.keepMounted, PopupPortalOptions { keepMounted? }, PopupController.isMounted(options?), and portal(options?). Popup-backed collection and selection controllers expose the same methods. Collapsible exposes isPanelMounted(options?); Accordion and Tabs expose isPanelMounted(value, options?). A default-closed popup is not mounted, an exiting popup remains mounted, and a kept popup remains mounted but hidden.
  • Popup dismissal and triggers: nonmodal Popover, Dialog, and Drawer infer focus-out dismissal while pointer dismissal is enabled; closeOnFocusOutside overrides the inference. Multiple triggers share one popup, only the active trigger reports expanded/open, interaction transfers ownership without closing, late mounts do not steal ownership, and every mounted trigger remains inside the outside-event boundary.
  • Checkbox and Switch: uncheckedValue?: string plus uncheckedInput() opt into an explicit unchecked/off submitted value without changing native checked submission. Their catalog anatomy includes unchecked-input. ControlIndicatorOptions.keepMounted retains inactive Checkbox, Checkbox Group, and Radio indicators.
  • Checkbox Group: parentState, toggleAll(), parent(CheckboxGroupParentOptions?), and parentIndicator(CheckboxGroupParentIndicatorOptions?) provide checked/mixed parent control semantics. Canonical anatomy includes parent and parent-indicator.
  • Selection values: SelectionValue<Value> = Value | readonly Value[] | null and AutocompleteFieldValue<Value> = string | readonly Value[]. SelectOptions.field and ComboboxOptions.field bind the committed selection; AutocompleteOptions.field binds a string in single mode and selected values in multiple mode. Field and explicit controlling props are mutually exclusive. Values must match declared items, shape, and uniqueness.
  • Editable selection: CompletionMode, ComboboxOptions.openOnInputClick (Combobox default true, Autocomplete default false), and AutocompleteOptions.keepHighlight (default false). Paired committed-value/text transitions roll back together when either change is canceled.
  • Select typeahead and focus: a closed single Select commits a printable-key match; a closed multiple/read-only Select ignores it; an open Select only moves its highlight. Trigger-to-popup focus remains internal to a composed Field, while an accepted focus-out/outside dismissal or actual external blur completes touched/blur validation.
  • Field relationships are mount-aware. label(), description(), and error() register reactive relationships when requested/mounted and remove them on directive cleanup; composed controls inherit Field constraints, state hooks, native validity, reset, and cancellation.
  • OTP: OtpFieldOptions.onValueComplete, deprecated onComplete, and autoSubmit. Completion callbacks receive ChangeDetails<OtpFieldChangeReason>; cancellation suppresses auto-submit.
  • Slider: SliderThumbPartOptions supports ariaLabel, ariaLabelledBy, ariaValueText, getAriaLabel(index), and getAriaValueText(formattedValue, value, index) through thumb(index, options?).
  • Scroll Area: ScrollAreaScrollbarOptions { label?, labelledBy? } names each role="scrollbar"; axis names are the defaults and labelledBy takes precedence. Viewports expose data-clank-scroll-area-viewport; mounted viewports share one nonce-aware behavioral rule per document that hides WebKit native bars, and custom tracks preserve Ctrl+wheel browser zoom.
  • Drawer-specific contracts include DrawerSnapPoint, DrawerResolvedSnapPoint, and DrawerMeasurements. Toast swipe ignores interactive descendants and [data-base-ui-swipe-ignore]/[data-swipe-ignore], and always releases timer pauses on cancel, capture loss, or root cleanup. Toast root relationships follow mounted title/description parts; empty F6 is a no-op, and dismissing a keyboard-focused toast repairs focus.
  • Tooltip Provider: only an accepted-open tooltip can own the provider. Canceled opens never steal ownership, and a contender rolls back when the active tooltip vetoes closing.

Compiler

  • clank dev [directory]: run the deployment-configured build and entry, watch the project, health-swap successful replacements, preserve the last good process after errors, and reload connected browser tabs.
  • clank build [input] [output]: compile .ts/.tsx and copy static files once.
  • clank watch [input] [output]: rebuild after source changes.
  • --jsx-import-source=specifier: choose the generated runtime module.
  • compile(source, options?): programmatic TypeScript/TSX compilation.
  • transformTSX(source, options?): programmatic TSX-only lowering.

Semantic browser journeys

  • defineJourney(input) → immutable JourneyDefinition: validate and snapshot a bounded, data-only semantic acceptance flow.
  • runJourney(journey, driver, options) → JourneyReport: execute with same-origin navigation, overall/step timeouts, optional secret resolution, redacted failure surfaces, and step events.
  • createDomJourneyDriver(window, agentSurface) → JourneyDriver: adapt a mounted browser app.
  • clank journey [file]: run JSON or trusted local module suites in isolated real Chrome.
  • Types: JourneyInput, JourneyDefinition, JourneyStep, JourneyExpectation, JourneyInputValue, JourneySecretReference, JourneyKey, JourneyDriver, JourneyReport, JourneyStepReport, RunJourneyOptions.

Component specimens

Optional module: @clank.run/framework/component-harness; see component harness.

  • defineComponentSpecimen(input) → registered ComponentSpecimen<Props>: capture schema-validated props, synchronous factory, semantic part mappings, current assertions and journeys.
  • renderComponentSpecimen(specimen) → { html, snapshot }: SSR with owned cleanup and an immutable fingerprint/common UI contract.
  • mountComponentSpecimen(root, specimen) / hydrateComponentSpecimen(root, specimen, snapshot, { signal? }?) → ComponentHarness: mount in a dedicated connected root with one active harness per document.
  • Controller: snapshot(), reset(), select(specimen), check(), exportAssertions(), dispose(). A stale check returns null.
  • exportComponentAssertions(specimen) → deterministic CLI-compatible clank-component-assertions/1 JSON.
  • mountComponentHarnessControls(container, harness, specimens) → cleanup: mount native selection/reset/check/export/dispose controls outside the fixture root; cleanup also disposes the harness.
  • Types: ComponentSpecimen, ComponentSpecimenInput, ComponentSpecimenInstance, ComponentSpecimenSnapshot, ComponentHarness, ComponentHarnessSnapshot.

Realtime collaboration

  • createCollaborationHub(options) → CollaborationHub: authenticated, CSRF-protected, same-origin presence and ephemeral signal rooms over bounded Fetch + SSE.
  • createAuthCollaborationHub(auth, options?): reuse Clank sessions and CSRF checks with an application-supplied exact-room authorization callback.
  • createCollaborationClient(options) → CollaborationClient: reconnecting reactive browser state with immutable participants, event/error signals, presence replacement, and signals.
  • CollaborationHub.diagnostics(): aggregate room/participant/stream counts without identities, room names, connection IDs, or payloads.
  • Types: CollaborationValue, CollaborationPrincipal, CollaborationParticipant, CollaborationEvent, CollaborationOperation, CollaborationLimits, CollaborationHub, CollaborationClient, CollaborationClientState, CreateCollaborationHubOptions, CreateAuthCollaborationHubOptions, CreateCollaborationClientOptions.

Product analytics

  • defineAnalytics({ events, funnels? }) → immutable typed event/funnel contract with bounded, aggregate-safe properties and a clank-analytics/1 manifest.
  • openAnalytics(definition, database, options) → per-app SQLite analytics runtime with consent/DNT gates, HMAC pseudonyms, idempotency, sampling, expiry, erasure, and storage bounds.
  • AnalyticsRuntime.track(name, properties, context): validate and conditionally persist one event.
  • AnalyticsRuntime.ingest(events, context): ingest at most 25 typed memory-only client events after server-side identity and consent resolution.
  • AnalyticsRuntime.query(input): cohort-protected time series, finite dimension breakdown, and bounded numeric average; no raw-event read API exists.
  • AnalyticsRuntime.funnel(name, range): ordered, windowed, bounded, cohort-protected conversion.
  • AnalyticsRuntime.forgetSubject(input), .purge(now?), .diagnostics(): privacy erasure, retention, and identity-free aggregate operations.
  • createAnalyticsClient(definition, options): typed memory-only consent/DNT-aware batching client with application-owned transport and no browser identity or local persistence.
  • Types: AnalyticsDefinition, AnalyticsEventInput, AnalyticsFunnelInput, AnalyticsRuntime, AnalyticsManifest, AnalyticsTrackContext, AnalyticsTrackResult, AnalyticsQueryInput, AnalyticsQueryResult, AnalyticsFunnelResult, AnalyticsClient, AnalyticsClientEvent, OpenAnalyticsOptions.

Deployment artifacts

  • readDeploymentConfig(root, filename?): read and normalize clank.deploy.json.
  • parseDeploymentConfig(value): validate a config already in memory.
  • createDeploymentBundle(root, config, options?): deterministic gzip artifact with checked files and provenance.
  • decodeDeploymentBundle(bytes, limits?): bounded protocol, path, size, base64, and SHA-256 verification.
  • extractDeploymentBundle(bundle, directory): exclusive extraction into a release root.
  • deploymentDigest(bytes): SHA-256 artifact digest.
  • Types: DeploymentConfig, DeployDatabaseConfig, DeployPreviewDataConfig, DeployPreviewDataTableConfig, DeployPreviewDataTransform, DeployPreviewJsonTransform, DeploymentBundle, DeploymentFile, BundleLimits.

Migrations

  • loadMigrations(directory, options?): ordered SQL files and SHA-256 checksums.
  • planMigrations(path, migrations): applied/pending state with immutable-history verification.
  • applyMigrations(options): apply pending SQL in one immediate transaction.
  • assertSafeMigrationSql(sql, id?): reject cross-database and transaction controls.
  • backupSQLite(source, destination): consistent built-in SQLite backup.
  • restoreSQLiteBackup(source, destination): replace a stopped database and clear WAL sidecars.
  • Types: Migration, MigrationRecord, MigrationPlan, ApplyMigrationsOptions.

Recovery

  • openBackupManager(options): consistent AES-256-GCM SQLite recovery points with authenticated manifests, retention, verification, explicit restore confirmation, and optional chunked ObjectStore persistence.
  • BackupManager.createFromSnapshot(options): validate and directly encrypt a bounded consistent SQLite byte snapshot without plaintext repository staging; databasePath may be omitted for an import-only repository.
  • BackupManager.read(id): authenticate and decrypt one recovery point into bounded memory for a fenced remote restore path without writing plaintext staging data.
  • BackupManager.purge({ confirmation: "delete all backups" }): explicit repository-wide cleanup, including incomplete object promotions.
  • Local mode commits owner-only envelope/manifest directories atomically. Object mode promotes existing local copies, publishes an HMAC-authenticated per-database catalog, verifies every chunk and the reconstructed database, and retains the local copy after provider failure.
  • Types: BackupManager, BackupManagerOptions, BackupManifest, BackupVerification, BackupSnapshotInput, BackupReadResult, BackupObjectRepositoryOptions.

Deployment platform

  • Environment HTTP contracts: PlatformEnvironmentName, PlatformEnvironmentMigrationPolicy, PlatformEnvironment, PlatformEnvironmentBindingRequest, PlatformPromotionRequest, PlatformPromotion. Versioned same-workspace bindings and exact-artifact activation use /api/projects/:root/environments; see environment promotions.
  • Persistent release channels — PlatformReleaseChannelEntry, PlatformReleaseChannel, PlatformChannelPinRequest, PlatformChannelActivationRequest, PlatformChannelRollbackRequest, PlatformChannelAction. Exact retained pins, readonly history and explicit environment activation use /api/projects/:root/channels; see release channels.
  • Scheduled release windows — PlatformReleaseWindowRequest, PlatformReleaseWindow, PlatformReleaseWindowCancelRequest, PlatformReleaseWindowRecoveryRequest; exact future promotions, current authority and verified recovery use /api/projects/:root/release-windows. See scheduled release windows.
  • openPlatform({ providerPromotionHosts }): private operator certificate/profile registry for initialized co-located loopback provider targets under code-only policy. Current host proof is required before staging and acceptance; unsupported profiles fail closed.
  • openPlatform({ supervisor }): opt-in dedicated same-host Linux coordinators with retained ownership epochs, native transaction fencing, independent process guardians and automatic standby recovery. See Automatic supervisor leadership for configuration, failure bounds and migration. Optional PlatformRuntime.supervisor() returns readonly local state/epoch/expiry/responsibilities; standbys serve 503 with Retry-After.
  • openPlatform({ canary: { provider, stages, ... } }): opt-in isolated provider candidates with exact anonymous read paths, measured traffic stages and durable retirement before ordinary activation. Requires native supervisor and project ownership; enabling it permanently enrolls supervisor protocol 2. GET /api/projects/:id/canary includes non-secret retained status. POST /api/projects/:id/canary/recover accepts exact { operationId, expectedEpoch } and only retries cleanup. See provider canary configuration and recovery.
  • openPlatform(options): browser dashboard, workspace people/invitation administration and activity, transparent monthly usage, device authorization, tokens, projects, transactionally enforced capacity and traffic limits, ingress metrics, DNS/domain lifecycle, TLS eligibility, encrypted secrets, role-filtered audit, release transaction, logs, rollback, and supervision.
  • PlatformRuntime: Fetch .handle, .publicUrl, .dataDirectory, resolved .hostingProfile, .runnerKind, and async .close().
  • openPlatform({ serviceAccounts }): opt-in dedicated machine accounts, expiring scoped credentials and recently verified human administration. PlatformRuntime.authenticateServiceAccount(request) returns a current server capability with .identity and .assertCurrent(); display JSON cannot authenticate a caller. createOrganizationServiceAccountClient() exposes versioned organization administration and explicit exact retries. See service accounts.
  • Runners: dependency-free process runner or constrained Docker runner.
  • openPlatform({ sqliteIsolation }): namespace by default; trusted-process requires an explicit hostingProfile: "trusted", process runner, and non-public signup. The policy is scoped to that platform's startup, requests, and background work, without changing other platforms or standalone database helpers. See SQLite worker isolation.
  • openPlatform({ invitations }): durable, encrypted, cross-instance-leased invitation delivery through any EmailService, while retaining manual copy-once fallback.
  • openPlatform({ projectCosts }) adds trusted cumulative measurements, immutable rate cards, version-fenced budgets, expiring overrides and private operational alerts. Public createProjectCostClient(), createProjectCostView() and createProjectCostMcpTools() share native project authorization. See project costs.
  • Types: ClankPlatformOptions, PlatformBackupOptions, PlatformJobOperationsOptions, PlatformInvitationDeliveryOptions, PlatformLimits, PlatformHostingProfile, PlatformRunnerOptions, ProcessRunnerOptions, DockerRunnerOptions, PlatformProjectPlacement.
  • openPlatform({ deploymentAgents: { placement } }): enables immutable per-project local | provider selection. Provider projects use stateful endpoint/label placement, an encrypted frozen environment per generation, lease-scoped clank-runtime/1, exact observed activation, allowlisted managed-ingress publication, fenced rollback/delete, and resumable pending deploys. Generation-bound provider snapshots feed the same encrypted local or object recovery repository used by local projects; create, schedule, list, verify, and fenced restore are supported. Restore verifies the selected point, creates a safety recovery point, and publishes a replacement generation only after provider data replacement, current migrations, and health succeed. The same exact active generation supplies bounded logs and Docker memory/CPU/PID/network/block-I/O diagnostics plus shared provider-filesystem capacity to a platform-administrator browser session; token, project-member, and support-impersonation responses redact shared capacity to an unavailable record. Secret values are redacted at the control plane. placement.maxDatabaseBytes bounds snapshot transfer, recovery reads, and runtime-capsule capacity. Provider placement requires managed ingress.
  • POST /api/admin/projects/:projectId/provider-failover: browser-admin-only emergency recovery from a revoked and independently fenced exact source. Requires recent authentication, CSRF, backupId, sourceNodeId, exact confirmation, acknowledgeSourceFenced: true, and acknowledgeDataLoss: true. It verifies the encrypted recovery point, preserves target requirements/capacity, removes old ingress, and publishes only an exactly observed higher generation. Bearer tokens and support impersonation are rejected.

Object storage

  • openLocalObjectStore(options): atomic, owner-only, no-follow local object envelopes with verified metadata, length, and SHA-256.
  • createS3ObjectStore(options): zero-dependency S3-compatible HEAD/GET/PUT/DELETE adapter with SigV4 payload signing, virtual-hosted or path-style URLs, retries, deadlines, response bounds, and independent download integrity checks.
  • ObjectStoreError: stable status and code without provider response details.
  • Types: ObjectStore, ObjectMetadata, StoredObject, LocalObjectStoreOptions, S3ObjectStoreOptions.
  • openPlatform({ deploymentAgents: { artifacts: { namespace, store } } }): retains each new local or remote-runner upload under a persisted repository identity and content-addressed key. Without an object repository, original uploads use private project artifact files. Earlier local releases without retained uploads remain runnable but cannot be reconstructed for promotion. Mismatched repositories fail closed.
  • openPlatform({ backups: { objects: { namespace, store } } }): gives every project an isolated authenticated backup catalog and binds the repository identity/root in the control database.

Managed buckets

openMediaProcessing({ database, auth, buckets, transforms, policyRevision, authorize }) queues declared transforms on the existing native job system. The services must share a persistent native catalog. enqueue(currentAuth, input) freezes exact generations and retains an owner-scoped operation ID; get, cancel, workOnce, startWorker and close cover its lifecycle. Publication and bounded receipts commit together, while external providers must honor the stable operation key. See durable media processing for the complete authorization, capacity and recovery contract.

  • defineBucket(input): freezes visibility, ownership, browser access, MIME, image, cache, per-object, per-owner, and total quota policy.
  • openBucketManager(options): opens the SQLite catalog over any ObjectStore, with project-wide caps, signed capabilities, resumable uploads, verified generations, listing, and cleanup.
  • createBucketClient(name, options): authenticated browser listing, metadata, resumable upload, deletion, and private read intents without object-provider credentials.
  • createBucketMcpTools(manager, options): current owner-scoped read/write tools for each declared bucket and image variant. openBackend({ buckets }) installs these automatically.
  • inspectBucketImage(bytes, contentType?): signature and dimension inspection for PNG, JPEG, GIF, WebP, and AVIF.
  • Types: BucketDefinition, BucketManager, BucketRuntime, BucketObject, BucketUsage, BucketClient, BucketUploadIntent, BucketReadIntent, and BucketImageTransformer.

Remote deployment coordination

  • createDeploymentCoordinatorHandler(orchestrator, options): optional versioned HTTP boundary for deployment-node enrollment, heartbeat, draining, operation claims, renewal, settlement, and desired-state observation.
  • createDeploymentCoordinatorClient(options): HTTPS/loopback-only, redirect-refusing, bounded remote-node client. .artifact(...) verifies the leased, content-addressed binary release before returning it.
  • openDeploymentAgent(options): provider-neutral enrollment, credential recovery, heartbeat, bounded claim/concurrency, lease-renewal, fenced settlement, and graceful-drain loop. The provider-specific execute callback receives the current claim, an abort signal, verified leased artifact(), and generation-fenced observe.
  • fileDeploymentNodeCredentials(path): serialized, atomic, owner-only persistent node credential store with file type, mode, size, version, token, and symlink validation.
  • memoryDeploymentNodeCredentials(initial?): ephemeral credential store for tests and temporary nodes.
  • DEPLOYMENT_COORDINATOR_PREFIX: fixed /api/runner/v1 protocol namespace.
  • DeploymentCoordinatorError: safe client error with HTTP status and stable code.
  • DeploymentOrchestrator.authenticateNode(id, token): verifies the current node credential and heartbeat lease without extending it.
  • DeploymentOrchestrator.authenticateOperation(operation): returns the canonical stored lease only when the exact node/token/fence/expiry tuple is current, without extending or settling it.
  • Operation claims allocate a durable, monotonically increasing fence across every operation for the same project. Retries and later releases cannot reuse an earlier provider fence; separate projects retain independent sequences.
  • DeploymentOrchestrator.setDesired({ placementMode }): portable placements may move after node loss; stateful placements durably reserve one node identity and fail closed instead of moving node-local data implicitly.
  • DeploymentOrchestrator.relocateStateful({ projectId, sourceNodeId, runtimeProtocol }): advances an exact running stateful placement to a different compatible node only after the source is offline or expired, preserves region/capability/process-slot requirements, cancels stale work, clears observed state, and queues one higher-generation reconcile. This low-level primitive does not move data or prove physical fencing; platform callers must supply and verify recovery data and enforce the operator boundary.
  • DeploymentOrchestrator.setDesired({ nodeRequirements }): persists endpoint and exact-label capability requirements so initial and delayed placement select only compatible nodes.
  • Types: DeploymentCoordinatorHandler, DeploymentCoordinatorHandlerOptions, DeploymentCoordinatorClient, DeploymentCoordinatorClientOptions, DeploymentArtifact, DeploymentArtifactRequest, DeploymentArtifactProvider, DeploymentNodeCredentialStore, DeploymentExecutionContext, DeploymentAgentOptions, DeploymentAgentRuntime.

Deployment providers

  • openProviderDeploymentAgent(options): validates canonical desired-state plus rollback/delete operations, verifies running artifacts, derives destructive confirmations, strips coordinator credentials before adapter execution, and returns only fixed non-secret results.
  • executeDeploymentProvider(provider, operation, context): reusable dispatcher for reconcile, rollback, and delete operations.
  • reconcileDeploymentProvider(provider, operation, context): reusable validation/execution boundary for custom reconcile-only agent loops.
  • createHttpDeploymentProvider(options): HTTPS/loopback-only binary client with a separate bearer token, redirect refusal, deadlines, exact idempotent retries, and bounded failure responses.
  • createDeploymentProviderHandler(provider, options): authenticated fixed-path bridge that independently bounds, hashes, and decodes reconcile content while requiring empty-body, generation/fence-bound rollback and deletion.
  • DEPLOYMENT_PROVIDER_RECONCILE_PATH, DEPLOYMENT_PROVIDER_ROLLBACK_PATH, and DEPLOYMENT_PROVIDER_DELETE_PATH: fixed provider protocol paths.
  • DeploymentProviderError: stable HTTP status and code without a provider response body.
  • Types: DeploymentProvider, DeploymentProviderRequest, DeploymentProviderLifecycleRequest, DeploymentProviderOperation, DeploymentProviderDesiredState, DeploymentProviderArtifact, ProviderDeploymentAgentOptions, HttpDeploymentProviderOptions, DeploymentProviderHandler, and DeploymentProviderHandlerOptions.

Provider Docker runtime

  • openDockerDeploymentRuntimeLauncher(options): exact-owner orphan cleanup, immutable-image Docker launch, private health, worker/scheduler topology, generation fencing, stop, and shutdown.
  • launch({ prepared, signal, deferBackground? }): starts the config embedded in verified provider data and returns a non-secret loopback candidate. Deferred mode health-checks only web.
  • activate(candidate, signal): starts a deferred candidate's workers/scheduler after provider data commits, verifies them, releases the memory-only activation plan, and marks it active.
  • commit(candidate): marks the exact healthy candidate active after provider data commits.
  • diagnostics(projectId, logLimit?, signal?): returns a bounded memory-only output tail and one non-streaming per-role Docker resource sample plus a path-free shared-filesystem capacity sample, or null when no runtime is tracked. An optional abort signal cancels the one-shot Docker command.
  • inspect(), stop(projectId, generation?), forget(projectId, generation), and close(): non-secret state, verified container removal, deletion cleanup, and fail-closed shutdown.
  • Types: DockerDeploymentRuntimeLauncherOptions, DockerDeploymentRuntimeCandidate, DockerDeploymentRuntimeState, DockerDeploymentRuntimeDiagnostics, DockerDeploymentFilesystemDiagnostics, DockerDeploymentRuntimeLauncher.

Linux host certification

Optional module: @clank.run/framework/host-certification; see Linux host certification for disposable-host preparation, bounded supported profiles, proof details, private metadata and interruption recovery.

  • certifyLinuxHost({ directory, profile, disposable: true, quotaId, ttlMs?, signal? }): runs fixed enforcement probes and saves a versioned, locally authenticated report.
  • inspectLinuxHostCertification({ directory, profile }): rechecks the saved report's authentication, expiry and current policy/host binding; returns a fixed reason and report.
  • requireCurrentLinuxHostCertification({ directory, profile }): returns only a current all-passed report, otherwise throws LINUX_HOST_CERTIFICATION_REQUIRED.
  • Types: LinuxHostCertificationProfile, LinuxHostCertificationReport, LinuxHostCertificationInspection, LinuxHostCapability, LinuxHostCertificationCheck, LinuxHostCertificationOptions, CertifyLinuxHostOptions.

Local provider fleet simulator

Optional module: @clank.run/framework/fleet-simulator; see local provider fleets for host admission, fixed faults, operator reservations, proof limits and interruption recovery.

  • parseLocalProviderFleetScenario(input): capture and freeze one bounded versioned scenario.
  • exportLocalProviderFleetScenario(scenario): deterministic JSON without operator configuration.
  • runLocalProviderFleetScenario({ certificate, scenario, disposable: true, quotaIds, portStart, signal? }): fixed real-process drills, current certified-host admission, bounded timeline and verified cleanup.
  • Types: LocalProviderFleetScenarioKind, LocalProviderFleetScenario, LocalProviderFleetOptions, LocalProviderFleetEvent, LocalProviderFleetReport.

Complete deployment provider service

  • openDockerDeploymentProviderService(options): opens provider data, exact-owner Docker cleanup and launch, private runtime ingress, and durable service fencing with secure defaults.
  • openDeploymentProviderService(options): composes injected data, Docker-runtime, and ingress components for custom hosting and deterministic tests.
  • reconcile(request): independently verifies the capsule, persists exact operation/fence intent, drains before stopping a writer, recovers/stages/migrates data, defers jobs until commit, activates ingress last, and supports exact retry after response loss or restart.
  • rollback(request): requires the exact current data generation, project-wide operation fence, confirmation, and abort signal; it drains all writers, durably records intent, restores the immediate predecessor, and resumes an interrupted post-commit attempt.
  • delete(request): requires the same fenced lifecycle envelope plus exact project confirmation, then drains all writers and removes provider data and service state idempotently.
  • handle(request): generation-bound private application ingress plus separately authenticated active-generation snapshot and diagnostics control boundaries.
  • deploymentProviderSnapshotPath(projectId): exact provider-private path for the consistent SQLite snapshot endpoint. It requires the memory-only control token carried by the active runtime capsule and returns DEPLOYMENT_PROVIDER_SNAPSHOT_MEDIA_TYPE.
  • deploymentProviderDiagnosticsPath(projectId): exact provider-private path for current generation logs and resource attribution. It uses the separate memory-only control token and returns DEPLOYMENT_PROVIDER_DIAGNOSTICS_MEDIA_TYPE.
  • deploymentProviderCanaryPath(projectId, "binding" | "prepare" | "inspect" | "stop" | "retire"): exact authenticated provider canary controls. Binding issuance persists a private credential digest receipt; old credentials grant only exact retained cleanup. Responses use DEPLOYMENT_PROVIDER_CANARY_CONTROL_PROTOCOL and DEPLOYMENT_PROVIDER_CANARY_CONTROL_MEDIA_TYPE. Only exact prepare returns a private candidate route token. canaries.controlTimeoutMs bounds HTTP handling; an uncertain timeout requires durable retirement retry. See the HTTP contract and restart limits.
  • inspect(projectId), snapshot(projectId), diagnostics(projectId, logLimit?), and close(): serialized non-secret durable progress, consistent backup input, bounded runtime visibility, and revoke/drain/verified-stop shutdown.
  • DeploymentProviderDataStore.apply(input, validate, discard?): optional cleanup hook runs before uncommitted SQLite rollback; failed cleanup leaves the journal intact.
  • Types: DeploymentProviderService, DeploymentProviderServiceLifecycleRequest, DeploymentProviderServiceOptions, DockerDeploymentProviderServiceOptions, and DeploymentProviderServiceState.

Managed data plane

  • createManagedIngress(options): exact-host reverse proxy with fixed upstream origins, bounded streaming request bodies, metadata-minimal fail-closed admitRequest, hop-header stripping, safe retries, circuits, health, and admitted/denied request observation.
  • inspectDomainRouting(hostname, target, resolver?): compare live CNAME/A/AAAA results to a configured edge target.
  • createDomainManager(options): project-bound random TXT ownership challenges.
  • createMemoryDomainStore(): in-memory domain challenge store for local use and tests.
  • Types: IngressRoute, IngressRequestMetric, IngressAdmissionRequest, IngressAdmissionDecision, IngressAdmissionPolicy, ManagedIngress, DomainChallenge, DomainDnsResolver, DomainRoutingReport.

AI

  • defineApp(input): normalize and freeze a clank-app/1 application blueprint.
  • parseAppBlueprint(source, filename?): statically parse a JSON or constrained TypeScript data module without executing it.
  • generateAppFiles(blueprint, options?): return deterministic full-stack application files.
  • createAppPlan(blueprint, options?): checksum every generated file and return a clank-plan/1 review artifact.
  • explainApp(blueprint): summarize identity, data, routes, services, deployment requirements, and warnings.
  • AppAdminStudioDefinition: configure the generated studio's static path, application roles, entity allowlist, and mutation-control visibility. Backend action roles and ownership remain authoritative.
  • Blueprint fixtures: AppFixtureDefinition, AppFixtureUserDefinition, AppFixtureRecordDefinition, and AppFixtureValue describe bounded synthetic states. Normalized AppFixture, AppFixtureUser, and AppFixtureRecord values are frozen, included in plan checksums, written under fixtures/, and exercised by the generated app-owned test.
  • generateBlueprintSigningKey(label, options): create a separately scoped Ed25519 publisher or registry key plus its public trust record.
  • signBlueprintRelease(blueprint, input) / verifyBlueprintRelease(value, trust, options?): bind exact name, semantic version, normalized blueprint, SHA-256 digests, namespace, and key.
  • signBlueprintCatalog(input) / verifyBlueprintCatalog(value, trust, options?): bind an exact HTTPS origin, monotonic sequence, sorted release entries, registry key, digest, and signature.
  • fetchBlueprintCatalog(url, trust, options?) / resolveBlueprintRelease(...): bounded, no-redirect, same-origin, exact-version remote discovery with complete re-verification.
  • createBlueprintTrustPolicy(input): immutable explicit roles/scopes, revocations, and minimum catalog sequences. BlueprintRegistryError.code identifies safe verification failures.
  • Types: BlueprintPrivateKey, BlueprintTrustKey, BlueprintTrustPolicy, SignedBlueprintRelease, SignedBlueprintCatalog, BlueprintCatalogEntry, VerifiedBlueprintRelease, VerifiedBlueprintCatalog, BlueprintRegistryFetchOptions.
  • s: runtime schema builders and JSON Schema generation. Includes string, email, URL, date, date-time, number, boolean, literal, enum, array, record, object, optional, nullable, default, refinement, union, and numeric/boolean coercion. Refinement predicates must return booleans synchronously; non-boolean results throw TypeError, rejected thenables are contained, and actual predicate failures propagate.
  • ValidationError: aggregate issues with paths.
  • defineAction(definition) → callable Action with .manifest and .definition.
  • ActionError: explicit code/status/details error.
  • createAgentBridge(actions, options?): registry, discovery, bounded/origin-aware invocation, confirmation enforcement, and Fetch handler.
  • actionRunner(action): reactive pending/data/error execution state.
  • defineView(definition): component with machine-readable viewManifest.
  • inspectAgentSurface(root): compact semantic UI tree with native labels/roles and form state; omits password/file values.
  • createAgentSurface(root): inspect, activate, and input operations through explicit agent IDs or native element IDs.
  • Types: Schema, Action, ActionContext, AgentBridge, ActionRunner, AgentNode, AgentSurface.

MCP

  • createMcpServer(options): zero-dependency MCP Streamable HTTP server for custom typed tools.
  • defineMcpApp(definition): validate and freeze one ui:// HTML resource, CSP declaration, permission request, dedicated domain, and border preference.
  • createMcpAppDocument(options): build a complete HTML5 resource with Clank's dependency-free iframe bridge inlined; no CDN or separate view bundle is required.
  • createMcpAppClient(options, environment?): connect a view to its host over JSON-RPC postMessage, then call tools, read resources, receive tool results and host context, request display modes, and handle teardown.
  • applyMcpAppTheme(context, root?): apply negotiated light/dark state and safe MCP host CSS variables to a view.
  • mcpAppClientScript(): standalone source used by createMcpAppDocument() and available for custom HTML generation.
  • portableMcpToolNames(names): deterministically converts logical dotted or hyphenated action paths into unique ASCII letter/number/underscore identifiers capped at 64 characters. Ordinary separators become _; overlong or colliding names receive a stable digest suffix.
  • McpServerOptions.metadata: optional bounded immutable contract data published inside the authenticated clank://actions resource; framework workflow graphs use this channel.
  • McpServer.revision: deterministic identity of server metadata, contract metadata, and the complete visible tool contract.
  • McpServer.notifyToolsChanged(): sends notifications/tools/list_changed to initialized legacy clients; close() terminates compatibility sessions and streams. Stateless 2026-07-28 clients use zero-TTL discovery instead.
  • MCP_PROTOCOL_VERSION: current stable protocol revision (2026-07-28).
  • MCP_APPS_PROTOCOL_VERSION: stable MCP Apps extension revision (2026-01-26).
  • MCP_APP_MIME_TYPE: exact HTML view MIME type (text/html;profile=mcp-app).
  • MCP_APPS_EXTENSION_ID: negotiated UI extension identifier (io.modelcontextprotocol/ui).
  • MCP_SUPPORTED_PROTOCOL_VERSIONS: current stateless revision plus compatible legacy revisions accepted by the dual-era transport.
  • McpToolError: public, redacted application-level tool failure.
  • McpTool.actionPath: optional original logical path published as clank/actionPath metadata when the public tool name is normalized.
  • Types: McpServer, McpServerOptions, McpTool, McpToolAnnotations, McpAuthentication, McpScope, McpAppDefinition, McpToolApp, McpAppCsp, McpAppPermissions, McpAppClient, McpAppHostContext, McpAppHostCapabilities, McpAppContentModalities, and McpAppDocumentOptions.
  • defineBackend() functions accept description and agent metadata.
  • openBackend() exposes eligible functions at /__clank/mcp by default and installs OAuth discovery automatically when the backend uses Clank auth. BackendRuntime.contractRevision is the same revision published by MCP discovery and GET /__clank/manifest.
  • Authenticated backends expose a server-rendered agent access inbox at /__clank/oauth/access and the no-store clank-agent-grants/1 contract at /__clank/oauth/grants. agent.maxUserGrants sets the per-user active-family ceiling from 1 through 1,000; the default is 100.
  • agentActionPath(reference): resolve a literal or typed backend function reference to its exact browser/MCP path.
  • inspectAgentActions(htmlOrRoot): collect bounded data-clank-action controls from SSR HTML or a rendered DOM.
  • checkAgentActionParity(surface, manifest, options?): return a frozen clank-agent-action-parity/1 report without throwing.
  • assertAgentActionParity(...): throw AgentActionParityError when a rendered action is stale, internal, undocumented, missing a stable ID, or absent when required.
  • verifyAgentActionParity(surface, options?): fetch the no-store backend manifest with a bounded response, bind its contract-revision header, and assert the current rendered surface.
  • Types: AgentActionTarget, AgentActionControl, AgentBackendManifest, AgentActionParityOptions, AgentActionParityReport, and VerifyAgentActionParityOptions.

See Interactive MCP Apps for embedded views, Agent protocol for connection, OAuth, scope, discovery, and security details, and Agent access for grant inspection, reduction, and revocation.

Router

  • createRouter(options) → router with state, current, navigate, resolve, start, View, and Link.
  • matchPath(pattern, pathname): parameter matcher.
  • matchRoutes(routes, URL, base?): route selection and URL decoding.
  • redirect(to, status?): Fetch redirect response.
  • Types: RouteDefinition, RouteMatch, RouteState, RouteLoadContext, RouteGuardContext, Router.

Server

  • createApp(options?) → Fetch request router with redacted errors and an error hook.
  • .use, .route, .get, .post, .put, .patch, .delete, .handle.
  • json(value, init?), text(value, init?), html(value, init?).
  • cors(options?), securityHeaders(options?), logger(write?): built-in middleware.
  • Types: RequestContext, RequestHandler, Middleware, RequestApp.

Authentication

  • defineAuth(options?): default or custom-profile auth contract.
  • openAuth(definition, database, options?): low-level SQLite auth runtime; normally opened automatically by openBackend.
  • authState(requestAuth): safe serializable SSR subset.
  • createAuthClient(options?): reactive auth-only client.
  • createClient<typeof authenticatedBackend>(options?): combined typed API, auth, CSRF mutation, seeding, and live client.
  • AuthGate: reactive signed-in boundary with default auth screen.
  • AuthForm: default accessible email/password registration/login UI.
  • AuthRuntime: .resolve, .handle, .middleware, .setRole, .disableUser, .revokeUserSessions, .verifyCsrf, current-session refresh and subscription/status, .close.
  • AuthClient: .user, .session, .authenticated, .loading, .error, .reload, .register, .login, .logout, .logoutAll, .changePassword.
  • AuthRequest: .user, .session, .csrfToken, .requireUser(), .requireRole().
  • AuthError: explicit safe auth code, status, and optional retry delay.
  • openOrganizationSecurityPolicies(database, auth, options): same-store current human policy controller with read, preview, version-fenced change, independent recover, immutable delegation capture/carry and current admission. Hooks are synchronous and bounded; JSON state cannot authenticate. openBackend(definition, { organizationSecurity: { organizationId, policy } }) binds application/CLI-MCP admission explicitly. Native openPlatform enables enforcement with organizationSecurity: { operatorRecovery?: boolean }.
  • createOrganizationSecurityClient({ auth, url?, prefix?, fetch?, timeoutMs? }): current session/CSRF transport for read, preview, change and recover. Retain exact unknown acknowledgements, then read current policy. See organization security policies for console, recovery, protocol and failure boundaries.
  • openOrganizationSso(database, auth, options): organization OIDC authentication, opt-in verified identity linking and scoped SCIM User/Group provisioning with a persistent policy revision. Provider provisioning accepts a separate expiring token and bounded external-group-to-viewer/developer mappings. Embedded applications supply synchronous onProvisioning; the native platform supplies transactional membership provenance and reviewed adoption. See organization and account security for the bounded SCIM profile, conditional writes, retained receipts, deactivation, migration and rollback requirements.
  • createOrganizationIdentityClient({ auth, url?, prefix?, fetch? }): account-bound browser identity inventory, fresh provider linking and versioned unlink receipts. AccountSecurity({ auth, identities?, onIdentityRedirect? }) supplies the corresponding account controls. Both are exported from @clank.run/framework/account-security.
  • Types: AuthDefinition, AuthDefinitionOptions, AuthUser, AuthSession, AuthState, AuthRegisterInput, AuthLoginInput, AuthUserId, DefaultAuthProfile.

Full-stack backend

  • defineTable(fields): validated document table definition; .index(name, fields) declares SQLite JSON expression indexes; .owned() scopes documents to the authenticated user.
  • defineDatabase(tables): preserves table names and field schemas as the inference root.
  • DocumentFor<Database, Table>: inferred fields plus branded _id, _creationTime, _version, and _ownerId for owned tables.
  • Id<Table> / DocumentId<Table> / s.id(table): nominal table-specific IDs.
  • openSQLite(schema, options?): opens Node's built-in synchronous SQLite engine.
  • openPostgres(schema, options): opens the bounded PostgreSQL application subset with verified TLS/SCRAM, trusted owner scopes, native transactions, retained revisions and explicit reconnect. History, aggregates and SQLite-native services are unsupported. See PostgreSQL application databases for exact startup and unknown-commit behavior.
  • ApplicationDatabase<Schema>: portable generated-table core; SQLiteDatabase retains its private native services and PostgresDatabase exposes its capability tuple and .reconnect().
  • createSQLiteDatabase(schema, connection, options?): wraps a compatible connection.
  • QueryBuilder.aggregate({ joins?, groupBy?, measures, authorize, limits? }): typed complete counts/sums/groups over declared root fields and direct references. Requires caller-scoped synchronous policies for every source, checks native stored-JSON admission before decoding, retains selective related/ACL dependencies, and rejects partial or oversized results. Types: AggregateJoin, AggregateField, AggregateMeasure, AggregateLimits, AggregateOptions, AggregateResult, AggregateScalar. See authorized aggregates.
  • SQLiteDatabase: .read, .tracked, .transaction, .subscribe, .version, .close.
  • Read table: .get, .query, .collect, .history(id?, options?).
  • Write table: .insert, .patch, .replace, .delete, .restore(id, cursor, options?).
  • DocumentWriteOptions: { ifVersion } optimistic concurrency for patch, replace, and delete.
  • DatabaseConflictError: stale-write error exposed as HTTP 409 VERSION_CONFLICT.
  • DocumentRevision, DocumentRevisionCursor, DocumentHistoryOptions, and DocumentRestoreOptions: typed immutable snapshots, bounded pagination, and compensating restore.
  • DatabaseRevisionNotFoundError: unavailable or ownership-hidden history exposed as 404 REVISION_NOT_FOUND.
  • Query builder: .where, .orderBy, .limit, .collect, .first.
  • defineBackend({ schema, auth? }).functions(builders): inference-first nested function tree. Auth backends make query/mutation required and expose explicit publicQuery/publicMutation.
  • createApi<typeof backend>(): zero-codegen typed function-reference proxy.
  • openBackend(definition, options?): consistent query cache, owner-scoped/persisted dependency invalidation, atomic mutations, manifest, bounded RPC, and SSE handler.
  • BackendRuntime: .auth, .caller(request), .query, .mutation, .subscribe, .handle, .version, .close.
  • createSyncClient(options?): typed browser/Fetch client with .query, .mutate, .live, and .seed.
  • createClient<typeof backend>(options?): authenticated combined client with .api and .auth.
  • BackendClientError: safe RPC error with code/status.
  • LiveQuery: reactive .data, .loading, .error, .version, plus .dispose().
  • functionPath, functionKey, stableStringify: reference and canonical argument helpers.
  • Types: DatabaseSchema, TableDefinition, DocumentWriteOptions, DatabaseChange, SQLiteOptions, QueryBuilder, ReadDatabase, WriteDatabase, BackendFunction, BackendDefinition, FunctionReference, ApiOf, BackendRuntime.

Service drivers

  • createServiceRegistry(drivers): named capability registry with startup assertions, isolated health checks, and reverse-order shutdown.
  • openFileEmailService({ directory }): owner-only development outbox; it does not send mail.
  • createHttpEmailService(options): normalized HTTPS JSON delivery with bounded transport retry, optional bearer authorization, and idempotency forwarding.
  • createResendEmailService(options): zero-SDK Resend POST /emails driver with provider recipient and tag validation plus idempotency forwarding.
  • Types: ServiceDriver, ServiceRequirement, ServiceRegistry, EmailAddress, EmailMessage, EmailReceipt, and EmailService.

See Service drivers and Invitations and email delivery.

Durable jobs and cron

  • defineJobs({ schema }).jobs(builders): inference-first nested job tree sharing an application database schema.
  • defineWorkflow({ args, graph, returns?, output?, agent? }): typed acyclic graph over ordinary jobs and durable waits. step(job, { needs?, args, compensate? }) declares explicit result flow; compensate: { job, args } declares a registered job with agent.idempotent: true, while { manual: reason } preserves an explicit irreversible boundary. Cleanup mappers receive typed input, run/step/original-job identities, stable operation key and discriminated outcome. wait({ mode, needs?, timeoutMs, returns, request }) declares a typed decision/event result without a runnable job. Wait mappers are synchronous; deadlines are 1 second through 30 days.
  • defineWorkflows(jobSystem, tree): registers stable nested workflow paths on a job system.
  • job({ args, returns?, queue?, priority?, timeoutMs?, retry?, schedules?, handler }): validated async handler definition with agent/operator metadata.
  • Mutation context.jobs.enqueue(definition, args, options?): transactional, owner-scoped enqueue.
  • openJobs(definition, { database, ...options }): low-level durable runtime for an already-open Clank SQLite database. Wait graphs require workflowWaits: { signingKey, policyRevision }; use one persistent 32–1024 character secret and increasing revision across all processes.
  • runJobProcess(runtime, options?): provider-neutral worker/scheduler entry with environment role selection and graceful signals.
  • normalizeCron(expression) / nextCronOccurrence(expression, after, timezone?): strict five-field cron parser and IANA-zone occurrence calculation.
  • jobPath(definition) / jobManifest(system): stable definition identity and agent-readable metadata.
  • workflowPath(definition) / workflowManifest(system): stable graph identity, schemas, step job paths, dependency edges, descriptions, and agent metadata.
  • JobRuntime: .enqueue, .publisher, .get, .list, .events, .stats, .cancel, .retry, .purge, .startWorkflow, .getWorkflow, .listWorkflows, .workflowEvents, .getWorkflowWait, .resumeWorkflowWait, .cancelWorkflow, .purgeWorkflows, .advanceWorkflows, .workOnce, .scheduleOnce, .startWorker, .startScheduler, .close.
  • JobRuntime.getWorkflowWait(workflowId, step): trusted server ticket containing the persisted request, owner, deadline, state/version and secret resume token. Ordinary inventory/events omit tokens. Independently authorize every adapter exposing a ticket or accepting an event.
  • StoredWorkflowRun.compensation?: separate retained recovery state and ordered per-step job/result/error evidence. The original failed/cancelled outcome is preserved. Automatic cleanup runs one job at a time in reverse dependency order after forward children settle; manual barriers and exhausted cleanup stop upstream work. Successful runs report not-needed.
  • JobRuntime.purgeWorkflows({ includeUnresolvedCompensations: true, ... }): trusted-operator opt-in to delete inactive manual recovery evidence. Routine purge protects unresolved recovery and its referenced jobs; active jobs remain protected even with this opt-in. See workflow compensation.
  • JobRuntime.resumeWorkflowWait({ waitId, expectedVersion, resumeToken, idempotencyKey, choice, result? }): synchronous transactional resume/deny. Human decisions require current accepted reviewed-action execution by the run owner; external adapters authenticate their provider. Schema validation, current policy/token and exact version prevent stale transitions. Exact retained retries return historical receipts; changed retries reject. No anonymous endpoint is installed. See durable waits.
  • openPlatform({ jobs: { alertDueAfterMs } }): sets the hosted overdue-work alert threshold without changing application retry or scheduling policy.
  • Hosted job API: GET /api/projects/<id>/jobs?state=&queue=&limit=, POST /api/projects/<id>/jobs/<job-id>/cancel, and POST /api/projects/<id>/jobs/<job-id>/retry. Responses omit arguments, results, error text, owner/group identity, worker identity, and lease tokens. Provider projects use the identical contract through an exact-generation authenticated private control route and fail closed with PROVIDER_JOBS_UNAVAILABLE during node or generation instability.
  • Types: JobDefinition, JobHandlerContext, JobPublisher, JobHandle, StoredJob, JobEvent, JobStats, JobRetryOptions, CronDefinition, JobWorkerOptions, JobSchedulerOptions, JobRetentionOptions, WorkflowDefinition, WorkflowStepDefinition, WorkflowHandle, StoredWorkflowRun, StoredWorkflowStep, WorkflowEvent, WorkflowManifestEntry, WorkflowCompensationContext, WorkflowCompensationDefinition, WorkflowCompensationState, WorkflowCompensationStepState, StoredWorkflowCompensation, and StoredWorkflowCompensationStep.

See Durable jobs and cron for transaction, lease, retry, scheduling, process, deployment, and at-least-once semantics.

Durable objects

  • defineDurableObject({ name, state, initial, version?, migrations?, methods, alarm? }): define a stable stateful namespace with typed query and mutation methods.
  • openDurableObjects(definitions, { database, ...options }): open the SQLite-backed runtime with per-ID local lanes, renewable cross-process leases, revision fencing, bounded state, and durable mutation idempotency.
  • runtime.get(definition, id) / runtime.namespace(definition).get(id): obtain an inert typed stub. .call() returns the method value; .invoke() also returns revision and deduplication.
  • stub.inspect() / .subscribe(listener): trusted server snapshot and cross-process revision observation. namespace.list() is a bounded operator read, not a browser endpoint.
  • storage.get(), mutation .set(), .update(), .deleteAll(), .getAlarm(), .setAlarm(): immutable reads and commit-on-success state operations.
  • runtime.runAlarmsOnce() / .startAlarmScheduler(): fenced one-alarm-per-object execution with bounded exponential retry and retained failure diagnostics.
  • durableObjectManifest(definitions): immutable state/method/alarm JSON Schema contract.
  • durableObjectMcpTools(runtime, definition, { authorize }): convert explicitly agent-enabled methods into scoped MCP tools with mandatory exact-object authorization.
  • Types: DurableObjectDefinition, DurableObjectMethod, DurableObjectStorage, DurableObjectMutableStorage, DurableObjectStub, DurableObjectNamespace, DurableObjectRuntime, DurableObjectSnapshot, DurableObjectCallResult, DurableObjectAlarmDefinition, and DurableObjectMcpToolsOptions.

See Durable objects for state evolution, serialization, external side-effect, alarm-process, authorization, backup, and placement guarantees.

SSR

  • renderToString(view, options?): escaped async HTML rendering with hydration markers by default.
  • renderDocument(view, options?): complete document template with title, head content, stylesheets, state, module scripts, and optional CSP nonce.
  • serializeState(value): JSON serialization safe for an HTML script element.
  • readState<Value>(id?, root?): reads a serialized application state script.
  • Types: RenderStringOptions, RenderDocumentOptions.

Node

  • serve(app, options?): bounded Fetch-standard Node HTTP server with streaming, timeouts, Host allowlists, proxy controls, and redacted errors.
  • staticFiles(root, options?): traversal/symlink-aware static GET/HEAD handler with dotfile policy and weak ETag revalidation through If-None-Match.
  • Types: FetchApplication, ServeOptions, ServerHandle, StaticFilesOptions.

Backend OpenAPI export

  • exportBackendOpenAPI(definition, options) exports OpenAPI 3.1.1 for existing HTTP RPC functions.
  • OpenAPIOptions specifies title/version, deployment URL, runtime prefix and optional replay policy.
  • Explicit result schemas are required; unsupported/coercing/refined contracts reject export.
  • See database contracts for auth, retry and compatibility details.

Translation review

  • exportTranslationBundle(messages, options) extracts source keys/parameters with source/current fingerprints.
  • reviewTranslationBundle(messages, json, options) validates a translator artifact and returns issues and a before/after diff.
  • acceptTranslationReview(messages, review, options) rechecks content and catalog versions before returning accepted typed messages.
  • messageCatalogRevision(catalog, locale) and I18n.revision() provide the same browser/server content identity.
  • See localization for release/rollback boundaries.

Durable document collaboration

@clank.run/framework/retention-administration exports openRetentionAdministration, createRetentionAdministrationClient and mountRetentionAdministration for scoped inventory, exact purge previews/receipts, versioned holds and persistent schedules. See retention administration for the protected data subset, current-session/operator checks, capacity limits and upgrade/recovery boundaries.

@clank.run/framework/collaborative-documents provides openCollaborativeDocuments, createCollaborativeDocumentsClient, textEdit and mountCollaborativeEditor. See durable data workflows for authorization, replay and capacity policies.

  • Cursors: setCursor, cursors, clearCursor and mountDocumentCursorPresence; session-bound ephemeral selections at explicit persistent text revisions, with expiry and rebasing.
  • Proposals: createBranch, readBranch, branches, saveBranch, proposeBranch, previewBranch, decideBranch and mountDocumentBranchReview; durable named drafts, reviewed before/after text, atomic merge decisions and exact retry identities.
  • Types: DocumentSelection, DocumentCursor, DocumentBranch, DocumentBranchSummary, DocumentBranchPreview.

Search browsing

@clank.run/framework/search exports createSearchBrowsingClient and mountSearchBrowsing. Enable browsing: { policyRevision, maxSavedSearches?, maxSavedIdentities?, maxSavedBytes? } on openSearch with a linked source and optional typed scalar source.facets. The client adds browse, saved, version-fenced save and removeSaved; legacy SearchClient stays compatible. See search browsing for complete authorized counts, cursor invalidation, compact retired keys, limits and rollback semantics.

Project dependency configuration, checks, retained activations and verified recovery use /api/projects/:id/dependencies. See deployment dependency gates for strict bodies, version/check binding, upload headers, rollback fencing and human override scope.

  • createTemporaryAccessClient and createTemporaryAccessView expose current-session, bounded native preview grants with expected versions, exact retry intents and explicit revocation. TemporaryAccessError supplies bounded transport error codes/status. See temporary preview access for mandatory native freshness, restart invalidation and the restricted creation header.

Customer status pages

Use createCustomerStatusClient() from @clank.run/framework/customer-status for current human administration, public projections and own-account subscriber preferences/inboxes. create, configure, preview, publish and unpublish retain native versions and exact operation receipts. domains, beginDomain and verifyDomain use current native domain reservations. publicPage omits credentials and validates the strict public projection. preferences, subscribe and notifications act only on the actual native account. See Customer status pages for publication review, assurance, limits, custom domains and recovery.