// Pack registry (the twins architecture notes → "Optional shared // libraries"; #1). A lightweight, dependency-free way for vendor twins to *declare* // themselves so tooling can discover them — "add a vendor" gets cheaper. A pack // EXPORTS a `TwinPack` descriptor (no import side-effects); a consumer that imports // the packs it wants registers them and queries the registry. The kernel never // imports packs (no dependency inversion) — discovery is the consumer's choice. // // This is an optional convenience, NOT a kernel that defines the twin: a pack can // ignore the registry entirely. Pure + deterministic. import { declareRateBudget, type RateBudgetDeclaration } from './rateBudget.ts'; import type { TwinAuthStrategy } from './executor.ts'; import { referenceField, registerReferences, type ReferenceDeclaration } from './references.ts'; import { deriveStateSystem, deriveVendorStateSystem } from './derived-real.ts'; import type { DerivedManifest, VendorManifest } from './derived-core.ts'; import type { DerivedSurface } from './derived.ts'; import { registerAuthStrategy, registerStateSystem, type StateSystemAdapters } from './state-system.ts'; import { PROTOCOL_VERSION, protocolStanding } from './protocol.ts'; export { PROTOCOL_VERSION, PROTOCOL_MAJOR, protocolStanding } from './protocol.ts'; /** * How a pack's clients ADDRESS it. The first three are HTTP API styles; `raw-tcp` is the * RAW-PROTOCOL class — a pack whose clients speak their protocol directly over a TCP socket * rather than through the HTTP/1 fetch machinery, so none of the HTTP machinery applies: no * `browserRouting`, and no entry in the injector's `VENDOR_HOSTS` host map is possible (the * injector patches http/fetch and never sees the traffic). Such a pack is wired into a world * through app-read host/port env instead, and this value is what tells a reader that "no injector * entry" is STRUCTURAL rather than a missing wiring point. `@volter/twin-smtp` (a line protocol) * is the first; `@volter/twin-temporal` (gRPC: HTTP/2 framing its clients drive themselves) the * second. * * Deliberately the transport CLASS, not the protocol name: naming the wire protocol would put a * vendor id in the kernel the moment a pack is named after its protocol, which is exactly what * A2, "the kernel does not branch on vendor identity" (`scripts/architecture-auto.ts`), forbids. The * specific protocol belongs on the pack's own `specSource`/`description`. */ export type PackTransport = 'rest' | 'graphql' | 'web-api' | 'raw-tcp'; /** * The pack's SERVE-FAMILY — the axis the invariant matrix keys strictness off, DECLARED * because it is the pack's own claim about what kind of thing it is (a heuristic over file * shapes would be the loose-scan disease). Orthogonal facts stay derived: transport is its * own field, screens are the manifest's, webhooks are the events module. * 'crud' — stateful resource CRUD behind the vendor's API (the default family; * includes ingestion→grouping packs — the ingest door is a trait). * 'generative' — model-shaped surface serving deterministic stubs/scenarios; "cannot * run the model" is the invariant, never a gap. * 'signed-protocol' — the wire is a signature/format protocol (SigV4 + XML/AWS-JSON …): * request authentication IS the fidelity surface. * 'engine-control' — a control plane driving a REAL execution engine behind an injected * seam (fly's runtime, github's git plane, supabase's external stack). * 'proxy' — the vendor itself is a forwarding plane (tunnel). */ export const PACK_ARCHETYPES = ['crud', 'generative', 'signed-protocol', 'engine-control', 'proxy'] as const; export type PackArchetype = (typeof PACK_ARCHETYPES)[number]; /** * How often this vendor's REAL API may be pulled — a property of the VENDOR's rate limits, so it * belongs to the pack that knows them, not to every world that might sync one (same argument as * `browserRouting`: vendor knowledge in the descriptor, kernel stays vendor-agnostic). * * - `'continuous'` — limits are generous and well-documented, so a scheduled/shadow world may sync * this vendor on a cadence (slack, github: thousands/hour, per-method tiers, clear headers). * - `'on-demand'` — limits are tight, opaque, cost-based, or punish bursts with long lockouts, so a * real pull happens ONLY when a human/agent explicitly asks for one. Never on a schedule, never * as a side effect of booting a world. Figma is the cautionary case: undocumented cost-based * limits; a burst of renders can exhaust an account's quota. * * DEFAULT IS `'on-demand'` when omitted — deliberately the safe direction. A pack that hasn't * thought about its limits must not be assumed schedulable; being wrong that way costs a slower * sync, while being wrong the other way costs a lockout. */ export type PullPosture = 'continuous' | 'on-demand'; /** The posture to assume for a pack that doesn't declare one. Conservative on purpose. */ export const DEFAULT_PULL_POSTURE: PullPosture = 'on-demand'; /** A pack's effective posture — its declaration, or the conservative default. */ export function pullPosture(pack: Pick): PullPosture { return pack.pullPosture ?? DEFAULT_PULL_POSTURE; } /** * What may name a vendor at a pull seam: the pack descriptor itself (the pack knows its own * posture — no registration needed) or a vendor id resolved through the registry. The id form is * the convenient one; it is also the one that FAILS CLOSED, because an id nothing registered * resolves to a posture-less descriptor, i.e. the conservative default. */ export type PullVendor = string | Pick; /** * Why a pull is happening — the distinction the posture rule actually turns on. * * - `'scheduled'` — a cadence, a poll loop, a shadow tick, or any pull that happens as a side * effect of something else (booting a world, a cron). Allowed for `'continuous'` vendors ONLY. * - `'explicit'` — a human/agent asked for THIS pull, now. Sanctioned for any vendor; it is the * only way an on-demand vendor is ever supposed to be pulled. * * Omitted ⇒ `'scheduled'`, matching the posture default: an unlabeled pull is treated as the * dangerous kind, so labeling is what unlocks the vendor, never silence. */ export type PullTrigger = 'scheduled' | 'explicit'; /** Resolve a `PullVendor` to the descriptor whose posture governs it. Unregistered ⇒ no posture. */ export function resolvePullVendor(vendor: PullVendor): Pick { if (typeof vendor !== 'string') return vendor; return getPack(vendor) ?? { vendor }; } /** * Guard a SCHEDULED/continuous sync. Throws for a vendor that may only be pulled on demand. * * This is the mechanical form of the rule — worlds differ in what they may pull: * • sealed (hermetic OA cycle worlds) pull NOTHING; they seed synthetic state over loopback and * an egress guard blocks the internet, so posture is irrelevant there; * • shadow/scheduled worlds sync real state on a cadence — `'continuous'` vendors ONLY; * • on-demand pulls are explicit, operator-invoked, and may target any vendor. * A scheduled world that quietly includes an on-demand vendor is how a lockout happens, so it * fails loudly here instead. */ export function assertContinuousPullAllowed(vendor: PullVendor): void { const pack = resolvePullVendor(vendor); if (pullPosture(pack) === 'continuous') return; const undeclared = pack.pullPosture === undefined; throw new Error( `pull posture: "${pack.vendor}" is on-demand — it must NOT be pulled on a schedule or as a side ` + `effect of booting a world. Its rate limits are tight/opaque enough that a burst risks a long ` + `lockout. Pull it explicitly when someone asks, through the pack's guarded connector; a sealed ` + `world should seed synthetic state locally instead. If this vendor's limits are genuinely ` + `generous, declare pullPosture:'continuous' on its TwinPack and say why.` + (undeclared ? ` (Nothing declared a posture for "${pack.vendor}" — either no pack is registered under ` + `that id (registerPack) or its TwinPack omits pullPosture. Silence is not permission: the ` + `conservative default applied. If this pull is a one-off someone asked for, say so at the ` + `call site — pass the explicit trigger instead of putting it on a cadence.)` : ''), ); } /** * The ONE sanctioned way to pull a vendor on a cadence. Asserts the posture BEFORE `pull` runs, so * a refused vendor makes ZERO vendor requests — the guard has to sit in front of the network call, * not behind it (guarding the fold, e.g. `syncPull`, would be theatre: the request already went out). * * Wrap any scheduler/cron/loop's pull in this and the rule enforces itself: * `await pullOnSchedule(pack, () => syncSlackFromReal(client, opts))` * An explicit, human-asked pull does NOT go through here — it calls the connector directly, which is * exactly the sanctioned path for an on-demand vendor. */ export async function pullOnSchedule(vendor: PullVendor, pull: () => Promise): Promise { assertContinuousPullAllowed(vendor); return pull(); } /** * One injector host rule — DATA the committed inject.cjs compiles, never a function. Exactly one * selector: `host` (exact), `suffix` (endsWith), or `hostPattern` (a RegExp SOURCE over the * hostname — regional families like `^s3[.-][a-z0-9-]+\.amazonaws\.com$`). `pathPattern` (a * RegExp source over the pathname) splits a host shared between packs. `key` names the routing * identity the rule belongs to — the `_TWIN_URL` env stem — when it is not the pack's own * vendor id (aws's one twin answers under s3 and secretsmanager); a key belongs to ONE pack. `exclude: true` carves a host out of * the key's includes (`.upstash.io` minus `*-vector.upstash.io`): a key matches when any include * matches and no exclude does. Validated by twin-standard's descriptor compiler: keys are `[a-z0-9-]+`, a * foreign key is never another pack's vendor id, belongs to one pack, and must appear in the * pack's `adoption.worldIds` (the world wires `_TWIN_URL` from there); no key is exclude-only; * `exclude` is `true` or absent. `basic` is a vendor fact for the executor: on * a URL the rule names, the host takes the sealed token as HTTP Basic's password under this user (a vendor's git over * HTTP whose API takes the same token as a bearer; ADR 0031). */ export type HostRule = ({ host: string } | { suffix: string } | { hostPattern: string }) & { pathPattern?: string; demandPathPattern?: string | false; key?: string; exclude?: true; basic?: string; }; export type RoundTripWrite = { method: string; path: string; body?: unknown; headers?: Record }; /** A pack's descriptor: docs/contributing/architecture.md, "The descriptor". */ export type TwinPack = { // Each field is defined once, in docs/contributing/architecture.md, "The descriptor"; a field is added there first. vendor: string; transport: PackTransport; archetype?: PackArchetype; protocol?: string; /** Files the serve path reads: a path in the pack's own tree, or `{ package, path }`, a file of an exactly pinned * devDependency the take places at `vendor//` (architecture, "A vendor's published package files"). */ assets?: Array; resourcesUnreachable?: Record; resources: string[]; bin?: string; specSource?: string; description?: string; browserRouting?: { apiPathPrefix: string; loaderHost?: string }; pullPosture?: PullPosture; pullPostureReason?: string; rateBudget?: RateBudgetDeclaration; serveExport?: string; /** Declared HTTP transport cap, in bytes; the serve seam and World fronts honor it. */ maxRequestBodySize?: number; adoption?: { sdks?: string[]; pypi?: string[]; scopes?: string[]; envStems?: string[]; configFiles?: Array<{ file: string; usage: 'application' | 'build' | 'deployment'; when?: string }>; /** import specifiers of modules that reach the vendor by themselves (`next/font/google`): an application that imports * one reaches the vendor without its SDK (architecture, "Selection") */ modules?: string[]; worldIds?: string[]; tools?: Array<{ package: string; usage: 'build' | 'deployment' }>; }; /** Why no client case is owed though `adoption.sdks` names npm clients: the vendor maintains no official SDK, or the * demand's applications use none (architecture, "The descriptor"; `conform`'s client check reads it). */ clientCasesNone?: string; hosts?: HostRule[]; hostsNone?: string; hostsClaimed?: { door: string; note: string }; endpointEnv?: { name: string; templates?: Record; note: string }; endpointEnvNone?: string; /** The door that issues the application the credentials the twin will accept (a key made on the vendor's dashboard, * and whatever names it: a database's URL, a project's id), and the env names it fills, each from a field of the * answer: `init` writes `$issue:` for each, and `up`, once this twin is running, POSTs the body to the door * and sets each name to its field (`file:` materializes one file; `directory:` a relative-file map). A twin that holds its keys (refusing any it * did not issue) declares one, so a World's applications hold keys it issued rather than fixtures it refuses. */ credentialDoor?: { path: string; body: Record; fill: Record; account?: { field: string } & ({ tenancy?: never; source?: never } | { tenancy: string; source: string }); deployment?: { field: string; object: string; source: string; organizationOutputs?: string[] }; }; /** Another pack of this vendor issues the API's credentials; architecture, descriptor World wiring. */ credentialIssuer?: string; prismaAdapter?: { adapter: string; export: string; urlEnv: string }; managedService?: { kind: string; scheme: string; note: string; configurationArg?: '--configuration'; originalInputs?: { version: 1; manifestArg: '--original-inputs'; rootArg: '--original-root'; digestArg: '--original-inputs-sha256'; paths: string[] } }; managedDatabase?: { kind: 'postgres'; arg: string; user: string; database: string; clock: 'wall'; credentialField: string; note: string }; sidePorts?: Array<{ name: string; option: string; flag: string; path?: string; scheme?: string; note: string }>; /** The vendor's own requests a World's generated seed makes for what its world.json declares (ADR 0033 §3), each a URL * at the vendor's own host, defined by the twin's own screen form for that act: its sign-up, and its domain screen's * add and verify with `record`, the one `/_twin/` stand-in, for a record at the domain's DNS host; `settles` is the * World-clock time the vendor takes to settle a verified domain (`10m`). */ seed?: { signUp?: string; domain?: { add: string; record: string; verify: string; settles: string } }; stateSystem?: StateSystemAdapters; /** The pack has no vendor-backed half, and why (copied from the manifest by packOf). */ vendorBacked?: { none: string }; refresh?: { every?: string; webhook?: boolean; onDemand?: { atMost: string } }; roundTrip?: RoundTripWrite | RoundTripWrite[]; references?: ReferenceDeclaration[]; referenceTrip?: RoundTripWrite; parityOrigin?: string; shapeParity?: 'held'; refreshRefusal?: { refusal: string; reason: string }; auth?: TwinAuthStrategy; engine?: { module: string; note?: string }; }; /** The descriptor a pack declares as data in its manifest (docs/contributing/architecture.md, "The descriptor"): the * pack's fields without the ones that are code or that the derived core supplies (the state system and refresh, round * trips and references, parity, a rate budget, the emitter, conformance fields, the engine key, pull posture). */ export type PackDescriptor = Omit; const registry = new Map(); /** Register (or replace) a pack descriptor. Returns it. * * Side effect, deliberately: a `rateBudget` declaration on the descriptor is ARMED here, so * registering a pack is enough to give its vendor the ceiling it declared. `declareRateBudget` * is idempotent for an identical declaration and REFUSES a widening one, so re-registering is * safe and "register a fatter pack descriptor to buy a bigger budget" is not a move. */ /** A derived pack's descriptor, from its manifest (`manifest.descriptor`, named by the manifest's `vendor`). Given the * pack's generated surface (a vendor of lanes: each lane's manifest and surface), the kernel derives what a pack never * writes by hand (the real-system adapters, "Where it lives"): its state system (perform, refresh, ingest), the * references its subjects hold (from the manifest's `embeds` and each `parent.field` naming its parent by id) and its * rate budget (the manifest's). A descriptor that declares any of them by hand is refused. */ export function packOf( manifest: { vendor: string; descriptor?: Omit } & Partial>, surface?: DerivedSurface | Record, /** the lanes beside a pack that has an API of its own */ beside: Record = {}, ): TwinPack { if (!manifest.descriptor) throw new Error(`${manifest.vendor}: the manifest declares no descriptor (architecture, "The descriptor")`); const hand = (['stateSystem', 'references', 'rateBudget'] as const).filter((k) => (manifest.descriptor as Record)[k] !== undefined); if (hand.length) throw new Error(`${manifest.vendor}: the descriptor declares ${hand.join(', ')} by hand; the kernel derives them from the manifest (architecture, "The real-system adapters")`); const pack: TwinPack = { vendor: manifest.vendor, ...manifest.descriptor, ...(manifest.rateBudget ? { rateBudget: manifest.rateBudget } : {}) }; // a pack with no vendor-backed half says why, and derives no adapters; one whose own surface has none beside lanes // that do derives its lanes' adapters, its own writes settled as the World's (`unsent`) const live = Object.fromEntries(Object.entries(beside).filter(([, l]) => !l.manifest.vendorBacked?.none)); if (manifest.vendorBacked?.none && !Object.keys(live).length) return { ...pack, vendorBacked: { none: manifest.vendorBacked.none } }; if (!surface) return pack; // the unit's own surface: its operations, or a command table (a vendor that carries Redis over HTTP: architecture, // "Other wires"), which names no operation a derived adapter performs; anything else is a map of lanes const ownSurface = 'operations' in surface || 'commands' in surface; if (manifest.vendorBacked?.none && ownSurface) { const own = new Set(((surface as DerivedSurface).operations ?? []).map((o) => o.id)); // a command table's every write is the unit's own (no operation of it is performed) const commandTable = !('operations' in surface); const why = manifest.vendorBacked.none; const references = [manifest as unknown as DerivedManifest, ...Object.values(beside).map((l) => l.manifest)].flatMap(derivedReferences); return { ...pack, stateSystem: { ...deriveVendorStateSystem(manifest as unknown as VendorManifest, live), unsent: (input) => (input && typeof input.lane !== 'string' && (commandTable || own.has(String(input.operationId))) ? why : undefined) }, ...(references.length ? { references } : {}), }; } const lanes = ownSurface ? undefined : (surface as Record); const units = lanes ? Object.values(lanes).map((l) => l.manifest) : [manifest as unknown as DerivedManifest, ...Object.values(beside).map((l) => l.manifest)]; const references = units.flatMap(derivedReferences); return { ...pack, stateSystem: lanes ? deriveVendorStateSystem(manifest as unknown as VendorManifest, lanes) : deriveStateSystem(manifest as unknown as DerivedManifest, surface as DerivedSurface, beside), ...(references.length ? { references } : {}), }; } /** The references a derived manifest's subjects hold: each `embeds` field naming another resource, and each child's * `parent.field` when it holds the parent's id (a `value` template joins several parameters, so it holds no one id). */ function derivedReferences(m: DerivedManifest): ReferenceDeclaration[] { const stored = (r: string): string => m.resources[r]?.storedAs ?? r; const out: ReferenceDeclaration[] = []; for (const [resource, decl] of Object.entries(m.resources)) { for (const [field, to] of Object.entries(decl.embeds ?? {})) if (m.resources[to]) out.push(referenceField(stored(resource), field, stored(to))); if (decl.parent && !decl.parent.value && !decl.parent.where && m.resources[decl.parent.resource]) out.push(referenceField(stored(resource), decl.parent.field, stored(decl.parent.resource))); } return out; } export function registerPack(pack: TwinPack): TwinPack { if (!/^[a-z0-9-]+$/.test(pack.vendor)) throw new Error(`invalid pack vendor id: ${pack.vendor}`); if (protocolStanding(pack.protocol).standing !== 'current') throw new Error(`${pack.vendor}: protocol ${pack.protocol ?? '(missing)'} refused; this kernel serves ${PROTOCOL_VERSION}`); if (pack.rateBudget) declareRateBudget(pack.vendor, pack.rateBudget); if (pack.stateSystem) registerStateSystem(pack.vendor, pack.stateSystem); if (pack.auth) registerAuthStrategy(pack.vendor, pack.auth); if (pack.references) registerReferences(pack.vendor, pack.references); registry.set(pack.vendor, pack); return pack; } export function getPack(vendor: string): TwinPack | undefined { return registry.get(vendor); } /** All registered packs, sorted by vendor (deterministic). */ export function listPacks(): TwinPack[] { return [...registry.values()].sort((a, b) => a.vendor.localeCompare(b.vendor)); } /** Clear the registry (tests). */ export function clearRegistry(): void { registry.clear(); }