@theaiplatform/sdk
v0.5.2
Published
Portable TAP capability contracts and federation/MCP adapters
Readme
TAP SDK
Portable capability descriptors, host-service contracts, a transactional installation registry, Module Federation loading, and MCP access. Business logic, identity policy and native implementations belong to products and hosts.
Build with pnpm build; pnpm pack emits an installable ESM package with declarations. Consumers use the package's exports, never its source directory. React is optional for headless consumers.
UI-only descriptors omit mcp; headless descriptors omit targets and contributions. A descriptor with both provides UI and tools. Host context describes the current actor and placement; the receiving service still verifies credentials and authorizes each operation. Optional host services report their absence for the affected feature.
Schema 2 also permits execution-only descriptors with no UI or HTTP MCP endpoint. Schema 1 remains unchanged for existing consumers; putting an execution declaration under schema 1 is rejected. Required execution semantics must not be silently stripped by older hosts.
@theaiplatform/sdk/registry prepares a replacement before making it active, retains the previous selection after failure, and refuses removal/replacement while a surface reports unsaved edits. An immutable remote revision must have its own federation name. Reusing a loaded name with a different entry requires reopening the host; arbitrary in-place remote replacement is unsupported.
The SDK is independently versioned and published as @theaiplatform/sdk; releases up to 0.3.0 were packaged as @with-tap/sdk. With TAP, The AI Platform and other hosts consume the same package. See the workspace README for the reference integrations and compatibility evidence.
Releases publish through Release Please with npm trusted publishing. Private-source releases omit npm provenance, while public-source releases retain it.
Descriptor and host context additions
The following are all optional and remain schemaVersion: 1. The 0.3 schema strips unknown keys, so installed 0.3 hosts accept these descriptors and ignore the new fields.
Descriptor fields:
requires/optional: host features. Built-in features arenetwork,files,localDataandopenExternal. Host operations usehost:<vendor>.<name>, for examplehost:with-tap.commerce.appearance:{ brand: "host" | "own", schemes? }.icon: resolved like target entries.targets.*.shared: singleton ranges.- Per contribution:
contexts:workspace,roomorrecord:<kind>;app: aui://MCP App resource used when a host cannot load federation.
Exception: MCP App-only capabilities. A capability with no federation target is a new shape that 0.3 hosts reject. Publish a federation target as well while 0.3 hosts remain supported.
Exception: requires on 0.3 hosts. 0.3 hosts ignore requires.
HostContext additions: features, navigation.openExternal, context.recordKind, and an observable appearance with theme and subscribe.
context.workspaceId is an opaque host scope. Hosts may have one workspace or many. It is never a product workspace or a grant.
Host kernel (@theaiplatform/sdk/host)
createCapabilityHost(ports) is the host-independent runtime. It covers:
- origin trust for descriptors, remotes, icons and MCP endpoints;
- target selection;
- transactional installation through the registry;
- MCP connection and local-data admission;
HostContextassembly;- installation- and scope-keyed storage;
- save/restore with pins;
- disposal of late arrivals.
Ports. A host supplies storage, a surface loader, credentials, appearance and its trusted configuration. It keeps its own chrome, navigation and update discovery.
Credentials. These attach only through trust.services, keyed by capability ID.
- A descriptor cannot name an audience.
- Each binding lists the
originsallowed to receive it. The descriptor and every federation entry must come from them, so another trusted origin cannot claim the ID. - Requests must use paths within the binding's base path. Dot segments, encoded separators and absolute or protocol-relative URLs are refused.
- A credential port appends the path to
baseUrl.
Disposal. Replacement, restore and removal retire the displaced installation. Retained legacy local/files, admitted local-data and MCP handles are fenced along with network, services, navigation, open-external and dirty tracking. Calls started before retirement can already have committed at the backing adapter; the fence prevents new calls and rejects results arriving after retirement, but cannot undo a committed write. Adapters that need stronger in-flight cancellation must enforce it themselves.
Scope changes. setScope abandons in-flight installs, disposes every surface and client, then restores the new scope's saved installations. Failed cleanup remains owned for retry on a later scope change or close; a failed transition does not restore the new scope automatically.
Restore. It accepts each saved release from an unconfigured origin individually through acceptSavedRelease, never the whole origin. Each replacement preserves the previous installation if preparation fails; successful admission determines whether the localData feature is available before loading contributions.
Target selection. selectTarget tries native, then web federation, then MCP App frame, then tools only. It checks requires against host features and targets.*.shared against host singleton versions. Each skipped rung is reported with a reason. satisfiesRange supports exact, ^, ~, comparison operators, *, conjunctions and ||. Anything else fails closed. The 0.4 kernel loads web federation. A native loader follows with the mobile work. AgentCatalogPort is defined for adapters; the kernel does not call it yet.
Execution and background service contracts
execution, runtime and installer are portable subpaths with no React or native-runtime imports. They define metadata, receiver contracts and validation; importing them does not install software, register an OS job or open a device. Product consumers acquire these exports only by explicitly adopting a newly approved packaged SDK release.
Schema-2 descriptors require execution: ExecutionDeclaration with contractVersion: 1. executionDeclarationSchema validates bounded service/operation lists, local service references and unique route IDs. Each operation has explicit hosted or local routes. Local routes declare presentation (none, offscreen-renderer, visible-ui), lifetime (ui-attached, user-session) and required permissions. Hosted routes name a trusted serviceBinding, never a token audience. No route implicitly falls back to another.
import { descriptorSchema } from "@theaiplatform/sdk";
const descriptor = descriptorSchema.parse({
schemaVersion: 2,
id: "example.calendar",
title: "Calendar",
version: "1.0.0",
execution: {
contractVersion: 1,
services: [],
operations: {
"calendar.list": {
routes: [{ id: "api", kind: "hosted", serviceBinding: "calendar.api" }],
},
},
},
});Local service references include a stable ID, HTTPS manifest URL and SHA-256 digest, protocol name/major version, instance scope, supported activation policies and login-start support. Default activation is on-demand; persistent enablement and login start are separate preferences. A referenced digest is not publisher authentication: native installers must verify signed manifests, artifact identity and platform compatibility. Executable hooks/commands and unknown execution-contract fields are rejected. Artifact/driver packaging remains a native adapter responsibility.
Runtime state. runtimeSnapshotSchema separates installation, OS registration/approval, desired policy and observed process state. Installed/running releases carry their own verified manifest digests. Ready processes require an installed/registered service, enabled policy, generation and compatible protocol. Stopped/faulted instances cannot advertise stale running metadata. describeExecutionRoute combines one parsed route with trusted receiver observations and a validated snapshot, returning ready, startable or a specific blocker. It checks exact running/installed manifest pins, permissions, authority, presentation dependency and product/device/network blockers. It does not verify signatures, activate a process, prompt for permissions, authorize requests or choose a fallback. Execution must recheck these conditions.
Host attachment. A schema-2 host supplies execution: ExecutionHostPort with contractVersion: 1. Without it, installation fails before loading surfaces, even when the UI/MCP fallback would otherwise work. prepare validates the declaration and attaches to already approved execution; unsupported requirements reject. It is not an installation hook. It returns guarded operations, a dispose that releases only this attachment, and optionally an admitted MCP App/resource connection. The adapter owns that connection's cleanup. Schema-2 operations cannot bypass the adapter through the legacy host operation override or raw MCP connection fallback. MCP App presentation requires its admitted transport.
Surface removal/host shutdown disposes this attachment and revokes its HostContext; independent product jobs retain their own authenticated grants and durable IDs. Late attachments after close are disposed before publication. Administrative RuntimeInstaller is a separate receiver and is never automatically exposed to product surfaces or agent connections.
Runtime client. RuntimeClient describes/watches service state and acquires generation-bound RuntimeAttachments. Its authenticated receiver scope identifies the principal/product/workspace. acquire uses an expected revision and cannot install software, prompt, override disable policy or reuse a disposed UI grant. release cannot stop another attachment or independently admitted work. Watch history is bounded: resync-required asks for a fresh snapshot. Product command schemas, authorization, persistent jobs and cancellation semantics remain product-owned.
Installer. RuntimeInstaller plans install/update/uninstall, applies retained plans by ID/revision/idempotency key, changes policy, stops services and reconciles durable installation-operation IDs. installationPlanSchema validates a bounded review projection with typed component actions. The native receiver retains the authoritative plan, exact artifact digests, approval/expiry/dependency state and installation journal; it cannot execute a client-supplied replacement action list. Cancellation or transport loss after acceptance requires operation reconciliation, not blind retry. Native implementations must preserve user disable policy, distinguish pending OS approval from readiness, and never start capture or recording merely because installation succeeds.
The conformance kit's optional execution group verifies that presentation detachment revokes the UI client while independently admitted work remains alive. The SDK fixture exercises host ownership only; it does not establish OS registration, signed helper permissions, virtual audio routing or service provisioning. Remaining adapters and device acceptance are tracked in background runtime implementation.
Managed account and access (@theaiplatform/sdk/access)
HostContext.access is optional. Its presence means the host owns embedded account sign-in, product-specific credential acquisition and entitlement presentation. Contributions use the existing session/context for local scoping and network for the host-selected product transport; they do not mount another sign-in or seat-purchase gate. Hosts without this service retain independent product flows.
HostAccess.getSnapshot() returns a stable object until a change. subscribe(listener) notifies after a change and returns an unsubscribe function. States are checking, ready with mode: "edit", local with mode: "read", and denied/unavailable with a public message. Local recovery permits only explicitly supported local reading/export, not paid editing or online access. Missing or inactive services are unavailable rather than another sign-in prompt. useHostAccess(host) from /react subscribes in web and React Native surfaces; absent service returns undefined without probing product tools.
The host kernel accepts an optional access(capability, {scope, signal}) source port and declares the access feature only for installations receiving it. Supplying the port must not start sign-in or entitlement checks during installation. Hosts own check timing, chrome, cancellation, native receiver admission and revocation. bindHostAccess validates snapshots and fences subscriptions after installation/account teardown. The reserved services.call("host.access", {}) compatibility operation returns {managed:true, mode} only for admitted ready/local states and cannot be impersonated by an MCP tool.
Snapshots carry no token, membership, permission list or server authority. Every API still validates its own audience and workspace/product grants; native data/edit admission remains independently verified. This contract neither widens consent nor promises silent resource authorization. 0.4.0 is a local packaged candidate until independently released; older exact consumer pins remain unchanged unless explicitly adopted.
Theming (@theaiplatform/sdk/theme, @theaiplatform/sdk/react)
Vocabulary. The vocabulary is the MCP Apps 1.7.5 style keys (standardThemeKeys) plus extensionThemeKeys such as tap-action and tap-accent-text. A HostTheme contains:
- the current scheme's
variables; - optional
schemes.light/schemes.darksets; fontsfor frames.
Federated surfaces. applyTheme writes --tap-host-<key> values, data-tap-host-scheme and color-scheme to the surface's mount element, never to the document. Shadcn/Tailwind hosts already define names such as --font-sans and --shadow-sm, so the prefix keeps the contract unambiguous. Products read the prefixed names through their own aliases, with their own values as fallbacks.
Each value is written as --tap-host-<key> and also as --tap-host-<scheme>-<key> for the host's current scheme. A product reads the scheme-qualified name for the scheme it is drawing, for example var(--tap-host-dark-color-background-primary, #000) in its dark palette. A dark subtree then takes host values only while the host is dark, a nested subtree in the other scheme keeps the product's own colors, and an explicit schemes set from the host overrides the alias. Scheme-independent values (fonts, radii) are read unqualified. Both forms are inherited properties, so they also cross a shadow root.
Fonts and validation. Hosts load fonts at document level, and products use family stacks. validateTheme reports unknown keys, unsafe values, missing required keys (see productThemeKeys) and WCAG contrast failures. Colors it cannot evaluate, such as oklch(), are reported as unverifiable.
React.
CapabilitySurfacerenders a surface insideThemedMountwith an error boundary. Theme changes update the mount in place, so the surface keeps its state.brand: "own"surfaces receive only the scheme.useHostAppearanceanduseHostThemealso work in React Native.
MCP App frames.
- On the host side,
mountMcpAppacceptstheme, sends standard host-context styles plus the complete theme underwith-tap.ai/theme, and adds font origins to the frame CSP. @theaiplatform/sdk/react/mcp-apprenders that frame and forwards theme changes.- Inside a frame,
connectAppViewapplies both name sets and returns anappearance.
Conformance (@theaiplatform/sdk/testing)
conformanceScenarios(createDriver) returns framework-neutral scenarios. A host adapter must pass them:
- complete host context and declared features;
- untrusted-origin refusal;
- per-installation and per-scope storage;
- credentials only for the trusted binding and service-relative paths;
- in-place theme application.
conformanceThemes are deliberately unusual packs, so an unthemed surface is obvious. The workspace runs the kit against a kernel driver in tests/conformance.test.ts, including a deliberately leaky host that must fail. examples/minimal-host is the browser reference: one adapter file, no product code.
Optional local data (protocol version 1)
HostContext.localData?: LocalDataCapabilities is an additive, versioned host extension. Existing local, files, services and hosts remain unchanged. Check localData?.version === 1 before using the group. Each of sql, files, embeddings and vectors is independently optional. These APIs require an explicitly adopted candidate artifact; older pinned artifacts do not acquire them automatically.
import { describeLocalCapability } from "@theaiplatform/sdk/local-data";
import type { HostContext } from "@theaiplatform/sdk";
async function openCache(host: HostContext) {
const sql = host.localData?.version === 1 ? host.localData.sql : undefined;
const state = await describeLocalCapability(sql);
if (!sql || state.status !== "available") return state;
return sql.open({ name: "search-cache-v1", storage: "evictable", create: true });
}| Export | Contracts and dependency-free helpers |
| --- | --- |
| @theaiplatform/sdk/local-data | LocalDataCapabilities, LocalSql, ScopedLocalFiles, branded handles, storage/availability/error types; describeLocalCapability, LocalDataError, validateLocalOperation, validateLocalStoreRequest, validateLocalStoreInfo, validateLocalSqlQuery, validateLocalSqlBatch, validateLocalSqlResult, validateLocalFileRange, validateLocalFileWrite, validateLocalFileReplace |
| @theaiplatform/sdk/local-semantic | LocalEmbeddings, LocalVectors, model-space/request/result/limit types; validateLocalEmbeddingSpace, assertLocalEmbeddingSpace, validateLocalEmbeddingRequest, validateLocalEmbeddingResult, validateLocalVectorOpenRequest, validateLocalVectorUpsert, validateLocalVectorRemove, validateLocalVectorQuery, validateLocalVectorResult |
Neither subpath imports a database, model, inference client, framework or native runtime. Models are optional host facilities, not an inference subscription requirement. There is no SDK workflow API or automatic cloud fallback.
Authority, guarantees and errors
Hosts inject a receiver already bound to an authorized account/workspace/publisher/installation and issue opaque handles. Logical names are not paths, principals or authorization. TypeScript brands prevent accidental handle mixing, not forgery: adapters must authenticate the caller and check their handle registry and current grants on every operation. Handles cannot be shared across receivers/scopes. Closing, revocation, logout and incompatible installations invalidate handles; reopening obtains a fresh handle under fresh authorization. Trusted federation shares the host JavaScript realm; injection alone does not sandbox hostile code.
describe() returns either { status: "available", info } or an explicit unsupported, unavailable, permission-required, permission-denied, revoked or quota-exceeded state. describeLocalCapability(undefined) reports unsupported. Operation failures use LocalDataError.code; bridges must preserve that code, not depend on instanceof across realms. Discovery is a snapshot, not a grant or assurance that the next operation succeeds.
Opens request exactly durable, evictable or session storage. There is no silent downgrade. Durable storage requires committed crash recovery and cannot be cache-evicted; it is not a claim of backup or immunity to disk loss/user deletion. Encryption is unknown unless explicitly reported, and verified encryption includes a host-described key lifecycle. Quota is a snapshot or null when unknown. create defaults to true; false requires an existing store. Products own schemas, CAS/migration logic, sync, accepted-work recovery, sends and index invalidation.
All operations accept { signal?, timeoutMs? }. Hosts impose advertised finite deadlines even when omitted, enforce limits before work and during result production, and cancel native/model work rather than only discarding a reply. A cancelled SQL/vector mutation must not have committed; a known commit wins a racing abort. A transport failure can be indeterminate: reconcile using product-owned identifiers rather than blindly retrying mutations.
SQL and files
SQL offers parameterized, read-only query and a bounded atomic batch of single SQL statements. No callback transaction can span network/model I/O. expectChanges provides a product-owned optimistic guard: any mismatch is a conflict and rolls back the entire batch. Results exceeding row/byte caps fail without partial results. Product migrations can use a schema-version table and guarded updates in the same batch; the SDK never chooses a migration, repairs an index or resets a database.
Batches accept only non-row-producing statements. Row-producing mutations such as INSERT, UPDATE or DELETE with RETURNING are rejected by this candidate; they cannot use the read-only query lane.
SQL validators check payload bounds and result shape, not SQL safety or authorization. Native adapters must enforce read-only queries, single statements and an engine-level allowlist/authorizer. Deny transaction-control SQL, attach/detach, external files, extension loading, unsafe pragmas/functions and unapproved virtual-table modules. Advertise FTS5 only when actually supported and authorized.
Scoped files offer bounded range reads, optional random-access writes, optional atomic replacement and optional flush. Features must match implemented methods and actual guarantees. They deliberately advertise locking: "none": this is not a SQLite VFS, WAL or cross-process-locking contract. The old whole-file HostContext.files does not gain these guarantees. Plugin-owned engines may use the scoped route when its guarantees suffice; a SQLite VFS requires a separate verified locking/recovery adapter. External source-file reopening/reselection is not granted by these handles.
Local embeddings and vectors
Embeddings discover installed-model availability separately from service availability. open selects an exact model space; it does not download a model. Embedding work and vector storage/search stay on the device; unavailable local work does not authorize remote processing. A model space includes id, model, immutable pipeline revision, dimensions and normalization. A changed model/tokenizer/pooling configuration requires a distinct identity/revision; matching dimensions alone is insufficient.
Record IDs and model-space identity strings must be well-formed Unicode. Unpaired surrogates are rejected rather than normalized to the replacement character, preserving distinct identifiers across UTF-8-backed adapters.
Vector indexes are independently scoped logical stores with an immutable model space and metric (cosine, dot or euclidean). Open must reject incompatible existing indexes without resetting them. Upsert/remove are atomic bounded batches; search returns IDs and scores, not product metadata. Optional candidate IDs restrict results within the already-authorized index; they are not access grants. Cosine/dot results sort by descending similarity; Euclidean results sort by ascending distance. Products join IDs to their own authorized records and own rebuild/version policy. Neither SQL nor a specific engine such as Zvec is required by the semantic contracts.
Browser, desktop and mobile must negotiate independently. Existing browser virtual files do not imply SQL, durable recovery or persistent model/index support; a native host is not automatically durable/encrypted either. Browser eviction and worker/locking constraints and mobile suspension/background execution need separate evidence. Use the local data contracts, validators and semantic contracts for exact signatures and payload accounting; remaining acceptance is tracked separately. The conformance fixtures prove contract/validator behavior, not native persistence, crash recovery or inference.
Optional host semantic helpers
@theaiplatform/sdk/host/local-semantic is an opt-in, dependency-free host helper
entry. It exports createInstalledLocalEmbeddings, createSqlLocalVectors,
their configuration/provider types, and LocalSemanticGrant. Desktop and proof
hosts own admission, revocation, resource cleanup, SQL namespaces, installed-model
policy, and corpus budgets. Products consume only HostContext.localData and
the portable semantic contracts; this entry is not a product storage engine,
model runtime, workflow engine, or authority boundary. It adds no mandatory
database/model dependency and never selects a cloud inference fallback.
The exact SQL vector implementation defaults to a bounded 2048-entry/16-MiB corpus; production hosts must explicitly choose measured budgets. With TAP's native host currently admits the smaller 128-entry/256-KiB profile on a dedicated native index namespace. The proof-host semantic paths remain compatibility reexports, including private operation helpers used by its tests.
Companion widgets
The optional top-level companion: { contractVersion: 1, widgets: [...] } envelope registers
host-rendered status, list, and controls templates independently of full UI contributions
and required schema-2 execution. Read it with companionWidgets from @theaiplatform/sdk/companion.
Unknown envelope versions or malformed widgets omit only that optional presentation. Preserve the
raw envelope in saved descriptors; a host upgrading a snapshot made by 0.4 must refresh metadata
from the same trusted exact pinned release before widgets become visible.
A CompanionPort belongs to the product adapter. read observes without installing, activating,
logging in, capturing or opening UI. invoke independently validates product/workspace authority,
arguments, revision and operation id, returning an acknowledged product response and matching view.
Keep repeat operation ids idempotent; lost replies remain unconfirmed and retry replays the same
id. dispose releases only the presentation, never approved work. Every view is limited to 32 KiB,
five items and three displayed actions, from at most eight declared actions across widget states. The host escapes text and draws every control; no product
HTML/code or native prompts execute inside the companion. Authentication is the shared host account,
never a widget action. Native capture consent remains a separate product-owned flow.
createCompanionAttachment fences late reads/actions on disposal, hides stale product titles and
requires matching operation receipts. Hosts own pins, layout, trusted service status/microphone
indicators and verified agent observations; widget contents never establish those facts.
An installer may expose resumeOperation(id) to reconcile its own durable accepted intent after a presentation or process restart. This administrative method reuses the retained release, policy, plan and idempotency key; it cannot introduce new intent. Feature-detect it on older installers. Missing support is an explicit reconciliation requirement, never permission to manufacture a new install, Stop or Disable request.
