@powerhousedao/host-core 6.2.3-dev.70 → 6.2.3-dev.72

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/compound-B6RZMA0Y.mjs +2804 -0
  2. package/dist/compound-B6RZMA0Y.mjs.map +1 -0
  3. package/dist/compound-PhoVeqe1.d.mts +2401 -0
  4. package/dist/compound-PhoVeqe1.d.mts.map +1 -0
  5. package/dist/env-substitution-C_fVirPh.d.mts +17 -0
  6. package/dist/env-substitution-C_fVirPh.d.mts.map +1 -0
  7. package/dist/env-substitution-Dj3pdsut.mjs +330 -0
  8. package/dist/env-substitution-Dj3pdsut.mjs.map +1 -0
  9. package/dist/host-schemas-mqOYNGot.d.mts +2153 -0
  10. package/dist/host-schemas-mqOYNGot.d.mts.map +1 -0
  11. package/dist/index.d.mts +908 -691
  12. package/dist/index.d.mts.map +1 -1
  13. package/dist/index.mjs +335 -109
  14. package/dist/index.mjs.map +1 -1
  15. package/dist/plugins-XL6WsvTL.d.mts +182 -0
  16. package/dist/plugins-XL6WsvTL.d.mts.map +1 -0
  17. package/dist/plugins.d.mts +2 -120
  18. package/dist/plugins.mjs.map +1 -1
  19. package/dist/projection.d.mts +586 -0
  20. package/dist/projection.d.mts.map +1 -0
  21. package/dist/projection.mjs +1505 -0
  22. package/dist/projection.mjs.map +1 -0
  23. package/dist/runners/compound.d.mts +157 -12
  24. package/dist/runners/compound.d.mts.map +1 -1
  25. package/dist/runners/compound.mjs +5 -13
  26. package/dist/runners/compound.mjs.map +1 -1
  27. package/dist/schema.d.mts +105 -0
  28. package/dist/schema.d.mts.map +1 -0
  29. package/dist/schema.mjs +35 -0
  30. package/dist/schema.mjs.map +1 -0
  31. package/package.json +16 -4
  32. package/dist/compound-C8P0kvPJ.d.mts +0 -157
  33. package/dist/compound-C8P0kvPJ.d.mts.map +0 -1
  34. package/dist/host-schemas-CtPNRr5v.mjs +0 -720
  35. package/dist/host-schemas-CtPNRr5v.mjs.map +0 -1
  36. package/dist/plugins.d.mts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["factory"],"sources":["../src/backend-projection.ts","../src/reactor-config.ts","../src/plugins-resolve.ts"],"sourcesContent":["import type {\n ReactorBackend,\n ReactorConfig,\n ReactorProtocol,\n} from \"./reactor-config.js\";\n\n/**\n * Phase 4 (track R): project named host backends onto reactor-monitor's\n * `ReactorDescriptor` shape — the input `provision()` takes. Pure and\n * dependency-free; a type-assignability test pins the output to the real\n * `ReactorDescriptor` so an upstream field rename fails this package's tests\n * instead of silently drifting (D2.b: aligned locally, upstreaming not\n * blocked on).\n */\n\n/** The browser-provisionable storage union — reactor-monitor's\n * `ReactorStorageConfig` shape. `postgres` is the SERVER extension (D2.b): a\n * switchboard backend's storage, never a provisioned browser reactor's. */\nexport type ProjectedStorage =\n | { kind: \"idb\" }\n | { kind: \"memory\" }\n | { kind: \"path\"; dataDir: string };\n\nexport interface ProjectedDescriptor {\n kind: \"in-process\" | \"worker\" | \"remote\";\n name: string;\n storage?: ProjectedStorage;\n packages?: { cdnUrl?: string; specs?: string[]; dynamic?: boolean };\n featureFlags?: {\n documentDecisions?: boolean;\n authEnforcement?: boolean;\n authGroups?: boolean;\n authConditions?: boolean;\n };\n remote?: { url: string };\n}\n\nfunction projectStorage(\n name: string,\n storage: NonNullable<ReactorBackend[\"storage\"]>,\n): ProjectedStorage {\n switch (storage.kind) {\n case \"idb\":\n return { kind: \"idb\" };\n case \"memory\":\n return { kind: \"memory\" };\n case \"path\": {\n if (!storage.dataDir) {\n throw new Error(\n `Backend \"${name}\": storage kind \"path\" requires dataDir.`,\n );\n }\n return { kind: \"path\", dataDir: storage.dataDir };\n }\n case \"postgres\":\n throw new Error(\n `Backend \"${name}\": storage kind \"postgres\" is server-side only — ` +\n `a provisioned (in-process/worker) reactor cannot use it. Point a ` +\n `\"remote\" backend at the switchboard that owns that database instead.`,\n );\n }\n}\n\n/** One backend → one descriptor. The protocol's featureFlags ride every\n * descriptor (they are fleet consensus, not per-backend). A remote backend\n * must carry remote.url — provision() requires it. */\nexport function backendToDescriptor(\n name: string,\n backend: ReactorBackend,\n protocol?: ReactorProtocol,\n): ProjectedDescriptor {\n const descriptor: ProjectedDescriptor = {\n kind: backend.kind ?? \"in-process\",\n name,\n };\n if (descriptor.kind === \"remote\") {\n const url = backend.remote?.url;\n if (!url) {\n throw new Error(\n `Backend \"${name}\" is kind \"remote\" but has no remote.url — ` +\n `a remote descriptor attaches to an already-running reactor by URL.`,\n );\n }\n descriptor.remote = { url };\n // remote attaches; it builds nothing, so local-build fields do not apply\n return descriptor;\n }\n if (backend.storage) {\n descriptor.storage = projectStorage(name, backend.storage);\n }\n if (backend.packages) descriptor.packages = backend.packages;\n if (protocol?.featureFlags) descriptor.featureFlags = protocol.featureFlags;\n return descriptor;\n}\n\n/** All named backends, in placement-primary-first order (the order a\n * createReactorClients step would provision them). */\nexport function backendsToDescriptors(\n reactor: ReactorConfig | undefined,\n): ProjectedDescriptor[] {\n const backends = reactor?.backends;\n if (!backends) return [];\n const names = Object.keys(backends);\n const primary = reactor.placement?.primary;\n const ordered =\n primary && names.includes(primary)\n ? [primary, ...names.filter((n) => n !== primary)]\n : names;\n return ordered.map((name) =>\n backendToDescriptor(name, backends[name], reactor.protocol),\n );\n}\n\nconst LOCAL_KINDS = new Set([\"in-process\", \"worker\", undefined]);\n\n/**\n * Structural multi-reactor (phase 4): true when the block names BOTH a local\n * backend (in-process/worker — the tab's own reactor) and a remote one. This\n * is the shape Connect's routing client serves; a lone remote backend is an\n * attach-only host (assistant/agent shape), not a routed tab.\n */\nexport function isStructuralMultiReactor(\n reactor: ReactorConfig | undefined,\n): boolean {\n const backends = reactor?.backends;\n if (!backends) return false;\n const kinds = Object.values(backends).map((b) => b.kind);\n return (\n kinds.some((k) => LOCAL_KINDS.has(k)) && kinds.some((k) => k === \"remote\")\n );\n}\n\n/** The remote backends' urls, placement order — what the routing client dials. */\nexport function remoteBackendUrls(\n reactor: ReactorConfig | undefined,\n): string[] {\n return backendsToDescriptors(reactor)\n .filter((d) => d.kind === \"remote\")\n .map((d) => d.remote?.url)\n .filter((u): u is string => typeof u === \"string\");\n}\n","/**\n * The shared `reactor` host-config block and its projections onto today's\n * Switchboard env / Connect runtime config. Phase 2 of uniform-runners: makes\n * the reactor block live through the bridge runners, BEFORE track R replaces\n * the projection with reactor-monitor's provision(). The headline is\n * single-sourced `reactor.protocol` — both projections read the same block, so\n * client and server cannot diverge, and a contradicting pre-set env fails boot.\n */\n\nexport type ReactorBackendKind = \"in-process\" | \"worker\" | \"remote\";\n\nexport interface ReactorStorageConfig {\n kind: \"idb\" | \"memory\" | \"path\" | \"postgres\";\n dataDir?: string;\n url?: string;\n}\n\nexport interface ReactorPackageConfig {\n cdnUrl?: string;\n specs?: string[];\n /** on-demand model resolution (was DYNAMIC_MODEL_LOADING). */\n dynamic?: boolean;\n}\n\nexport interface ReactorRemoteConfig {\n host?: string;\n url?: string;\n}\n\nexport interface ReactorBackend {\n kind?: ReactorBackendKind;\n storage?: ReactorStorageConfig;\n readModel?: { url?: string };\n packages?: ReactorPackageConfig;\n remote?: ReactorRemoteConfig;\n}\n\n/** Replay/admission rules every sync peer must share. */\nexport interface ReactorProtocol {\n featureFlags?: {\n documentDecisions?: boolean;\n authEnforcement?: boolean;\n authGroups?: boolean;\n authConditions?: boolean;\n };\n createSignaturePolicy?: \"legacy\" | \"v2-required\";\n unsupportedStoredDocuments?: \"refuse\" | \"read-only\";\n}\n\nexport interface ReactorConfig {\n backends?: Record<string, ReactorBackend>;\n placement?: {\n primary?: string;\n default?: Record<string, unknown>;\n };\n workflows?: boolean;\n protocol?: ReactorProtocol;\n}\n\n/** The single primary backend for phase-2 projection (multi-backend routing is\n * track R). Prefers placement.primary, else \"main\"/\"local\", else the first. */\nexport function primaryBackend(\n reactor: ReactorConfig | undefined,\n): ReactorBackend | undefined {\n const backends = reactor?.backends;\n if (!backends) return undefined;\n const names = Object.keys(backends);\n if (names.length === 0) return undefined;\n const pick =\n reactor.placement?.primary ??\n (names.includes(\"main\")\n ? \"main\"\n : names.includes(\"local\")\n ? \"local\"\n : names[0]);\n return backends[pick];\n}\n\nconst FLAG_ENV: Record<\n keyof NonNullable<ReactorProtocol[\"featureFlags\"]>,\n string\n> = {\n documentDecisions: \"REACTOR_DOCUMENT_DECISIONS\",\n authEnforcement: \"REACTOR_AUTH_ENFORCEMENT\",\n authGroups: \"REACTOR_AUTH_GROUPS\",\n authConditions: \"REACTOR_AUTH_CONDITIONS\",\n};\n\n/** The env vars a protocol block maps onto, with their string values. Only\n * keys the block actually sets appear. */\nexport function protocolEnv(\n protocol: ReactorProtocol | undefined,\n): Record<string, string> {\n const env: Record<string, string> = {};\n if (!protocol) return env;\n for (const [key, varName] of Object.entries(FLAG_ENV)) {\n const value = protocol.featureFlags?.[key as keyof typeof FLAG_ENV];\n if (value !== undefined) env[varName] = value ? \"true\" : \"false\";\n }\n if (protocol.createSignaturePolicy !== undefined) {\n env.CREATE_SIGNATURE_POLICY = protocol.createSignaturePolicy;\n }\n if (protocol.unsupportedStoredDocuments !== undefined) {\n env.REACTOR_UNSUPPORTED_STORED_DOCUMENTS =\n protocol.unsupportedStoredDocuments;\n }\n return env;\n}\n\nexport interface SwitchboardReactorProjection {\n /** Env the switchboard server reads at boot. Only keys the block sets. */\n env: Record<string, string>;\n /** Options passed to startSwitchboard (DB path). */\n options: { dbPath?: string };\n}\n\n/** Project the reactor block onto the switchboard's env + options. */\nexport function projectReactorToSwitchboard(\n reactor: ReactorConfig | undefined,\n): SwitchboardReactorProjection {\n const env = protocolEnv(reactor?.protocol);\n const backend = primaryBackend(reactor);\n const options: { dbPath?: string } = {};\n\n if (backend?.storage) {\n const s = backend.storage;\n const dbUrl = s.kind === \"postgres\" ? s.url : s.dataDir;\n if (dbUrl) env.PH_REACTOR_DATABASE_URL = dbUrl;\n }\n if (backend?.readModel?.url) options.dbPath = backend.readModel.url;\n if (backend?.packages?.dynamic) env.DYNAMIC_MODEL_LOADING = \"true\";\n if (reactor?.workflows !== undefined) {\n env.PH_WORKFLOWS_ENABLED = reactor.workflows ? \"1\" : \"0\";\n }\n return { env, options };\n}\n\n/** The four reactor-client shapes a Connect host can select (mirrors the\n * shared PHReactorClientMode; kept local to avoid an import cycle). */\nexport type ReactorClientMode = \"in-process\" | \"worker\" | \"remote\" | \"router\";\n\nconst LOCAL_BACKEND_KINDS = new Set<ReactorBackendKind | undefined>([\n \"in-process\",\n \"worker\",\n undefined,\n]);\n\n/**\n * Which reactor client the backend topology asks for:\n * - local (in-process/worker) AND remote backends -> `router`\n * - remote backend(s) only -> `remote`\n * - a worker backend -> `worker`\n * - anything else local -> `in-process`\n * `undefined` when no backends are declared — the caller then keeps the\n * legacy reactorWorker/multiReactor behaviour untouched.\n */\nexport function reactorClientMode(\n reactor: ReactorConfig | undefined,\n): ReactorClientMode | undefined {\n const backends = reactor?.backends;\n if (!backends) return undefined;\n const kinds = Object.values(backends).map((b) => b.kind);\n if (kinds.length === 0) return undefined;\n const hasLocal = kinds.some((k) => LOCAL_BACKEND_KINDS.has(k));\n const hasRemote = kinds.some((k) => k === \"remote\");\n if (hasLocal && hasRemote) return \"router\";\n if (hasRemote) return \"remote\";\n return primaryBackend(reactor)?.kind === \"worker\" ? \"worker\" : \"in-process\";\n}\n\nexport interface ConnectReactorProjection {\n /** Patch merged into the connect runtime config (connect.*). */\n connect: {\n reactor?: ReactorProtocol;\n instance?: { reactorWorker?: boolean; reactorClient?: ReactorClientMode };\n app?: { workflowsEnabled?: boolean };\n };\n}\n\n/** Project the reactor block onto the Connect runtime config: protocol →\n * connect.reactor (same shape), backend topology → instance.reactorWorker\n * (legacy) + instance.reactorClient (the explicit 4-way selector),\n * workflows → app.workflowsEnabled. */\nexport function projectReactorToConnect(\n reactor: ReactorConfig | undefined,\n): ConnectReactorProjection {\n const connect: ConnectReactorProjection[\"connect\"] = {};\n if (reactor?.protocol) connect.reactor = reactor.protocol;\n const backend = primaryBackend(reactor);\n const mode = reactorClientMode(reactor);\n if (backend?.kind !== undefined || mode !== undefined) {\n connect.instance = {\n ...(backend?.kind !== undefined\n ? { reactorWorker: backend.kind === \"worker\" }\n : {}),\n ...(mode !== undefined ? { reactorClient: mode } : {}),\n };\n }\n if (reactor?.workflows !== undefined) {\n connect.app = { workflowsEnabled: reactor.workflows };\n }\n return { connect };\n}\n\n/**\n * The enforcement teeth of single-sourcing: if a pre-set env var CONTRADICTS\n * the host's protocol block, fail loudly naming the var, the host value, and\n * the env value. An env var that merely matches, or is unset, is fine (phase-2\n * transition keeps an operator's explicit env as an escape hatch unless it\n * disagrees with the protocol — see the WBS precedence note).\n */\nexport function assertProtocolConsistency(\n protocol: ReactorProtocol | undefined,\n env: Record<string, string | undefined>,\n hostFile = \"the host file\",\n): void {\n if (!protocol) return;\n const expected = protocolEnv(protocol);\n for (const [varName, hostValue] of Object.entries(expected)) {\n const envValue = env[varName];\n if (envValue !== undefined && envValue !== hostValue) {\n throw new Error(\n `reactor.protocol conflict: ${varName} is \"${envValue}\" in the environment ` +\n `but \"${hostValue}\" in ${hostFile}. These are fleet-consensus settings — ` +\n `a mismatch would diverge replay. Remove the env override or align the host.`,\n );\n }\n }\n}\n","import { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { z } from \"zod\";\nimport {\n entryActiveForVerb,\n hostTypeSatisfies,\n normalizePluginEntries,\n PluginError,\n type HostPlugin,\n type PluginEntry,\n type ResolvedPlugin,\n} from \"./plugins.js\";\n\n/**\n * NODE-ONLY plugin resolution (split from plugins.ts so the pure runner core\n * stays browser-safe for ConnectCore — R3). Resolves host.js entries from the\n * PROJECT dependency tree, exactly like runner modules.\n */\n\nfunction isHostPluginShape(value: unknown): value is HostPlugin {\n return (\n value !== null &&\n typeof value === \"object\" &&\n typeof (value as HostPlugin).name === \"string\"\n );\n}\n\n/**\n * Resolve host.js plugin entries into live plugins for one host boot:\n * verb-filter → module resolution from the project tree (default condition,\n * like runners) → factory/object contract → config validation → appliesTo.\n */\nexport async function resolveHostPlugins<THooks = Record<string, unknown>>(\n projectRoot: string,\n hostType: string,\n verb: string,\n entries: readonly PluginEntry[],\n where: string,\n): Promise<ResolvedPlugin<THooks>[]> {\n const normalized = normalizePluginEntries(entries, where);\n const projectRequire = createRequire(\n pathToFileURL(path.join(projectRoot, \"package.json\")).href,\n );\n\n const resolved: ResolvedPlugin<THooks>[] = [];\n for (const entry of normalized) {\n if (!entryActiveForVerb(entry, verb)) continue;\n\n let file: string;\n try {\n file = projectRequire.resolve(entry.module);\n } catch {\n throw new PluginError(\n `${where}: cannot resolve plugin \"${entry.module}\" from ${projectRoot}.`,\n \"Plugins resolve from the project dependency tree, exactly like runner modules.\",\n );\n }\n const module = (await import(pathToFileURL(file).href)) as {\n default?: unknown;\n };\n const exported = module.default;\n\n let plugin: HostPlugin<THooks>;\n if (typeof exported === \"function\") {\n const factory = exported as (config: unknown) => HostPlugin<THooks>;\n plugin = factory(entry.config);\n } else if (isHostPluginShape(exported)) {\n if (Object.keys(entry.config).length > 0 && !exported.configSchema) {\n throw new PluginError(\n `${where}: plugin \"${entry.module}\" takes no config, but the entry passes one.`,\n );\n }\n plugin = exported as HostPlugin<THooks>;\n } else {\n throw new PluginError(\n `${where}: \"${entry.module}\" does not default-export a plugin object or factory.`,\n \"Export `{ name, hooks?, contributions? }` or `(config) => plugin`.\",\n );\n }\n\n if (plugin.configSchema) {\n const parsed = plugin.configSchema.safeParse(entry.config);\n if (!parsed.success) {\n throw new PluginError(\n `${where}: config for plugin \"${plugin.name}\" is invalid:\\n` +\n z.prettifyError(parsed.error),\n );\n }\n }\n\n const appliesTo = plugin.appliesTo ?? \"reactor\";\n if (!hostTypeSatisfies(hostType, appliesTo)) {\n throw new PluginError(\n `${where}: plugin \"${plugin.name}\" applies to \"${appliesTo}\" hosts, but this host is \"${hostType}\".`,\n );\n }\n\n resolved.push({ entry, plugin, provenance: \"dependency\" });\n }\n return resolved;\n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C,SAAS,KAAK,CAAC,SAAS,cACpD,MAAM,IAAI,YACR,GAAG,MAAM,YAAY,MAAM,OAAO,6CACpC;GAEF,SAAS;EACX,OACE,MAAM,IAAI,YACR,GAAG,MAAM,KAAK,MAAM,OAAO,wDAC3B,oEACF;EAGF,IAAI,OAAO,cAAc;GACvB,MAAM,SAAS,OAAO,aAAa,UAAU,MAAM,MAAM;GACzD,IAAI,CAAC,OAAO,SACV,MAAM,IAAI,YACR,GAAG,MAAM,uBAAuB,OAAO,KAAK,mBAC1C,EAAE,cAAc,OAAO,KAAK,CAChC;EAEJ;EAEA,MAAM,YAAY,OAAO,aAAa;EACtC,IAAI,CAAC,kBAAkB,UAAU,SAAS,GACxC,MAAM,IAAI,YACR,GAAG,MAAM,YAAY,OAAO,KAAK,gBAAgB,UAAU,6BAA6B,SAAS,GACnG;EAGF,SAAS,KAAK;GAAE;GAAO;GAAQ,YAAY;EAAa,CAAC;CAC3D;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/drives.ts","../src/reactor-config.ts","../src/backend-projection.ts","../src/connect-projection.ts","../src/expect-host.ts"],"sourcesContent":["import crypto from \"node:crypto\";\nimport {\n DRIVE_ICON_MAX_BYTES,\n resolveImageRef,\n} from \"@powerhousedao/shared/connect/image-ref\";\nimport { projectDriveIdWith, type DriveDeclaration } from \"./drive-schema.js\";\n\n/**\n * R1 — core drive declarations. A reactor without drives is not a running\n * reactor, so declaring + seeding them is HOST RUNTIME work (not a plugin):\n * onReactorReady → idempotent slug-keyed seeding → onDrivesReady. Plugins\n * CONTRIBUTE declarations into the same merged list (Contributions.drives);\n * `--explain drives` prints the merged set with provenance.\n *\n * The declaration schema lives in drive-schema.ts (platform-neutral); this\n * module is the node half: resolution (image refs read files), seeding and\n * the node:crypto-bound project drive id.\n */\n\nexport {\n driveDeclarationSchema,\n drivesSchema,\n type DriveDeclaration,\n} from \"./drive-schema.js\";\n\nconst sha256Hex = (input: string): string =>\n crypto.createHash(\"sha256\").update(input).digest(\"hex\");\n\nexport function projectDriveId(projectRoot: string, slug: string): string {\n return projectDriveIdWith(sha256Hex, projectRoot, slug);\n}\n\nexport interface ResolvedDrive {\n kind: \"local\" | \"remote\";\n id: string;\n slug: string;\n name: string;\n icon?: string;\n preferredEditor?: string;\n sharingType: \"public\" | \"private\" | \"shared\";\n availableOffline: boolean;\n remoteUrl?: string;\n}\n\nexport function resolveDriveDeclaration(\n projectRoot: string,\n decl: DriveDeclaration,\n): ResolvedDrive {\n const id = decl.projectHash\n ? projectDriveId(projectRoot, decl.slug)\n : (decl.id ?? decl.slug);\n // Hash-derived drives serve under the hashed slug too (classic parity:\n // the vetra drive's slug IS its hashed id) — unless only the id is hashed.\n const slug = decl.projectHash === true ? id : decl.slug;\n if (decl.remote) {\n return {\n kind: \"remote\",\n id,\n slug,\n name: decl.name ?? decl.slug,\n remoteUrl: decl.remote.url,\n sharingType: decl.sharingType ?? \"public\",\n availableOffline: decl.availableOffline ?? true,\n };\n }\n return {\n kind: \"local\",\n id,\n slug,\n name: decl.name ?? decl.slug,\n // A project path becomes a data URI here (the icon lives in synced drive\n // state, so it is size-capped); URLs and data URIs pass through.\n icon: resolveImageRef(projectRoot, decl.icon, {\n maxBytes: DRIVE_ICON_MAX_BYTES,\n warn: (m) => console.warn(m),\n }),\n preferredEditor: decl.preferredEditor,\n sharingType: decl.sharingType ?? \"public\",\n availableOffline: decl.availableOffline ?? true,\n };\n}\n\n/* ------------------------------------------------------------------ seeding */\n\n/** The minimal client surface the seeder needs — runners adapt their reactor\n * clients (IReactorClient, addDefaultDrive-style helpers) onto it. */\nexport interface DriveSeederClient {\n /** Return the existing drive's id for a slug, or undefined. */\n findDriveBySlug(slug: string): Promise<string | undefined>;\n /** Create a local drive; preferredEditor lands on header.meta. */\n createDrive(drive: ResolvedDrive): Promise<void>;\n /** Attach a remote drive by URL (idempotent on the client side). */\n attachRemoteDrive(url: string): Promise<void>;\n}\n\nexport interface SeedResult {\n created: string[];\n existing: string[];\n attached: string[];\n}\n\n/** Idempotent, slug-keyed: an existing slug is left untouched (never\n * recreated, never mutated — preserveStrategy refinements live here later). */\nexport async function seedDrives(\n client: DriveSeederClient,\n drives: readonly ResolvedDrive[],\n): Promise<SeedResult> {\n const result: SeedResult = { created: [], existing: [], attached: [] };\n for (const drive of drives) {\n if (drive.kind === \"remote\") {\n await client.attachRemoteDrive(drive.remoteUrl!);\n result.attached.push(drive.slug);\n continue;\n }\n const existing = await client.findDriveBySlug(drive.slug);\n if (existing !== undefined) {\n result.existing.push(drive.slug);\n continue;\n }\n await client.createDrive(drive);\n result.created.push(drive.slug);\n }\n return result;\n}\n\n/* ------------------------------------------------------------------ explain */\n\nexport interface DrivePlanEntry {\n drive: ResolvedDrive;\n /** \"host\" for host.js declarations; a plugin name for contributions. */\n source: string;\n}\n\n/** Merge host-declared drives with plugin contributions, slug-keyed — the\n * host file wins on conflicts (it is the most explicit source). */\nexport function mergeDrivePlan(\n projectRoot: string,\n hostDeclared: readonly DriveDeclaration[],\n contributed: readonly { declaration: DriveDeclaration; source: string }[],\n): DrivePlanEntry[] {\n const plan = new Map<string, DrivePlanEntry>();\n for (const { declaration, source } of contributed) {\n const drive = resolveDriveDeclaration(projectRoot, declaration);\n plan.set(drive.slug, { drive, source });\n }\n for (const declaration of hostDeclared) {\n const drive = resolveDriveDeclaration(projectRoot, declaration);\n plan.set(drive.slug, { drive, source: \"host\" });\n }\n return [...plan.values()];\n}\n\nexport function explainDrivePlan(plan: readonly DrivePlanEntry[]): string {\n if (plan.length === 0) return \"(no drives declared)\";\n const lines = plan.map(({ drive, source }) => {\n const kind =\n drive.kind === \"remote\" ? `remote ${drive.remoteUrl}` : \"local\";\n const editor = drive.preferredEditor\n ? ` editor=${drive.preferredEditor}`\n : \"\";\n return ` ${drive.slug} (${kind}, id=${drive.id}${editor}) [${source}]`;\n });\n return [\"drives:\", ...lines].join(\"\\n\");\n}\n","/**\n * The shared `reactor` host-config block and its projections onto today's\n * Switchboard env / Connect runtime config. Phase 2 of uniform-runners: makes\n * the reactor block live through the bridge runners, BEFORE track R replaces\n * the projection with reactor-monitor's provision(). The headline is\n * single-sourced `reactor.protocol` — both projections read the same block, so\n * client and server cannot diverge, and a contradicting pre-set env fails boot.\n */\n\nimport type {\n ReactorBackend,\n ReactorBackendKind,\n ReactorConfig,\n ReactorProtocol,\n} from \"./host-schemas.js\";\n\nexport type {\n ReactorBackend,\n ReactorBackendKind,\n ReactorConfig,\n ReactorPackageConfig,\n ReactorProtocol,\n ReactorRemoteConfig,\n ReactorStorageConfig,\n} from \"./host-schemas.js\";\n\n/** The single primary backend for phase-2 projection (multi-backend routing is\n * track R). Prefers placement.primary, else \"main\"/\"local\", else the first. */\nexport function primaryBackend(\n reactor: ReactorConfig | undefined,\n): ReactorBackend | undefined {\n const backends = reactor?.backends;\n if (!backends) return undefined;\n const names = Object.keys(backends);\n if (names.length === 0) return undefined;\n const pick =\n reactor.placement?.primary ??\n (names.includes(\"main\")\n ? \"main\"\n : names.includes(\"local\")\n ? \"local\"\n : names[0]);\n return backends[pick];\n}\n\nconst FLAG_ENV: Record<\n keyof NonNullable<ReactorProtocol[\"featureFlags\"]>,\n string\n> = {\n documentDecisions: \"REACTOR_DOCUMENT_DECISIONS\",\n authEnforcement: \"REACTOR_AUTH_ENFORCEMENT\",\n authGroups: \"REACTOR_AUTH_GROUPS\",\n authConditions: \"REACTOR_AUTH_CONDITIONS\",\n};\n\n/** The env vars a protocol block maps onto, with their string values. Only\n * keys the block actually sets appear. */\nexport function protocolEnv(\n protocol: ReactorProtocol | undefined,\n): Record<string, string> {\n const env: Record<string, string> = {};\n if (!protocol) return env;\n for (const [key, varName] of Object.entries(FLAG_ENV)) {\n const value = protocol.featureFlags?.[key as keyof typeof FLAG_ENV];\n if (value !== undefined) env[varName] = value ? \"true\" : \"false\";\n }\n if (protocol.createSignaturePolicy !== undefined) {\n env.CREATE_SIGNATURE_POLICY = protocol.createSignaturePolicy;\n }\n if (protocol.unsupportedStoredDocuments !== undefined) {\n env.REACTOR_UNSUPPORTED_STORED_DOCUMENTS =\n protocol.unsupportedStoredDocuments;\n }\n return env;\n}\n\nexport interface SwitchboardReactorProjection {\n /** Env the switchboard server reads at boot. Only keys the block sets. */\n env: Record<string, string>;\n /** Options passed to startSwitchboard (DB path). */\n options: { dbPath?: string };\n}\n\n/** Project the reactor block onto the switchboard's env + options. */\nexport function projectReactorToSwitchboard(\n reactor: ReactorConfig | undefined,\n): SwitchboardReactorProjection {\n const env = protocolEnv(reactor?.protocol);\n const backend = primaryBackend(reactor);\n const options: { dbPath?: string } = {};\n\n if (backend?.storage) {\n const s = backend.storage;\n const dbUrl = s.kind === \"postgres\" ? s.url : s.dataDir;\n if (dbUrl) env.PH_REACTOR_DATABASE_URL = dbUrl;\n }\n if (backend?.readModel?.url) options.dbPath = backend.readModel.url;\n if (backend?.packages?.dynamic) env.DYNAMIC_MODEL_LOADING = \"true\";\n if (reactor?.workflows !== undefined) {\n env.PH_WORKFLOWS_ENABLED = reactor.workflows ? \"1\" : \"0\";\n }\n return { env, options };\n}\n\n/** The four reactor-client shapes a Connect host can select (mirrors the\n * shared PHReactorClientMode; kept local to avoid an import cycle). */\nexport type ReactorClientMode = \"in-process\" | \"worker\" | \"remote\" | \"router\";\n\nconst LOCAL_BACKEND_KINDS = new Set<ReactorBackendKind>([\n \"in-process\",\n \"worker\",\n]);\n\n/**\n * Which reactor client the backend topology asks for:\n * - local (in-process/worker) AND remote backends -> `router`\n * - remote backend(s) only -> `remote`\n * - a worker backend -> `worker`\n * - anything else local -> `in-process`\n * `undefined` when no backends are declared — the caller then keeps the\n * legacy reactorWorker/multiReactor behaviour untouched.\n */\nexport function reactorClientMode(\n reactor: ReactorConfig | undefined,\n): ReactorClientMode | undefined {\n const backends = reactor?.backends;\n if (!backends) return undefined;\n const kinds = Object.values(backends).map((b) => b.kind);\n if (kinds.length === 0) return undefined;\n const hasLocal = kinds.some((k) => LOCAL_BACKEND_KINDS.has(k));\n const hasRemote = kinds.some((k) => k === \"remote\");\n if (hasLocal && hasRemote) return \"router\";\n if (hasRemote) return \"remote\";\n return primaryBackend(reactor)?.kind === \"worker\" ? \"worker\" : \"in-process\";\n}\n\nexport interface ConnectReactorProjection {\n /** Patch merged into the connect runtime config (connect.*). */\n connect: {\n reactor?: ReactorProtocol;\n instance?: { reactorWorker?: boolean; reactorClient?: ReactorClientMode };\n app?: { workflowsEnabled?: boolean };\n };\n}\n\n/** Project the reactor block onto the Connect runtime config: protocol →\n * connect.reactor (same shape), backend topology → instance.reactorWorker\n * (legacy) + instance.reactorClient (the explicit 4-way selector),\n * workflows → app.workflowsEnabled. */\nexport function projectReactorToConnect(\n reactor: ReactorConfig | undefined,\n): ConnectReactorProjection {\n const connect: ConnectReactorProjection[\"connect\"] = {};\n if (reactor?.protocol) connect.reactor = reactor.protocol;\n const backend = primaryBackend(reactor);\n const mode = reactorClientMode(reactor);\n if (backend?.kind !== undefined || mode !== undefined) {\n connect.instance = {\n ...(backend?.kind !== undefined\n ? { reactorWorker: backend.kind === \"worker\" }\n : {}),\n ...(mode !== undefined ? { reactorClient: mode } : {}),\n };\n }\n if (reactor?.workflows !== undefined) {\n connect.app = { workflowsEnabled: reactor.workflows };\n }\n return { connect };\n}\n\n/**\n * The enforcement teeth of single-sourcing: if a pre-set env var CONTRADICTS\n * the host's protocol block, fail loudly naming the var, the host value, and\n * the env value. An env var that merely matches, or is unset, is fine (phase-2\n * transition keeps an operator's explicit env as an escape hatch unless it\n * disagrees with the protocol — see the WBS precedence note).\n */\nexport function assertProtocolConsistency(\n protocol: ReactorProtocol | undefined,\n env: Record<string, string | undefined>,\n hostFile = \"the host file\",\n): void {\n if (!protocol) return;\n const expected = protocolEnv(protocol);\n for (const [varName, hostValue] of Object.entries(expected)) {\n const envValue = env[varName];\n if (envValue !== undefined && envValue !== hostValue) {\n throw new Error(\n `reactor.protocol conflict: ${varName} is \"${envValue}\" in the environment ` +\n `but \"${hostValue}\" in ${hostFile}. These are fleet-consensus settings — ` +\n `a mismatch would diverge replay. Remove the env override or align the host.`,\n );\n }\n }\n}\n","import type {\n ReactorBackend,\n ReactorBackendKind,\n ReactorConfig,\n ReactorProtocol,\n} from \"./host-schemas.js\";\n\n/**\n * Phase 4 (track R): project named host backends onto reactor-monitor's\n * `ReactorDescriptor` shape — the input `provision()` takes. Pure and\n * dependency-free; a type-assignability test pins the output to the real\n * `ReactorDescriptor` so an upstream field rename fails this package's tests\n * instead of silently drifting (D2.b: aligned locally, upstreaming not\n * blocked on).\n */\n\n/** The browser-provisionable storage union — reactor-monitor's\n * `ReactorStorageConfig` shape. `postgres` is the SERVER extension (D2.b): a\n * switchboard backend's storage, never a provisioned browser reactor's. */\nexport type ProjectedStorage =\n | { kind: \"idb\" }\n | { kind: \"memory\" }\n | { kind: \"path\"; dataDir: string };\n\nexport interface ProjectedDescriptor {\n kind: \"in-process\" | \"worker\" | \"remote\";\n name: string;\n storage?: ProjectedStorage;\n packages?: { cdnUrl?: string; specs?: string[]; dynamic?: boolean };\n featureFlags?: {\n documentDecisions?: boolean;\n authEnforcement?: boolean;\n authGroups?: boolean;\n authConditions?: boolean;\n };\n remote?: { url: string };\n}\n\nfunction projectStorage(\n name: string,\n storage: NonNullable<ReactorBackend[\"storage\"]>,\n): ProjectedStorage {\n switch (storage.kind) {\n case \"idb\":\n return { kind: \"idb\" };\n case \"memory\":\n return { kind: \"memory\" };\n case \"path\": {\n if (!storage.dataDir) {\n throw new Error(\n `Backend \"${name}\": storage kind \"path\" requires dataDir.`,\n );\n }\n return { kind: \"path\", dataDir: storage.dataDir };\n }\n case \"postgres\":\n throw new Error(\n `Backend \"${name}\": storage kind \"postgres\" is server-side only — ` +\n `a provisioned (in-process/worker) reactor cannot use it. Point a ` +\n `\"remote\" backend at the switchboard that owns that database instead.`,\n );\n }\n}\n\n/** One backend → one descriptor. The protocol's featureFlags ride every\n * descriptor (they are fleet consensus, not per-backend). A remote backend\n * must carry remote.url — provision() requires it. */\nexport function backendToDescriptor(\n name: string,\n backend: ReactorBackend,\n protocol?: ReactorProtocol,\n): ProjectedDescriptor {\n const descriptor: ProjectedDescriptor = {\n kind: backend.kind,\n name,\n };\n if (descriptor.kind === \"remote\") {\n const url = backend.remote?.url;\n if (!url) {\n throw new Error(\n `Backend \"${name}\" is kind \"remote\" but has no remote.url — ` +\n `a remote descriptor attaches to an already-running reactor by URL.`,\n );\n }\n descriptor.remote = { url };\n // remote attaches; it builds nothing, so local-build fields do not apply\n return descriptor;\n }\n if (backend.storage) {\n descriptor.storage = projectStorage(name, backend.storage);\n }\n if (backend.packages) descriptor.packages = backend.packages;\n if (protocol?.featureFlags) descriptor.featureFlags = protocol.featureFlags;\n return descriptor;\n}\n\n/** All named backends, in placement-primary-first order (the order a\n * createReactorClients step would provision them). */\nexport function backendsToDescriptors(\n reactor: ReactorConfig | undefined,\n): ProjectedDescriptor[] {\n const backends = reactor?.backends;\n if (!backends) return [];\n const names = Object.keys(backends);\n const primary = reactor.placement?.primary;\n const ordered =\n primary && names.includes(primary)\n ? [primary, ...names.filter((n) => n !== primary)]\n : names;\n return ordered.map((name) =>\n backendToDescriptor(name, backends[name], reactor.protocol),\n );\n}\n\nconst LOCAL_KINDS = new Set<ReactorBackendKind>([\"in-process\", \"worker\"]);\n\n/**\n * Structural multi-reactor (phase 4): true when the block names BOTH a local\n * backend (in-process/worker — the tab's own reactor) and a remote one. This\n * is the shape Connect's routing client serves; a lone remote backend is an\n * attach-only host (assistant/agent shape), not a routed tab.\n */\nexport function isStructuralMultiReactor(\n reactor: ReactorConfig | undefined,\n): boolean {\n const backends = reactor?.backends;\n if (!backends) return false;\n const kinds = Object.values(backends).map((b) => b.kind);\n return (\n kinds.some((k) => LOCAL_KINDS.has(k)) && kinds.some((k) => k === \"remote\")\n );\n}\n\n/** The remote backends' urls, placement order — what the routing client dials. */\nexport function remoteBackendUrls(\n reactor: ReactorConfig | undefined,\n): string[] {\n return backendsToDescriptors(reactor)\n .filter((d) => d.kind === \"remote\")\n .map((d) => d.remote?.url)\n .filter((u): u is string => typeof u === \"string\");\n}\n","import type {\n PHConnectDefaultDrive,\n PHConnectRuntimeConfig,\n} from \"@powerhousedao/shared/clis\";\n\n/**\n * Instance-fact projection for compound hosts: the drives a compound's\n * reactor member created, projected into the Connect member's runtime-config\n * override. Pure functions, moved from ph-cli's vetra service so the generic\n * compound and the classic path share one implementation.\n */\n\nfunction isLocalDrive(\n drive: PHConnectDefaultDrive,\n): drive is Extract<PHConnectDefaultDrive, { local: true }> {\n return \"local\" in drive;\n}\n\n// Identity key for de-duplication: remote entries are keyed by URL; local\n// entries are keyed by `local:<id>` so a local drive id can never collide\n// with a remote URL that happens to be the same string.\nconst driveKey = (drive: PHConnectDefaultDrive): string =>\n isLocalDrive(drive) ? `local:${drive.id}` : drive.url;\n\n/**\n * Concatenate groups of `connect.drives.defaultDrives` in the order given,\n * de-duplicating by drive identity (URL for remote entries, id for local\n * ones). The first occurrence of a drive wins, so earlier groups keep their\n * position and metadata — e.g. the Vetra drive `ph vetra` starts stays first\n * even when the project's `powerhouse.config.json` lists the same drive.\n */\nexport function mergeDefaultDrives(\n ...groups: PHConnectDefaultDrive[][]\n): PHConnectDefaultDrive[] {\n const seen = new Set<string>();\n const out: PHConnectDefaultDrive[] = [];\n for (const group of groups) {\n for (const drive of group) {\n const key = driveKey(drive);\n if (seen.has(key)) continue;\n seen.add(key);\n out.push(drive);\n }\n }\n return out;\n}\n\n/**\n * Rebase a local drive URL onto a public base: keeps the /d/<slug> path,\n * swaps the loopback origin for the public base. Browser clients behind a\n * reverse proxy can't reach http://localhost:<port>. Non-loopback URLs\n * (e.g. a remote drive) are already public and pass through unchanged, as do\n * unparseable ones.\n */\nexport function rebaseDriveUrl(driveUrl: string, publicBase: string): string {\n let url: URL;\n try {\n url = new URL(driveUrl);\n } catch {\n return driveUrl;\n }\n if (![\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname)) {\n return driveUrl;\n }\n return `${publicBase.replace(/\\/+$/, \"\")}${url.pathname}`;\n}\n\nexport interface DriveProjectionInput {\n /** Drive URLs the compound's reactor member created, in display order\n * (e.g. vetra, preview, workflows). Null/undefined entries are skipped. */\n createdDriveUrls: (string | null | undefined)[];\n /** The project's configured `connect.drives.defaultDrives`. */\n configuredDefaultDrives?: PHConnectDefaultDrive[];\n /** `--drives-public-base`: advertise proxy-reachable URLs to the browser. */\n publicBase?: string | null;\n}\n\n/**\n * The compound's drives projection: created drives first (rebased onto the\n * public base when given), then the project's configured drives, de-duplicated\n * — and `preserve-all`, because compound-injected drive lists change per\n * launch context and must never detach drives the user added by hand.\n */\nexport function projectDrivesIntoConnect(\n input: DriveProjectionInput,\n): Pick<PHConnectRuntimeConfig, \"drives\"> {\n const created: PHConnectDefaultDrive[] = input.createdDriveUrls\n .filter((url): url is string => typeof url === \"string\" && url.length > 0)\n .map((url) => ({\n url: input.publicBase ? rebaseDriveUrl(url, input.publicBase) : url,\n name: null,\n icon: null,\n }));\n return {\n drives: {\n defaultDrives: mergeDefaultDrives(\n created,\n input.configuredDefaultDrives ?? [],\n ),\n preserveStrategy: \"preserve-all\",\n },\n };\n}\n","import {\n backendToDescriptor,\n isStructuralMultiReactor,\n} from \"./backend-projection.js\";\nimport type {\n ReactorBackend,\n ReactorBackendKind,\n ReactorConfig,\n ReactorStorageConfig,\n RunnerKind,\n} from \"./host-schemas.js\";\nimport { reactorClientMode, type ReactorClientMode } from \"./reactor-config.js\";\nimport { envSitesOf, outputSitesOf, refKey } from \"./resolve/declared.js\";\nimport type { CompoundPlan } from \"./resolve/plan.js\";\nimport type { OutputPath } from \"./tokens.js\";\n\n/**\n * What a host amounts to once its pipeline has run (typed-host-configs G2,\n * 2.2): the reactor-client shape its backends select, the drives it serves\n * or attaches, the producers whose outputs it consumes and, for a compound,\n * the start order and each member's expectation. Pure and platform-neutral:\n * the caller runs load → declared validation → resolve → resolved\n * validation (and plugin contribution discovery) and hands over the\n * results. The returned value is JSON-only, so it can be pinned in a test\n * table or shipped to another process (a future reactor-monitor).\n */\n\n/** One backend, in placement-primary-first order. */\nexport interface ExpectedBackend {\n name: string;\n kind: ReactorBackendKind;\n storage?: ReactorStorageConfig[\"kind\"];\n /** The RESOLVED storage dir (`\"${userData}\"` sugar and `$env` applied). */\n dataDir?: string;\n /** Why a provisioned reactor (a browser tab, reactor-monitor) cannot be\n * built from this backend (`backendToDescriptor`): e.g. postgres storage\n * is server-side only, a remote backend needs `remote.url`. Absent when\n * it can. A switchboard's own backend may legitimately carry one. */\n provisionError?: string;\n}\n\n/** One drive of the merged plan: plugin contributions first, then the\n * host's own declarations (the host wins a slug). Identity is the DECLARED\n * slug: a `projectHash` drive reports the flag, not a hashed id, so the\n * expectation does not depend on where the project lives. */\nexport interface ExpectedDrive {\n slug: string;\n kind: \"local\" | \"remote\";\n /** \"host\" for `reactor.drives`; the plugin name for a contribution. */\n source: string;\n /** A remote drive's resolved URL. */\n url?: string;\n id?: string;\n projectHash?: boolean | \"id\";\n}\n\n/** One `$output` token in the declared host. */\nexport interface ConsumedOutput {\n /** Host path of the token (`reactor.backends.sb.remote.url`). */\n at: string;\n host: string;\n member?: string;\n path: OutputPath;\n}\n\nexport interface HostExpectation {\n name: string;\n kind: RunnerKind;\n /** The verb this host runs at: `runner.defaultVerb ?? \"run\"` standalone;\n * for a compound member, its own effective verb under the compound's. */\n verb: string;\n /** Reactor hosts with backends: `reactorClientMode`. */\n clientMode?: ReactorClientMode;\n /** Reactor hosts: local AND remote backends (Connect's routing client). */\n multiReactor?: boolean;\n backends?: ExpectedBackend[];\n /** The resolved URLs of the remote backends, placement order. */\n remotes?: string[];\n drives?: ExpectedDrive[];\n /** Producers its own tokens read (`host` or `host#member`), sorted. */\n dependsOn: string[];\n consumes: ConsumedOutput[];\n /** `$env` names its own tokens read, sorted (values are not recorded). */\n env: string[];\n /** Compound: member keys in start order. */\n startOrder?: string[];\n /** Compound: each member's expectation. */\n members?: Record<string, MemberExpectation>;\n}\n\nexport interface MemberExpectation extends Omit<\n HostExpectation,\n \"startOrder\" | \"members\"\n> {\n /** The member's host folder (`children.<key>.host`). */\n host: string;\n /** Member keys this member consumes (it starts after them), sorted. */\n after: string[];\n}\n\n/** A drive a plugin contributes, as plugin contribution discovery reports\n * it (`resolvePluginContributions`). */\nexport interface ContributedDriveInput {\n declaration: Record<string, unknown>;\n source: string;\n}\n\nexport interface ExpectHostInput {\n kind: RunnerKind;\n /** The host as declared (tokens in place); a compound member's draft\n * (its host.js with the wrapper applied). */\n declared: Record<string, unknown>;\n /** The resolved (and parsed) host. Default: `declared`. */\n resolved?: Record<string, unknown>;\n /** Drives the host's plugins contribute at its verb. */\n contributed?: readonly ContributedDriveInput[];\n /** Compound: its members, any order (the plan orders them). */\n members?: readonly MemberInput[];\n /** Compound: the dependency plan (`planCompound`). */\n plan?: CompoundPlan;\n}\n\nexport interface MemberInput extends Omit<ExpectHostInput, \"members\" | \"plan\"> {\n key: string;\n host: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction runnerOf(host: Record<string, unknown>): Record<string, unknown> {\n return isRecord(host.runner) ? host.runner : {};\n}\n\nfunction defaultVerbOf(host: Record<string, unknown>): string | undefined {\n const verb = runnerOf(host).defaultVerb;\n return typeof verb === \"string\" ? verb : undefined;\n}\n\n/** At compound verb \"run\" each member runs its own defaultVerb; any other\n * compound verb is forwarded uniformly (compound.ts `memberVerbOf`). */\nfunction memberVerb(compoundVerb: string, member: Record<string, unknown>) {\n return compoundVerb === \"run\"\n ? (defaultVerbOf(member) ?? \"run\")\n : compoundVerb;\n}\n\n/** Backend names, placement-primary first (`backendsToDescriptors` order). */\nfunction orderedBackends(reactor: ReactorConfig): [string, ReactorBackend][] {\n const backends = Object.entries(reactor.backends ?? {});\n const primary = reactor.placement?.primary;\n const first = backends.filter(([name]) => name === primary);\n return [...first, ...backends.filter(([name]) => name !== primary)];\n}\n\nfunction expectBackend(\n name: string,\n backend: ReactorBackend,\n reactor: ReactorConfig,\n): ExpectedBackend {\n const out: ExpectedBackend = { name, kind: backend.kind };\n if (backend.storage) out.storage = backend.storage.kind;\n if (typeof backend.storage?.dataDir === \"string\") {\n out.dataDir = backend.storage.dataDir;\n }\n try {\n backendToDescriptor(name, backend, reactor.protocol);\n } catch (error) {\n out.provisionError = error instanceof Error ? error.message : String(error);\n }\n return out;\n}\n\nfunction expectDrive(\n declaration: Record<string, unknown>,\n source: string,\n): ExpectedDrive | undefined {\n if (typeof declaration.slug !== \"string\") return undefined;\n const remote = isRecord(declaration.remote) ? declaration.remote : undefined;\n const drive: ExpectedDrive = {\n slug: declaration.slug,\n kind: remote ? \"remote\" : \"local\",\n source,\n };\n if (remote && typeof remote.url === \"string\") drive.url = remote.url;\n if (typeof declaration.id === \"string\") drive.id = declaration.id;\n const projectHash = declaration.projectHash;\n if (typeof projectHash === \"boolean\" || projectHash === \"id\") {\n drive.projectHash = projectHash;\n }\n return drive;\n}\n\n/** The key `mergeDrivePlan` merges on: the SERVED slug, which for\n * `projectHash: true` is the hashed id (never equal to a plain slug). */\nfunction servedSlugKey(drive: ExpectedDrive): string {\n return drive.projectHash === true ? `${drive.slug}\\0hashed` : drive.slug;\n}\n\n/** Contributions first, then host declarations; keyed by served slug, the\n * host wins (and keeps the contribution's position), like `mergeDrivePlan`. */\nfunction drivePlan(\n reactor: ReactorConfig | undefined,\n contributed: readonly ContributedDriveInput[],\n): ExpectedDrive[] {\n const plan = new Map<string, ExpectedDrive>();\n for (const { declaration, source } of contributed) {\n const drive = expectDrive(declaration, source);\n if (drive) plan.set(servedSlugKey(drive), drive);\n }\n for (const declaration of reactor?.drives ?? []) {\n const drive = expectDrive(declaration, \"host\");\n if (drive) plan.set(servedSlugKey(drive), drive);\n }\n return [...plan.values()];\n}\n\n/** Token facts of the host's OWN fields (a compound's `children` are its\n * members' own). */\nfunction tokenFacts(\n declared: Record<string, unknown>,\n kind: RunnerKind,\n): Pick<HostExpectation, \"dependsOn\" | \"consumes\" | \"env\"> {\n const own =\n kind === \"compound\"\n ? Object.fromEntries(\n Object.entries(declared).filter(([key]) => key !== \"children\"),\n )\n : declared;\n const sites = outputSitesOf(own);\n const consumes = sites.map(({ path, ref, outputPath }): ConsumedOutput => ({\n at: path,\n host: ref.host,\n ...(ref.member !== undefined ? { member: ref.member } : {}),\n path: outputPath,\n }));\n return {\n dependsOn: [...new Set(sites.map(({ ref }) => refKey(ref)))].sort(),\n consumes,\n env: [...new Set(envSitesOf(own).map(({ name }) => name))].sort(),\n };\n}\n\nfunction expectOwn(\n input: Omit<ExpectHostInput, \"members\" | \"plan\">,\n verb: string,\n): HostExpectation {\n const resolved = input.resolved ?? input.declared;\n const expectation: HostExpectation = {\n name: typeof resolved.name === \"string\" ? resolved.name : \"\",\n kind: input.kind,\n verb,\n ...tokenFacts(input.declared, input.kind),\n };\n if (input.kind !== \"reactor\") return expectation;\n\n const reactor = isRecord(resolved.reactor)\n ? (resolved.reactor as ReactorConfig)\n : undefined;\n const mode = reactorClientMode(reactor);\n if (mode !== undefined) expectation.clientMode = mode;\n expectation.multiReactor = isStructuralMultiReactor(reactor);\n const backends = reactor ? orderedBackends(reactor) : [];\n if (reactor && backends.length > 0) {\n expectation.backends = backends.map(([name, backend]) =>\n expectBackend(name, backend, reactor),\n );\n expectation.remotes = backends.flatMap(([, backend]) =>\n backend.kind === \"remote\" && typeof backend.remote?.url === \"string\"\n ? [backend.remote.url]\n : [],\n );\n }\n expectation.drives = drivePlan(reactor, input.contributed ?? []);\n return expectation;\n}\n\n/**\n * The expectation for one host. A reactor host's comes from its resolved\n * reactor block and contributed drives; a compound's lists its members in\n * plan order, each with the verb it runs at under the compound's own verb\n * and the members it starts after.\n */\nexport function expectHost(input: ExpectHostInput): HostExpectation {\n const verb = defaultVerbOf(input.declared) ?? \"run\";\n const expectation = expectOwn(input, verb);\n if (input.kind !== \"compound\" || !input.members) return expectation;\n\n const order = input.plan?.order ?? input.members.map((m) => m.key);\n const edges = input.plan?.edges ?? [];\n const byKey = new Map(input.members.map((m) => [m.key, m]));\n const members: Record<string, MemberExpectation> = {};\n for (const key of order) {\n const member = byKey.get(key);\n if (!member) continue;\n members[key] = {\n host: member.host,\n ...expectOwn(member, memberVerb(verb, member.declared)),\n after: [\n ...new Set(\n edges.filter((e) => e.consumer === key).map((e) => e.producer),\n ),\n ].sort(),\n };\n }\n expectation.startOrder = order.filter((key) => byKey.has(key));\n expectation.members = members;\n return expectation;\n}\n"],"mappings":";;;;AAyBA,MAAM,aAAa,UACjB,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;AAExD,SAAgB,eAAe,aAAqB,MAAsB;CACxE,OAAO,mBAAmB,WAAW,aAAa,IAAI;AACxD;AAcA,SAAgB,wBACd,aACA,MACe;CACf,MAAM,KAAK,KAAK,cACZ,eAAe,aAAa,KAAK,IAAI,IACpC,KAAK,MAAM,KAAK;CAGrB,MAAM,OAAO,KAAK,gBAAgB,OAAO,KAAK,KAAK;CACnD,IAAI,KAAK,QACP,OAAO;EACL,MAAM;EACN;EACA;EACA,MAAM,KAAK,QAAQ,KAAK;EACxB,WAAW,KAAK,OAAO;EACvB,aAAa,KAAK,eAAe;EACjC,kBAAkB,KAAK,oBAAoB;CAC7C;CAEF,OAAO;EACL,MAAM;EACN;EACA;EACA,MAAM,KAAK,QAAQ,KAAK;EAGxB,MAAM,gBAAgB,aAAa,KAAK,MAAM;GAC5C,UAAU;GACV,OAAO,MAAM,QAAQ,KAAK,CAAC;EAC7B,CAAC;EACD,iBAAiB,KAAK;EACtB,aAAa,KAAK,eAAe;EACjC,kBAAkB,KAAK,oBAAoB;CAC7C;AACF;;;AAuBA,eAAsB,WACpB,QACA,QACqB;CACrB,MAAM,SAAqB;EAAE,SAAS,CAAC;EAAG,UAAU,CAAC;EAAG,UAAU,CAAC;CAAE;CACrE,KAAK,MAAM,SAAS,QAAQ;EAC1B,IAAI,MAAM,SAAS,UAAU;GAC3B,MAAM,OAAO,kBAAkB,M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UAA6C,CAAC;CACpD,KAAK,MAAM,OAAO,OAAO;EACvB,MAAM,SAAS,MAAM,IAAI,GAAG;EAC5B,IAAI,CAAC,QAAQ;EACb,QAAQ,OAAO;GACb,MAAM,OAAO;GACb,GAAG,UAAU,QAAQ,WAAW,MAAM,OAAO,QAAQ,CAAC;GACtD,OAAO,CACL,GAAG,IAAI,IACL,MAAM,QAAQ,MAAM,EAAE,aAAa,GAAG,CAAC,CAAC,KAAK,MAAM,EAAE,QAAQ,CAC/D,CACF,CAAC,CAAC,KAAK;EACT;CACF;CACA,YAAY,aAAa,MAAM,QAAQ,QAAQ,MAAM,IAAI,GAAG,CAAC;CAC7D,YAAY,UAAU;CACtB,OAAO;AACT"}
