@powerhousedao/host-core 6.2.3-dev.82 → 6.2.3-dev.84

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.
@@ -1 +1 @@
1
- {"version":3,"file":"projection.mjs","names":[],"sources":["../src/reactor-config.ts","../src/backend-projection.ts","../src/child-wrapper.ts","../src/connect-projection.ts","../src/run-record-schema.ts","../src/resolve/walk.ts","../src/resolve/declared.ts","../src/resolve/plan.ts","../src/resolve/resolve.ts","../src/resolve/removed-forms.ts","../src/resolve/sources.ts","../src/expect-host.ts"],"sourcesContent":["/**\n * The shared `reactor` host-config block and its projections onto the\n * Switchboard config / 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\n/** The switchboard config layer a reactor block maps to (the shape of\n * `@powerhousedao/switchboard/config`'s input). Only keys the block sets. */\nexport interface SwitchboardReactorLayer {\n storage?: { reactor?: { url: string }; readModel?: { url: string } };\n protocol?: ReactorProtocol;\n packages?: { dynamic: true };\n features?: { workflows: boolean };\n}\n\n/** The reactor block as a switchboard config layer. The reactor store and the\n * read model are separate fields: `readModel.url` never moves the reactor. */\nexport function reactorBlockToSwitchboardConfig(\n reactor: ReactorConfig | undefined,\n): SwitchboardReactorLayer {\n const layer: SwitchboardReactorLayer = {};\n const backend = primaryBackend(reactor);\n const storage = backend?.storage;\n const reactorUrl =\n storage?.kind === \"postgres\" ? storage.url : storage?.dataDir;\n const readModelUrl = backend?.readModel?.url;\n if (reactorUrl || readModelUrl) {\n layer.storage = {\n ...(reactorUrl ? { reactor: { url: reactorUrl } } : {}),\n ...(readModelUrl ? { readModel: { url: readModelUrl } } : {}),\n };\n }\n if (reactor?.protocol) layer.protocol = reactor.protocol;\n if (backend?.packages?.dynamic) layer.packages = { dynamic: true };\n if (reactor?.workflows !== undefined) {\n layer.features = { workflows: reactor.workflows };\n }\n return layer;\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/** Each pre-set env var that CONTRADICTS the host's protocol block, as a\n * message naming the var, the host value and the env value. An env var that\n * merely matches, or is unset, is fine. */\nexport function protocolConflicts(\n protocol: ReactorProtocol | undefined,\n env: Readonly<Record<string, string | undefined>>,\n hostFile = \"the host file\",\n): string[] {\n if (!protocol) return [];\n return Object.entries(protocolEnv(protocol)).flatMap(\n ([varName, hostValue]) => {\n const envValue = env[varName];\n if (envValue === undefined || envValue === hostValue) return [];\n return [\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\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 (phase-2 transition keeps an operator's explicit env as an\n * escape hatch unless it disagrees with the protocol — see the WBS\n * precedence note).\n */\nexport function assertProtocolConsistency(\n protocol: ReactorProtocol | undefined,\n env: Record<string, string | undefined>,\n hostFile = \"the host file\",\n): void {\n const conflict = protocolConflicts(protocol, env, hostFile).at(0);\n if (conflict) throw new Error(conflict);\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' drive addresses, placement order. */\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 { ChildWrapper, HostDefinition } from \"./host-schemas.js\";\n\n/** A member's host.js with its wrapper applied, tokens unresolved. */\nexport type MemberDraft = Record<string, unknown> & {\n name: string;\n runner: HostDefinition[\"runner\"];\n};\n\n/** Generic compound rule: `reactor`/`config` replace, `runner` key-merges. */\nexport function applyChildWrapper(\n base: HostDefinition,\n wrapper: ChildWrapper,\n): MemberDraft {\n const reactor = wrapper.reactor ?? base.reactor;\n const config = wrapper.config ?? base.config;\n return {\n ...base,\n runner: { ...base.runner, ...wrapper.runner },\n ...(config !== undefined ? { config } : {}),\n ...(reactor !== undefined ? { reactor } : {}),\n };\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 { z } from \"zod\";\nimport { hostNameSchema, runnerKindSchema } from \"./host-schemas.js\";\n\n/**\n * `.ph/run/<host>.json`, version 2 (typed-host-configs 3.6): what a running\n * host and its members produced. Validated on read; a v1 (or any invalid)\n * record reads as \"not running\". `projectName` is kept beyond the plan's\n * sketch because the live/foreign probe needs it. `host` is the host's\n * `name` (the file key), not its folder.\n */\n\nconst outputsSchema = z.record(z.string(), z.unknown());\n\nexport const runRecordMemberSchema = z.strictObject({\n /** The member's host folder (`children.<key>.host`). */\n host: z.string().min(1),\n runnerModule: z.string().min(1),\n kind: runnerKindSchema,\n verb: z.string().min(1),\n outputs: outputsSchema,\n});\n\nexport const runRecordSchema = z.strictObject({\n version: z.literal(2),\n host: hostNameSchema,\n projectName: z.string(),\n kind: runnerKindSchema,\n verb: z.string().min(1),\n pid: z.number().int(),\n startedAt: z.string(),\n /** Standalone hosts: the runner's outputs. */\n outputs: outputsSchema.optional(),\n /** Compounds: one entry per started member, keyed by member name. */\n members: z.record(z.string(), runRecordMemberSchema).optional(),\n /** Host-specific extras (e.g. mcpUrl) a runner wants in the record. */\n extra: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport type RunRecord = z.infer<typeof runRecordSchema>;\nexport type RunRecordMember = z.infer<typeof runRecordMemberSchema>;\n","import {\n TOKEN_ESCAPE_KEY,\n tokenKeyOf,\n type OutputPath,\n type TokenKey,\n} from \"../tokens.js\";\n\n/**\n * Token discovery over a declared (JSON-shaped) host: where every operator\n * sits and in which syntactic position, which is what declared validation\n * (`$env` optional placement), the dependency plan and `--explain outputs`\n * read. Pure: no node imports.\n */\n\n/** Where a token sits: the direct value of an object property, an array\n * element, the whole value, a `$concat` part, a `$map`'s `over`, or the\n * whole `to` template of a `$map` (the top of the rendered element). */\nexport type TokenPosition =\n | \"property\"\n | \"element\"\n | \"root\"\n | \"concat\"\n | \"over\"\n | \"template\";\n\n/** An enclosing `$map`, as seen from a token inside its `to` template. */\nexport interface MapScope {\n /** Host path of the `$map` token. */\n path: OutputPath;\n /** Its binding name (`$map.as`), if any. */\n as?: string;\n /** The `$map` token itself. */\n token: Record<string, unknown>;\n}\n\nexport interface TokenSite {\n /** Property keys and array indices from the host root to the token\n * (`$map` operands appear as `…$map.over` / `…$map.to…`). */\n path: OutputPath;\n key: TokenKey;\n /** The token object itself (`{ $output: … }`, …). */\n token: Record<string, unknown>;\n position: TokenPosition;\n /** The `$map`s whose template holds this token, outermost first (the\n * innermost binding is last). A map's own `over` is in its OUTER scope. */\n scopes: readonly MapScope[];\n}\n\nexport function isPlainObject(\n value: unknown,\n): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n return false;\n }\n const proto: unknown = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/** `a.b[2].c` (or `<root>`). */\nexport function formatPath(path: readonly (string | number)[]): string {\n let out = \"\";\n for (const segment of path) {\n if (typeof segment === \"number\") out += `[${segment}]`;\n else out += out ? `.${segment}` : segment;\n }\n return out || \"<root>\";\n}\n\n/** Is this object a `$$` escape (`{ $$: literal }`)? */\nexport function isEscape(value: Record<string, unknown>): boolean {\n const keys = Object.keys(value);\n return keys.length === 1 && keys[0] === TOKEN_ESCAPE_KEY;\n}\n\n/** Every token in `value`, in document order. `$concat` parts and `$map`\n * operands (`over`, then the `to` template) are visited: they may hold tokens\n * themselves. Each site carries the `$map` scopes it sits in. A `$$` escape\n * hides its operand. */\nexport function collectTokenSites(value: unknown): TokenSite[] {\n const sites: TokenSite[] = [];\n visit(value, [], \"root\", [], sites);\n return sites;\n}\n\nfunction visit(\n value: unknown,\n path: OutputPath,\n position: TokenPosition,\n scopes: readonly MapScope[],\n sites: TokenSite[],\n): void {\n const key = tokenKeyOf(value);\n if (key && isPlainObject(value)) {\n sites.push({ path, key, token: value, position, scopes });\n const operand = value[key];\n if (key === \"$concat\" && Array.isArray(operand)) {\n operand.forEach((part: unknown, index) =>\n visit(part, [...path, \"$concat\", index], \"concat\", scopes, sites),\n );\n }\n if (key === \"$map\" && isPlainObject(operand)) {\n const at = [...path, \"$map\"];\n // `over` is evaluated in the enclosing scope; only `to` sees this map.\n if (\"over\" in operand) {\n visit(operand.over, [...at, \"over\"], \"over\", scopes, sites);\n }\n if (\"to\" in operand) {\n const scope: MapScope = {\n path,\n token: value,\n ...(typeof operand.as === \"string\" ? { as: operand.as } : {}),\n };\n visit(operand.to, [...at, \"to\"], \"template\", [...scopes, scope], sites);\n }\n }\n return;\n }\n if (Array.isArray(value)) {\n value.forEach((child: unknown, index) =>\n visit(child, [...path, index], \"element\", scopes, sites),\n );\n return;\n }\n if (!isPlainObject(value) || isEscape(value)) return;\n for (const [childKey, child] of Object.entries(value)) {\n visit(child, [...path, childKey], \"property\", scopes, sites);\n }\n}\n\n/** An `$item` path as text: `url`, `drives.x`, `<element>` for `[]`. */\nfunction pathText(path: readonly unknown[]): string {\n if (path.length === 0) return \"<element>\";\n return formatPath(\n path.filter(\n (p): p is string | number =>\n typeof p === \"string\" || typeof p === \"number\",\n ),\n );\n}\n\n/** A one-line human rendering of a token, for `--explain` and messages. */\nexport function describeToken(token: unknown): string {\n const key = tokenKeyOf(token);\n if (!key || !isPlainObject(token)) return JSON.stringify(token);\n const operand = token[key];\n if (key === \"$output\" && isPlainObject(operand)) {\n const host = typeof operand.host === \"string\" ? operand.host : \"?\";\n const member =\n typeof operand.member === \"string\" ? ` (member ${operand.member})` : \"\";\n const path = Array.isArray(operand.path)\n ? formatPath(\n operand.path.filter(\n (p): p is string | number =>\n typeof p === \"string\" || typeof p === \"number\",\n ),\n )\n : \"?\";\n return `$output ${host}${member} › ${path}`;\n }\n if (key === \"$env\") {\n if (typeof operand === \"string\") return `$env ${operand}`;\n if (isPlainObject(operand) && typeof operand.name === \"string\") {\n return `$env ${operand.name} (optional)`;\n }\n }\n if (key === \"$item\") {\n const named = isPlainObject(operand) ? operand : undefined;\n const raw: unknown = named ? named.path : operand;\n const path = Array.isArray(raw) ? pathText(raw) : \"?\";\n const binding =\n named && typeof named.as === \"string\" ? `(${named.as})` : \"\";\n return `$item${binding} ${path}`;\n }\n if (key === \"$key\") {\n return typeof operand === \"string\" ? `$key(${operand})` : \"$key\";\n }\n if (key === \"$map\" && isPlainObject(operand)) {\n const as = typeof operand.as === \"string\" ? ` as ${operand.as}` : \"\";\n const into = operand.into === \"record\" ? \" into record\" : \"\";\n return `$map over [${describeToken(operand.over)}]${as}${into} → ${JSON.stringify(render(operand.to))}`;\n }\n if (key === \"$concat\" && Array.isArray(operand)) {\n const parts = operand.map((part: unknown) =>\n typeof part === \"string\"\n ? JSON.stringify(part)\n : typeof part === \"number\"\n ? String(part)\n : `[${describeToken(part)}]`,\n );\n return `$concat ${parts.join(\" + \")}`;\n }\n return `${key} ${JSON.stringify(operand)}`;\n}\n\n/** A display copy of `value` with every token replaced by `«description»`\n * (for printing declared hosts, e.g. `--explain drives`). */\nexport function renderTokens<T>(value: T): T {\n return render(value) as T;\n}\n\nfunction render(value: unknown): unknown {\n if (tokenKeyOf(value)) return `«${describeToken(value)}»`;\n if (Array.isArray(value)) return value.map(render);\n if (!isPlainObject(value) || isEscape(value)) return value;\n const out: Record<string, unknown> = {};\n for (const [key, child] of Object.entries(value)) out[key] = render(child);\n return out;\n}\n\n/** A copy of `value` with every `$$` escape replaced by its operand (the\n * literal it protects). Run after the no-token walk. */\nexport function unwrapEscapes<T>(value: T): T {\n return unwrap(value) as T;\n}\n\nfunction unwrap(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(unwrap);\n if (!isPlainObject(value)) return value;\n if (isEscape(value)) return structuredClone(value[TOKEN_ESCAPE_KEY]);\n const out: Record<string, unknown> = {};\n for (const [key, child] of Object.entries(value)) out[key] = unwrap(child);\n return out;\n}\n","import { tokenSchema, type OutputPath } from \"../tokens.js\";\nimport {\n collectTokenSites,\n describeToken,\n formatPath,\n isPlainObject,\n type MapScope,\n type TokenSite,\n} from \"./walk.js\";\n\n/**\n * Declared validation (pipeline step 3) of a host's tokens, before anything\n * runs: operator shapes, `$env` `optional` placement, and every `$output`\n * path against the producer's `outputsSchema`. No environment value is read\n * and no producer needs to be running. Pure: producers are looked up through\n * a callback the node side fills.\n */\n\n/** Which host's outputs a `$output` token names: `host` is the producer's\n * FOLDER (`hosts/<host>/`); `member` picks one compound member when two\n * share a host. */\nexport interface OutputRef {\n host: string;\n member?: string;\n}\n\nexport interface DeclaredIssue {\n /** Host path of the token (`runner.plugins[0].config.drive`). */\n path: string;\n message: string;\n}\n\nfunction refOf(site: TokenSite): OutputRef | undefined {\n const operand = site.token.$output;\n if (!isPlainObject(operand) || typeof operand.host !== \"string\") {\n return undefined;\n }\n return typeof operand.member === \"string\"\n ? { host: operand.host, member: operand.member }\n : { host: operand.host };\n}\n\nfunction pathOf(site: TokenSite): OutputPath {\n const operand = site.token.$output;\n if (!isPlainObject(operand) || !Array.isArray(operand.path)) return [];\n return operand.path.filter(\n (p): p is string | number => typeof p === \"string\" || typeof p === \"number\",\n );\n}\n\nexport function refKey(ref: OutputRef): string {\n return ref.member ? `${ref.host}#${ref.member}` : ref.host;\n}\n\n/** The distinct producers a host's `$output` tokens name, in document order. */\nexport function outputRefsOf(host: unknown): OutputRef[] {\n const seen = new Map<string, OutputRef>();\n for (const site of collectTokenSites(host)) {\n if (site.key !== \"$output\") continue;\n const ref = refOf(site);\n if (ref && !seen.has(refKey(ref))) seen.set(refKey(ref), ref);\n }\n return [...seen.values()];\n}\n\n/** Every `$output` token with its host path and producer (for the plan and\n * `--explain outputs`). */\nexport function outputSitesOf(\n host: unknown,\n): { path: string; ref: OutputRef; outputPath: OutputPath }[] {\n return collectTokenSites(host).flatMap((site) => {\n if (site.key !== \"$output\") return [];\n const ref = refOf(site);\n return ref\n ? [{ path: formatPath(site.path), ref, outputPath: pathOf(site) }]\n : [];\n });\n}\n\n/** Every `$env` token with its host path (for `--explain outputs`). */\nexport function envSitesOf(\n host: unknown,\n): { path: string; name: string; optional: boolean }[] {\n return collectTokenSites(host).flatMap(\n (\n site,\n ): {\n path: string;\n name: string;\n optional: boolean;\n }[] => {\n if (site.key !== \"$env\") return [];\n const operand = site.token.$env;\n if (typeof operand === \"string\") {\n return [\n { path: formatPath(site.path), name: operand, optional: false },\n ];\n }\n if (isPlainObject(operand) && typeof operand.name === \"string\") {\n return [\n { path: formatPath(site.path), name: operand.name, optional: true },\n ];\n }\n return [];\n },\n );\n}\n\n/** The binding name an `$item`/`$key` site names (undefined: innermost). */\nfunction bindingNameOf(site: TokenSite): string | undefined {\n const operand = site.token[site.key];\n if (site.key === \"$key\")\n return typeof operand === \"string\" ? operand : undefined;\n if (site.key === \"$item\" && isPlainObject(operand)) {\n return typeof operand.as === \"string\" ? operand.as : undefined;\n }\n return undefined;\n}\n\n/** The enclosing `$map` an `$item`/`$key` site binds to, or why none. */\nfunction scopeOf(site: TokenSite): MapScope | { error: string } {\n const name = bindingNameOf(site);\n if (site.scopes.length === 0) {\n return {\n error: `${site.key} is used outside any $map; it reads the element a $map template is rendering, so it is legal only inside a $map's \\`to\\` (or a nested $map's \\`over\\`).`,\n };\n }\n if (name === undefined) return site.scopes[site.scopes.length - 1];\n for (let i = site.scopes.length - 1; i >= 0; i--) {\n if (site.scopes[i].as === name) return site.scopes[i];\n }\n const named = site.scopes.flatMap((s) => (s.as ? [`\"${s.as}\"`] : []));\n return {\n error: `${describeToken(site.token)} names the $map binding \"${name}\", which no enclosing $map declares (enclosing bindings: ${named.join(\", \") || 'none; add as: \"' + name + '\" to the outer $map'}).`,\n };\n}\n\n/** Item path of an `$item` site. */\nfunction itemPathOf(site: TokenSite): OutputPath {\n const operand = site.token.$item;\n const raw: unknown = isPlainObject(operand) ? operand.path : operand;\n return Array.isArray(raw)\n ? raw.filter(\n (p): p is string | number =>\n typeof p === \"string\" || typeof p === \"number\",\n )\n : [];\n}\n\n/** Operator shapes and placement: malformed operands, `$item`/`$key`\n * outside any `$map` or naming an unknown binding, and\n * `{ $env: { name, optional: true } }` anywhere but the direct value of an\n * object property (it omits that property when unset). */\nexport function checkTokenSites(host: unknown): DeclaredIssue[] {\n const issues: DeclaredIssue[] = [];\n for (const site of collectTokenSites(host)) {\n const path = formatPath(site.path);\n if (!tokenSchema.safeParse(site.token).success) {\n issues.push({\n path,\n message: `malformed ${site.key} token ${JSON.stringify(site.token)}. Shapes: { $output: { host, member?, path: [...] } }, { $concat: [string | number | token, ...] }, { $env: \"NAME\" } or { $env: { name: \"NAME\", optional: true } }, { $map: { over: $output | $item, as?: \"name\", to: template, into?: \"record\" } }, { $item: [path] } or { $item: { as: \"name\", path: [...] } }, { $key: true } or { $key: \"name\" }.`,\n });\n continue;\n }\n if (site.key === \"$item\" || site.key === \"$key\") {\n const scope = scopeOf(site);\n if (\"error\" in scope) issues.push({ path, message: scope.error });\n continue;\n }\n const operand = site.token.$env;\n if (\n site.key === \"$env\" &&\n isPlainObject(operand) &&\n site.position !== \"property\"\n ) {\n const where =\n site.position === \"concat\"\n ? \"a $concat part\"\n : site.position === \"element\"\n ? \"an array element\"\n : site.position === \"template\"\n ? \"the whole $map template\"\n : \"the whole host\";\n issues.push({\n path,\n message: `{ $env: { name, optional: true } } is legal only as the direct value of an object property (it omits that property when ${String(operand.name)} is unset), not as ${where}. Use { $env: ${JSON.stringify(operand.name)} } here.`,\n });\n }\n }\n return issues;\n}\n\n/* ------------------------------------------------------- output path check */\n\n/** What a producer lookup yields: its runner's `outputsSchema` (any zod\n * instance), or why there is none. */\nexport type OutputsSchemaLookup =\n | { schema: unknown; label: string }\n | { error: string };\n\ntype ZodDef = Record<string, unknown> & { type: string };\n\nfunction defOf(schema: unknown): ZodDef | undefined {\n if (!isPlainObjectLike(schema)) return undefined;\n const internals = schema._zod;\n if (!isPlainObjectLike(internals)) return undefined;\n const def = internals.def;\n if (!isPlainObjectLike(def) || typeof def.type !== \"string\") return undefined;\n return { ...def, type: def.type };\n}\n\n// zod schemas are class instances, so \"plain object\" is too strict here.\nfunction isPlainObjectLike(value: unknown): value is Record<string, unknown> {\n return (\n (typeof value === \"object\" || typeof value === \"function\") && value !== null\n );\n}\n\nconst WRAPPERS = new Set([\n \"optional\",\n \"nullable\",\n \"default\",\n \"prefault\",\n \"readonly\",\n \"nonoptional\",\n \"catch\",\n \"success\",\n]);\n\n/** The schema at `path` inside a zod schema (walking objects, records,\n * arrays, tuples, unions and wrappers), or why the path does not exist. */\nexport function schemaAtPath(\n schema: unknown,\n path: OutputPath,\n): { ok: true; schema: unknown } | { ok: false; at: number; reason: string } {\n let current = schema;\n for (let i = 0; i <= path.length; i++) {\n // unwrap\n for (let guard = 0; guard < 32; guard++) {\n const def = defOf(current);\n if (!def) break;\n if (WRAPPERS.has(def.type)) current = def.innerType;\n else if (def.type === \"lazy\" && typeof def.getter === \"function\") {\n const getter = def.getter as () => unknown;\n current = getter();\n } else if (def.type === \"pipe\") {\n const out = defOf(def.out);\n current = out && out.type !== \"transform\" ? def.out : def.in;\n } else break;\n }\n if (i === path.length) return { ok: true, schema: current };\n const segment = path[i];\n const def = defOf(current);\n if (!def) return { ok: false, at: i, reason: \"is not a schema\" };\n switch (def.type) {\n case \"any\":\n case \"unknown\":\n return { ok: true, schema: current };\n case \"object\": {\n const shape = isPlainObjectLike(def.shape) ? def.shape : {};\n if (typeof segment === \"string\" && segment in shape) {\n current = shape[segment];\n break;\n }\n const catchall = defOf(def.catchall);\n if (catchall && catchall.type !== \"never\") {\n current = def.catchall;\n break;\n }\n const keys = Object.keys(shape);\n return {\n ok: false,\n at: i,\n reason: `has no key ${JSON.stringify(segment)} (keys: ${keys.join(\", \") || \"none\"})`,\n };\n }\n case \"record\":\n if (typeof segment !== \"string\") {\n return { ok: false, at: i, reason: \"is a record (string keys)\" };\n }\n current = def.valueType;\n break;\n case \"array\":\n if (typeof segment !== \"number\") {\n return { ok: false, at: i, reason: \"is an array (numeric index)\" };\n }\n current = def.element;\n break;\n case \"tuple\": {\n const items = Array.isArray(def.items) ? def.items : [];\n if (typeof segment !== \"number\" || segment >= items.length) {\n return { ok: false, at: i, reason: `is a ${items.length}-tuple` };\n }\n current = items[segment];\n break;\n }\n case \"union\": {\n const options = Array.isArray(def.options) ? def.options : [];\n for (const option of options) {\n const hit = schemaAtPath(option, path.slice(i));\n if (hit.ok) return hit;\n }\n return { ok: false, at: i, reason: \"matches no union member\" };\n }\n default:\n return {\n ok: false,\n at: i,\n reason: `is a ${def.type}, not a container`,\n };\n }\n }\n return { ok: true, schema: current };\n}\n\n/** Whether the object schema at `path` names `key` in its shape (a\n * catchall does not count): what a runner's schema explicitly declares,\n * e.g. `runner.cspRegistrySync`. A union declares a key any member does. */\nexport function declaresKey(\n schema: unknown,\n path: OutputPath,\n key: string,\n): boolean {\n const at = schemaAtPath(schema, path);\n if (!at.ok) return false;\n const def = defOf(at.schema);\n if (def?.type === \"object\") {\n return isPlainObjectLike(def.shape) && key in def.shape;\n }\n if (def?.type === \"union\" && Array.isArray(def.options)) {\n return def.options.some((option: unknown) => declaresKey(option, [], key));\n }\n return false;\n}\n\n/** Whether a (property) schema admits an absent value on the OUTPUT side:\n * `.optional()` does; `.default()`/`.prefault()` fill it in, and\n * `.nonoptional()` forbids it. */\nfunction mayBeAbsent(schema: unknown): boolean {\n let current = schema;\n for (let guard = 0; guard < 32; guard++) {\n const internals = isPlainObjectLike(current) ? current._zod : undefined;\n if (isPlainObjectLike(internals) && internals.optout === \"optional\") {\n return true;\n }\n const def = defOf(current);\n if (!def) return false;\n if (def.type === \"optional\") return true;\n if (\n def.type === \"default\" ||\n def.type === \"prefault\" ||\n def.type === \"nonoptional\" ||\n !WRAPPERS.has(def.type)\n ) {\n return false;\n }\n current = def.innerType;\n }\n return false;\n}\n\n/** Whether `key` may be absent from a value of the object schema `schema`:\n * an optional property, or (in a union) one some member makes optional or\n * lacks. A record value or an array element is never optional. */\nfunction optionalKeyIn(schema: unknown, key: string): boolean {\n const unwrapped = schemaAtPath(schema, []);\n const def = unwrapped.ok ? defOf(unwrapped.schema) : undefined;\n if (def?.type === \"object\") {\n const shape = isPlainObjectLike(def.shape) ? def.shape : {};\n return key in shape && mayBeAbsent(shape[key]);\n }\n if (def?.type === \"union\" && Array.isArray(def.options)) {\n return def.options.some((option: unknown) => {\n const inner = schemaAtPath(option, []);\n const optionDef = inner.ok ? defOf(inner.schema) : undefined;\n const shape =\n optionDef?.type === \"object\" && isPlainObjectLike(optionDef.shape)\n ? optionDef.shape\n : undefined;\n return (\n shape !== undefined && (!(key in shape) || mayBeAbsent(shape[key]))\n );\n });\n }\n return false;\n}\n\n/**\n * Whether the field `path[at]` is OPTIONAL in `schema` (a producer's\n * `outputsSchema`, or a `$map` element schema), given that `path[0..at-1]`\n * exists: the codegen'd `OutputToken<T | undefined>` / `ItemToken<T |\n * undefined>` positions, whose rendered property the resolver omits when\n * the field is absent. False for a record key, an array index, or a path\n * the schema does not describe.\n */\nexport function isOptionalField(\n schema: unknown,\n path: OutputPath,\n at: number,\n): boolean {\n const key = path[at];\n if (typeof key !== \"string\") return false;\n const parent = schemaAtPath(schema, path.slice(0, at));\n return parent.ok && optionalKeyIn(parent.schema, key);\n}\n\n/** The element schema of a collection schema (array element, record\n * value), or undefined when the schema does not say. */\nexport function elementSchemaOf(schema: unknown): unknown {\n const collection = collectionOf(schema);\n return collection.kind === \"array\" || collection.kind === \"record\"\n ? collection.element\n : undefined;\n}\n\n/** What a `$map` iterates, as far as the schemas tell: its element schema\n * (undefined: unknown, so its `$item` paths are not checked) and a label for\n * messages. */\ninterface MapElement {\n element: unknown;\n label: string;\n}\n\n/** The collection kind of a schema (unwrapped): array, record, unknown (no\n * check possible) or something else. */\nfunction collectionOf(\n schema: unknown,\n):\n | { kind: \"array\" | \"record\"; element: unknown }\n | { kind: \"unknown\" }\n | { kind: \"other\"; type: string } {\n const unwrapped = schemaAtPath(schema, []);\n const def = unwrapped.ok ? defOf(unwrapped.schema) : undefined;\n if (!def) return { kind: \"unknown\" };\n if (def.type === \"array\") return { kind: \"array\", element: def.element };\n if (def.type === \"record\") return { kind: \"record\", element: def.valueType };\n // An object with a catchall is a record of its catchall (known keys may\n // differ: no element schema); a tuple renders like an array.\n if (def.type === \"object\") {\n const catchall = defOf(def.catchall);\n if (catchall && catchall.type !== \"never\") {\n const shape = isPlainObjectLike(def.shape) ? def.shape : {};\n return Object.keys(shape).length === 0\n ? { kind: \"record\", element: def.catchall }\n : { kind: \"record\", element: undefined };\n }\n }\n if (def.type === \"tuple\") return { kind: \"array\", element: undefined };\n if (def.type === \"any\" || def.type === \"unknown\" || def.type === \"union\") {\n return { kind: \"unknown\" };\n }\n return { kind: \"other\", type: def.type };\n}\n\n/** Every `$output` token's producer exists and its path is valid against\n * the producer's `outputsSchema`; every `$map`'s `over` is a collection\n * there (a record under `into: \"record\"`), and every `$item` path exists\n * in the element schema of the map it binds. */\nexport function checkOutputPaths(\n host: unknown,\n outputsSchemaOf: (ref: OutputRef) => OutputsSchemaLookup,\n): DeclaredIssue[] {\n const issues: DeclaredIssue[] = [];\n // Element schema per `$map` token; outer maps are visited before the\n // tokens of their templates (document order).\n const elements = new Map<Record<string, unknown>, MapElement | undefined>();\n const elementOf = (scope: MapScope | { error: string }) =>\n \"error\" in scope ? undefined : elements.get(scope.token);\n for (const site of collectTokenSites(host)) {\n if (!tokenSchema.safeParse(site.token).success) continue;\n if (site.key === \"$map\") {\n elements.set(\n site.token,\n checkMap(site, outputsSchemaOf, elementOf, issues),\n );\n continue;\n }\n if (site.key === \"$item\") {\n const scope = scopeOf(site);\n const element = elementOf(scope);\n if (!element || element.element === undefined || \"error\" in scope) {\n continue;\n }\n const itemPath = itemPathOf(site);\n const hit = schemaAtPath(element.element, itemPath);\n if (!hit.ok) {\n const parent = itemPath.slice(0, hit.at);\n issues.push({\n path: formatPath(site.path),\n message: `${describeToken(site.token)}: the element${parent.length ? `'s ${formatPath(parent)}` : \"\"} of the $map at ${formatPath(scope.path)}${scope.as ? ` (as \"${scope.as}\")` : \"\"} ${hit.reason} (element of ${element.label}).`,\n });\n }\n continue;\n }\n if (site.key !== \"$output\") continue;\n const ref = refOf(site);\n if (!ref) continue;\n const path = formatPath(site.path);\n const lookup = outputsSchemaOf(ref);\n if (\"error\" in lookup) {\n issues.push({ path, message: lookup.error });\n continue;\n }\n const outputPath = pathOf(site);\n const hit = schemaAtPath(lookup.schema, outputPath);\n if (!hit.ok) {\n const parent = outputPath.slice(0, hit.at);\n const where = parent.length\n ? `outputs.${formatPath(parent)}`\n : \"the outputs\";\n issues.push({\n path,\n message: `${describeToken(site.token)}: ${where} ${hit.reason} in the outputsSchema of ${lookup.label}.`,\n });\n }\n }\n return issues;\n}\n\n/** A `$map`'s `over` against its schema: a collection (a record under\n * `into: \"record\"`). Returns the element schema for the map's `$item`s. */\nfunction checkMap(\n site: TokenSite,\n outputsSchemaOf: (ref: OutputRef) => OutputsSchemaLookup,\n elementOf: (scope: MapScope | { error: string }) => MapElement | undefined,\n issues: DeclaredIssue[],\n): MapElement | undefined {\n const operand = site.token.$map;\n if (!isPlainObject(operand)) return undefined;\n const over = operand.over;\n const into = operand.into === \"record\";\n let schema: unknown;\n let label: string;\n // The over's own token site reports a bad producer or path; here only a\n // valid one is classified.\n if (isPlainObject(over) && \"$output\" in over) {\n const overSite: TokenSite = { ...site, key: \"$output\", token: over };\n const ref = refOf(overSite);\n if (!ref) return undefined;\n const lookup = outputsSchemaOf(ref);\n if (\"error\" in lookup) return undefined;\n const hit = schemaAtPath(lookup.schema, pathOf(overSite));\n if (!hit.ok) return undefined;\n schema = hit.schema;\n label = `${describeToken(over)} in the outputsSchema of ${lookup.label}`;\n } else if (isPlainObject(over) && \"$item\" in over) {\n const overSite: TokenSite = { ...site, key: \"$item\", token: over };\n const scope = scopeOf(overSite);\n const outer = elementOf(scope);\n if (!outer || outer.element === undefined) return undefined;\n const hit = schemaAtPath(outer.element, itemPathOf(overSite));\n if (!hit.ok) return undefined;\n schema = hit.schema;\n label = `${describeToken(over)} (element of ${outer.label})`;\n } else {\n return undefined;\n }\n const path = formatPath(site.path);\n const collection = collectionOf(schema);\n if (collection.kind === \"unknown\") return undefined;\n if (collection.kind === \"other\") {\n issues.push({\n path,\n message: `$map over ${label} is a ${collection.type}, not an array or a record; a $map iterates a collection.`,\n });\n return undefined;\n }\n if (into && collection.kind === \"array\") {\n issues.push({\n path,\n message: `$map with into: \"record\" maps over ${label}, which is an array: an array has no keys to keep. Drop into: \"record\" (the result is an array) or map over a record.`,\n });\n return undefined;\n }\n return { element: collection.element, label };\n}\n","import { refKey, type OutputRef } from \"./declared.js\";\n\n/**\n * The dependency plan (pipeline step 4): which compound member consumes\n * which member's outputs, and the start order that follows. Producers start\n * before consumers; `config.startOrder` is optional and, when given, must\n * agree with the tokens. Cycles fail. Pure.\n */\n\nexport class PlanError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"PlanError\";\n }\n}\n\nexport interface PlanMember {\n /** The member key (`children.<key>`). */\n key: string;\n /** The member's host folder (`children.<key>.host`). */\n host: string;\n /** The producers its tokens name, with the host path of one token each. */\n refs: { ref: OutputRef; path: string }[];\n}\n\nexport interface PlanEdge {\n consumer: string;\n producer: string;\n /** Host path in the consumer of the (first) token behind this edge. */\n path: string;\n}\n\nexport interface CompoundPlan {\n /** Member keys in start order. */\n order: string[];\n edges: PlanEdge[];\n /** \"tokens\": derived from the dependencies; \"startOrder\": the declared\n * order, checked against them. */\n source: \"tokens\" | \"startOrder\";\n}\n\n/** The member a ref names: the unique member running `ref.host`, or the\n * member `ref.member` when given (it must run `ref.host`). */\nexport function memberForRef(\n ref: OutputRef,\n members: readonly Pick<PlanMember, \"key\" | \"host\">[],\n): { key: string } | { error: string } {\n if (ref.member !== undefined) {\n const named = members.find((m) => m.key === ref.member);\n if (!named) {\n return {\n error: `names member \"${ref.member}\", which this compound does not declare (members: ${members.map((m) => m.key).join(\", \")}).`,\n };\n }\n if (named.host !== ref.host) {\n return {\n error: `names member \"${ref.member}\" of host \"${ref.host}\", but that member runs host \"${named.host}\".`,\n };\n }\n return { key: named.key };\n }\n const running = members.filter((m) => m.host === ref.host);\n if (running.length === 1) return { key: running[0].key };\n if (running.length === 0) {\n return {\n error: `names host \"${ref.host}\", which no member of this compound runs (members run: ${[...new Set(members.map((m) => m.host))].join(\", \")}).`,\n };\n }\n return {\n error: `names host \"${ref.host}\", which members ${running.map((m) => `\"${m.key}\"`).join(\" and \")} both run; add member: \"<key>\" to pick one.`,\n };\n}\n\nfunction edgesOf(members: readonly PlanMember[]): PlanEdge[] {\n const edges: PlanEdge[] = [];\n const problems: string[] = [];\n for (const member of members) {\n const seen = new Set<string>();\n for (const { ref, path } of member.refs) {\n const target = memberForRef(ref, members);\n if (\"error\" in target) {\n problems.push(`${member.key}: ${path} ${target.error}`);\n continue;\n }\n if (target.key === member.key) {\n problems.push(\n `${member.key}: ${path} reads ${refKey(ref)}'s outputs, which is this member itself.`,\n );\n continue;\n }\n if (seen.has(target.key)) continue;\n seen.add(target.key);\n edges.push({ consumer: member.key, producer: target.key, path });\n }\n }\n if (problems.length > 0) {\n throw new PlanError(problems.join(\"\\n\"));\n }\n return edges;\n}\n\n/** Declared start order: the named members first, then the rest in\n * declaration order. */\nfunction declaredOrder(\n members: readonly PlanMember[],\n startOrder: readonly string[],\n): string[] {\n const keys = members.map((m) => m.key);\n const named = [...new Set(startOrder)].filter((k) => keys.includes(k));\n return [...named, ...keys.filter((k) => !named.includes(k))];\n}\n\nexport function planCompound(\n members: readonly PlanMember[],\n startOrder?: readonly string[],\n): CompoundPlan {\n const edges = edgesOf(members);\n\n if (startOrder) {\n const order = declaredOrder(members, startOrder);\n const index = new Map(order.map((k, i) => [k, i]));\n const bad = edges.filter(\n (e) => (index.get(e.producer) ?? 0) > (index.get(e.consumer) ?? 0),\n );\n if (bad.length > 0) {\n throw new PlanError(\n bad\n .map(\n (e) =>\n `config.startOrder starts \"${e.consumer}\" before \"${e.producer}\", but ${e.consumer}.${e.path} consumes \"${e.producer}\"'s outputs. Reorder startOrder (or omit it: the order follows the tokens).`,\n )\n .join(\"\\n\"),\n );\n }\n return { order, edges, source: \"startOrder\" };\n }\n\n // Kahn's algorithm; ties keep declaration order.\n const pending = new Map(members.map((m) => [m.key, new Set<string>()]));\n for (const e of edges) pending.get(e.consumer)?.add(e.producer);\n const order: string[] = [];\n while (order.length < members.length) {\n const next = members.find(\n (m) => !order.includes(m.key) && pending.get(m.key)?.size === 0,\n );\n if (!next) {\n const stuck = members.filter((m) => !order.includes(m.key));\n throw new PlanError(\n `output tokens form a cycle between ${stuck.map((m) => `\"${m.key}\"`).join(\", \")}: ${edges\n .filter(\n (e) =>\n stuck.some((m) => m.key === e.consumer) &&\n stuck.some((m) => m.key === e.producer),\n )\n .map((e) => `${e.consumer} (${e.path}) needs ${e.producer}`)\n .join(\"; \")}.`,\n );\n }\n order.push(next.key);\n for (const set of pending.values()) set.delete(next.key);\n }\n return { order, edges, source: \"tokens\" };\n}\n","import {\n isBuiltinEnvName,\n substituteBuiltinEnv,\n type BuiltinEnv,\n} from \"../env-substitution.js\";\nimport { tokenKeyOf, tokenSchema } from \"../tokens.js\";\nimport {\n elementSchemaOf,\n isOptionalField,\n refKey,\n schemaAtPath,\n type OutputRef,\n} from \"./declared.js\";\nimport { memberForRef } from \"./plan.js\";\nimport {\n collectTokenSites,\n describeToken,\n formatPath,\n isEscape,\n isPlainObject,\n} from \"./walk.js\";\n\n/**\n * The resolver (pipeline step 5): replaces every token in a declared host\n * with its value. `$output` reads the producer's outputs through an\n * `OutputSource` (live compound members, or a standalone run record: the\n * node adapters in ./node.ts); `$env` reads the environment map of the\n * resolving process; `$map` renders its `to` template once per element of\n * its `over` (arrays in order, records key-sorted; `$item`/`$key` read the\n * element being rendered); the `\"${userData}\"`/`\"${projectRoot}\"` string\n * sugar is substituted on the way. An `$output`/`$item` that reads a field\n * absent from the data but optional in the producer's schema (codegen's\n * `OutputToken<T | undefined>`) omits its enclosing property, like an unset\n * optional `$env`. Pure and browser-safe.\n */\n\nexport type OutputLookup =\n | {\n status: \"available\";\n outputs: unknown;\n /** The producer's `outputsSchema`, when known: an absent field it\n * marks optional omits the consuming property instead of failing. */\n schema?: unknown;\n }\n /** `message` is the complete, user-facing reason (e.g. \"connect needs\n * outputs from host \"switchboard\", which is not running. …\"). */\n | { status: \"unavailable\"; message: string };\n\nexport interface OutputSource {\n lookup(ref: OutputRef): OutputLookup;\n}\n\nexport interface ResolveSources {\n /** Where `$output` tokens read. Absent: any `$output` fails. */\n outputs?: OutputSource;\n /** The resolving process's environment (`$env`). */\n env?: Readonly<Record<string, string | undefined>>;\n /** `userData`/`projectRoot`: always resolvable `$env` names and string\n * sugar. */\n builtins?: BuiltinEnv;\n /** The host file named in errors (`hosts/connect/host.js`). */\n where?: string;\n}\n\nexport class TokenResolutionError extends Error {\n /** The host path that failed and the reason, without the file prefix. */\n readonly detail?: { path: string; reason: string };\n\n constructor(message: string, detail?: { path: string; reason: string }) {\n super(message);\n this.name = \"TokenResolutionError\";\n if (detail) this.detail = detail;\n }\n}\n\n/** Why a required `$env` cannot resolve. */\nexport function unsetEnvMessage(name: string): string {\n return `reads $env ${name}, which is not set. Set ${name} in the environment of the process that resolves this host (or declare { $env: { name: \"${name}\", optional: true } } to omit the property when unset).`;\n}\n\n/** A resolved `{ $env: { name, optional: true } }` whose variable is unset,\n * or an `$output`/`$item` reading an absent optional field: its enclosing\n * property is omitted. */\nconst OMIT = Symbol(\"omit\");\n\n/** A resolved value with the schema describing it (when known). */\ninterface Read {\n value: unknown;\n schema?: unknown;\n}\n\ntype Trail = (string | number)[];\n\n/** One enclosing `$map` while its template renders: the element being\n * rendered, its key (record key, or array index) and the map's binding. */\ninterface Binding {\n /** Host path of the `$map` token. */\n path: Trail;\n as?: string;\n key: string | number;\n item: unknown;\n /** The element schema, when the `over` came from a schema'd output. */\n schema?: unknown;\n}\n\n/** Innermost last. */\ntype Scope = readonly Binding[];\n\n/** `reactor.drives[\"workflows\"]` (or `…[2]` for an array element). */\nfunction elementText(binding: Binding): string {\n const key =\n typeof binding.key === \"number\"\n ? `[${binding.key}]`\n : `[${JSON.stringify(binding.key)}]`;\n return `${formatPath(binding.path)}${key}`;\n}\n\n/** Provenance of `$map`-rendered arrays: element index → the input key\n * (record key, or array index) it was rendered from. Lets resolved\n * validation name the element key, not just the result index. */\nconst renderedKeys = new WeakMap<object, readonly (string | number)[]>();\n\n/**\n * The `$map` elements an issue path (from resolved validation of a resolved\n * host) passes through, as text: `$map element \"workflows\"`. Undefined when\n * the path crosses no `$map`-rendered array. Walk the SAME object\n * `resolveHostOutputs` returned (provenance is by identity).\n */\nexport function describeMapElements(\n host: unknown,\n path: readonly PropertyKey[],\n): string | undefined {\n const found: string[] = [];\n let current = host;\n for (const segment of path) {\n if (Array.isArray(current) && typeof segment === \"number\") {\n const keys = renderedKeys.get(current);\n const key = keys?.[segment];\n if (key !== undefined) {\n found.push(\n `$map element ${typeof key === \"number\" ? `[${key}]` : JSON.stringify(key)}`,\n );\n }\n current = (current as unknown[])[segment];\n } else if (isPlainObject(current) && typeof segment === \"string\") {\n current = current[segment];\n } else {\n break;\n }\n }\n return found.length ? found.join(\" › \") : undefined;\n}\n\n/** A deep copy of a resolved (JSON-shaped) value that keeps the `$map`\n * provenance of its rendered arrays (structuredClone would drop it). */\nfunction cloneWithProvenance(value: unknown): unknown {\n if (Array.isArray(value)) {\n const copy = value.map(cloneWithProvenance);\n const keys = renderedKeys.get(value);\n if (keys) renderedKeys.set(copy, keys);\n return copy;\n }\n if (isPlainObject(value)) {\n const copy: Record<string, unknown> = {};\n for (const [key, child] of Object.entries(value)) {\n copy[key] = cloneWithProvenance(child);\n }\n return copy;\n }\n return value;\n}\n\ntype PathWalk =\n | { ok: true; value: unknown }\n | { ok: false; at: number; has: string };\n\n/** The value at `path` inside `root` (output data: records and arrays). */\nfunction walkPath(root: unknown, path: readonly unknown[]): PathWalk {\n let current = root;\n for (let i = 0; i < path.length; i++) {\n const segment = path[i];\n const next = Array.isArray(current)\n ? typeof segment === \"number\"\n ? (current as unknown[])[segment]\n : undefined\n : isPlainObject(current) && typeof segment === \"string\"\n ? current[segment]\n : undefined;\n if (next === undefined) {\n const has = isPlainObject(current)\n ? Object.keys(current).join(\", \") || \"nothing\"\n : Array.isArray(current)\n ? `${current.length} elements`\n : JSON.stringify(current);\n return { ok: false, at: i, has };\n }\n current = next;\n }\n return { ok: true, value: current };\n}\n\n/** The schema at `path` inside `schema`, when both are known. */\nfunction schemaOf(schema: unknown, path: (string | number)[]): unknown {\n if (schema === undefined) return undefined;\n const hit = schemaAtPath(schema, path);\n return hit.ok ? hit.schema : undefined;\n}\n\nfunction pathSegments(path: readonly unknown[]): (string | number)[] {\n return path.filter(\n (p): p is string | number => typeof p === \"string\" || typeof p === \"number\",\n );\n}\n\n/** A compound's own member set, for `deferSelf`. */\nexport interface SelfMembers {\n /** The compound's members: key (`children.<key>`) and host folder. */\n members: readonly { key: string; host: string }[];\n}\n\n/** A token in a compound's own fields that reads one of its members. */\nexport interface DeferredToken {\n /** Host path (`config.agents.assistant.url`). */\n path: string;\n /** The member keys whose outputs it needs. */\n members: string[];\n}\n\nexport interface DeferredResolution<T> {\n /** The host with every token resolved EXCEPT the deferred ones (still in\n * place) and the `children` wrappers (member-level: each member resolves\n * its own). */\n host: T;\n deferred: DeferredToken[];\n /** The member keys any deferred token needs (start them first). */\n needs: string[];\n /** Resolve the deferred tokens once those members have started, from\n * their live outputs (e.g. `compoundOutputSource`); returns the fully\n * resolved host (children still untouched). */\n finish(outputs: OutputSource): T;\n}\n\ninterface DeferredSite {\n trail: Trail;\n token: Record<string, unknown>;\n members: string[];\n}\n\nclass Resolver {\n readonly deferred: DeferredSite[] = [];\n /** What the last OMIT stood for, for the \"nothing to omit\" errors. */\n omitted = \"an optional $env\";\n\n constructor(\n private readonly sources: ResolveSources,\n private readonly self?: SelfMembers | \"outputs\",\n ) {}\n\n /** The member keys a token reads (`$output` on a member's host), when\n * resolving a compound's own fields with `deferSelf`. */\n private selfRefs(token: Record<string, unknown>, trail: Trail): string[] {\n if (!this.self) return [];\n const keys = new Set<string>();\n for (const site of collectTokenSites(token)) {\n const operand = site.token.$output;\n if (site.key !== \"$output\" || !isPlainObject(operand)) continue;\n if (typeof operand.host !== \"string\") continue;\n const ref: OutputRef =\n typeof operand.member === \"string\"\n ? { host: operand.host, member: operand.member }\n : { host: operand.host };\n if (this.self === \"outputs\") {\n keys.add(refKey(ref));\n continue;\n }\n const isMember = this.self.members.some((m) => m.host === ref.host);\n if (!isMember) continue;\n const target = memberForRef(ref, this.self.members);\n if (\"error\" in target) {\n this.fail([...trail, ...site.path], `in a compound ${target.error}`);\n }\n keys.add(target.key);\n }\n return [...keys];\n }\n\n fail(trail: Trail, message: string, scope: Scope = []): never {\n const where = this.sources.where ? `${this.sources.where}: ` : \"\";\n const inside = scope.length\n ? ` (rendering $map element ${scope.map(elementText).join(\" › \")})`\n : \"\";\n const path = formatPath(trail);\n throw new TokenResolutionError(`${where}\\`${path}\\` ${message}${inside}`, {\n path,\n reason: `${message}${inside}`,\n });\n }\n\n value(value: unknown, trail: Trail, scope: Scope = []): unknown {\n if (typeof value === \"string\") {\n return this.sources.builtins\n ? substituteBuiltinEnv(value, this.sources.builtins)\n : value;\n }\n if (Array.isArray(value)) {\n return value.map((child: unknown, index) => {\n const out = this.value(child, [...trail, index], scope);\n if (out === OMIT) {\n this.fail(\n [...trail, index],\n `is ${this.omitted} inside an array.`,\n scope,\n );\n }\n return out;\n });\n }\n if (!isPlainObject(value)) return value;\n // A `$$` escape stays wrapped: validateHost unwraps it after its\n // no-token walk, so an escaped literal is never mistaken for a token.\n if (isEscape(value)) return structuredClone(value);\n if (tokenKeyOf(value)) {\n // Inside a template the enclosing (top-level) $map was already\n // examined: a self-reference anywhere in it defers the whole map.\n const members = scope.length === 0 ? this.selfRefs(value, trail) : [];\n if (members.length > 0) {\n this.deferred.push({ trail, token: value, members });\n return structuredClone(value);\n }\n return this.token(value, trail, scope);\n }\n const out: Record<string, unknown> = {};\n for (const [key, child] of Object.entries(value)) {\n // deferSelf: member wrappers resolve per member, not here.\n if (\n typeof this.self === \"object\" &&\n trail.length === 0 &&\n key === \"children\"\n ) {\n out[key] = child;\n continue;\n }\n const resolved = this.value(child, [...trail, key], scope);\n if (resolved !== OMIT) out[key] = resolved;\n }\n return out;\n }\n\n token(\n token: Record<string, unknown>,\n trail: Trail,\n scope: Scope = [],\n ): unknown {\n const parsed = tokenSchema.safeParse(token);\n if (!parsed.success) {\n this.fail(\n trail,\n `is a malformed token: ${JSON.stringify(token)}.`,\n scope,\n );\n }\n const key = tokenKeyOf(token);\n switch (key) {\n case \"$output\":\n return this.output(token, trail, scope);\n case \"$env\":\n return this.env(token.$env, trail, scope);\n case \"$concat\":\n return this.concat(token.$concat, trail, scope);\n case \"$map\":\n return this.map(token.$map, trail, scope);\n case \"$item\":\n return this.item(token.$item, trail, scope);\n case \"$key\":\n return this.key(token.$key, trail, scope);\n default:\n return this.fail(trail, `is not a token.`, scope);\n }\n }\n\n /** The binding an `$item`/`$key` names: the innermost map, or the\n * enclosing map whose `as` is `name`. */\n binding(\n name: string | undefined,\n operator: \"$item\" | \"$key\",\n trail: Trail,\n scope: Scope,\n ): Binding {\n if (scope.length === 0) {\n return this.fail(\n trail,\n `uses ${operator} outside any $map; ${operator} reads the element a $map template is rendering.`,\n );\n }\n if (name === undefined) return scope[scope.length - 1];\n for (let i = scope.length - 1; i >= 0; i--) {\n if (scope[i].as === name) return scope[i];\n }\n const named = scope.flatMap((b) => (b.as ? [`\"${b.as}\"`] : []));\n return this.fail(\n trail,\n `uses ${operator} with binding \"${name}\", which no enclosing $map declares (as: ${named.join(\", \") || \"none\"}).`,\n scope,\n );\n }\n\n map(operand: unknown, trail: Trail, scope: Scope): unknown {\n if (!isPlainObject(operand)) {\n return this.fail(trail, \"is a malformed $map token.\", scope);\n }\n const into = operand.into === \"record\";\n const as = typeof operand.as === \"string\" ? operand.as : undefined;\n const read = this.readWithSchema(\n operand.over,\n [...trail, \"$map\", \"over\"],\n scope,\n );\n const over = read.value;\n // An absent optional collection: the mapped property is omitted.\n if (over === OMIT) return OMIT;\n const element =\n read.schema === undefined ? undefined : elementSchemaOf(read.schema);\n const render = (key: string | number, item: unknown): unknown => {\n const inner: Scope = [\n ...scope,\n {\n path: trail,\n key,\n item,\n ...(as !== undefined ? { as } : {}),\n ...(element !== undefined ? { schema: element } : {}),\n },\n ];\n const at = [...trail, \"$map\", \"to\"];\n const out = this.value(operand.to, at, inner);\n if (out === OMIT) {\n return this.fail(\n at,\n `is ${this.omitted} as the whole $map template; there is no property to omit.`,\n inner,\n );\n }\n return out;\n };\n if (Array.isArray(over)) {\n if (into) {\n return this.fail(\n trail,\n `is a $map with into: \"record\", but its over (${describeToken(operand.over)}) resolved to an array, which has no keys to keep. Drop into: \"record\" (the result is an array) or map over a record.`,\n scope,\n );\n }\n const rendered = over.map((item: unknown, index) => render(index, item));\n renderedKeys.set(\n rendered,\n over.map((_: unknown, index) => index),\n );\n return rendered;\n }\n if (isPlainObject(over)) {\n // Key-sorted (code-unit order): deterministic, whatever order the\n // producer published its outputs in.\n const keys = Object.keys(over).sort();\n if (!into) {\n const rendered = keys.map((key) => render(key, over[key]));\n renderedKeys.set(rendered, keys);\n return rendered;\n }\n const out: Record<string, unknown> = {};\n for (const key of keys) out[key] = render(key, over[key]);\n return out;\n }\n return this.fail(\n trail,\n `is a $map whose over (${describeToken(operand.over)}) resolved to ${JSON.stringify(over)}${into ? `; into: \"record\" needs a record` : \", which is not an array or a record\"}.`,\n scope,\n );\n }\n\n item(operand: unknown, trail: Trail, scope: Scope): unknown {\n return this.readItem(operand, trail, scope).value;\n }\n\n /** A `$map`'s `over` with the schema describing it, when it reads a\n * schema'd `$output` (or an `$item` of a schema'd element). */\n private readWithSchema(value: unknown, trail: Trail, scope: Scope): Read {\n const key = tokenKeyOf(value);\n if (\n isPlainObject(value) &&\n (key === \"$output\" || key === \"$item\") &&\n tokenSchema.safeParse(value).success\n ) {\n return key === \"$output\"\n ? this.readOutput(value, trail, scope)\n : this.readItem(value.$item, trail, scope);\n }\n return { value: this.value(value, trail, scope) };\n }\n\n private omit(what: string): Read {\n this.omitted = what;\n return { value: OMIT };\n }\n\n private readItem(operand: unknown, trail: Trail, scope: Scope): Read {\n const named = isPlainObject(operand) ? operand : undefined;\n const name = named && typeof named.as === \"string\" ? named.as : undefined;\n const raw: unknown = named ? named.path : operand;\n const path = pathSegments(Array.isArray(raw) ? raw : []);\n const binding = this.binding(name, \"$item\", trail, scope);\n const hit = walkPath(binding.item, path);\n if (!hit.ok) {\n if (\n binding.schema !== undefined &&\n isOptionalField(binding.schema, path, hit.at)\n ) {\n return this.omit(\"an absent optional $item field\");\n }\n const missing = formatPath(path.slice(0, hit.at + 1));\n return this.fail(\n trail,\n `reads $item ${formatPath(path)}, but $map element ${elementText(binding)} has no ${missing} (it has: ${hit.has}).`,\n scope,\n );\n }\n return {\n value: structuredClone(hit.value),\n schema: schemaOf(binding.schema, path),\n };\n }\n\n key(operand: unknown, trail: Trail, scope: Scope): string | number {\n const name = typeof operand === \"string\" ? operand : undefined;\n return this.binding(name, \"$key\", trail, scope).key;\n }\n\n output(\n token: Record<string, unknown>,\n trail: Trail,\n scope: Scope = [],\n ): unknown {\n return this.readOutput(token, trail, scope).value;\n }\n\n private readOutput(\n token: Record<string, unknown>,\n trail: Trail,\n scope: Scope,\n ): Read {\n const operand = token.$output;\n if (!isPlainObject(operand) || typeof operand.host !== \"string\") {\n return this.fail(trail, \"is a malformed $output token.\", scope);\n }\n const ref: OutputRef =\n typeof operand.member === \"string\"\n ? { host: operand.host, member: operand.member }\n : { host: operand.host };\n const path = pathSegments(Array.isArray(operand.path) ? operand.path : []);\n if (!this.sources.outputs) {\n return this.fail(\n trail,\n `reads ${describeToken(token)}, but no outputs are available here.`,\n scope,\n );\n }\n const lookup = this.sources.outputs.lookup(ref);\n if (lookup.status === \"unavailable\") {\n const where = this.sources.where ? `${this.sources.where}: ` : \"\";\n const path = formatPath(trail);\n const reason = `${lookup.message}\\n (needed by \\`${path}\\`: ${describeToken(token)})`;\n throw new TokenResolutionError(`${where}${reason}`, { path, reason });\n }\n const hit = walkPath(lookup.outputs, path);\n if (!hit.ok) {\n if (\n lookup.schema !== undefined &&\n isOptionalField(lookup.schema, path, hit.at)\n ) {\n return this.omit(\"an absent optional output\");\n }\n const parent = path.slice(0, hit.at);\n const container = parent.length\n ? `outputs.${formatPath(parent)}`\n : \"its outputs\";\n const missing = formatPath(path.slice(0, hit.at + 1));\n return this.fail(\n trail,\n `reads ${describeToken(token)}, but host \"${ref.host}\" has no output at ${missing} (${container} has: ${hit.has}).`,\n scope,\n );\n }\n return {\n value: structuredClone(hit.value),\n schema: schemaOf(lookup.schema, path),\n };\n }\n\n env(operand: unknown, trail: Trail, scope: Scope = []): unknown {\n const optional = isPlainObject(operand);\n const name = optional ? operand.name : operand;\n if (typeof name !== \"string\") {\n return this.fail(trail, \"is a malformed $env token.\", scope);\n }\n const builtins = this.sources.builtins;\n if (isBuiltinEnvName(name) && builtins?.[name]) {\n return builtins[name];\n }\n const value = this.sources.env?.[name];\n if (value !== undefined) return value;\n if (optional) return this.omit(\"an optional $env\").value;\n return this.fail(trail, unsetEnvMessage(name), scope);\n }\n\n concat(parts: unknown, trail: Trail, scope: Scope = []): string {\n if (!Array.isArray(parts)) {\n return this.fail(trail, \"is a malformed $concat token.\", scope);\n }\n return parts\n .map((part: unknown, index) => {\n const at = [...trail, \"$concat\", index];\n const value = this.value(part, at, scope);\n if (value === OMIT) {\n return this.fail(at, `is ${this.omitted} inside $concat.`, scope);\n }\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\") return String(value);\n return this.fail(\n at,\n `resolved to ${JSON.stringify(value)}; every $concat part must be a string or a number.`,\n scope,\n );\n })\n .join(\"\");\n }\n}\n\nexport interface ResolveOptions {\n /** Resolving a COMPOUND's own fields: tokens that read one of its members\n * are deferred until those members have started (see\n * `DeferredResolution`); `children` is left for the members. `\"outputs\"`\n * defers every `$output` (its `members` are the producers' ref keys). */\n deferSelf: SelfMembers | \"outputs\";\n}\n\n/**\n * Resolve every token in a declared host (or any JSON-shaped value): the\n * result has the same shape with tokens replaced by values, optional unset\n * `$env` properties omitted and the built-in string sugar substituted (`$$`\n * escapes are kept; validateHost unwraps them). Throws `TokenResolutionError` naming the host path;\n * an `$output` whose producer is not running fails with the source's\n * message (no fallback, no waiting).\n *\n * With `{ deferSelf }` (a compound resolving its own fields), returns a\n * `DeferredResolution` instead: everything but the self-references now,\n * and `finish(outputs)` for the rest once the members it needs run.\n */\nexport function resolveHostOutputs<T>(host: T, sources: ResolveSources): T;\nexport function resolveHostOutputs<T>(\n host: T,\n sources: ResolveSources,\n options: ResolveOptions,\n): DeferredResolution<T>;\nexport function resolveHostOutputs<T>(\n host: T,\n sources: ResolveSources,\n options?: ResolveOptions,\n): T | DeferredResolution<T> {\n const resolver = new Resolver(sources, options?.deferSelf);\n const out = resolver.value(host, []);\n if (out === OMIT) {\n resolver.fail([], `is ${resolver.omitted} with nothing to omit it from.`);\n }\n // Same shape as the declared input: every token-able field's input type\n // admits both the token and the value it resolves to.\n const partial = out as T;\n if (!options) return partial;\n const sites = resolver.deferred;\n return {\n host: partial,\n deferred: sites.map((d) => ({\n path: formatPath(d.trail),\n members: d.members,\n })),\n needs: [...new Set(sites.flatMap((d) => d.members))],\n finish(outputs: OutputSource): T {\n const done: unknown = cloneWithProvenance(partial);\n const late = new Resolver({ ...sources, outputs });\n for (const site of sites) {\n const value = late.token(site.token, site.trail);\n // An array slot has no property to omit (as when resolving eagerly).\n if (value === OMIT && typeof site.trail.at(-1) === \"number\") {\n late.fail(site.trail, `is ${late.omitted} inside an array.`);\n }\n setAt(\n done,\n site.trail,\n value === OMIT ? undefined : value,\n value === OMIT,\n );\n }\n return done as T;\n },\n };\n}\n\nfunction setAt(\n root: unknown,\n trail: Trail,\n value: unknown,\n omit: boolean,\n): void {\n let current = root;\n for (const key of trail.slice(0, -1)) {\n if (Array.isArray(current) && typeof key === \"number\")\n current = current[key];\n else if (isPlainObject(current) && typeof key === \"string\")\n current = current[key];\n else return;\n }\n const last = trail[trail.length - 1];\n if (Array.isArray(current) && typeof last === \"number\") {\n current[last] = value;\n } else if (isPlainObject(current) && typeof last === \"string\") {\n if (omit) delete current[last];\n else current[last] = value;\n }\n}\n","import { isPlainObject } from \"./walk.js\";\n\n/**\n * The cross-host forms removed in T3 (typed-host-configs 3.7), detected\n * before schema validation so the error names the token form that replaces\n * each one instead of a bare \"Unrecognized key\". clint's `agents.*.host` and\n * proxy `routes.*.member` are checked by the clint runner schemas.\n */\n\nexport interface RemovedForm {\n /** Host path of the removed value. */\n path: string;\n message: string;\n}\n\nfunction outputToken(host: string, path: string[], member?: string): string {\n const memberPart = member ? `, member: \"${member}\"` : \"\";\n return `{ $output: { host: \"${host}\"${memberPart}, path: [${path.map((p) => JSON.stringify(p)).join(\", \")}] } }`;\n}\n\nfunction isDriveReference(\n value: unknown,\n): value is { from: string; slug: string } {\n if (!isPlainObject(value)) return false;\n const keys = Object.keys(value).sort();\n return (\n keys.length === 2 &&\n keys[0] === \"from\" &&\n keys[1] === \"slug\" &&\n typeof value.from === \"string\" &&\n typeof value.slug === \"string\"\n );\n}\n\nfunction checkReactor(\n reactor: unknown,\n base: string,\n found: RemovedForm[],\n): void {\n if (!isPlainObject(reactor) || !isPlainObject(reactor.backends)) return;\n for (const [name, backend] of Object.entries(reactor.backends)) {\n if (!isPlainObject(backend) || !isPlainObject(backend.remote)) continue;\n const host = backend.remote.host;\n if (host === undefined) continue;\n const producer = typeof host === \"string\" ? host : \"switchboard\";\n found.push({\n path: `${base}reactor.backends.${name}.remote.host`,\n message: `remote: { host } was removed; use a drive address: remote: { url: ${producer}.drives.<slug>.url } with ${producer} from ../${producer}/outputs.js, or remote: { url: ${outputToken(producer, [\"drives\", \"<slug>\", \"url\"])} }.`,\n });\n }\n}\n\nfunction checkPlugins(\n runner: unknown,\n base: string,\n memberHosts: Record<string, string>,\n found: RemovedForm[],\n): void {\n if (!isPlainObject(runner) || !Array.isArray(runner.plugins)) return;\n runner.plugins.forEach((entry: unknown, index) => {\n if (!isPlainObject(entry) || !isPlainObject(entry.config)) return;\n for (const [key, value] of Object.entries(entry.config)) {\n if (!isDriveReference(value)) continue;\n const host = memberHosts[value.from] ?? value.from;\n const member = memberHosts[value.from] ? value.from : undefined;\n found.push({\n path: `${base}runner.plugins[${index}].config.${key}`,\n message: `${key}: { from, slug } was removed; use ${host}.drives.${value.slug}.url from ../${host}/outputs.js, or ${outputToken(host, [\"drives\", value.slug, \"url\"])}${member ? ` (add member: \"${member}\" if two members run host \"${host}\")` : \"\"}.`,\n });\n }\n });\n}\n\n/** Every removed form in a host file (reactor or compound), in document\n * order. Compound wrappers are checked too. */\nexport function findRemovedForms(host: unknown): RemovedForm[] {\n const found: RemovedForm[] = [];\n if (!isPlainObject(host)) return found;\n const children = isPlainObject(host.children) ? host.children : undefined;\n const memberHosts: Record<string, string> = {};\n for (const [key, wrapper] of Object.entries(children ?? {})) {\n if (isPlainObject(wrapper) && typeof wrapper.host === \"string\") {\n memberHosts[key] = wrapper.host;\n }\n }\n\n checkReactor(host.reactor, \"\", found);\n checkPlugins(host.runner, \"\", memberHosts, found);\n for (const [key, wrapper] of Object.entries(children ?? {})) {\n if (!isPlainObject(wrapper)) continue;\n checkReactor(wrapper.reactor, `children.${key}.`, found);\n checkPlugins(wrapper.runner, `children.${key}.`, memberHosts, found);\n }\n if (children && isPlainObject(host.config)) {\n for (const key of [\"projectDrivesIntoConnect\", \"drivesPublicBase\"]) {\n if (host.config[key] === undefined) continue;\n found.push({\n path: `config.${key}`,\n message: `config.${key} was removed; declare the drives on the member that consumes them, by output token: reactor.drives: [{ slug: \"<slug>\", remote: { url: ${outputToken(\"switchboard\", [\"drives\", \"<slug>\", \"url\"])} } }].`,\n });\n }\n }\n return found;\n}\n","import type { OutputRef } from \"./declared.js\";\nimport { memberForRef } from \"./plan.js\";\nimport type { OutputSource } from \"./resolve.js\";\n\n/**\n * The compound output source: a member's `$output` tokens read the live\n * `RunnerHandle.outputs` of the members started before it. `schemas` (member\n * key → its runner's `outputsSchema`) lets an absent optional output field\n * omit the consuming property. Pure (the run-record source for standalone\n * hosts is node: ./node.ts).\n */\nexport function compoundOutputSource(\n members: readonly { key: string; host: string }[],\n started: ReadonlyMap<string, unknown>,\n compound: string,\n schemas?: ReadonlyMap<string, unknown>,\n): OutputSource {\n return {\n lookup(ref: OutputRef) {\n const target = memberForRef(ref, members);\n if (\"error\" in target) {\n return {\n status: \"unavailable\",\n message: `compound \"${compound}\": a token ${target.error}`,\n };\n }\n if (!started.has(target.key)) {\n return {\n status: \"unavailable\",\n message: `compound \"${compound}\": member \"${target.key}\" (host \"${ref.host}\") has not started yet; a producer must start before its consumers.`,\n };\n }\n const schema = schemas?.get(target.key);\n return {\n status: \"available\",\n outputs: started.get(target.key),\n ...(schema !== undefined ? { schema } : {}),\n };\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":";;;;;AA4BA,SAAgB,eACd,SAC4B;CAC5B,MAAM,WAAW,SAAS;CAC1B,IAAI,CAAC,UAAU,OAAO,KAAA;CACtB,MAAM,QAAQ,OAAO,KAAK,QAAQ;CAClC,IAAI,MAAM,WAAW,GAAG,OAAO,KAAA;CAQ/B,OAAO,SANL,QAAQ,WAAW,YAClB,MAAM,SAAS,MAAM,IAClB,SACA,MAAM,SAAS,OAAO,IACpB,UACA,MAAM;AAEhB;AAEA,MAAM,WAGF;CACF,mBAAmB;CACnB,iBAAiB;CACjB,YAAY;CACZ,gBAAgB;AAClB;;;AAIA,SAAgB,YACd,UACwB;CACxB,MAAM,MAA8B,CAAC;CACrC,IAAI,CAAC,UAAU,OAAO;CACtB,KAAK,MAAM,CAAC,KAAK,YAAY,OAAO,QAAQ,QAAQ,GAAG;EACrD,MAAM,QAAQ,SAAS,eAAe;EACtC,IAAI,UAAU,KAAA,GAAW,IAAI,WAAW,QAAQ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backend-projection.ts","../src/reactor-config.ts","../src/child-wrapper.ts","../src/connect-projection.ts","../src/run-record-schema.ts","../src/resolve/walk.ts","../src/resolve/declared.ts","../src/resolve/plan.ts","../src/resolve/resolve.ts","../src/resolve/removed-forms.ts","../src/resolve/sources.ts","../src/expect-host.ts"],"sourcesContent":["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' drive addresses, placement order. */\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 remote backends by host key, placement order. */\nexport function remoteBackends(\n reactor: ReactorConfig | undefined,\n): { name: string; url: string }[] {\n return backendsToDescriptors(reactor).flatMap((d) =>\n d.kind === \"remote\" && d.remote\n ? [{ name: d.name, url: d.remote.url }]\n : [],\n );\n}\n","/**\n * The shared `reactor` host-config block and its projections onto the\n * Switchboard config / 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 { remoteBackends } from \"./backend-projection.js\";\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\n/** The switchboard config layer a reactor block maps to (the shape of\n * `@powerhousedao/switchboard/config`'s input). Only keys the block sets. */\nexport interface SwitchboardReactorLayer {\n storage?: { reactor?: { url: string }; readModel?: { url: string } };\n protocol?: ReactorProtocol;\n packages?: { dynamic: true };\n features?: { workflows: boolean };\n}\n\n/** The reactor block as a switchboard config layer. The reactor store and the\n * read model are separate fields: `readModel.url` never moves the reactor. */\nexport function reactorBlockToSwitchboardConfig(\n reactor: ReactorConfig | undefined,\n): SwitchboardReactorLayer {\n const layer: SwitchboardReactorLayer = {};\n const backend = primaryBackend(reactor);\n const storage = backend?.storage;\n const reactorUrl =\n storage?.kind === \"postgres\" ? storage.url : storage?.dataDir;\n const readModelUrl = backend?.readModel?.url;\n if (reactorUrl || readModelUrl) {\n layer.storage = {\n ...(reactorUrl ? { reactor: { url: reactorUrl } } : {}),\n ...(readModelUrl ? { readModel: { url: readModelUrl } } : {}),\n };\n }\n if (reactor?.protocol) layer.protocol = reactor.protocol;\n if (backend?.packages?.dynamic) layer.packages = { dynamic: true };\n if (reactor?.workflows !== undefined) {\n layer.features = { workflows: reactor.workflows };\n }\n return layer;\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?: {\n reactorWorker?: boolean;\n reactorClient?: ReactorClientMode;\n remoteBackends?: { name: string; url: string }[];\n };\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 and instance.remoteBackends,\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 ...(mode === \"router\" || mode === \"remote\"\n ? { remoteBackends: remoteBackends(reactor) }\n : {}),\n };\n }\n if (reactor?.workflows !== undefined) {\n connect.app = { workflowsEnabled: reactor.workflows };\n }\n return { connect };\n}\n\n/** Each pre-set env var that CONTRADICTS the host's protocol block, as a\n * message naming the var, the host value and the env value. An env var that\n * merely matches, or is unset, is fine. */\nexport function protocolConflicts(\n protocol: ReactorProtocol | undefined,\n env: Readonly<Record<string, string | undefined>>,\n hostFile = \"the host file\",\n): string[] {\n if (!protocol) return [];\n return Object.entries(protocolEnv(protocol)).flatMap(\n ([varName, hostValue]) => {\n const envValue = env[varName];\n if (envValue === undefined || envValue === hostValue) return [];\n return [\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\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 (phase-2 transition keeps an operator's explicit env as an\n * escape hatch unless it disagrees with the protocol — see the WBS\n * precedence note).\n */\nexport function assertProtocolConsistency(\n protocol: ReactorProtocol | undefined,\n env: Record<string, string | undefined>,\n hostFile = \"the host file\",\n): void {\n const conflict = protocolConflicts(protocol, env, hostFile).at(0);\n if (conflict) throw new Error(conflict);\n}\n","import type { ChildWrapper, HostDefinition } from \"./host-schemas.js\";\n\n/** A member's host.js with its wrapper applied, tokens unresolved. */\nexport type MemberDraft = Record<string, unknown> & {\n name: string;\n runner: HostDefinition[\"runner\"];\n};\n\n/** Generic compound rule: `reactor`/`config` replace, `runner` key-merges. */\nexport function applyChildWrapper(\n base: HostDefinition,\n wrapper: ChildWrapper,\n): MemberDraft {\n const reactor = wrapper.reactor ?? base.reactor;\n const config = wrapper.config ?? base.config;\n return {\n ...base,\n runner: { ...base.runner, ...wrapper.runner },\n ...(config !== undefined ? { config } : {}),\n ...(reactor !== undefined ? { reactor } : {}),\n };\n}\n","import type {\n PHConnectCollection,\n PHConnectDefaultDrive,\n PHConnectRuntimeConfig,\n PHConnectRuntimeDefaultDrive,\n} from \"@powerhousedao/shared/clis\";\nimport { switchboardOfDrive } from \"@powerhousedao/shared/host-tokens\";\nimport { remoteBackends } from \"./backend-projection.js\";\nimport type { ReactorConfig } from \"./host-schemas.js\";\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\n/** A served slug names a declared one as is, or hashed (`<slug>-<8 hex>`). */\nfunction servesSlug(declared: string, served: string): boolean {\n return (\n served === declared ||\n (served.startsWith(`${declared}-`) &&\n /^[0-9a-f]{8}$/.test(served.slice(declared.length + 1)))\n );\n}\n\nexport interface PlacedConnectDrives {\n defaultDrives: PHConnectRuntimeDefaultDrive[];\n collections?: Record<string, PHConnectCollection>;\n}\n\n/** Annotates remote default drives with their backend (`sync: false` when placed on it); other remote placements become collections. */\nexport function placeConnectDrives(\n reactor: ReactorConfig | undefined,\n defaultDrives: readonly PHConnectDefaultDrive[],\n): PlacedConnectDrives {\n const remotes = remoteBackends(reactor).flatMap(({ name, url }) => {\n const at = switchboardOfDrive(url);\n return at ? [{ name, base: at.base }] : [];\n });\n if (remotes.length === 0) return { defaultDrives: [...defaultDrives] };\n const placement = Object.entries(reactor?.placement?.drives ?? {});\n const matched = new Set<string>();\n const placed = defaultDrives.map((drive): PHConnectRuntimeDefaultDrive => {\n if (!(\"url\" in drive)) return drive;\n const at = switchboardOfDrive(drive.url);\n const backend = remotes.find((remote) => remote.base === at?.base)?.name;\n if (!at || !backend) return drive;\n const entry = placement.find(([slug]) => servesSlug(slug, at.slug));\n if (entry) matched.add(entry[0]);\n return entry?.[1] === backend\n ? { ...drive, backend, sync: false }\n : { ...drive, backend };\n });\n const names = new Set(remotes.map((remote) => remote.name));\n const collections = Object.fromEntries(\n placement\n .filter(([slug, backend]) => !matched.has(slug) && names.has(backend))\n .map(([slug, backend]) => [slug, { backend, sync: false }]),\n );\n return Object.keys(collections).length > 0\n ? { defaultDrives: placed, collections }\n : { defaultDrives: placed };\n}\n","import { z } from \"zod\";\nimport { hostNameSchema, runnerKindSchema } from \"./host-schemas.js\";\n\n/**\n * `.ph/run/<host>.json`, version 2 (typed-host-configs 3.6): what a running\n * host and its members produced. Validated on read; a v1 (or any invalid)\n * record reads as \"not running\". `projectName` is kept beyond the plan's\n * sketch because the live/foreign probe needs it. `host` is the host's\n * `name` (the file key), not its folder.\n */\n\nconst outputsSchema = z.record(z.string(), z.unknown());\n\nexport const runRecordMemberSchema = z.strictObject({\n /** The member's host folder (`children.<key>.host`). */\n host: z.string().min(1),\n runnerModule: z.string().min(1),\n kind: runnerKindSchema,\n verb: z.string().min(1),\n outputs: outputsSchema,\n});\n\nexport const runRecordSchema = z.strictObject({\n version: z.literal(2),\n host: hostNameSchema,\n projectName: z.string(),\n kind: runnerKindSchema,\n verb: z.string().min(1),\n pid: z.number().int(),\n startedAt: z.string(),\n /** Standalone hosts: the runner's outputs. */\n outputs: outputsSchema.optional(),\n /** Compounds: one entry per started member, keyed by member name. */\n members: z.record(z.string(), runRecordMemberSchema).optional(),\n /** Host-specific extras (e.g. mcpUrl) a runner wants in the record. */\n extra: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport type RunRecord = z.infer<typeof runRecordSchema>;\nexport type RunRecordMember = z.infer<typeof runRecordMemberSchema>;\n","import {\n TOKEN_ESCAPE_KEY,\n tokenKeyOf,\n type OutputPath,\n type TokenKey,\n} from \"../tokens.js\";\n\n/**\n * Token discovery over a declared (JSON-shaped) host: where every operator\n * sits and in which syntactic position, which is what declared validation\n * (`$env` optional placement), the dependency plan and `--explain outputs`\n * read. Pure: no node imports.\n */\n\n/** Where a token sits: the direct value of an object property, an array\n * element, the whole value, a `$concat` part, a `$map`'s `over`, or the\n * whole `to` template of a `$map` (the top of the rendered element). */\nexport type TokenPosition =\n | \"property\"\n | \"element\"\n | \"root\"\n | \"concat\"\n | \"over\"\n | \"template\";\n\n/** An enclosing `$map`, as seen from a token inside its `to` template. */\nexport interface MapScope {\n /** Host path of the `$map` token. */\n path: OutputPath;\n /** Its binding name (`$map.as`), if any. */\n as?: string;\n /** The `$map` token itself. */\n token: Record<string, unknown>;\n}\n\nexport interface TokenSite {\n /** Property keys and array indices from the host root to the token\n * (`$map` operands appear as `…$map.over` / `…$map.to…`). */\n path: OutputPath;\n key: TokenKey;\n /** The token object itself (`{ $output: … }`, …). */\n token: Record<string, unknown>;\n position: TokenPosition;\n /** The `$map`s whose template holds this token, outermost first (the\n * innermost binding is last). A map's own `over` is in its OUTER scope. */\n scopes: readonly MapScope[];\n}\n\nexport function isPlainObject(\n value: unknown,\n): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n return false;\n }\n const proto: unknown = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/** `a.b[2].c` (or `<root>`). */\nexport function formatPath(path: readonly (string | number)[]): string {\n let out = \"\";\n for (const segment of path) {\n if (typeof segment === \"number\") out += `[${segment}]`;\n else out += out ? `.${segment}` : segment;\n }\n return out || \"<root>\";\n}\n\n/** Is this object a `$$` escape (`{ $$: literal }`)? */\nexport function isEscape(value: Record<string, unknown>): boolean {\n const keys = Object.keys(value);\n return keys.length === 1 && keys[0] === TOKEN_ESCAPE_KEY;\n}\n\n/** Every token in `value`, in document order. `$concat` parts and `$map`\n * operands (`over`, then the `to` template) are visited: they may hold tokens\n * themselves. Each site carries the `$map` scopes it sits in. A `$$` escape\n * hides its operand. */\nexport function collectTokenSites(value: unknown): TokenSite[] {\n const sites: TokenSite[] = [];\n visit(value, [], \"root\", [], sites);\n return sites;\n}\n\nfunction visit(\n value: unknown,\n path: OutputPath,\n position: TokenPosition,\n scopes: readonly MapScope[],\n sites: TokenSite[],\n): void {\n const key = tokenKeyOf(value);\n if (key && isPlainObject(value)) {\n sites.push({ path, key, token: value, position, scopes });\n const operand = value[key];\n if (key === \"$concat\" && Array.isArray(operand)) {\n operand.forEach((part: unknown, index) =>\n visit(part, [...path, \"$concat\", index], \"concat\", scopes, sites),\n );\n }\n if (key === \"$map\" && isPlainObject(operand)) {\n const at = [...path, \"$map\"];\n // `over` is evaluated in the enclosing scope; only `to` sees this map.\n if (\"over\" in operand) {\n visit(operand.over, [...at, \"over\"], \"over\", scopes, sites);\n }\n if (\"to\" in operand) {\n const scope: MapScope = {\n path,\n token: value,\n ...(typeof operand.as === \"string\" ? { as: operand.as } : {}),\n };\n visit(operand.to, [...at, \"to\"], \"template\", [...scopes, scope], sites);\n }\n }\n return;\n }\n if (Array.isArray(value)) {\n value.forEach((child: unknown, index) =>\n visit(child, [...path, index], \"element\", scopes, sites),\n );\n return;\n }\n if (!isPlainObject(value) || isEscape(value)) return;\n for (const [childKey, child] of Object.entries(value)) {\n visit(child, [...path, childKey], \"property\", scopes, sites);\n }\n}\n\n/** An `$item` path as text: `url`, `drives.x`, `<element>` for `[]`. */\nfunction pathText(path: readonly unknown[]): string {\n if (path.length === 0) return \"<element>\";\n return formatPath(\n path.filter(\n (p): p is string | number =>\n typeof p === \"string\" || typeof p === \"number\",\n ),\n );\n}\n\n/** A one-line human rendering of a token, for `--explain` and messages. */\nexport function describeToken(token: unknown): string {\n const key = tokenKeyOf(token);\n if (!key || !isPlainObject(token)) return JSON.stringify(token);\n const operand = token[key];\n if (key === \"$output\" && isPlainObject(operand)) {\n const host = typeof operand.host === \"string\" ? operand.host : \"?\";\n const member =\n typeof operand.member === \"string\" ? ` (member ${operand.member})` : \"\";\n const path = Array.isArray(operand.path)\n ? formatPath(\n operand.path.filter(\n (p): p is string | number =>\n typeof p === \"string\" || typeof p === \"number\",\n ),\n )\n : \"?\";\n return `$output ${host}${member} › ${path}`;\n }\n if (key === \"$env\") {\n if (typeof operand === \"string\") return `$env ${operand}`;\n if (isPlainObject(operand) && typeof operand.name === \"string\") {\n return `$env ${operand.name} (optional)`;\n }\n }\n if (key === \"$item\") {\n const named = isPlainObject(operand) ? operand : undefined;\n const raw: unknown = named ? named.path : operand;\n const path = Array.isArray(raw) ? pathText(raw) : \"?\";\n const binding =\n named && typeof named.as === \"string\" ? `(${named.as})` : \"\";\n return `$item${binding} ${path}`;\n }\n if (key === \"$key\") {\n return typeof operand === \"string\" ? `$key(${operand})` : \"$key\";\n }\n if (key === \"$map\" && isPlainObject(operand)) {\n const as = typeof operand.as === \"string\" ? ` as ${operand.as}` : \"\";\n const into = operand.into === \"record\" ? \" into record\" : \"\";\n return `$map over [${describeToken(operand.over)}]${as}${into} → ${JSON.stringify(render(operand.to))}`;\n }\n if (key === \"$concat\" && Array.isArray(operand)) {\n const parts = operand.map((part: unknown) =>\n typeof part === \"string\"\n ? JSON.stringify(part)\n : typeof part === \"number\"\n ? String(part)\n : `[${describeToken(part)}]`,\n );\n return `$concat ${parts.join(\" + \")}`;\n }\n return `${key} ${JSON.stringify(operand)}`;\n}\n\n/** A display copy of `value` with every token replaced by `«description»`\n * (for printing declared hosts, e.g. `--explain drives`). */\nexport function renderTokens<T>(value: T): T {\n return render(value) as T;\n}\n\nfunction render(value: unknown): unknown {\n if (tokenKeyOf(value)) return `«${describeToken(value)}»`;\n if (Array.isArray(value)) return value.map(render);\n if (!isPlainObject(value) || isEscape(value)) return value;\n const out: Record<string, unknown> = {};\n for (const [key, child] of Object.entries(value)) out[key] = render(child);\n return out;\n}\n\n/** A copy of `value` with every `$$` escape replaced by its operand (the\n * literal it protects). Run after the no-token walk. */\nexport function unwrapEscapes<T>(value: T): T {\n return unwrap(value) as T;\n}\n\nfunction unwrap(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(unwrap);\n if (!isPlainObject(value)) return value;\n if (isEscape(value)) return structuredClone(value[TOKEN_ESCAPE_KEY]);\n const out: Record<string, unknown> = {};\n for (const [key, child] of Object.entries(value)) out[key] = unwrap(child);\n return out;\n}\n","import { tokenSchema, type OutputPath } from \"../tokens.js\";\nimport {\n collectTokenSites,\n describeToken,\n formatPath,\n isPlainObject,\n type MapScope,\n type TokenSite,\n} from \"./walk.js\";\n\n/**\n * Declared validation (pipeline step 3) of a host's tokens, before anything\n * runs: operator shapes, `$env` `optional` placement, and every `$output`\n * path against the producer's `outputsSchema`. No environment value is read\n * and no producer needs to be running. Pure: producers are looked up through\n * a callback the node side fills.\n */\n\n/** Which host's outputs a `$output` token names: `host` is the producer's\n * FOLDER (`hosts/<host>/`); `member` picks one compound member when two\n * share a host. */\nexport interface OutputRef {\n host: string;\n member?: string;\n}\n\nexport interface DeclaredIssue {\n /** Host path of the token (`runner.plugins[0].config.drive`). */\n path: string;\n message: string;\n}\n\nfunction refOf(site: TokenSite): OutputRef | undefined {\n const operand = site.token.$output;\n if (!isPlainObject(operand) || typeof operand.host !== \"string\") {\n return undefined;\n }\n return typeof operand.member === \"string\"\n ? { host: operand.host, member: operand.member }\n : { host: operand.host };\n}\n\nfunction pathOf(site: TokenSite): OutputPath {\n const operand = site.token.$output;\n if (!isPlainObject(operand) || !Array.isArray(operand.path)) return [];\n return operand.path.filter(\n (p): p is string | number => typeof p === \"string\" || typeof p === \"number\",\n );\n}\n\nexport function refKey(ref: OutputRef): string {\n return ref.member ? `${ref.host}#${ref.member}` : ref.host;\n}\n\n/** The distinct producers a host's `$output` tokens name, in document order. */\nexport function outputRefsOf(host: unknown): OutputRef[] {\n const seen = new Map<string, OutputRef>();\n for (const site of collectTokenSites(host)) {\n if (site.key !== \"$output\") continue;\n const ref = refOf(site);\n if (ref && !seen.has(refKey(ref))) seen.set(refKey(ref), ref);\n }\n return [...seen.values()];\n}\n\n/** Every `$output` token with its host path and producer (for the plan and\n * `--explain outputs`). */\nexport function outputSitesOf(\n host: unknown,\n): { path: string; ref: OutputRef; outputPath: OutputPath }[] {\n return collectTokenSites(host).flatMap((site) => {\n if (site.key !== \"$output\") return [];\n const ref = refOf(site);\n return ref\n ? [{ path: formatPath(site.path), ref, outputPath: pathOf(site) }]\n : [];\n });\n}\n\n/** Every `$env` token with its host path (for `--explain outputs`). */\nexport function envSitesOf(\n host: unknown,\n): { path: string; name: string; optional: boolean }[] {\n return collectTokenSites(host).flatMap(\n (\n site,\n ): {\n path: string;\n name: string;\n optional: boolean;\n }[] => {\n if (site.key !== \"$env\") return [];\n const operand = site.token.$env;\n if (typeof operand === \"string\") {\n return [\n { path: formatPath(site.path), name: operand, optional: false },\n ];\n }\n if (isPlainObject(operand) && typeof operand.name === \"string\") {\n return [\n { path: formatPath(site.path), name: operand.name, optional: true },\n ];\n }\n return [];\n },\n );\n}\n\n/** The binding name an `$item`/`$key` site names (undefined: innermost). */\nfunction bindingNameOf(site: TokenSite): string | undefined {\n const operand = site.token[site.key];\n if (site.key === \"$key\")\n return typeof operand === \"string\" ? operand : undefined;\n if (site.key === \"$item\" && isPlainObject(operand)) {\n return typeof operand.as === \"string\" ? operand.as : undefined;\n }\n return undefined;\n}\n\n/** The enclosing `$map` an `$item`/`$key` site binds to, or why none. */\nfunction scopeOf(site: TokenSite): MapScope | { error: string } {\n const name = bindingNameOf(site);\n if (site.scopes.length === 0) {\n return {\n error: `${site.key} is used outside any $map; it reads the element a $map template is rendering, so it is legal only inside a $map's \\`to\\` (or a nested $map's \\`over\\`).`,\n };\n }\n if (name === undefined) return site.scopes[site.scopes.length - 1];\n for (let i = site.scopes.length - 1; i >= 0; i--) {\n if (site.scopes[i].as === name) return site.scopes[i];\n }\n const named = site.scopes.flatMap((s) => (s.as ? [`\"${s.as}\"`] : []));\n return {\n error: `${describeToken(site.token)} names the $map binding \"${name}\", which no enclosing $map declares (enclosing bindings: ${named.join(\", \") || 'none; add as: \"' + name + '\" to the outer $map'}).`,\n };\n}\n\n/** Item path of an `$item` site. */\nfunction itemPathOf(site: TokenSite): OutputPath {\n const operand = site.token.$item;\n const raw: unknown = isPlainObject(operand) ? operand.path : operand;\n return Array.isArray(raw)\n ? raw.filter(\n (p): p is string | number =>\n typeof p === \"string\" || typeof p === \"number\",\n )\n : [];\n}\n\n/** Operator shapes and placement: malformed operands, `$item`/`$key`\n * outside any `$map` or naming an unknown binding, and\n * `{ $env: { name, optional: true } }` anywhere but the direct value of an\n * object property (it omits that property when unset). */\nexport function checkTokenSites(host: unknown): DeclaredIssue[] {\n const issues: DeclaredIssue[] = [];\n for (const site of collectTokenSites(host)) {\n const path = formatPath(site.path);\n if (!tokenSchema.safeParse(site.token).success) {\n issues.push({\n path,\n message: `malformed ${site.key} token ${JSON.stringify(site.token)}. Shapes: { $output: { host, member?, path: [...] } }, { $concat: [string | number | token, ...] }, { $env: \"NAME\" } or { $env: { name: \"NAME\", optional: true } }, { $map: { over: $output | $item, as?: \"name\", to: template, into?: \"record\" } }, { $item: [path] } or { $item: { as: \"name\", path: [...] } }, { $key: true } or { $key: \"name\" }.`,\n });\n continue;\n }\n if (site.key === \"$item\" || site.key === \"$key\") {\n const scope = scopeOf(site);\n if (\"error\" in scope) issues.push({ path, message: scope.error });\n continue;\n }\n const operand = site.token.$env;\n if (\n site.key === \"$env\" &&\n isPlainObject(operand) &&\n site.position !== \"property\"\n ) {\n const where =\n site.position === \"concat\"\n ? \"a $concat part\"\n : site.position === \"element\"\n ? \"an array element\"\n : site.position === \"template\"\n ? \"the whole $map template\"\n : \"the whole host\";\n issues.push({\n path,\n message: `{ $env: { name, optional: true } } is legal only as the direct value of an object property (it omits that property when ${String(operand.name)} is unset), not as ${where}. Use { $env: ${JSON.stringify(operand.name)} } here.`,\n });\n }\n }\n return issues;\n}\n\n/* ------------------------------------------------------- output path check */\n\n/** What a producer lookup yields: its runner's `outputsSchema` (any zod\n * instance), or why there is none. */\nexport type OutputsSchemaLookup =\n | { schema: unknown; label: string }\n | { error: string };\n\ntype ZodDef = Record<string, unknown> & { type: string };\n\nfunction defOf(schema: unknown): ZodDef | undefined {\n if (!isPlainObjectLike(schema)) return undefined;\n const internals = schema._zod;\n if (!isPlainObjectLike(internals)) return undefined;\n const def = internals.def;\n if (!isPlainObjectLike(def) || typeof def.type !== \"string\") return undefined;\n return { ...def, type: def.type };\n}\n\n// zod schemas are class instances, so \"plain object\" is too strict here.\nfunction isPlainObjectLike(value: unknown): value is Record<string, unknown> {\n return (\n (typeof value === \"object\" || typeof value === \"function\") && value !== null\n );\n}\n\nconst WRAPPERS = new Set([\n \"optional\",\n \"nullable\",\n \"default\",\n \"prefault\",\n \"readonly\",\n \"nonoptional\",\n \"catch\",\n \"success\",\n]);\n\n/** The schema at `path` inside a zod schema (walking objects, records,\n * arrays, tuples, unions and wrappers), or why the path does not exist. */\nexport function schemaAtPath(\n schema: unknown,\n path: OutputPath,\n): { ok: true; schema: unknown } | { ok: false; at: number; reason: string } {\n let current = schema;\n for (let i = 0; i <= path.length; i++) {\n // unwrap\n for (let guard = 0; guard < 32; guard++) {\n const def = defOf(current);\n if (!def) break;\n if (WRAPPERS.has(def.type)) current = def.innerType;\n else if (def.type === \"lazy\" && typeof def.getter === \"function\") {\n const getter = def.getter as () => unknown;\n current = getter();\n } else if (def.type === \"pipe\") {\n const out = defOf(def.out);\n current = out && out.type !== \"transform\" ? def.out : def.in;\n } else break;\n }\n if (i === path.length) return { ok: true, schema: current };\n const segment = path[i];\n const def = defOf(current);\n if (!def) return { ok: false, at: i, reason: \"is not a schema\" };\n switch (def.type) {\n case \"any\":\n case \"unknown\":\n return { ok: true, schema: current };\n case \"object\": {\n const shape = isPlainObjectLike(def.shape) ? def.shape : {};\n if (typeof segment === \"string\" && segment in shape) {\n current = shape[segment];\n break;\n }\n const catchall = defOf(def.catchall);\n if (catchall && catchall.type !== \"never\") {\n current = def.catchall;\n break;\n }\n const keys = Object.keys(shape);\n return {\n ok: false,\n at: i,\n reason: `has no key ${JSON.stringify(segment)} (keys: ${keys.join(\", \") || \"none\"})`,\n };\n }\n case \"record\":\n if (typeof segment !== \"string\") {\n return { ok: false, at: i, reason: \"is a record (string keys)\" };\n }\n current = def.valueType;\n break;\n case \"array\":\n if (typeof segment !== \"number\") {\n return { ok: false, at: i, reason: \"is an array (numeric index)\" };\n }\n current = def.element;\n break;\n case \"tuple\": {\n const items = Array.isArray(def.items) ? def.items : [];\n if (typeof segment !== \"number\" || segment >= items.length) {\n return { ok: false, at: i, reason: `is a ${items.length}-tuple` };\n }\n current = items[segment];\n break;\n }\n case \"union\": {\n const options = Array.isArray(def.options) ? def.options : [];\n for (const option of options) {\n const hit = schemaAtPath(option, path.slice(i));\n if (hit.ok) return hit;\n }\n return { ok: false, at: i, reason: \"matches no union member\" };\n }\n default:\n return {\n ok: false,\n at: i,\n reason: `is a ${def.type}, not a container`,\n };\n }\n }\n return { ok: true, schema: current };\n}\n\n/** Whether the object schema at `path` names `key` in its shape (a\n * catchall does not count): what a runner's schema explicitly declares,\n * e.g. `runner.cspRegistrySync`. A union declares a key any member does. */\nexport function declaresKey(\n schema: unknown,\n path: OutputPath,\n key: string,\n): boolean {\n const at = schemaAtPath(schema, path);\n if (!at.ok) return false;\n const def = defOf(at.schema);\n if (def?.type === \"object\") {\n return isPlainObjectLike(def.shape) && key in def.shape;\n }\n if (def?.type === \"union\" && Array.isArray(def.options)) {\n return def.options.some((option: unknown) => declaresKey(option, [], key));\n }\n return false;\n}\n\n/** Whether a (property) schema admits an absent value on the OUTPUT side:\n * `.optional()` does; `.default()`/`.prefault()` fill it in, and\n * `.nonoptional()` forbids it. */\nfunction mayBeAbsent(schema: unknown): boolean {\n let current = schema;\n for (let guard = 0; guard < 32; guard++) {\n const internals = isPlainObjectLike(current) ? current._zod : undefined;\n if (isPlainObjectLike(internals) && internals.optout === \"optional\") {\n return true;\n }\n const def = defOf(current);\n if (!def) return false;\n if (def.type === \"optional\") return true;\n if (\n def.type === \"default\" ||\n def.type === \"prefault\" ||\n def.type === \"nonoptional\" ||\n !WRAPPERS.has(def.type)\n ) {\n return false;\n }\n current = def.innerType;\n }\n return false;\n}\n\n/** Whether `key` may be absent from a value of the object schema `schema`:\n * an optional property, or (in a union) one some member makes optional or\n * lacks. A record value or an array element is never optional. */\nfunction optionalKeyIn(schema: unknown, key: string): boolean {\n const unwrapped = schemaAtPath(schema, []);\n const def = unwrapped.ok ? defOf(unwrapped.schema) : undefined;\n if (def?.type === \"object\") {\n const shape = isPlainObjectLike(def.shape) ? def.shape : {};\n return key in shape && mayBeAbsent(shape[key]);\n }\n if (def?.type === \"union\" && Array.isArray(def.options)) {\n return def.options.some((option: unknown) => {\n const inner = schemaAtPath(option, []);\n const optionDef = inner.ok ? defOf(inner.schema) : undefined;\n const shape =\n optionDef?.type === \"object\" && isPlainObjectLike(optionDef.shape)\n ? optionDef.shape\n : undefined;\n return (\n shape !== undefined && (!(key in shape) || mayBeAbsent(shape[key]))\n );\n });\n }\n return false;\n}\n\n/**\n * Whether the field `path[at]` is OPTIONAL in `schema` (a producer's\n * `outputsSchema`, or a `$map` element schema), given that `path[0..at-1]`\n * exists: the codegen'd `OutputToken<T | undefined>` / `ItemToken<T |\n * undefined>` positions, whose rendered property the resolver omits when\n * the field is absent. False for a record key, an array index, or a path\n * the schema does not describe.\n */\nexport function isOptionalField(\n schema: unknown,\n path: OutputPath,\n at: number,\n): boolean {\n const key = path[at];\n if (typeof key !== \"string\") return false;\n const parent = schemaAtPath(schema, path.slice(0, at));\n return parent.ok && optionalKeyIn(parent.schema, key);\n}\n\n/** The element schema of a collection schema (array element, record\n * value), or undefined when the schema does not say. */\nexport function elementSchemaOf(schema: unknown): unknown {\n const collection = collectionOf(schema);\n return collection.kind === \"array\" || collection.kind === \"record\"\n ? collection.element\n : undefined;\n}\n\n/** What a `$map` iterates, as far as the schemas tell: its element schema\n * (undefined: unknown, so its `$item` paths are not checked) and a label for\n * messages. */\ninterface MapElement {\n element: unknown;\n label: string;\n}\n\n/** The collection kind of a schema (unwrapped): array, record, unknown (no\n * check possible) or something else. */\nfunction collectionOf(\n schema: unknown,\n):\n | { kind: \"array\" | \"record\"; element: unknown }\n | { kind: \"unknown\" }\n | { kind: \"other\"; type: string } {\n const unwrapped = schemaAtPath(schema, []);\n const def = unwrapped.ok ? defOf(unwrapped.schema) : undefined;\n if (!def) return { kind: \"unknown\" };\n if (def.type === \"array\") return { kind: \"array\", element: def.element };\n if (def.type === \"record\") return { kind: \"record\", element: def.valueType };\n // An object with a catchall is a record of its catchall (known keys may\n // differ: no element schema); a tuple renders like an array.\n if (def.type === \"object\") {\n const catchall = defOf(def.catchall);\n if (catchall && catchall.type !== \"never\") {\n const shape = isPlainObjectLike(def.shape) ? def.shape : {};\n return Object.keys(shape).length === 0\n ? { kind: \"record\", element: def.catchall }\n : { kind: \"record\", element: undefined };\n }\n }\n if (def.type === \"tuple\") return { kind: \"array\", element: undefined };\n if (def.type === \"any\" || def.type === \"unknown\" || def.type === \"union\") {\n return { kind: \"unknown\" };\n }\n return { kind: \"other\", type: def.type };\n}\n\n/** Every `$output` token's producer exists and its path is valid against\n * the producer's `outputsSchema`; every `$map`'s `over` is a collection\n * there (a record under `into: \"record\"`), and every `$item` path exists\n * in the element schema of the map it binds. */\nexport function checkOutputPaths(\n host: unknown,\n outputsSchemaOf: (ref: OutputRef) => OutputsSchemaLookup,\n): DeclaredIssue[] {\n const issues: DeclaredIssue[] = [];\n // Element schema per `$map` token; outer maps are visited before the\n // tokens of their templates (document order).\n const elements = new Map<Record<string, unknown>, MapElement | undefined>();\n const elementOf = (scope: MapScope | { error: string }) =>\n \"error\" in scope ? undefined : elements.get(scope.token);\n for (const site of collectTokenSites(host)) {\n if (!tokenSchema.safeParse(site.token).success) continue;\n if (site.key === \"$map\") {\n elements.set(\n site.token,\n checkMap(site, outputsSchemaOf, elementOf, issues),\n );\n continue;\n }\n if (site.key === \"$item\") {\n const scope = scopeOf(site);\n const element = elementOf(scope);\n if (!element || element.element === undefined || \"error\" in scope) {\n continue;\n }\n const itemPath = itemPathOf(site);\n const hit = schemaAtPath(element.element, itemPath);\n if (!hit.ok) {\n const parent = itemPath.slice(0, hit.at);\n issues.push({\n path: formatPath(site.path),\n message: `${describeToken(site.token)}: the element${parent.length ? `'s ${formatPath(parent)}` : \"\"} of the $map at ${formatPath(scope.path)}${scope.as ? ` (as \"${scope.as}\")` : \"\"} ${hit.reason} (element of ${element.label}).`,\n });\n }\n continue;\n }\n if (site.key !== \"$output\") continue;\n const ref = refOf(site);\n if (!ref) continue;\n const path = formatPath(site.path);\n const lookup = outputsSchemaOf(ref);\n if (\"error\" in lookup) {\n issues.push({ path, message: lookup.error });\n continue;\n }\n const outputPath = pathOf(site);\n const hit = schemaAtPath(lookup.schema, outputPath);\n if (!hit.ok) {\n const parent = outputPath.slice(0, hit.at);\n const where = parent.length\n ? `outputs.${formatPath(parent)}`\n : \"the outputs\";\n issues.push({\n path,\n message: `${describeToken(site.token)}: ${where} ${hit.reason} in the outputsSchema of ${lookup.label}.`,\n });\n }\n }\n return issues;\n}\n\n/** A `$map`'s `over` against its schema: a collection (a record under\n * `into: \"record\"`). Returns the element schema for the map's `$item`s. */\nfunction checkMap(\n site: TokenSite,\n outputsSchemaOf: (ref: OutputRef) => OutputsSchemaLookup,\n elementOf: (scope: MapScope | { error: string }) => MapElement | undefined,\n issues: DeclaredIssue[],\n): MapElement | undefined {\n const operand = site.token.$map;\n if (!isPlainObject(operand)) return undefined;\n const over = operand.over;\n const into = operand.into === \"record\";\n let schema: unknown;\n let label: string;\n // The over's own token site reports a bad producer or path; here only a\n // valid one is classified.\n if (isPlainObject(over) && \"$output\" in over) {\n const overSite: TokenSite = { ...site, key: \"$output\", token: over };\n const ref = refOf(overSite);\n if (!ref) return undefined;\n const lookup = outputsSchemaOf(ref);\n if (\"error\" in lookup) return undefined;\n const hit = schemaAtPath(lookup.schema, pathOf(overSite));\n if (!hit.ok) return undefined;\n schema = hit.schema;\n label = `${describeToken(over)} in the outputsSchema of ${lookup.label}`;\n } else if (isPlainObject(over) && \"$item\" in over) {\n const overSite: TokenSite = { ...site, key: \"$item\", token: over };\n const scope = scopeOf(overSite);\n const outer = elementOf(scope);\n if (!outer || outer.element === undefined) return undefined;\n const hit = schemaAtPath(outer.element, itemPathOf(overSite));\n if (!hit.ok) return undefined;\n schema = hit.schema;\n label = `${describeToken(over)} (element of ${outer.label})`;\n } else {\n return undefined;\n }\n const path = formatPath(site.path);\n const collection = collectionOf(schema);\n if (collection.kind === \"unknown\") return undefined;\n if (collection.kind === \"other\") {\n issues.push({\n path,\n message: `$map over ${label} is a ${collection.type}, not an array or a record; a $map iterates a collection.`,\n });\n return undefined;\n }\n if (into && collection.kind === \"array\") {\n issues.push({\n path,\n message: `$map with into: \"record\" maps over ${label}, which is an array: an array has no keys to keep. Drop into: \"record\" (the result is an array) or map over a record.`,\n });\n return undefined;\n }\n return { element: collection.element, label };\n}\n","import { refKey, type OutputRef } from \"./declared.js\";\n\n/**\n * The dependency plan (pipeline step 4): which compound member consumes\n * which member's outputs, and the start order that follows. Producers start\n * before consumers; `config.startOrder` is optional and, when given, must\n * agree with the tokens. Cycles fail. Pure.\n */\n\nexport class PlanError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"PlanError\";\n }\n}\n\nexport interface PlanMember {\n /** The member key (`children.<key>`). */\n key: string;\n /** The member's host folder (`children.<key>.host`). */\n host: string;\n /** The producers its tokens name, with the host path of one token each. */\n refs: { ref: OutputRef; path: string }[];\n}\n\nexport interface PlanEdge {\n consumer: string;\n producer: string;\n /** Host path in the consumer of the (first) token behind this edge. */\n path: string;\n}\n\nexport interface CompoundPlan {\n /** Member keys in start order. */\n order: string[];\n edges: PlanEdge[];\n /** \"tokens\": derived from the dependencies; \"startOrder\": the declared\n * order, checked against them. */\n source: \"tokens\" | \"startOrder\";\n}\n\n/** The member a ref names: the unique member running `ref.host`, or the\n * member `ref.member` when given (it must run `ref.host`). */\nexport function memberForRef(\n ref: OutputRef,\n members: readonly Pick<PlanMember, \"key\" | \"host\">[],\n): { key: string } | { error: string } {\n if (ref.member !== undefined) {\n const named = members.find((m) => m.key === ref.member);\n if (!named) {\n return {\n error: `names member \"${ref.member}\", which this compound does not declare (members: ${members.map((m) => m.key).join(\", \")}).`,\n };\n }\n if (named.host !== ref.host) {\n return {\n error: `names member \"${ref.member}\" of host \"${ref.host}\", but that member runs host \"${named.host}\".`,\n };\n }\n return { key: named.key };\n }\n const running = members.filter((m) => m.host === ref.host);\n if (running.length === 1) return { key: running[0].key };\n if (running.length === 0) {\n return {\n error: `names host \"${ref.host}\", which no member of this compound runs (members run: ${[...new Set(members.map((m) => m.host))].join(\", \")}).`,\n };\n }\n return {\n error: `names host \"${ref.host}\", which members ${running.map((m) => `\"${m.key}\"`).join(\" and \")} both run; add member: \"<key>\" to pick one.`,\n };\n}\n\nfunction edgesOf(members: readonly PlanMember[]): PlanEdge[] {\n const edges: PlanEdge[] = [];\n const problems: string[] = [];\n for (const member of members) {\n const seen = new Set<string>();\n for (const { ref, path } of member.refs) {\n const target = memberForRef(ref, members);\n if (\"error\" in target) {\n problems.push(`${member.key}: ${path} ${target.error}`);\n continue;\n }\n if (target.key === member.key) {\n problems.push(\n `${member.key}: ${path} reads ${refKey(ref)}'s outputs, which is this member itself.`,\n );\n continue;\n }\n if (seen.has(target.key)) continue;\n seen.add(target.key);\n edges.push({ consumer: member.key, producer: target.key, path });\n }\n }\n if (problems.length > 0) {\n throw new PlanError(problems.join(\"\\n\"));\n }\n return edges;\n}\n\n/** Declared start order: the named members first, then the rest in\n * declaration order. */\nfunction declaredOrder(\n members: readonly PlanMember[],\n startOrder: readonly string[],\n): string[] {\n const keys = members.map((m) => m.key);\n const named = [...new Set(startOrder)].filter((k) => keys.includes(k));\n return [...named, ...keys.filter((k) => !named.includes(k))];\n}\n\nexport function planCompound(\n members: readonly PlanMember[],\n startOrder?: readonly string[],\n): CompoundPlan {\n const edges = edgesOf(members);\n\n if (startOrder) {\n const order = declaredOrder(members, startOrder);\n const index = new Map(order.map((k, i) => [k, i]));\n const bad = edges.filter(\n (e) => (index.get(e.producer) ?? 0) > (index.get(e.consumer) ?? 0),\n );\n if (bad.length > 0) {\n throw new PlanError(\n bad\n .map(\n (e) =>\n `config.startOrder starts \"${e.consumer}\" before \"${e.producer}\", but ${e.consumer}.${e.path} consumes \"${e.producer}\"'s outputs. Reorder startOrder (or omit it: the order follows the tokens).`,\n )\n .join(\"\\n\"),\n );\n }\n return { order, edges, source: \"startOrder\" };\n }\n\n // Kahn's algorithm; ties keep declaration order.\n const pending = new Map(members.map((m) => [m.key, new Set<string>()]));\n for (const e of edges) pending.get(e.consumer)?.add(e.producer);\n const order: string[] = [];\n while (order.length < members.length) {\n const next = members.find(\n (m) => !order.includes(m.key) && pending.get(m.key)?.size === 0,\n );\n if (!next) {\n const stuck = members.filter((m) => !order.includes(m.key));\n throw new PlanError(\n `output tokens form a cycle between ${stuck.map((m) => `\"${m.key}\"`).join(\", \")}: ${edges\n .filter(\n (e) =>\n stuck.some((m) => m.key === e.consumer) &&\n stuck.some((m) => m.key === e.producer),\n )\n .map((e) => `${e.consumer} (${e.path}) needs ${e.producer}`)\n .join(\"; \")}.`,\n );\n }\n order.push(next.key);\n for (const set of pending.values()) set.delete(next.key);\n }\n return { order, edges, source: \"tokens\" };\n}\n","import {\n isBuiltinEnvName,\n substituteBuiltinEnv,\n type BuiltinEnv,\n} from \"../env-substitution.js\";\nimport { tokenKeyOf, tokenSchema } from \"../tokens.js\";\nimport {\n elementSchemaOf,\n isOptionalField,\n refKey,\n schemaAtPath,\n type OutputRef,\n} from \"./declared.js\";\nimport { memberForRef } from \"./plan.js\";\nimport {\n collectTokenSites,\n describeToken,\n formatPath,\n isEscape,\n isPlainObject,\n} from \"./walk.js\";\n\n/**\n * The resolver (pipeline step 5): replaces every token in a declared host\n * with its value. `$output` reads the producer's outputs through an\n * `OutputSource` (live compound members, or a standalone run record: the\n * node adapters in ./node.ts); `$env` reads the environment map of the\n * resolving process; `$map` renders its `to` template once per element of\n * its `over` (arrays in order, records key-sorted; `$item`/`$key` read the\n * element being rendered); the `\"${userData}\"`/`\"${projectRoot}\"` string\n * sugar is substituted on the way. An `$output`/`$item` that reads a field\n * absent from the data but optional in the producer's schema (codegen's\n * `OutputToken<T | undefined>`) omits its enclosing property, like an unset\n * optional `$env`. Pure and browser-safe.\n */\n\nexport type OutputLookup =\n | {\n status: \"available\";\n outputs: unknown;\n /** The producer's `outputsSchema`, when known: an absent field it\n * marks optional omits the consuming property instead of failing. */\n schema?: unknown;\n }\n /** `message` is the complete, user-facing reason (e.g. \"connect needs\n * outputs from host \"switchboard\", which is not running. …\"). */\n | { status: \"unavailable\"; message: string };\n\nexport interface OutputSource {\n lookup(ref: OutputRef): OutputLookup;\n}\n\nexport interface ResolveSources {\n /** Where `$output` tokens read. Absent: any `$output` fails. */\n outputs?: OutputSource;\n /** The resolving process's environment (`$env`). */\n env?: Readonly<Record<string, string | undefined>>;\n /** `userData`/`projectRoot`: always resolvable `$env` names and string\n * sugar. */\n builtins?: BuiltinEnv;\n /** The host file named in errors (`hosts/connect/host.js`). */\n where?: string;\n}\n\nexport class TokenResolutionError extends Error {\n /** The host path that failed and the reason, without the file prefix. */\n readonly detail?: { path: string; reason: string };\n\n constructor(message: string, detail?: { path: string; reason: string }) {\n super(message);\n this.name = \"TokenResolutionError\";\n if (detail) this.detail = detail;\n }\n}\n\n/** Why a required `$env` cannot resolve. */\nexport function unsetEnvMessage(name: string): string {\n return `reads $env ${name}, which is not set. Set ${name} in the environment of the process that resolves this host (or declare { $env: { name: \"${name}\", optional: true } } to omit the property when unset).`;\n}\n\n/** A resolved `{ $env: { name, optional: true } }` whose variable is unset,\n * or an `$output`/`$item` reading an absent optional field: its enclosing\n * property is omitted. */\nconst OMIT = Symbol(\"omit\");\n\n/** A resolved value with the schema describing it (when known). */\ninterface Read {\n value: unknown;\n schema?: unknown;\n}\n\ntype Trail = (string | number)[];\n\n/** One enclosing `$map` while its template renders: the element being\n * rendered, its key (record key, or array index) and the map's binding. */\ninterface Binding {\n /** Host path of the `$map` token. */\n path: Trail;\n as?: string;\n key: string | number;\n item: unknown;\n /** The element schema, when the `over` came from a schema'd output. */\n schema?: unknown;\n}\n\n/** Innermost last. */\ntype Scope = readonly Binding[];\n\n/** `reactor.drives[\"workflows\"]` (or `…[2]` for an array element). */\nfunction elementText(binding: Binding): string {\n const key =\n typeof binding.key === \"number\"\n ? `[${binding.key}]`\n : `[${JSON.stringify(binding.key)}]`;\n return `${formatPath(binding.path)}${key}`;\n}\n\n/** Provenance of `$map`-rendered arrays: element index → the input key\n * (record key, or array index) it was rendered from. Lets resolved\n * validation name the element key, not just the result index. */\nconst renderedKeys = new WeakMap<object, readonly (string | number)[]>();\n\n/**\n * The `$map` elements an issue path (from resolved validation of a resolved\n * host) passes through, as text: `$map element \"workflows\"`. Undefined when\n * the path crosses no `$map`-rendered array. Walk the SAME object\n * `resolveHostOutputs` returned (provenance is by identity).\n */\nexport function describeMapElements(\n host: unknown,\n path: readonly PropertyKey[],\n): string | undefined {\n const found: string[] = [];\n let current = host;\n for (const segment of path) {\n if (Array.isArray(current) && typeof segment === \"number\") {\n const keys = renderedKeys.get(current);\n const key = keys?.[segment];\n if (key !== undefined) {\n found.push(\n `$map element ${typeof key === \"number\" ? `[${key}]` : JSON.stringify(key)}`,\n );\n }\n current = (current as unknown[])[segment];\n } else if (isPlainObject(current) && typeof segment === \"string\") {\n current = current[segment];\n } else {\n break;\n }\n }\n return found.length ? found.join(\" › \") : undefined;\n}\n\n/** A deep copy of a resolved (JSON-shaped) value that keeps the `$map`\n * provenance of its rendered arrays (structuredClone would drop it). */\nfunction cloneWithProvenance(value: unknown): unknown {\n if (Array.isArray(value)) {\n const copy = value.map(cloneWithProvenance);\n const keys = renderedKeys.get(value);\n if (keys) renderedKeys.set(copy, keys);\n return copy;\n }\n if (isPlainObject(value)) {\n const copy: Record<string, unknown> = {};\n for (const [key, child] of Object.entries(value)) {\n copy[key] = cloneWithProvenance(child);\n }\n return copy;\n }\n return value;\n}\n\ntype PathWalk =\n | { ok: true; value: unknown }\n | { ok: false; at: number; has: string };\n\n/** The value at `path` inside `root` (output data: records and arrays). */\nfunction walkPath(root: unknown, path: readonly unknown[]): PathWalk {\n let current = root;\n for (let i = 0; i < path.length; i++) {\n const segment = path[i];\n const next = Array.isArray(current)\n ? typeof segment === \"number\"\n ? (current as unknown[])[segment]\n : undefined\n : isPlainObject(current) && typeof segment === \"string\"\n ? current[segment]\n : undefined;\n if (next === undefined) {\n const has = isPlainObject(current)\n ? Object.keys(current).join(\", \") || \"nothing\"\n : Array.isArray(current)\n ? `${current.length} elements`\n : JSON.stringify(current);\n return { ok: false, at: i, has };\n }\n current = next;\n }\n return { ok: true, value: current };\n}\n\n/** The schema at `path` inside `schema`, when both are known. */\nfunction schemaOf(schema: unknown, path: (string | number)[]): unknown {\n if (schema === undefined) return undefined;\n const hit = schemaAtPath(schema, path);\n return hit.ok ? hit.schema : undefined;\n}\n\nfunction pathSegments(path: readonly unknown[]): (string | number)[] {\n return path.filter(\n (p): p is string | number => typeof p === \"string\" || typeof p === \"number\",\n );\n}\n\n/** A compound's own member set, for `deferSelf`. */\nexport interface SelfMembers {\n /** The compound's members: key (`children.<key>`) and host folder. */\n members: readonly { key: string; host: string }[];\n}\n\n/** A token in a compound's own fields that reads one of its members. */\nexport interface DeferredToken {\n /** Host path (`config.agents.assistant.url`). */\n path: string;\n /** The member keys whose outputs it needs. */\n members: string[];\n}\n\nexport interface DeferredResolution<T> {\n /** The host with every token resolved EXCEPT the deferred ones (still in\n * place) and the `children` wrappers (member-level: each member resolves\n * its own). */\n host: T;\n deferred: DeferredToken[];\n /** The member keys any deferred token needs (start them first). */\n needs: string[];\n /** Resolve the deferred tokens once those members have started, from\n * their live outputs (e.g. `compoundOutputSource`); returns the fully\n * resolved host (children still untouched). */\n finish(outputs: OutputSource): T;\n}\n\ninterface DeferredSite {\n trail: Trail;\n token: Record<string, unknown>;\n members: string[];\n}\n\nclass Resolver {\n readonly deferred: DeferredSite[] = [];\n /** What the last OMIT stood for, for the \"nothing to omit\" errors. */\n omitted = \"an optional $env\";\n\n constructor(\n private readonly sources: ResolveSources,\n private readonly self?: SelfMembers | \"outputs\",\n ) {}\n\n /** The member keys a token reads (`$output` on a member's host), when\n * resolving a compound's own fields with `deferSelf`. */\n private selfRefs(token: Record<string, unknown>, trail: Trail): string[] {\n if (!this.self) return [];\n const keys = new Set<string>();\n for (const site of collectTokenSites(token)) {\n const operand = site.token.$output;\n if (site.key !== \"$output\" || !isPlainObject(operand)) continue;\n if (typeof operand.host !== \"string\") continue;\n const ref: OutputRef =\n typeof operand.member === \"string\"\n ? { host: operand.host, member: operand.member }\n : { host: operand.host };\n if (this.self === \"outputs\") {\n keys.add(refKey(ref));\n continue;\n }\n const isMember = this.self.members.some((m) => m.host === ref.host);\n if (!isMember) continue;\n const target = memberForRef(ref, this.self.members);\n if (\"error\" in target) {\n this.fail([...trail, ...site.path], `in a compound ${target.error}`);\n }\n keys.add(target.key);\n }\n return [...keys];\n }\n\n fail(trail: Trail, message: string, scope: Scope = []): never {\n const where = this.sources.where ? `${this.sources.where}: ` : \"\";\n const inside = scope.length\n ? ` (rendering $map element ${scope.map(elementText).join(\" › \")})`\n : \"\";\n const path = formatPath(trail);\n throw new TokenResolutionError(`${where}\\`${path}\\` ${message}${inside}`, {\n path,\n reason: `${message}${inside}`,\n });\n }\n\n value(value: unknown, trail: Trail, scope: Scope = []): unknown {\n if (typeof value === \"string\") {\n return this.sources.builtins\n ? substituteBuiltinEnv(value, this.sources.builtins)\n : value;\n }\n if (Array.isArray(value)) {\n return value.map((child: unknown, index) => {\n const out = this.value(child, [...trail, index], scope);\n if (out === OMIT) {\n this.fail(\n [...trail, index],\n `is ${this.omitted} inside an array.`,\n scope,\n );\n }\n return out;\n });\n }\n if (!isPlainObject(value)) return value;\n // A `$$` escape stays wrapped: validateHost unwraps it after its\n // no-token walk, so an escaped literal is never mistaken for a token.\n if (isEscape(value)) return structuredClone(value);\n if (tokenKeyOf(value)) {\n // Inside a template the enclosing (top-level) $map was already\n // examined: a self-reference anywhere in it defers the whole map.\n const members = scope.length === 0 ? this.selfRefs(value, trail) : [];\n if (members.length > 0) {\n this.deferred.push({ trail, token: value, members });\n return structuredClone(value);\n }\n return this.token(value, trail, scope);\n }\n const out: Record<string, unknown> = {};\n for (const [key, child] of Object.entries(value)) {\n // deferSelf: member wrappers resolve per member, not here.\n if (\n typeof this.self === \"object\" &&\n trail.length === 0 &&\n key === \"children\"\n ) {\n out[key] = child;\n continue;\n }\n const resolved = this.value(child, [...trail, key], scope);\n if (resolved !== OMIT) out[key] = resolved;\n }\n return out;\n }\n\n token(\n token: Record<string, unknown>,\n trail: Trail,\n scope: Scope = [],\n ): unknown {\n const parsed = tokenSchema.safeParse(token);\n if (!parsed.success) {\n this.fail(\n trail,\n `is a malformed token: ${JSON.stringify(token)}.`,\n scope,\n );\n }\n const key = tokenKeyOf(token);\n switch (key) {\n case \"$output\":\n return this.output(token, trail, scope);\n case \"$env\":\n return this.env(token.$env, trail, scope);\n case \"$concat\":\n return this.concat(token.$concat, trail, scope);\n case \"$map\":\n return this.map(token.$map, trail, scope);\n case \"$item\":\n return this.item(token.$item, trail, scope);\n case \"$key\":\n return this.key(token.$key, trail, scope);\n default:\n return this.fail(trail, `is not a token.`, scope);\n }\n }\n\n /** The binding an `$item`/`$key` names: the innermost map, or the\n * enclosing map whose `as` is `name`. */\n binding(\n name: string | undefined,\n operator: \"$item\" | \"$key\",\n trail: Trail,\n scope: Scope,\n ): Binding {\n if (scope.length === 0) {\n return this.fail(\n trail,\n `uses ${operator} outside any $map; ${operator} reads the element a $map template is rendering.`,\n );\n }\n if (name === undefined) return scope[scope.length - 1];\n for (let i = scope.length - 1; i >= 0; i--) {\n if (scope[i].as === name) return scope[i];\n }\n const named = scope.flatMap((b) => (b.as ? [`\"${b.as}\"`] : []));\n return this.fail(\n trail,\n `uses ${operator} with binding \"${name}\", which no enclosing $map declares (as: ${named.join(\", \") || \"none\"}).`,\n scope,\n );\n }\n\n map(operand: unknown, trail: Trail, scope: Scope): unknown {\n if (!isPlainObject(operand)) {\n return this.fail(trail, \"is a malformed $map token.\", scope);\n }\n const into = operand.into === \"record\";\n const as = typeof operand.as === \"string\" ? operand.as : undefined;\n const read = this.readWithSchema(\n operand.over,\n [...trail, \"$map\", \"over\"],\n scope,\n );\n const over = read.value;\n // An absent optional collection: the mapped property is omitted.\n if (over === OMIT) return OMIT;\n const element =\n read.schema === undefined ? undefined : elementSchemaOf(read.schema);\n const render = (key: string | number, item: unknown): unknown => {\n const inner: Scope = [\n ...scope,\n {\n path: trail,\n key,\n item,\n ...(as !== undefined ? { as } : {}),\n ...(element !== undefined ? { schema: element } : {}),\n },\n ];\n const at = [...trail, \"$map\", \"to\"];\n const out = this.value(operand.to, at, inner);\n if (out === OMIT) {\n return this.fail(\n at,\n `is ${this.omitted} as the whole $map template; there is no property to omit.`,\n inner,\n );\n }\n return out;\n };\n if (Array.isArray(over)) {\n if (into) {\n return this.fail(\n trail,\n `is a $map with into: \"record\", but its over (${describeToken(operand.over)}) resolved to an array, which has no keys to keep. Drop into: \"record\" (the result is an array) or map over a record.`,\n scope,\n );\n }\n const rendered = over.map((item: unknown, index) => render(index, item));\n renderedKeys.set(\n rendered,\n over.map((_: unknown, index) => index),\n );\n return rendered;\n }\n if (isPlainObject(over)) {\n // Key-sorted (code-unit order): deterministic, whatever order the\n // producer published its outputs in.\n const keys = Object.keys(over).sort();\n if (!into) {\n const rendered = keys.map((key) => render(key, over[key]));\n renderedKeys.set(rendered, keys);\n return rendered;\n }\n const out: Record<string, unknown> = {};\n for (const key of keys) out[key] = render(key, over[key]);\n return out;\n }\n return this.fail(\n trail,\n `is a $map whose over (${describeToken(operand.over)}) resolved to ${JSON.stringify(over)}${into ? `; into: \"record\" needs a record` : \", which is not an array or a record\"}.`,\n scope,\n );\n }\n\n item(operand: unknown, trail: Trail, scope: Scope): unknown {\n return this.readItem(operand, trail, scope).value;\n }\n\n /** A `$map`'s `over` with the schema describing it, when it reads a\n * schema'd `$output` (or an `$item` of a schema'd element). */\n private readWithSchema(value: unknown, trail: Trail, scope: Scope): Read {\n const key = tokenKeyOf(value);\n if (\n isPlainObject(value) &&\n (key === \"$output\" || key === \"$item\") &&\n tokenSchema.safeParse(value).success\n ) {\n return key === \"$output\"\n ? this.readOutput(value, trail, scope)\n : this.readItem(value.$item, trail, scope);\n }\n return { value: this.value(value, trail, scope) };\n }\n\n private omit(what: string): Read {\n this.omitted = what;\n return { value: OMIT };\n }\n\n private readItem(operand: unknown, trail: Trail, scope: Scope): Read {\n const named = isPlainObject(operand) ? operand : undefined;\n const name = named && typeof named.as === \"string\" ? named.as : undefined;\n const raw: unknown = named ? named.path : operand;\n const path = pathSegments(Array.isArray(raw) ? raw : []);\n const binding = this.binding(name, \"$item\", trail, scope);\n const hit = walkPath(binding.item, path);\n if (!hit.ok) {\n if (\n binding.schema !== undefined &&\n isOptionalField(binding.schema, path, hit.at)\n ) {\n return this.omit(\"an absent optional $item field\");\n }\n const missing = formatPath(path.slice(0, hit.at + 1));\n return this.fail(\n trail,\n `reads $item ${formatPath(path)}, but $map element ${elementText(binding)} has no ${missing} (it has: ${hit.has}).`,\n scope,\n );\n }\n return {\n value: structuredClone(hit.value),\n schema: schemaOf(binding.schema, path),\n };\n }\n\n key(operand: unknown, trail: Trail, scope: Scope): string | number {\n const name = typeof operand === \"string\" ? operand : undefined;\n return this.binding(name, \"$key\", trail, scope).key;\n }\n\n output(\n token: Record<string, unknown>,\n trail: Trail,\n scope: Scope = [],\n ): unknown {\n return this.readOutput(token, trail, scope).value;\n }\n\n private readOutput(\n token: Record<string, unknown>,\n trail: Trail,\n scope: Scope,\n ): Read {\n const operand = token.$output;\n if (!isPlainObject(operand) || typeof operand.host !== \"string\") {\n return this.fail(trail, \"is a malformed $output token.\", scope);\n }\n const ref: OutputRef =\n typeof operand.member === \"string\"\n ? { host: operand.host, member: operand.member }\n : { host: operand.host };\n const path = pathSegments(Array.isArray(operand.path) ? operand.path : []);\n if (!this.sources.outputs) {\n return this.fail(\n trail,\n `reads ${describeToken(token)}, but no outputs are available here.`,\n scope,\n );\n }\n const lookup = this.sources.outputs.lookup(ref);\n if (lookup.status === \"unavailable\") {\n const where = this.sources.where ? `${this.sources.where}: ` : \"\";\n const path = formatPath(trail);\n const reason = `${lookup.message}\\n (needed by \\`${path}\\`: ${describeToken(token)})`;\n throw new TokenResolutionError(`${where}${reason}`, { path, reason });\n }\n const hit = walkPath(lookup.outputs, path);\n if (!hit.ok) {\n if (\n lookup.schema !== undefined &&\n isOptionalField(lookup.schema, path, hit.at)\n ) {\n return this.omit(\"an absent optional output\");\n }\n const parent = path.slice(0, hit.at);\n const container = parent.length\n ? `outputs.${formatPath(parent)}`\n : \"its outputs\";\n const missing = formatPath(path.slice(0, hit.at + 1));\n return this.fail(\n trail,\n `reads ${describeToken(token)}, but host \"${ref.host}\" has no output at ${missing} (${container} has: ${hit.has}).`,\n scope,\n );\n }\n return {\n value: structuredClone(hit.value),\n schema: schemaOf(lookup.schema, path),\n };\n }\n\n env(operand: unknown, trail: Trail, scope: Scope = []): unknown {\n const optional = isPlainObject(operand);\n const name = optional ? operand.name : operand;\n if (typeof name !== \"string\") {\n return this.fail(trail, \"is a malformed $env token.\", scope);\n }\n const builtins = this.sources.builtins;\n if (isBuiltinEnvName(name) && builtins?.[name]) {\n return builtins[name];\n }\n const value = this.sources.env?.[name];\n if (value !== undefined) return value;\n if (optional) return this.omit(\"an optional $env\").value;\n return this.fail(trail, unsetEnvMessage(name), scope);\n }\n\n concat(parts: unknown, trail: Trail, scope: Scope = []): string {\n if (!Array.isArray(parts)) {\n return this.fail(trail, \"is a malformed $concat token.\", scope);\n }\n return parts\n .map((part: unknown, index) => {\n const at = [...trail, \"$concat\", index];\n const value = this.value(part, at, scope);\n if (value === OMIT) {\n return this.fail(at, `is ${this.omitted} inside $concat.`, scope);\n }\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\") return String(value);\n return this.fail(\n at,\n `resolved to ${JSON.stringify(value)}; every $concat part must be a string or a number.`,\n scope,\n );\n })\n .join(\"\");\n }\n}\n\nexport interface ResolveOptions {\n /** Resolving a COMPOUND's own fields: tokens that read one of its members\n * are deferred until those members have started (see\n * `DeferredResolution`); `children` is left for the members. `\"outputs\"`\n * defers every `$output` (its `members` are the producers' ref keys). */\n deferSelf: SelfMembers | \"outputs\";\n}\n\n/**\n * Resolve every token in a declared host (or any JSON-shaped value): the\n * result has the same shape with tokens replaced by values, optional unset\n * `$env` properties omitted and the built-in string sugar substituted (`$$`\n * escapes are kept; validateHost unwraps them). Throws `TokenResolutionError` naming the host path;\n * an `$output` whose producer is not running fails with the source's\n * message (no fallback, no waiting).\n *\n * With `{ deferSelf }` (a compound resolving its own fields), returns a\n * `DeferredResolution` instead: everything but the self-references now,\n * and `finish(outputs)` for the rest once the members it needs run.\n */\nexport function resolveHostOutputs<T>(host: T, sources: ResolveSources): T;\nexport function resolveHostOutputs<T>(\n host: T,\n sources: ResolveSources,\n options: ResolveOptions,\n): DeferredResolution<T>;\nexport function resolveHostOutputs<T>(\n host: T,\n sources: ResolveSources,\n options?: ResolveOptions,\n): T | DeferredResolution<T> {\n const resolver = new Resolver(sources, options?.deferSelf);\n const out = resolver.value(host, []);\n if (out === OMIT) {\n resolver.fail([], `is ${resolver.omitted} with nothing to omit it from.`);\n }\n // Same shape as the declared input: every token-able field's input type\n // admits both the token and the value it resolves to.\n const partial = out as T;\n if (!options) return partial;\n const sites = resolver.deferred;\n return {\n host: partial,\n deferred: sites.map((d) => ({\n path: formatPath(d.trail),\n members: d.members,\n })),\n needs: [...new Set(sites.flatMap((d) => d.members))],\n finish(outputs: OutputSource): T {\n const done: unknown = cloneWithProvenance(partial);\n const late = new Resolver({ ...sources, outputs });\n for (const site of sites) {\n const value = late.token(site.token, site.trail);\n // An array slot has no property to omit (as when resolving eagerly).\n if (value === OMIT && typeof site.trail.at(-1) === \"number\") {\n late.fail(site.trail, `is ${late.omitted} inside an array.`);\n }\n setAt(\n done,\n site.trail,\n value === OMIT ? undefined : value,\n value === OMIT,\n );\n }\n return done as T;\n },\n };\n}\n\nfunction setAt(\n root: unknown,\n trail: Trail,\n value: unknown,\n omit: boolean,\n): void {\n let current = root;\n for (const key of trail.slice(0, -1)) {\n if (Array.isArray(current) && typeof key === \"number\")\n current = current[key];\n else if (isPlainObject(current) && typeof key === \"string\")\n current = current[key];\n else return;\n }\n const last = trail[trail.length - 1];\n if (Array.isArray(current) && typeof last === \"number\") {\n current[last] = value;\n } else if (isPlainObject(current) && typeof last === \"string\") {\n if (omit) delete current[last];\n else current[last] = value;\n }\n}\n","import { isPlainObject } from \"./walk.js\";\n\n/**\n * The cross-host forms removed in T3 (typed-host-configs 3.7), detected\n * before schema validation so the error names the token form that replaces\n * each one instead of a bare \"Unrecognized key\". clint's `agents.*.host` and\n * proxy `routes.*.member` are checked by the clint runner schemas.\n */\n\nexport interface RemovedForm {\n /** Host path of the removed value. */\n path: string;\n message: string;\n}\n\nfunction outputToken(host: string, path: string[], member?: string): string {\n const memberPart = member ? `, member: \"${member}\"` : \"\";\n return `{ $output: { host: \"${host}\"${memberPart}, path: [${path.map((p) => JSON.stringify(p)).join(\", \")}] } }`;\n}\n\nfunction isDriveReference(\n value: unknown,\n): value is { from: string; slug: string } {\n if (!isPlainObject(value)) return false;\n const keys = Object.keys(value).sort();\n return (\n keys.length === 2 &&\n keys[0] === \"from\" &&\n keys[1] === \"slug\" &&\n typeof value.from === \"string\" &&\n typeof value.slug === \"string\"\n );\n}\n\nfunction checkReactor(\n reactor: unknown,\n base: string,\n found: RemovedForm[],\n): void {\n if (!isPlainObject(reactor) || !isPlainObject(reactor.backends)) return;\n for (const [name, backend] of Object.entries(reactor.backends)) {\n if (!isPlainObject(backend) || !isPlainObject(backend.remote)) continue;\n const host = backend.remote.host;\n if (host === undefined) continue;\n const producer = typeof host === \"string\" ? host : \"switchboard\";\n found.push({\n path: `${base}reactor.backends.${name}.remote.host`,\n message: `remote: { host } was removed; use a drive address: remote: { url: ${producer}.drives.<slug>.url } with ${producer} from ../${producer}/outputs.js, or remote: { url: ${outputToken(producer, [\"drives\", \"<slug>\", \"url\"])} }.`,\n });\n }\n}\n\nfunction checkPlugins(\n runner: unknown,\n base: string,\n memberHosts: Record<string, string>,\n found: RemovedForm[],\n): void {\n if (!isPlainObject(runner) || !Array.isArray(runner.plugins)) return;\n runner.plugins.forEach((entry: unknown, index) => {\n if (!isPlainObject(entry) || !isPlainObject(entry.config)) return;\n for (const [key, value] of Object.entries(entry.config)) {\n if (!isDriveReference(value)) continue;\n const host = memberHosts[value.from] ?? value.from;\n const member = memberHosts[value.from] ? value.from : undefined;\n found.push({\n path: `${base}runner.plugins[${index}].config.${key}`,\n message: `${key}: { from, slug } was removed; use ${host}.drives.${value.slug}.url from ../${host}/outputs.js, or ${outputToken(host, [\"drives\", value.slug, \"url\"])}${member ? ` (add member: \"${member}\" if two members run host \"${host}\")` : \"\"}.`,\n });\n }\n });\n}\n\n/** Every removed form in a host file (reactor or compound), in document\n * order. Compound wrappers are checked too. */\nexport function findRemovedForms(host: unknown): RemovedForm[] {\n const found: RemovedForm[] = [];\n if (!isPlainObject(host)) return found;\n const children = isPlainObject(host.children) ? host.children : undefined;\n const memberHosts: Record<string, string> = {};\n for (const [key, wrapper] of Object.entries(children ?? {})) {\n if (isPlainObject(wrapper) && typeof wrapper.host === \"string\") {\n memberHosts[key] = wrapper.host;\n }\n }\n\n checkReactor(host.reactor, \"\", found);\n checkPlugins(host.runner, \"\", memberHosts, found);\n for (const [key, wrapper] of Object.entries(children ?? {})) {\n if (!isPlainObject(wrapper)) continue;\n checkReactor(wrapper.reactor, `children.${key}.`, found);\n checkPlugins(wrapper.runner, `children.${key}.`, memberHosts, found);\n }\n if (children && isPlainObject(host.config)) {\n for (const key of [\"projectDrivesIntoConnect\", \"drivesPublicBase\"]) {\n if (host.config[key] === undefined) continue;\n found.push({\n path: `config.${key}`,\n message: `config.${key} was removed; declare the drives on the member that consumes them, by output token: reactor.drives: [{ slug: \"<slug>\", remote: { url: ${outputToken(\"switchboard\", [\"drives\", \"<slug>\", \"url\"])} } }].`,\n });\n }\n }\n return found;\n}\n","import type { OutputRef } from \"./declared.js\";\nimport { memberForRef } from \"./plan.js\";\nimport type { OutputSource } from \"./resolve.js\";\n\n/**\n * The compound output source: a member's `$output` tokens read the live\n * `RunnerHandle.outputs` of the members started before it. `schemas` (member\n * key → its runner's `outputsSchema`) lets an absent optional output field\n * omit the consuming property. Pure (the run-record source for standalone\n * hosts is node: ./node.ts).\n */\nexport function compoundOutputSource(\n members: readonly { key: string; host: string }[],\n started: ReadonlyMap<string, unknown>,\n compound: string,\n schemas?: ReadonlyMap<string, unknown>,\n): OutputSource {\n return {\n lookup(ref: OutputRef) {\n const target = memberForRef(ref, members);\n if (\"error\" in target) {\n return {\n status: \"unavailable\",\n message: `compound \"${compound}\": a token ${target.error}`,\n };\n }\n if (!started.has(target.key)) {\n return {\n status: \"unavailable\",\n message: `compound \"${compound}\": member \"${target.key}\" (host \"${ref.host}\") has not started yet; a producer must start before its consumers.`,\n };\n }\n const schema = schemas?.get(target.key);\n return {\n status: \"available\",\n outputs: started.get(target.key),\n ...(schema !== undefined ? { schema } : {}),\n };\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":";;;;AAsCA,SAAS,eACP,MACA,SACkB;CAClB,QAAQ,QAAQ,MAAhB;EACE,KAAK,OACH,OAAO,EAAE,MAAM,MAAM;EACvB,KAAK,UACH,OAAO,EAAE,MAAM,SAAS;EAC1B,KAAK;GACH,IAAI,CAAC,QAAQ,SACX,MAAM,IAAI,MACR,YAAY,KAAK,yCACnB;GAEF,OAAO;IAAE,MAAM;IAAQ,SAAS,QAAQ;GAAQ;EAElD,KAAK,YACH,MAAM,IAAI,MACR,YAAY,KAAK,uLAGnB;CACJ;AACF;;;;AAKA,SAAgB,oBACd,MACA,SACA,UACqB;CACrB,MAAM,aAAkC;EACtC,MAAM,QAAQ;EACd;CACF;CACA,IAAI,WAAW,SAAS,UAAU;EAChC,MAAM,MAAM,QAAQ,QAAQ;EAC5B,IAAI,CAAC,KACH,MAAM,IAAI,MACR,YAAY,KAAK,8GAEnB;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