@@ -0,0 +1,182 @@
1
+ import { C as declaredGenericCompoundHostSchema } from "./host-schemas-mqOYNGot.mjs";
2
+ import { z } from "zod";
3
+ //#region src/host-types.d.ts
4
+ declare global {
5
+ /** `"<runner specifier>": { host: <z.input of its hostSchema>; outputs:
6
+ * <z.infer of its outputsSchema> }`, one entry per runner module. */
7
+ interface PHHostRunners {}
8
+ /** `"<plugin specifier>": <z.input of its configSchema>`. */
9
+ interface PHPluginConfigs {}
10
+ }
11
+ type RunnerSpecifier = keyof PHHostRunners & string;
12
+ type PluginSpecifier = keyof PHPluginConfigs & string;
13
+ /** A runner's host input with `runner.plugins` typed as authoring
14
+ * {@link PluginEntry}s (the zod input type only knows the untyped data
15
+ * shape), so a known plugin's config is checked against its own type. */
16
+ type WithTypedPlugins<H, M extends string> = H extends {
17
+ runner: infer R;
18
+ } ? Omit<H, "runner"> & {
19
+ runner: Omit<R, "module" | "plugins"> & {
20
+ module: M;
21
+ plugins?: PluginEntry[];
22
+ };
23
+ } : never;
24
+ /** Any host file, discriminated by `runner.module`. `never` until a runner
25
+ * package augments PHHostRunners. */
26
+ type PHHost = { [M in RunnerSpecifier]: PHHostRunners[M] extends {
27
+ host: infer H;
28
+ } ? WithTypedPlugins<H, M> : never; }[RunnerSpecifier];
29
+ /** The outputs a runner's creation produces, by specifier. */
30
+ type PHHostOutputs<M extends RunnerSpecifier> = PHHostRunners[M] extends {
31
+ outputs: infer O;
32
+ } ? O : never;
33
+ interface PluginEntryObject<M extends string, C> {
34
+ module: M;
35
+ /** Presence is activation by default; false is the explicit off-switch. */
36
+ enabled?: boolean;
37
+ /** "*" (default) or the run verbs this entry is active for. */
38
+ verbs?: "*" | string[];
39
+ config?: C;
40
+ }
41
+ type KnownPluginEntry = { [M in PluginSpecifier]: M | PluginEntryObject<M, PHPluginConfigs[M]>; }[PluginSpecifier];
42
+ /** A `runner.plugins` entry as an author writes it. A known specifier (one
43
+ * a package augments PHPluginConfigs with) carries its plugin's config type,
44
+ * and only that: the object fallback for other specifiers takes no config,
45
+ * because TS cannot express "any string but the known ones" and a
46
+ * `Record<string, unknown>` fallback would admit a known specifier with a
47
+ * wrong config. Any specifier may still be named bare, or as an object
48
+ * without config; a third-party plugin that takes config augments
49
+ * PHPluginConfigs (in its package, or in the project's hosts/types.d.ts). */
50
+ type PluginEntry = KnownPluginEntry | string | PluginEntryObject<string, undefined>;
51
+ declare global {
52
+ interface PHHostRunners {
53
+ "@powerhousedao/host-core/runners/compound": {
54
+ host: z.input<typeof declaredGenericCompoundHostSchema>;
55
+ outputs: Record<string, never>;
56
+ };
57
+ }
58
+ }
59
+ //#endregion
60
+ //#region src/plugins.d.ts
61
+ /**
62
+ * R1 — the host plugin framework (bridge-runners-to-plugins plan,
63
+ * customization-references/host-core as the blueprint).
64
+ *
65
+ * A plugin is hooks + contributions; hooks are boot wiring (main realm only),
66
+ * contributions are declarative, serializable surface. Host RUNTIMES define
67
+ * the hook vocabulary and interleave their own wiring between stages — they
68
+ * are never plugins themselves.
69
+ *
70
+ * host.js carries the COMPOSITION as `runner.plugins` entries:
71
+ * string | { module, enabled?, verbs?, config? }
72
+ * Presence is activation (enabled defaults true); `verbs` scopes an entry to
73
+ * matching run verbs; `config` is validated against the plugin's declared
74
+ * zod schema. Entries resolve from the PROJECT's dependency tree exactly
75
+ * like runner modules.
76
+ */
77
+ declare class PluginError extends Error {
78
+ constructor(message: string, hint?: string);
79
+ }
80
+ declare const pluginEntryObjectSchema: z.ZodObject<{
81
+ module: z.ZodString;
82
+ enabled: z.ZodOptional<z.ZodBoolean>;
83
+ verbs: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"*">, z.ZodArray<z.ZodString>]>>;
84
+ config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
85
+ }, z.core.$strict>;
86
+ declare const pluginEntrySchema: z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
87
+ module: z.ZodString;
88
+ enabled: z.ZodOptional<z.ZodBoolean>;
89
+ verbs: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"*">, z.ZodArray<z.ZodString>]>>;
90
+ config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
91
+ }, z.core.$strict>]>;
92
+ /** The validated (runtime) entry shape. Authors write `PluginEntry`
93
+ * (host-types.ts), which types known plugins' configs. */
94
+ type PluginEntryData = z.infer<typeof pluginEntrySchema>;
95
+ interface NormalizedPluginEntry {
96
+ module: string;
97
+ enabled: boolean;
98
+ verbs: "*" | string[];
99
+ config: Record<string, unknown>;
100
+ }
101
+ declare function normalizePluginEntry(entry: PluginEntryData): NormalizedPluginEntry;
102
+ /** Module is the identity key: a duplicate makes override targeting and
103
+ * ordering ambiguous, so it fails loudly. */
104
+ declare function normalizePluginEntries(entries: readonly PluginEntryData[], where: string): NormalizedPluginEntry[];
105
+ declare function entryActiveForVerb(entry: NormalizedPluginEntry, verb: string): boolean;
106
+ declare function registerHostType(id: string, parent: string | null): void;
107
+ declare function hostTypeSatisfies(hostType: string, appliesTo: string): boolean;
108
+ /** Hook kinds (v1 §2.2). The hook VOCABULARY is defined by host runtimes;
109
+ * plugins implement subsets of it. */
110
+ type Provide<T, C> = (ctx: C) => T | Promise<T>;
111
+ type Transform<T, C> = (value: T, ctx: C) => T | Promise<T>;
112
+ type Observe<C> = (ctx: C) => void | Promise<void>;
113
+ /**
114
+ * Core contributions — declarative, serializable, realm-crossing. Host
115
+ * runtimes extend this with their own kinds (UI slots live in connect-host,
116
+ * never here). `drives` entries use the drive declaration shape from
117
+ * drives.ts; kept as unknown here to avoid a cycle — the merge is shape-blind.
118
+ */
119
+ interface Contributions {
120
+ drives?: unknown[];
121
+ packages?: string[];
122
+ configDeclarations?: {
123
+ name: string;
124
+ type?: string;
125
+ description?: string;
126
+ }[];
127
+ [kind: string]: unknown[] | undefined;
128
+ }
129
+ interface HostPlugin<THooks = Record<string, unknown>, TConfig = unknown> {
130
+ /** Stable id; used in ordering, dependsOn, and every diagnostic. */
131
+ name: string;
132
+ /** Host-type requirement; the entry is rejected on a host outside the
133
+ * hierarchy branch. Default: "reactor". */
134
+ appliesTo?: string;
135
+ /** Coarse ordering bucket (Vite-style). Default: "normal". */
136
+ enforce?: "pre" | "post";
137
+ /** Hard dependencies on OTHER PLUGINS — the host runtime is implied and
138
+ * never named. Missing dependency or cycle fails boot naming both sides. */
139
+ dependsOn?: string[];
140
+ /** Declared config shape; entry config is validated against it. A plugin
141
+ * without a schema accepts no config (passing one is a boot error). */
142
+ configSchema?: z.ZodType<TConfig>;
143
+ hooks?: Partial<THooks>;
144
+ contributions?: Contributions;
145
+ }
146
+ /** A plugin module default-exports either a HostPlugin object (no config
147
+ * accepted) or a factory `(config) => HostPlugin`. */
148
+ type HostPluginModule<THooks = Record<string, unknown>, TConfig = unknown> = HostPlugin<THooks, TConfig> | ((config: TConfig) => HostPlugin<THooks, TConfig>);
149
+ interface ResolvedPlugin<THooks = Record<string, unknown>> {
150
+ entry: NormalizedPluginEntry;
151
+ plugin: HostPlugin<THooks>;
152
+ /** Provenance for contribution merge ordering. */
153
+ provenance: "built-in" | "local" | "dependency";
154
+ }
155
+ /** Registration order, bucketed pre → normal → post (stable within buckets),
156
+ * then dependsOn topo-sorted within the bucketed order. */
157
+ declare function resolveOrder<THooks>(plugins: readonly HostPlugin<THooks>[]): HostPlugin<THooks>[];
158
+ declare function runProvideHook<T, C>(name: string, plugins: readonly HostPlugin[], ctx: C): Promise<T | undefined>;
159
+ declare function runTransformHook<T, C>(name: string, plugins: readonly HostPlugin[], ctx: C, seed: T): Promise<T>;
160
+ /** Sequential observe, in plugin order — for lifecycle moments whose order
161
+ * is load-bearing (teardown: the switchboard stops privacy before workflows
162
+ * before the api, per the carve map). */
163
+ declare function runObserveHookSequential<C>(name: string, plugins: readonly HostPlugin[], ctx: C): Promise<void>;
164
+ declare function runObserveHook<C>(name: string, plugins: readonly HostPlugin[], ctx: C): Promise<void>;
165
+ interface ContributionSource {
166
+ pluginName: string;
167
+ provenance: "built-in" | "local" | "dependency";
168
+ }
169
+ interface MergedContribution<T = unknown> {
170
+ value: T;
171
+ source: ContributionSource;
172
+ }
173
+ /** Array kinds concatenate in provenance-then-order sequence (built-in first,
174
+ * so later sources read as overrides where consumers want last-wins). */
175
+ declare function mergeContributions(resolved: readonly {
176
+ plugin: HostPlugin;
177
+ provenance: ContributionSource["provenance"];
178
+ }[]): Record<string, MergedContribution[]>;
179
+ //#endregion
180
+ export { runObserveHookSequential as C, PHHostOutputs as D, PHHost as E, PluginEntry as O, runObserveHook as S, runTransformHook as T, normalizePluginEntry as _, MergedContribution as a, registerHostType as b, PluginEntryData as c, ResolvedPlugin as d, Transform as f, normalizePluginEntries as g, mergeContributions as h, HostPluginModule as i, PluginError as l, hostTypeSatisfies as m, Contributions as n, NormalizedPluginEntry as o, entryActiveForVerb as p, HostPlugin as r, Observe as s, ContributionSource as t, Provide as u, pluginEntryObjectSchema as v, runProvideHook as w, resolveOrder as x, pluginEntrySchema as y };
181
+ export {};
182
+ //# sourceMappingURL=plugins-XL6WsvTL.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugins-XL6WsvTL.d.mts","names":[],"sources":["../src/host-types.ts","../src/plugins.ts"],"mappings":";;;QAUQ;;;YAII;;YAGA;;KAMP,wBAAwB;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S;EACvC,OAAO;EACP,QAAQ,WAAW;;EAEnB;;;;iBAOc,aAAa,QAC3B,kBAAkB,WAAW,YAC5B,WAAW;iBA6CQ,eAAe,GAAG,GACtC,cACA,kBAAkB,cAClB,KAAK,IACJ,QAAQ;iBAWW,iBAAiB,GAAG,GACxC,cACA,kBAAkB,cAClB,KAAK,GACL,MAAM,IACL,QAAQ;;;;iBAYW,yBAAyB,GAC7C,cACA,kBAAkB,cAClB,KAAK,IACJ;iBAOmB,eAAe,GACnC,cACA,kBAAkB,cAClB,KAAK,IACJ;UAWc;EACf;EACA;;UAGe,mBAAmB;EAClC,OAAO;EACP,QAAQ;;;;iBAKM,mBACd;EACE,QAAQ;EACR,YAAY;MAEb,eAAe"}
@@ -1,121 +1,3 @@
1
- import { z } from "zod";
2
- //#region src/plugins.d.ts
3
- /**
4
- * R1 — the host plugin framework (bridge-runners-to-plugins plan,
5
- * customization-references/host-core as the blueprint).
6
- *
7
- * A plugin is hooks + contributions; hooks are boot wiring (main realm only),
8
- * contributions are declarative, serializable surface. Host RUNTIMES define
9
- * the hook vocabulary and interleave their own wiring between stages — they
10
- * are never plugins themselves.
11
- *
12
- * host.js carries the COMPOSITION as `runner.plugins` entries:
13
- * string | { module, enabled?, verbs?, config? }
14
- * Presence is activation (enabled defaults true); `verbs` scopes an entry to
15
- * matching run verbs; `config` is validated against the plugin's declared
16
- * zod schema. Entries resolve from the PROJECT's dependency tree exactly
17
- * like runner modules.
18
- */
19
- export declare class PluginError extends Error {
20
- constructor(message: string, hint?: string);
21
- }
22
- export declare const pluginEntryObjectSchema: z.ZodObject<{
23
- module: z.ZodString;
24
- enabled: z.ZodOptional<z.ZodBoolean>;
25
- verbs: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"*">, z.ZodArray<z.ZodString>]>>;
26
- config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
27
- }, z.core.$strict>;
28
- export declare const pluginEntrySchema: z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
29
- module: z.ZodString;
30
- enabled: z.ZodOptional<z.ZodBoolean>;
31
- verbs: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<"*">, z.ZodArray<z.ZodString>]>>;
32
- config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
33
- }, z.core.$strict>]>;
34
- export type PluginEntry = z.infer<typeof pluginEntrySchema>;
35
- export interface NormalizedPluginEntry {
36
- module: string;
37
- enabled: boolean;
38
- verbs: "*" | string[];
39
- config: Record<string, unknown>;
40
- }
41
- export declare function normalizePluginEntry(entry: PluginEntry): NormalizedPluginEntry;
42
- /** Module is the identity key: a duplicate makes override targeting and
43
- * ordering ambiguous, so it fails loudly. */
44
- export declare function normalizePluginEntries(entries: readonly PluginEntry[], where: string): NormalizedPluginEntry[];
45
- export declare function entryActiveForVerb(entry: NormalizedPluginEntry, verb: string): boolean;
46
- export declare function registerHostType(id: string, parent: string | null): void;
47
- export declare function hostTypeSatisfies(hostType: string, appliesTo: string): boolean;
48
- /** Hook kinds (v1 §2.2). The hook VOCABULARY is defined by host runtimes;
49
- * plugins implement subsets of it. */
50
- export type Provide<T, C> = (ctx: C) => T | Promise<T>;
51
- export type Transform<T, C> = (value: T, ctx: C) => T | Promise<T>;
52
- export type Observe<C> = (ctx: C) => void | Promise<void>;
53
- /**
54
- * Core contributions — declarative, serializable, realm-crossing. Host
55
- * runtimes extend this with their own kinds (UI slots live in connect-host,
56
- * never here). `drives` entries use the drive declaration shape from
57
- * drives.ts; kept as unknown here to avoid a cycle — the merge is shape-blind.
58
- */
59
- export interface Contributions {
60
- drives?: unknown[];
61
- packages?: string[];
62
- configDeclarations?: {
63
- name: string;
64
- type?: string;
65
- description?: string;
66
- }[];
67
- [kind: string]: unknown[] | undefined;
68
- }
69
- export interface HostPlugin<THooks = Record<string, unknown>, TConfig = unknown> {
70
- /** Stable id; used in ordering, dependsOn, and every diagnostic. */
71
- name: string;
72
- /** Host-type requirement; the entry is rejected on a host outside the
73
- * hierarchy branch. Default: "reactor". */
74
- appliesTo?: string;
75
- /** Coarse ordering bucket (Vite-style). Default: "normal". */
76
- enforce?: "pre" | "post";
77
- /** Hard dependencies on OTHER PLUGINS — the host runtime is implied and
78
- * never named. Missing dependency or cycle fails boot naming both sides. */
79
- dependsOn?: string[];
80
- /** Declared config shape; entry config is validated against it. A plugin
81
- * without a schema accepts no config (passing one is a boot error). */
82
- configSchema?: z.ZodType<TConfig>;
83
- hooks?: Partial<THooks>;
84
- contributions?: Contributions;
85
- }
86
- /** A plugin module default-exports either a HostPlugin object (no config
87
- * accepted) or a factory `(config) => HostPlugin`. */
88
- export type HostPluginModule<THooks = Record<string, unknown>, TConfig = unknown> = HostPlugin<THooks, TConfig> | ((config: TConfig) => HostPlugin<THooks, TConfig>);
89
- export interface ResolvedPlugin<THooks = Record<string, unknown>> {
90
- entry: NormalizedPluginEntry;
91
- plugin: HostPlugin<THooks>;
92
- /** Provenance for contribution merge ordering. */
93
- provenance: "built-in" | "local" | "dependency";
94
- }
95
- /** Registration order, bucketed pre → normal → post (stable within buckets),
96
- * then dependsOn topo-sorted within the bucketed order. */
97
- export declare function resolveOrder<THooks>(plugins: readonly HostPlugin<THooks>[]): HostPlugin<THooks>[];
98
- export declare function runProvideHook<T, C>(name: string, plugins: readonly HostPlugin[], ctx: C): Promise<T | undefined>;
99
- export declare function runTransformHook<T, C>(name: string, plugins: readonly HostPlugin[], ctx: C, seed: T): Promise<T>;
100
- /** Sequential observe, in plugin order — for lifecycle moments whose order
101
- * is load-bearing (teardown: the switchboard stops privacy before workflows
102
- * before the api, per the carve map). */
103
- export declare function runObserveHookSequential<C>(name: string, plugins: readonly HostPlugin[], ctx: C): Promise<void>;
104
- export declare function runObserveHook<C>(name: string, plugins: readonly HostPlugin[], ctx: C): Promise<void>;
105
- export interface ContributionSource {
106
- pluginName: string;
107
- provenance: "built-in" | "local" | "dependency";
108
- }
109
- export interface MergedContribution<T = unknown> {
110
- value: T;
111
- source: ContributionSource;
112
- }
113
- /** Array kinds concatenate in provenance-then-order sequence (built-in first,
114
- * so later sources read as overrides where consumers want last-wins). */
115
- export declare function mergeContributions(resolved: readonly {
116
- plugin: HostPlugin;
117
- provenance: ContributionSource["provenance"];
118
- }[]): Record<string, MergedContribution[]>;
119
- //#endregion
1
+ import { C as runObserveHookSequential, O as PluginEntry, S as runObserveHook, T as runTransformHook, _ as normalizePluginEntry, a as MergedContribution, b as registerHostType, c as PluginEntryData, d as ResolvedPlugin, f as Transform, g as normalizePluginEntries, h as mergeContributions, i as HostPluginModule, l as PluginError, m as hostTypeSatisfies, n as Contributions, o as NormalizedPluginEntry, p as entryActiveForVerb, r as HostPlugin, s as Observe, t as ContributionSource, u as Provide, v as pluginEntryObjectSchema, w as runProvideHook, x as resolveOrder, y as pluginEntrySchema } from "./plugins-XL6WsvTL.mjs";
2
+ export { ContributionSource, Contributions, HostPlugin, HostPluginModule, MergedContribution, NormalizedPluginEntry, Observe, type PluginEntry, PluginEntryData, PluginError, Provide, ResolvedPlugin, Transform, entryActiveForVerb, hostTypeSatisfies, mergeContributions, normalizePluginEntries, normalizePluginEntry, pluginEntryObjectSchema, pluginEntrySchema, registerHostType, resolveOrder, runObserveHook, runObserveHookSequential, runProvideHook, runTransformHook };
120
3
  export {};
121
- //# sourceMappingURL=plugins.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"plugins.mjs","names":[],"sources":["../src/plugins.ts"],"sourcesContent":["import { z } from \"zod\";\n\n/**\n * R1 — the host plugin framework (bridge-runners-to-plugins plan,\n * customization-references/host-core as the blueprint).\n *\n * A plugin is hooks + contributions; hooks are boot wiring (main realm only),\n * contributions are declarative, serializable surface. Host RUNTIMES define\n * the hook vocabulary and interleave their own wiring between stages — they\n * are never plugins themselves.\n *\n * host.js carries the COMPOSITION as `runner.plugins` entries:\n * string | { module, enabled?, verbs?, config? }\n * Presence is activation (enabled defaults true); `verbs` scopes an entry to\n * matching run verbs; `config` is validated against the plugin's declared\n * zod schema. Entries resolve from the PROJECT's dependency tree exactly\n * like runner modules.\n */\n\nexport class PluginError extends Error {\n constructor(message: string, hint?: string) {\n super(hint ? `${message}\\n Hint: ${hint}` : message);\n this.name = \"PluginError\";\n }\n}\n\n/* ------------------------------------------------------------------ entries */\n\nexport const pluginEntryObjectSchema = z.strictObject({\n module: z.string().min(1),\n /** Presence is activation BY DEFAULT; false is the explicit off-switch. */\n enabled: z.boolean().optional(),\n /** \"*\" (default) or the run verbs this entry is active for. */\n verbs: z\n .union([z.literal(\"*\"), z.array(z.string().min(1)).min(1)])\n .optional(),\n /** Validated against the plugin's declared configSchema at resolution. */\n config: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport const pluginEntrySchema = z.union([\n z.string().min(1),\n pluginEntryObjectSchema,\n]);\n\nexport type PluginEntry = z.infer<typeof pluginEntrySchema>;\n\nexport interface NormalizedPluginEntry {\n module: string;\n enabled: boolean;\n verbs: \"*\" | string[];\n config: Record<string, unknown>;\n}\n\nexport function normalizePluginEntry(\n entry: PluginEntry,\n): NormalizedPluginEntry {\n if (typeof entry === \"string\") {\n return { module: entry, enabled: true, verbs: \"*\", config: {} };\n }\n return {\n module: entry.module,\n enabled: entry.enabled ?? true,\n verbs: entry.verbs ?? \"*\",\n config: entry.config ?? {},\n };\n}\n\n/** Module is the identity key: a duplicate makes override targeting and\n * ordering ambiguous, so it fails loudly. */\nexport function normalizePluginEntries(\n entries: readonly PluginEntry[],\n where: string,\n): NormalizedPluginEntry[] {\n const normalized = entries.map(normalizePluginEntry);\n const seen = new Set<string>();\n for (const entry of normalized) {\n if (seen.has(entry.module)) {\n throw new PluginError(\n `${where}: plugin \"${entry.module}\" is listed twice.`,\n \"Module specifiers are the identity key of a composition; a plugin meant to run twice needs distinct subpath specifiers.\",\n );\n }\n seen.add(entry.module);\n }\n return normalized;\n}\n\nexport function entryActiveForVerb(\n entry: NormalizedPluginEntry,\n verb: string,\n): boolean {\n if (!entry.enabled) return false;\n return entry.verbs === \"*\" || entry.verbs.includes(verb);\n}\n\n/* ---------------------------------------------------------------- hierarchy */\n\n/**\n * The appliesTo hierarchy. \"reactor\" is the base every reactor host extends;\n * \"compound\" is its own branch (plugins over the member set — e.g. the clint\n * proxy). Host runtimes register their id with a parent; compatibility walks\n * the parent chain.\n */\nconst HOST_TYPE_PARENTS: Record<string, string | null> = {\n reactor: null,\n compound: null,\n connect: \"reactor\",\n switchboard: \"reactor\",\n mastra: \"reactor\",\n};\n\nexport function registerHostType(id: string, parent: string | null): void {\n if (id in HOST_TYPE_PARENTS && HOST_TYPE_PARENTS[id] !== parent) {\n throw new PluginError(\n `Host type \"${id}\" is already registered with parent \"${String(HOST_TYPE_PARENTS[id])}\".`,\n );\n }\n HOST_TYPE_PARENTS[id] = parent;\n}\n\nexport function hostTypeSatisfies(\n hostType: string,\n appliesTo: string,\n): boolean {\n let current: string | null = hostType;\n while (current !== null) {\n if (current === appliesTo) return true;\n current = current in HOST_TYPE_PARENTS ? HOST_TYPE_PARENTS[current] : null;\n }\n return false;\n}\n\n/* ------------------------------------------------------------------- plugin */\n\n/** Hook kinds (v1 §2.2). The hook VOCABULARY is defined by host runtimes;\n * plugins implement subsets of it. */\nexport type Provide<T, C> = (ctx: C) => T | Promise<T>;\nexport type Transform<T, C> = (value: T, ctx: C) => T | Promise<T>;\nexport type Observe<C> = (ctx: C) => void | Promise<void>;\n\n/**\n * Core contributions — declarative, serializable, realm-crossing. Host\n * runtimes extend this with their own kinds (UI slots live in connect-host,\n * never here). `drives` entries use the drive declaration shape from\n * drives.ts; kept as unknown here to avoid a cycle — the merge is shape-blind.\n */\nexport interface Contributions {\n drives?: unknown[];\n packages?: string[];\n configDeclarations?: { name: string; type?: string; description?: string }[];\n [kind: string]: unknown[] | undefined;\n}\n\nexport interface HostPlugin<\n THooks = Record<string, unknown>,\n TConfig = unknown,\n> {\n /** Stable id; used in ordering, dependsOn, and every diagnostic. */\n name: string;\n /** Host-type requirement; the entry is rejected on a host outside the\n * hierarchy branch. Default: \"reactor\". */\n appliesTo?: string;\n /** Coarse ordering bucket (Vite-style). Default: \"normal\". */\n enforce?: \"pre\" | \"post\";\n /** Hard dependencies on OTHER PLUGINS — the host runtime is implied and\n * never named. Missing dependency or cycle fails boot naming both sides. */\n dependsOn?: string[];\n /** Declared config shape; entry config is validated against it. A plugin\n * without a schema accepts no config (passing one is a boot error). */\n configSchema?: z.ZodType<TConfig>;\n hooks?: Partial<THooks>;\n contributions?: Contributions;\n}\n\n/** A plugin module default-exports either a HostPlugin object (no config\n * accepted) or a factory `(config) => HostPlugin`. */\nexport type HostPluginModule<\n THooks = Record<string, unknown>,\n TConfig = unknown,\n> =\n | HostPlugin<THooks, TConfig>\n | ((config: TConfig) => HostPlugin<THooks, TConfig>);\n\nexport interface ResolvedPlugin<THooks = Record<string, unknown>> {\n entry: NormalizedPluginEntry;\n plugin: HostPlugin<THooks>;\n /** Provenance for contribution merge ordering. */\n provenance: \"built-in\" | \"local\" | \"dependency\";\n}\n\n/* ----------------------------------------------------------------- ordering */\n\n/** Registration order, bucketed pre → normal → post (stable within buckets),\n * then dependsOn topo-sorted within the bucketed order. */\nexport function resolveOrder<THooks>(\n plugins: readonly HostPlugin<THooks>[],\n): HostPlugin<THooks>[] {\n const buckets: Record<\"pre\" | \"normal\" | \"post\", HostPlugin<THooks>[]> = {\n pre: [],\n normal: [],\n post: [],\n };\n for (const plugin of plugins)\n buckets[plugin.enforce ?? \"normal\"].push(plugin);\n const bucketed = [...buckets.pre, ...buckets.normal, ...buckets.post];\n\n const byName = new Map(bucketed.map((p) => [p.name, p]));\n for (const plugin of bucketed) {\n for (const dep of plugin.dependsOn ?? []) {\n if (!byName.has(dep)) {\n throw new PluginError(\n `Plugin \"${plugin.name}\" depends on missing plugin \"${dep}\".`,\n \"dependsOn names PLUGINS only — the host runtime is implied and never named.\",\n );\n }\n }\n }\n\n const ordered: HostPlugin<THooks>[] = [];\n const state = new Map<string, \"visiting\" | \"done\">();\n const visit = (plugin: HostPlugin<THooks>, chain: string[]): void => {\n const mark = state.get(plugin.name);\n if (mark === \"done\") return;\n if (mark === \"visiting\") {\n throw new PluginError(\n `Plugin dependency cycle: ${[...chain, plugin.name].join(\" -> \")}.`,\n );\n }\n state.set(plugin.name, \"visiting\");\n for (const dep of plugin.dependsOn ?? []) {\n visit(byName.get(dep)!, [...chain, plugin.name]);\n }\n state.set(plugin.name, \"done\");\n ordered.push(plugin);\n };\n for (const plugin of bucketed) visit(plugin, []);\n return ordered;\n}\n\n/* -------------------------------------------------------------------- hooks */\n\nexport async function runProvideHook<T, C>(\n name: string,\n plugins: readonly HostPlugin[],\n ctx: C,\n): Promise<T | undefined> {\n const impls = plugins.filter((p) => typeof p.hooks?.[name] === \"function\");\n if (impls.length > 1) {\n throw new PluginError(\n `Hook \"${name}\" is provided by ${impls.map((p) => `\"${p.name}\"`).join(\" and \")} — provide hooks have one winner.`,\n );\n }\n const impl = impls[0]?.hooks?.[name] as Provide<T, C> | undefined;\n return impl ? await impl(ctx) : undefined;\n}\n\nexport async function runTransformHook<T, C>(\n name: string,\n plugins: readonly HostPlugin[],\n ctx: C,\n seed: T,\n): Promise<T> {\n let value = seed;\n for (const plugin of plugins) {\n const impl = plugin.hooks?.[name] as Transform<T, C> | undefined;\n if (typeof impl === \"function\") value = await impl(value, ctx);\n }\n return value;\n}\n\n/** Sequential observe, in plugin order — for lifecycle moments whose order\n * is load-bearing (teardown: the switchboard stops privacy before workflows\n * before the api, per the carve map). */\nexport async function runObserveHookSequential<C>(\n name: string,\n plugins: readonly HostPlugin[],\n ctx: C,\n): Promise<void> {\n for (const plugin of plugins) {\n const impl = plugin.hooks?.[name] as Observe<C> | undefined;\n if (typeof impl === \"function\") await impl(ctx);\n }\n}\n\nexport async function runObserveHook<C>(\n name: string,\n plugins: readonly HostPlugin[],\n ctx: C,\n): Promise<void> {\n await Promise.all(\n plugins.map(async (plugin) => {\n const impl = plugin.hooks?.[name] as Observe<C> | undefined;\n if (typeof impl === \"function\") await impl(ctx);\n }),\n );\n}\n\n/* ------------------------------------------------------------ contributions */\n\nexport interface ContributionSource {\n pluginName: string;\n provenance: \"built-in\" | \"local\" | \"dependency\";\n}\n\nexport interface MergedContribution<T = unknown> {\n value: T;\n source: ContributionSource;\n}\n\n/** Array kinds concatenate in provenance-then-order sequence (built-in first,\n * so later sources read as overrides where consumers want last-wins). */\nexport function mergeContributions(\n resolved: readonly {\n plugin: HostPlugin;\n provenance: ContributionSource[\"provenance\"];\n }[],\n): Record<string, MergedContribution[]> {\n const rank: Record<ContributionSource[\"provenance\"], number> = {\n \"built-in\": 0,\n local: 1,\n dependency: 2,\n };\n const sorted = [...resolved].sort(\n (a, b) => rank[a.provenance] - rank[b.provenance],\n );\n const merged: Record<string, MergedContribution[]> = {};\n for (const { plugin, provenance } of sorted) {\n for (const [kind, values] of Object.entries(plugin.contributions ?? {})) {\n if (!values) continue;\n const bucket = (merged[kind] ??= []);\n for (const value of values) {\n bucket.push({ value, source: { pluginName: plugin.name, provenance } });\n }\n }\n }\n return merged;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmBA,IAAa,cAAb,cAAiC,MAAM;CACrC,YAAY,SAAiB,MAAe;EAC1C,MAAM,OAAO,GAAG,QAAQ,YAAY,SAAS,OAAO;EACpD,KAAK,OAAO;CACd;AACF;AAIA,MAAa,0BAA0B,EAAE,aAAa;CACpD,QAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;;CAExB,SAAS,EAAE,QAAQ,CAAC,CAAC,SAAS;;CAE9B,OAAO,EACJ,MAAM,CAAC,EAAE,QAAQ,GAAG,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAC1D,SAAS;;CAEZ,QAAQ,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,SAAS;AACrD,CAAC;AAED,MAAa,oBAAoB,EAAE,MAAM,CACvC,EAAE,OAAO,CAAC,CAA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sourcesContent":["import { z } from \"zod\";\n\n/**\n * R1 — the host plugin framework (bridge-runners-to-plugins plan,\n * customization-references/host-core as the blueprint).\n *\n * A plugin is hooks + contributions; hooks are boot wiring (main realm only),\n * contributions are declarative, serializable surface. Host RUNTIMES define\n * the hook vocabulary and interleave their own wiring between stages — they\n * are never plugins themselves.\n *\n * host.js carries the COMPOSITION as `runner.plugins` entries:\n * string | { module, enabled?, verbs?, config? }\n * Presence is activation (enabled defaults true); `verbs` scopes an entry to\n * matching run verbs; `config` is validated against the plugin's declared\n * zod schema. Entries resolve from the PROJECT's dependency tree exactly\n * like runner modules.\n */\n\nexport class PluginError extends Error {\n constructor(message: string, hint?: string) {\n super(hint ? `${message}\\n Hint: ${hint}` : message);\n this.name = \"PluginError\";\n }\n}\n\n/* ------------------------------------------------------------------ entries */\n\nexport const pluginEntryObjectSchema = z.strictObject({\n module: z.string().min(1),\n /** Presence is activation BY DEFAULT; false is the explicit off-switch. */\n enabled: z.boolean().optional(),\n /** \"*\" (default) or the run verbs this entry is active for. */\n verbs: z\n .union([z.literal(\"*\"), z.array(z.string().min(1)).min(1)])\n .optional(),\n /** Validated against the plugin's declared configSchema at resolution. */\n config: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport const pluginEntrySchema = z.union([\n z.string().min(1),\n pluginEntryObjectSchema,\n]);\n\n/** The validated (runtime) entry shape. Authors write `PluginEntry`\n * (host-types.ts), which types known plugins' configs. */\nexport type PluginEntryData = z.infer<typeof pluginEntrySchema>;\nexport type { PluginEntry } from \"./host-types.js\";\n\nexport interface NormalizedPluginEntry {\n module: string;\n enabled: boolean;\n verbs: \"*\" | string[];\n config: Record<string, unknown>;\n}\n\nexport function normalizePluginEntry(\n entry: PluginEntryData,\n): NormalizedPluginEntry {\n if (typeof entry === \"string\") {\n return { module: entry, enabled: true, verbs: \"*\", config: {} };\n }\n return {\n module: entry.module,\n enabled: entry.enabled ?? true,\n verbs: entry.verbs ?? \"*\",\n config: entry.config ?? {},\n };\n}\n\n/** Module is the identity key: a duplicate makes override targeting and\n * ordering ambiguous, so it fails loudly. */\nexport function normalizePluginEntries(\n entries: readonly PluginEntryData[],\n where: string,\n): NormalizedPluginEntry[] {\n const normalized = entries.map(normalizePluginEntry);\n const seen = new Set<string>();\n for (const entry of normalized) {\n if (seen.has(entry.module)) {\n throw new PluginError(\n `${where}: plugin \"${entry.module}\" is listed twice.`,\n \"Module specifiers are the identity key of a composition; a plugin meant to run twice needs distinct subpath specifiers.\",\n );\n }\n seen.add(entry.module);\n }\n return normalized;\n}\n\nexport function entryActiveForVerb(\n entry: NormalizedPluginEntry,\n verb: string,\n): boolean {\n if (!entry.enabled) return false;\n return entry.verbs === \"*\" || entry.verbs.includes(verb);\n}\n\n/* ---------------------------------------------------------------- hierarchy */\n\n/**\n * The appliesTo hierarchy. \"reactor\" is the base every reactor host extends;\n * \"compound\" is its own branch (plugins over the member set — e.g. the clint\n * proxy). Host runtimes register their id with a parent; compatibility walks\n * the parent chain.\n */\nconst HOST_TYPE_PARENTS: Record<string, string | null> = {\n reactor: null,\n compound: null,\n connect: \"reactor\",\n switchboard: \"reactor\",\n mastra: \"reactor\",\n};\n\nexport function registerHostType(id: string, parent: string | null): void {\n if (id in HOST_TYPE_PARENTS && HOST_TYPE_PARENTS[id] !== parent) {\n throw new PluginError(\n `Host type \"${id}\" is already registered with parent \"${String(HOST_TYPE_PARENTS[id])}\".`,\n );\n }\n HOST_TYPE_PARENTS[id] = parent;\n}\n\nexport function hostTypeSatisfies(\n hostType: string,\n appliesTo: string,\n): boolean {\n let current: string | null = hostType;\n while (current !== null) {\n if (current === appliesTo) return true;\n current = current in HOST_TYPE_PARENTS ? HOST_TYPE_PARENTS[current] : null;\n }\n return false;\n}\n\n/* ------------------------------------------------------------------- plugin */\n\n/** Hook kinds (v1 §2.2). The hook VOCABULARY is defined by host runtimes;\n * plugins implement subsets of it. */\nexport type Provide<T, C> = (ctx: C) => T | Promise<T>;\nexport type Transform<T, C> = (value: T, ctx: C) => T | Promise<T>;\nexport type Observe<C> = (ctx: C) => void | Promise<void>;\n\n/**\n * Core contributions — declarative, serializable, realm-crossing. Host\n * runtimes extend this with their own kinds (UI slots live in connect-host,\n * never here). `drives` entries use the drive declaration shape from\n * drives.ts; kept as unknown here to avoid a cycle — the merge is shape-blind.\n */\nexport interface Contributions {\n drives?: unknown[];\n packages?: string[];\n configDeclarations?: { name: string; type?: string; description?: string }[];\n [kind: string]: unknown[] | undefined;\n}\n\nexport interface HostPlugin<\n THooks = Record<string, unknown>,\n TConfig = unknown,\n> {\n /** Stable id; used in ordering, dependsOn, and every diagnostic. */\n name: string;\n /** Host-type requirement; the entry is rejected on a host outside the\n * hierarchy branch. Default: \"reactor\". */\n appliesTo?: string;\n /** Coarse ordering bucket (Vite-style). Default: \"normal\". */\n enforce?: \"pre\" | \"post\";\n /** Hard dependencies on OTHER PLUGINS — the host runtime is implied and\n * never named. Missing dependency or cycle fails boot naming both sides. */\n dependsOn?: string[];\n /** Declared config shape; entry config is validated against it. A plugin\n * without a schema accepts no config (passing one is a boot error). */\n configSchema?: z.ZodType<TConfig>;\n hooks?: Partial<THooks>;\n contributions?: Contributions;\n}\n\n/** A plugin module default-exports either a HostPlugin object (no config\n * accepted) or a factory `(config) => HostPlugin`. */\nexport type HostPluginModule<\n THooks = Record<string, unknown>,\n TConfig = unknown,\n> =\n | HostPlugin<THooks, TConfig>\n | ((config: TConfig) => HostPlugin<THooks, TConfig>);\n\nexport interface ResolvedPlugin<THooks = Record<string, unknown>> {\n entry: NormalizedPluginEntry;\n plugin: HostPlugin<THooks>;\n /** Provenance for contribution merge ordering. */\n provenance: \"built-in\" | \"local\" | \"dependency\";\n}\n\n/* ----------------------------------------------------------------- ordering */\n\n/** Registration order, bucketed pre → normal → post (stable within buckets),\n * then dependsOn topo-sorted within the bucketed order. */\nexport function resolveOrder<THooks>(\n plugins: readonly HostPlugin<THooks>[],\n): HostPlugin<THooks>[] {\n const buckets: Record<\"pre\" | \"normal\" | \"post\", HostPlugin<THooks>[]> = {\n pre: [],\n normal: [],\n post: [],\n };\n for (const plugin of plugins)\n buckets[plugin.enforce ?? \"normal\"].push(plugin);\n const bucketed = [...buckets.pre, ...buckets.normal, ...buckets.post];\n\n const byName = new Map(bucketed.map((p) => [p.name, p]));\n for (const plugin of bucketed) {\n for (const dep of plugin.dependsOn ?? []) {\n if (!byName.has(dep)) {\n throw new PluginError(\n `Plugin \"${plugin.name}\" depends on missing plugin \"${dep}\".`,\n \"dependsOn names PLUGINS only — the host runtime is implied and never named.\",\n );\n }\n }\n }\n\n const ordered: HostPlugin<THooks>[] = [];\n const state = new Map<string, \"visiting\" | \"done\">();\n const visit = (plugin: HostPlugin<THooks>, chain: string[]): void => {\n const mark = state.get(plugin.name);\n if (mark === \"done\") return;\n if (mark === \"visiting\") {\n throw new PluginError(\n `Plugin dependency cycle: ${[...chain, plugin.name].join(\" -> \")}.`,\n );\n }\n state.set(plugin.name, \"visiting\");\n for (const dep of plugin.dependsOn ?? []) {\n visit(byName.get(dep)!, [...chain, plugin.name]);\n }\n state.set(plugin.name, \"done\");\n ordered.push(plugin);\n };\n for (const plugin of bucketed) visit(plugin, []);\n return ordered;\n}\n\n/* -------------------------------------------------------------------- hooks */\n\nexport async function runProvideHook<T, C>(\n name: string,\n plugins: readonly HostPlugin[],\n ctx: C,\n): Promise<T | undefined> {\n const impls = plugins.filter((p) => typeof p.hooks?.[name] === \"function\");\n if (impls.length > 1) {\n throw new PluginError(\n `Hook \"${name}\" is provided by ${impls.map((p) => `\"${p.name}\"`).join(\" and \")} — provide hooks have one winner.`,\n );\n }\n const impl = impls[0]?.hooks?.[name] as Provide<T, C> | undefined;\n return impl ? await impl(ctx) : undefined;\n}\n\nexport async function runTransformHook<T, C>(\n name: string,\n plugins: readonly HostPlugin[],\n ctx: C,\n seed: T,\n): Promise<T> {\n let value = seed;\n for (const plugin of plugins) {\n const impl = plugin.hooks?.[name] as Transform<T, C> | undefined;\n if (typeof impl === \"function\") value = await impl(value, ctx);\n }\n return value;\n}\n\n/** Sequential observe, in plugin order — for lifecycle moments whose order\n * is load-bearing (teardown: the switchboard stops privacy before workflows\n * before the api, per the carve map). */\nexport async function runObserveHookSequential<C>(\n name: string,\n plugins: readonly HostPlugin[],\n ctx: C,\n): Promise<void> {\n for (const plugin of plugins) {\n const impl = plugin.hooks?.[name] as Observe<C> | undefined;\n if (typeof impl === \"function\") await impl(ctx);\n }\n}\n\nexport async function runObserveHook<C>(\n name: string,\n plugins: readonly HostPlugin[],\n ctx: C,\n): Promise<void> {\n await Promise.all(\n plugins.map(async (plugin) => {\n const impl = plugin.hooks?.[name] as Observe<C> | undefined;\n if (typeof impl === \"function\") await impl(ctx);\n }),\n );\n}\n\n/* ------------------------------------------------------------ contributions */\n\nexport interface ContributionSource {\n pluginName: string;\n provenance: \"built-in\" | \"local\" | \"dependency\";\n}\n\nexport interface MergedContribution<T = unknown> {\n value: T;\n source: ContributionSource;\n}\n\n/** Array kinds concatenate in provenance-then-order sequence (built-in first,\n * so later sources read as overrides where consumers want last-wins). */\nexport function mergeContributions(\n resolved: readonly {\n plugin: HostPlugin;\n provenance: ContributionSource[\"provenance\"];\n }[],\n): Record<string, MergedContribution[]> {\n const rank: Record<ContributionSource[\"provenance\"], number> = {\n \"built-in\": 0,\n local: 1,\n dependency: 2,\n };\n const sorted = [...resolved].sort(\n (a, b) => rank[a.provenance] - rank[b.provenance],\n );\n const merged: Record<string, MergedContribution[]> = {};\n for (const { plugin, provenance } of sorted) {\n for (const [kind, values] of Object.entries(plugin.contributions ?? {})) {\n if (!values) continue;\n const bucket = (merged[kind] ??= []);\n for (const value of values) {\n bucket.push({ value, source: { pluginName: plugin.name, provenance } });\n }\n }\n }\n return merged;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmBA,IAAa,cAAb,cAAiC,MAAM;CACrC,YAAY,SAAiB,MAAe;EAC1C,MAAM,OAAO,GAAG,QAAQ,YAAY,SAAS,OAAO;EACpD,KAAK,OAAO;CACd;AACF;AA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